code
stringlengths 2
1.05M
|
---|
var yaa = require('yaa');
var codec = require('../../../bin/index.js');
var runner = require('../../runner.js');
var testName = 'codec.json.decode';
var cases = [];
var input = {
'a': [3, 4],
'b': {
'e': 5,
'y': {
'a&j': 1
}
},
'c': "123"
};
var output = '{"a": [3, 4], "b": {"e": 5, "y": {"a&j": 1}}, "c": "123"}';
cases.push(yaa.assert.outputDeepEquals(
yaa.insert(codec.json.decode(output)),
yaa.insert(input),
'[codec.json.decode]'
));
module.exports = runner(cases, testName);
|
+(function (factory) {
if (typeof exports === 'undefined') {
factory(webduino || {});
} else {
module.exports = factory;
}
}(function (scope) {
'use strict';
var push = Array.prototype.push;
var EventEmitter = scope.EventEmitter,
TransportEvent = scope.TransportEvent,
Transport = scope.Transport,
PinEvent = scope.PinEvent,
Pin = scope.Pin,
util = scope.util,
proto;
var BoardEvent = {
ANALOG_DATA: 'analogData',
DIGITAL_DATA: 'digitalData',
FIRMWARE_VERSION: 'firmwareVersion',
FIRMWARE_NAME: 'firmwareName',
STRING_MESSAGE: 'stringMessage',
SYSEX_MESSAGE: 'sysexMessage',
PIN_STATE_RESPONSE: 'pinStateResponse',
READY: 'ready',
ERROR: 'error'
};
// Message command bytes (128-255/0x80-0xFF)
var DIGITAL_MESSAGE = 0x90,
ANALOG_MESSAGE = 0xE0,
REPORT_ANALOG = 0xC0,
REPORT_DIGITAL = 0xD0,
SET_PIN_MODE = 0xF4,
REPORT_VERSION = 0xF9,
SYSEX_RESET = 0xFF,
START_SYSEX = 0xF0,
END_SYSEX = 0xF7;
// Extended command set using sysex (0-127/0x00-0x7F)
var SERVO_CONFIG = 0x70,
STRING_DATA = 0x71,
SHIFT_DATA = 0x75,
I2C_REQUEST = 0x76,
I2C_REPLY = 0x77,
I2C_CONFIG = 0x78,
EXTENDED_ANALOG = 0x6F,
PIN_STATE_QUERY = 0x6D,
PIN_STATE_RESPONSE = 0x6E,
CAPABILITY_QUERY = 0x6B,
CAPABILITY_RESPONSE = 0x6C,
ANALOG_MAPPING_QUERY = 0x69,
ANALOG_MAPPING_RESPONSE = 0x6A,
REPORT_FIRMWARE = 0x79,
SAMPLING_INTERVAL = 0x7A,
SYSEX_NON_REALTIME = 0x7E,
SYSEX_REALTIME = 0x7F;
var MIN_SAMPLING_INTERVAL = 10,
MAX_SAMPLING_INTERVAL = 100;
function Board(options) {
EventEmitter.call(this);
this._options = options;
this._buf = [];
this._digitalPort = [];
this._numPorts = 0;
this._analogPinMapping = [];
this._digitalPinMapping = [];
this._i2cPins = [];
this._ioPins = [];
this._totalPins = 0;
this._totalAnalogPins = 0;
this._samplingInterval = 19;
this._isReady = false;
this._firmwareName = '';
this._firmwareVersion = 0;
this._capabilityQueryResponseReceived = false;
this._numPinStateRequests = 0;
this._transport = null;
this._pinStateEventCenter = new EventEmitter();
this._initialVersionResultHandler = onInitialVersionResult.bind(this);
this._sendOutHandler = sendOut.bind(this);
this._readyHandler = onReady.bind(this);
this._messageHandler = onMessage.bind(this);
this._errorHandler = onError.bind(this);
this.setTransport(this._options.transport || 0);
}
function onInitialVersionResult(event) {
var version = event.version * 10,
name = event.name;
if (version >= 23) {
// TODO: do reset and handle response
// this.systemReset();
this.queryCapabilities();
} else {
throw new Error('error: You must upload StandardFirmata version 2.3 ' +
'or greater from Arduino version 1.0 or higher');
}
}
function sendOut(pin) {
var type = pin._type,
pinNum = pin.number,
value = pin.value;
switch (type) {
case Pin.DOUT:
this.sendDigitalData(pinNum, value);
break;
case Pin.AOUT:
this.sendAnalogData(pinNum, value);
break;
case Pin.SERVO:
this.sendServoData(pinNum, value);
break;
}
}
function onReady() {
this.begin();
}
function onMessage(data) {
var len = data.length;
if (len) {
for (var i = 0; i < len; i++) {
this.processInput(data[i]);
}
} else {
this.processInput(data);
}
}
function onError(error) {
this._isReady = false;
this.emit(BoardEvent.ERROR, error);
}
function debug(msg) {
console && console.log(msg.stack || msg);
}
Board.prototype = proto = Object.create(EventEmitter.prototype, {
constructor: {
value: Board
},
samplingInterval: {
get: function () {
return this._samplingInterval;
},
set: function (interval) {
if (interval >= MIN_SAMPLING_INTERVAL && interval <= MAX_SAMPLING_INTERVAL) {
this._samplingInterval = interval;
this.send([
START_SYSEX,
SAMPLING_INTERVAL,
interval & 0x007F, (interval >> 7) & 0x007F,
END_SYSEX
]);
} else {
throw new Error('warning: Sampling interval must be between ' + MIN_SAMPLING_INTERVAL +
' and ' + MAX_SAMPLING_INTERVAL);
}
}
},
isReady: {
get: function () {
return this._isReady;
}
}
});
proto.begin = function () {
this.once(BoardEvent.FIRMWARE_NAME, this._initialVersionResultHandler);
this.reportFirmware();
};
proto.processInput = function (inputData) {
var len, cmd;
inputData = parseInt(inputData, 10);
this._buf.push(inputData);
len = this._buf.length;
cmd = this._buf[0];
if (cmd >= 128 && cmd !== START_SYSEX) {
if (len === 3) {
this.processMultiByteCommand(this._buf);
this._buf = [];
}
} else if (cmd === START_SYSEX && inputData === END_SYSEX) {
this.processSysexCommand(this._buf);
this._buf = [];
} else if (inputData >= 128 && cmd < 128) {
this._buf = [];
if (inputData !== END_SYSEX) {
this._buf.push(inputData);
}
}
};
proto.processMultiByteCommand = function (commandData) {
var command = commandData[0],
channel;
if (command < 0xF0) {
command = command & 0xF0;
channel = commandData[0] & 0x0F;
}
switch (command) {
case DIGITAL_MESSAGE:
this.processDigitalMessage(channel, commandData[1], commandData[2]);
break;
case REPORT_VERSION:
this._firmwareVersion = commandData[1] + commandData[2] / 10;
this.emit(BoardEvent.FIRMWARE_VERSION, {
version: this._firmwareVersion
});
break;
case ANALOG_MESSAGE:
this.processAnalogMessage(channel, commandData[1], commandData[2]);
break;
}
};
proto.processDigitalMessage = function (port, bits0_6, bits7_13) {
var offset = port * 8,
lastPin = offset + 8,
portVal = bits0_6 | (bits7_13 << 7),
pinVal,
pin = {};
if (lastPin >= this._totalPins) {
lastPin = this._totalPins;
}
var j = 0;
for (var i = offset; i < lastPin; i++) {
pin = this.getDigitalPin(i);
if (pin === undefined) {
return;
}
if (pin._type === Pin.DIN) {
pinVal = (portVal >> j) & 0x01;
if (pinVal !== pin.value) {
pin.value = pinVal;
this.emit(BoardEvent.DIGITAL_DATA, {
pin: pin
});
}
}
j++;
}
};
proto.processAnalogMessage = function (channel, bits0_6, bits7_13) {
var analogPin = this.getAnalogPin(channel);
if (analogPin === undefined) {
return;
}
analogPin.value = this.getValueFromTwo7bitBytes(bits0_6, bits7_13) / analogPin.analogReadResolution;
if (analogPin.value !== analogPin.lastValue) {
this.emit(BoardEvent.ANALOG_DATA, {
pin: analogPin
});
}
};
proto.processSysexCommand = function (sysexData) {
sysexData.shift();
sysexData.pop();
var command = sysexData[0];
switch (command) {
case REPORT_FIRMWARE:
this.processQueryFirmwareResult(sysexData);
break;
case STRING_DATA:
this.processSysExString(sysexData);
break;
case CAPABILITY_RESPONSE:
this.processCapabilitiesResponse(sysexData);
break;
case PIN_STATE_RESPONSE:
this.processPinStateResponse(sysexData);
break;
case ANALOG_MAPPING_RESPONSE:
this.processAnalogMappingResponse(sysexData);
break;
default:
this.emit(BoardEvent.SYSEX_MESSAGE, {
message: sysexData
});
break;
}
};
proto.processQueryFirmwareResult = function (msg) {
var data;
for (var i = 3, len = msg.length; i < len; i += 2) {
data = msg[i];
data += msg[i + 1];
this._firmwareName += String.fromCharCode(data);
}
this._firmwareVersion = msg[1] + msg[2] / 10;
this.emit(BoardEvent.FIRMWARE_NAME, {
name: this._firmwareName,
version: this._firmwareVersion
});
};
proto.processSysExString = function (msg) {
var str = '',
data,
len = msg.length;
for (var i = 1; i < len; i += 2) {
data = msg[i];
data += msg[i + 1];
str += String.fromCharCode(data);
}
this.emit(BoardEvent.STRING_MESSAGE, {
message: str
});
};
proto.processCapabilitiesResponse = function (msg) {
var pinCapabilities = {},
byteCounter = 1,
pinCounter = 0,
analogPinCounter = 0,
len = msg.length,
type,
pin;
this._capabilityQueryResponseReceived = true;
while (byteCounter <= len) {
if (msg[byteCounter] === 127) {
this._digitalPinMapping[pinCounter] = pinCounter;
type = undefined;
if (pinCapabilities[Pin.DOUT]) {
type = Pin.DOUT;
}
if (pinCapabilities[Pin.AIN]) {
type = Pin.AIN;
this._analogPinMapping[analogPinCounter++] = pinCounter;
}
pin = new Pin(pinCounter, type);
pin.setCapabilities(pinCapabilities);
this.managePinListener(pin);
this._ioPins[pinCounter] = pin;
if (pin._capabilities[Pin.I2C]) {
this._i2cPins.push(pin.number);
}
pinCapabilities = {};
pinCounter++;
byteCounter++;
} else {
pinCapabilities[msg[byteCounter]] = msg[byteCounter + 1];
byteCounter += 2;
}
}
this._numPorts = Math.ceil(pinCounter / 8);
for (var j = 0; j < this._numPorts; j++) {
this._digitalPort[j] = 0;
}
this._totalPins = pinCounter;
this._totalAnalogPins = analogPinCounter;
this.queryAnalogMapping();
};
proto.processAnalogMappingResponse = function (msg) {
var len = msg.length;
for (var i = 1; i < len; i++) {
if (msg[i] !== 127) {
this._analogPinMapping[msg[i]] = i - 1;
this.getPin(i - 1).setAnalogNumber(msg[i]);
}
}
this.startup();
};
proto.startup = function () {
this._isReady = true;
this.emit(BoardEvent.READY);
};
proto.systemReset = function () {
this.send(SYSEX_RESET);
};
proto.processPinStateResponse = function (msg) {
if (this._numPinStateRequests <= 0) {
return;
}
var len = msg.length,
pinNumber = msg[1],
pinType = msg[2],
pinState,
pin = this._ioPins[pinNumber];
if (len > 4) {
pinState = this.getValueFromTwo7bitBytes(msg[3], msg[4]);
} else if (len > 3) {
pinState = msg[3];
}
if (pin._type !== pinType) {
pin.setType(pinType);
this.managePinListener(pin);
}
pin.setState(pinState);
this._numPinStateRequests--;
if (this._numPinStateRequests < 0) {
this._numPinStateRequests = 0;
}
this._pinStateEventCenter.emit(pinNumber, pin);
this.emit(BoardEvent.PIN_STATE_RESPONSE, {
pin: pin
});
};
proto.toDec = function (ch) {
ch = ch.substring(0, 1);
var decVal = ch.charCodeAt(0);
return decVal;
};
proto.managePinListener = function (pin) {
if (pin._type === Pin.DOUT || pin._type === Pin.AOUT || pin._type === Pin.SERVO) {
if (!EventEmitter.listenerCount(pin, PinEvent.CHANGE)) {
pin.on(PinEvent.CHANGE, this._sendOutHandler);
}
} else {
if (EventEmitter.listenerCount(pin, PinEvent.CHANGE)) {
try {
pin.removeListener(PinEvent.CHANGE, this._sendOutHandler);
} catch (e) {
// Pin had reference to other handler, ignore
debug("debug: caught pin removeEventListener exception");
}
}
}
};
proto.sendAnalogData = function (pin, value) {
var pwmResolution = this.getDigitalPin(pin).analogWriteResolution;
value *= pwmResolution;
value = (value < 0) ? 0 : value;
value = (value > pwmResolution) ? pwmResolution : value;
if (pin > 15 || value > Math.pow(2, 14)) {
this.sendExtendedAnalogData(pin, value);
} else {
this.send([ANALOG_MESSAGE | (pin & 0x0F), value & 0x007F, (value >> 7) & 0x007F]);
}
};
proto.sendExtendedAnalogData = function (pin, value) {
var analogData = [];
// If > 16 bits
if (value > Math.pow(2, 16)) {
throw new Error('error: Extended Analog values > 16 bits are not currently supported by StandardFirmata');
}
analogData[0] = START_SYSEX;
analogData[1] = EXTENDED_ANALOG;
analogData[2] = pin;
analogData[3] = value & 0x007F;
analogData[4] = (value >> 7) & 0x007F; // Up to 14 bits
// If > 14 bits
if (value >= Math.pow(2, 14)) {
analogData[5] = (value >> 14) & 0x007F;
}
analogData.push(END_SYSEX);
this.send(analogData);
};
proto.sendDigitalData = function (pin, value) {
var portNum = Math.floor(pin / 8);
if (value === Pin.HIGH) {
// Set the bit
this._digitalPort[portNum] |= (value << (pin % 8));
} else if (value === Pin.LOW) {
// Clear the bit
this._digitalPort[portNum] &= ~(1 << (pin % 8));
} else {
// Should not happen...
throw new Error('Invalid value passed to sendDigital, value must be 0 or 1.');
}
this.sendDigitalPort(portNum, this._digitalPort[portNum]);
};
proto.sendServoData = function (pin, value) {
var servoPin = this.getDigitalPin(pin);
if (servoPin._type === Pin.SERVO && servoPin.lastValue !== value) {
this.sendAnalogData(pin, value);
}
};
proto.queryCapabilities = function () {
this.send([START_SYSEX, CAPABILITY_QUERY, END_SYSEX]);
};
proto.queryAnalogMapping = function () {
this.send([START_SYSEX, ANALOG_MAPPING_QUERY, END_SYSEX]);
};
proto.getValueFromTwo7bitBytes = function (lsb, msb) {
return (msb << 7) | lsb;
};
proto.getTransport = function () {
return this._transport;
};
proto.setTransport = function (type) {
var klass = scope.transport[type],
trsp;
if (this._transport instanceof Transport) {
try {
this._transport.close();
} catch (e) {}
this._transport.removeAllListeners();
delete this._transport;
}
if (klass && (trsp = new klass(this._options)) instanceof Transport) {
this._transport = trsp;
trsp.on(TransportEvent.READY, this._readyHandler);
trsp.on(TransportEvent.MESSAGE, this._messageHandler);
trsp.on(TransportEvent.ERROR, this._errorHandler);
}
};
proto.reportVersion = function () {
this.send(REPORT_VERSION);
};
proto.reportFirmware = function () {
this.send([START_SYSEX, REPORT_FIRMWARE, END_SYSEX]);
};
proto.enableDigitalPins = function () {
for (var i = 0; i < this._numPorts; i++) {
this.sendDigitalPortReporting(i, Pin.ON);
}
};
proto.disableDigitalPins = function () {
for (var i = 0; i < this._numPorts; i++) {
this.sendDigitalPortReporting(i, Pin.OFF);
}
};
proto.sendDigitalPortReporting = function (port, mode) {
this.send([(REPORT_DIGITAL | port), mode]);
};
proto.enableAnalogPin = function (pin) {
this.sendAnalogPinReporting(pin, Pin.ON);
};
proto.disableAnalogPin = function (pin) {
this.sendAnalogPinReporting(pin, Pin.OFF);
};
proto.sendAnalogPinReporting = function (pinNumber, mode) {
this.send([REPORT_ANALOG | pinNumber, mode]);
};
proto.setDigitalPinMode = function (pinNumber, mode, silent) {
this.getDigitalPin(pinNumber).setType(mode);
this.managePinListener(this.getDigitalPin(pinNumber));
if (!silent || silent !== true) {
this.send([SET_PIN_MODE, pinNumber, mode]);
}
};
proto.setAnalogPinMode = function (pinNumber, mode, silent) {
this.getAnalogPin(pinNumber).setType(mode);
if (!silent || silent !== true) {
this.send([SET_PIN_MODE, pinNumber, mode]);
}
};
proto.enablePullUp = function (pinNum) {
this.sendDigitalData(pinNum, Pin.HIGH);
};
proto.getFirmwareName = function () {
return this._firmwareName;
};
proto.getFirmwareVersion = function () {
return this._firmwareVersion;
};
proto.getPinCapabilities = function () {
var capabilities = [],
len,
pinElements,
pinCapabilities,
hasCapabilities;
var modeNames = {
0: 'input',
1: 'output',
2: 'analog',
3: 'pwm',
4: 'servo',
5: 'shift',
6: 'i2c',
7: 'onewire',
8: 'stepper'
};
len = this._ioPins.length;
for (var i = 0; i < len; i++) {
pinElements = {};
pinCapabilities = this._ioPins[i]._capabilities;
hasCapabilities = false;
for (var mode in pinCapabilities) {
if (pinCapabilities.hasOwnProperty(mode)) {
hasCapabilities = true;
if (mode >= 0) {
pinElements[modeNames[mode]] = this._ioPins[i]._capabilities[mode];
}
}
}
if (!hasCapabilities) {
capabilities[i] = {
'not available': '0'
};
} else {
capabilities[i] = pinElements;
}
}
return capabilities;
};
proto.queryPinState = function (pins, callback) {
var self = this,
promises = [],
cmds = [];
pins = util.isArray(pins) ? pins : [pins];
if (typeof callback === 'function') {
var once = self._pinStateEventCenter.once.bind(self._pinStateEventCenter);
pins.forEach(function (pin) {
promises.push(util.promisify(once, function (pin) {
this.resolve(pin);
})(pin.number));
});
Promise.all(promises).then(function (pins) {
callback.call(self, pins.length > 1 ? pins : pins[0]);
});
}
pins.forEach(function (pin) {
push.apply(cmds, [START_SYSEX, PIN_STATE_QUERY, pin.number, END_SYSEX]);
self._numPinStateRequests++;
})
self.send(cmds);
};
proto.sendDigitalPort = function (portNumber, portData) {
this.send([DIGITAL_MESSAGE | (portNumber & 0x0F), portData & 0x7F, portData >> 7]);
};
proto.sendString = function (str) {
var decValues = [];
for (var i = 0, len = str.length; i < len; i++) {
decValues.push(this.toDec(str[i]) & 0x007F);
decValues.push((this.toDec(str[i]) >> 7) & 0x007F);
}
this.sendSysex(STRING_DATA, decValues);
};
proto.sendSysex = function (command, data) {
var sysexData = [];
sysexData[0] = START_SYSEX;
sysexData[1] = command;
for (var i = 0, len = data.length; i < len; i++) {
sysexData.push(data[i]);
}
sysexData.push(END_SYSEX);
this.send(sysexData);
};
proto.sendServoAttach = function (pin, minPulse, maxPulse) {
var servoPin,
servoData = [];
minPulse = minPulse || 544; // Default value = 544
maxPulse = maxPulse || 2400; // Default value = 2400
servoData[0] = START_SYSEX;
servoData[1] = SERVO_CONFIG;
servoData[2] = pin;
servoData[3] = minPulse % 128;
servoData[4] = minPulse >> 7;
servoData[5] = maxPulse % 128;
servoData[6] = maxPulse >> 7;
servoData[7] = END_SYSEX;
this.send(servoData);
servoPin = this.getDigitalPin(pin);
servoPin.setType(Pin.SERVO);
this.managePinListener(servoPin);
};
proto.getPin = function (pinNumber) {
return this._ioPins[pinNumber];
};
proto.getAnalogPin = function (pinNumber) {
return this._ioPins[this._analogPinMapping[pinNumber]];
};
proto.getDigitalPin = function (pinNumber) {
return this._ioPins[this._digitalPinMapping[pinNumber]];
};
proto.getPins = function () {
return this._ioPins;
};
proto.analogToDigital = function (analogPinNumber) {
return this.getAnalogPin(analogPinNumber).number;
};
proto.getPinCount = function () {
return this._totalPins;
};
proto.getAnalogPinCount = function () {
return this._totalAnalogPins;
};
proto.getI2cPins = function () {
return this._i2cPins;
};
proto.reportCapabilities = function () {
var capabilities = this.getPinCapabilities(),
len = capabilities.length,
resolution;
for (var i = 0; i < len; i++) {
debug('Pin ' + i + ':');
for (var mode in capabilities[i]) {
if (capabilities[i].hasOwnProperty(mode)) {
resolution = capabilities[i][mode];
debug('\t' + mode + ' (' + resolution + (resolution > 1 ? ' bits)' : ' bit)'));
}
}
}
};
proto.send = function (data) {
this._transport.send(data);
};
proto.close = function () {
this._transport.close();
};
scope.BoardEvent = BoardEvent;
scope.Board = Board;
}));
|
'use strict';
var connectSSI = require('connect-ssi');
module.exports = {
grunt: {
connect: {
server: {
options: {
port: 9001,
base: './',
livereload: 4444,
debug: true,
open: true,
middleware: function(connect, options, middlewares) {
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
var directory = options.directory || options.base[options.base.length - 1];
console.log(directory)
middlewares.unshift(connectSSI({
baseDir: directory,
ext: '.html'
}));
return middlewares;
}
}
}
},
availabletasks: {
tasks: {}
},
watch: {
// If any .less file changes in directory "build/less/" run the "less"-task.
files: ["build/less/*.less", "build/less/skins/*.less", "dist/js/app.js"],
tasks: ["less", "uglify"],
options: {
livereload: 4444
}
},
// "less"-task configuration
// This task will compile all less files upon saving to create both layout.css and layout.min.css
less: {
// Development not compressed
development: {
options: {
// Whether to compress or not
compress: false
},
files: {
// compilation.css : source.less
"dist/css/layout.css": "build/less/layout.less",
//Non minified skin files
"dist/css/skins/skin-blue.css": "build/less/skins/skin-blue.less",
"dist/css/skins/skin-black.css": "build/less/skins/skin-black.less",
"dist/css/skins/skin-yellow.css": "build/less/skins/skin-yellow.less",
"dist/css/skins/skin-green.css": "build/less/skins/skin-green.less",
"dist/css/skins/skin-red.css": "build/less/skins/skin-red.less",
"dist/css/skins/skin-purple.css": "build/less/skins/skin-purple.less",
"dist/css/skins/skin-blue-light.css": "build/less/skins/skin-blue-light.less",
"dist/css/skins/skin-black-light.css": "build/less/skins/skin-black-light.less",
"dist/css/skins/skin-yellow-light.css": "build/less/skins/skin-yellow-light.less",
"dist/css/skins/skin-green-light.css": "build/less/skins/skin-green-light.less",
"dist/css/skins/skin-red-light.css": "build/less/skins/skin-red-light.less",
"dist/css/skins/skin-purple-light.css": "build/less/skins/skin-purple-light.less",
"dist/css/skins/_all-skins.css": "build/less/skins/_all-skins.less"
}
},
// Production compresses version
production: {
options: {
// Whether to compress or not
compress: true
},
files: {
// compilation.css : source.less
"dist/css/layout.min.css": "build/less/layout.less",
// Skins minified
"dist/css/skins/skin-blue.min.css": "build/less/skins/skin-blue.less",
"dist/css/skins/skin-black.min.css": "build/less/skins/skin-black.less",
"dist/css/skins/skin-yellow.min.css": "build/less/skins/skin-yellow.less",
"dist/css/skins/skin-green.min.css": "build/less/skins/skin-green.less",
"dist/css/skins/skin-red.min.css": "build/less/skins/skin-red.less",
"dist/css/skins/skin-purple.min.css": "build/less/skins/skin-purple.less",
"dist/css/skins/skin-blue-light.min.css": "build/less/skins/skin-blue-light.less",
"dist/css/skins/skin-black-light.min.css": "build/less/skins/skin-black-light.less",
"dist/css/skins/skin-yellow-light.min.css": "build/less/skins/skin-yellow-light.less",
"dist/css/skins/skin-green-light.min.css": "build/less/skins/skin-green-light.less",
"dist/css/skins/skin-red-light.min.css": "build/less/skins/skin-red-light.less",
"dist/css/skins/skin-purple-light.min.css": "build/less/skins/skin-purple-light.less",
"dist/css/skins/_all-skins.min.css": "build/less/skins/_all-skins.less"
}
}
},
// Uglify task info. Compress the js files.
uglify: {
options: {
mangle: true,
preserveComments: 'some'
},
my_target: {
files: {
'dist/js/app.min.js': ['dist/js/app.js']
}
}
},
// Build the documentation files
includes: {
build: {
src: ['*.html'], // Source files
dest: 'documentation/', // Destination directory
flatten: true,
cwd: 'documentation/build',
options: {
silent: true,
includePath: 'documentation/build/include'
}
}
},
// Optimize images
image: {
dynamic: {
files: [{
expand: true,
cwd: 'build/img/',
src: ['**/*.{png,jpg,gif,svg,jpeg}'],
dest: 'dist/img/'
}]
}
},
// Validate JS code
jshint: {
options: {
jshintrc: '.jshintrc'
},
core: {
src: 'dist/js/app.js'
},
demo: {
src: 'dist/js/demo.js'
},
pages: {
src: 'dist/js/pages/*.js'
}
},
// Validate CSS files
csslint: {
options: {
csslintrc: 'build/less/.csslintrc'
},
dist: [
'dist/css/layout.css',
]
},
// Validate Bootstrap HTML
bootlint: {
options: {
relaxerror: ['W005']
},
files: ['pages/**/*.html', '*.html']
},
// Delete images in build directory
// After compressing the images in the build/img dir, there is no need
// for them
clean: {
build: ["build/img/*"]
}
}
}
|
/*! SmartAdmin - v1.5 - 2014-10-13 */if($(".tree > ul")&&!mytreebranch){var mytreebranch=$(".tree").find("li:has(ul)").addClass("parent_li").attr("role","treeitem").find(" > span").attr("title","Collapse this branch");$(".tree > ul").attr("role","tree").find("ul").attr("role","group"),mytreebranch.on("click",function(a){var b=$(this).parent("li.parent_li").find(" > ul > li");b.is(":visible")?(b.hide("fast"),$(this).attr("title","Expand this branch").find(" > i").addClass("icon-plus-sign").removeClass("icon-minus-sign")):(b.show("fast"),$(this).attr("title","Collapse this branch").find(" > i").addClass("icon-minus-sign").removeClass("icon-plus-sign")),a.stopPropagation()})} |
"use strict";
/*
* Copyright 2015 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the terms of the LICENSE file distributed with this project.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var classNames = require("classnames");
var React = require("react");
var abstractComponent_1 = require("../../common/abstractComponent");
var Classes = require("../../common/classes");
var AnimationStates;
(function (AnimationStates) {
AnimationStates[AnimationStates["CLOSED"] = 0] = "CLOSED";
AnimationStates[AnimationStates["OPENING"] = 1] = "OPENING";
AnimationStates[AnimationStates["OPEN"] = 2] = "OPEN";
AnimationStates[AnimationStates["CLOSING_START"] = 3] = "CLOSING_START";
AnimationStates[AnimationStates["CLOSING_END"] = 4] = "CLOSING_END";
})(AnimationStates = exports.AnimationStates || (exports.AnimationStates = {}));
/*
* A collapse can be in one of 5 states:
* CLOSED
* When in this state, the contents of the collapse is not rendered, the collapse height is 0,
* and the body Y is at -height (so that the bottom of the body is at Y=0).
*
* OPEN
* When in this state, the collapse height is set to auto, and the body Y is set to 0 (so the element can be seen
* as normal).
*
* CLOSING_START
* When in this state, height has been changed from auto to the measured height of the body to prepare for the
* closing animation in CLOSING_END.
*
* CLOSING_END
* When in this state, the height is set to 0 and the body Y is at -height. Both of these properties are transformed,
* and then after the animation is complete, the state changes to CLOSED.
*
* OPENING
* When in this state, the body is re-rendered, height is set to the measured body height and the body Y is set to 0.
* This is all animated, and on complete, the state changes to OPEN.
*
* When changing the isOpen prop, the following happens to the states:
* isOpen = true : CLOSED -> OPENING -> OPEN
* isOpen = false: OPEN -> CLOSING_START -> CLOSING_END -> CLOSED
* These are all animated.
*/
var Collapse = (function (_super) {
tslib_1.__extends(Collapse, _super);
function Collapse() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.state = {
animationState: AnimationStates.OPEN,
height: "0px",
};
// The most recent non-0 height (once a height has been measured - is 0 until then)
_this.height = 0;
_this.contentsRefHandler = function (el) {
_this.contents = el;
if (el != null) {
_this.height = _this.contents.clientHeight;
_this.setState({
animationState: _this.props.isOpen ? AnimationStates.OPEN : AnimationStates.CLOSED,
height: _this.height + "px",
});
}
};
return _this;
}
Collapse.prototype.componentWillReceiveProps = function (nextProps) {
var _this = this;
if (this.contents != null && this.contents.clientHeight !== 0) {
this.height = this.contents.clientHeight;
}
if (this.props.isOpen !== nextProps.isOpen) {
this.clearTimeouts();
if (this.state.animationState !== AnimationStates.CLOSED && !nextProps.isOpen) {
this.setState({
animationState: AnimationStates.CLOSING_START,
height: this.height + "px",
});
}
else if (this.state.animationState !== AnimationStates.OPEN && nextProps.isOpen) {
this.setState({
animationState: AnimationStates.OPENING,
height: this.height + "px",
});
this.setTimeout(function () { return _this.onDelayedStateChange(); }, this.props.transitionDuration);
}
}
};
Collapse.prototype.render = function () {
var isContentVisible = this.state.animationState !== AnimationStates.CLOSED;
var shouldRenderChildren = isContentVisible || this.props.keepChildrenMounted;
var displayWithTransform = isContentVisible && this.state.animationState !== AnimationStates.CLOSING_END;
var isAutoHeight = this.state.height === "auto";
var containerStyle = {
height: isContentVisible ? this.state.height : undefined,
overflowY: (isAutoHeight ? "visible" : undefined),
transition: isAutoHeight ? "none" : undefined,
};
var contentsStyle = {
transform: displayWithTransform ? "translateY(0)" : "translateY(-" + this.height + "px)",
transition: isAutoHeight ? "none" : undefined,
};
// HACKHACK: type cast because there's no single overload that supports all
// three ReactTypes (string | ComponentClass | StatelessComponent)
return React.createElement(this.props.component, {
className: classNames(Classes.COLLAPSE, this.props.className),
style: containerStyle,
}, React.createElement("div", { className: "pt-collapse-body", ref: this.contentsRefHandler, style: contentsStyle, "aria-hidden": !isContentVisible && this.props.keepChildrenMounted }, shouldRenderChildren ? this.props.children : null));
};
Collapse.prototype.componentDidMount = function () {
this.forceUpdate();
if (this.props.isOpen) {
this.setState({ animationState: AnimationStates.OPEN, height: "auto" });
}
else {
this.setState({ animationState: AnimationStates.CLOSED });
}
};
Collapse.prototype.componentDidUpdate = function () {
var _this = this;
if (this.state.animationState === AnimationStates.CLOSING_START) {
this.setTimeout(function () {
return _this.setState({
animationState: AnimationStates.CLOSING_END,
height: "0px",
});
});
this.setTimeout(function () { return _this.onDelayedStateChange(); }, this.props.transitionDuration);
}
};
Collapse.prototype.onDelayedStateChange = function () {
switch (this.state.animationState) {
case AnimationStates.OPENING:
this.setState({ animationState: AnimationStates.OPEN, height: "auto" });
break;
case AnimationStates.CLOSING_END:
this.setState({ animationState: AnimationStates.CLOSED });
break;
default:
break;
}
};
Collapse.displayName = "Blueprint.Collapse";
Collapse.defaultProps = {
component: "div",
isOpen: false,
keepChildrenMounted: false,
transitionDuration: 200,
};
return Collapse;
}(abstractComponent_1.AbstractComponent));
exports.Collapse = Collapse;
|
'use strict';
module.exports = function(app, config) {
if (config.facebook) {
require('./facebook')(app, config.facebook);
}
if (config.google) {
require('./google')(app, config.google);
}
if (config.twitter) {
return require('./twitter')(app, config.twitter);
}
};
|
import React, { Component } from 'react'
import { Grid, Col, Row } from 'react-bootstrap'
/* re-export */
export { default as About } from './About'
export * from './Hobbies'
export { default as App } from './App'
export { default as Footer } from './Footer'
export { default as Header } from './Header'
export { default as NavBar } from './NavBar'
/* export Index component */
export class Index extends Component {
render() {
return (
<Grid id='indexContainer'>
<Row>
<Col xs={8} md={6} lg={5} xsOffset={2} mdOffset={2} lgOffset={2}>
<div className='title'>
<i className='fa fa-smile-o'></i>: Hello, world!
</div>
<p>-I am Kei-sau, CHING</p>
</Col>
</Row>
</Grid>
)
}
}
|
import React from 'react'; const House = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><polygon points="6.00058581 10.9998 6 11 6 19.9998 11 19.9998 11 16.0009 13 16.0009 13 19.9998 18 19.9998 18 11 17.9994142 10.9998 18.0027466 10.9998 12.0003 4.9998 6.0003 10.9998"/></g></g></svg>; export default House;
|
/**
* Numpy like n-dimensional array proccessing class
* http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html
*
* @author pissang (https://github.com/pissang/)
*/
define(function(require) {
'use strict';
require('./kwargs');
var ArraySlice = Array.prototype.slice;
var global = window;
// Polyfill of Typed Array
global.Int32Array = global.Int32Array || Array;
global.Int16Array = global.Int16Array || Array;
global.Int8Array = global.Int8Array || Array;
global.Uint32Array = global.Uint32Array || Array;
global.Uint16Array = global.Uint16Array || Array;
global.Uint8Array = global.Uint8Array || Array;
global.Float32Array = global.Float32Array || Array;
global.Float64Array = global.Float64Array || Array;
// Map of numpy dtype and typed array
// http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#arrays-dtypes
// http://www.khronos.org/registry/typedarray/specs/latest/
var ArrayConstructor = {
'int32' : global.Int32Array,
'int16' : global.Int16Array,
'int8' : global.Int8Array,
'uint32' : global.Uint32Array,
'uint16' : global.Uint16Array,
'uint8' : global.Uint8Array,
// 'uint8c' is not existed in numpy
'uint8c' : global.Uint8ClampedArray,
'float32' : global.Float32Array,
'float64' : global.Float64Array,
'number' : Array
};
var dTypeStrideMap = {
'int32' : 4,
'int16' : 2,
'int8' : 1,
'uint32' : 4,
'uint16' : 2,
'uint8' : 1,
'uint8c' : 1,
'float32' : 4,
'float64' : 8,
// Consider array stride is 1
'number' : 1
};
var E_ADD = 0;
var E_SUB = 1;
var E_MUL = 2;
var E_DIV = 3;
var E_MOD = 4;
var E_AND = 5;
var E_OR = 6;
var E_XOR = 7;
var E_EQL = 8;
function guessDataType(arr) {
if (typeof(arr) === 'undefined') {
return 'number';
}
switch(Object.prototype.toString.call(arr)) {
case '[object Int32Array]':
return 'int32';
case '[object Int16Array]':
return 'int16';
case '[object Int8Array]':
return 'int8';
case '[object Uint32Array]':
return 'uint32';
case '[object Uint16Array]':
return 'uint16';
case '[object Uint8Array]':
return 'uint8';
case '[object Uint8ClampedArray]':
return 'uint8c';
case '[object Float32Array]':
return 'float32';
case '[object Float64Array]':
return 'float64';
default:
return 'number';
}
}
/**
* NDArray
* @param {Array|NDArray} array
* @param {String} dtype
*/
var NDArray = function(array) {
// Last argument describe the data type of ndarray
var dtype = arguments[arguments.length-1];
if (typeof(dtype) == 'string') {
this._dtype = dtype;
} else {
// Normal array
this._dtype = guessDataType(array);
}
if (array && typeof(array) !== 'string') {
if (array instanceof NDArray) {
array._dtype = this._dtype;
return array;
} else if (array.length) {
// Init from array
this.initFromArray(array);
} else if(typeof(array) === 'number') {
// Init from shape
this.initFromShape.apply(this, arguments);
}
} else {
/**
* _array
* Initialized with an empty array
* Data is continuous one-dimensional array, row-major
* A [2, 2] dim empty array is stored like
* [0,0, 0,0]
* TODO : Consider column majors ?
* @type {ArrayConstructor}
*/
this._array = new ArrayConstructor[this._dtype]();
/**
* _shape
* a tuple array describe the dimension and size of each dimension
* [10, 10] means a 10x10 array
* @type {Array}
*/
this._shape = [0];
/**
* _size
* size of the storage array length
* @type {Number}
*/
this._size = 0;
}
};
NDArray.prototype = {
/**
* Initialize from a normal js array.
*
* @param {Array} input
* @return {NDArray} this
*/
initFromArray : function(input) {
var dim = getDimension(input);
var cursor = 0;
function flatten(axis, _out, _in) {
var len = _in.length;
for (var i = 0; i < len; i++) {
if (axis < dim-1) {
flatten(axis+1, _out, _in[i]);
} else {
_out[cursor++] = _in[i];
}
}
}
var shape = getShape(input);
var size = getSize(shape);
this._array = new ArrayConstructor[this._dtype](size);
flatten(0, this._array, input);
this._shape = shape;
this._size = size;
return this;
},
/**
* Initialize from the given shape description.
* @param {Array} shape
* @return {NDArray} this
*/
initFromShape : function(shape) {
if (typeof(shape) == 'number') {
shape = Array.prototype.slice.call(arguments);
}
if(shape) {
var size = getSize(shape);
if (this._dtype === 'number') {
this._array = [];
var data = this._array;
for (var i = 0; i < size; i++) {
data[i] = 0;
}
} else {
this._array = new ArrayConstructor[this._dtype](size);
}
}
this._shape = shape;
this._size = getSize(shape);
return this;
},
/**
* Fill the array with the given value.
* @param {Number} value
* @return {NDArray} this
*/
fill : function(value) {
var data = this._array;
for (var i = 0; i < data.length; i++) {
data[i] = value;
}
return this;
},
/**
* Get ndarray shape copy.
* @return {Array}
*/
shape : function() {
// Create a copy
return this._shape.slice();
},
/**
* Get array size
* @return {Number}
*/
size : function() {
return this._size;
},
/**
* Get array data type.
* 'int32'
* 'int16'
* 'int8'
* 'uint32'
* 'uint16'
* 'uint8'
* 'float32'
* 'float64'
* @return {String}
*/
dtype : function() {
return this._dtype;
},
/**
* Get array dimension.
* @return {[type]} [description]
*/
dimension : function() {
return this._shape.length;
},
/**
* Tuple of bytes to step in each dimension when traversing an array.
* @return {Array}
*/
strides : function() {
var strides = calculateDimStrides(this._shape);
var dTypeStride = dTypeStrideMap[this._dtype];
for (var i = 0; i < strides.length; i++) {
strides[i] *= dTypeStride;
}
return strides;
},
/**
* Gives a new shape to an array without changing its data.
* @param {Array} shape
* @return {NDArray}
*/
reshape : function(shape) {
if (typeof(shape) == 'number') {
shape = Array.prototype.slice.call(arguments);
}
if (this._isShapeValid(shape)) {
this._shape = shape;
} else {
throw new Error('Total size of new array must be unchanged');
}
return this;
},
_isShapeValid : function(shape) {
return getSize(shape) === this._size;
},
/**
* Change shape and size of array in-place.
* @param {Array} shape
* @return {NDArray}
*/
resize : function(shape) {
if (typeof(shape) == 'number') {
shape = Array.prototype.slice.call(arguments);
}
var len = getSize(shape);
if (len < this._size) {
if (this._dtype === 'number') {
this._array.length = len;
}
} else {
if (this._dtype === 'number') {
for (var i = this._array.length; i < len; i++) {
// Fill the rest with zero
this._array[i] = 0;
}
} else {
// Reallocate new buffer
var newArr = new ArrayConstructor[this._dtype](len);
var originArr = this._array;
// Copy data
for (var i = 0; i < originArr.length; i++) {
newArr[i] = originArr[i];
}
this._array = newArr;
}
}
this._shape = shape;
this._size = len;
return this;
},
/**
* Returns a new array with axes transposed.
* @param {Array} [axes]
* @param {NDArray} [out]
* @return {NDArray}
*/
transpose : function(axes, out) {
var originAxes = [];
for (var i = 0; i < this._shape.length; i++) {
originAxes.push(i);
}
if (typeof(axes) === 'undefined') {
axes = originAxes.slice();
}
// Check if any axis is out of bounds
for (var i = 0; i < axes.length; i++) {
if (axes[i] >= this._shape.length) {
throw new Error(axisOutofBoundsErrorMsg(axes[i]));
}
}
// Has no effect on 1-D transpose
if (axes.length <= 1) {
return this;
}
var targetAxes = originAxes.slice();
for (var i = 0; i < Math.floor(axes.length / 2); i++) {
for (var j = axes.length-1; j >= Math.ceil(axes.length / 2) ; j--) {
// Swap axes
targetAxes[axes[i]] = axes[j];
targetAxes[axes[j]] = axes[i];
}
}
return this._transposelike(targetAxes, out);
}.kwargs(),
/**
* Return a new array with axis1 and axis2 interchanged.
* @param {Number} axis1
* @param {Number} axis2
* @param {NDArray} out
* @return {NDArray}
*/
swapaxes : function(axis1, axis2, out) {
return this.transpose([axis1, axis2], out);
}.kwargs(),
/**
* Roll the specified axis backwards, until it lies in a given position.
* @param {Number} axis
* @param {Number} [start=0]
* @param {NDArray} out
* @return {NDArray}
*/
rollaxis : function(axis, start, out) {
if (axis >= this._shape.length) {
throw new Error(axisOutofBoundsErrorMsg(axis));
}
var axes = [];
for (var i = 0; i < this._shape.length; i++) {
axes.push(i);
}
axes.splice(axis, 1);
axes.splice(start, 0, axis);
return this._transposelike(axes, out);
}.kwargs({ start : 0}),
// Base function for transpose-like operations
_transposelike : function(axes, out) {
var source = this._array;
var shape = this._shape.slice();
var strides = calculateDimStrides(this._shape);
var dim = shape.length;
// Swap
var tmpStrides = [];
var tmpShape = [];
for (var i = 0; i < axes.length; i++) {
var axis = axes[i];
// swap to target axis
tmpShape[i] = shape[axis];
tmpStrides[i] = strides[axis];
}
strides = tmpStrides;
shape = tmpShape;
this._shape = shape;
var transposedStrides = calculateDimStrides(this._shape);
if (!out) {
out = new NDArray();
out._shape = this._shape.slice();
out._dtype = this._dtype;
out._size = this._size;
}
// FIXME in-place transpose?
var transposedData = new ArrayConstructor[this._dtype](this._size);
out._array = transposedData;
// @param Item offset in current axis offset of the original array
// @param Item offset in current axis offset of the transposed array
function transpose(axis, offset, transposedOffset) {
var size = shape[axis];
// strides in orginal array
var stride = strides[axis];
// strides in transposed array
var transposedStride = transposedStrides[axis];
if (axis < dim-1) {
for (var i = 0; i < size; i++) {
transpose(
axis+1,
offset + stride * i,
transposedOffset + transposedStride * i
);
}
} else {
for (var i = 0; i < size; i++) {
// offset + stride * i is the index of the original array
// transposedOffset + i is the index of the transposed array
transposedData[transposedOffset + i]
= source[offset + stride * i];
}
}
}
transpose(0, 0, 0);
return out;
},
/**
* Repeat elements of an array along axis
* @param {Number} repeats
* The number of repetitions for each element.
* repeats is broadcasted to fit the shape of the given axis.
* @param {Number} [axis]
* The axis along which to repeat values.
* By default, use the flattened input array,
* and return a flat output array.
* @param {NDArray} [out]
* @return {NDArray}
*/
repeat : function(repeats, axis, out) {
var shape;
// flattened input array
if (typeof(axis) === 'undefined') {
shape = [this._size];
axis = 0;
} else {
shape = this._shape.slice();
}
var originShape = shape.slice();
shape[axis] *= repeats;
if (!out) {
out = new NDArray(this._dtype);
out.initFromShape(shape);
} else {
if (!arrayEqual(shape, out._shape)) {
throw new Error(broadcastErrorMsg(shape, out._shape));
}
}
var data = out._array;
var stride = calculateDimStride(originShape, axis);
var axisSize = originShape[axis];
var source = this._array;
var offsetStride = stride * axisSize;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var k = 0; k < stride; k++) {
var idx = offset + k;
var idxRepeated = offset * repeats + k;
for (var i = 0; i < axisSize; i++) {
for (var j = 0; j < repeats; j++) {
data[idxRepeated] = source[idx];
idxRepeated += stride;
}
idx += stride;
}
}
}
return out;
}.kwargs(),
choose : function() {
console.warn('TODO');
},
take : function() {
console.warn('TODO');
},
tile : function() {
console.warn('TODO');
},
/**
* Preprocess for array calculation
* max, min, argmax, argmin, sum, ptp, val, mean
* Which will reduce one axis if the axis is given
*
* @param {Number} axis
* @param {NDArray} out
* @param {Function} funcWithAxis
* @param {Function} funcFlatten
* @return {Number|NDArray}
*/
_withPreprocess1 : function(axis, out, funcWithAxis, funcFlatten) {
var source = this._array;
if (!this._size) {
return;
}
if (typeof(axis)!=='undefined') {
if (axis < 0) {
axis = this._shape.length + axis;
}
if (axis >= this._shape.length || axis < 0) {
throw new Error(axisOutofBoundsErrorMsg(axis));
}
var shape = this._shape.slice();
shape.splice(axis, 1);
if (out && !arrayEqual(shape, out._shape)) {
throw new Error(broadcastErrorMsg(shape, out._shape));
}
if (!out) {
out = new NDArray(this._dtype);
out.initFromShape(shape);
}
var data = out._array;
var stride = calculateDimStride(this._shape, axis);
var axisSize = this._shape[axis];
var offsetStride = stride * axisSize;
funcWithAxis.call(
this, data, source, offsetStride, axisSize, stride
);
return out;
} else {
return funcFlatten.call(this, source);
}
},
/**
* Preprocess for array calculation cumsum, cumprod
* Which will keep the shape if axis is given
* and flatten if axis is undefined
* @param {Number} axis
* @param {NDArray} out
* @param {Function} funcWithAxis
* @param {Function} funcFlatten
* @return {NDArray}
*/
_withPreprocess2 : function(axis, out, funcWithAxis, funcFlatten) {
var source = this._array;
if (!this._size) {
return;
}
if (out && !arrayEqual(this._shape, out._shape)) {
throw new Error(broadcastErrorMsg(this._shape, out._shape));
}
if (!out) {
out = new NDArray(this._dtype);
out.initFromShape(this._shape);
}
var data = out._array;
if (typeof(axis)!=='undefined') {
if (axis < 0) {
axis = this._shape.length + axis;
}
if (axis >= this._shape.length || axis < 0) {
throw new Error(axisOutofBoundsErrorMsg(axis));
}
if (axis >= this._shape.length) {
throw new Error(axisOutofBoundsErrorMsg(axis));
}
var stride = calculateDimStride(this._shape, axis);
var axisSize = this._shape[axis];
var offsetStride = stride * axisSize;
funcWithAxis.call(
this, data, source, offsetStride, axisSize, stride
);
} else {
out.reshape([this._size]);
funcFlatten.call(this, data, source);
}
return out;
},
/**
* Get the max value of ndarray
* If the axis is given, the max is only calculate in this dimension
* Example, for the given ndarray
* [[3, 9],
* [4, 8]]
* >>> max(0)
* [4, 9]
* >>> max(1)
* [9, 8]
*
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
max : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var idx = i + offset;
var max = source[idx];
for (var j = 0; j < axisSize; j++) {
var d = source[idx];
if (d > max) {
max = d;
}
idx += stride;
}
data[cursor++] = max;
}
}
}
function withFlatten(source) {
var max = source[0];
for (var i = 1; i < this._size; i++) {
if (source[i] > max) {
max = source[i];
}
}
return max;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Return the minimum of an array or minimum along an axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
min : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var idx = i + offset;
var min = source[idx];
for (var j = 0; j < axisSize; j++) {
var d = source[idx];
if (d < min) {
min = d;
}
idx += stride;
}
data[cursor++] = min;
}
}
}
function withFlatten(source) {
var min = source[0];
for (var i = 1; i < this._size; i++) {
if (source[i] < min) {
min = source[i];
}
}
return min;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Return indices of the maximum values along an axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
argmax : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var dataIdx = 0;
var idx = i + offset;
var max = source[idx];
for (var j = 0; j < axisSize; j++) {
var d = source[idx];
if (d > max) {
max = d;
dataIdx = j;
}
idx += stride;
}
data[cursor++] = dataIdx;
}
}
}
function withFlatten(source) {
var max = source[0];
var idx = 0;
for (var i = 1; i < this._size; i++) {
if (source[i] > max) {
idx = i;
max = source[i];
}
}
return idx;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Indices of the minimum values along an axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
argmin : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var dataIdx = 0;
var idx = i + offset;
var min = source[idx];
for (var j = 0; j < axisSize; j++) {
var d = source[idx];
if (d < min) {
min = d;
dataIdx = j;
}
idx += stride;
}
data[cursor++] = dataIdx;
}
}
}
function withFlatten(source) {
var min = source[0];
var idx = 0;
for (var i = 1; i < this._size; i++) {
if (source[i] < min) {
idx = i;
min = source[i];
}
}
return idx;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Return the sum of the array elements over the given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
sum : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var sum = 0;
var idx = i + offset;
for (var j = 0; j < axisSize; j++) {
sum += source[idx];
idx += stride;
}
data[cursor++] = sum;
}
}
}
function withFlatten(source) {
var sum = 0;
for (var i = 0; i < this._size; i++) {
sum += source[i];
}
return sum;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Return the product of the array elements over the given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
prod : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var prod = 1;
var idx = i + offset;
for (var j = 0; j < axisSize; j++) {
prod *= source[idx];
idx += stride;
}
data[cursor++] = prod;
}
}
}
function withFlatten(source) {
var prod = 1;
for (var i = 0; i < this._size; i++) {
prod *= source[i];
}
return prod;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Returns the average of the array elements along given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
mean : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var sum = 0;
var idx = i + offset;
for (var j = 0; j < axisSize; j++) {
sum += source[idx];
idx += stride;
}
var mean = sum / axisSize;
data[cursor++] = mean;
}
}
}
function withFlatten(source) {
var sum = 0;
var len = source.length;
for (var i = 0; i < len; i++) {
sum += source[i];
}
var mean = sum / len;
return mean;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Return the variance of the array elements over the given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
'var' : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var sum = 0;
var idx = i + offset;
for (var j = 0; j < axisSize; j++) {
sum += source[idx];
idx += stride;
}
var mean = sum / axisSize;
var moments = 0;
idx = i + offset;
for (var j = 0; j < axisSize; j++) {
var diff = source[idx] - mean;
moments += diff * diff;
idx += stride;
}
data[cursor++] = moments / axisSize;
}
}
}
function withFlatten(source) {
var sum = 0;
var len = source.length;
for (var i = 0; i < len; i++) {
sum += source[i];
}
var mean = sum / len;
var moments = 0;
for (var i = 0; i < len; i++) {
var diff = source[i] - mean;
moments += diff * diff;
}
return moments / len;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Return the standard derivatione of the array elements
* over the given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
std : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var sum = 0;
var idx = i + offset;
for (var j = 0; j < axisSize; j++) {
sum += source[idx];
idx += stride;
}
var mean = sum / axisSize;
var moments = 0;
idx = i + offset;
for (var j = 0; j < axisSize; j++) {
var diff = source[idx] - mean;
moments += diff * diff;
idx += stride;
}
data[cursor++] = Math.sqrt(moments / axisSize);
}
}
}
function withFlatten(source) {
var sum = 0;
var len = source.length;
for (var i = 0; i < len; i++) {
sum += source[i];
}
var mean = sum / len;
var moments = 0;
for (var i = 0; i < len; i++) {
var diff = source[i] - mean;
moments += diff * diff;
}
return Math.sqrt(moments / len);
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Peak to peak (maximum - minimum) value along a given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
ptp : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
var cursor = 0;
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var idx = offset + i;
var min = source[idx];
var max = source[idx];
for (var j = 0; j < axisSize; j++) {
var d = source[idx];
if (d < min) {
min = d;
}
if (d > max) {
max = d;
}
idx += stride;
}
data[cursor++] = max - min;
}
}
}
function withFlatten(source) {
var min = source[0];
var max = source[0];
for (var i = 1; i < this._size; i++) {
if (source[i] < min) {
min = source[i];
}
if (source[i] > max) {
max = source[i];
}
}
return max - min;
}
return function(axis, out) {
return this._withPreprocess1(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
*
* @param {Number} [axis=-1]
* @param {string} [order='ascending']
* 'ascending' | 'descending'
* @return {NDArray}
*/
// FIXME : V8 is quick sort, firefox and safari is merge sort
// order : ascending or desc
sort : function(axis, order) {
if (axis < 0) {
axis = this._shape.length + axis;
}
var compareFunc;
if (order === 'ascending') {
compareFunc = function(a, b) {
return a - b;
};
} else if( order === 'descending') {
compareFunc = function(a, b) {
return b - a;
};
}
var source = this._array;
var stride = calculateDimStride(this._shape, axis);
var axisSize = this._shape[axis];
var offsetStride = stride * axisSize;
var tmp = new Array(axisSize);
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var idx = offset + i;
for (var j = 0; j < axisSize; j++) {
tmp[j] = source[idx];
idx += stride;
}
tmp.sort(compareFunc);
var idx = offset + i;
// Copy back
for (var j = 0; j < axisSize; j++) {
source[idx] = tmp[j];
idx += stride;
}
}
}
return this;
}.kwargs({axis : -1, order : 'ascending'}),
/**
*
* @param {Number} [axis=-1]
* @param {string} [order='ascending']
* 'ascending' | 'descending'
* @param {NDArray} [out]
* @return {NDArray}
*/
argsort : function(axis, order, out) {
if (axis < 0) {
axis = this._shape.length + axis;
}
if (!this._size) {
return;
}
if (out && !arrayEqual(this._shape, out._shape)) {
throw new Error(broadcastErrorMsg(this._shape, out._shape));
}
if (!out) {
out = new NDArray(this._dtype);
out.initFromShape(this._shape);
}
var data = out._array;
var compareFunc;
if (order === 'ascending') {
compareFunc = function(a, b) {
return tmp[a] - tmp[b];
};
} else if( order === 'descending') {
compareFunc = function(a, b) {
return tmp[b] - tmp[a];
};
}
var source = this._array;
var stride = calculateDimStride(this._shape, axis);
var axisSize = this._shape[axis];
var offsetStride = stride * axisSize;
var tmp = new Array(axisSize);
var indexList = new Array(axisSize);
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var idx = offset + i;
for (var j = 0; j < axisSize; j++) {
tmp[j] = source[idx];
indexList[j] = j;
idx += stride;
}
indexList.sort(compareFunc);
// Copy back
var idx = offset + i;
for (var j = 0; j < axisSize; j++) {
data[idx] = indexList[j];
idx += stride;
}
}
}
return out;
}.kwargs({axis : -1, order : 'ascending'}),
/**
* Return the cumulative sum of the elements along the given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
cumsum : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var idx = offset + i;
var prevIdx = idx;
data[idx] = source[idx];
for (var j = 1; j < axisSize; j++) {
prevIdx = idx;
idx += stride;
data[idx] = data[prevIdx] + source[idx];
}
}
}
}
function withFlatten(data, source) {
data[0] = source[0];
for (var i = 1; i < data.length; i++) {
data[i] = data[i-1] + source[i];
}
}
return function(axis, out) {
return this._withPreprocess2(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Return the cumulative product of the elements along the given axis.
* @param {Number} [axis]
* @param {NDArray} out
* @return {NDArray}
*/
cumprod : (function() {
function withAxis(data, source, offsetStride, axisSize, stride) {
for (var offset = 0; offset < this._size; offset+=offsetStride) {
for (var i = 0; i < stride; i++) {
var idx = offset + i;
var prevIdx = idx;
data[idx] = source[idx];
for (var j = 1; j < axisSize; j++) {
prevIdx = idx;
idx += stride;
data[idx] = data[prevIdx] * source[idx];
}
}
}
}
function withFlatten(data, source) {
data[0] = source[0];
for (var i = 1; i < data.length; i++) {
data[i] = data[i-1] * source[i];
}
}
return function(axis, out) {
return this._withPreprocess2(
axis, out,
withAxis, withFlatten
);
};
})().kwargs(),
/**
* Dot product of two arrays.
*
* @param {NDArray|Number} b
* @param {NDArray} [out]
* @return {NDArray|Number}
*/
dot : function() {
console.warn('TODO');
},
/**
* Mapped to region [min, max]
* @param {Number} mappedMin
* @param {Number} mappedMax
*/
map : function(mappedMin, mappedMax) {
var input = this._array;
var output = this._array;
var min = input[0];
var max = input[0];
var l = this._size;
for (var i = 1; i < l; i++) {
var val = input[i];
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
var range = max - min;
var mappedRange = mappedMax - mappedMin;
for (var i = 0; i < l; i++) {
if (range === 0) {
output[i] = mappedMin;
} else {
var val = input[i];
var percent = (val - min) / range;
output[i] = mappedRange * percent + mappedMin;
}
}
return this;
},
/**
* Add
*/
add : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_ADD, out
);
},
/**
* Substract
*/
sub : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_SUB, out
);
},
/**
* Multiply
*/
mul : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_MUL, out
);
},
/**
* Divide
*/
div : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_DIV, out
);
},
/**
* mod
*/
mod : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_MOD, out
);
},
/**
* and
*/
and : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_AND, out
);
},
/**
* or
*/
or : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_OR, out
);
},
/**
* xor
*/
xor : function(rightOperand, out) {
return this.binaryOperation(
this, rightOperand, E_XOR, out
);
},
/**
* equal
*/
equal : function(rightOperand) {
return this.binaryOperation(
this, rightOperand, E_EQL, out
);
},
binaryOperation : function(lo, ro, op, out) {
// Broadcasting
// http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
var shape = [];
var isLoScalar = typeof(lo) === 'number';
var isRoScalar = typeof(ro) === 'number';
if (isLoScalar) {
shape = ro._shape.slice();
} else if (isRoScalar) {
shape = lo._shape.slice();
} else {
// Starts with the trailing dimensions
var cl = lo._shape.length-1;
var cr = ro._shape.length-1;
var loBroadCasted = lo;
var roBroadCasted = ro;
while (cl >= 0 && cr >= 0) {
if (lo._shape[cl] == 1) {
shape.unshift(ro._shape[cr]);
loBroadCasted = lo.repeat(ro._shape[cr], cl);
} else if(ro._shape[cr] == 1) {
shape.unshift(lo._shape[cl]);
roBroadCasted = ro.repeat(lo._shape[cl], cr);
} else if(ro._shape[cr] == lo._shape[cl]) {
shape.unshift(lo._shape[cl]);
} else {
throw new Error(broadcastErrorMsg(lo._shape, ro._shape));
}
cl --;
cr --;
}
for (var i = cl; i >= 0; i--) {
shape.unshift(lo._shape[i]);
}
for (var i = cr; i >= 0; i--) {
shape.unshift(ro._shape[i]);
}
lo = loBroadCasted;
ro = roBroadCasted;
}
if (!out) {
out = new NDArray(this._dtype);
out.initFromShape(shape);
} else {
if (! arrayEqual(shape, out._shape)) {
throw new Error(broadcastErrorMsg(shape, out._shape));
}
}
var outData = out._array;
var diffAxis;
var isLoLarger;
var loData;
var roData;
if (isLoScalar) {
diffAxis = ro._shape.length-1;
isLoLarger = false;
loData = lo;
roData = ro._array;
} else if(isRoScalar) {
diffAxis = lo._shape.length-1;
isLoLarger = true;
roData = ro;
loData = lo._array;
} else {
diffAxis = Math.abs(lo._shape.length - ro._shape.length);
isLoLarger = lo._shape.length >= ro._shape.length;
loData = lo._array;
roData = ro._array;
}
var stride = calculateDimStride(shape, diffAxis);
var axisSize = shape[diffAxis];
var offsetStride = stride * axisSize;
var offsetRepeats = out._size / offsetStride;
var _a, _b, res;
var idx = 0;
if (isLoLarger) {
if(isRoScalar) {
for (var c = 0; c < offsetRepeats; c++) {
for (var i = 0; i < offsetStride; i++) {
_a = loData[idx]; _b = roData;
switch (op) {
case E_ADD: res = _a + _b; break;
case E_SUB: res = _a - _b; break;
case E_MUL: res = _a * _b; break;
case E_DIV: res = _a / _b; break;
case E_MOD: res = _a % _b; break;
case E_AND: res = _a & _b; break;
case E_OR: res = _a | _b; break;
case E_XOR: res = _a ^ _b; break;
case E_EQL: res = _a == _b; break;
default: throw new Error('Unkown operation ' + op);
}
outData[idx] = res;
idx ++;
}
}
} else {
for (var c = 0; c < offsetRepeats; c++) {
for (var i = 0; i < offsetStride; i++) {
_a = loData[idx]; _b = roData[i];
switch (op) {
case E_ADD: res = _a + _b; break;
case E_SUB: res = _a - _b; break;
case E_MUL: res = _a * _b; break;
case E_DIV: res = _a / _b; break;
case E_MOD: res = _a % _b; break;
case E_AND: res = _a & _b; break;
case E_OR: res = _a | _b; break;
case E_XOR: res = _a ^ _b; break;
case E_EQL: res = _a == _b; break;
default: throw new Error('Unkown operation ' + op);
}
outData[idx] = res;
idx ++;
}
}
}
} else {
if (isLoScalar) {
for (var c = 0; c < offsetRepeats; c++) {
for (var i = 0; i < offsetStride; i++) {
_a = loData; _b = roData[idx];
switch (op) {
case E_ADD: res = _a + _b; break;
case E_SUB: res = _a - _b; break;
case E_MUL: res = _a * _b; break;
case E_DIV: res = _a / _b; break;
case E_MOD: res = _a % _b; break;
case E_AND: res = _a & _b; break;
case E_OR: res = _a | _b; break;
case E_XOR: res = _a ^ _b; break;
case E_EQL: res = _a == _b; break;
default: throw new Error('Unkown operation ' + op);
}
outData[idx] = res;
idx ++;
}
}
} else {
for (var c = 0; c < offsetRepeats; c++) {
for (var i = 0; i < offsetStride; i++) {
_a = loData[idx]; _b = roData[i];
switch (op) {
case E_ADD: res = _a + _b; break;
case E_SUB: res = _a - _b; break;
case E_MUL: res = _a * _b; break;
case E_DIV: res = _a / _b; break;
case E_MOD: res = _a % _b; break;
case E_AND: res = _a & _b; break;
case E_OR: res = _a | _b; break;
case E_XOR: res = _a ^ _b; break;
case E_EQL: res = _a == _b; break;
default: throw new Error('Unkown operation ' + op);
}
outData[idx] = res;
idx ++;
}
}
}
}
return out;
},
/**
* negtive
*/
neg : function() {
var data = this._array;
for (var i = 0; i < this._size; i++) {
data[i] = -data[i];
}
return this;
},
/**
* @return {NDArray} this
*/
sin : function() {
return this._mathAdapter(Math.sin);
},
/**
* @return {NDArray} this
*/
cos : function() {
return this._mathAdapter(Math.cos);
},
/**
* @return {NDArray} this
*/
tan : function() {
return this._mathAdapter(Math.tan);
},
/**
* @return {NDArray} this
*/
abs : function() {
return this._mathAdapter(Math.abs);
},
/**
* @return {NDArray} this
*/
log : function() {
return this._mathAdapter(Math.log);
},
/**
* @return {NDArray} this
*/
sqrt : function() {
return this._mathAdapter(Math.sqrt);
},
/**
* @return {NDArray} this
*/
ceil : function() {
return this._mathAdapter(Math.ceil);
},
/**
* @return {NDArray} this
*/
floor : function() {
return this._mathAdapter(Math.floor);
},
/**
* @return {NDArray} this
*/
pow : function(exp) {
var data = this._array;
for (var i = 0; i < this._size; i++) {
data[i] = Math.pow(data[i], exp);
}
return this;
},
_mathAdapter : function(mathFunc) {
var data = this._array;
for (var i = 0; i < this._size; i++) {
data[i] = mathFunc(data[i]);
}
return this;
},
/**
* @param {Number} decimals
* @return {NDArray} this
*/
round : function(decimals) {
decimals = Math.floor(decimals || 0);
var offset = Math.pow(10, decimals);
var data = this._array;
if (decimals === 0) {
for (var i = 0; i < this._size; i++) {
data[i] = Math.round(data[i]);
}
} else {
for (var i = 0; i < this._size; i++) {
data[i] = Math.round(data[i] * offset) / offset;
}
}
return this;
},
/**
* @param {Number} min
* @param {Number} max
* Clip to [min, max]
*/
clip : function(min, max) {
// TODO : Support array_like param
var data = this._array;
for (var i = 0; i < this._size; i++) {
data[i] = Math.max(Math.min(data[i], max), min);
}
return this;
},
/**
* Indexing array, support range indexing
* @param {string} index
* Index syntax can be an integer 1, 2, 3
* Or more complex range indexing
* '1:2'
* '1:2, 1:2'
* '1:2, :'
* More about the indexing syntax can check the doc of numpy ndarray
* @param {NDArray} [out]
* @return {NDArray} New created sub array, or out if given
*/
get : function(index, out) {
if (typeof(index) == 'number') {
index = index.toString();
}
var strides = calculateDimStrides(this._shape);
var res = this._parseRanges(index);
var ranges = res[0];
var shape = res[1];
if (ranges.length > this._shape.length) {
throw new Error('Too many indices');
}
// Get data
var len = ranges.length;
var data;
if (shape.length) {
out = new NDArray(this._dtype);
out.initFromShape(shape);
data = out._array;
} else {
data = [];
}
var source = this._array;
var cursor = 0;
function getPiece(axis, offset) {
var range = ranges[axis];
var stride = strides[axis];
if (axis < len-1) {
if (range[2] > 0) {
for (var i = range[0]; i < range[1]; i += range[2]) {
getPiece(axis+1, offset + stride * i);
}
} else {
for (var i = range[0]; i > range[1]; i += range[2]) {
getPiece(axis+1, offset + stride * i);
}
}
} else {
if (range[2] > 0) {
for (var i = range[0]; i < range[1]; i += range[2]) {
for (var j = 0; j < stride; j++) {
data[cursor++] = source[i*stride + j + offset];
}
}
} else {
for (var i = range[0]; i > range[1]; i += range[2]) {
for (var j = 0; j < stride; j++) {
data[cursor++] = source[i*stride + j + offset];
}
}
}
}
}
getPiece(0, 0);
if (shape.length) {
// Return scalar
return out;
} else {
return data[0];
}
},
/**
*
* @param {string} index
* index syntax can be an integer 1, 2, 3
* Or more complex range indexing
* '1:2'
* '1:2, 1:2'
* '1:2, :'
* More about the indexing syntax can check the doc of numpy ndarray
* @param {NDArray} ndarray Ndarray data source
* @return {NDArray} this
*/
set : function(index, narray) {
if (typeof(index) == 'number') {
index = index.toString();
}
var strides = calculateDimStrides(this._shape);
var res = this._parseRanges(index);
var ranges = res[0];
var shape = res[1];
if (ranges.length > this._shape.length) {
throw new Error('Too many indices');
}
var isScalar = typeof(narray) == 'number';
var len = ranges.length;
var data = this._array;
if (isScalar) {
// Set with a single scalar
var source = narray;
} else {
if (!arrayEqual(shape, narray.shape())) {
throw new Error(broadcastErrorMsg(shape, narray.shape()));
}
var source = narray._array;
}
var cursor = 0;
var setPiece = function(axis, offset) {
var range = ranges[axis];
var stride = strides[axis];
if (axis < len-1) {
if (range[2] > 0) {
for (var i = range[0]; i < range[1]; i += range[2]) {
setPiece(axis+1, offset + stride * i);
}
} else {
for (var i = range[0]; i > range[1]; i += range[2]) {
setPiece(axis+1, offset + stride * i);
}
}
} else {
if (range[2] > 0) {
for (var i = range[0]; i < range[1]; i += range[2]) {
for (var j = 0; j < stride; j++) {
if (isScalar) {
data[i*stride + j + offset] = source;
} else {
data[i*stride + j + offset] = source[cursor++];
}
}
}
} else {
for (var i = range[0]; i > range[1]; i += range[2]) {
for (var j = 0; j < stride; j++) {
if (isScalar) {
data[i*stride + j + offset] = source;
} else {
data[i*stride + j + offset] = source[cursor++];
}
}
}
}
}
};
setPiece(0, 0);
return this;
},
/**
* Insert values along the given axis before the given indices.
* @param {Number|Array} obj
* Object that defines the index or indices before
* which values is inserted.
* @param {Number|Array|NDArray} values
* Values to insert
* @param {Number} [axis]
* @return {NDArray} this
*/
insert : function(obj, values, axis) {
var data = this._array;
var isObjScalar = false;
if (typeof(obj) === 'number') {
obj = [obj];
isObjScalar = true;
}
if (typeof(values) === 'number') {
values = new NDArray([values]);
} else if (values instanceof Array) {
values = new NDArray(values);
}
if (typeof(axis) === 'undefined') {
this._shape = [this._size];
axis = 0;
}
// Checking if indices is valid
var prev = obj[0];
var axisSize = this._shape[axis];
for (var i = 0; i < obj.length; i++) {
if (obj[i] < 0) {
obj[i] = axisSize + obj[i];
}
if (obj[i] > axisSize) {
throw new Error(indexOutofBoundsErrorMsg(obj[i]));
}
if (obj[i] < prev) {
throw new Error('Index must be in ascending order');
}
prev = obj[i];
}
// Broadcasting
var targetShape = this._shape.slice();
if (isObjScalar) {
targetShape.splice(axis, 1);
} else {
targetShape[axis] = obj.length;
}
var sourceShape = values._shape;
var cs = sourceShape.length - 1;
var ct = targetShape.length - 1;
var valueBroadcasted = values;
while (cs >= 0 && ct >= 0) {
if (sourceShape[cs] === 1) {
valueBroadcasted = values.repeat(targetShape[ct], cs);
} else if(sourceShape[cs] !== targetShape[ct]) {
throw new Error(broadcastErrorMsg(sourceShape, targetShape));
}
cs --;
ct --;
}
values = valueBroadcasted;
// Calculate indices to insert
var stride = calculateDimStride(this._shape, axis);
var axisSize = this._shape[axis];
var offsetStride = axisSize * stride;
var offsetRepeats = this._size / offsetStride;
var objLen = obj.length;
var indices = new Uint32Array(offsetRepeats * objLen);
var cursor = 0;
for (var offset = 0; offset < this._size; offset += offsetStride) {
for (var i = 0; i < objLen; i++) {
var objIdx = obj[i];
indices[cursor++] = offset + objIdx * stride;
}
}
var resShape = this._shape.slice();
resShape[axis] += obj.length;
var resSize = getSize(resShape);
if (this._array.length < resSize) {
var data = new ArrayConstructor[this._dtype](resSize);
} else {
var data = this._array;
}
var source = this._array;
var valuesArr = values._array;
var idxCursor = indices.length - 1;
var end = this._size;
var start = indices[idxCursor];
var dataCursor = resSize - 1;
var valueCursor = values._size - 1;
while (idxCursor >= 0) {
// Copy source data;
for (var i = end - 1; i >= start; i--) {
data[dataCursor--] = source[i];
}
end = start;
start = indices[--idxCursor];
// Copy inserted data;
for (var i = 0; i < stride; i++) {
if (valueCursor < 0) {
valueCursor = values._size - 1;
}
data[dataCursor--] = valuesArr[valueCursor--];
}
}
// Copy the rest
for (var i = end - 1; i >= 0; i--) {
data[dataCursor--] = source[i];
}
this._array = data;
this._shape = resShape;
this._size = resSize;
return this;
}.kwargs(),
append : function() {
console.warn('TODO');
}.kwargs(),
/**
* Delete values along the axis
* @param {Array|Number} obj
* @param {Number} [axis]
* @return {NDArray} this
*/
'delete' : function(obj, axis) {
var data = this._array;
if (typeof(obj) === 'number') {
obj = [obj];
}
var size = this._size;
if (typeof(axis) === 'undefined') {
this._shape = [size];
axis = 0;
}
var stride = calculateDimStride(this._shape, axis);
var axisSize = this._shape[axis];
var offsetStride = stride * axisSize;
var cursor = 0;
for (var offset = 0; offset < size; offset += offsetStride) {
var start = 0;
var end = obj[0];
var objCursor = 0;
while(objCursor < obj.length) {
if (end < 0) {
end = end + axisSize;
}
if (end > axisSize) {
throw new Error(indexOutofBoundsErrorMsg(end));
}
if (end < start) {
throw new Error('Index must be in ascending order');
}
for (var i = start; i < end; i++) {
for (var j = 0; j < stride; j++) {
data[cursor++] = data[i * stride + j + offset];
}
}
start = end + 1;
end = obj[++objCursor];
}
// Copy the rest
for (var i = start; i < axisSize; i++) {
for (var j = 0; j < stride; j++) {
data[cursor++] = data[i * stride + j + offset];
}
}
}
this._shape[axis] -= obj.length;
this._size = getSize(this._shape);
return this;
}.kwargs(),
_parseRanges : function(index) {
var rangesStr = index.split(/\s*,\s*/);
// Parse range of each axis
var ranges = [];
var shape = [];
var j = 0;
for (var i = 0; i < rangesStr.length; i++) {
if (rangesStr[i] === '...') {
var end = this._shape.length - (rangesStr.length - i);
while (j <= end) {
ranges.push([0, this._shape[j], 1]);
shape.push(this._shape[j]);
j++;
}
} else {
var range = parseRange(rangesStr[i], this._shape[j]);
ranges.push(range);
if(rangesStr[i].indexOf(':') >= 0) {
var size = Math.floor((range[1] - range[0]) / range[2]);
size = size < 0 ? 0 : size;
// Get a range not a item
shape.push(size);
}
j++;
}
}
// Copy the lower dimension size
for (; j < this._shape.length; j++) {
shape.push(this._shape[j]);
}
return [ranges, shape];
},
/**
* Export normal js array
* @return {Array}
*/
toArray : function() {
var data = this._array;
var cursor = 0;
var shape = this._shape;
var dim = shape.length;
function create(axis, out) {
var len = shape[axis];
for (var i = 0; i < len; i++) {
if (axis < dim-1) {
create(axis+1, out[i] = []);
} else {
out[i] = data[cursor++];
}
}
}
var output = [];
create(0, output);
return output;
},
/**
* Create a copy of self
* @return {NDArray}
*/
copy : function() {
var numArr = new NDArray();
numArr._array = ArraySlice.call(this._array);
numArr._shape = this._shape.slice();
numArr._dtype = this._dtype;
numArr._size = this._size;
return numArr;
},
constructor : NDArray
};
/**
*
* @param {Number} [min=0]
* @param {Number} max
* @param {Number} [step=1]
* @param {string} [dtype]
* @return {NDArray}
*/
NDArray.range = function(min, max, step, dtype) {
var args = ArraySlice.call(arguments);
// Last argument describe the data type of ndarray
var lastArg = args[args.length-1];
if (typeof(lastArg) == 'string') {
var dtype = lastArg;
args.pop();
}
if (args.length === 1) {
max = args[0];
step = 1;
min = 0;
} else if(args.length == 2) {
step = 1;
}
dtype = dtype || 'number';
var array = new ArrayConstructor[dtype](Math.ceil((max - min)/step));
var cursor = 0;
for (var i = min; i < max; i+=step) {
array[cursor++] = i;
}
var ndarray = new NDArray();
ndarray._array = array;
ndarray._shape = [array.length];
ndarray._dtype = dtype;
ndarray._size = array.length;
return ndarray;
}.kwargs();
/**
*
* @param {Array} shape
* @param {String} [dtype]
* @return {NDArray}
*/
NDArray.zeros = function(shape, dtype) {
var ret = new NDArray(dtype);
ret.initFromShape(shape);
return ret;
}.kwargs();
/**
* Python like array indexing
* http://www.python.org/dev/peps/pep-0204/
*
* @param {string} index
* index can be a simple integer 1,2,3,
* or a range 2:10, 2:10:1
* example :
* 2:10 => [2, 10, 1],
* 10:2:-2 => [10, 2, -2],
* : => [0, dimSize, 1],
* ::-1 => [dimSize-1, -1, -1],
* @param {number} dimSize
* @return {Array} a tuple array [startOffset, endOffset, sliceStep]
*/
function parseRange(index, dimSize) {
if (index.indexOf(':') >= 0) {
// Range indexing;
var res = index.split(/\s*:\s*/);
var step = parseInt(res[2] || 1, 10);
var start, end;
if (step === 0) {
throw new Error('Slice step cannot be zero');
}
else if (step > 0) {
start = parseInt(res[0] || 0, 10);
end = parseInt(res[1] || dimSize, 10);
}
else {
start = parseInt(res[0] || dimSize - 1, 10);
end = parseInt(res[1] || -1, 10);
}
// Negtive offset
if (start < 0) {
start = dimSize + start;
}
// Negtive offset
if (end < 0 && res[1]) {
end = dimSize + end;
}
if (step > 0) {
// Clamp to [0-dimSize]
start = Math.max(Math.min(dimSize, start), 0);
// Clamp to [0-dimSize]
end = Math.max(Math.min(dimSize, end), 0);
} else {
// Clamp to [0-dimSize)
start = Math.max(Math.min(dimSize-1, start), -1);
// Clamp to [0-dimSize)
end = Math.max(Math.min(dimSize-1, end), -1);
}
return [start, end, step];
} else {
var start = parseInt(index, 10);
// Negtive offset
if (start < 0) {
start = dimSize + start;
}
if (start < 0 || start > dimSize) {
throw new Error(indexOutofBoundsErrorMsg(index));
}
// Clamp to [0-dimSize)
start = Math.max(Math.min(dimSize-1, start), 0);
return [start, start+1, 1];
}
}
function getSize(shape) {
var size = shape[0];
for (var i = 1; i < shape.length; i++) {
size *= shape[i];
}
return size;
}
function getDimension(array) {
var dim = 1;
var el = array[0];
while (el instanceof Array) {
el = el[0];
dim ++;
}
return dim;
}
function getShape(array) {
var shape = [array.length];
var el = array[0];
while (el instanceof Array) {
shape.push(el.length);
el = el[0];
}
return shape;
}
function calculateDimStride(shape, axis) {
if (axis == shape.length-1) {
return 1;
}
var stride = shape[axis+1];
for (var i = axis+2; i < shape.length; i++) {
stride *= shape[i];
}
return stride;
}
function calculateDimStrides(shape) {
// Calculate stride of each axis
var strides = [];
var tmp = 1;
var len = getSize(shape);
for (var i = 0; i < shape.length; i++) {
tmp *= shape[i];
strides.push(len / tmp);
}
return strides;
}
function arrayEqual(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (var i = 0; i <arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
function broadcastErrorMsg(shape1, shape2) {
return 'Shape ('
+ shape1.toString() + ') (' + shape2.toString()
+') could not be broadcast together';
}
function axisOutofBoundsErrorMsg(axis) {
return 'Axis ' + axis + ' out of bounds';
}
function indexOutofBoundsErrorMsg(idx) {
return 'Index ' + idx + ' out of bounds';
}
return NDArray;
});
|
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.core.mvc.View.
sap.ui.define(['jquery.sap.global', 'sap/ui/base/ManagedObject', 'sap/ui/core/Control', 'sap/ui/core/ExtensionPoint', 'sap/ui/core/library'],
function(jQuery, ManagedObject, Control, ExtensionPoint, library) {
"use strict";
/**
* @namespace
* @name sap.ui.core.mvc
* @public
*/
/**
* Constructor for a new View.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class A base class for Views.
*
* Introduces the relationship to a Controller, some basic visual appearance settings like width and height
* and provides lifecycle events.
*
* @extends sap.ui.core.Control
* @version 1.26.8
*
* @constructor
* @public
* @alias sap.ui.core.mvc.View
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var View = Control.extend("sap.ui.core.mvc.View", /** @lends sap.ui.core.mvc.View.prototype */ { metadata : {
library : "sap.ui.core",
properties : {
/**
* The width
*/
width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : '100%'},
/**
* The height
*/
height : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},
/**
* Name of the View
*/
viewName : {type : "string", group : "Misc", defaultValue : null},
/**
* Whether the CSS display should be set to "block".
* Set this to "true" if the default display "inline-block" causes a vertical scrollbar with Views that are set to 100% height.
* Do not set this to "true" if you want to display other content in the same HTML parent on either side of the View (setting to "true" may push that other content to the next/previous line).
*/
displayBlock : {type : "boolean", group : "Appearance", defaultValue : false}
},
aggregations : {
/**
* Child Controls of the view
*/
content : {type : "sap.ui.core.Control", multiple : true, singularName : "content"}
},
events : {
/**
* Fired when the View has parsed the UI description and instantiated the contained controls (/control tree).
*/
afterInit : {},
/**
* Fired when the view has received the request to destroy itself, but before it has destroyed anything.
*/
beforeExit : {},
/**
* Fired when the View has been (re-)rendered and its HTML is present in the DOM.
*/
afterRendering : {},
/**
* Fired before this View is re-rendered. Use to unbind event handlers from HTML elements etc.
*/
beforeRendering : {}
}
}});
/**
* initialize the View and connect (create if no instance is given) the Controller
*
* @private
*/
View.prototype._initCompositeSupport = function(mSettings) {
// init View with constructor settings
// (e.g. parse XML or identify default controller)
// make user specific data available during view instantiation
this.oViewData = mSettings.viewData;
// remember the name of this View
this.sViewName = mSettings.viewName;
//check if there are custom properties configured for this view, and only if there are, create a settings preprocessor applying these
if (sap.ui.core.CustomizingConfiguration && sap.ui.core.CustomizingConfiguration.hasCustomProperties(this.sViewName, this)) {
var that = this;
this._fnSettingsPreprocessor = function(mSettings) {
var sId = this.getId();
if (sap.ui.core.CustomizingConfiguration && sId) {
if (that.isPrefixedId(sId)) {
sId = sId.substring((that.getId() + "--").length);
}
var mCustomSettings = sap.ui.core.CustomizingConfiguration.getCustomProperties(that.sViewName, sId, that);
if (mCustomSettings) {
mSettings = jQuery.extend(mSettings, mCustomSettings); // override original property initialization with customized property values
}
}
};
}
if (this.initViewSettings) {
this.initViewSettings(mSettings);
}
createAndConnectController(this, mSettings);
// the controller is connected now => notify the view implementations
if (this.onControllerConnected) {
this.onControllerConnected(this.oController);
}
// notifies the listeners that the View is initialized
this.fireAfterInit();
};
/**
* Returns the view's Controller instance or null for a controller-less View.
*
* @return {object} Controller of this view.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
View.prototype.getController = function() {
return this.oController;
};
/**
* Returns an Element by its id in the context of the View.
*
* @param {string} sId view local Id of the Element
* @return {sap.ui.core.Element} Element by its id or undefined
* @public
*/
View.prototype.byId = function(sId) {
return sap.ui.getCore().byId(this.createId(sId));
};
/**
* Convert the given view local Element id to a globally unique id
* by prefixing it with the view Id.
*
* @param {string} sId view local Id of the Element
* @return {string} prefixed id
* @public
*/
View.prototype.createId = function(sId) {
if (!this.isPrefixedId(sId)) {
// views have 2 dashes as separator, components 3 and controls/elements 1
sId = this.getId() + "--" + sId;
}
return sId;
};
/**
* Checks whether the given ID is already prefixed with this View's ID
*
* @param {string} potentially prefixed id
* @return {boolean} whether the ID is already prefixed
*/
View.prototype.isPrefixedId = function(sId) {
return !!(sId && sId.indexOf(this.getId() + "--") === 0);
};
/**
* Creates and connects the controller if the controller is not given in the
* mSettings
*
* @private
*/
function createAndConnectController(oThis, mSettings) {
if (!sap.ui.getCore().getConfiguration().getControllerCodeDeactivated()) {
// only set when used internally
var oController = mSettings.controller;
if (!oController && oThis.getControllerName) {
// get optional default controller name
var defaultController = oThis.getControllerName();
if (defaultController) {
// create controller
oController = sap.ui.controller(defaultController);
}
}
if ( oController ) {
oThis.oController = oController;
// connect controller
oController.connectToView(oThis);
}
} else {
oThis.oController = {};
}
}
/**
* Returns user specific data object
*
* @return object viewData
* @public
*/
View.prototype.getViewData = function(){
return this.oViewData;
};
/**
* exit hook
*
* @private
*/
View.prototype.exit = function() {
this.fireBeforeExit();
this.oController = null;
};
/**
* onAfterRendering hook
*
* @private
*/
View.prototype.onAfterRendering = function() {
this.fireAfterRendering();
};
/**
* onBeforeRendering hook
*
* @private
*/
View.prototype.onBeforeRendering = function() {
this.fireBeforeRendering();
};
/**
* Override clone method to avoid conflict between generic cloning of content
* and content creation as defined by the UI5 Model View Controller lifecycle.
*
* For more details see the development guide section about Model View Controller in UI5.
*
* @param {string} [sIdSuffix] a suffix to be appended to the cloned element id
* @param {string[]} [aLocalIds] an array of local IDs within the cloned hierarchy (internally used)
* @return {sap.ui.core.Element} reference to the newly created clone
* @protected
*/
View.prototype.clone = function(sIdSuffix, aLocalIds) {
var mSettings = {}, sKey, oClone;
//Clone properties (only those with non-default value)
for (sKey in this.mProperties && !(this.isBound && this.isBound(sKey))) {
if ( this.mProperties.hasOwnProperty(sKey) ) {
mSettings[sKey] = this.mProperties[sKey];
}
}
oClone = Control.prototype.clone.call(this, sIdSuffix, aLocalIds, {cloneChildren:false, cloneBindings: true});
oClone.applySettings(mSettings);
return oClone;
};
/**
* An (optional) method to be implemented by Views.
* When no controller instance is given at View instantiation time AND this method exists and returns the (package and class) name of a controller,
* the View tries to load and instantiate the controller and to connect it to itself.
*
* @return {string} the name of the controller
* @public
* @name sap.ui.core.mvc.View#getControllerName
* @function
*/
/**
* Creates a view of the given type, name and with the given id.
*
* The <code>oView</code> configuration object can have the following properties for the view
* instantiation:
* <ul>
* <li>The ID <code>oView.id</code> specifies an ID for the View instance. If no ID is given,
* an ID will be generated.</li>
* <li>The view name <code>oView.viewName</code> corresponds to an XML module that can be loaded
* via the module system (oView.viewName + suffix ".view.xml")</li>
* <li>The controller instance <code>oView.controller</code> must be a valid controller implementation.
* The given controller instance overrides the controller defined in the view definition</li>
* <li>The view type <code>oView.type</code> specifies what kind of view will be instantiated. All valid
* view types are listed in the enumeration sap.ui.core.mvc.ViewType.</li>
* <li>The view data <code>oView.viewData</code> can hold user specific data. This data is available
* during the whole lifecycle of the view and the controller</li>
* </ul>
*
* @param {string} sId id of the newly created view, only allowed for instance creation
* @param {object} [vView] the view configuration object
* @public
* @static
* @return {sap.ui.core.mvc.View} the created View instance
*/
sap.ui.view = function(sId, vView, sType /* used by factory functions */) {
var view = null, oView = {};
// if the id is a configuration object or a string
// and the vView is not defined we shift the parameters
if (typeof sId === "object" ||
typeof sId === "string" && vView === undefined) {
vView = sId;
sId = undefined;
}
// prepare the parameters
if (vView) {
if (typeof vView === "string") {
oView.viewName = vView;
} else {
oView = vView;
}
}
// apply the id if defined
if (sId) {
oView.id = sId;
}
// apply the type defined in specialized factory functions
if (sType) {
oView.type = sType;
}
// view replacement
if (sap.ui.core.CustomizingConfiguration) {
var customViewConfig = sap.ui.core.CustomizingConfiguration.getViewReplacement(oView.viewName, ManagedObject._sOwnerId);
if (customViewConfig) {
jQuery.sap.log.info("Customizing: View replacement for view '" + oView.viewName + "' found and applied: " + customViewConfig.viewName + " (type: " + customViewConfig.type + ")");
jQuery.extend(oView, customViewConfig);
} else {
jQuery.sap.log.debug("Customizing: no View replacement found for view '" + oView.viewName + "'.");
}
}
// view creation
if (!oView.type) {
throw new Error("No view type specified.");
} else if (oView.type === sap.ui.core.mvc.ViewType.JS) {
view = new sap.ui.core.mvc.JSView(oView);
} else if (oView.type === sap.ui.core.mvc.ViewType.JSON) {
view = new sap.ui.core.mvc.JSONView(oView);
} else if (oView.type === sap.ui.core.mvc.ViewType.XML) {
view = new sap.ui.core.mvc.XMLView(oView);
} else if (oView.type === sap.ui.core.mvc.ViewType.HTML) {
view = new sap.ui.core.mvc.HTMLView(oView);
} else if (oView.type === sap.ui.core.mvc.ViewType.Template) {
view = new sap.ui.core.mvc.TemplateView(oView);
} else { // unknown view type
throw new Error("Unknown view type " + oView.type + " specified.");
}
return view;
};
/**
* Helper method to resolve an event handler either locally (from a controller) or globally.
*
* Which contexts are checked for the event handler depends on the syntax of the name:
* <ul>
* <li><i>relative</i>: names starting with a dot ('.') must specify a handler in
* the controller (example: <code>".myLocalHandler"</code>)</li>
* <li><i>absolute</i>: names that contain, but do not start with a dot ('.') are
* always assumed to mean a global handler function. {@link jQuery.sap.getObject}
* will be used to retrieve the function (example: <code>"some.global.handler"</code> )</li>
* <li><i>legacy</i>: Names that contain no dot at all are first interpreted as a relative name
* and then - if nothing is found - as an absolute name. This variant is only supported
* for backward compatibility (example: <code>"myHandler"</code>)</li>
* </ul>
*
* The returned settings will always use the given <code>oController</code> as context object ('this')
* This should allow the implementation of generic global handlers that might need an easy back link
* to the controller/view in which they are currently used (e.g. to call createId/byId). It also makes
* the development of global event handlers more consistent with controller local event handlers.
*
* <strong>Note</strong>: It is not mandatory but improves readability of declarative views when
* legacy names are converted to relative names where appropriate.
*
* @param {string} sName the name to resolve
* @param {sap.ui.core.mvc.Controller} oController the controller to use as context
* @return {any[]} an array with function and context object, suitable for applySettings.
* @private
*/
View._resolveEventHandler = function(sName, oController) {
var fnHandler;
if (!sap.ui.getCore().getConfiguration().getControllerCodeDeactivated()) {
switch (sName.indexOf('.')) {
case 0:
// starts with a dot, must be a controller local handler
fnHandler = oController && oController[sName.slice(1)];
break;
case -1:
// no dot at all: first check for a controller local, then for a global handler
fnHandler = oController && oController[sName];
if ( fnHandler != null ) {
// if the name can be resolved, don't try to find a global handler (even if it is not a function)
break;
}
// falls through
default:
fnHandler = jQuery.sap.getObject(sName);
}
} else {
// When design mode is enabled, controller code is not loaded. That is why we stub the handler functions.
fnHandler = function() {};
}
if ( typeof fnHandler === "function" ) {
// the handler name is set as property on the function to keep this information
// e.g. for serializers which convert a control tree back to a declarative format
fnHandler._sapui_handlerName = sName;
// always attach the handler with the controller as context ('this')
return [ fnHandler, oController ];
}
// return undefined
};
return View;
}, /* bExport= */ true);
|
'use strict';
angular.module('answers').controller('AnswersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Answers',
function($scope, $stateParams, $location, Authentication, Answers) {
$scope.authentication = Authentication;
$scope.create = function() {
var answer = new Answers({
title: this.title,
content: this.content
});
answer.$save(function(response) {
$location.path('answers/' + response._id);
$scope.title = '';
$scope.content = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.remove = function(answer) {
if (answer) {
answer.$remove();
for (var i in $scope.answers) {
if ($scope.answers[i] === answer) {
$scope.answers.splice(i, 1);
}
}
} else {
$scope.answer.$remove(function() {
$location.path('answers');
});
}
};
$scope.update = function() {
var answer = $scope.answer;
answer.$update(function() {
$location.path('answers/' + answer._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.answers = Answers.query();
};
$scope.findOne = function() {
$scope.answer = Answers.get({
answerId: $stateParams.answerId
});
};
}
]); |
/*
* @package Cyprass
* @subpackage Cyprass HTML
*
* Template Scripts
* Created by Themeturn
1. Fixed header
2. Site search
3. Main slideshow
4. Owl Carousel
a. Testimonial
b. Clients
c. Team
5. Back to top
6. Skills
7. BX slider
a. Blog Slider
b. Portfolio item slider
8. Isotope
9. Animation (wow)
10. Flickr
*/
jQuery(function($) {
"use strict";
$.noConflict();
$('.nav a').on('click', function(){
if($('.navbar-toggle').css('display') !='none'){
$(".navbar-toggle").trigger( "click" );
}
});
// Navigation scrolling
$('a.page-scroll').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 40
}, 900);
return false;
}
}
});
// accordian
$('.accordion-toggle').on('click', function(){
$(this).closest('.panel-group').children().each(function(){
$(this).find('>.panel-heading').removeClass('active');
});
$(this).closest('.panel-heading').toggleClass('active');
});
/* ----------------------------------------------------------- */
/* BX slider
/* ----------------------------------------------------------- */
//Portfolio item and blog slider
/*Smooth Scroll*/
smoothScroll.init({
speed: 400,
easing: 'easeInQuad',
offset:0,
updateURL: true,
callbackBefore: function ( toggle, anchor ) {},
callbackAfter: function ( toggle, anchor ) {}
});
/* ----------------------------------------------------------- */
/* Main slideshow
/* ----------------------------------------------------------- */
$('#slider_part').carousel({
pause: true,
interval: 100000,
});
/* ----------------------------------------------------------- */
/*ISotope Portfolio
/* ----------------------------------------------------------- */
var $container = $('.portfolio-wrap');
var $filter = $('#isotope-filter');
// Initialize isotope
$container.isotope({
filter: '*',
layoutMode: 'fitRows',
animationOptions: {
duration: 750,
easing: 'linear'
}
});
// Filter items when filter link is clicked
$filter.find('a').click(function () {
var selector = $(this).attr('data-filter');
$filter.find('a').removeClass('current');
$(this).addClass('current');
$container.isotope({
filter: selector,
animationOptions: {
animationDuration: 750,
easing: 'linear',
queue: false,
}
});
return false;
});
// Portfolio Isotope
var container = $('.portfolio-wrap');
function splitColumns() {
var winWidth = $(window).width(),
columnNumb = 1;
if (winWidth > 1024) {
columnNumb = 4;
} else if (winWidth > 900) {
columnNumb = 2;
} else if (winWidth > 479) {
columnNumb = 2;
} else if (winWidth < 479) {
columnNumb = 1;
}
return columnNumb;
}
function setColumns() {
var winWidth = $(window).width(),
columnNumb = splitColumns(),
postWidth = Math.floor(winWidth / columnNumb);
container.find('.portfolio-box').each(function () {
$(this).css( {
width : postWidth + 'px'
});
});
}
function setProjects() {
setColumns();
container.isotope('reLayout');
}
container.imagesLoaded(function () {
setColumns();
});
$(window).bind('resize', function () {
setProjects();
});
/* ----------------------------------------------------------- */
/* Team Carousel
/* ----------------------------------------------------------- */
$("#owl-demo").owlCarousel({
navigation : true, // Show next and prev buttons
// navigationText: ["prev","next"],
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
slideSpeed : 300,
paginationSpeed : 400,
autoPlay: true,
items : 4,
itemsDesktop:[1199,4],
itemsDesktopSmall:[979,3], //As above.
itemsTablet:[768,3], //As above.
// itemsTablet:[640,2],
itemsMobile:[479,1], //As above
goToFirst: true, //Slide to first item if autoPlay reach end
goToFirstSpeed:1000
});
//Testimonial
$("#testimonial-carousel").owlCarousel({
navigation : true, // Show next and prev buttons
slideSpeed : 600,
pagination:false,
singleItem:true
});
// Custom Navigation Events
var owl = $("#testimonial-carousel");
// Custom Navigation Events
$(".next").click(function(){
owl.trigger('owl.next');
})
$(".prev").click(function(){
owl.trigger('owl.prev');
})
$(".play").click(function(){
owl.trigger('owl.play',1000); //owl.play event accept autoPlay speed as second parameter
})
$(".stop").click(function(){
owl.trigger('owl.stop');
})
//Clients
//
$("#client-carousel").owlCarousel({
navigation : true, // Show next and prev buttons
navigationText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
slideSpeed : 400,
pagination:false,
items : 5,
rewindNav: true,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3],
itemsTablet:[768,3], //As above.
// itemsMobile:[479,2],
itemsMobile:[320,1],
stopOnHover:true,
autoPlay:true
});
/* ----------------------------------------------------------- */
/* Team Carousel
/* ----------------------------------------------------------- */
$("#owl-blog").owlCarousel({
autoPlay: true,
items : 4,
itemsDesktop:[1199,4],
itemsDesktopSmall:[979,3], //As above.
itemsTablet:[768,2], //As above.
itemsMobile:[479,1], //As above
goToFirst: true, //Slide to first item if autoPlay reach end
goToFirstSpeed:1000,
});
//Counter
// jQuery(document).ready(function( $ ) {
$('.counter').counterUp({
delay: 100,
time: 2000
});
// });
// prettyphoto
$("a[data-rel^='prettyPhoto']").prettyPhoto();
/* ==============================================
Back To Top Button
=============================================== */
$(window).scroll(function () {
if ($(this).scrollTop() > 50) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});
// scroll body to 0px on click
$('#back-top').click(function () {
$('#back-top a').tooltip('hide');
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
$('#back-top').tooltip('hide');
}); |
"use strict";
const yaml = require("js-yaml");
const _ = require("lodash");
const fs = require("fs");
const path = require("path");
const logger = require("log4js").getLogger("translations");
const utils = require("./utils");
const parseYaml = (file) => {
try {
return yaml.safeLoad(file.contents);
} catch (e) {
if (e.name === "YAMLException") {
throw new Error(`Error parsing ${file.path}: [${e.mark.line}:${e.mark.column}] ${e.reason}`);
} else {
throw e;
}
}
};
const mapLeaves = (obj, iteratee, path) => {
path = path || [];
return _.flatMap(obj, (value, key) => {
if (_.isObject(value)) {
return mapLeaves(value, iteratee, path.concat(key));
} else {
return iteratee(value, path.concat(key));
}
})
};
const setValueAt = (obj, path, value) => {
const next = path.shift();
if (path.length === 0) {
obj[next] = value;
} else {
obj[next] = obj[next] || {};
setValueAt(obj[next], path, value);
}
};
const statistics = (opts) =>
partials => {
const translations = _.flatMap(partials, partial =>
mapLeaves(partial.translations, (value, path) =>
({value, key: path.join("."), file: partial.path, lang: _.last(path)})));
const duplicatedValues = _.chain(translations)
.filter(translation => _.filter(translations, t => translation.value === t.value && translation.lang === t.lang).length > 1)
.groupBy("value")
.value();
let duplicatedKeys = _.filter(translations, translation =>
_.filter(translations, t => translation.key === t.key).length > 1);
const conflictingKeys = _.chain(duplicatedKeys)
.filter(translation => _.some(duplicatedKeys, t => translation.key === t.key && translation.value !== t.value))
.groupBy("key")
.value();
duplicatedKeys = _.groupBy(duplicatedKeys, "key");
const maxFileNameLength = _.maxBy(translations, t => t.file.length).file.length;
if (_.size(conflictingKeys) > 0) {
_.each(conflictingKeys, (translations, key) => {
logger.error(`Conflict for "${key}":`);
_.each(translations, t => {
logger.error(`${_.padEnd(`${t.file} `, maxFileNameLength + 2, "-")}> ${t.value}`)
});
});
return Promise.reject(new Error(`Translation failed: Conflicting translations.`));
}
if (opts.verbose) {
_.each(duplicatedValues, (translations, value) => {
logger.debug(`Duplicated value for "${value}":`);
_.each(translations, t => {
logger.debug(`${_.padEnd(`${t.file} `, maxFileNameLength + 2, "-")}> ${t.key}`)
});
});
}
const duplicatedValuesPercent = _.size(duplicatedValues) / translations.length * 100;
if (!_.isUndefined(opts.duplicateThreshold)) {
if (duplicatedValuesPercent > opts.duplicateThreshold) {
return Promise.reject(new Error(`Translation failed: Too may duplicates: ${_.size(duplicatedValues)} (${(duplicatedValuesPercent).toFixed(1)}%)`))
}
}
logger.debug(`Translation duplicates: ${_.size(duplicatedValues)} (${(duplicatedValuesPercent).toFixed(1)}%)`);
return partials;
};
const byLanguage = translations => {
const result = {};
mapLeaves(translations, (value, path) => {
setValueAt(result, [path.pop()].concat(path), value);
});
return result;
};
exports.compile = (src, dest, opts) =>
utils.getFiles(src)
.then(paths => Promise.all(paths.map(path =>
utils.readFile(path).then(contents => ({contents, path})))))
.then(files => Promise.all(files.map(file =>
({path: file.path, translations: parseYaml(file)}))))
.then(statistics(_.pick(opts, "verbose", "duplicateThreshold")))
.then(partials => _.defaultsDeep.apply(_, _.map(partials, "translations")))
.then(byLanguage)
.then(translations => `export default ${JSON.stringify(translations, null, 4)};`)
.then(content => utils.writeFile(dest, content)); |
'use strict';
var getInstalled = require('../../../lib/component/getInstalled');
describe('component getInstalled', function () {
it('should get installed components', function (done) {
getInstalled()
.then(function (installed) {
var installedList = installed.map(function (component) {
return component.name + '@' + component.version;
}).sort();
expect(installedList).toEqual(['[email protected]', '[email protected]', '[email protected]', '[email protected]']);
done();
});
});
}); |
(function(h,x){"object"===typeof module&&module.exports?module.exports=x(require("jquery")):x(h.jQuery)})(this,function(h){function x(a,c,d){a=h(a);(c=c||a.data("title"))||(c=a.attr("title"));if(c){var b=h('<div class="ssi-fadeOut ssi-fade ssi-tooltipText">'+c+"</div>").appendTo(d.$element);a.one("mouseleave",function(){b.remove()});c=-16;a.hasClass("ssi-noPreviewSubMessage")&&(c=23);b.css({top:a.position().top-b.height()+c,left:a.position().left-b.width()/2}).removeClass("ssi-fadeOut");return b}}
var l=function(a,c){this.options=c;this.$element="";this.language=H[this.options.locale];this.uploadList=[];this.totalProgress=[];this.toUpload=[];this.imgNames=[];this.currentListLength=this.inProgress=this.pending=this.abortedWithError=this.aborted=this.successfulUpload=this.totalFilesLength=0;this.inputName="";this.init(a)};l.prototype.init=function(a){h(a).addClass("ssi-uploadInput").after(this.$element=h('<div class="ssi-uploader">'));a=h('<span class="ssi-InputLabel"><button class="ssi-button success">'+
this.language.chooseFiles+"</button></span>").append(a);var c=h('<button id="ssi-uploadBtn" class="ssi-button success ssi-hidden" ><span class="ssi-btnIn">'+this.language.upload+' </span><div id="ssi-up_loading" class="ssi-btnIn"></div></button>'),d=h('<button id="ssi-clearBtn" class="ssi-hidden ssi-button info" >'+this.language.clear+"</button>"),b=h('<button id="ssi-abortBtn" class="ssi-button error ssi-cancelAll ssi-hidden" ><span class="inBtn">'+this.language.abort+" </span></button>");this.options.inForm&&
c.hide();this.$element.append(h('<div class="ssi-buttonWrapper">').append(a,b,c,d));if(this.options.preview){var f=h('<div id="ssi-previewBox" class="ssi-uploadBox ssi-previewBox '+(this.options.dropZone?"ssi-dropZonePreview ssi-dropZone":"")+'"><div id="ssi-info">'+(this.options.dropZone?'<div id="ssi-DropZoneBack">'+this.language.drag+"</div>":"")+'<div id="ssi-fileNumber" class="ssi-hidden">?</div></div></div>');this.$element.append(f)}else{this.$element.addClass("ssi-uploaderNP");var n=h('<table id="ssi-fileList" class="ssi-fileList"></table>'),
g=h('<span class="ssi-namePreview"></span>'),m=h('<div id="ssi-uploadFiles" class="ssi-tooltip ssi-uploadFiles '+(this.options.dropZone?"ssi-dropZone":"")+'"><div id="ssi-uploadProgressNoPreview" class="ssi-uploadProgressNoPreview"></div></div>').append(g),z=h('<div class="ssi-uploadDetails"></div>').append(n);f=h('<div class="ssi-uploadBoxWrapper ssi-uploadBox"></div>').append(m,z);this.$element.prepend(f)}var e=this,p=a.find(".ssi-uploadInput");this.inputName=p.attr("name")||"files";a.find("button").click(function(a){a.preventDefault();
p.trigger("click")});p.on("change",function(){e.toUploadFiles(this.files);e.options.inForm||p.val("")});e.options.dropZone&&(f.on("drop",function(a){a.preventDefault();f.removeClass("ssi-dragOver");e.toUploadFiles(a.originalEvent.dataTransfer.files)}),f.on("dragover",function(a){a.preventDefault();f.addClass("ssi-dragOver");return!1}),f.on("dragleave",function(a){a.preventDefault();f.removeClass("ssi-dragOver");return!1}));e.options.preview||m.click(function(){1<e.currentListLength&&z.toggleClass("ssi-uploadBoxOpened")});
d.click(function(a){a.preventDefault();e.clear()});f.on("mouseenter",".ssi-statusLabel",function(a){a=h(a.currentTarget);var b=a.attr("data-status");b&&""!==b&&x(a,b,e)});f.on("mouseenter","#ssi-fileNumber",function(a){a=h(a.currentTarget);x(a," "+e.language.pending+": "+e.pending+" <br> "+e.language.completed+": "+(e.successfulUpload+e.aborted+e.abortedWithError)+"<br> "+e.language.inProgress+": "+e.inProgress,e)});f.on("click",".ssi-removeBtn",function(a){a.preventDefault();var b=h(a.currentTarget);
a=b.data("delete");e.pending--;e.currentListLength--;1>e.pending&&e.$element.find("#ssi-fileNumber").addClass("ssi-hidden");0===e.pending&&c.prop("disabled",!0);e.options.preview?b.parents("table.ssi-imgToUploadTable").remove():(b=b.parents("tr.ssi-toUploadTr"),g.html(e.currentListLength+" files"),b.prev().remove(),b.remove(),1===e.currentListLength&&C(e));e.toUpload[a]=null;e.imgNames[a]=null;0===e.currentListLength&&(e.options.dropZone||f.removeClass("ssi-uploadNoDropZone"),d.addClass("ssi-hidden"),
c.addClass("ssi-hidden"))});f.on("click",".ssi-abortUpload",function(a){a.preventDefault();a=h(a.currentTarget).data("delete");e.abort(a)});c.click(function(a){a.preventDefault();e.uploadFiles()});b.click(function(a){a.preventDefault();e.abortAll()})};l.prototype.abortAll=function(){for(var a=0;a<this.uploadList.length;a++)"object"===typeof this.uploadList[a]&&this.abort(a)};l.prototype.toUploadFiles=function(a){function c(){var a=d.imgNames.length;0===a&&(d.options.preview&&(d.options.dropZone||
e.addClass("ssi-uploadNoDropZone")),g.removeClass("ssi-hidden"),m.removeClass("ssi-hidden"));m.prop("disabled",!0);d.toUpload[a]=k;var c=k.name,f=c.getExtension();d.imgNames[a]=c;if(d.options.preview){var h=function(b){return'<table class="ssi-imgToUploadTable ssi-pending"><tr><td class="ssi-upImgTd">'+b+'</td></tr><tr><td><div id="ssi-uploadProgress'+a+'" class="ssi-hidden ssi-uploadProgress"></div></td></tr><tr><td><button data-delete="'+a+'" class=" ssi-button error ssi-removeBtn"><span class="trash10 trash"></span></button></td></tr><tr><td>'+
y(c,f,15)+"</td></tr></table>"};if("image"==k.type.split("/")[0]){g.prop("disabled",!0);m.prop("disabled",!0);var r=new FileReader;r.onload=function(){n+=h('<img class="ssi-imgToUpload" src=""/><i class="fa-spin fa fa-spinner fa-pulse"></i>');p[a]=r.result;b++;t===b?(d.$element.find("#ssi-fileNumber").removeClass("ssi-hidden"),e.append(n),setTimeout(function(){u();g.prop("disabled",!1);m.prop("disabled",!1)},10),g.prop("disabled",!1),m.prop("disabled",!1),n="",t=[]):t/2==Math.round(b)&&(e.append(n),
u(),n="")};r.readAsDataURL(k)}else p[a]=null,e.append(h('<div class="document-item" href="test.mov" filetype="'+f+'"><span class = "fileCorner"></span></div>')),b++}else m.prop("disabled",!1),d.$element.find(".ssi-namePreview").html(0===a?y(c,f,13):d.currentListLength+1+" "+d.language.files),z.append('<tr class="ssi-space"><td></td></tr><tr class="ssi-toUploadTr ssi-pending"><td><div id="ssi-uploadProgress'+a+'" class="ssi-hidden ssi-uploadProgress ssi-uploadProgressNoPre"></div><span>'+y(c,f,20)+
'</span></td><td><a data-delete="'+a+'" class="ssi-button ssi-removeBtn ssi-removeBtnNP"><span class="trash7 trash"></span></a></td></tr>');var u=function(){for(var a=0;a<p.length;a++)null!==p[a]&&(e.find("#ssi-uploadProgress"+a).parents("table.ssi-imgToUploadTable").find(".ssi-imgToUpload").attr("src",p[a]).next().remove(),p[a]=null);p=[]}}if(!("number"===typeof this.options.maxNumberOfFiles&&this.inProgress+this.pending>=this.options.maxNumberOfFiles)){var d=this,b=0,f,n="",g=this.$element.find("#ssi-uploadBtn"),
m=this.$element.find("#ssi-clearBtn"),z=this.$element.find("#ssi-fileList"),e=this.$element.find(".ssi-uploadBox"),p=[];0===this.inProgress&&0===this.pending&&this.clear();var u=[],r=[],v="",t,q=f=t=a.length;"number"===typeof this.options.maxNumberOfFiles&&q>this.options.maxNumberOfFiles-(this.inProgress+this.pending)&&(q=t=this.options.maxNumberOfFiles-(this.inProgress+this.pending));for(var l=0;l<q;l++){var k=a[l],w=k.name.getExtension();-1===h.inArray(w,this.options.allowed)?(f>q?q++:t--,-1===
h.inArray(w,u)&&u.push(w)):(k.size*Math.pow(10,-6)).toFixed(2)>this.options.maxFileSize?(f>q?q++:t--,r.push(y(k.name,w,15))):this.options.allowDuplicates||-1===h.inArray(k.name,this.imgNames)?(g.prop("disabled",!1),c(k),this.pending++,this.currentListLength++):f>q?q++:t--}a=u.length;f=r.length;0<a+f&&(0<a&&(v=this.language.extError.replaceText(u.toString().replace(/,/g,", "))),0<f&&(v+=this.language.sizeError.replaceText(r.toString().replace(/,/g,", "),this.options.maxFileSize+"mb")),this.options.errorHandler.method(v,
this.options.errorHandler.error))}};var D=function(a){var c=a.$element.find(".ssi-completed");a.successfulUpload=0;a.aborted=0;a.abortedWithError=0;a.options.preview||c.prev("tr").remove();c.remove()},E=function(a){for(var c=a.$element.find(".ssi-pending"),d=a.imgNames.length,b=0;b<d;b++)null===a.imgNames[b]&&(a.toUpload.splice(b,1),a.imgNames.splice(b,1));a.toUpload.splice(-a.pending,a.pending);a.imgNames.splice(-a.pending,a.pending);a.pending=0;a.options.preview||c.prev("tr").remove();c.remove()};
l.prototype.clear=function(a){switch(a){case "pending":E(this);break;case "completed":D(this);break;default:E(this),D(this)}a=this.$element.find("#ssi-uploadBtn");var c=this.$element.find("#ssi-clearBtn");this.currentListLength=this.inProgress+this.successfulUpload+this.aborted+this.abortedWithError+this.pending;0===this.inProgress&&(this.totalProgress=[]);0===this.currentListLength&&(c.addClass("ssi-hidden"),a.addClass("ssi-hidden"),this.$element.find("#ssi-fileNumber").addClass("ssi-hidden"),this.totalFilesLength=
0,this.options.dropZone||this.$element.find(".ssi-uploadBox").removeClass("ssi-uploadNoDropZone"));c.prop("disabled",!0);a.prop("disabled",!0);this.options.preview||F(this)};var F=function(a){1<a.currentListLength?a.$element.find(".ssi-namePreview").html(a.currentListLength+" files"):1===a.currentListLength?C(a):(a.$element.find(".ssi-uploadDetails").removeClass("ssi-uploadBoxOpened"),a.$element.find("#ssi-fileList").empty(),a.$element.find(".ssi-namePreview").empty())};l.prototype.appendFileToFormData=
function(a){var c=new FormData;c.append(this.inputName,a);h.each(this.options.data,function(a,b){c.append(a,b)});return c};l.prototype.tryToTransform=function(a,c){if("function"===typeof this.options.transformFile)try{a=this.options.transformFile(a),a instanceof Promise?a.then(function(a){c(a)}):c(a)}catch(d){if(!this.options.ignoreCallbackErrors)return console.error("There is an error in transformFile"),console.error(d)}else c(a)};l.prototype.uploadFiles=function(){function a(n,g){var m="table.ssi-imgToUploadTable";
b.options.preview||(m="tr.ssi-toUploadTr");var l=b.$element.find("#ssi-uploadProgress"+g);l.removeClass("ssi-hidden").parents(m).removeClass("ssi-pending");m=h.extend({},{xhr:function(){var a=new window.XMLHttpRequest;a.upload.addEventListener("progress",function(a){if(a.lengthComputable){a=a.loaded/a.total*100;l&&l.css({width:a+"%"});b.totalProgress[g]=a;a=b.totalProgress;for(var e=0,d=0;d<a.length;d++)"number"===typeof a[d]&&(e+=a[d]);a=e/(b.inProgress+b.successfulUpload);b.options.preview||b.$element.find("#ssi-uploadProgressNoPreview").removeClass("ssi-hidden").css({width:a+
"%"});c.find("#ssi-up_loading").html(Math.ceil(a)+"%")}},!1);return a},async:!0,beforeSend:function(a,d){b.uploadList[g]=a;console.log("TCL: ajaxLoopRequest -> thisS.toUpload",b.toUpload);console.log("TCL: ajaxLoopRequest -> ii",g);c.find("#ssi-up_loading").html('<i class="fa fa-spinner fa-pulse"></i>');var e={name:b.toUpload[g].name,type:b.toUpload[g].type,size:(b.toUpload[g].size/1024).toFixed(2)};if("function"===typeof b.options.beforeEachUpload)try{var f=b.options.beforeEachUpload(e,a,d)}catch(v){"Error"==
v.name?b.abort(g,void 0,v.message):b.options.ignoreCallbackErrors||(console.log("There is an error in beforeEachUpload callback. Filename:"+b.toUpload[g].name),console.log(v),b.abort(g,void 0,b.language.wentWrong));return}b.$element.find("input.ssi-uploadInput").trigger("beforeEachUpload.ssi-uploader",[e]);0===a.status&&"canceled"===a.statusText&&("undefined"===typeof f&&(f=!1),b.abortedWithError++,b.abort(g,f))},type:"POST",method:"POST",data:n,cache:!1,contentType:!1,processData:!1,url:b.options.url,
error:function(a,c){if("abort"!==c){l.addClass("ssi-canceledProgressBar");var e=b.language.error;b.abortedWithError++;b.totalProgress.splice(g,1);b.options.preview||(e='<span class="exclamation7"></span>');A(b,g,"error",e,b.language.serverError);b.totalProgress[g]="";b.inProgress--;d.prop("disabled",!1);if("function"===typeof b.options.onEachUpload)try{b.options.onEachUpload({uploadStatus:"error",responseMsg:b.language.serverError,name:b.toUpload[g].name,size:(b.toUpload[g].size/1024).toFixed(2),
type:b.toUpload[g].type})}catch(r){b.options.ignoreCallbackErrors||(console.log("There is an error in onEachUpload callback. File name:"+b.toUpload[g].name),console.log(r))}0===b.inProgress&&B(b);console.log(arguments);console.log(" Ajax error: "+c)}}},b.options.ajaxOptions);h.ajax(m).done(function(a,c,f){function e(a,c){a?(q="success",n=b.language.success,p="check",b.successfulUpload++):(l.addClass("ssi-canceledProgressBar"),b.options.preview&&(n=b.language.error),b.abortedWithError++);m=c}var n,
m="",q="error",p="exclamation";try{var k=h.parseJSON(a)}catch(w){k=a}b.options.responseValidation?(a=b.options.responseValidation,"object"===typeof a.validationKey&&"validationKey"==a.resultKey?k.hasOwnProperty(a.validationKey.success)?e(!0,k[a.validationKey.success]):e(!1,k[a.validationKey.error]):k[a.validationKey]==a.success?e(!0,k[a.resultKey]):e(!1,k[a.resultKey])):200==f.status?e(!0,k):e(!1,k);b.options.preview||(n='<span class="'+p+'7"></span>');A(b,g,q,n,m);a={uploadStatus:q,responseMsg:m,
name:b.toUpload[g].name,size:(b.toUpload[g].size/1024).toFixed(2),type:b.toUpload[g].type};if("function"===typeof b.options.onEachUpload)try{b.options.onEachUpload(a,k)}catch(w){console.log("There is an error in onEachUpload callback"),console.log(w)}b.$element.find("input.ssi-uploadInput").trigger("onEachUpload.ssi-uploader",[a]);b.inProgress--;d.prop("disabled",!1);0===b.inProgress&&B(b);b.uploadList[g]="";b.toUpload[g]="";b.imgNames[g]=""});f=g;for(f++;!b.toUpload[f]&&"undefined"!==typeof b.toUpload[f];)f++;
f<b.toUpload.length&&b.tryToTransform(b.toUpload[f],function(c){c=b.appendFileToFormData(c);a(c,f)})}if(0<this.pending){if("function"===typeof this.options.beforeUpload)try{this.options.beforeUpload()}catch(n){if(!this.options.ignoreCallbackErrors)return console.log("There is an error in beforeUpload callback"),console.log(n)}this.$element.find("#ssi-abortBtn").removeClass("ssi-hidden");this.$element.find(".ssi-removeBtn").addClass("ssi-abortUpload").removeClass("ssi-removeBtn").children("span").removeClass("trash7 trash10 trash").addClass(this.options.preview?
"ban7w":"ban7");var c=this.$element.find("#ssi-uploadBtn"),d=this.$element.find("#ssi-clearBtn");c.prop("disabled",!0);var b=this,f=this.totalFilesLength;0===this.totalFilesLength||this.options.preview||F(this);this.inProgress+=this.pending;this.totalFilesLength+=this.pending;this.pending=0;for(this.inProgress===this.currentListLength&&d.prop("disabled",!0);!b.toUpload[f];)f++;b.tryToTransform(b.toUpload[f],function(c){c=b.appendFileToFormData(c);a(c,f)})}};var A=function(a,c,d,b,f){var h="",g="table.ssi-imgToUploadTable";
a.options.preview||(h="ssi-noPreviewSubMessage",g="tr.ssi-toUploadTr",1===a.currentListLength&&(a.errors=f));a=a.$element.find(".ssi-abortUpload[data-delete='"+c+"']");a.parents(g).addClass("ssi-completed");a.after(G(d,b,f,h)).remove()},G=function(a,c,d,b){return'<span class="ssi-statusLabel '+b+" "+a+'" data-status="'+d+'">'+c+"</span>"},C=function(a){var c=a.$element.find("#ssi-fileList").find("span").html(),d=c.getExtension();a.$element.find(".ssi-uploadDetails").removeClass("ssi-uploadBoxOpened");
a.$element.find(".ssi-namePreview").html(y(c,d,15))};l.prototype.abort=function(a,c,d){"undefined"===typeof c?(this.uploadList[a].abort(),this.totalProgress[a]="",c=d||"Aborted",this.aborted++):"string"!==typeof c&&(c="");d=this.language.aborted;this.options.preview||(d='<span class="ban7w"></span>');A(this,a,"error",d,c);this.$element.find("#ssi-uploadProgress"+a).removeClass("ssi-hidden").addClass("ssi-canceledProgressBar");this.toUpload[a]=void 0;this.uploadList[a]=void 0;this.imgNames[a]=void 0;
this.$element.find("#ssi-clearBtn").prop("disabled",!1);this.inProgress--;0===this.inProgress&&B(this)};var B=function(a){a.$element.find("#ssi-abortBtn").addClass("ssi-hidden");if(!a.options.preview){var c="error",d="",b="";0<a.abortedWithError?(d=1===a.totalFilesLength?a.errors:a.language.someErrorsOccurred,b='<span class="exclamation23"></span>'):0<a.aborted&&0===a.successfulUpload?(b='<span class="ban23"></span>',d=a.language.aborted):0<a.successfulUpload&&(c="success",b='<span class="check23"></span>',
d=a.language.sucUpload);a.$element.find(".ssi-namePreview").append(G(c,b,d,"ssi-noPreviewMessage"));a.$element.find("#ssi-uploadProgressNoPreview").removeAttr("styles").addClass("ssi-hidden")}if("function"===typeof a.options.onUpload)try{a.options.onUpload(c)}catch(f){a.options.ignoreCallbackErrors||(console.log("There is an error in onUpload callback"),console.log(f))}a.$element.find("input.ssi-uploadInput").trigger("onUpload.ssi-uploader",[c]);c=a.$element.find("#ssi-uploadBtn");a.$element.find("#ssi-clearBtn").prop("disabled",
!1);c.prop("disabled",!1).find("#ssi-up_loading").empty();0===a.pending&&(c.addClass("ssi-hidden"),a.toUpload=[],a.imgNames=[],a.totalFilesLength=0);a.uploadList=[];a.totalProgress=[];a.currentListLength=a.inProgress+a.successfulUpload+a.aborted+a.abortedWithError+a.pending;a.inProgress=0};h.fn.ssi_uploader=function(a){var c=h.extend(!0,{allowDuplicates:!1,url:"",data:{},locale:"en",preview:!0,dropZone:!0,maxNumberOfFiles:"",responseValidation:!1,ignoreCallbackErrors:!1,maxFileSize:2,inForm:!1,ajaxOptions:{},
onUpload:function(){},onEachUpload:function(){},beforeUpload:function(){},beforeEachUpload:function(){},allowed:"",errorHandler:{method:function(a){alert(a)},success:"success",error:"error"}},a);c.allowed=c.allowed||["jpg","jpeg","png","bmp","gif"];return this.each(function(){var a=h(this);if(a.is('input[type="file"]')){if(!a.data("ssi_upload")){var b=new l(this,c);a.data("ssi_upload",b)}}else console.log("The targeted element is not file input.")})};String.prototype.replaceText=function(){for(var a=
Array.apply(null,arguments),c=this,d=0;d<a.length;d++)c=c.replace("$"+(d+1),a[d]);return c};String.prototype.getExtension=function(){return this.split(".").pop().toLowerCase()};var y=function(a,c,d){"undefined"===typeof c&&(c="");"undefined"===typeof d&&(d=10);if(!(4>d)){var b=c.length;return a.length-2>d?(a=a.substring(0,d),a=a.substring(0,a.length-b),a+"..."+c):a}},H={en:{success:"Success",sucUpload:"Successful upload",chooseFiles:"Choose files",uploadFailed:"Upload failed",serverError:"Internal server error",
error:"Error",abort:"Abort",aborted:"Aborted",files:"files",upload:"Upload",clear:"Clear",drag:"Drag n Drop",sizeError:"$1 exceed the size limit of $2",extError:"$1 file types are not supported",someErrorsOccurred:"Some errors occurred!",wentWrong:"Something went wrong!",pending:"Pending",completed:"Completed",inProgress:"In progress"},gr:{success:"\u0395\u03c0\u03b9\u03c4\u03c5\u03c7\u03af\u03b1",sucUpload:"\u0395\u03c0\u03b9\u03c4\u03c5\u03c7\u03ae\u03c2 \u03bc\u03b5\u03c4\u03b1\u03c6\u03cc\u03c1\u03c4\u03c9\u03c3\u03b7",
chooseFiles:"\u0395\u03c0\u03b9\u03bb\u03ad\u03be\u03c4\u03b5 \u03b1\u03c1\u03c7\u03b5\u03af\u03b1",uploadFailed:"\u0397 \u03bc\u03b5\u03c4\u03b1\u03c6\u03cc\u03c1\u03c4\u03c9\u03c3\u03b7 \u03b1\u03c0\u03ad\u03c4\u03c5\u03c7\u03b5!",serverError:"\u0395\u03c3\u03c9\u03c4\u03b5\u03c1\u03b9\u03ba\u03cc \u03c3\u03c6\u03ac\u03bb\u03bc\u03b1 \u03b4\u03b9\u03b1\u03ba\u03bf\u03bc\u03b9\u03c3\u03c4\u03ae!",error:"\u03a3\u03c6\u03ac\u03bb\u03bc\u03b1",abort:"\u0394\u03b9\u03b1\u03ba\u03bf\u03c0\u03ae",aborted:"\u0394\u03b9\u03b1\u03ba\u03cc\u03c0\u03b7\u03ba\u03b5",
files:"\u03b1\u03c1\u03c7\u03b5\u03af\u03b1",upload:"\u039c\u03b5\u03c4\u03b1\u03c6\u03cc\u03c1\u03c4\u03c9\u03c3\u03b7",clear:"\u0395\u03ba\u03ba\u03b1\u03b8\u03ac\u03c1\u03b9\u03c3\u03b7",drag:"\u03a3\u03c5\u03c1\u03b5\u03c4\u03b5 \u03b5\u03b4\u03ce...",sizeError:"$1 \u03ad\u03c7\u03b5\u03b9 \u03be\u03b5\u03c0\u03b5\u03c1\u03ac\u03c3\u03b5\u03b9 \u03c4\u03bf \u03cc\u03c1\u03b9\u03bf \u03c4\u03c9\u03bd $2.",extError:"$1 \u03b1\u03c1\u03c7\u03b5\u03af\u03b1 \u03b4\u03b5\u03bd \u03c5\u03c0\u03bf\u03c3\u03c4\u03b7\u03c1\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9.",
someErrorsOccurred:"\u03a3\u03b7\u03bc\u03b5\u03b9\u03ce\u03b8\u03b7\u03ba\u03b1\u03bd \u03bf\u03c1\u03b9\u03c3\u03bc\u03ad\u03bd\u03b1 \u03bb\u03ac\u03b8\u03b7!",wentWrong:"\u039a\u03ac\u03c4\u03b9 \u03c0\u03ae\u03b3\u03b5 \u03c3\u03c4\u03c1\u03b1\u03b2\u03ac!",pending:"\u03a3\u03b5 \u03b5\u03ba\u03ba\u03c1\u03b5\u03bc\u03cc\u03c4\u03b7\u03c4\u03b1",completed:"\u039f\u03bb\u03bf\u03ba\u03bb\u03b7\u03c1\u03bf\u03bc\u03ad\u03bd\u03b1",inProgress:"\u03a3\u03b5 \u03b5\u03be\u03ad\u03bb\u03b9\u03be\u03b7"},
fr:{success:"Succ\u00e8s",sucUpload:"Envoi r\u00e9ussi",chooseFiles:"Choisissez fichiers",uploadFailed:"Envoi \u00e9chou\u00e9",serverError:"Erreur interne du serveur",error:"Erreur",abort:"Annuler",aborted:"Annul\u00e9",files:"Fichiers",upload:"Envoyer",clear:"Effacer",drag:"Glisser d\u00e9poser",sizeError:"$1 exc\u00e8de la taille limite de $2",extError:"Types de fichier $1 non autoris\u00e9",someErrorsOccurred:"Une erreur a eu lieu !",wentWrong:"Une erreur a eu lieu !",pending:"\u0395n attendant",
completed:"Termin\u00e9",inProgress:"En cours"},zh_CN:{success:"\u4e0a\u4f20\u6210\u529f",sucUpload:"\u4e0a\u4f20\u6210\u529f",chooseFiles:"\u9009\u62e9\u6587\u4ef6",uploadFailed:"\u4e0a\u4f20\u5931\u8d25",serverError:"\u670d\u52a1\u5668\u5185\u90e8\u9519\u8bef",error:"\u9519\u8bef",abort:"\u4e2d\u6b62",aborted:"\u5df2\u4e2d\u6b62",files:"\u6587\u4ef6",upload:"\u4e0a\u4f20",clear:"\u6e05\u7a7a",drag:"\u5c06\u56fe\u7247\u62d6\u62fd\u81f3\u6b64\u5e76\u91ca\u653e",sizeError:"$1 \u8d85\u51fa\u4e86 $2 \u7684\u5927\u5c0f\u9650\u5236",
extError:"$1 \u7c7b\u578b\u4e0d\u88ab\u652f\u6301",someErrorsOccurred:"\u53d1\u751f\u4e86\u4e00\u4e9b\u9519\u8bef!",wentWrong:"\u51fa\u95ee\u9898\u4e86\u54e6!",pending:"\u7b49\u5f85\u4e0a\u4f20",completed:"\u5b8c\u6210",inProgress:"\u6b63\u5728\u4e0a\u4f20"}}});
//# sourceMappingURL=ssi-uploader.min.js.map
|
/*
* This file is part of the Fxp package.
*
* (c) François Pluchino <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import AppPjax from '../app-pjax';
import '@fxp/jquery-table-select';
/**
* Add the App Pjax Component Register and Unregister.
*/
AppPjax.addDefaultRegisters('tableSelect', '[data-table-select="true"]');
|
'use strict';
const fs = require('fs');
const path = require('path');
const util = require('util');
const assert = require('assert');
const extract = require('..');
const read = name => fs.readFileSync(path.join(__dirname, `fixtures/${name}`), 'utf8');
function isBlock(c) {
return c.type === 'BlockComment';
}
function isLine(c) {
return c.type === 'LineComment';
}
describe('esprima-extract-comments', function() {
describe('main export', function() {
it('should extract line comments', function() {
const comments = extract('foo // bar');
assert(Array.isArray(comments));
assert.equal(comments.filter(isLine).length, 1);
assert.equal(comments.filter(isLine)[0].value, ' bar');
});
it('should extract block comments', function() {
const comments = extract(read('app.js'));
assert(comments.filter(isBlock).length > 1);
});
it('should extract line and block comments', function() {
const str = fs.readFileSync(path.join(__dirname, '../index.js'), 'utf8');
const comments = extract(str);
assert(Array.isArray(comments));
assert(comments.length >= 1);
assert(/esprima-extract-comments/.test(comments[0].value));
});
it('should extract complex comments', function() {
const comments = extract(read('angular.js'), { allowReturnOutsideFunction: true });
assert.equal(comments[comments.length - 1].loc.start.line, 29702);
});
});
describe('.file', function() {
it('should extract block comments from a file', function() {
const comments = extract.file('app.js', { cwd: path.join(__dirname, 'fixtures') });
assert(comments.filter(isBlock).length > 1);
});
it('should extract line comments from a file', function() {
const comments = extract.file('app.js', { cwd: path.join(__dirname, 'fixtures') });
assert(comments.filter(isLine).length >= 1);
});
});
});
|
/**
* Test sagas
*/
/* eslint-disable redux-saga/yield-effects */
import { take, call, put, select, cancel, takeLatest } from 'redux-saga/effects';
import { createMockTask } from 'redux-saga/lib/utils';
import { LOCATION_CHANGE } from 'react-router-redux';
import { paths } from 'config';
import request from 'utils/request';
import { fromJS } from 'immutable';
import * as router from 'react-router';
import { login, getLoginResponse, changeToUserPage } from '../sagas';
import { DO_LOGIN_ACTION, LOGIN_SUCCESS_ACTION, LOGIN_ERROR_MSG_DEFAULT } from '../constants';
import { makeSelectLoginCredentials } from '../selectors';
import { makeLoginSuccessAction, makeLoginErrorAction } from '../actions';
describe('changeToUserPage', () => {
let pushMock;
beforeEach(() => {
pushMock = jest.fn();
router.browserHistory = { push: pushMock };
});
it('should push to user page', () => {
const changeToUserPageGenerator = changeToUserPage();
changeToUserPageGenerator.next();
expect(pushMock).toBeCalledWith(paths.appPaths.user.path);
});
});
describe('getLoginResponse saga', () => {
let getLoginResponseGenerator;
beforeEach(() => {
getLoginResponseGenerator = getLoginResponse();
const selectDescriptor = getLoginResponseGenerator.next().value;
// using stringify because that's what they did in the redux-saga issue
// https://github.com/redux-saga/redux-saga/issues/325
expect(
JSON.stringify(selectDescriptor)
).toEqual(JSON.stringify(select(makeSelectLoginCredentials())));
const expectedBody = {
username: 'foo',
password: 'bar',
remember: true,
};
const loginCred = fromJS(expectedBody);
const callDescriptor = getLoginResponseGenerator.next(loginCred).value;
expect(callDescriptor).toEqual(call(request, paths.api.auth.LOGIN, {
method: 'POST',
body: expectedBody,
}));
});
it('should dispatch onLoginSuccess for a success', () => {
const loginResponse = {
status: 200,
};
const putDescriptor = getLoginResponseGenerator.next(loginResponse).value;
expect(putDescriptor).toEqual(put(makeLoginSuccessAction(loginResponse)));
});
it('should dispatch onLoginFailure for a failure and set msg if has msg', () => {
const loginErrorMsg = 'foo';
const loginResponse = {
status: 500,
body: { loginErrorMsg },
};
const putDescriptor = getLoginResponseGenerator.throw(loginResponse).value;
expect(putDescriptor).toEqual(put(makeLoginErrorAction(loginErrorMsg)));
});
it('should dispatch onLoginFailure for a failure and use default if no msg', () => {
const loginResponse = {
status: 500,
};
const putDescriptor = getLoginResponseGenerator.throw(loginResponse).value;
expect(putDescriptor).toEqual(put(makeLoginErrorAction(LOGIN_ERROR_MSG_DEFAULT)));
});
});
describe('login Saga', () => {
const loginSaga = login();
const mockDoLoginWatcher = createMockTask();
const mockLoginSuccessWatcher = createMockTask();
it('should start task to watch for DO_LOGIN action', () => {
const takeLatestDescriptor = loginSaga.next().value;
expect(takeLatestDescriptor).toEqual(takeLatest(DO_LOGIN_ACTION, getLoginResponse));
});
it('should start task to watch for LOGIN_SUCCESS action', () => {
const takeLatestDescriptor = loginSaga.next(mockDoLoginWatcher).value;
expect(takeLatestDescriptor).toEqual(takeLatest(LOGIN_SUCCESS_ACTION, changeToUserPage));
});
it('should yield until LOCATION_CHANGE action', () => {
const takeDescriptor = loginSaga.next(mockLoginSuccessWatcher).value;
expect(takeDescriptor).toEqual(take(LOCATION_CHANGE));
});
it('should cancel the forked task when LOCATION_CHANGE happens', () => {
const cancelDescriptor = loginSaga.next().value;
expect(cancelDescriptor).toEqual([cancel(mockDoLoginWatcher), cancel(mockLoginSuccessWatcher)]);
});
});
|
import { status, json } from '../../../shared/helpers/fetch';
import steamAuth from 'electron-steam-openid';
export default function requestToken() {
var config = {
redirectUri: 'http://localhost'
};
const windowParams = {
alwaysOnTop: true,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: false
}
}
return steamAuth(config, windowParams).authenticate();
}
|
var mongoose = require('mongoose');
mongoose.connect('mongodb://mongo:[email protected]:28799/discretka');
module.exports = mongoose.connection; |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PaymentSchema = new Schema({
reference: String,
businessId: String,
customerId: String,
price: Number,
status: {
type: Boolean,
default: 0
}
});
module.exports = mongoose.model('Payment', PaymentSchema); |
/**
* @intro: action的类型管理.
*
*/
// 设置用户信息和登录
export const SET_USER_INFO = 'SET_USER_INFO'
|
const { assert } = require('chai');
const { beginTests } = require('./dist/tests.umd');
const mod = require('../dist/keycode.cjs');
beginTests(mod, { test: it, assertEquals: assert.equal });
|
'use strict';
/* jasmine specs for controllers go here */
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
var ctrl, $httpBackend;
beforeEach(module('phonecatApp'));
beforeEach(inject(function(_$httpBackend_, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('phones/phones.json').
respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
ctrl = $controller('PhoneListCtrl');
}));
it('should create "phones" model with 2 phones fetched from xhr', function() {
expect(phoneListCtrl.phones).toBeUndefined();
$httpBackend.flush();
expect(ctrl.phones).toEqual([{name: 'Nexus S'},
{name: 'Motorola DROID'}]);
});
it('should set the default value of orderProp model', function() {
expect(ctrl.orderProp).toBe('age');
});
});
describe('PhoneDetailCtrl', function(){
});
});
|
// Generated on 2013-08-24 using generator-webapp 0.2.7
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function(connect, dir) {
return connect.static(require('path').resolve(dir));
};
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function(grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// dust.js requires
// require('dustmotes-iterate');
// configurable paths
var yeomanConfig = {
app: 'src',
dist: 'dist',
scripts: 'src/scripts',
data: 'src/data',
translations: 'src/data/translations',
templates: 'src/templates'
};
grunt.initConfig({
yeoman: yeomanConfig,
watch: {
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server', 'autoprefixer']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['copy:styles', 'autoprefixer']
},
dusthtml: {
files: [
'<%= yeoman.app %>/templates/dust/{,*/}*.dust.html',
'<%= yeoman.data %>/references/*.json'
],
tasks: ['dusthtml']
},
json: {
files: [
'<%= yeoman.translations %>/de/{,*/}*.json',
'<%= yeoman.translations %>/en/{,*/}*.json',
'<%= yeoman.data %>/*.json'
],
tasks: ['json_merge', 'filesToJavascript', 'dusthtml']
},
includes: {
files: ['src/templates/*.html'],
tasks: ['includes']
},
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: [
'<%= yeoman.app %>/*.html',
'.tmp/styles/{,*/}*.css',
'{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
open: {
appName: 'chromium-browser'
},
middleware: function(connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
test: {
options: {
middleware: function(connect) {
return [
mountFolder(connect, '.tmp'),
mountFolder(connect, 'test')
];
}
}
},
dist: {
options: {
middleware: function(connect) {
return [
mountFolder(connect, yeomanConfig.dist)
];
}
}
}
},
open: {
server: {
path: 'http://localhost:<%= connect.options.port %>'
}
},
clean: {
dist: {
files: [
{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*'
]
}
]
},
server: '.tmp'
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js',
'!<%= yeoman.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '.tmp/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: '<%= yeoman.app %>/../bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false
},
dist: {
options: {
generatedImagesDir: '<%= yeoman.dist %>/images/generated'
}
},
server: {
options: {
debugInfo: true
}
}
},
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [
{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}
]
}
},
// not used since Uglify task does concat,
// but still available if needed
/*concat: {
dist: {}
},*/
// not enabled since usemin task does concat and uglify
// check index.html to edit your build targets
// enable this task if you prefer defining your build targets here
/*uglify: {
dist: {}
},*/
rev: {
dist: {
files: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
}
},
useminPrepare: {
options: {
dest: '<%= yeoman.dist %>'
},
html: ['<%= yeoman.app %>/index.html']
},
usemin: {
options: {
dirs: ['<%= yeoman.dist %>']
},
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css']
},
svgmin: {
dist: {
files: [
{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}
]
}
},
cssmin: {
// This task is pre-configured if you do not wish to use Usemin
// blocks for your CSS. By default, the Usemin block from your
// `index.html` will take care of minification, e.g.
//
// <!-- build:css({.tmp,app}) styles/main.css -->
//
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= yeoman.app %>/styles/{,*/}*.css'
// ]
// }
// }
},
htmlmin: {
dist: {
options: {
/*removeCommentsFromCDATA: true,
// https://github.com/yeoman/grunt-usemin/issues/44
//collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeOptionalTags: true*/
},
files: [
{
expand: true,
cwd: '<%= yeoman.app %>',
src: '*.html',
dest: '<%= yeoman.dist %>'
}
]
}
},
// Put files not handled in other tasks here
copy: {
dist: {
files: [
{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,jpg,jpeg,txt}',
'.htaccess',
'images/{,*/}*.{webp,gif,png,jpg,jpeg}',
'styles/fonts/*',
'CNAME'
]
}
]
},
styles: {
expand: true,
dot: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
concurrent: {
server: [
'compass',
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'compass',
'copy:styles',
'svgmin',
'htmlmin'
]
},
includes: {
files: {
cwd: 'src/templates/',
src: ['index.html'], // Source files
dest: 'src', // Destination directory
flatten: false,
options: {
includePath: 'src/templates/'
}
}
},
json_merge: {
englishFiles: {
files: {
'<%= yeoman.translations %>/all/en.translation.json': [
'<%= yeoman.translations %>/en/*.json'
]
}
},
germanFiles: {
files: {
'<%= yeoman.translations %>/all/de.translation.json': [
'<%= yeoman.translations %>/de/*.json'
]
}
},
germanPathFiles: {
files: {
'<%= yeoman.translations %>/all/path/de.translation.pathEvents.json': [
'<%= yeoman.translations %>/de/path/{,*/}*.json'
]
}
},
englishPathFiles: {
files: {
'<%= yeoman.translations %>/all/path/en.translation.pathEvents.json': [
'<%= yeoman.translations %>/en/path/{,*/}*.json'
]
}
}
},
filesToJavascript: {
i18n: {
options: {
inputFilesFolder: '<%= yeoman.translations %>/all',
inputFileExtension: 'json',
shouldMinify: true,
outputBaseFile: '<%= yeoman.scripts %>/i18n-base.js',
outputFile: '<%= yeoman.scripts %>/i18n.js',
outputBaseFileVariable: 'resources'
}
}
},
dusthtml: {
about: {
src: "<%= yeoman.app %>/templates/dust/about.dust.html",
dest: "<%= yeoman.app %>/templates/about.html",
options: {
module: 'dustjs-helpers-extra',
context: [
"<%= yeoman.translations %>/en/pages.en.json"
]
}
},
path: {
src: "<%= yeoman.app %>/templates/dust/path.dust.html",
dest: "<%= yeoman.app %>/templates/path.html",
options: {
module: 'dustjs-helpers-extra',
context: [
"<%= yeoman.translations %>/all/path/en.translation.pathEvents.json",
"<%= yeoman.data %>/skills.json",
"<%= yeoman.data %>/references/references.json"
]
}
},
references: {
src: "<%= yeoman.templates %>/dust/references.dust.html",
dest: "<%= yeoman.templates %>/references.html",
options: {
module: 'dustjs-helpers-extra',
context: [
"<%= yeoman.data %>/references/references.json"
]
}
}
},
'gh-pages': {
options: {
base: 'dist'
},
src: ['**']
}
});
grunt.registerTask('server', function(target) {
if (target === 'dist') {
return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'dusthtml',
'json_merge',
'filesToJavascript',
'includes',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'open',
'watch'
]);
});
grunt.registerTask('watchdust', [
'dusthtml',
'watch:dusthtml'
]);
grunt.registerTask('i18n', [
'json_merge',
'filesToJavascript'
]);
grunt.registerTask('references', [
'dusthtml:references'
]);
grunt.registerTask('build', [
'clean:dist',
'dusthtml',
'json_merge',
'filesToJavascript',
'includes',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'cssmin',
// 'uglify',
'copy:dist',
'rev',
'usemin'
]);
grunt.registerTask('ghpages', ['gh-pages']);
grunt.registerTask('default', [
'server'
]);
};
|
'use strict';
var _ = require('underscore');
AnalyzeAllCtrl.$inject = ['$scope', '$http', '$location', 'd3', 'format'];
AnalyzeFactionCtrl.$inject = ['$scope', '$http', '$location', '$routeParams', 'd3', 'format'];
module.exports = {
faction: AnalyzeFactionCtrl,
all: AnalyzeAllCtrl
};
function AnalyzeAllCtrl($scope, $http, $location, d3, format) {
$scope.format = format.buildFormat();
$scope.faction = { imgUrl: "/img/all.png", name: "all" };
$http({ method: 'GET', url: '/data/faction/' + $scope.faction.name })
.then(function(response) {
if(response.data) {
$scope.factionData = response.data;
buildAndSaveHeatmap($scope, $scope.factionData.results)
}
});
loadTooltips();
function buildAndSaveHeatmap($scope, results) {
var factions = _.map(results, x => x.faction);
var data = new Array(factions.length);
for(var i = 0; i < factions.length; i++) {
data[i] = new Array(factions.length);
}
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < data[i].length; j++) {
if(Math.floor(i / 2) == Math.floor(j / 2)) { // same color
data[i][j] = "";
} else {
var denom = results[i][factions[j]].win + results[i][factions[j]].loss;
var percent = denom == 0 ? "-" :
Math.round(results[i][factions[j]].win / denom * 100);
data[i][j] = percent;
}
}
}
$scope.factions = factions;
$scope.heatmap = data;
}
function loadTooltips() {
$(".explanation").tooltip({ tooltipClass: "explanation-tooltip" });
}
}
function AnalyzeFactionCtrl($scope, $http, $location, $routeParams, d3, format) {
$scope.format = format.buildFormat()
$scope.faction = getFactionSettings($routeParams.faction);
if($scope.faction) {
$http({ method: 'GET', url: '/data/faction/' + $scope.faction.name })
.then(function(response) {
if(response.data) {
$scope.factionData = response.data;
}
});
}
loadTooltips();
function getFactionSettings(faction) {
if(!faction) {
return null;
}
var imgUrlPrefix = "http://www.terra-mystica-spiel.de/img/";
if(faction.toUpperCase() == "DWARVES") {
return {
imgUrl: imgUrlPrefix + "volk_7_300.jpg",
name: "dwarves"
};
} else if(faction.toUpperCase() == "ENGINEERS") {
return {
imgUrl: imgUrlPrefix + "volk_8_300.jpg",
name: "engineers"
};
} else if(faction.toUpperCase() == "CHAOSMAGICIANS") {
return {
imgUrl: imgUrlPrefix + "volk_3_300.jpg",
name: "chaosmagicians"
};
} else if(faction.toUpperCase() == "GIANTS") {
return {
imgUrl: imgUrlPrefix + "volk_4_300.jpg",
name: "giants"
};
} else if(faction.toUpperCase() == "FAKIRS") {
return {
imgUrl: imgUrlPrefix + "volk_1_300.jpg",
name: "fakirs"
};
} else if(faction.toUpperCase() == "NOMADS") {
return {
imgUrl: imgUrlPrefix + "volk_2_300.jpg",
name: "nomads"
};
} else if(faction.toUpperCase() == "HALFLINGS") {
return {
imgUrl: imgUrlPrefix + "volk_9_300.jpg",
name: "halflings"
};
} else if(faction.toUpperCase() == "CULTISTS") {
return {
imgUrl: imgUrlPrefix + "volk_10_300.jpg",
name: "cultists"
};
} else if(faction.toUpperCase() == "ALCHEMISTS") {
return {
imgUrl: imgUrlPrefix + "volk_11_300.jpg",
name: "alchemists"
};
} else if(faction.toUpperCase() == "DARKLINGS") {
return {
imgUrl: imgUrlPrefix + "volk_12_300.jpg",
name: "darklings"
};
} else if(faction.toUpperCase() == "SWARMLINGS") {
return {
imgUrl: imgUrlPrefix + "volk_5_300.jpg",
name: "swarmlings"
};
} else if(faction.toUpperCase() == "MERMAIDS") {
return {
imgUrl: imgUrlPrefix + "volk_6_300.jpg",
name: "mermaids"
};
} else if(faction.toUpperCase() == "AUREN") {
return {
imgUrl: imgUrlPrefix + "volk_13_300.jpg",
name: "auren"
};
} else if(faction.toUpperCase() == "WITCHES") {
return {
imgUrl: imgUrlPrefix + "volk_14_300.jpg",
name: "witches"
};
} else {
return null;
}
}
function loadTooltips() {
$(".explanation").tooltip();
}
} |
$(function() {
var socket = io();
var commands = [
"/close",
"/connect",
"/deop",
"/devoice",
"/disconnect",
"/invite",
"/join",
"/kick",
"/leave",
"/mode",
"/msg",
"/nick",
"/notice",
"/op",
"/part",
"/query",
"/quit",
"/raw",
"/say",
"/send",
"/server",
"/slap",
"/topic",
"/voice",
"/whois"
];
var sidebar = $("#sidebar, #footer");
var chat = $("#chat");
if (navigator.standalone) {
$("html").addClass("web-app-mode");
}
var pop;
try {
pop = new Audio();
pop.src = "/audio/pop.ogg";
} catch (e) {
pop = {
play: $.noop
};
}
$("#play").on("click", function() { pop.play(); });
$("#footer .icon").tooltip();
$(".tse-scrollable").TrackpadScrollEmulator();
var favico = new Favico({
animation: "none"
});
function render(name, data) {
return Handlebars.templates[name](data);
}
Handlebars.registerHelper(
"partial", function(id) {
return new Handlebars.SafeString(render(id, this));
}
);
socket.on("error", function(e) {
console.log(e);
});
$.each(["connect_error", "disconnect"], function(i, e) {
socket.on(e, function() {
refresh();
});
});
socket.on("auth", function(/* data */) {
var body = $("body");
var login = $("#sign-in");
if (!login.length) {
refresh();
return;
}
login.find(".btn").prop("disabled", false);
var token = $.cookie("token");
if (token) {
$.removeCookie("token");
socket.emit("auth", {token: token});
}
if (body.hasClass("signed-out")) {
var error = login.find(".error");
error.show().closest("form").one("submit", function() {
error.hide();
});
}
if (!token) {
body.addClass("signed-out");
}
var input = login.find("input[name='user']");
if (input.val() === "") {
input.val($.cookie("user") || "");
}
if (token) {
return;
}
sidebar.find(".sign-in")
.click()
.end()
.find(".networks")
.html("")
.next()
.show();
});
socket.on("init", function(data) {
if (data.networks.length === 0) {
$("#footer").find(".connect").trigger("click");
} else {
sidebar.find(".empty").hide();
sidebar.find(".networks").html(
render("network", {
networks: data.networks
})
);
var channels = $.map(data.networks, function(n) {
return n.channels;
});
chat.html(
render("chat", {
channels: channels
})
);
confirmExit();
}
if (data.token) {
$.cookie(
"token",
data.token, {
expires: expire(30)
}
);
}
$("body").removeClass("signed-out");
$("#sign-in").detach();
var id = data.active;
var target = sidebar.find("[data-id='" + id + "']").trigger("click");
if (target.length === 0) {
var first = sidebar.find(".chan")
.eq(0)
.trigger("click");
if (first.length === 0) {
$("#footer").find(".connect").trigger("click");
}
}
sortable();
});
socket.on("join", function(data) {
var id = data.network;
var network = sidebar.find("#network-" + id);
network.append(
render("chan", {
channels: [data.chan]
})
);
chat.append(
render("chat", {
channels: [data.chan]
})
);
var chan = sidebar.find(".chan")
.sort(function(a, b) { return $(a).data("id") - $(b).data("id"); })
.last();
if (!whois) {
chan = chan.filter(":not(.query)");
}
whois = false;
chan.click();
});
socket.on("msg", function(data) {
var target = "#chan-" + data.chan;
if (data.msg.type === "error") {
target = "#chan-" + chat.find(".active").data("id");
}
var chan = chat.find(target);
var from = data.msg.from;
var msg = $(render("msg", {messages: [data.msg]}));
chan.find(".messages")
.append(msg)
.trigger("msg", [
target,
data.msg
]);
var text = msg.find(".text");
if (text.find("i").size() === 1) {
text = text.find("i");
}
// Channels names are strings (beginning with a '&' or '#' character)
// of length up to 200 characters.
// See https://tools.ietf.org/html/rfc1459#section-1.3
text.html(text.html().replace(/(^|\s)([#&][^\x07\x2C\s]{0,199})/ig,
'$1<span class="inline-channel" role="button" tabindex="0" data-chan="$2">$2</span>'));
text.find("span.inline-channel")
.on("click", function() {
var chan = $(".network")
.find(".chan.active")
.parent(".network")
.find(".chan[data-title='" + $(this).data("chan") + "']");
if (chan.size() === 1) {
chan.click();
} else {
socket.emit("input", {
target: chat.data("id"),
text: "/join " + $(this).data("chan")
});
}
});
if (!chan.hasClass("channel")) {
return;
}
var type = data.msg.type;
if (type === "message" || type === "action") {
var nicks = chan.find(".users").data("nicks");
if (nicks) {
var find = nicks.indexOf(from);
if (find !== -1 && typeof move === "function") {
move(nicks, find, 0);
}
}
}
});
socket.on("more", function(data) {
var target = data.chan;
var chan = chat
.find("#chan-" + target)
.find(".messages")
.prepend(render("msg", {messages: data.messages}))
.end();
if (data.messages.length !== 100) {
chan.find(".show-more").removeClass("show");
}
});
socket.on("network", function(data) {
sidebar.find(".empty").hide();
sidebar.find(".networks").append(
render("network", {
networks: [data.network]
})
);
chat.append(
render("chat", {
channels: data.network.channels
})
);
sidebar.find(".chan")
.last()
.trigger("click");
$("#connect")
.find(".btn")
.prop("disabled", false)
.end();
confirmExit();
sortable();
});
socket.on("nick", function(data) {
var id = data.network;
var nick = data.nick;
var network = sidebar.find("#network-" + id).data("nick", nick);
if (network.find(".active").length) {
setNick(nick);
}
});
socket.on("part", function(data) {
var id = data.chan;
sidebar.find(".chan[data-id='" + id + "']").remove();
$("#chan-" + id).remove();
var next = null;
var highest = -1;
chat.find(".chan").each(function() {
var self = $(this);
var z = parseInt(self.css("z-index"));
if (z > highest) {
highest = z;
next = self;
}
});
if (next !== null) {
id = next.data("id");
sidebar.find("[data-id=" + id + "]").click();
} else {
sidebar.find(".chan")
.eq(0)
.click();
}
});
socket.on("quit", function(data) {
var id = data.network;
sidebar.find("#network-" + id)
.remove()
.end();
var chan = sidebar.find(".chan")
.eq(0)
.trigger("click");
if (chan.length === 0) {
sidebar.find(".empty").show();
}
});
socket.on("toggle", function(data) {
var toggle = $("#toggle-" + data.id);
toggle.parent().after(render("toggle", {toggle: data}));
switch (data.type) {
case "link":
if (options.links) {
toggle.click();
}
break;
case "image":
if (options.thumbnails) {
toggle.click();
}
break;
}
});
socket.on("topic", function(data) {
// .text() escapes HTML but not quotes. That only matters with text inside attributes.
var topic = $("#chan-" + data.chan).find(".header .topic");
topic.text(data.topic);
// .attr() is safe escape-wise but consider the capabilities of the attribute
topic.attr("title", data.topic);
});
socket.on("users", function(data) {
var users = chat.find("#chan-" + data.chan).find(".users").html(render("user", data));
var nicks = [];
for (var i in data.users) {
nicks.push(data.users[i].name);
}
users.data("nicks", nicks);
});
$.cookie.json = true;
var settings = $("#settings");
var options = $.extend({
badge: false,
colors: false,
join: true,
links: true,
mode: true,
motd: false,
nick: true,
notification: true,
part: true,
thumbnails: true,
quit: true,
notifyAllMessages: false,
}, $.cookie("settings"));
for (var i in options) {
if (options[i]) {
settings.find("input[name=" + i + "]").prop("checked", true);
}
}
settings.on("change", "input", function() {
var self = $(this);
var name = self.attr("name");
options[name] = self.prop("checked");
$.cookie(
"settings",
options, {
expires: expire(365)
}
);
if ([
"join",
"mode",
"motd",
"nick",
"part",
"quit",
"notifyAllMessages",
].indexOf(name) !== -1) {
chat.toggleClass("hide-" + name, !self.prop("checked"));
}
if (name === "colors") {
chat.toggleClass("no-colors", !self.prop("checked"));
}
}).find("input")
.trigger("change");
$("#badge").on("change", function() {
var self = $(this);
if (self.prop("checked")) {
if (Notification.permission !== "granted") {
Notification.requestPermission();
}
}
});
var viewport = $("#viewport");
viewport.on("click", ".lt, .rt", function(e) {
var self = $(this);
viewport.toggleClass(self.attr("class"));
if (viewport.is(".lt, .rt")) {
e.stopPropagation();
chat.find(".chat").one("click", function() {
viewport.removeClass("lt");
});
}
});
var input = $("#input")
.history()
.tab(complete, {hint: false});
var form = $("#form");
form.on("submit", function(e) {
e.preventDefault();
var text = input.val();
input.val("");
if (text.indexOf("/clear") === 0) {
clear();
return;
}
socket.emit("input", {
target: chat.data("id"),
text: text
});
});
chat.on("click", ".messages", function() {
setTimeout(function() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type !== "Control") {
text = document.selection.createRange().text;
}
if (!text) {
focus();
}
}, 2);
});
$(window).on("focus", focus);
function focus() {
var chan = chat.find(".active");
if (screen.width > 768 && chan.hasClass("chan")) {
input.focus();
}
}
var top = 1;
sidebar.on("click", ".chan, button", function() {
var self = $(this);
var target = self.data("target");
if (!target) {
return;
}
chat.data(
"id",
self.data("id")
);
socket.emit(
"open",
self.data("id")
);
sidebar.find(".active").removeClass("active");
self.addClass("active")
.find(".badge")
.removeClass("highlight")
.data("count", "")
.empty();
if (sidebar.find(".highlight").length === 0) {
favico.badge("");
}
viewport.removeClass("lt");
$("#windows .active").removeClass("active");
var chan = $(target)
.addClass("active")
.trigger("show")
.css("z-index", top++)
.find(".chat")
.sticky()
.end();
var title = "Shout";
if (chan.data("title")) {
title = chan.data("title") + " — " + title;
}
document.title = title;
if (self.hasClass("chan")) {
var nick = self
.closest(".network")
.data("nick");
if (nick) {
setNick(nick);
}
}
if (screen.width > 768 && chan.hasClass("chan")) {
input.focus();
}
});
sidebar.on("click", "#sign-out", function() {
$.removeCookie("token");
location.reload();
});
sidebar.on("click", ".close", function() {
var cmd = "/close";
var chan = $(this).closest(".chan");
if (chan.hasClass("lobby")) {
cmd = "/quit";
var server = chan.find(".name").html();
if (!confirm("Disconnect from " + server + "?")) {
return false;
}
}
socket.emit("input", {
target: chan.data("id"),
text: cmd
});
chan.css({
transition: "none",
opacity: 0.4
});
return false;
});
chat.on("input", ".search", function() {
var value = $(this).val().toLowerCase();
var names = $(this).closest(".users").find(".names");
names.find("button").each(function() {
var btn = $(this);
var name = btn.text().toLowerCase().replace(/[+%@~]/, "");
if (name.indexOf(value) === 0) {
btn.show();
} else {
btn.hide();
}
});
});
var whois = false;
chat.on("click", ".user", function() {
var user = $(this).text().trim().replace(/[+%@~&]/, "");
if (user.indexOf("#") !== -1) {
return;
}
whois = true;
var text = "/whois " + user;
socket.emit("input", {
target: chat.data("id"),
text: text
});
});
chat.on("click", ".close", function() {
var id = $(this)
.closest(".chan")
.data("id");
sidebar.find(".chan[data-id='" + id + "']")
.find(".close")
.click();
});
chat.on("msg", ".messages", function(e, target, msg) {
var button = sidebar.find(".chan[data-target=" + target + "]");
var isQuery = button.hasClass("query");
var type = msg.type;
var highlight = type.contains("highlight");
var message = type.contains("message");
var settings = $.cookie("settings") || {};
if (highlight || isQuery || (settings.notifyAllMessages && message)) {
if (!document.hasFocus() || !$(target).hasClass("active")) {
if (settings.notification) {
pop.play();
}
favico.badge("!");
if (settings.badge && Notification.permission === "granted") {
var notify = new Notification(msg.from + " says:", {
body: msg.text.trim(),
icon: "/img/logo-64.png"
});
notify.onclick = function() {
window.focus();
button.click();
this.close();
};
window.setTimeout(function() {
notify.close();
}, 5 * 1000);
}
}
}
button = button.filter(":not(.active)");
if (button.length === 0) {
return;
}
var ignore = [
"join",
"part",
"quit",
"nick",
"mode",
];
if ($.inArray(type, ignore) !== -1){
return;
}
var badge = button.find(".badge");
if (badge.length !== 0) {
var i = (badge.data("count") || 0) + 1;
badge.data("count", i);
badge.html(i > 999 ? (i / 1000).toFixed(1) + "k" : i);
if (highlight || isQuery) {
badge.addClass("highlight");
}
}
});
chat.on("click", ".show-more-button", function() {
var self = $(this);
var count = self.parent().next(".messages").children().length;
socket.emit("more", {
target: self.data("id"),
count: count
});
});
chat.on("click", ".toggle-button", function() {
var self = $(this);
var chat = self.closest(".chat");
var bottom = chat.isScrollBottom();
var content = self.parent().next(".toggle-content");
if (bottom && !content.hasClass("show")) {
var img = content.find("img");
if (img.length !== 0 && !img.width()) {
img.on("load", function() {
chat.scrollBottom();
});
}
}
content.toggleClass("show");
if (bottom) {
chat.scrollBottom();
}
});
var windows = $("#windows");
var forms = $("#sign-in, #connect");
windows.on("show", "#sign-in", function() {
var self = $(this);
var inputs = self.find("input");
inputs.each(function() {
var self = $(this);
if (self.val() === "") {
self.focus();
return false;
}
});
});
windows.on("click", ".input", function() {
$(this).select();
});
forms.on("submit", "form", function(e) {
e.preventDefault();
var event = "auth";
var form = $(this);
form.find(".btn")
.attr("disabled", true)
.end();
if (form.closest(".window").attr("id") === "connect") {
event = "conn";
}
var values = {};
$.each(form.serializeArray(), function(i, obj) {
if (obj.value !== "") {
values[obj.name] = obj.value;
}
});
if (values.user) {
$.cookie(
"user",
values.user, {
expires: expire(30)
}
);
}
socket.emit(
event, values
);
});
forms.on("input", ".nick", function() {
var nick = $(this).val();
forms.find(".username").val(nick);
});
Mousetrap.bind([
"command+up",
"command+down",
"ctrl+up",
"ctrl+down"
], function(e, keys) {
var channels = sidebar.find(".chan");
var index = channels.index(channels.filter(".active"));
var direction = keys.split("+").pop();
switch (direction) {
case "up":
// Loop
var upTarget = (channels.length + (index - 1 + channels.length)) % channels.length;
channels.eq(upTarget).click();
break;
case "down":
// Loop
var downTarget = (channels.length + (index + 1 + channels.length)) % channels.length;
channels.eq(downTarget).click();
break;
}
});
Mousetrap.bind([
"command+k",
"ctrl+shift+l"
], function(e) {
if (e.target === input[0]) {
clear();
e.preventDefault();
}
});
setInterval(function() {
chat.find(".chan:not(.active)").each(function() {
var chan = $(this);
if (chan.find(".messages").children().slice(0, -100).remove().length) {
chan.find(".show-more").addClass("show");
}
});
}, 1000 * 10);
function clear() {
chat.find(".active .messages").empty();
chat.find(".active .show-more").addClass("show");
}
function complete(word) {
var words = commands.slice();
var users = chat.find(".active").find(".users");
var nicks = users.data("nicks");
if (!nicks) {
nicks = [];
users.find(".user").each(function() {
var nick = $(this).text().replace(/[~&@%+]/, "");
nicks.push(nick);
});
users.data("nicks", nicks);
}
for (var i in nicks) {
words.push(nicks[i]);
}
sidebar.find(".chan")
.each(function() {
var self = $(this);
if (!self.hasClass("lobby")) {
words.push(self.data("title"));
}
});
return $.grep(
words,
function(w) {
return !w.toLowerCase().indexOf(word.toLowerCase());
}
);
}
function confirmExit() {
if ($("body").hasClass("public")) {
window.onbeforeunload = function() {
return "Are you sure you want to navigate away from this page?";
};
}
}
function refresh() {
window.onbeforeunload = null;
location.reload();
}
function expire(days) {
var date = new Date();
date.setTime(date.getTime() + ((3600 * 1000 * 24) * days));
return date;
}
function sortable() {
sidebar.sortable({
axis: "y",
containment: "parent",
cursor: "grabbing",
distance: 12,
items: ".network",
handle: ".lobby",
placeholder: "network-placeholder",
forcePlaceholderSize: true,
update: function() {
var order = [];
sidebar.find(".network").each(function() {
var id = $(this).data("id");
order.push(id);
});
socket.emit(
"sort", {
type: "networks",
order: order
}
);
}
});
sidebar.find(".network").sortable({
axis: "y",
containment: "parent",
cursor: "grabbing",
distance: 12,
items: ".chan:not(.lobby)",
placeholder: "chan-placeholder",
forcePlaceholderSize: true,
update: function(e, ui) {
var order = [];
var network = ui.item.parent();
network.find(".chan").each(function() {
var id = $(this).data("id");
order.push(id);
});
socket.emit(
"sort", {
type: "channels",
target: network.data("id"),
order: order
}
);
}
});
}
function setNick(nick) {
var width = $("#nick")
.html(nick + ":")
.width();
if (width) {
width += 31;
input.css("padding-left", width);
}
}
function move(array, old_index, new_index) {
if (new_index >= array.length) {
var k = new_index - array.length;
while ((k--) + 1) {
this.push(undefined);
}
}
array.splice(new_index, 0, array.splice(old_index, 1)[0]);
return array;
}
document.addEventListener(
"visibilitychange",
function() {
if (sidebar.find(".highlight").length === 0) {
favico.badge("");
}
}
);
});
|
var structrocksdb_1_1CompactionJobInfo =
[
[ "CompactionJobInfo", "structrocksdb_1_1CompactionJobInfo.html#a96e41af9b2d9ea49ac699face8afb0df", null ],
[ "CompactionJobInfo", "structrocksdb_1_1CompactionJobInfo.html#a8d54f1c4b1aee7a12c32fd7beab9f1ef", null ],
[ "base_input_level", "structrocksdb_1_1CompactionJobInfo.html#a5e023143a01c181a17dbd3b80181fba5", null ],
[ "cf_name", "structrocksdb_1_1CompactionJobInfo.html#aacbd3037dd53ade1bd7bca97e8268e39", null ],
[ "compaction_reason", "structrocksdb_1_1CompactionJobInfo.html#a55ed52084f36f0456a21794c2d9ba547", null ],
[ "input_files", "structrocksdb_1_1CompactionJobInfo.html#a159303c2316a367d7f55dc09fe255f25", null ],
[ "job_id", "structrocksdb_1_1CompactionJobInfo.html#ad5eb897de9c40c55dd7011d4ed4c0096", null ],
[ "output_files", "structrocksdb_1_1CompactionJobInfo.html#a0cf1e4c7357345baefbf384555692846", null ],
[ "output_level", "structrocksdb_1_1CompactionJobInfo.html#af018098d27ea7a3ec51850973510c253", null ],
[ "stats", "structrocksdb_1_1CompactionJobInfo.html#a393e4d0075f482bdcca653e308a67f64", null ],
[ "status", "structrocksdb_1_1CompactionJobInfo.html#a53eaaa3b53c9bf62b84d86d3c0a02399", null ],
[ "table_properties", "structrocksdb_1_1CompactionJobInfo.html#ad2afb3bdbf47e8a94a646bc51500f800", null ],
[ "thread_id", "structrocksdb_1_1CompactionJobInfo.html#a833d35256c54be979199c1af036f8f6d", null ]
]; |
var api = require('groupme').Stateless;
var botID = process.env.BOT_ID || -1;
var accessToken = process.env.ACCESS_TOKEN || -1;
var logger = require('./log.js');
const PAD_LENGTH = 25;
function _postMessage(message) {
var botResponse, options, body;
logger.info('Message sent');
api.Bots.post(accessToken, botID, message, {picture_url:""}, function(){});
}
module.exports = {
postMessage: _postMessage
};
|
/*
*
* SubmitRealWorldExample actions
*
*/
import {
DEFAULT_ACTION,
SUBMIT_RESOURCE,
SUBMISSION_COMPLETE,
SUBMISSION_ERROR,
} from './constants';
export function defaultAction() {
return {
type: DEFAULT_ACTION,
};
}
export function submitResource({url, title, description, captcha }) {
return {
type: SUBMIT_RESOURCE,
data: { url, title, description, captcha }
}
}
export function successfulSubmission() {
return {
type: SUBMISSION_COMPLETE
}
}
export function submissionError() {
return {
type: SUBMISSION_ERROR
}
}
|
const { knex } = require('../config/db');
const userType = require('../types/user');
class UserModel {
static list() {
return knex.from('user').whereNot('user.status', userType.DELETED);
}
static get(userId) {
return knex
.select('id', 'name', 'status')
.from('user')
.whereNot('user.status', userType.DELETED)
.where('user.id', userId)
.first();
}
static post(data) {
return knex.from('user').insert(data);
}
static put(userId, data) {
const query = knex.from('user');
if (data.name) {
query.update('name', data.name);
}
return query
.where('user.id', userId)
.whereNot('user.status', userType.DELETED);
}
static delete(userId) {
return knex
.from('user')
.where('user.id', userId)
.whereNot('user.status', userType.DELETED)
.update({
status: userType.DELETED,
deletedAt: knex.raw('NOW()'),
});
}
}
module.exports = UserModel;
|
describe("toHaveBeenCalled", function() {
it("passes when the actual was called, with a custom .not fail message", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalled(),
calledSpy = jasmineUnderTest.createSpy('called-spy'),
result;
calledSpy();
result = matcher.compare(calledSpy);
expect(result.pass).toBe(true);
expect(result.message).toEqual("Expected spy called-spy not to have been called.");
});
it("fails when the actual was not called", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalled(),
uncalledSpy = jasmineUnderTest.createSpy('uncalled spy'),
result;
result = matcher.compare(uncalledSpy);
expect(result.pass).toBe(false);
});
it("throws an exception when the actual is not a spy", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalled(),
fn = function() {};
expect(function() { matcher.compare(fn) }).toThrow(new Error("Expected a spy, but got Function."));
});
it("throws an exception when invoked with any arguments", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalled(),
spy = jasmineUnderTest.createSpy('sample spy');
expect(function() { matcher.compare(spy, 'foo') }).toThrow(new Error("toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith"));
});
it("has a custom message on failure", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalled(),
spy = jasmineUnderTest.createSpy('sample-spy'),
result;
result = matcher.compare(spy);
expect(result.message).toEqual("Expected spy sample-spy to have been called.");
});
});
|
/**
* A simple Chartist plugin to put labels on top of bar charts.
*
* Copyright (c) 2015 Yorkshire Interactive (yorkshireinteractive.com)
*
* 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.
*/
(function(window, document, Chartist) {
'use strict';
var defaultOptions = {
// The class name so you can style the text
labelClass: 'ct-bar-label',
// Use this to get the text of the data and you can return your own
// formatted text. For example, for a percentage:
// {
// labelInterpolationFnc: function (text) { return text + '%' }
// }
labelInterpolationFnc: Chartist.noop,
// Depending on your font size you may need to tweak these
labelOffset: {
x: 0,
y: 0
},
// If labelOffset doesn't work for you and you need more custom positioning
// you can use this. You can set position.x and position.y to functions and
// instead of centering + labelOffset. This will _completely_ override the
// built in positioning so labelOffset will no longer do anything. It will
// pass the bar `data` back as the first param.
//
// Example:
// Chartist.plugins.ctBarLabels({
// position: {
// x: function (data) {
// return data.x1 + 50; // align left with 50px of padding
// }
// }
// });
position: {
x: null,
y: null
}
};
Chartist.plugins = Chartist.plugins || {};
Chartist.plugins.ctBarLabels = function(options) {
options = Chartist.extend({}, defaultOptions, options);
var positionX = options.position.x || function (data) {
return ((data.x1 + data.x2) / 2) + options.labelOffset.x;
};
var positionY = options.position.y || function (data) {
return ((data.y1 + data.y2) / 2) + options.labelOffset.y;
};
return function ctBarLabels(chart) {
// Since it's specific to bars, verify its a bar chart
if(chart instanceof Chartist.Bar) {
chart.on('draw', function(data) {
// If the data we're drawing is the actual bar, let's add the text
// inside of it
if(data.type === 'bar') {
data.group.elem('text', {
// This gets the middle point of the bars and then adds the
// optional offset to them
x: positionX(data),
y: positionY(data),
style: 'text-anchor: middle'
}, options.labelClass)
.text(
options.labelInterpolationFnc(
// If there's not x (horizontal bars) there must be a y
data.value.x || data.value.y
)
);
}
});
}
};
};
}(window, document, Chartist)); |
import React, { Component } from "react"
import { Link } from "gatsby"
import Img from "gatsby-image"
import hex2rgba from "hex2rgba"
import { style } from "glamor"
import styles from "../shared/styles"
import MdArrowForward from "react-icons/lib/md/arrow-forward"
import ShowcaseItemCategories from "./showcase-item-categories"
import FeaturedSitesIcon from "../../assets/featured-sites-icons.svg"
import { ShowcaseIcon } from "../../assets/mobile-nav-icons"
import URLQuery from "../../components/url-query"
import { options, rhythm, scale } from "../../utils/typography"
import presets, { colors } from "../../utils/presets"
import scrollToAnchor from "../../utils/scroll-to-anchor"
class FeaturedSites extends Component {
onClickHandler = (target, updateQuery, filter) =>
target.current
? scrollToAnchor(target.current, () => {
updateQuery(({ filters }) => {
return { filters: [filter] }
})
})
: () => {}
render = () => {
const { featured, showcase } = this.props
return (
<section
className="featured-sites"
css={{
margin: `${rhythm(options.blockMarginBottom)} ${rhythm(3 / 4)} 0`,
position: `relative`,
display: `none`,
[presets.Desktop]: {
display: `block`,
},
}}
>
<div
css={{
background: `url(${FeaturedSitesIcon})`,
backgroundRepeat: `no-repeat`,
backgroundSize: `contain`,
position: `absolute`,
height: `100%`,
width: `100%`,
left: -100,
opacity: 0.02,
top: 0,
zIndex: -1,
}}
/>
<div
css={{
marginBottom: rhythm(options.blockMarginBottom * 2),
display: `flex`,
alignItems: `center`,
flexWrap: `wrap`,
}}
>
<img src={FeaturedSitesIcon} alt="icon" css={{ marginBottom: 0 }} />
<h1
css={{
...scale(1 / 5),
color: colors.gatsby,
fontFamily: options.headerFontFamily.join(`,`),
fontWeight: `bold`,
marginRight: 30,
marginLeft: 15,
marginTop: 0,
marginBottom: 0,
}}
>
Featured Sites
</h1>
<URLQuery>
{(_, updateQuery) => (
<a
href="#showcase"
{...styles.withTitleHover}
css={{
display: `none`,
[presets.Phablet]: {
display: `block`,
},
"&&": {
...scale(-1 / 6),
boxShadow: `none`,
borderBottom: 0,
color: colors.lilac,
cursor: `pointer`,
fontFamily: options.headerFontFamily.join(`,`),
fontWeight: `normal`,
"&:hover": {
background: `transparent`,
color: colors.gatsby,
},
},
}}
onClick={this.onClickHandler(showcase, updateQuery, `Featured`)}
>
<span className="title">View all</span>
<MdArrowForward
style={{ marginLeft: 4, verticalAlign: `sub` }}
/>
</a>
)}
</URLQuery>
<div
css={{
display: `flex`,
alignItems: `center`,
marginLeft: `auto`,
}}
>
<div
css={{
...scale(-1 / 6),
color: colors.gray.calm,
marginRight: 15,
fontFamily: options.headerFontFamily.join(`,`),
display: `none`,
[presets.Tablet]: {
display: `block`,
},
}}
>
Want to get featured?
</div>
<a
href="https://next.gatsbyjs.org/docs/site-showcase-submissions/"
target="_blank"
rel="noopener noreferrer"
css={{ ...styles.button }}
>
Submit
{` `}
<span
css={{
display: `none`,
[presets.Desktop]: {
display: `inline`,
},
}}
>
your
{` `}
</span>
Site
<MdArrowForward style={{ marginLeft: 4, verticalAlign: `sub` }} />
</a>
</div>
</div>
<div
css={{
position: `relative`,
}}
>
<div
css={{
display: `flex`,
overflowX: `scroll`,
flexShrink: 0,
margin: `0 -${rhythm(3 / 4)}`,
padding: `3px ${rhythm(3 / 4)} 0`,
...styles.scrollbar,
}}
>
{featured.slice(0, 9).map(({ node }) => (
<div
key={node.id}
{...styles.featuredSitesCard}
{...styles.withTitleHover}
>
<Link
css={{
"&&": {
borderBottom: `none`,
boxShadow: `none`,
transition: `box-shadow .3s cubic-bezier(.4,0,.2,1), transform .3s cubic-bezier(.4,0,.2,1)`,
"&:hover": { ...styles.screenshotHover },
},
}}
to={node.fields.slug}
state={{ isModal: true }}
>
{node.childScreenshot && (
<Img
sizes={
node.childScreenshot.screenshotFile.childImageSharp
.sizes
}
alt={node.title}
css={{ ...styles.screenshot }}
/>
)}
<div>
<span className="title">{node.title}</span>
</div>
</Link>
<div
css={{
...scale(-1 / 6),
color: colors.gray.calm,
fontWeight: `normal`,
[presets.Desktop]: {
marginTop: `auto`,
},
}}
>
{node.built_by && (
<div
css={{
fontFamily: options.headerFontFamily.join(`,`),
}}
>
Built by {node.built_by}
</div>
)}
<ShowcaseItemCategories
categories={node.categories}
onClickHandler={this.onClickHandler}
showcase={showcase}
/>
</div>
</div>
))}
<div
css={{
display: `flex`,
}}
>
<URLQuery>
{(_, updateQuery) => (
<a
href="#showcase"
{...styles.featuredSitesCard}
css={{
marginRight: `${rhythm(3 / 4)} !important`,
border: `1px solid ${hex2rgba(colors.lilac, 0.2)}`,
borderRadius: presets.radius,
textAlign: `center`,
"&&": {
boxShadow: `none`,
transition: `all ${presets.animation.speedDefault} ${
presets.animation.curveDefault
}`,
"&:hover": {
backgroundColor: hex2rgba(colors.ui.light, 0.25),
transform: `translateY(-3px)`,
boxShadow: `0 8px 20px ${hex2rgba(
colors.lilac,
0.5
)}`,
},
},
}}
onClick={this.onClickHandler(
showcase,
updateQuery,
`Featured`
)}
>
<div
css={{
margin: rhythm(1),
background: colors.ui.whisper,
display: `flex`,
alignItems: `center`,
position: `relative`,
flexBasis: `100%`,
}}
>
<img
src={ShowcaseIcon}
css={{
position: `absolute`,
height: `100%`,
width: `auto`,
display: `block`,
margin: `0`,
opacity: 0.04,
}}
alt=""
/>
<span
css={{
margin: `0 auto`,
color: colors.gatsby,
}}
>
<img
src={ShowcaseIcon}
css={{
height: 44,
width: `auto`,
display: `block`,
margin: `0 auto ${rhythm(
options.blockMarginBottom
)}`,
[presets.Tablet]: {
height: 64,
},
[presets.Hd]: {
height: 72,
},
}}
alt=""
/>
View all Featured Sites
</span>
</div>
</a>
)}
</URLQuery>
</div>
</div>
<div
css={{
position: `absolute`,
top: `0`,
bottom: rhythm(options.blockMarginBottom),
right: `-${rhythm(3 / 4)}`,
width: 60,
pointerEvents: `none`,
background: `linear-gradient(90deg, rgba(0,0,0,0) 0%, rgba(255,255,255,1) 100%)`,
}}
/>
</div>
</section>
)
}
}
export default FeaturedSites
|
const snekfetch = require('snekfetch');
exports.run = (client, msg, args) => {
let [title, contents] = args.join(" ").split("|");
if(!contents) {
[title, contents] = ["Achievement Get!", title];
}
let rnd = Math.floor((Math.random() * 39) + 1);
if(args.join(" ").toLowerCase().includes("burn")) rnd = 38;
if(args.join(" ").toLowerCase().includes("cookie")) rnd = 21;
if(args.join(" ").toLowerCase().includes("cake")) rnd = 10;
if(title.length > 22 || contents.length > 22) return msg.edit("Max Length: 22 Characters. Soz.").then(msg.delete.bind(msg), 2000);
const url = `https://www.minecraftskinstealer.com/achievement/a.php?i=${rnd}&h=${encodeURIComponent(title)}&t=${encodeURIComponent(contents)}`;
snekfetch.get(url)
.then(r=>msg.channel.send("", {files:[{attachment: r.body}]}));
msg.delete();
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ["mca"]
};
exports.help = {
name: 'achievement',
description: 'Send a Minecraft Achievement image to the channel',
usage: 'achievement Title|Text (/achievement Achievement Get|Used a Command!)'
}; |
/**
* @module environment
* @description
* Update the given environment
*/
const properties = require('./properties');
const keywords = require('./keywords');
const validators = require('../validators');
const formats = require('./formats');
const { keys } = require('./uri');
const { transformation } = require('./schema');
const environmentConfig = {};
function add(version, config) {
environmentConfig[version] = config;
}
function use(version) {
if (!version || !environmentConfig[version]) {
return;
}
const patchEnvironment = environmentConfig[version];
patchEnvironment({
properties,
keywords,
validators,
formats,
keys,
transformation,
});
}
module.exports = {
add,
use,
};
|
require("./coverage");
describe("The user", function () {
afterEach(uploadCoverage);
it("should be able to open the list of suppliers", function () {
browser.get("");
element(by.css(".navigation-link")).click(); // Open the modal
element(by.css("a[ui-sref=suppliers]")).click(); // Click on the "suppliers" option
expect(element.all(by.css("table")).count()).toBe(1); // Check if the table exists
// Must exist five fields per supplier
expect(element.all(by.css("table tbody tr td.ng-binding")).then(
/**
* @param {{length}} elements
*/
(elements) => elements.length % 4
)).toBe(0);
});
it("should be able to open the details of a supplier", function () {
browser.get("#!/suppliers");
element.all(by.css("table tbody tr td.ng-binding")).first().click();
expect(element.all(by.css("table")).count()).toBe(0); // Check if the table is gone
expect(element.all(by.css(".ui-view [ng-controller]")).count()).toBe(1); // Check if the view was injected
// 13 fields must exist
expect(element.all(by.css(".column")).count()).toBe(16); // + 3 field divisions
expect(element.all(by.css("label")).count()).toBe(13);
expect(element.all(by.css("input")).count()).toBe(12);
expect(element.all(by.css("select")).count()).toBe(1);
// Test masks
expect(element(by.css("#cnpj")).getAttribute("value")).toMatch(/\d{2}\.\d{3}\.\d{3}\/0001-\d{2}/);
expect(element(by.css("#mobile")).getAttribute("value")).toMatch(/\(\d{3}\) \d \d{4}-\d{4}/);
expect(element(by.css("#phone")).getAttribute("value")).toMatch(/\(\d{3}\) \d{4}-\d{4}/);
expect(element(by.css("#cep")).getAttribute("value")).toMatch(/\d{5}-\d{3}/);
});
it("should be able to navigate to the details of a supplier", function () {
// Note: this supplier id is specified in the file "tests/webservice/database.json"
browser.get("#!/suppliers/1");
// 13 fields must exist
expect(element.all(by.css(".column")).count()).toBe(16); // + 3 field divisions
expect(element.all(by.css("label")).count()).toBe(13);
expect(element.all(by.css("input")).count()).toBe(12);
expect(element.all(by.css("select")).count()).toBe(1);
// Test masks
expect(element(by.css("#cnpj")).getAttribute("value")).toMatch(/\d{2}\.\d{3}\.\d{3}\/0001-\d{2}/);
expect(element(by.css("#mobile")).getAttribute("value")).toMatch(/\(\d{3}\) \d \d{4}-\d{4}/);
expect(element(by.css("#phone")).getAttribute("value")).toMatch(/\(\d{3}\) \d{4}-\d{4}/);
expect(element(by.css("#cep")).getAttribute("value")).toMatch(/\d{5}-\d{3}/);
});
it("should be able to see the view for supplier creation", function () {
browser.get("#!/suppliers");
expect(element.all(by.css("button-plus button")).count()).toBe(1);
element(by.css("button-plus button")).click();
expect(element.all(by.css("button-plus button")).count()).toBe(0);
expect(element.all(by.css("button-v button")).count()).toBe(1);
expect(element.all(by.css(".ui-view [ng-controller]")).count()).toBe(1); // Check if the view was injected
// 13 fields must exist
expect(element.all(by.css(".column")).count()).toBe(16); // + 3 field divisions
expect(element.all(by.css("label")).count()).toBe(13);
expect(element.all(by.css("input")).count()).toBe(12);
expect(element.all(by.css("select")).count()).toBe(1);
expect(element.all(by.css("select option")).count()).toBe(3);
// Test masks
let cpfInput = element(by.css("#cnpj"));
cpfInput.sendKeys("12345678000123");
expect(cpfInput.getAttribute("value")).toBe("12.345.678/0001-23");
let mobileInput = element(by.css("#mobile"));
mobileInput.sendKeys("123456789123");
expect(mobileInput.getAttribute("value")).toBe("(123) 4 5678-9123");
let phoneInput = element(by.css("#phone"));
phoneInput.sendKeys("12345678912");
expect(phoneInput.getAttribute("value")).toBe("(123) 4567-8912");
let cepInput = element(by.css("#cep"));
cepInput.sendKeys("12345678");
expect(cepInput.getAttribute("value")).toBe("12345-678");
});
}); |
var crypto = require('crypto');
var sodium = {};
exports.id = '3a';
// env-specific crypto methods
exports.crypt = function(lib)
{
sodium = lib;
}
exports.generate = function(){
var kp = sodium.crypto_box_keypair();
return Promise.resolve({key:kp.publicKey, secret:kp.secretKey})
}
exports.Local = function(pair){
var local = new exports._Local(pair)
this.err = local.err;
this.secret = local.secret;
this.load = Promise.resolve()
this.decrypt = function(body){
var decrypted = local.decrypt(body);
return (decrypted) ? Promise.resolve(local.decrypt(body)) : Promise.reject(new Error("cs3a local failed to decrypt"))
}
return this;
}
exports.Remote = function(key){
var remote = new exports._Remote(key)
this.token = remote.token;
this.load = Promise.resolve()
this.ephemeral = remote.ephemeral;
this.encrypt = function(a1, a2){
return Promise.resolve(remote.encrypt(a1, a2))
}
this.verify = function(a1, a2){
return Promise.resolve(remote.verify(a1,a2))
};
return this;
}
exports.Ephemeral = function(remote, body){
var ephemeral = new exports._Ephemeral(remote, body)
this.load = Promise.resolve()
this.token = ephemeral.token;
this.encrypt = function(body){
var encrypted = ephemeral.encrypt(body);
return (encrypted) ? Promise.resolve(encrypted) : Promise.reject(new Error("cs3a ephemeral encrypt failed"))
}
this.decrypt = function(body){
var decrypted = ephemeral.decrypt(body)
return (decrypted) ? Promise.resolve(decrypted) : Promise.reject(new Error("cs3a ephemeral decrypt failed"));
}
return this;
}
exports._Local = function(pair)
{
var self = this;
try{
if(!Buffer.isBuffer(pair.key) || pair.key.length != 32) throw new Error("invalid public key");
self.key = pair.key;
if(!Buffer.isBuffer(pair.secret) || pair.secret.length != 32) throw new Error("invalid secret key");
self.secret = pair.secret;
}catch(E){
self.err = E;
}
// decrypt message body and return the inner
self.decrypt = function(body){
if(!Buffer.isBuffer(body)) return false;
if(body.length < 32+24+16) return false;
var key = body.slice(0,32);
var nonce = body.slice(32,32+24);
var innerc = body.slice(32+24,body.length-16);
var secret = sodium.crypto_box_beforenm(key, self.secret);
// decipher the inner
var zeros = new Buffer(Array(sodium.crypto_secretbox_BOXZEROBYTES)); // add zeros for nacl's api
var inner = sodium.crypto_secretbox_open(Buffer.concat([zeros,innerc]),nonce,secret);
//console.log("SODIUM", inner)
return inner;
};
}
exports._Remote = function(key)
{
var self = this;
try{
if(!Buffer.isBuffer(key) || key.length != 32) throw new Error("invalid public key");
self.endpoint = key;
self.ephemeral = sodium.crypto_box_keypair();
self.token = crypto.createHash('sha256').update(self.ephemeral.publicKey.slice(0,16)).digest().slice(0,16);
}catch(E){
self.err = E;
}
// verifies the hmac on an incoming message body
self.verify = function(local, body){
if(!Buffer.isBuffer(body)) return false;
var mac1 = body.slice(body.length-16).toString("hex");
var nonce = body.slice(32,32+24);
var secret = sodium.crypto_box_beforenm(self.endpoint, local.secret);
var akey = crypto.createHash('sha256').update(Buffer.concat([nonce,secret])).digest();
var mac2 = sodium.crypto_onetimeauth(body.slice(0,body.length-16),akey).toString("hex");
if(mac2 != mac1) return false;
return true;
};
self.encrypt = function(local, inner){
if(!Buffer.isBuffer(inner)) return false;
// get the shared secret to create the iv+key for the open aes
var secret = sodium.crypto_box_beforenm(self.endpoint, self.ephemeral.secretKey);
var nonce = crypto.randomBytes(24);
// encrypt the inner, encode if needed
var innerc = sodium.crypto_secretbox(inner, nonce, secret);
innerc = innerc.slice(sodium.crypto_secretbox_BOXZEROBYTES); // remove zeros from nacl's api
var body = Buffer.concat([self.ephemeral.publicKey,nonce,innerc]);
// prepend the line public key and hmac it
var secret = sodium.crypto_box_beforenm(self.endpoint, local.secret);
var akey = crypto.createHash('sha256').update(Buffer.concat([nonce,secret])).digest();
var mac = sodium.crypto_onetimeauth(body,akey);
return Buffer.concat([body,mac]);
};
}
exports._Ephemeral = function(remote, body)
{
var self = this;
try{
// sender token
self.token = crypto.createHash('sha256').update(body.slice(0,16)).digest().slice(0,16);
// extract received ephemeral key
var key = body.slice(0,32);
var secret = sodium.crypto_box_beforenm(key, remote.ephemeral.secretKey);
self.encKey = crypto.createHash("sha256")
.update(secret)
.update(remote.ephemeral.publicKey)
.update(key)
.digest();
self.decKey = crypto.createHash("sha256")
.update(secret)
.update(key)
.update(remote.ephemeral.publicKey)
.digest();
}catch(E){
self.err = E;
}
self.decrypt = function(outer){
// decrypt body
var nonce = outer.slice(0,24);
var cbody = outer.slice(24);
var zeros = new Buffer(Array(sodium.crypto_secretbox_BOXZEROBYTES)); // add zeros for nacl's api
var body = sodium.crypto_secretbox_open(Buffer.concat([zeros,cbody]),nonce,self.decKey);
return body;
};
self.encrypt = function(inner){
// now encrypt the packet
var nonce = crypto.randomBytes(24);
var cbody = sodium.crypto_secretbox(inner, nonce, self.encKey);
cbody = cbody.slice(sodium.crypto_secretbox_BOXZEROBYTES); // remove zeros from nacl's api
// return final body
return Buffer.concat([nonce,cbody]);
};
}
|
const utils = require('../utils')
module.exports = () => {
return async (ctx, next) => {
await next()
const events = ctx.state.outgoingEvents
const client = ctx.clients.LINE
const results = await Promise.all(
events.map(async e => {
if (e.event === 'whoami') {
const userProfile = await client.getProfile(e.userId)
e.message = [
{
type: 'text',
text: `你的名字,${userProfile.displayName}`
},
{
type: 'text',
text: `和身分證字號,${e.userId}`
}
]
}
// TODO: Fix bad logic here!!!!
const carouselMessageIndex = Array.isArray(e.message) === true
? e.message.findIndex(m => m.type === 'carousel')
: e.message.type === 'carousel' ? 0 : -1
if (carouselMessageIndex !== -1 && Array.isArray(e.message) === true) {
e.message[carouselMessageIndex] = utils.carouselMessageFormatter(
e.message[carouselMessageIndex].altText,
e.message[carouselMessageIndex].cards
)
} else if (
Array.isArray(e.message) === false &&
e.message.type === 'carousel'
) {
e.message = utils.carouselMessageFormatter(
e.message.altText,
e.message.cards
)
}
if (e.message.type === 'button') {
e.message = utils.buttonMessageFormatter(
e.message.altText,
e.message.description,
e.message.actions,
e.message.title,
e.message.thumbnailURL
)
}
return replyUserAgent(client, e)
})
)
ctx.state.serviceResponses = [...ctx.state.serviceResponses, results]
ctx.body = {}
}
}
/**
* To handle the communication with LINE Message API server
* @param {Client} client - Client object of LINE API server
* @param {Object} event - The object describe the reply information
* @param {String} event.type - The deliver method for the event
* @param {String} event.target - The receiver id, maybe replyToken or userId
* @param {Object} event.message - The message object for this reply event
* @return {Object} - The response body from LINE API server
*/
async function replyUserAgent(client, event) {
try {
switch (event.type) {
case 'reply':
return await client.replyMessage(event.target, event.message)
case 'push':
return await client.pushMessage(event.target, event.message)
default:
throw new TypeError('Unknown handler for LINE client!')
}
} catch (errorResponse) {
if (errorResponse instanceof TypeError) {
throw errorResponse
}
// For other types of error, just pass it currently
return errorResponse
}
}
|
goog.provide('ngeo.mapDirective');
goog.require('goog.asserts');
goog.require('ngeo');
goog.require('ol.Map');
/**
* Provides a directive used to insert a user-defined OpenLayers
* map in the DOM. The directive does not create an isolate scope.
*
* Example:
*
* <div ngeo-map="ctrl.map"></div>
*
* See our live examples:
* {@link ../examples/permalink.html}
* {@link ../examples/simple.html}
*
* @htmlAttribute {ol.Map} ngeo-map The map.
* @return {angular.Directive} Directive Definition Object.
* @ngInject
* @ngdoc directive
* @ngname ngeoMap
*/
ngeo.mapDirective = function() {
return {
restrict: 'A',
link:
/**
* @param {angular.Scope} scope Scope.
* @param {angular.JQLite} element Element.
* @param {angular.Attributes} attrs Attributes.
*/
function(scope, element, attrs) {
var attr = 'ngeoMap';
var prop = attrs[attr];
var map = /** @type {ol.Map} */ (scope.$eval(prop));
goog.asserts.assertInstanceof(map, ol.Map);
map.setTarget(element[0]);
}
};
};
ngeo.module.directive('ngeoMap', ngeo.mapDirective);
|
var util = require("util");
var choreography = require("temboo/core/choreography");
/*
CreateIdentity
Create a new identity.
*/
var CreateIdentity = function(session) {
/*
Create a new instance of the CreateIdentity Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/SendGrid/NewsletterAPI/Identity/CreateIdentity"
CreateIdentity.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new CreateIdentityResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new CreateIdentityInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the CreateIdentity
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var CreateIdentityInputSet = function() {
CreateIdentityInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from SendGrid.)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APIUser input for this Choreo. ((required, string) The username registered with SendGrid. )
*/
this.set_APIUser = function(value) {
this.setInput("APIUser", value);
}
/*
Set the value of the Address input for this Choreo. ((required, string) The physical address to be used for this Identity.)
*/
this.set_Address = function(value) {
this.setInput("Address", value);
}
/*
Set the value of the City input for this Choreo. ((required, string) The city for this Identity.)
*/
this.set_City = function(value) {
this.setInput("City", value);
}
/*
Set the value of the Country input for this Choreo. ((required, string) The country to be associated with this Identity.)
*/
this.set_Country = function(value) {
this.setInput("Country", value);
}
/*
Set the value of the Email input for this Choreo. ((required, string) The email address to be used for this identity.)
*/
this.set_Email = function(value) {
this.setInput("Email", value);
}
/*
Set the value of the Identity input for this Choreo. ((required, string) The name for this identity.)
*/
this.set_Identity = function(value) {
this.setInput("Identity", value);
}
/*
Set the value of the Name input for this Choreo. ((required, string) Enter the name to be associated with this identity.)
*/
this.set_Name = function(value) {
this.setInput("Name", value);
}
/*
Set the value of the ReplyTo input for this Choreo. ((required, string) An email address to be used in the Reply-To field.)
*/
this.set_ReplyTo = function(value) {
this.setInput("ReplyTo", value);
}
/*
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid. Specify json, or xml. Default is set to json.)
*/
this.set_ResponseFormat = function(value) {
this.setInput("ResponseFormat", value);
}
/*
Set the value of the State input for this Choreo. ((required, string) The state to be associated with this Identity.)
*/
this.set_State = function(value) {
this.setInput("State", value);
}
/*
Set the value of the Zip input for this Choreo. ((required, integer) The zip code associated with this Identity.)
*/
this.set_Zip = function(value) {
this.setInput("Zip", value);
}
/*
Set the value of the VaultFile input for this Choreo. ()
*/
}
/*
A ResultSet with methods tailored to the values returned by the CreateIdentity Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var CreateIdentityResultSet = function(resultStream) {
CreateIdentityResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(CreateIdentity, choreography.Choreography);
util.inherits(CreateIdentityInputSet, choreography.InputSet);
util.inherits(CreateIdentityResultSet, choreography.ResultSet);
exports.CreateIdentity = CreateIdentity;
/*
DeleteIdentity
Delete an Identity.
*/
var DeleteIdentity = function(session) {
/*
Create a new instance of the DeleteIdentity Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/SendGrid/NewsletterAPI/Identity/DeleteIdentity"
DeleteIdentity.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new DeleteIdentityResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new DeleteIdentityInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the DeleteIdentity
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var DeleteIdentityInputSet = function() {
DeleteIdentityInputSet.super_.call(this);
/*
Set the value of the Response input for this Choreo. ((required, any) The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
*/
this.set_Response = function(value) {
this.setInput("Response", value);
}
/*
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from SendGrid.)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APIUser input for this Choreo. ((required, string) The username registered with SendGrid. )
*/
this.set_APIUser = function(value) {
this.setInput("APIUser", value);
}
/*
Set the value of the Identity input for this Choreo. ((required, string) The identity to be removed from your account.)
*/
this.set_Identity = function(value) {
this.setInput("Identity", value);
}
/*
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid. Specify json, or xml. Default is set to json.)
*/
this.set_ResponseFormat = function(value) {
this.setInput("ResponseFormat", value);
}
/*
Set the value of the VaultFile input for this Choreo. ()
*/
}
/*
A ResultSet with methods tailored to the values returned by the DeleteIdentity Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var DeleteIdentityResultSet = function(resultStream) {
DeleteIdentityResultSet.super_.call(this, resultStream);
}
util.inherits(DeleteIdentity, choreography.Choreography);
util.inherits(DeleteIdentityInputSet, choreography.InputSet);
util.inherits(DeleteIdentityResultSet, choreography.ResultSet);
exports.DeleteIdentity = DeleteIdentity;
/*
EditIdentity
Edit a newsletter identity.
*/
var EditIdentity = function(session) {
/*
Create a new instance of the EditIdentity Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/SendGrid/NewsletterAPI/Identity/EditIdentity"
EditIdentity.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new EditIdentityResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new EditIdentityInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the EditIdentity
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var EditIdentityInputSet = function() {
EditIdentityInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from SendGrid.)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APIUser input for this Choreo. ((required, string) The username registered with SendGrid. )
*/
this.set_APIUser = function(value) {
this.setInput("APIUser", value);
}
/*
Set the value of the Address input for this Choreo. ((required, string) The new physical address to be used for this Identity.)
*/
this.set_Address = function(value) {
this.setInput("Address", value);
}
/*
Set the value of the City input for this Choreo. ((required, string) The new city for this Identity.)
*/
this.set_City = function(value) {
this.setInput("City", value);
}
/*
Set the value of the Country input for this Choreo. ((required, string) The new country to be associated with this Identity.)
*/
this.set_Country = function(value) {
this.setInput("Country", value);
}
/*
Set the value of the Email input for this Choreo. ((required, string) An email address to be used for this identity.)
*/
this.set_Email = function(value) {
this.setInput("Email", value);
}
/*
Set the value of the Identity input for this Choreo. ((required, string) The identity that is to be edited.)
*/
this.set_Identity = function(value) {
this.setInput("Identity", value);
}
/*
Set the value of the Name input for this Choreo. ((required, string) The new name to be associated with this identity.)
*/
this.set_Name = function(value) {
this.setInput("Name", value);
}
/*
Set the value of the NewIdentity input for this Choreo. ((optional, string) The new name for this identity.)
*/
this.set_NewIdentity = function(value) {
this.setInput("NewIdentity", value);
}
/*
Set the value of the ReplyTo input for this Choreo. ((required, string) An email address to be used in the Reply-To field.)
*/
this.set_ReplyTo = function(value) {
this.setInput("ReplyTo", value);
}
/*
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid: Soecify json, or xml. Default is set to json.)
*/
this.set_ResponseFormat = function(value) {
this.setInput("ResponseFormat", value);
}
/*
Set the value of the State input for this Choreo. ((required, string) The state to be associated with this Identity.)
*/
this.set_State = function(value) {
this.setInput("State", value);
}
/*
Set the value of the Zip input for this Choreo. ((required, integer) The new zip code associated with this Identity.)
*/
this.set_Zip = function(value) {
this.setInput("Zip", value);
}
/*
Set the value of the VaultFile input for this Choreo. ()
*/
}
/*
A ResultSet with methods tailored to the values returned by the EditIdentity Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var EditIdentityResultSet = function(resultStream) {
EditIdentityResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(EditIdentity, choreography.Choreography);
util.inherits(EditIdentityInputSet, choreography.InputSet);
util.inherits(EditIdentityResultSet, choreography.ResultSet);
exports.EditIdentity = EditIdentity;
/*
GetIdentityInfo
Retrieve information about a specified Identity.
*/
var GetIdentityInfo = function(session) {
/*
Create a new instance of the GetIdentityInfo Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/SendGrid/NewsletterAPI/Identity/GetIdentityInfo"
GetIdentityInfo.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new GetIdentityInfoResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new GetIdentityInfoInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the GetIdentityInfo
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var GetIdentityInfoInputSet = function() {
GetIdentityInfoInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from SendGrid.)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APIUser input for this Choreo. ((required, string) The username registered with SendGrid. )
*/
this.set_APIUser = function(value) {
this.setInput("APIUser", value);
}
/*
Set the value of the Identity input for this Choreo. ((required, string) The identity for which info will be retrieved.)
*/
this.set_Identity = function(value) {
this.setInput("Identity", value);
}
/*
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid: Specify json, or xml. Default is set to json.)
*/
this.set_ResponseFormat = function(value) {
this.setInput("ResponseFormat", value);
}
/*
Set the value of the VaultFile input for this Choreo. ()
*/
}
/*
A ResultSet with methods tailored to the values returned by the GetIdentityInfo Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var GetIdentityInfoResultSet = function(resultStream) {
GetIdentityInfoResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(GetIdentityInfo, choreography.Choreography);
util.inherits(GetIdentityInfoInputSet, choreography.InputSet);
util.inherits(GetIdentityInfoResultSet, choreography.ResultSet);
exports.GetIdentityInfo = GetIdentityInfo;
/*
ListAllIdentities
Retrieve information about a specified Identity.
*/
var ListAllIdentities = function(session) {
/*
Create a new instance of the ListAllIdentities Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/SendGrid/NewsletterAPI/Identity/ListAllIdentities"
ListAllIdentities.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new ListAllIdentitiesResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new ListAllIdentitiesInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the ListAllIdentities
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var ListAllIdentitiesInputSet = function() {
ListAllIdentitiesInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from SendGrid.)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APIUser input for this Choreo. ((required, string) The username registered with SendGrid. )
*/
this.set_APIUser = function(value) {
this.setInput("APIUser", value);
}
/*
Set the value of the Identity input for this Choreo. ((optional, string) The identity for which info will be retrieved. Leave it empty to list all Identities in this account.)
*/
this.set_Identity = function(value) {
this.setInput("Identity", value);
}
/*
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid. Specify json, or xml. Default is set to json.)
*/
this.set_ResponseFormat = function(value) {
this.setInput("ResponseFormat", value);
}
/*
Set the value of the VaultFile input for this Choreo. ()
*/
}
/*
A ResultSet with methods tailored to the values returned by the ListAllIdentities Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var ListAllIdentitiesResultSet = function(resultStream) {
ListAllIdentitiesResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(ListAllIdentities, choreography.Choreography);
util.inherits(ListAllIdentitiesInputSet, choreography.InputSet);
util.inherits(ListAllIdentitiesResultSet, choreography.ResultSet);
exports.ListAllIdentities = ListAllIdentities;
/******************************************************************************
Begin output wrapper classes
******************************************************************************/
/**
* Utility function, to retrieve the array-type sub-item specified by the key from the parent (array) specified by the item.
* Returns an empty array if key is not present.
*/
function getSubArrayByKey(item, key) {
var val = item[key];
if(val == null) {
val = new Array();
}
return val;
}
|
'use strict';
var assert = require('assert');
var yaml = require('../../');
var DEPRECATED_BOOLEANS_SYNTAX = [
'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
];
it('Dumper should not take into account booleans syntax from YAML 1.0/1.1 in noCompatMode', function () {
DEPRECATED_BOOLEANS_SYNTAX.forEach(function (string) {
var dump = yaml.dump(string, { noCompatMode: true }).trim();
assert(
(dump === string),
('"' + string + '" string is not dumped as-is; actual dump: ' + dump)
);
});
});
|
// index.js
console.log('Hello, npm!'); |
"use strict";
/**
* Parses Command Arguments.
*
* @export
* @returns {IFacile}
*/
function parse() {
var ver = this._pkg.version;
return this;
}
exports.parse = parse;
//# sourceMappingURL=commands.js.map |
var expect = require("chai").expect;
var sinon = require("sinon");
var proxyquire = require("proxyquire");
var requestStub = sinon.stub();
var service = proxyquire("../lib/services/facebook.service", {
request: requestStub
});
var config = require("./../lib/config/services.config.json")['facebook'];
describe("Facebook service", function () {
var callbackSpy;
beforeEach(function() {
callbackSpy = sinon.spy();
});
afterEach(function() {
requestStub.reset();
});
it("should do GET http request to " + config, function () {
service(sinon.stub());
expect(requestStub.getCall(0).args[0].url).to.equal(config);
expect(requestStub.getCall(0).args[0].method).to.equal("GET");
expect(requestStub.getCall(0).args[0].headers["User-Agent"]).to.equal("request");
});
it('should call provided callback with message "Problem with the connection." in case of error', function (done) {
var responseBody = "foo";
//make fake `request` method call the second argument as a callback with specified arguments
requestStub.callsArgWithAsync(1, "error", null, responseBody);
service(callbackSpy);
setTimeout(function() {
expect(callbackSpy.calledOnce).to.equal(true);
expect(callbackSpy.getCall(0).args[0].message).to.equal("Problem with the connection.");
done();
}, 10);
});
it('should call provided callback with message "Could not parse the response." if body contains invalid JSON', function (done) {
var responseBody = "foo";
requestStub.callsArgWithAsync(1, null, null, responseBody);
service(callbackSpy);
setTimeout(function() {
expect(callbackSpy.calledOnce).to.equal(true);
expect(callbackSpy.getCall(0).args[0].message).to.equal("Could not parse the response.");
done();
}, 10);
});
it('should call provided callback with status true if response health is 1', function (done) {
var responseBody = {
current: {
health: 1,
subject: "Facebook Platform is Healthy",
},
};
requestStub.callsArgWithAsync(1, null, null, JSON.stringify(responseBody));
service(callbackSpy);
setTimeout(function() {
expect(callbackSpy.calledOnce).to.equal(true);
expect(callbackSpy.getCall(0).args[0].status).to.be.true;
done();
}, 10);
});
it('should call provided callback with status false if response health is not 1', function (done) {
var responseBody = {
current: {
health: 0,
subject: "Oh no! It doesn't work!",
},
};
requestStub.callsArgWithAsync(1, null, null, JSON.stringify(responseBody));
service(callbackSpy);
setTimeout(function() {
expect(callbackSpy.calledOnce).to.equal(true);
expect(callbackSpy.getCall(0).args[0].status).to.be.false;
done();
}, 10);
});
it('should call provided callback with message Facebook gives if health is 1', function (done) {
var responseBody = {
current: {
health: 1,
subject: "Facebook Platform is Healthy",
},
};
requestStub.callsArgWithAsync(1, null, null, JSON.stringify(responseBody));
service(callbackSpy);
setTimeout(function() {
expect(callbackSpy.calledOnce).to.equal(true);
expect(callbackSpy.getCall(0).args[0].message).to.equal(responseBody.current.subject);
done();
}, 10);
});
it('should call provided callback with message Facebook gives if health is not 1', function (done) {
var responseBody = {
current: {
health: 0,
subject: "Oh no! It doesn't work!",
},
};
requestStub.callsArgWithAsync(1, null, null, JSON.stringify(responseBody));
service(callbackSpy);
setTimeout(function() {
expect(callbackSpy.calledOnce).to.equal(true);
expect(callbackSpy.getCall(0).args[0].message).to.equal(responseBody.current.subject);
done();
}, 10);
});
it('should call provided callback with message "Empty response. Try Again." if resonse body is empty', function (done) {
requestStub.callsArgWithAsync(1, null, null, undefined);
service(callbackSpy);
setTimeout(function() {
expect(callbackSpy.calledOnce).to.equal(true);
expect(callbackSpy.getCall(0).args[0].message).to.equal("Empty response. Try Again.");
done();
}, 10);
});
});
|
// Static code to support GIS Feature CRUD
s3_gis_feature_crud = function(feature_type) {
if (feature_type === '') {
// Pass
} else if (feature_type == 1) {
// Point
// Hide the WKT input
$('#gis_location_wkt__row').hide();
$('#gis_location_wkt__row1').hide();
// Show the Lat/Lon inputs
$('#gis_location_lat__row').show();
$('#gis_location_lon__row').show();
$('#gis_location_lat__row1').show();
$('#gis_location_lon__row1').show();
} else {
// Hide the Lat/Lon inputs
$('#gis_location_lat__row').hide();
$('#gis_location_lon__row').hide();
$('#gis_location_lat__row1').hide();
$('#gis_location_lon__row1').hide();
// Show the WKT input
$('#gis_location_wkt__row').show();
$('#gis_location_wkt__row1').show();
if (feature_type == 2) {
// Line
if ($('#gis_location_wkt').val() === ''){
// Pre-populate the WKT field
$('#gis_location_wkt').val('LINESTRING( , , )');
}
} else if (feature_type == 3) {
// Polygon
if ($('#gis_location_wkt').val() === ''){
// Pre-populate the WKT field
$('#gis_location_wkt').val('POLYGON(( , , ))');
}
} else if (feature_type == 6) {
// Polygon
if ($('#gis_location_wkt').val() === ''){
// Pre-populate the WKT field
$('#gis_location_wkt').val('MULTIPOLYGON(( , , ))');
}
}
}
};
$(function() {
var feature_type = $('#gis_location_gis_feature_type').val();
s3_gis_feature_crud(feature_type);
// When the Type changes:
$('#gis_location_gis_feature_type').change(function() {
// What is the new type?
feature_type = $(this).val();
s3_gis_feature_crud(feature_type);
});
var level = $('#gis_location_level').val();
if (level) {
//If the Location is a Admin Boundary then Street Address makes no sense
$('#gis_location_addr_street__row').hide();
$('#gis_location_addr_street__row1').hide();
$('#gis_location_addr_postcode__row').hide();
$('#gis_location_addr_postcode__row1').hide();
// If the Location is a Country then Parent makes no sense
if (level == 'L0') {
$('#gis_location_parent__row').hide();
}
}
// When the Level changes:
$('#gis_location_level').change(function() {
// What is the new type?
var level = $(this).val();
if (level) {
// If the Location is a Admin Boundary then Street Address makes no sense
$('#gis_location_addr_street__row').hide();
$('#gis_location_addr_street__row1').hide();
$('#gis_location_addr_postcode__row').hide();
$('#gis_location_addr_postcode__row1').hide();
if (level == 'L0') {
// If the Location is a Country then Parent makes no sense
$('#gis_location_parent__row').hide();
$('#gis_location_parent__row1').hide();
$('#gis_location_parent').val('');
} else {
$('#gis_location_parent__row').show();
$('#gis_location_parent__row1').show();
}
} else {
$('#gis_location_addr_street__row').show();
$('#gis_location_addr_street__row1').show();
$('#gis_location_addr_postcode__row').show();
$('#gis_location_addr_postcode__row1').show();
$('#gis_location_parent__row').show();
$('#gis_location_parent__row1').show();
}
});
}); |
'use strict';
require('./_contact.scss');
module.exports = {
template: require('./contact.html'),
controller: ['$log', '$location', ContactController],
controllerAs: 'contactCtrl'
}
function ContactController($log, $location){
$log.log('ContactController()');
}
|
var PLAYER = {};
PLAYER.ticksPerBeat = 1200;
//PLAYER.delay0 = 1;
PLAYER.delay0 = 0.0;
PLAYER.isPlaying = false;
PLAYER.distPerSec = 0.2;
PLAYER.graphics = null;
PLAYER.scene = null;
PLAYER.graphicsScale = null;
PLAYER.muted = {};
PLAYER.midiObj = null;
PLAYER.loadedInstruments = {};
PLAYER.lastEventPlayTime = 0;
PLAYER.lastEventClockTime = 0;
PLAYER.seqNum = 0;
PLAYER.graphicsX0 = -8;
PLAYER.graphicsSpiral = true;
PLAYER.crankFactor = 0;
PLAYER.crankAngle0 = null;
PLAYER.crankAngle = null;
PLAYER.instruments = {};
PLAYER.USE_NEW_METHOD = true;
//PLAYER.tracks = {}
PLAYER.startPlaying = function()
{
report("startPlaying");
if (PLAYER.midiObj == null) {
report("No midi loaded");
return;
}
$("#midiTogglePlaying").text("Pause");
PLAYER.crankAngle0 = PLAYER.crankAngle;
PLAYER.setupInstruments();
PLAYER.playSync(PLAYER.midiObj);
}
PLAYER.pausePlaying = function()
{
report("Pause Playing");
PLAYER.isPlaying = false;
PLAYER.setPlayTime(PLAYER.getPlayTime());
$("#midiTogglePlaying").text("Play");
}
PLAYER.stopPlaying = PLAYER.pausePlaying;
PLAYER.rewind = function()
{
report("rewind");
PLAYER.i = 0;
PLAYER.setPlayTime(0);
PLAYER.crankAngle0 = PLAYER.crankAngle;
}
PLAYER.togglePlaying = function()
{ if ($("#midiTogglePlaying").text() == "Play") {
PLAYER.startPlaying();
}
else {
PLAYER.pausePlaying();
}
}
PLAYER.playMelody = function(name)
{
var melodyUrl = "midi/"+name+".json";
PLAYER.stopPlaying();
$.getJSON(melodyUrl, function(obj) { PLAYER.playMidiObj(obj) });
}
PLAYER.fmt = function(t) { return ""+Math.floor(t*1000)/1000; }
PLAYER.playMidiObj = function(obj)
{
PLAYER.midiObj = processMidiObj(obj);
//TODO: make this really wait until instruments are loaded.
PLAYER.i = 0;
PLAYER.setPlayTime(0);
//PLAYER.startPlaying();
if (PLAYER.scene) {
report("***** adding Note Graphics ******");
PLAYER.addNoteGraphics(PLAYER.scene, PLAYER.midiObj);
}
else {
report("***** No registered scene so not adding Note Graphics ******");
}
}
/*
This takes a midiObj as returned by JSON and figures out what
instruments are requred, and also arranges a sequence of events
grouped by times.
*/
function processMidiObj(midiObj)
{
report("processMidiObj");
if (midiObj.type != "MidiObj") {
report("midiObj has unexpected type "+midiObj.type);
}
var tracks = midiObj.tracks;
var ntracks = tracks.length;
report("num tracks "+ntracks);
report("Now merging "+ntracks+" tracks.");
seqTimes = [];
seqEvents = {};
PLAYER.trackChannels = {}; // These are 'global' tracks which
// arise from a given channel of a
// midi track
PLAYER.instruments = {};
for (var i=0; i<tracks.length; i++) {
var track = tracks[i];
var ntchs = 0;
if (track.numNotes === 0)
continue;
if (track.channels) {
for (var k=0; k<track.channels.length; k++) {
var ch = track.channels[k];
var gch = ch; // global channel assignment
//var tchName = "T"+i+"."+k+"_"+ch;
var tchName = "T"+i+"_"+ch+"_"+gch;
report(">>>>>> tch: "+tchName+" "+gch);
PLAYER.trackChannels[tchName] = {'id': tchName,
'channel': ch,
'track': track};
ntchs++;
}
}
if (ntchs == 0) {
// No channels were assigned - we will use 0
var ch = 0;
var gch = 0; //
var tchName = "T"+i+"_"+ch+"_"+gch;
PLAYER.trackChannels[tchName] = {'id': tchName,
'channel': ch,
'track': track};
}
if (track.instrument != undefined) {
//PLAYER.instruments[track.instrument] = 1;
PLAYER.instruments[track.instrument] = 0;
}
else {
//PLAYER.instruments[0] = 1;
PLAYER.instruments[0] = 0;
}
if (track.instruments) {
for (var k=0; k<PLAYER.instruments.length; k++) {
var inst = PLAYER.instruments[k];
PLAYER.instruments[inst] = 1;
}
}
var evGroups = track.seq;
for (var j=0; j<evGroups.length; j++) {
var evGroup = evGroups[j];
var t0 = evGroup[0];
var evs = evGroup[1];
for (var k=0; k<evs.length; k++) {
var ev = evs[k];
ev.track = i;
if (ev[0] == "programChange") {
var ch = ev[2];
var gch = ch;
var inst = ev[3];
var tchName = "T"+i+"_"+ch+"_"+gch;
report(">> "+tchName);
PLAYER.trackChannels[tchName].instrument = inst;
}
//report("ev: "+JSON.stringify(ev)+" "+ev.track);
if (seqEvents[t0]) {
seqEvents[t0][1].push(ev);
}
else {
seqEvents[t0] = [t0, [ev]];
seqTimes.push(t0);
}
}
}
}
seqTimes.sort(function(a,b) { return a-b; });
var seq = []
var maxTime = 0;
for (var i=0; i<seqTimes.length; i++) {
var t = seqTimes[i];
var evGroup = seqEvents[t];
seq.push([t, evGroup[1]]);
maxTime = t;//
//report("t: "+ t+ " nevents: "+evGroup.length);
}
midiObj.seq = seq;
midiObj.duration = maxTime/PLAYER.ticksPerBeat;
PLAYER.loadInstruments();
try {
PLAYER.setupTrackInfo();
}
catch (e) {
report("err: "+e);
}
return midiObj;
// return midiObj.tracks[ntracks-1];
}
/*
This version starts a series of callbacks for each time
that events must be started. There is one callback for
each time that one or more new notes are played.
*/
PLAYER.playSync = function(obj)
{
report("playSync");
PLAYER.seqNum += 1;
//PLAYER.i = 0;
PLAYER.delay0 = 0;
PLAYER.events = obj.seq;
PLAYER.isPlaying = true;
//PLAYER.lastEventPlayTime = 0;
//PLAYER.lastEventClockTime = Date.now()/1000.0;
if (!PLAYER.USE_NEW_METHOD) {
setTimeout(function() {
PLAYER.playNextStep(PLAYER.seqNum)}, 0);
}
}
PLAYER.getPlayTime = function()
{
if (PLAYER.crankFactor && PLAYER.crankAngle) {
if (PLAYER.crankAngle0 == null)
PLAYER.crankAngle0 = PLAYER.crankAngle;
return PLAYER.crankFactor*(PLAYER.crankAngle-PLAYER.crankAngle0);
}
var ct = Date.now()/1000.0;
if (PLAYER.isPlaying) {
var t = PLAYER.lastEventPlayTime + (ct - PLAYER.lastEventClockTime);
return t;
}
else {
PLAYER.lastEventClockTime = ct;
return PLAYER.lastEventPlayTime;
}
}
PLAYER.setPlayTime = function(t)
{
report("setPlayTime t: "+t);
PLAYER.lastEventPlayTime = t;
PLAYER.lastEventClockTime = Date.now()/1000.0;
//TODO: should set PLAYER.i to appopriate place...
}
//
// THis works and is self scheduling...
PLAYER.playNextStep = function(seqNum)
{
//report("playNextStep "+PLAYER.i);
if (!PLAYER.isPlaying) {
report("player stopped!");
return;
}
if (seqNum != PLAYER.seqNum) {
report("***** old sequence detected - dropping it *****");
return
}
var evGroup = PLAYER.events[PLAYER.i];
var t0 = evGroup[0];
var pt = t0/PLAYER.ticksPerBeat;
PLAYER.lastEventPlayTime = pt;
PLAYER.lastEventClockTime = Date.now()/1000.0;
PLAYER.handleEventGroup(evGroup);
PLAYER.i += 1;
if (PLAYER.i >= PLAYER.events.length) {
report("FInished playing");
PLAYER.isPlaying = false;
PLAYER.stopPlaying();
return;
}
var t1 = PLAYER.events[PLAYER.i][0];
var dt = (t1-t0)/PLAYER.ticksPerBeat;
setTimeout(function() {
PLAYER.playNextStep(seqNum)}, dt*1000);
}
//
PLAYER.checkForEvent = function()
{
//report("playNextStep "+PLAYER.i);
if (!PLAYER.isPlaying) {
report("player stopped!");
return;
}
var pt = PLAYER.getPlayTime();
var evGroup = PLAYER.events[PLAYER.i];
var nextT0 = evGroup[0];
var nextPt = nextT0/PLAYER.ticksPerBeat;
if (pt < nextPt)
{
if (PLAYER.i > 0) {
var evGroup = PLAYER.events[PLAYER.i-1];
var prevT0 = evGroup[0];
var prevPt = prevT0/PLAYER.ticksPerBeat;
if (pt > prevPt)
return;
PLAYER.lastEventPlayTime = pt;
PLAYER.lastEventClockTime = Date.now()/1000.0;
PLAYER.handleEventGroup(evGroup);
PLAYER.i -= 1;
if (PLAYER.i < 0)
PLAYER.i = 0;
}
return;
}
PLAYER.lastEventPlayTime = pt;
PLAYER.lastEventClockTime = Date.now()/1000.0;
PLAYER.handleEventGroup(evGroup);
PLAYER.i += 1;
if (PLAYER.i >= PLAYER.events.length) {
report("FInished playing");
PLAYER.isPlaying = false;
PLAYER.stopPlaying();
return;
}
}
PLAYER.handleEventGroup = function(eventGroup)
{
var t0 = eventGroup[0];
var notes = eventGroup[1];
for (var k=0; k<notes.length; k++) {
// if (maxNumNotes && i > maxNumNotes)
// break;
var note = notes[k];
if (PLAYER.muted[note.track])
continue;
/*
var channel = PLAYER.trackChannels[note.track];
var etype = note[0];
var t0_ = note[1];
var pitch = note[2];
var v = note[3];
var dur = note[4]/PLAYER.ticksPerBeat;
*/
var etype = note[0];
var t0_ = note[1];
var t = 0;
if (etype == "tempo") {
report("tempo");
continue;
}
var channel = note[2];
if (etype == "programChange") {
var inst = note[3];
report("programChange ch: "+channel+" inst: "+inst);
//MIDI.programChange(channel, inst);
PLAYER.programChange(note.track, channel, inst);
continue;
}
var pitch = note[3];
var v = note[4];
var dur = note[5]/PLAYER.ticksPerBeat;
if (etype != "note") {
report("*** unexpected etype: "+etype);
}
if (t0_ != t0) {
report("*** mismatch t0: "+t0+" t0_: "+t0_);
}
/*
if (channel != 0) {
report("channel "+channel+" -> 0");
channel = 0;
}
*/
//report(""+t0+" note channel: "+channel+" pitch: "+pitch+" v:"+v+" dur: "+dur);
MIDI.noteOn(channel, pitch, v, t+PLAYER.delay0);
MIDI.noteOff(channel, pitch, v, t+dur+PLAYER.delay0);
}
}
PLAYER.programChange = function(trackNo, ch, inst)
{
MIDI.programChange(ch, inst);
try {
var selName = "selectT"+trackNo+"_"+ch+"_"+ch;
report("programChange sel: "+selName+" "+inst);
$("#"+selName).val(inst);
}
catch (e) {
report("err: "+e);
}
}
/*
PLAYER.setupChannels = function(instruments)
{
if (!instruments)
instruments = PLAYER.instruments;
report("setupChannels "+JSON.stringify(instruments));
for (var chNo in instruments) {
var inst = instruments[chNo];
report("ch "+chNo+" instrument: "+inst);
if (PLAYER.loadedInstruments[inst]) {
report("instrument already loaded "+inst);
}
PLAYER.setupChannel(chNo, inst);
}
}
*/
var instMap = {
0: "acoustic_grand_piano",
1: "violin",
2: "harpsichord",
3: "voice_oohs",
4: "steel_drun",
5: "choir_aahs",
6: "paradiddle",
7: "pad_3_polysynth",
};
instMap = {};
PLAYER.getInstName = function(inst)
{
if (typeof inst == typeof "str")
return inst;
if (instMap[inst])
return instMap[inst];
return inst;
}
PLAYER.setupInstruments = function()
{
report("setupInstruments");
for (var tchName in PLAYER.trackChannels) {
tch = PLAYER.trackChannels[tchName];
if (tch.instrument) {
PLAYER.programChange(tch.channel, tch.instrument)
}
}
}
PLAYER.loadInstruments = function(successFn)
{
report("loadInstruments "+JSON.stringify(PLAYER.instruments));
var instruments = [];
for (var id in PLAYER.instruments) {
var instObj = MIDI.GM.byId[id];
instruments.push(instObj.id);
}
report("instruments: "+instruments);
MIDI.loadPlugin({
soundfontUrl: "./soundfont/",
instruments: instruments,
onprogress:function(state,progress){
MIDI.loader.setValue(progress*100);
},
onprogress: function(state,progress)
{
if (MIDI.loader)
MIDI.loader.setValue(progress*100);
},
onsuccess: function()
{
report("** finished with loading instruments");
for (var i=0; i<instruments.length; i++) {
var inst = instruments[i];
report("loaded "+inst);
PLAYER.loadedInstruments[inst] = true;
}
if (successFn)
successFn();
}
});
}
PLAYER.setupChannel = function(chNo, inst, successFn)
{
var instName = PLAYER.getInstName(inst);
report("setupInstrument chNo: "+chNo+" inst: "+inst+" name: "+instName);
instrument = instName;
MIDI.loadPlugin({
soundfontUrl: "./soundfont/",
instrument: instName,
onprogress:function(state,progress){
MIDI.loader.setValue(progress*100);
},
onprogress: function(state,progress)
{
if (MIDI.loader)
MIDI.loader.setValue(progress*100);
},
onsuccess: function()
{
PLAYER.loadedInstruments[instrument] = true;
MIDI.programChange(chNo, instrument);
if (successFn)
successFn();
}
});
}
/*
PLAYER.loadInstrument = function(instr, successFn)
{
report("loadInstrument "+instr);
PLAYER.setupChannel(0, instr, successFn);
}
*/
PLAYER.getTimeGraphicR = function()
{
var y0 = -6;
var x0 = PLAYER.graphicsX0;
var z0 = 0;
var gap = .2;
var w = .1;
var material = new THREE.MeshPhongMaterial( { color: 0xff0000 } );
var geometry = new THREE.BoxGeometry( 0.001, 300, w );
var g = new THREE.Mesh( geometry, material );
g._mat = material;
g.position.x = x0;
g.position.y = y0;
g.position.z = z0;
return g;
}
PLAYER.getNoteGraphicR = function(t, dur, pitch, material)
{
var y0 = -6;
var x0 = 0;//PLAYER.graphicsX0;
var z0 = 0;
var gap = .2;
var w = .1;
var h = PLAYER.distPerSec*dur;
material.color.setHSL((pitch%12)/12.0, .6, .5);
var geometry = new THREE.BoxGeometry( h, w, w );
var ng = new THREE.Mesh( geometry, material );
ng._mat = material;
ng.position.x = x0 + PLAYER.distPerSec*t + h/2;
ng.position.y = y0 + gap * pitch;
ng.position.z = z0;
return ng;
}
PLAYER.getTimeGraphicS = function()
{
var tDur = PLAYER.midiObj.duration;
var c = tDur*PLAYER.distPerSec;
var r = c / (2*Math.PI);
var y0 = 4;
var x0 = 0;//PLAYER.graphicsX0;
var z0 = 0;
var w = 10;
var material = new THREE.MeshPhongMaterial( { color: 0xff0000 } );
//var geometry = new THREE.BoxGeometry( 0.001, 300, w );
var geometry = new THREE.BoxGeometry( 0.01, 300, 2 );
var g = new THREE.Mesh( geometry, material );
g._mat = material;
material.transparent = true;
material.opacity = .3;
g.position.x = x0;
g.position.y = y0;
g.position.z = z0 + r;
report("**** getTimeGraphicS "+JSON.stringify(g.position));
return g;
}
PLAYER.getNoteGraphicS = function(t, dur, pitch, material)
{
var tDur = PLAYER.midiObj.duration;
var c = tDur*PLAYER.distPerSec;
var r = c / (2*Math.PI);
var y0 = 4;
var x0 = 0;//PLAYER.graphicsX0;
var z0 = 0;
var gap = .2;
var w = .1;
var h = PLAYER.distPerSec*dur;
material.color.setHSL((pitch%12)/12.0, .6, .5);
var geometry = new THREE.BoxGeometry( h, w, w );
var ng = new THREE.Mesh( geometry, material );
ng._mat = material;
var a = 2*Math.PI*(t+dur/2)/tDur;
var p = ng.position;
p.x = x0 + r*Math.sin(a);
p.z = z0 + r*Math.cos(a);
p.y = y0 + gap * pitch;
//report("getNoteGraphicS a: "+a+" r: "+r+" x: "+p.x+" y: "+p.y+" z: "+p.z);
ng.rotation.y = a;
return ng;
}
PLAYER.graphicsHandleEventGroup = function(gObj, eventGroup)
{
var t0 = eventGroup[0];
var notes = eventGroup[1];
for (var k=0; k<notes.length; k++) {
// if (maxNumNotes && i > maxNumNotes)
// break;
var note = notes[k];
var pitch = note[3];
var v = note[4];
var dur = note[5]/PLAYER.ticksPerBeat;
var t = t0/PLAYER.ticksPerBeat;
//report(t0+" graphic for note pitch: "+pitch+" v:"+v+" dur: "+dur);
var material = new THREE.MeshPhongMaterial( { color: 0x00dddd } );
var noteGraphic;
if (PLAYER.graphicsSpiral)
noteGraphic = PLAYER.getNoteGraphicS(t, dur, pitch, material);
else
noteGraphic = PLAYER.getNoteGraphicR(t, dur, pitch, material);
gObj.add( noteGraphic );
}
}
PLAYER.addNoteGraphics = function(scene, midiTrack)
{
if (PLAYER.graphics) {
scene.remove(PLAYER.graphics);
}
report("Adding note graphics...");
var events = midiTrack.seq;
PLAYER.graphics = new THREE.Object3D();
PLAYER.notesGraphic = new THREE.Object3D();
PLAYER.graphics.add(PLAYER.notesGraphic);
if (PLAYER.graphicsSpiral)
PLAYER.timeGraphic = PLAYER.getTimeGraphicS();
else
PLAYER.timeGraphic = PLAYER.getTimeGraphicR();
for (var i=0; i<events.length; i++) {
PLAYER.graphicsHandleEventGroup(PLAYER.notesGraphic, events[i]);
}
PLAYER.graphics.add(PLAYER.timeGraphic)
if (PLAYER.graphicsScale) {
var s = PLAYER.graphicsScale;
PLAYER.graphics.scale.x = s[0];
PLAYER.graphics.scale.y = s[1];
PLAYER.graphics.scale.z = s[2];
}
scene.add(PLAYER.graphics);
return PLAYER.graphics;
}
PLAYER.prevPt = null;
PLAYER.update = function()
{
if (PLAYER.isPlaying && PLAYER.USE_NEW_METHOD)
PLAYER.checkForEvent();
if (!PLAYER.graphics)
return;
clockTime = Date.now()/1000;
var pt = PLAYER.getPlayTime();
if (PLAYER.prevPt && pt < PLAYER.prevPt) {
report("**** pt < prevPt ****");
}
PLAYER.prevPt = pt;
$("#midiStatus").html("Time: "+PLAYER.fmt(pt));
if (PLAYER.graphicsSpiral) {
var a = 2*Math.PI*pt/PLAYER.midiObj.duration;
PLAYER.notesGraphic.rotation.y = -a;
}
else {
var x = PLAYER.graphicsX0 - pt*PLAYER.distPerSec;
PLAYER.notesGraphic.position.x = x;
}
}
//******************************************************************
// These have to do with the Web GUI for midi control
//
function muteCheckboxChanged(e)
{
report("muteCheckboxChanged")
var id = $(this).attr('id');
var i = id.lastIndexOf("_");
var ch = id.slice(i+1);
report("id: "+id+" ch: "+ch);
var val = $(this).is(":checked");
//var val = $("#"+mute_id).is(":checked");
val = eval(val);
report("mute_id: "+id+" ch: "+ch+" val: "+val);
PLAYER.muted[ch] = val;
}
function instrumentChanged(e)
{
report("instrumentChanged")
var id = $(this).attr('id');
var i = id.lastIndexOf("_");
var ch = id.slice(i+1);
var val = $(this).val();
val = eval(val);
//val = val - 1; // indices start at 0 but names start at 1
report("id: "+id+" ch: "+ch+" val: "+val);
PLAYER.setupChannel(ch, val);
}
PLAYER.compositionChanged = function(e)
{
var name = $(this).val();
report("compositionChanged: "+name);
PLAYER.playMelody(name);
}
PLAYER.setupMidiControlDiv = function()
{
report("setupMidiControlDiv");
if ($("#midiControl").length == 0) {
report("*** no midiControlDiv found ****");
}
str = '<div id="midiTrackInfo">\n' +
'No Tracks Loaded<br>\n' +
'</div>\n' +
'<button onclick="PLAYER.rewind()">|< </button>\n' +
'<button id="midiTogglePlaying" onclick="PLAYER.togglePlaying()">Play</button>\n' +
' <select id="midiCompositionSelection"></select>\n' +
' <span id="midiStatus" style="{width: 300px;}">No Midi Object</span>\n';
$("#midiControl").html(str);
//
report("*** adding compositions ");
var sel = $("#midiCompositionSelection");
sel.append($('<option>', { value: "None", text: "(None)"}));
for (var i=0; i<PLAYER.compositions.length; i++) {
var compName = PLAYER.compositions[i];
report("**** adding comp "+compName);
sel.append($('<option>', { value: compName, text: compName}));
}
sel.change(PLAYER.compositionChanged);
}
PLAYER.compositions = [
"chopin69",
"wtc0",
"beethovenSym5m1",
"shepard",
"BluesRhythm1",
"minute_waltz",
"jukebox",
"risset0",
"shimauta1",
"passac",
"DistantDrums",
"EarthandSky",
"silkroad",
"shores_of_persia",
"distdrums",
"cello2",
];
PLAYER.setupTrackInfo = function()
{
report("showTrackInfo");
report("trackChannels: "+JSON.stringify(PLAYER.trackChannels));
var d = $("#midiTrackInfo");
if (d.length == 0) {
report("**** No track info div found *****");
PLAYER.setupMidiControlDiv();
}
d.html("");
for (var tchName in PLAYER.trackChannels) {
var trackChannel = PLAYER.trackChannels[tchName];
var ch = trackChannel.channel;
report("Tchannel: "+tchName+" ch: "+ch);
var mute_id = "mute"+tchName;
var select_id = "select"+tchName;
var s = "track: "+tchName+" ";
report("mute_id: "+mute_id+" select_id: "+select_id);
s += 'mute: <input type="checkbox" id="MUTE_ID">\n';
s += ' ';
s += 'instrument: <select id="SELECT_ID"></select>\n'
s += '<br>\n';
s = s.replace("MUTE_ID", mute_id);
s = s.replace("SELECT_ID", select_id);
d.append(s);
var cb = $("#"+mute_id);
cb.change(muteCheckboxChanged)
var sel = $("#"+select_id);
for (var i=0; i<128; i++) {
var instObj = MIDI.GM.byId[i];
//var instName = (i+1)+" "+instObj.name;
var instName = i+" "+instObj.name;
//sel.append($('<option>', { value: i+1, text: instName}));
sel.append($('<option>', { value: i, text: instName}));
}
report("PLAYER.instruments[ch]: "+PLAYER.instruments[ch]);
var inst = trackChannel.instrument;
report("instrument: "+inst);
if (inst) {
sel.val(inst);
}
sel.change(instrumentChanged);
}
}
$(document).ready( function() {
PLAYER.setupTrackInfo();
});
|
'use strict';
module.exports = require('@esscorp/eslint').configs.backend;
|
import { expect } from 'chai';
import * as DateHelpers from '../../../imports/helpers/date';
import * as SubElements from '../../../imports/helpers/subElements';
import proxyquire from 'proxyquire';
import sinon from 'sinon';
import _ from 'underscore';
let MeetingSeriesSchema = {};
let Meteor = {
call: sinon.stub(),
callPromise: sinon.stub()
};
let Minutes = {};
let Topic = {};
let UserRoles = {};
let PromisedMethods = {};
let MinutesFinder = {
result: undefined,
lastMinutesOfMeetingSeries() {
return this.result;
}
};
DateHelpers['@noCallThru'] = true;
SubElements['@noCallThru'] = true;
const Random = {id: () => {}};
const jQuery = {};
const {
MeetingSeries
} = proxyquire('../../../imports/meetingseries', {
'meteor/meteor': { Meteor, '@noCallThru': true},
'meteor/random': { Random, '@noCallThru': true},
'meteor/jquery': { jQuery, '@noCallThru': true},
'./collections/meetingseries.schema': { MeetingSeriesSchema, '@noCallThru': true},
'./collections/meetingseries_private': { MeetingSeriesSchema, '@noCallThru': true},
'./helpers/promisedMethods': { PromisedMethods, '@noCallThru': true},
'./minutes': { Minutes, '@noCallThru': true},
'./topic': { Topic, '@noCallThru': true},
'./userroles': { UserRoles, '@noCallThru': true},
'/imports/helpers/date': DateHelpers,
'/imports/helpers/subElements': SubElements,
'meteor/underscore': { _, '@noCallThru': true},
'/imports/services/minutesFinder': { MinutesFinder, '@noCallThru': true}
});
describe('MeetingSeries', function () {
describe('#constructor', function () {
let meetingSeries;
beforeEach(function () {
meetingSeries = {
project: 'foo',
name: 'bar'
};
});
it('sets the project correctly', function () {
var ms = new MeetingSeries(meetingSeries);
expect(ms.project).to.equal(meetingSeries.project);
});
it('sets the name correctly', function () {
var ms = new MeetingSeries(meetingSeries);
expect(ms.name).to.equal(meetingSeries.name);
});
});
describe('#getMinimumAllowedDateForMinutes', function () {
let series;
beforeEach(function () {
series = new MeetingSeries();
});
afterEach(function () {
if (Minutes.hasOwnProperty("findAllIn")) {
delete Minutes.findAllIn;
}
});
function compareDates(actualDate, expectedDate) {
expect(actualDate.getYear(), "year mismatch").to.be.equal(expectedDate.getYear());
expect(actualDate.getMonth(), "month mismatch").to.be.equal(expectedDate.getMonth());
expect(actualDate.getDay(), "day mismatch").to.be.equal(expectedDate.getDay());
}
it('retrieves the date of the lastMinutes() if no id is given', function () {
let expectedDate = new Date();
MinutesFinder.result = {date: expectedDate};
var actualDate = series.getMinimumAllowedDateForMinutes();
compareDates(actualDate, expectedDate);
});
it('gets the date from the second to last minute if id of last minute is given', function () {
let lastMinuteId = "lastMinuteId",
expectedDate = new Date();
Minutes.findAllIn = sinon.stub().returns([{
_id: 'someid',
date: expectedDate
}, {
_id: lastMinuteId,
date: new Date(2013, 12, 11, 0, 0)
}]);
var actualDate = series.getMinimumAllowedDateForMinutes(lastMinuteId);
compareDates(actualDate, expectedDate);
});
it('gets the date from the last minute if id of second to last minute is given', function () {
let secondToLastMinuteId = "minuteId",
expectedDate = new Date();
Minutes.findAllIn = sinon.stub().returns([{
_id: secondToLastMinuteId,
date: new Date(2013, 12, 11, 0, 0)
}, {
_id: 'last minute',
date: expectedDate
}]);
var actualDate = series.getMinimumAllowedDateForMinutes(secondToLastMinuteId);
compareDates(actualDate, expectedDate);
});
});
describe('#save', function () {
let meetingSeries;
beforeEach(function () {
meetingSeries = new MeetingSeries({
project: 'foo',
name: 'bar'
});
});
it('calls the meteor method meetingseries.insert', function () {
meetingSeries.save();
expect(Meteor.callPromise.calledOnce).to.be.true;
});
it('sends the document to the meteor method meetingseries.insert', function () {
meetingSeries.save();
expect(Meteor.callPromise.calledWith('meetingseries.insert', meetingSeries)).to.be.true;
});
});
});
|
/**
* Created by bogdanbiv on 8/24/14.
*/
define([
'intern!object',
'intern/chai!assert',
'dojo/request',
'public/components/dojox/calendar/Calendar',
'public/demos/calendar/utils'
], function (registerSuite, assert, request, calendar, utils) {
alert(JSON.stringify(calendar));
registerSuite({
name: 'async demo',
'async test': function () {
/*var dfd = this.async(1000);*/
assert.strictEqual(JSON.stringify(calendar), "", "strings are strictly equal");
/* calendar.set("store", utils.createDefaultStore(calendar));*/
}
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:193e020858b961763caecc34b9e8f573f3990659ca52da8e2aa67ff56a6e5dd0
size 11945
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, Mustache */
/*unittests: FindReplace*/
/**
* Adds Find and Replace commands
*
* Originally based on the code in CodeMirror2/lib/util/search.js.
*/
define(function (require, exports, module) {
"use strict";
var CommandManager = require("command/CommandManager"),
KeyBindingManager = require("command/KeyBindingManager"),
AppInit = require("utils/AppInit"),
Commands = require("command/Commands"),
DocumentManager = require("document/DocumentManager"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
Editor = require("editor/Editor"),
EditorManager = require("editor/EditorManager"),
ModalBar = require("widgets/ModalBar").ModalBar,
KeyEvent = require("utils/KeyEvent"),
ScrollTrackMarkers = require("search/ScrollTrackMarkers"),
PanelManager = require("view/PanelManager"),
Resizer = require("utils/Resizer"),
StatusBar = require("widgets/StatusBar"),
PreferencesManager = require("preferences/PreferencesManager"),
ViewUtils = require("utils/ViewUtils"),
_ = require("thirdparty/lodash"),
CodeMirror = require("thirdparty/CodeMirror2/lib/codemirror");
var searchBarTemplate = require("text!htmlContent/findreplace-bar.html"),
searchReplacePanelTemplate = require("text!htmlContent/search-replace-panel.html"),
searchReplaceResultsTemplate = require("text!htmlContent/search-replace-results.html");
/** @const Maximum file size to search within (in chars) */
var FIND_MAX_FILE_SIZE = 500000;
/** @const If the number of matches exceeds this limit, inline text highlighting and scroll-track tickmarks are disabled */
var FIND_HIGHLIGHT_MAX = 2000;
/** @const Maximum number of matches to collect for Replace All; any additional matches are not listed in the panel & are not replaced */
var REPLACE_ALL_MAX = 300;
/** @type {!Panel} Panel that shows results of replaceAll action */
var replaceAllPanel = null;
/** @type {?Document} Instance of the currently opened document when replaceAllPanel is visible */
var currentDocument = null;
/** @type {$.Element} jQuery elements used in the replaceAll panel */
var $replaceAllContainer,
$replaceAllWhat,
$replaceAllWith,
$replaceAllSummary,
$replaceAllTable;
/** @type {?ModalBar} Currently open Find or Find/Replace bar, if any */
var modalBar;
/** @type {!function():void} API from FindInFiles for closing its conflicting search bar, if open */
var closeFindInFilesBar;
function SearchState() {
this.searchStartPos = null;
this.query = null;
this.foundAny = false;
this.marked = [];
}
function getSearchState(cm) {
if (!cm._searchState) {
cm._searchState = new SearchState();
}
return cm._searchState;
}
function getSearchCursor(cm, query, pos) {
// Heuristic: if the query string is all lowercase, do a case insensitive search.
return cm.getSearchCursor(query, pos, !PreferencesManager.getViewState("caseSensitive"));
}
function _updateSearchBarFromPrefs() {
$("#find-case-sensitive").toggleClass("active", PreferencesManager.getViewState("caseSensitive"));
$("#find-regexp").toggleClass("active", PreferencesManager.getViewState("regexp"));
}
function _updatePrefsFromSearchBar() {
PreferencesManager.setViewState("caseSensitive", $("#find-case-sensitive").is(".active"));
PreferencesManager.setViewState("regexp", $("#find-regexp").is(".active"));
}
function parseQuery(query) {
$(".modal-bar .message").show();
$(".modal-bar .error").hide();
// Is it a (non-blank) regex?
if (query && $("#find-regexp").is(".active")) {
try {
var caseSensitive = $("#find-case-sensitive").is(".active");
return new RegExp(query, caseSensitive ? "" : "i");
} catch (e) {
$(".modal-bar .message").hide();
$(".modal-bar .error")
.show()
.text(e.message);
return "";
}
} else {
return query;
}
}
// NOTE: we can't just use the ordinary replace() function here because the string has been
// extracted from the original text and so might be missing some context that the regexp matched.
function parseDollars(replaceWith, match) {
replaceWith = replaceWith.replace(/(\$+)(\d{1,2}|&)/g, function (whole, dollars, index) {
var parsedIndex = parseInt(index, 10);
if (dollars.length % 2 === 1) { // check if dollar signs escape themselves (for example $$1, $$$$&)
if (index === "&") { // handle $&
return dollars.substr(1) + (match[0] || "");
} else if (parsedIndex !== 0) { // handle $n or $nn, don't handle $0 or $00
return dollars.substr(1) + (match[parsedIndex] || "");
}
}
return whole;
});
replaceWith = replaceWith.replace(/\$\$/g, "$"); // replace escaped dollar signs (for example $$) with single ones
return replaceWith;
}
/**
* @private
* Returns the next match for the current query (from the search state) before/after the given position. Wraps around
* the end of the document if no match is found before the end.
*
* @param {!Editor} editor The editor to search in
* @param {boolean} rev True to search backwards
* @param {{line: number, ch: number}=} pos The position to start from. Defaults to the current primary selection's
* head cursor position.
* @param {boolean=} wrap Whether to wrap the search around if we hit the end of the document. Default true.
* @return {?{start: {line: number, ch: number}, end: {line: number, ch: number}}} The range for the next match, or
* null if there is no match.
*/
function _getNextMatch(editor, rev, pos, wrap) {
var cm = editor._codeMirror;
var state = getSearchState(cm);
var cursor = getSearchCursor(cm, state.query, pos || editor.getCursorPos(false, rev ? "start" : "end"));
state.lastMatch = cursor.find(rev);
if (!state.lastMatch && wrap !== false) {
// If no result found before hitting edge of file, try wrapping around
cursor = getSearchCursor(cm, state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});
state.lastMatch = cursor.find(rev);
}
if (!state.lastMatch) {
// No result found, period: clear selection & bail
cm.setCursor(editor.getCursorPos()); // collapses selection, keeping cursor in place to avoid scrolling
return null;
}
return {start: cursor.from(), end: cursor.to()};
}
/**
* @private
* Sets the given selections in the editor and applies some heuristics to determine whether and how we should
* center the primary selection.
*
* @param {!Editor} editor The editor to search in
* @param {!Array<{start:{line:number, ch:number}, end:{line:number, ch:number}, primary:boolean, reversed: boolean}>} selections
* The selections to set. Must not be empty.
* @param {boolean} center Whether to try to center the primary selection vertically on the screen. If false, the selection will still be scrolled
* into view if it's offscreen, but will not be centered.
* @param {boolean=} preferNoScroll If center is true, whether to avoid scrolling if the hit is in the top half of the screen. Default false.
*/
function _selectAndScrollTo(editor, selections, center, preferNoScroll) {
var primarySelection = _.find(selections, function (sel) { return sel.primary; }) || _.last(selections),
resultVisible = editor.isLineVisible(primarySelection.start.line),
centerOptions = Editor.BOUNDARY_CHECK_NORMAL;
if (preferNoScroll && resultVisible) {
// no need to scroll if the line with the match is in view
centerOptions = Editor.BOUNDARY_IGNORE_TOP;
}
// Make sure the primary selection is fully visible on screen.
var primary = _.find(selections, function (sel) {
return sel.primary;
});
if (!primary) {
primary = _.last(selections);
}
editor._codeMirror.scrollIntoView({from: primary.start, to: primary.end});
editor.setSelections(selections, center, centerOptions);
}
/**
* Returns the range of the word surrounding the given editor position. Similar to getWordAt() from CodeMirror.
*
* @param {!Editor} editor The editor to search in
* @param {!{line: number, ch: number}} pos The position to find a word at.
* @return {{start:{line: number, ch: number}, end:{line:number, ch:number}, text:string}} The range and content of the found word. If
* there is no word, start will equal end and the text will be the empty string.
*/
function _getWordAt(editor, pos) {
var cm = editor._codeMirror,
start = pos.ch,
end = start,
line = cm.getLine(pos.line);
while (start && CodeMirror.isWordChar(line.charAt(start - 1))) {
--start;
}
while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) {
++end;
}
return {start: {line: pos.line, ch: start}, end: {line: pos.line, ch: end}, text: line.slice(start, end)};
}
/**
* @private
* Helper function. Returns true if two selections are equal.
* @param {!{start: {line: number, ch: number}, end: {line: number, ch: number}}} sel1 The first selection to compare
* @param {!{start: {line: number, ch: number}, end: {line: number, ch: number}}} sel2 The second selection to compare
* @return {boolean} true if the selections are equal
*/
function _selEq(sel1, sel2) {
return (CodeMirror.cmpPos(sel1.start, sel2.start) === 0 && CodeMirror.cmpPos(sel1.end, sel2.end) === 0);
}
/**
* Expands each empty range in the selection to the nearest word boundaries. Then, if the primary selection
* was already a range (even a non-word range), adds the next instance of the contents of that range as a selection.
*
* @param {!Editor} editor The editor to search in
* @param {boolean=} removePrimary Whether to remove the current primary selection in addition to adding the
* next one. If true, we add the next match even if the current primary selection is a cursor (we expand it
* first to determine what to match).
*/
function _expandWordAndAddNextToSelection(editor, removePrimary) {
editor = editor || EditorManager.getActiveEditor();
if (!editor) {
return;
}
var selections = editor.getSelections(),
primarySel,
primaryIndex,
searchText,
added = false;
_.each(selections, function (sel, index) {
var isEmpty = (CodeMirror.cmpPos(sel.start, sel.end) === 0);
if (sel.primary) {
primarySel = sel;
primaryIndex = index;
if (!isEmpty) {
searchText = editor.document.getRange(primarySel.start, primarySel.end);
}
}
if (isEmpty) {
var wordInfo = _getWordAt(editor, sel.start);
sel.start = wordInfo.start;
sel.end = wordInfo.end;
if (sel.primary && removePrimary) {
// Get the expanded text, even though we're going to remove this selection,
// since in this case we still want to select the next match.
searchText = wordInfo.text;
}
}
});
if (searchText && searchText.length) {
// We store this as a query in the state so that if the user next does a "Find Next",
// it will use the same query (but throw away the existing selection).
var state = getSearchState(editor._codeMirror);
state.query = searchText;
// Skip over matches that are already in the selection.
var searchStart = primarySel.end,
nextMatch,
isInSelection;
do {
nextMatch = _getNextMatch(editor, false, searchStart);
if (nextMatch) {
// This is a little silly, but if we just stick the equivalence test function in here
// JSLint complains about creating a function in a loop, even though it's safe in this case.
isInSelection = _.find(selections, _.partial(_selEq, nextMatch));
searchStart = nextMatch.end;
// If we've gone all the way around, then all instances must have been selected already.
if (CodeMirror.cmpPos(searchStart, primarySel.end) === 0) {
nextMatch = null;
break;
}
}
} while (nextMatch && isInSelection);
if (nextMatch) {
nextMatch.primary = true;
selections.push(nextMatch);
added = true;
}
}
if (removePrimary) {
selections.splice(primaryIndex, 1);
}
if (added) {
// Center the new match, but avoid scrolling to matches that are already on screen.
_selectAndScrollTo(editor, selections, true, true);
} else {
// If all we did was expand some selections, don't center anything.
_selectAndScrollTo(editor, selections, false);
}
}
function _skipCurrentMatch(editor) {
return _expandWordAndAddNextToSelection(editor, true);
}
/**
* Takes the primary selection, expands it to a word range if necessary, then sets the selection to
* include all instances of that range. Removes all other selections. Does nothing if the selection
* is not a range after expansion.
*/
function _findAllAndSelect(editor) {
editor = editor || EditorManager.getActiveEditor();
if (!editor) {
return;
}
var sel = editor.getSelection(),
newSelections = [];
if (CodeMirror.cmpPos(sel.start, sel.end) === 0) {
sel = _getWordAt(editor, sel.start);
}
if (CodeMirror.cmpPos(sel.start, sel.end) !== 0) {
var searchStart = {line: 0, ch: 0},
state = getSearchState(editor._codeMirror),
nextMatch;
state.query = editor.document.getRange(sel.start, sel.end);
while ((nextMatch = _getNextMatch(editor, false, searchStart, false)) !== null) {
if (_selEq(sel, nextMatch)) {
nextMatch.primary = true;
}
newSelections.push(nextMatch);
searchStart = nextMatch.end;
}
// This should find at least the original selection, but just in case...
if (newSelections.length) {
// Don't change the scroll position.
editor.setSelections(newSelections, false);
}
}
}
/**
* Selects the next match (or prev match, if rev==true) starting from either the current position
* (if pos unspecified) or the given position (if pos specified explicitly). The starting position
* need not be an existing match. If a new match is found, sets to state.lastMatch either the regex
* match result, or simply true for a plain-string match. If no match found, sets state.lastMatch
* to false.
* @param {!Editor} editor
* @param {?boolean} rev
* @param {?boolean} preferNoScroll
* @param {?Pos} pos
*/
function findNext(editor, rev, preferNoScroll, pos) {
var cm = editor._codeMirror;
cm.operation(function () {
var nextMatch = _getNextMatch(editor, rev, pos);
if (nextMatch) {
_selectAndScrollTo(editor, [nextMatch], true, preferNoScroll);
} else {
cm.setCursor(editor.getCursorPos()); // collapses selection, keeping cursor in place to avoid scrolling
}
});
}
function clearHighlights(cm, state) {
cm.operation(function () {
state.marked.forEach(function (markedRange) {
markedRange.clear();
});
});
state.marked.length = 0;
ScrollTrackMarkers.clear();
}
function clearSearch(cm) {
cm.operation(function () {
var state = getSearchState(cm);
if (!state.query) {
return;
}
state.query = null;
clearHighlights(cm, state);
});
}
function _closeFindBar() {
if (modalBar) {
// 1st arg = restore scroll pos; 2nd arg = no animation, since getting replaced immediately
modalBar.close(true, false);
}
}
function _registerFindInFilesCloser(closer) {
closeFindInFilesBar = closer;
}
function createModalBar(template) {
// Normally, creating a new modal bar will simply cause the old one to close
// automatically. This can cause timing issues because the focus change might
// cause the new one to think it should close, too. The old CodeMirror version
// of this handled it by adding a timeout within which a blur wouldn't cause
// the modal bar to close. Rather than reinstate that hack, we simply explicitly
// close the old modal bar (which may be a Find, Replace, *or* Find in Files bar
// before creating a new one. (TODO: remove once #6203 fixed)
_closeFindBar();
closeFindInFilesBar();
modalBar = new ModalBar(template, true); // 2nd arg = auto-close on Esc/blur
$(modalBar).on("close", function (event) {
modalBar = null;
});
}
function addShortcutToTooltip($elem, commandId) {
var replaceShortcut = KeyBindingManager.getKeyBindings(commandId)[0];
if (replaceShortcut) {
var oldTitle = $elem.attr("title");
oldTitle = (oldTitle ? oldTitle + " " : "");
$elem.attr("title", oldTitle + "(" + KeyBindingManager.formatKeyDescriptor(replaceShortcut.displayKey) + ")");
}
}
function toggleHighlighting(editor, enabled) {
// Temporarily change selection color to improve highlighting - see LESS code for details
if (enabled) {
$(editor.getRootElement()).addClass("find-highlighting");
} else {
$(editor.getRootElement()).removeClass("find-highlighting");
}
ScrollTrackMarkers.setVisible(editor, enabled);
}
/**
* Called each time the search query changes or document is modified (via Replace). Updates
* the match count, match highlights and scrollbar tickmarks. Does not change the cursor pos.
*/
function updateResultSet(editor) {
var cm = editor._codeMirror,
state = getSearchState(cm);
function indicateHasMatches(numResults) {
// Make the field red if it's not blank and it has no matches (which also covers invalid regexes)
ViewUtils.toggleClass($("#find-what"), "no-results", !state.foundAny && $("#find-what").val());
// Buttons disabled if blank, OR if no matches (Replace buttons) / < 2 matches (nav buttons)
$("#find-prev, #find-next").prop("disabled", !state.foundAny || numResults < 2);
$("#replace-yes, #replace-all").prop("disabled", !state.foundAny);
}
cm.operation(function () {
// Clear old highlights
if (state.marked) {
clearHighlights(cm, state);
}
if (!state.query) {
// Search field is empty - no results
$("#find-counter").text("");
state.foundAny = false;
indicateHasMatches();
return;
}
// Find *all* matches, searching from start of document
// (Except on huge documents, where this is too expensive)
var cursor = getSearchCursor(cm, state.query);
if (cm.getValue().length <= FIND_MAX_FILE_SIZE) {
// FUTURE: if last query was prefix of this one, could optimize by filtering last result set
var resultSet = [];
while (cursor.findNext()) {
resultSet.push(cursor.pos); // pos is unique obj per search result
}
// Highlight all matches if there aren't too many
if (resultSet.length <= FIND_HIGHLIGHT_MAX) {
toggleHighlighting(editor, true);
resultSet.forEach(function (result) {
state.marked.push(cm.markText(result.from, result.to,
{ className: "CodeMirror-searching", startStyle: "searching-first", endStyle: "searching-last" }));
});
var scrollTrackPositions = resultSet.map(function (result) {
return result.from;
});
ScrollTrackMarkers.addTickmarks(editor, scrollTrackPositions);
}
if (resultSet.length === 0) {
$("#find-counter").text(Strings.FIND_NO_RESULTS);
} else if (resultSet.length === 1) {
$("#find-counter").text(Strings.FIND_RESULT_COUNT_SINGLE);
} else {
$("#find-counter").text(StringUtils.format(Strings.FIND_RESULT_COUNT, resultSet.length));
}
state.foundAny = (resultSet.length > 0);
indicateHasMatches(resultSet.length);
} else {
// On huge documents, just look for first match & then stop
$("#find-counter").text("");
state.foundAny = cursor.findNext();
indicateHasMatches();
}
});
}
/**
* Called each time the search query field changes. Updates state.query (query will be falsy if the field
* was blank OR contained a regexp with invalid syntax). Then calls updateResultSet(), and then jumps to
* the first matching result, starting from the original cursor position.
* @param {!Editor} editor The editor we're searching in.
* @param {Object} state The current query state.
* @param {boolean} initial Whether this is the initial population of the query when the search bar opens.
* In that case, we don't want to change the selection unnecessarily.
*/
function handleQueryChange(editor, state, initial) {
state.query = parseQuery($("#find-what").val());
updateResultSet(editor);
if (state.query) {
// 3rd arg: prefer to avoid scrolling if result is anywhere within view, since in this case user
// is in the middle of typing, not navigating explicitly; viewport jumping would be distracting.
findNext(editor, false, true, state.searchStartPos);
} else if (!initial) {
// Blank or invalid query: just jump back to initial pos
editor._codeMirror.setCursor(state.searchStartPos);
}
}
/**
* Opens the search bar with the given HTML content (Find or Find-Replace), attaches common Find behaviors,
* and prepopulates the query field.
* @param {!Editor} editor
* @param {!Object} templateVars
*/
function openSearchBar(editor, templateVars) {
var cm = editor._codeMirror,
state = getSearchState(cm);
// Use the selection start as the searchStartPos. This way if you
// start with a pre-populated search and enter an additional character,
// it will extend the initial selection instead of jumping to the next
// occurrence.
state.searchStartPos = editor.getCursorPos(false, "start");
// If a previous search/replace bar was open, capture its query text for use below
var initialQuery;
if (modalBar) {
initialQuery = $("#find-what").val();
}
// Create the search bar UI (closing any previous modalBar in the process)
var htmlContent = Mustache.render(searchBarTemplate, $.extend(templateVars, Strings));
createModalBar(htmlContent);
addShortcutToTooltip($("#find-next"), Commands.EDIT_FIND_NEXT);
addShortcutToTooltip($("#find-prev"), Commands.EDIT_FIND_PREVIOUS);
$(modalBar).on("close", function (e, query) {
// Clear highlights but leave search state in place so Find Next/Previous work after closing
clearHighlights(cm, state);
// Dispose highlighting UI (important to restore normal selection color as soon as focus goes back to the editor)
toggleHighlighting(editor, false);
// Hide error popup, since it hangs down low enough to make the slide-out look awkward
$(".modal-bar .error").hide();
});
modalBar.getRoot()
.on("click", "#find-next", function (e) {
findNext(editor);
})
.on("click", "#find-prev", function (e) {
findNext(editor, true);
})
.on("click", "#find-case-sensitive, #find-regexp", function (e) {
$(e.currentTarget).toggleClass('active');
_updatePrefsFromSearchBar();
handleQueryChange(editor, state);
})
.on("keydown", function (e) {
if (e.keyCode === KeyEvent.DOM_VK_RETURN) {
if (!e.shiftKey) {
findNext(editor);
} else {
findNext(editor, true);
}
}
});
$("#find-what").on("input", function () {
handleQueryChange(editor, state);
});
// Prepopulate the search field
if (!initialQuery) {
// Prepopulate with the current primary selection, if any
var sel = editor.getSelection();
initialQuery = cm.getRange(sel.start, sel.end);
// Eliminate newlines since we don't generally support searching across line boundaries (#2960)
var newline = initialQuery.indexOf("\n");
if (newline !== -1) {
initialQuery = initialQuery.substr(0, newline);
}
}
// Initial UI state
$("#find-what")
.val(initialQuery)
.get(0).select();
_updateSearchBarFromPrefs();
handleQueryChange(editor, state, true);
}
/**
* If no search pending, opens the Find dialog. If search bar already open, moves to
* next/prev result (depending on 'rev')
*/
function doSearch(editor, rev) {
var state = getSearchState(editor._codeMirror);
if (state.query) {
findNext(editor, rev);
return;
}
openSearchBar(editor, {});
}
/**
* @private
* Closes a panel with search-replace results.
* Main purpose is to make sure that events are correctly detached from current document.
*/
function _closeReplaceAllPanel() {
if (replaceAllPanel !== null && replaceAllPanel.isVisible()) {
replaceAllPanel.hide();
}
$(currentDocument).off("change.replaceAll");
}
/**
* @private
* When the user switches documents (or closes the last document), ensure that the find bar
* closes, and also close the Replace All panel.
*/
function _handleDocumentChange() {
if (modalBar) {
modalBar.close();
}
_closeReplaceAllPanel();
}
/**
* @private
* Shows a panel with search results and offers to replace them,
* user can use checkboxes to select which results he wishes to replace.
* @param {Editor} editor - Currently active editor that was used to invoke this action.
* @param {string|RegExp} replaceWhat - Query that will be passed into CodeMirror Cursor to search for results.
* @param {string} replaceWith - String that should be used to replace chosen results.
*/
function _showReplaceAllPanel(editor, replaceWhat, replaceWith) {
var results = [],
cm = editor._codeMirror,
cursor = getSearchCursor(cm, replaceWhat),
from,
to,
line,
multiLine,
matchResult = cursor.findNext();
// Collect all results from document
while (matchResult) {
from = cursor.from();
to = cursor.to();
line = editor.document.getLine(from.line);
multiLine = from.line !== to.line;
results.push({
index: results.length, // add indexes to array
from: from,
to: to,
line: from.line + 1,
pre: line.slice(0, from.ch),
highlight: line.slice(from.ch, multiLine ? undefined : to.ch),
post: multiLine ? "\u2026" : line.slice(to.ch),
result: matchResult
});
if (results.length >= REPLACE_ALL_MAX) {
break;
}
matchResult = cursor.findNext();
}
// This text contains some formatting, so all the strings are assumed to be already escaped
var resultsLength = results.length,
summary = StringUtils.format(
Strings.FIND_REPLACE_TITLE_PART3,
resultsLength,
resultsLength > 1 ? Strings.FIND_IN_FILES_MATCHES : Strings.FIND_IN_FILES_MATCH,
resultsLength >= REPLACE_ALL_MAX ? Strings.FIND_IN_FILES_MORE_THAN : ""
);
// Insert the search summary
$replaceAllWhat.text(replaceWhat.toString());
$replaceAllWith.text(replaceWith.toString());
$replaceAllSummary.html(summary);
// All checkboxes are checked by default
$replaceAllContainer.find(".check-all").prop("checked", true);
// Attach event to replace button
$replaceAllContainer.find("button.replace-checked").off().on("click", function (e) {
$replaceAllTable.find(".check-one:checked")
.closest(".replace-row")
.toArray()
.reverse()
.forEach(function (checkedRow) {
var match = results[$(checkedRow).data("match")],
rw = typeof replaceWhat === "string" ? replaceWith : parseDollars(replaceWith, match.result);
editor.document.replaceRange(rw, match.from, match.to, "+replaceAll");
});
_closeReplaceAllPanel();
});
// Insert the search results
$replaceAllTable
.empty()
.append(Mustache.render(searchReplaceResultsTemplate, {searchResults: results}))
.off()
.on("click", ".check-one", function (e) {
e.stopPropagation();
})
.on("click", ".replace-row", function (e) {
var match = results[$(e.currentTarget).data("match")];
editor.setSelection(match.from, match.to, true);
});
// we can't safely replace after document has been modified
// this handler is only attached, when replaceAllPanel is visible
currentDocument = DocumentManager.getCurrentDocument();
$(currentDocument).on("change.replaceAll", function () {
_closeReplaceAllPanel();
});
replaceAllPanel.show();
$replaceAllTable.scrollTop(0); // Otherwise scroll pos from previous contents is remembered
}
/** Shows the Find-Replace search bar at top */
function replace(editor) {
// If Replace bar already open, treat the shortcut as a hotkey for the Replace button
var $replaceBtn = $("#replace-yes");
if ($replaceBtn.length) {
if ($replaceBtn.is(":enabled")) {
$replaceBtn.click();
}
return;
}
openSearchBar(editor, {replace: true});
addShortcutToTooltip($("#replace-yes"), Commands.EDIT_REPLACE);
var cm = editor._codeMirror,
state = getSearchState(cm);
function getReplaceWith() {
return $("#replace-with").val() || "";
}
modalBar.getRoot().on("click", function (e) {
if (e.target.id === "replace-yes") {
var text = getReplaceWith();
cm.replaceSelection(typeof state.query === "string" ? text : parseDollars(text, state.lastMatch));
updateResultSet(editor); // we updated the text, so result count & tickmarks must be refreshed
findNext(editor);
if (!state.lastMatch) {
// No more matches, so destroy modalBar
modalBar.close();
}
} else if (e.target.id === "replace-all") {
modalBar.close();
_showReplaceAllPanel(editor, state.query, getReplaceWith());
}
});
// One-off hack to make Find/Replace fields a self-contained tab cycle - TODO: remove once https://trello.com/c/lTSJgOS2 implemented
modalBar.getRoot().on("keydown", function (e) {
if (e.keyCode === KeyEvent.DOM_VK_TAB && !e.ctrlKey && !e.metaKey && !e.altKey) {
if (e.target.id === "replace-with" && !e.shiftKey) {
$("#find-what").focus();
e.preventDefault();
} else if (e.target.id === "find-what" && e.shiftKey) {
$("#replace-with").focus();
e.preventDefault();
}
}
});
}
function _launchFind() {
var editor = EditorManager.getActiveEditor();
if (editor) {
// Create a new instance of the search bar UI
clearSearch(editor._codeMirror);
doSearch(editor, false);
}
}
function _findNext() {
var editor = EditorManager.getActiveEditor();
if (editor) {
doSearch(editor);
}
}
function _findPrevious() {
var editor = EditorManager.getActiveEditor();
if (editor) {
doSearch(editor, true);
}
}
function _replace() {
var editor = EditorManager.getActiveEditor();
if (editor) {
replace(editor);
}
}
PreferencesManager.stateManager.definePreference("caseSensitive", "boolean", false);
PreferencesManager.stateManager.definePreference("regexp", "boolean", false);
PreferencesManager.convertPreferences(module, {"caseSensitive": "user", "regexp": "user"}, true);
// Initialize items dependent on HTML DOM
AppInit.htmlReady(function () {
var panelHtml = Mustache.render(searchReplacePanelTemplate, Strings);
replaceAllPanel = PanelManager.createBottomPanel("findReplace-all.panel", $(panelHtml), 100);
$replaceAllContainer = replaceAllPanel.$panel;
$replaceAllWhat = $replaceAllContainer.find(".replace-what");
$replaceAllWith = $replaceAllContainer.find(".replace-with");
$replaceAllSummary = $replaceAllContainer.find(".replace-summary");
$replaceAllTable = $replaceAllContainer.children(".table-container");
// Attach events to the panel
replaceAllPanel.$panel
.on("click", ".close", function () {
_closeReplaceAllPanel();
})
.on("click", ".check-all", function (e) {
var isChecked = $(this).is(":checked");
replaceAllPanel.$panel.find(".check-one").prop("checked", isChecked);
});
});
$(DocumentManager).on("currentDocumentChange", _handleDocumentChange);
CommandManager.register(Strings.CMD_FIND, Commands.EDIT_FIND, _launchFind);
CommandManager.register(Strings.CMD_FIND_NEXT, Commands.EDIT_FIND_NEXT, _findNext);
CommandManager.register(Strings.CMD_REPLACE, Commands.EDIT_REPLACE, _replace);
CommandManager.register(Strings.CMD_FIND_PREVIOUS, Commands.EDIT_FIND_PREVIOUS, _findPrevious);
CommandManager.register(Strings.CMD_FIND_ALL_AND_SELECT, Commands.EDIT_FIND_ALL_AND_SELECT, _findAllAndSelect);
CommandManager.register(Strings.CMD_ADD_NEXT_MATCH, Commands.EDIT_ADD_NEXT_MATCH, _expandWordAndAddNextToSelection);
CommandManager.register(Strings.CMD_SKIP_CURRENT_MATCH, Commands.EDIT_SKIP_CURRENT_MATCH, _skipCurrentMatch);
// APIs shared with FindInFiles
exports._updatePrefsFromSearchBar = _updatePrefsFromSearchBar;
exports._updateSearchBarFromPrefs = _updateSearchBarFromPrefs;
exports._closeFindBar = _closeFindBar;
exports._registerFindInFilesCloser = _registerFindInFilesCloser;
// For unit testing
exports._getWordAt = _getWordAt;
exports._expandWordAndAddNextToSelection = _expandWordAndAddNextToSelection;
exports._findAllAndSelect = _findAllAndSelect;
});
|
var _ = require('underscore'),
merge = require('deepmerge'),
path = require('path'),
yaml = require('js-yaml');
module.exports = function(env, fs) {
function addEnvVar(config, name, value, processor) {
if (value !== undefined) {
config[name] = processor ? processor(value) : value;
}
}
function parseBooleanEnvVar(value) {
return !!value.match(/^(?:1|t|true|y|yes)$/);
}
function Config(config) {
_.extend(this, _.pick(config || {}, 'payload', 'project', 'publish', 'server', 'servers', 'testRunUid', 'workspace'));
}
function clear(config) {
for (var name in config) {
delete config[name];
}
}
_.extend(Config.prototype, {
load: function(customConfig) {
clear(this);
var configFiles = [
path.join(env.HOME, '.rox', 'config.yml'),
env.ROX_CONFIG || 'rox.yml'
];
// TODO: log warning if yaml is invalid
var config = _.reduce(configFiles, function(memo, path) {
if (fs.existsSync(path)) {
memo = merge(memo, yaml.safeLoad(fs.readFileSync(path, { encoding: 'utf-8' })));
}
return memo;
}, { publish: true, project: {}, payload: {} });
delete config.testRunUid;
if (customConfig) {
config = merge(config, customConfig);
}
var envConfig = {
payload: {}
};
addEnvVar(envConfig, 'publish', env.ROX_PUBLISH, parseBooleanEnvVar);
addEnvVar(envConfig, 'server', env.ROX_SERVER);
addEnvVar(envConfig, 'workspace', env.ROX_WORKSPACE);
addEnvVar(envConfig.payload, 'cache', env.ROX_CACHE_PAYLOAD, parseBooleanEnvVar);
addEnvVar(envConfig.payload, 'print', env.ROX_PRINT_PAYLOAD, parseBooleanEnvVar);
addEnvVar(envConfig.payload, 'save', env.ROX_SAVE_PAYLOAD, parseBooleanEnvVar);
addEnvVar(envConfig, 'testRunUid', env.ROX_TEST_RUN_UID);
config = merge(config, envConfig);
_.extend(this, config);
},
getServerOptions: function() {
return _.isObject(this.servers) ? this.servers[this.server] || {} : {};
},
getProjectOptions: function() {
var options = {};
if (_.isObject(this.project)) {
_.extend(options, _.pick(this.project, 'apiId', 'version', 'category', 'tags', 'tickets'));
}
var serverOptions = this.getServerOptions();
if (serverOptions.projectApiId) {
options.apiId = serverOptions.projectApiId;
}
return options;
},
validate: function(errors) {
if (env.ROX_CONFIG && !fs.existsSync(env.ROX_CONFIG)) {
errors.push('No project configuration file found at ' + env.ROX_CONFIG + ' (set with $ROX_CONFIG environment variable)');
}
if (!this.project || !_.isObject(this.project)) {
errors.push('Project is not configured (set "project.apiId" and "project.version" in configuration file)');
} else {
if (!this.project.apiId) {
errors.push('Project API ID is not set (set "project.apiId" in configuration file)');
}
if (!this.project.version) {
errors.push('Project version is not set (set "project.version" in configuration file)');
}
}
if (!this.servers || !_.isObject(this.servers)) {
errors.push('No ROX Center server is configured (set "servers" in configuration file)');
} else {
_.each(this.servers, function(server, name) {
if (!server || !server.apiUrl) {
errors.push('No API URL is set for ROX Center server ' + name + ' (set "servers.' + name + '.apiUrl" in configuration file)');
}
if (!server || !server.apiKeyId) {
errors.push('No API key ID is set for ROX Center server ' + name + ' (set "servers.' + name + '.apiKeyId" in configuration file)');
}
if (!server || !server.apiKeySecret) {
errors.push('No API key secret is set for ROX Center server ' + name + ' (set "servers.' + name + '.apiKeySecret" in configuration file)');
}
});
}
}
});
return Config;
};
module.exports['@require'] = [ 'env', 'fs' ];
module.exports['@singleton'] = true;
|
angular.module('invertedIndex', ['indexTable', 'fileUpload', 'fileMenu', 'navBar', 'search'])
.controller('UploadController', ['$rootScope', '$scope', ($rootScope, $scope) => {
$rootScope.generatedIndex = [];
const readFile = (file) => {
return new Promise((resolve) => {
const reader = new FileReader();
let data = [];
reader.onload = (() => (event) => {
try {
const jsonData = JSON.parse(event.target.result);
if (jsonData) {
data = jsonData;
resolve(data);
}
} catch (error) {
$rootScope.error = { message: `${file.name} is an invalid JSON File` };
resolve(false);
}
})(file);
reader.readAsText(file);
});
};
$scope.onUpload = () => {
$rootScope.error = null;
const files = document.getElementById('files').files;
const uploaded = [];
for (let i = 0; i < files.length; i += 1) {
uploaded.push({ name: files[i].name, size: `${files[i].size} bytes`, fulldata: files[i] });
}
$rootScope.uploaded_files = uploaded;
$rootScope.$broadcast('files uploaded');
};
$rootScope.InvertedIndex = new InvertedIndex();
$rootScope.changeInput = (file, fn, callback) => {
$rootScope.data = {};
Object.keys(file).forEach((data) => {
if ($rootScope.error) {
callback();
} else {
readFile(file[data].fulldata).then((response) => {
try {
if ($rootScope.error) {
throw TypeError;
} else {
$rootScope.data[file[data].name] = response;
$rootScope.InvertedIndex.generateIndex(file[data].name, response);
setTimeout(() => {
fn('menu view');
}, 2000);
$rootScope.$broadcast('process');
}
} catch (error) {
if (!response) {
callback();
}
}
});
}
});
};
$rootScope.nextView = (view) => {
$rootScope.view = view;
$rootScope.$broadcast('change view');
};
}]);
|
const mongoose = require('../utils/mongoose-shim');
mongoose.models = {};
module.exports = {
InviteCode: require('./invite'),
Job: require('./job').default,
User: require('./user').default,
Project: require('./project'),
Config: require('./config'),
};
|
export default (() => {
let o;
return Jymfony.Component.VarExporter.Internal.Hydrator.hydrate(
o = [
(new ReflectionClass('Jymfony.Component.DateTime.Internal.RuleSet')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
],
null,
{
'Jymfony.Component.DateTime.Internal.RuleSet': {
['_name']: {
['0']: undefined,
},
['_rules']: {
['0']: [
o[1],
o[2],
o[3],
o[4],
o[5],
o[6],
o[7],
o[8],
o[9],
o[10],
o[11],
o[12],
o[13],
o[14],
o[15],
o[16],
],
},
['_cache']: {
['0']: {
['1918']: [
o[2],
o[3],
o[4],
],
['1919']: [
o[4],
o[5],
o[6],
o[7],
],
['1920']: [
o[7],
],
['1921']: [
o[7],
o[8],
o[9],
o[10],
o[11],
],
['1922']: [
o[11],
],
['1980']: [
o[11],
],
['1981']: [
o[11],
o[12],
o[13],
],
['1982']: [
o[11],
o[12],
o[13],
],
['1987']: [
o[13],
o[14],
o[15],
],
['1988']: [
o[13],
o[14],
o[15],
],
['1989']: [
o[13],
o[14],
o[15],
],
['1990']: [
o[13],
o[14],
o[15],
],
['1991']: [
o[13],
o[14],
o[15],
],
['1992']: [
o[13],
o[14],
o[15],
],
['1993']: [
o[13],
o[14],
o[15],
],
['1994']: [
o[13],
o[14],
o[15],
],
['1995']: [
o[13],
o[14],
o[15],
],
['1996']: [
o[14],
o[15],
o[16],
],
['1997']: [
o[14],
o[15],
o[16],
],
['2001']: [
o[14],
o[15],
o[16],
],
['2002']: [
o[14],
o[15],
o[16],
],
['2003']: [
o[14],
o[15],
o[16],
],
['2004']: [
o[14],
o[15],
o[16],
],
['2009']: [
o[14],
o[15],
o[16],
],
['2010']: [
o[14],
o[15],
o[16],
],
['2011']: [
o[16],
],
['2020']: [
o[16],
],
['2021']: [
o[16],
],
},
},
},
'Jymfony.Component.DateTime.Internal.Rule': {
['_fromYear']: {
['1']: 1917,
['2']: 1917,
['3']: 1918,
['4']: 1918,
['5']: 1919,
['6']: 1919,
['7']: 1919,
['8']: 1921,
['9']: 1921,
['10']: 1921,
['11']: 1921,
['12']: 1981,
['13']: 1981,
['14']: 1984,
['15']: 1985,
['16']: 1996,
},
['_toYear']: {
['1']: 1917,
['2']: 1917,
['3']: 1918,
['4']: 1918,
['5']: 1919,
['6']: 1919,
['7']: 1919,
['8']: 1921,
['9']: 1921,
['10']: 1921,
['11']: 1921,
['12']: 1984,
['13']: 1983,
['14']: 1995,
['15']: 2010,
['16']: 2010,
},
['_inMonth']: {
['1']: 7,
['2']: 12,
['3']: 5,
['4']: 9,
['5']: 5,
['6']: 7,
['7']: 8,
['8']: 2,
['9']: 3,
['10']: 9,
['11']: 10,
['12']: 4,
['13']: 10,
['14']: 9,
['15']: 3,
['16']: 10,
},
['_on']: {
['1']: '1',
['2']: '28',
['3']: '31',
['4']: '16',
['5']: '31',
['6']: '1',
['7']: '16',
['8']: '14',
['9']: '20',
['10']: '1',
['11']: '1',
['12']: '1',
['13']: '1',
['14']: 'last sun %s',
['15']: 'last sun %s',
['16']: 'last sun %s',
},
['_at']: {
['1']: '23:00',
['2']: '0:00',
['3']: '22:00',
['4']: '1:00',
['5']: '23:00',
['6']: '0:00u',
['7']: '0:00',
['8']: '23:00',
['9']: '23:00',
['10']: '0:00',
['11']: '0:00',
['12']: '0:00',
['13']: '0:00',
['14']: '2:00s',
['15']: '2:00s',
['16']: '2:00s',
},
['_save']: {
['1']: 3600,
['2']: 0,
['3']: 7200,
['4']: 3600,
['5']: 7200,
['6']: 3600,
['7']: 0,
['8']: 3600,
['9']: 7200,
['10']: 3600,
['11']: 0,
['12']: 3600,
['13']: 0,
['14']: 0,
['15']: 3600,
['16']: 0,
},
['_letters']: {
['1']: 'MST',
['2']: 'MMT',
['3']: 'MDST',
['4']: 'MST',
['5']: 'MDST',
['6']: 'MSD',
['7']: 'MSK',
['8']: 'MSD',
['9']: '+05',
['10']: 'MSD',
['11']: '-',
['12']: 'S',
['13']: '-',
['14']: '-',
['15']: 'S',
['16']: '-',
},
['_cache']: {
['1']: {},
['2']: {
['1917']: [
'001917-12-28T00:00:00',
'001917-12-28T00:00:00',
],
},
['3']: {
['1918']: [
'001918-05-31T22:00:00',
'001918-06-01T00:00:00',
],
},
['4']: {
['1918']: [
'001918-09-16T01:00:00',
'001918-09-16T02:00:00',
],
},
['5']: {
['1919']: [
'001919-05-31T23:00:00',
'001919-06-01T01:00:00',
],
},
['6']: {
['1919']: [
'001919-07-01T00:00:00u',
'001919-07-01T01:00:00',
],
},
['7']: {
['1919']: [
'001919-08-16T00:00:00',
'001919-08-16T00:00:00',
],
},
['8']: {
['1921']: [
'001921-02-14T23:00:00',
'001921-02-15T00:00:00',
],
},
['9']: {
['1921']: [
'001921-03-20T23:00:00',
'001921-03-21T01:00:00',
],
},
['10']: {
['1921']: [
'001921-09-01T00:00:00',
'001921-09-01T01:00:00',
],
},
['11']: {
['1921']: [
'001921-10-01T00:00:00',
'001921-10-01T00:00:00',
],
},
['12']: {
['1981']: [
'001981-04-01T00:00:00',
'001981-04-01T01:00:00',
],
['1982']: [
'001982-04-01T00:00:00',
'001982-04-01T01:00:00',
],
},
['13']: {
['1981']: [
'001981-10-01T00:00:00',
'001981-10-01T00:00:00',
],
['1982']: [
'001982-10-01T00:00:00',
'001982-10-01T00:00:00',
],
['1983']: [
'001983-10-01T00:00:00',
'001983-10-01T00:00:00',
],
},
['14']: {
['1987']: [
'001987-09-27T02:00:00',
'001987-09-27T02:00:00',
],
['1988']: [
'001988-09-25T02:00:00',
'001988-09-25T02:00:00',
],
['1989']: [
'001989-09-24T02:00:00',
'001989-09-24T02:00:00',
],
['1990']: [
'001990-09-30T02:00:00',
'001990-09-30T02:00:00',
],
['1991']: [
'001991-09-29T02:00:00',
'001991-09-29T02:00:00',
],
['1992']: [
'001992-09-27T02:00:00',
'001992-09-27T02:00:00',
],
['1993']: [
'001993-09-26T02:00:00',
'001993-09-26T02:00:00',
],
['1994']: [
'001994-09-25T02:00:00',
'001994-09-25T02:00:00',
],
['1995']: [
'001995-09-24T02:00:00',
'001995-09-24T02:00:00',
],
},
['15']: {
['1987']: [
'001987-03-29T02:00:00',
'001987-03-29T03:00:00',
],
['1988']: [
'001988-03-27T02:00:00',
'001988-03-27T03:00:00',
],
['1989']: [
'001989-03-26T02:00:00',
'001989-03-26T03:00:00',
],
['1990']: [
'001990-03-25T02:00:00',
'001990-03-25T03:00:00',
],
['1991']: [
'001991-03-31T02:00:00',
'001991-03-31T03:00:00',
],
['1992']: [
'001992-03-29T02:00:00',
'001992-03-29T03:00:00',
],
['1993']: [
'001993-03-28T02:00:00',
'001993-03-28T03:00:00',
],
['1994']: [
'001994-03-27T02:00:00',
'001994-03-27T03:00:00',
],
['1995']: [
'001995-03-26T02:00:00',
'001995-03-26T03:00:00',
],
['1996']: [
'001996-03-31T02:00:00',
'001996-03-31T03:00:00',
],
['1997']: [
'001997-03-30T02:00:00',
'001997-03-30T03:00:00',
],
['2001']: [
'002001-03-25T02:00:00',
'002001-03-25T03:00:00',
],
['2002']: [
'002002-03-31T02:00:00',
'002002-03-31T03:00:00',
],
['2003']: [
'002003-03-30T02:00:00',
'002003-03-30T03:00:00',
],
['2004']: [
'002004-03-28T02:00:00',
'002004-03-28T03:00:00',
],
['2009']: [
'002009-03-29T02:00:00',
'002009-03-29T03:00:00',
],
['2010']: [
'002010-03-28T02:00:00',
'002010-03-28T03:00:00',
],
},
['16']: {
['1996']: [
'001996-10-27T02:00:00',
'001996-10-27T02:00:00',
],
['1997']: [
'001997-10-26T02:00:00',
'001997-10-26T02:00:00',
],
['2001']: [
'002001-10-28T02:00:00',
'002001-10-28T02:00:00',
],
['2002']: [
'002002-10-27T02:00:00',
'002002-10-27T02:00:00',
],
['2003']: [
'002003-10-26T02:00:00',
'002003-10-26T02:00:00',
],
['2004']: [
'002004-10-31T02:00:00',
'002004-10-31T02:00:00',
],
['2009']: [
'002009-10-25T02:00:00',
'002009-10-25T02:00:00',
],
['2010']: [
'002010-10-31T02:00:00',
'002010-10-31T02:00:00',
],
},
},
},
},
[
{
['offset']: 12020,
['dst']: false,
['abbrev']: 'LMT',
['until']: -1593820800,
['format']: 'LMT',
},
{
['offset']: 10800,
['dst']: false,
['abbrev']: '+03',
['until']: -1247540400,
['format']: '+03',
},
{
['offset']: 14400,
['dst']: false,
['abbrev']: '+04',
['until']: -1102305600,
['format']: '+04',
},
{
['until']: 606866400,
['ruleSet']: o[0],
['offset']: 14400,
['abbrev']: '+04/+05',
},
{
['until']: 670374000,
['ruleSet']: o[0],
['offset']: 10800,
['abbrev']: '+03/+04',
},
{
['until']: 686098800,
['ruleSet']: o[0],
['offset']: 7200,
['abbrev']: '+02/+03',
},
{
['offset']: 10800,
['dst']: false,
['abbrev']: '+03',
['until']: 687916800,
['format']: '+03',
},
{
['until']: 1269727200,
['ruleSet']: o[0],
['offset']: 14400,
['abbrev']: '+04/+05',
},
{
['until']: 1301180400,
['ruleSet']: o[0],
['offset']: 10800,
['abbrev']: '+03/+04',
},
{
['offset']: 14400,
['dst']: false,
['abbrev']: '+04',
['until']: Infinity,
['format']: '+04',
},
],
[
0,
]
);
})();
;
|
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, util = require('util')
, fs = require('fs')
, customTheme = require('./fixtures/custom')
, cardinal = require('..')
function inspect (obj) {
return console.log(util.inspect(obj, false, 5, false))
}
var code = 'function foo() { var a = 3; return a > 2 ? true : false; }'
, codeWithErrors = 'function () { var a = 3; return a > 2 ? true : false; }';
test('supplying custom theme', function (t) {
var highlighted = cardinal.highlight(code, { theme: customTheme });
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[96ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[96ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[31mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('not supplying custom theme', function (t) {
var highlighted = cardinal.highlight(code);
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('errornous code', function (t) {
try {
cardinal.highlight(codeWithErrors);
} catch (e) {
t.similar(e.message, /Unable to perform highlight. The code contained syntax errors.* Line 1: Unexpected token [(]/)
t.end()
}
})
test('line numbers no firstline given', function (t) {
var highlighted = cardinal.highlight(code, { linenos: true });
t.equals(highlighted, '\u001b[90m1: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('line numbers firstline 99', function (t) {
var highlighted = cardinal.highlight(code, { linenos: true, firstline: 99 });
t.equals(highlighted, '\u001b[90m99: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('line numbers multi line no first line given', function (t) {
var multilineCode = '' +
function foo () {
return 1;
};
var highlighted = cardinal.highlight(multilineCode, { linenos: true });
t.equals(highlighted,'\u001b[90m1: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m2: \u001b[31mreturn\u001b[39m \u001b[34m1\u001b[39m\u001b[90m;\u001b[39m\n\u001b[90m3: \u001b[33m}\u001b[39m')
t.end()
})
test('line numbers multi line first line 99', function (t) {
var multilineCode = '' +
function foo () {
return 1;
};
var highlighted = cardinal.highlight(multilineCode, { linenos: true, firstline: 99 });
t.equals(highlighted,'\u001b[90m 99: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m100: \u001b[31mreturn\u001b[39m \u001b[34m1\u001b[39m\u001b[90m;\u001b[39m\n\u001b[90m101: \u001b[33m}\u001b[39m')
t.end()
})
|
define([], function () {
angular.module('ntext', [])
.filter('ntext', function ($sce) {
return function (text) {
return $sce.trustAsHtml(text.replace("\n", '<br />'));
}
});
;
}); |
'use strict';
import React from 'react'
import ModuleContain from './component/module/moduleContain'
import {Link, Route} from 'react-router-dom'
import {links, routes} from './config'
const cn = require('classnames/bind').bind(require('./app.scss'))
const App = props =>
<div className={cn('app')}>
{/*<NavList />*/}
<Section />
<ModuleContain />
</div>
const NavList = props =>
<nav>
{links.map(i=><Nav key={i.id} to={i.url} name={i.name}/>)}
</nav>
/**
*
* @param props {object} {
* {string} to:跳转地址
* {string} name:名称
* }
* @constructor
*/
const Nav = props =>
<Link to={props.to}><p className={cn('nav')}>{props.name}</p></Link>
const Section = props =>
<section>
{routes.map(i=><Context key={i.id} path={i.url} component={i.component}/>)}
</section>
/**
*
* @param props {object} {
* {string} path:地址
* {object} component:对应的组件
* }
* @constructor
*/
const Context = props =>
<Route exact path={props.path} component={props.component}/>
export default App |
const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml')
const prettify = require('prettify-xml')
const generatePictureList = require('../src/utils/generatePictureList.js')
const generateBlogList = require('../src/utils/generateBlogList.js')
const siteData = require('../src/utils/siteData.js')
async function render(pages, {
change = 'yearly',
priority = 0.6
} = {}) {
return prettify(`
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${
pages.map(page => `
<url>
<loc>${siteData.get('url')}/${page.path}</loc>
<changefreq>${page.change || change}</changefreq>
<priority>${page.priority || priority}</priority>
</url>
`).join('')
}
</urlset>
`)
}
fs.writeFileSync(
path.join(__dirname, '../static/sitemap.xml'),
render([
...siteData.get('pages'),
...generatePictureList(
path.join(__dirname, '../content/pictures')
),
...generateBlogList(
path.join(__dirname, '../content/blog')
)
])
)
|
var gulp = require('gulp');
var less = require('gulp-less');
var lessJsonImport = require('../index');
gulp.src(['*/style.less'])
.pipe(lessJsonImport())
.pipe(less())
.pipe(gulp.dest(__dirname + '/dist')); |
"use strict";
if ( typeof theory === 'undefined' ) {
throw new Error('You must load theory.js first.');
}
/*
* Theory's navigate handling -- allows for navigation around object structures
* in a similar way to jQuery.
*
* @module theory
* @class t.navigate
*/
t.internal.navigate = t.creator({
theory: {
prep: function(){
this.shared.empty = this.create();
},
requirements: [
function needIsJs(){ return typeof is != 'undefined' || new Error('This code requires is.js to be included.'); }
]
},
/*
* .shared is reserved for attributes that require a shared instance
* between instances of t.navigate(). By default methods are already shared.
*/
shared: {
simpleSelector: /^[a-z0-9 _.-]+$|^\*$/i,
lispSelector: /^\(\$\w+/i,
segmentedSelector: /\//,
endsWithSelector: /(^[^\/]+\$$)|(^\*[^\/]+$)/,
startsWithSelector: /(^\^[^\/]+$)|(^[^\/]+\*$)/,
empty: null
},
/*
* .i is reserved for internal data that is unique to this instance
*/
i: {
hasChildren: function(target){
for ( var i in target ) {
return true;
}
return false;
},
children: function(target, filter){
return (is.literalObject(target) && Object.values(target, filter)) || [];
},
hasParent: function(target){
return !!(target && target.parent);
},
parent: function(target, filter){
if ( target.parent ) {
if ( target.parent.call ) {
return [target.parent()];
}
else {
return [target.parent];
}
}
return [];
},
needsResolving: function(target){
return false;
},
resolve: function(target){
/// @TODO: theory needs to utilise Promises
return t.promise().resolve(target);
}
},
/*
* Return a new configuration of t.navigate().
* This can be used to create a version that operates slightly differently.
*
* @TODO: this should be handled using t.creator.namespace
*/
configuration: function(config){
var obj = this.create();
if ( config ) {
config.hasChildren && (obj.i.hasChildren = config.hasChildren);
config.children && (obj.i.children = config.children);
config.hasParent && (obj.i.hasParent = config.hasParent);
config.parent && (obj.i.parent = config.parent);
config.needsResolving && (obj.i.needsResolving = config.needsResolving);
config.resolve && (obj.i.resolve = config.resolve);
}
var caller = function(){ return obj.create.apply(obj, arguments); };
caller.configuration = function(){
return obj.configuration.apply(obj, arguments);
};
return caller;
},
/*
* Create a new instance of `t.navigate()`
*
* @static
* @method t.navigate.create
* @param target {Object} The target object to navigate
* @param [options] {Object} Configuration options
* @param [options.parents] {Boolean} Enable automatic `t.navigate.applyParents` to target
* @return {Object} an instance of `t.navigate`
* @chainable
*/
create: function(target, options){
var ret = this.prep.apply(Object.create(this), arguments);
ret.i.memories = Object.create(this.i.memories || {});
return ret;
},
/*
* Prep the new instance with references unique only to this instance.
* leave everything else shared. This is automatically called by `.create()`
*
* @method prep
* @param {Object} target
* @param {Object} [options]
* @return {Object} an instance of `t.navigate`
* @chainable
*/
prep: function(target, options){
this.i = Object.create(this.i);
this.i.targets = [];
target && options && options.parents && (target = this.applyParents(target));
target && (this.i.targets.push(target));
return this;
},
/*
* Recursively step an object structure and apply parent references
* This is rather awkward when it comes to plain JS Objects, however,
* for other data structures that already have parent references -- this
* step won't be required -- .parent() will just work.
*
* @static
* @method t.navigate.applyParents
* @param obj {Object} The object to apply the parents to.
* @param [maxDepth=100] {Number} To avoid possible circular loops.
* @param [depth=0] {Number} Internal parameter to keep track of recursion depth.
* @param [parent] {Function} Internal parameter for passing on the parent ref to recursed children.
* @return {Object} the original object that was passed in (unless it was a primitive, in which case `t.promotePrimitive(obj)` is returned instead.
*/
applyParents: function(obj, maxDepth, depth, parent){
if ( !depth ) depth = 0;
if ( !maxDepth ) maxDepth = 100; /// just in case
if ( depth > maxDepth ) return obj;
if ( !obj || obj.parent ) return obj;
/// support being called directly with a primative
if ( is.primitive(obj) ) {
obj = t.promotePrimitive(obj);
parent && (obj.parent = parent);
}
else {
parent && (obj.parent = parent);
var key, ref = this.createParentRef(obj);
for ( key in obj ) {
if ( key !== 'parent' && (!Object.prototype.hasOwnProperty || Object.prototype.hasOwnProperty.call(obj, key)) ) {
obj[key] = this.applyParents(obj[key], maxDepth, depth + 1, ref);
}
}
}
return obj;
},
/*
* Keep references to parents in closures to keep data exports clean
*
* @TODO: upgrade this to using Symbols with ES6
*/
createParentRef: function(parent){
return function(){return parent;};
},
/*
* Similar to jQuery's pushStack -- allows the addition of new targets
*
* @method pushStack
* @param {Array} items
* @return {Object} the current instance of `t.navigate`
* @chainable
*/
pushStack: function(items){
for ( var i=0, a=items, l=a.length, item; i<l; i++ ) {
if ( (item=a[i]) ) {
this.i.targets.push(item);
if ( this.i.needsResolving(item) ) {
if ( !this.i.resolving ) { this.i.resolving = []; }
this.i.resolving[i] = this.i.resolve(item);
}
}
}
return this;
},
/*
* Navigate an object's children, that are found using the
* internal children function. This defaults to looking for
* an array under the key of "children".
*
* @example
*
* #### Simple usage:
*
* t.navigate({children:[{a:1}, {b:2}, {c:3}]).children();
*
* #### Filter callback example:
*
* t.navigate({children:[{a:1}, {b:2}, {c:3}]).children(function(key, val){
* return !!val.a;
* });
*
* @method children
* @param {Array|String|Function} filter Filter in the children that will be matched, using either a string selector, a callback function or an array of either.
* @return {Object} a new instance of `t.navigate`, containing matched children
* @chainable
*/
children: function(filter){
var ret = this.create();
for ( var i=0, a=this.i.targets, l=a.length; i<l; i++ ) {
ret.pushStack( this.i.children(a[i], filter) );
};
return ret;
},
/*
* Treat an object's keyed items as children. It will only navigate
* down inside items that are objects.
*/
each: function(callback){
for ( var i=0, a=this.i.targets, l=a.length, item; i<l; i++ ) {
item = a[i];
if ( item && item.original ) { /// @TODO: is this a good idea?
item = item.original;
}
callback && callback.call && callback.call(this, item, i);
};
return this;
},
/*
* Remember a state accessible to all derived navigate objects
*/
rem: function(name){
name = name || 'default';
this.i.memories[name] = this;
return this;
},
/*
* Recall a remembered state
*/
rec: function(name){
name = name || 'default';
if ( this.i.memories && this.i.memories[name] ) {
return this.i.memories[name];
}
else {
return null;
}
},
/*
* From the current selection, move up the object structure
*
* @NOTE: This can only work if the object structure you are navigating
* has a reference stored back up to the parent.
*/
parent: function(filter){
var ret = this.create();
for ( var i=0, a=this.i.targets, l=a.length; i<l; i++ ) {
ret.pushStack( this.i.parent(a[i], filter) );
};
return ret;
},
/*
* List out the keys per each selected/targeted object
*/
getKeys: function(){
var ret = [];
for ( var i=0, a=this.i.targets, l=a.length; i<l; i++ ) {
ret = ret.concat(Object.keys(a[i]));
};
return ret;
},
/*
* This method expects a selector in Object Path Notation.
*/
select: function(opn, hint){
var ret = this.shared.empty; /// @TODO: Should this.shared.empty be cloned?
/// support for opn segments passed directly
if ( is.literalObject( opn ) && opn.type ) {
switch ( opn.type ) {
case 'segment':
ret = this.select(opn.string, opn);
break;
}
}
/// support for simple keyword selects
else if ( opn === '' || this.shared.simpleSelector.test(opn) ) {
switch ( opn ) {
/// the "you didn't mean to end with slash" selector
case '':
return this;
break;
/// wildcard filter
case '*':
ret = this.children();
break;
/// parent filter
case '..':
ret = this.parent();
break;
/// otherwise assume child filter
default:
ret = this.children(opn);
break;
}
return ret;
}
/// support for partial selectors, these aren't handled by OPN
/// and so should be detected by the navigation code.
else if ( this.shared.startsWithSelector.test(opn) ) {
if ( opn.indexOf('*') !== -1 ) {
opn = opn.substring(0, opn.length-1);
}
else if ( opn.charAt(0) === '^' ) {
opn = opn.substring(1, opn.length);
}
else {
opn = null;
}
if ( opn ) {
return this.children(function(key, val){
return key.indexOf(opn) === 0;
});
}
}
/// support for partial selectors, these aren't handled by OPN
/// and so should be detected by the navigation code.
else if ( this.shared.endsWithSelector.test(opn) ) {
if ( opn.charAt(0) === '*' ) {
opn = opn.substring(1, opn.length);
}
else if ( opn.indexOf('$') !== -1 ) { /// @TODO: should be more accurate
opn = opn.substring(0, opn.length-1);
}
else {
opn = null;
}
if ( opn ) {
return this.children(function(key, val){
return key.indexOf(opn) === 0;
});
}
}
/// support for functional selectors like ($keyContains ...)
/// @TODO: Currently t.string() doesn't support the ability to describe
/// a child group when there is no division. This means that ($key) can
/// not be fully parsed down to (, $key, ) -- whereas ($key ...) is fine
/// because it has a " " divider. For now lisp selectors will always
/// require an argument -- which is likely to be the operational case
/// anyway.
else if ( this.shared.lispSelector.test(opn) ) {
var name, func, args, kids = t.step(hint, 'children', 0, 'children', 0);
switch ( kids.type ) {
case 'spaces':
if ( (args = kids && kids.children) ) {
name = t.opn.wrap(args.shift()).string();
func = t.step(t.internal.object, 'selectors', name);
if ( func ) {
args = t.opn.wrap(args).strings();
return func.apply(this, args);
}
else {
return t.error(Error('Unknown selector function ' + name));
}
}
break;
}
}
else {
var notation = t.opn(opn),
segments = notation.segments(),
head = this,
segment
;
while ( +head && (segment=segments.next()) ) {
head = head.select( segment );
}
ret = head;
}
return ret;
},
get: function(){
return this.i.targets;
},
/*
* Simple little hack to allow this object to existence check with a simple number cast
*/
valueOf: function(){
return this.i.targets.length ? 1 : 0;
}
/// @TODO: map would be useful!
});
/*
* Set up some object selectors to improve t.object().select() support
*/
t.internal.object.selectors['$wildcardKey'] = t.method({
method: function(){
console.log(this, arguments);
}
});
/*
* Filter children based on a "contains" partial key.
*/
t.internal.object.selectors['$keyContains'] = t.method({
method: function(filter){
return this.children(function(key, val){
return key.indexOf(filter) !== -1;
});
}
});
/// one instance that navigates normal objects
t.object.navigate = t.navigate = t.internal.navigate.configuration(); |
describe('Controller: EditItemCtrl', function () {
// load the controller's module
beforeEach(module('barcodeCartBuilder', 'ionic', 'barcodeCartBuilder.services'));
var EditItemCtrl,
scope,
itemMock = {},
stateMock = {},
stateParamsMock = {};
var fakeBarcode1 = "123456789012";
var fakeBarcode2 = "888888888888";
var sampleItems = [
{itemId: "Yoohoo-1", itemGroupId: "1", itemDescription: "Yoohoo, 10 count", imageUrl: "http://upload.wikimedia.org/wikipedia/commons/b/b9/Yoohoo-boxes.jpg", quantity: 3}
];
// Initialize variables & mocks before each test
beforeEach(function () {
stateMock.go = jasmine.createSpy('go');
itemMock.clear = jasmine.createSpy('clear');
itemMock.all = jasmine.createSpy('all').andReturn(sampleItems);
itemMock.save = jasmine.createSpy('save');
stateParamsMock.itemIndex = 0;
}
);
it('should allow modification of quantity, saving and appropriate redirect', function () {
inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
//$scope, $timeout, Items, $state, SubmitCartService, $window
EditItemCtrl = $controller('EditItemCtrl', {
$scope: scope,
Items: itemMock,
$state: stateMock,
$stateParams: stateParamsMock
});
expect(scope.currentItem).toEqual(sampleItems[0]);
scope.currentItem.quantity = 999;
scope.processItem(scope.currentItem, false);
expect(itemMock.save).toHaveBeenCalledWith(sampleItems);
expect(stateMock.go).toHaveBeenCalledWith('home');
scope.processItem(scope.currentItem, true);
expect(itemMock.save).toHaveBeenCalledWith(sampleItems);
expect(stateMock.go).toHaveBeenCalledWith('scan');
});
});
}); |
import {isEmpty} from 'lodash';
export default function addFolderFormValidate(values) {
const errors = {};
if (! values.sourceLanguage) {
errors.sourceLanguage = {id: 'field-source-language-required'};
}
if (isEmpty(values.targetLanguages)) {
errors.targetLanguages = {id: 'choose-at-least-one-target-language'};
}
if (isEmpty(values.contentFields)) {
errors.contentFields = {id: 'choose-at-least-one-content-field'};
}
return errors;
}
|
/* @flow */
import { display } from '../display';
import { COLOR } from '../data/default';
import { DefineScale } from '../data/define';
import clip from '../clip/index';
export default function(settings: Object, _this: Global): GraghShape {
const draw = function() {
const canvas = _this.canvas;
const scale = _this.scale;
if(!this.fixed) {
DefineScale.call(this, scale, 'moveX', 'moveY', 'matrix', 'lineWidth');
}
const matrix = this.scaled_matrix;
canvas.save();
canvas.translate(this.scaled_moveX, this.scaled_moveY);
if(this.fixed) {
canvas.translate(-_this.transX, -_this.transY);
}
if(!this.hide) {
// clip path
canvas.beginPath();
clip(this, canvas, scale);
canvas.closePath();
canvas.beginPath();
matrix.forEach((point, i) => {
i === 0 ? canvas.moveTo(point[0], point[1]) : canvas.lineTo(point[0], point[1]);
});
canvas.lineTo(matrix[0][0], matrix[0][1]);
if(this.style === 'fill') {
canvas.fillStyle = this.color;
canvas.fill();
} else {
canvas.strokeStyle = this.color;
canvas.lineWidth = this.scaled_lineWidth;
canvas.stroke();
}
canvas.closePath();
}
canvas.restore();
};
return Object.assign({}, display(settings, _this), {
type: 'polygon',
draw: draw,
style: settings.style || 'fill',
color: settings.color || COLOR,
lineWidth: settings.lineWidth || 1,
matrix: settings.matrix,
scaled_matrix: settings.matrix
});
}
|
var callStdLibFn = require("../utils/callStdLibFn");
module.exports = function(ast, comp, e){
if(ast.value.length < 1){
return e("string", "");
}
var compElm = function(elm){
if(elm.type === "String"){
return e("string", elm.value, elm.loc);
}
return callStdLibFn(e, "beesting", [comp(elm)], elm.loc);
};
var curr = compElm(ast.value[0]);
var i = 1;
while(i < ast.value.length){
curr = e("+", curr, compElm(ast.value[i]));
i++;
}
return curr;
};
|
/*
* The MIT License
*
* Copyright 2012 Luis Salazar <[email protected]>.
*
* 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.
*/
documentController = {};
documentController.classifySymbol = function(e) {
var cm = $('#dcDocumentContent').data('codeMirror');
if (cm !== undefined) {
var selectedText = new String(cm.getSelection())
.replace(/^\s+|\s+$/g,'').substr(0,255);
baseController.showInfoBubble(selectedText, e.pageX, e.pageY);
}
};
documentController.update = function() {
baseController.ajaxRequest('/post/updateDocument', null, $('#dcUpdateForm').serialize());
}; |
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('lookup', function (table) {
table.integer('id').primary();
table.string('description').notNullable();
}),
knex.schema.table('sample', function (table) {
table.integer('value').references('id').inTable('lookup');
})
])
};
exports.down = function(knex, Promise) {
return Promise.all([
knex.schema.table('sample', function (table) {
table.dropColumn('value');
}),
knex.schema.dropTable('lookup')
])
};
|
define(module, function(exports, require) {
var code = {
hex: [
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F'
],
key: [
'NULL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT',
'FF', 'CR', 'SO', 'SI', 'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB',
'CAN', 'EM', 'SUB', 'ESC', 'FS', 'GS', 'RS', 'US', 'space', '!', '"', '#',
'$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
'<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '{', '|', '}', '~', 'delete'
]
};
function blue_white(s) { return `\x1b[47m\x1b[34m${s}\x1b[0m\x1b[0m`; }
function red(s) { return `\x1b[31m${s}\x1b[0m`; }
function green(s) { return `\x1b[32m${s}\x1b[0m`; }
function blue(s) { return `\x1b[34m${s}\x1b[0m`; }
function get_key(hex) {
var index = code.hex.indexOf(hex);
return index > -1 ? code.key[index] : '';
}
function get_hex(key) {
var index = code.key.indexOf(key);
return index > -1 ? code.hex[index] : '';
}
var child_process = require('child_process');
var readline = require('readline');
var qp = require('qp-utility');
qp.module(exports, {
blue_white: blue_white,
red: red,
green: green,
blue: blue,
exit: function(code) { process.exit(code || 0); },
set_title: function(title) {
process.stdout.write(String.fromCharCode(27) + ']0;' + title + String.fromCharCode(7));
},
clear: function() {
if (process.platform === 'win32') {
process.stdout.write('\033c');
} else {
process.stdout.write('\u001B[2J\u001B[0;0f');
}
},
log_title: function() { console.log(blue_white(qp.arg(arguments).join(''))); },
log: function() { console.log.apply(console, arguments); },
error: function() { console.error.apply(console, arguments); },
line: function() { console.log(); },
done: function(error) {
if (typeof error === 'string') {
console.error.apply(console, arguments);
} else if (typeof error === 'object' && error !== null) {
console.error(error.message);
} else {
console.log('Process Complete');
}
process.exit(error ? -1 : 0);
},
exec: function(command) {
return child_process.execSync(command);
},
run: function(command, options) {
return child_process.execSync(command, Object.assign({ stdio: [0,1,2] }, options));
},
keypress: function(handler) {
if (process.stdin.setRawMode) {
process.stdin.setRawMode(true);
process.stdin.setEncoding('utf8');
process.stdin.on('data', chr => {
var key = get_key(chr);
if (key === 'ETX') process.exit(0);
handler(key, chr);
});
process.stdin.resume();
}
},
/* USER INPUT */
input: function() {
var items = qp.arg(arguments);
var done = items.pop();
var results = {};
var next_input = () => {
if (items.length) {
var item = items.shift();
var action = item.action || (item.key === 'confirm' ? 'confirm' : item.options ? 'pick' : 'ask');
this[action](item, (error, result) => {
qp.override(results, result);
if (error) return done(error, results); else next_input();
});
} else {
done(null, results);
}
};
next_input();
},
confirm: function(data, done) {
var prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
if (data.default) data.default_text =` (${data.default})? `;
prompt.question(green(data.question + (data.default_text || '? ')), (answer) => {
prompt.close();
answer = qp.lower(answer || (data.default || 'n')).slice(0, 1);
done(null, { [data.key]: answer === 'y' });
});
},
ask: function(data, done) {
var prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
if (data.default) data.default_text =` (${data.default}): `;
prompt.question(green(data.question + (data.default_text || ': ')), (answer) => {
prompt.close();
done(null, { [data.key]: answer || data.default || '' });
});
},
pick: function(data, done) {
if (data.title) console.log(data.title);
data.default = {
option: null,
text: data.default ? ` (${data.default}): ` : ': ',
value: data.default
};
data.options.forEach((option, i) => {
option.key = option.key || i + 1;
console.log(`${option.key} - ${option.text}`);
if (option.default) {
data.default.option = option;
data.default.text = ` (${option.text}): `;
}
});
var prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
prompt.question(green(data.question + data.default.text), (answer) => {
prompt.close();
if (data.multi) {
if (answer === '') answer = data.default.value || '';
var options = qp.select(answer.split(''), key => {
var option = data.options.find(option => qp.lower(option.key) === qp.lower(key));
return qp.get(option, 'value', option);
});
done(null, { [data.key]: options });
} else {
var option = data.options.find(option => qp.lower(option.key) === qp.lower(answer)) || null;
if (data.default.option && !option) {
done(null, { [data.key]: qp.get(data.default.option, 'value', data.default.option) });
} else {
done(null, { [data.key]: qp.get(option, 'value', option) });
}
}
});
},
});
});
|
(function() {
'use strict';
angular
.module('portrack', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ngRoute', 'ui.bootstrap']);
})();
|
exports.config = {
namespace: 'castle',
generateDistribution: true,
bundles: [
{
components: [
'le-mirror',
'le-ascii-art'
]
}
]
};
exports.devServer = {
root: 'www',
watchGlob: '**/**'
}
|
//声明变量
//进度条显示层,背景层,方块绘制层,方块预览层
var loadingLayer,backLayer,graphicsMap,nextLayer;
var imglist = {};
var imgData = new Array(
{name:"backImage",path:"../1/images/backImage.png"},
{name:"r1",path:"../1/images/r1.png"},
{name:"r2",path:"../1/images/r2.png"},
{name:"r3",path:"../1/images/r3.png"},
{name:"r4",path:"../1/images/r4.png"}
);
//方块类变量,用于生成新的方块
var BOX;
//当前方块的位置
var pointBox={x:0,y:0};
//当前方块,预览方块
var nowBox,nextBox;
//方块坐标数组
var map;
//方块数据数组
var nodeList;
//方块图片数组
var bitmapdataList;
//得分相关
var point=0,pointText;
//消除层数相关
var del=0,delText;
//方块下落速度相关
var speed=15,speedMax=15,speedText,speedIndex = 0;
//方块区域起始位置
var START_X1=15,START_Y1=20,START_X2=228,START_Y2=65;
//控制相关
var myKey = {
keyControl:null,
step:1,
stepindex:0,
isTouchDown:false,
touchX:0,
touchY:0,
touchMove:false
};
function main(){
//方块类变量初始化
BOX = new Box();
//方块坐标数组初始化
map=[
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]
];
//背景层初始化
backLayer = new LSprite();
//在背景层上绘制黑色背景
backLayer.graphics.drawRect(1,"#000000",[0,0,800,450],true,"#000000");
//背景显示
addChild(backLayer);
//进度条读取层初始化
loadingLayer = new LoadingSample1();
//进度条读取层显示
backLayer.addChild(loadingLayer);
//利用LLoadManage类,读取所有图片,并显示进度条进程
LLoadManage.load(
imgData,
function(progress){
loadingLayer.setProgress(progress);
},
gameInit
);
}
//读取完所有图片,进行游戏标题画面的初始化工作
function gameInit(result){
//取得图片读取结果
imglist = result;
//移除进度条层
backLayer.removeChild(loadingLayer);
loadingLayer = null;
//显示游戏标题
var title = new LTextField();
title.x = 50;
title.y = 100;
title.size = 30;
title.color = "#ffffff";
title.text = "俄罗斯方块";
backLayer.addChild(title);
//显示说明文
backLayer.graphics.drawRect(1,"#ffffff",[50,240,220,40]);
var txtClick = new LTextField();
txtClick.size = 18;
txtClick.color = "#ffffff";
txtClick.text = "点击页面开始游戏";
txtClick.x = (LGlobal.width - txtClick.getWidth())/2;
txtClick.y = 245;
backLayer.addChild(txtClick);
//添加点击事件,点击画面则游戏开始
backLayer.addEventListener(LMouseEvent.MOUSE_UP,gameToStart);
}
//游戏画面初始化
function gameToStart(){
//背景层清空
backLayer.die();
backLayer.removeAllChild();
//背景图片显示
var bitmap = new LBitmap(new LBitmapData(imglist["backImage"]));
backLayer.addChild(bitmap);
//得分表示
pointText = new LTextField();
pointText.x = 240;
pointText.y = 200;
pointText.size = 20;
backLayer.addChild(pointText);
//消除层数表示
delText = new LTextField();
delText.x = 240;
delText.y = 290;
delText.size = 20;
backLayer.addChild(delText);
//速度表示
speedText = new LTextField();
speedText.x = 240;
speedText.y = 385;
speedText.size = 20;
backLayer.addChild(speedText);
//将游戏得分,消除层数以及游戏速度显示到画面上
showText();
//方块绘制层初始化
graphicsMap = new LSprite();
backLayer.addChild(graphicsMap);
//方块预览层初始化
nextLayer = new LSprite();
backLayer.addChild(nextLayer);
//将方块的图片数据保存到数组内
bitmapdataList = [
new LBitmapData(imglist["r1"]),
new LBitmapData(imglist["r2"]),
new LBitmapData(imglist["r3"]),
new LBitmapData(imglist["r4"])
];
//方块数据数组初始化
nodeList = [];
var i,j,nArr,bitmap;
for(i=0;i<map.length;i++){
nArr = [];
for(j=0;j<map[0].length;j++){
bitmap = new LBitmap(bitmapdataList[0]);
bitmap.x = bitmap.getWidth()*j+START_X1;
bitmap.y = bitmap.getHeight()*i+START_Y1;
graphicsMap.addChild(bitmap);
nArr[j] = {"index":-1,"value":0,"bitmap":bitmap};
}
nodeList[i] = nArr;
}
//预览层显示
getNewBox();
//将当前下落方块显示到画面上
plusBox();
//添加循环播放事件侦听
backLayer.addEventListener(LEvent.ENTER_FRAME, onframe);
//添加鼠标按下,鼠标弹起和鼠标移动事件
backLayer.addEventListener(LMouseEvent.MOUSE_DOWN,touchDown);
backLayer.addEventListener(LMouseEvent.MOUSE_UP,touchUp);
backLayer.addEventListener(LMouseEvent.MOUSE_MOVE,touchMove);
if(!LGlobal.canTouch){
//PC的时候,添加键盘事件 【上 下 左 右】
LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_DOWN,onkeydown);
LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_UP,onkeyup);
}
}
//游戏得分,消除层数以及游戏速度显示
function showText(){
pointText.text = point;
delText.text = del;
speedText.text = speedMax - speed + 1;
}
//键盘按下事件
function onkeydown(event){
if(myKey.keyControl != null)return;
if(event.keyCode == 37){//left
myKey.keyControl = "left";
}else if(event.keyCode == 38){//up
myKey.keyControl = "up";
}else if(event.keyCode == 39){//right
myKey.keyControl = "right";
}else if(event.keyCode == 40){//down
myKey.keyControl = "down";
}
}
//键盘弹起事件
function onkeyup(event){
myKey.keyControl = null;
myKey.stepindex = 0;
}
//鼠标按下
function touchDown(event){
myKey.isTouchDown = true;
myKey.touchX = Math.floor(event.selfX / 20);
myKey.touchY = Math.floor(event.selfY / 20);
myKey.touchMove = false;
myKey.keyControl = null;
}
//鼠标弹起
function touchUp(event){
myKey.isTouchDown = false;
if(!myKey.touchMove)myKey.keyControl = "up";
}
//鼠标移动
function touchMove(event){
if(!myKey.isTouchDown)return;
var mx = Math.floor(event.selfX / 20);
if(myKey.touchX == 0){
myKey.touchX = mx;
myKey.touchY = Math.floor(event.selfY / 20);
}
if(mx > myKey.touchX){
myKey.keyControl = "right";
}else if(mx < myKey.touchX){
myKey.keyControl = "left";
}
if(Math.floor(event.selfY / 20) > myKey.touchY){
myKey.keyControl = "down";
}
}
//循环播放
function onframe(){
//首先,将当前下落方块移除画面
minusBox();
if(myKey.keyControl != null && myKey.stepindex-- < 0){
myKey.stepindex = myKey.step;
switch(myKey.keyControl){
case "left":
if(checkPlus(-1,0)){
pointBox.x -= 1;
if(LGlobal.canTouch || true){
myKey.keyControl = null;
myKey.touchMove = true;
myKey.touchX = 0;
}
}
break;
case "right":
if(checkPlus(1,0)){
pointBox.x += 1;
if(LGlobal.canTouch || true){
myKey.keyControl = null;
myKey.touchMove = true;
myKey.touchX = 0;
}
}
break;
case "down":
if(checkPlus(0,1)){
pointBox.y += 1;
if(LGlobal.canTouch || true){
myKey.keyControl = null;
myKey.touchMove = true;
myKey.touchY = 0;
}
}
break;
case "up":
changeBox();
if(LGlobal.canTouch || true){
myKey.keyControl = null;
myKey.stepindex = 0;
}
break;
}
}
if(speedIndex++ > speed){
speedIndex = 0;
if (checkPlus(0,1)){
pointBox.y++;
}else{
plusBox();
if(pointBox.y < 0){
gameOver();
return;
}
removeBox();
getNewBox();
}
}
plusBox();
drawMap();
}
//游戏结束
function gameOver(){
backLayer.die();
var txt = new LTextField();
txt.color = "#ff0000";
txt.size = 40;
txt.text = "游戏结束";
txt.x = (LGlobal.width - txt.getWidth())*0.5;
txt.y = 200;
backLayer.addChild(txt);
}
//绘制所有方块
function drawMap(){
var i,j,boxl = 15;
for(i=0;i<map.length;i++){
for(j=0;j<map[0].length;j++){
if(nodeList[i][j]["index"] >= 0){
nodeList[i][j]["bitmap"].bitmapData = bitmapdataList[nodeList[i][j]["index"]];
}else{
nodeList[i][j]["bitmap"].bitmapData = null;
}
}
}
}
//方块变形
function changeBox(){
var saveBox = nowBox;
nowBox = [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
];
var i,j;
for(i=0;i<saveBox.length;i++){
for(j=0;j<saveBox[1].length;j++){
nowBox[i][j]=saveBox[(3-j)][i];
}
}
if (!checkPlus(0,0)){
nowBox = saveBox;
}
}
//消除指定层的方块
function moveLine(line){
var i;
for(i=line;i>1 ;i--){
for(j=0;j<map[0].length;j++){
map[i][j]=map[i-1][j];
nodeList[i][j].index=nodeList[i-1][j].index;
}
}
for(j=0;j<map[0].length;j++){
map[0][j]=0;
nodeList[0][j].index=-1;
}
}
//消除可消除的方块
function removeBox(){
var i,j,count = 0;
for(i=pointBox.y;i<(pointBox.y+4);i++){
if(i < 0 || i >= map.length)continue;
for(j=0;j<map[0].length;j++){
if(map[i][j]==0){
break;
}
if(j==map[0].length - 1){
moveLine(i);
count++;
}
}
}
if(count == 0)return;
del += count;
if(count == 1){
point += 1;
}else if(count == 2){
point += 3;
}else if(count == 3){
point += 6;
}else if(count == 4){
point += 10;
}
if(speed > 1 && del / 100 >= (speedMax - speed + 1)){
speed--;
}
showText();
}
//判断是否可移动
function checkPlus(nx,ny){
var i,j;
for(i=0;i<nowBox.length;i++){
for(j=0;j<nowBox[i].length;j++){
if(i+pointBox.y + ny < 0){
continue;
}else if(i+pointBox.y + ny >= map.length || j+pointBox.x + nx < 0 || j+pointBox.x + nx >= map[0].length){
if(nowBox[i][j] == 0){
continue;
}else{
return false;
}
}
if(nowBox[i][j] > 0 && map[i+pointBox.y + ny][j+pointBox.x + nx] > 0){
return false;
}
}
}
return true;
}
//移除方块
function minusBox(){
var i,j;
for(i=0;i<nowBox.length;i++){
for(j=0;j<nowBox[i].length;j++){
if(i+pointBox.y < 0 || i+pointBox.y >= map.length || j+pointBox.x < 0 || j+pointBox.x >= map[0].length){
continue;
}
map[i+pointBox.y][j+pointBox.x]=map[i+pointBox.y][j+pointBox.x]-nowBox[i][j];
nodeList[i+pointBox.y][j+pointBox.x]["index"] = map[i+pointBox.y][j+pointBox.x] - 1;
}
}
}
//添加方块
function plusBox(){
var i,j;
for(i=0;i<nowBox.length;i++){
for(j=0;j<nowBox[i].length;j++){
if(i+pointBox.y < 0 || i+pointBox.y >= map.length || j+pointBox.x < 0 || j+pointBox.x >= map[0].length){
continue;
}
map[i+pointBox.y][j+pointBox.x]=nowBox[i][j]+map[i+pointBox.y][j+pointBox.x];
nodeList[i+pointBox.y][j+pointBox.x]["index"] = map[i+pointBox.y][j+pointBox.x] - 1;
}
}
}
//获取下一方块
function getNewBox(){
if (nextBox==null){
nextBox=BOX.getBox();
}
nowBox=nextBox;
pointBox.x=3;
pointBox.y=-4;
nextBox=BOX.getBox();
nextLayer.removeAllChild();
var i,j,bitmap;
for(i=0;i<nextBox.length;i++){
for(j=0;j<nextBox[0].length;j++){
if(nextBox[i][j] == 0){
continue;
}
bitmap = new LBitmap(bitmapdataList[nextBox[i][j] - 1]);
bitmap.x = bitmap.getWidth()*j+START_X2;
bitmap.y = bitmap.getHeight()*i+START_Y2;
nextLayer.addChild(bitmap);
}
}
} |
var underscore = require('underscore');
/**
* Before creating any "SourceModel" that has a valid "hasOne" association with any other "TargetModel",
* automatically update the relating model if we haven't been specifically disabled.
*
* @param {Object} values the data originally provided to SourceModel.update()
* @param {Object} queryOptions the options originally provided to SourceModel.update()
* @param {Function} callback the callback to allow SourceModel.update() to continue execution
* @return {Promise} optionally return the promise for use in spread()
*/
module.exports = function createTargetModelBeforeSourceModel(as, association, targetModel, instance, values, queryOptions, callback) {
try {
if (values[as] !== undefined && values[as] !== null && values[as].entity === undefined && typeof values[as] === 'object') {
var data = underscore.extend(
typeof values[as] === 'object' ? underscore.clone(values[as]) : { id: values[as] }
);
data[association.options.foreignKey] = instance[targetModel.primaryKey]
targetModel
.create(data, queryOptions)
.then(function(targetInstance) {
values[as] = targetInstance;
callback(null);
})
.catch(callback);
} else {
callback(null);
}
} catch(e) {
callback(e);
}
}; |
var applicationConfig = require('../config.js').application;
module.exports = function(server, handler) {
server.route({
method: 'POST',
path: applicationConfig.apiUrl + 'login',
handler: handler
});
};
|
var Dictionary = require("@kaoscript/runtime").Dictionary;
module.exports = function() {
let foo = (() => {
const d = new Dictionary();
d.bar = "hello";
return d;
})();
}; |
const BaseStepWithPipeline = require('./basestepwithpipeline.js');
const SimpleStep = require('./simplestep.js');
const { EventNames } = require('../Constants');
const { EffectNames } = require('../Constants');
/**
D. Duel Timing
D.1 Duel begins.
D.2 Establish challenger and challengee.
D.3 Duel honor bid.
D.4 Reveal honor dials.
D.5 Transfer honor.
D.6 Modify dueling skill.
D.7 Compare skill value and determine results.
D.8 Apply duel results.
D.9 Duel ends.
*/
class DuelFlow extends BaseStepWithPipeline {
constructor(game, duel, costHandler, resolutionHandler) {
super(game);
this.duel = duel;
this.costHandler = costHandler;
this.resolutionHandler = resolutionHandler;
this.pipeline.initialise([
new SimpleStep(this.game, () => this.setCurrentDuel()),
new SimpleStep(this.game, () => this.promptForHonorBid()),
new SimpleStep(this.game, () => this.modifyDuelingSkill()),
new SimpleStep(this.game, () => this.determineResults()),
new SimpleStep(this.game, () => this.announceResult()),
new SimpleStep(this.game, () => this.applyDuelResults()),
new SimpleStep(this.game, () => this.cleanUpDuel()),
new SimpleStep(this.game, () => this.game.checkGameState(true))
]);
}
setCurrentDuel() {
this.duel.previousDuel = this.game.currentDuel;
this.game.currentDuel = this.duel;
this.game.checkGameState(true);
}
promptForHonorBid() {
let prohibitedBids = {};
for(const player of this.game.getPlayers()) {
prohibitedBids[player.uuid] = [...new Set(player.getEffects(EffectNames.CannotBidInDuels))];
}
this.game.promptForHonorBid('Choose your bid for the duel\n' + this.duel.getTotalsForDisplay(), this.costHandler, prohibitedBids);
}
modifyDuelingSkill() {
this.duel.modifyDuelingSkill();
}
determineResults() {
this.duel.determineResult();
}
announceResult() {
this.game.addMessage(this.duel.getTotalsForDisplay());
if(!this.duel.winner) {
this.game.addMessage('The duel ends in a draw');
}
this.game.raiseEvent(EventNames.AfterDuel, { duel: this.duel, winner: this.duel.winner, loser: this.duel.loser });
}
applyDuelResults() {
this.game.raiseEvent(EventNames.OnDuelResolution, { duel: this.duel }, () => this.resolutionHandler(this.duel));
}
cleanUpDuel() {
this.game.currentDuel = this.duel.previousDuel;
this.game.raiseEvent(EventNames.OnDuelFinished, { duel: this.duel });
}
}
module.exports = DuelFlow;
|
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// User Model
var User = require('../../models/user.server.model.js');
//possibly refactor to use userCtrl later - may need verifyUser method
//var userCtrl = require('../../controllers/user.server.controller');
module.exports = function () {
passport.use(new LocalStrategy({
usernameField: 'userName',
passwordField: 'password',
},
function(username, password, done) {
User.findOne({ userName: username })
.exec(function(err, user) {
if (user===null) {
console.log("User profile does not exist.");
return done(null, false, { message: 'Incorrect username.' });
} else if (err) {
var errMsg = 'Sorry, there was an error locating your user profile ' + err;
console.log(errMsg);
} else if (user.password === password) {
console.log("login success!");
return done(null, {name: user.userName});
}
});
}
));
}; |
'use strict';
var DocBlock = require('./docBlock.js');
var marked = require('marked');
var fluf = require('fluf');
// marked.setOptions({
// renderer: new marked.Renderer(),
// gfm: true,
// tables: true,
// breaks: false,
// pedantic: false,
// sanitize: true,
// smartLists: true,
// smartypants: false
// });
var DocBlockParser = function DocBlockParser(conf) {
conf = conf || {};
this.docBlockPattern = conf.docBlockPattern || '\\\/\\\*\\\*[^]*?\\\*\\\/';
this.docBlockStrip = '(^\\\s*\\\/\\\*\\\*)|(\\\*\\\/\\\s*$)';
this.docLineStrip = '^\\\s*\\\* ?';
/**
* Skip markdown parsing
* @property {boolean} skipMarkdown
*/
this.skipMarkdown = conf.skipMarkdown || false;
/**
* Defines a doc tag pattern.
*
* The first capture group must match the tag name
* The second capture group must macht the value
*
* @property {string} docTagPattern
*/
this.docTagPattern = '\\\\?@(?!\{)([a-zA-Z][a-zA-Z0-9_-]+)(.*)';
};
/**
* Parse source for DocBlocks
* @param {String} source Input source code
* @return {Object} Returns an array of DocBlocks
*/
DocBlockParser.prototype.parse = function(source, type) {
if (typeof Buffer !== 'undefined' && source instanceof Buffer) {
source = source.toString();
}
if (typeof source !== 'string') {
throw new Error('Unknown input type!');
}
this.codeType = type;
this.source = source;
var reg = new RegExp(this.docBlockPattern, 'g');
var match;
var docBlocks = [];
var loop = function() {
return true;
};
while (loop()) {
match = reg.exec(source);
if (!match) {
break;
}
docBlocks.push({ raw: match[0], pos: reg.lastIndex });
}
var prevPos = this.source.length;
for (var i = docBlocks.length - 1; i >= 0; i--) {
var block = docBlocks[i];
var code = this.source.slice(block.pos, prevPos);
prevPos = block.pos - block.raw.length;
block.code = this.undentCode(code);
}
docBlocks = docBlocks.map(this.parseBlock, this);
if (!this.skipVars) {
docBlocks.forEach(this.parseInlineTags);
}
if (!this.skipMarkdown) {
docBlocks = docBlocks.map(this.parseMarkdown);
}
return docBlocks;
};
/**
* Parse a docblock
* @param {String} block DocBlock
* @return {Object} Returns a DocBlock object
*/
DocBlockParser.prototype.parseBlock = function(block) {
var blockBody = block.raw.replace(new RegExp(this.docBlockStrip, 'g'), '');
var tagArray = this.parseTags(blockBody.trim());
var docBlock = new DocBlock(this.codeType);
var line = this.getLine(block.pos);
docBlock.setSourceLine(line);
docBlock.setSourceCode(this.codeType, block.code);
docBlock.setSourceFile(this.codeType, '');
var newBlock;
try {
newBlock = docBlock.create(tagArray);
}
catch(err) {
throw new Error(err.message + '\n\n' + this.createCodeView(block));
}
newBlock.raw = block.raw;
newBlock.pos = block.pos;
return newBlock;
};
DocBlockParser.prototype.createCodeView = function(block) {
var nextLine = this.getLine(block.pos);
var codeView = block.raw.split('\n');
codeView = codeView.map(function(line) {
var lineNumber = String(' ' + nextLine).substr(-(String(nextLine + 6).length));
nextLine++;
return lineNumber + ' | ' + line.replace(/^\t|\s{2}/g, '');
});
return codeView.join('\n');
};
/**
* Parse DocBlock body for tags
* @param {String} block DocBlock body
* @return {Object} Returns a DocBlock tags array
*/
DocBlockParser.prototype.parseTags = function(block) {
var lines = this.stripBlockLines(block);
var line = {
tag: 'title',
value: ''
};
var tags = [line];
var lastIndention = null;
var lastTag = line;
var reg = new RegExp(this.docTagPattern);
for (var i = 0, len = lines.length; i < len; i++) {
var match = reg.exec(lines[i]);
if (match && match[1]) {
if (match[0][0] === '\\') {
lastTag.value += '\n' + lines[i].replace('\\@', '@');
continue;
}
line = {};
line.tag = match[1];
line.value = match[2].trim();
lastIndention = match.index;
lastTag = line;
tags.push(line);
}
else {
if (lastIndention === null) {
var testReg = /\S/.exec(lines[i]);
if (testReg) {
lastIndention = testReg.index;
}
}
var val = lines[i].substr(lastIndention);
if (val) {
lastTag.value += '\n' + val;
}
if (i === 0) {
line = {
tag: 'description',
value: ''
};
lastTag = line;
tags.push(line);
}
}
}
tags = tags.map(function(tag) {
tag.value = tag.value
.replace(/^ |\t$/g, '')
.replace(/\\\//g, '/');
return tag;
});
return tags;
};
DocBlockParser.prototype.parseMarkdown = function(block) {
var whiteList = ['title', 'description'];
var parseMd = function(obj) {
var keys = Object.keys(obj);
for (var i = 0, len = keys.length; i < len; i++) {
if (typeof obj[keys[i]] === 'string') {
if (whiteList.indexOf(keys[i]) !== -1) {
obj[keys[i]] = marked(obj[keys[i]]).replace(/(^<p>)|(<\/p>\n?$)/g, '');
}
continue;
}
if (typeof obj[keys[i]] === 'object') {
if (Array.isArray(obj[keys[i]])) {
obj[keys[i]] = obj[keys[i]].map(parseMd);
}
else if (obj[keys[i]] instanceof Object) {
obj[keys[i]] = parseMd(obj[keys[i]]);
}
}
}
return obj;
};
return parseMd(block);
};
DocBlockParser.prototype.stripBlockLines = function(block) {
var lines = [];
var line;
var split = block.split('\n');
var reg = new RegExp(this.docLineStrip);
for (var i = 0, len = split.length; i < len; i++) {
line = split[i].replace(reg, '');
lines.push(line);
}
return lines;
};
/**
* Gets line number of a specific index position
*
* @method getLine
* @param {number} index Gets line number relative to this index
*/
DocBlockParser.prototype.getLine = function(index) {
var str = this.source.slice(0, index);
str = str.split(/\n/);
return str.length;
};
DocBlockParser.prototype.undentCode = function (code) {
var split = code.split('\n');
var indention = null;
var buffer = [];
for (var i = 0, l = split.length; i < l; i++) {
if (indention === null) {
if (/^\s*$/.test(split[i])) {
continue;
}
var match = /^\s+/.exec(split[i]);
if (match) {
indention = new RegExp('^' + match[0]);
}
else {
buffer = split.slice(i);
break;
}
}
var line = split[i].replace(indention, '');
if (line === split[i] && /\S+/.test(line)) {
// No indention removed, must be next scope.
break;
}
buffer.push(line);
}
return buffer.join('\n').trim();
};
DocBlockParser.prototype.parseInlineTags = function(block) {
var reg = /\@\{([a-zA-Z0-9._-]+)\}/g;
block = fluf(block);
block.walk(function(value, key) {
if (this.type === 'string') {
var self = this;
return value.replace(reg, function(m, key) {
var blockItem = block.get(key) || '';
if (Array.isArray(blockItem)) {
return blockItem[self.index] || '';
}
return blockItem || '';
});
}
});
return block.toJSON();
}
DocBlockParser.prototype.toJSON = function () {
};
module.exports = DocBlockParser;
|
/*
R: the following works to send & exec stuff from an iMac to an Espruino board ( original ) using an audio cable
This is what needs to be called on the iMac side of things ( see AST - AduioSerialTest [ using Espruino's team code ] ):
AST.audio_serial_write('digitalWrite(LED3, 1);\n', function(){ console.log('data written !'); })
On the Espruino side, we connect to Gnd & the C11 pin ( Serial4 Rx ), & use the following code:
var dataBuff = '';
Serial4.setup(9600); // aka: use default Serial4 Rx pin ( C11 on original Espruino board )
Serial4.on('data', function(data){
dataBuff += data;
if ( dataBuff.indexOf('\n') !== -1 ){
print('>' + dataBuff); // prints perfectly EVERYTHING ^^
eval ( dataBuff ); // yup, "being [too] confident" ^^
dataBuff = ''; // clear/reset data buff
}
});
The circuit & connections used were the following ( TRRS cable )
sleeve ----|---- Espruino Gnd
|
47k
+ |
tip ---)|-- |---- Espruino Serial4Rx/C11
1uF
ring1
ring2
Aside from not being able to use a Bluetooth audio receiver to get stuff sent using audio serial,
the above code is absolutely NOT error proof ( & "dangerously" calls 'eval()' .. ;p )
This being said, few things can be done to improve that:
- ensure that 'dataBuff' only contains allow stuff ? -> 'd mean encoding our chars in little chunks,
less likely to be received ( & generated ) by pure random hazard, & then decoding them ..
=> let' do that .. later ;)
- ensure that 'dataBuff' starts with the correct stuff ( & hope that no glitches 'll be received before the ending '\n' )
-> 'd mean just checking before adding to dataBuff that we have already received the startChar,
OR discarding anything in the buffer that's before the startChar if it contains it, or altogether otherwise
=> yup, quick & easy
var dataBuff = '';
var startChar = '#'
Serial4.setup(9600); // aka: use default Serial4 Rx pin ( C11 on original Espruino board )
Serial4.on('data', function(data){
dataBuff += data;
if ( dataBuff.indexOf('\n') !== -1 ){ // line ending in buffer
if ( data.indexOf('#') !== -1 ){ // startChar present in buffer ( but gibberish may be present before it )
dataBuff = dataBuff.substr( dataBuff.indexOf('#')+1 ); // strip gibberish BEFORE the startChar
print('>' + dataBuff); // prints perfectly EVERYTHING ^^
eval ( dataBuff ); // yup, "being [too] confident" ^^
} else { // no startChar in buffer, yet a line ending ( may be got stuff from a previous session ? "whatever" )
print('prefixing gibberish discarded: ' + dataBuff); // at least, log stg ;)
}
dataBuff = ''; // clear/reset data buff
}
});
*/
|
var app = angular.module(‘myApp', [‘ngRoute’]);
app.config(function($routeProvider) {
$routeProvider.when('/page1', {
templateUrl: 'templates/page1.html',
controller: 'page1Controller'
});
$routeProvider.otherwise({
redirectTo: '/'
}); |
//@flow
import type { InteractionsWithElement } from 'services/domEvents';
import { MouseMovementEventsForElementProvider } from './MouseMovementEventsForElementProvider';
export function getMouseMovementEvents(element : HTMLElement) : InteractionsWithElement {
const provider = new MouseMovementEventsForElementProvider(element);
return provider.getInteractions();
} |
/**
* hilojs 2.0.2 for standalone
* Copyright 2016 alibaba.com
* Licensed under the MIT License
*/
!function(n){n.Hilo||(n.Hilo={});var o=n.Hilo.Class,e=n.Hilo.util,i=o.create({constructor:function(n){n=n||{},e.copy(this,n,!0)},renderType:null,canvas:null,stage:null,blendMode:"source-over",startDraw:function(n){},draw:function(n){},endDraw:function(n){},transform:function(){},hide:function(){},remove:function(n){},clear:function(n,o,e,i){},resize:function(n,o){}});n.Hilo.Renderer=i}(window); |
export function fuzzyBinarySearch(elements, value, accessor) {
let lo = 0,
hi = elements.length - 1,
best = null,
bestValue = null;
while (lo <= hi) {
let mid = (lo + hi) >>> 1;
let midValue = accessor(elements[mid]);
if (bestValue === null || Math.abs(midValue - value) < Math.abs(bestValue - value)) {
best = mid;
bestValue = midValue;
}
if (midValue < value) { lo = mid + 1; continue; }
if (midValue > value) { hi = mid - 1; continue; }
break;
}
return best;
}
|
angular.module("ehelseEditor",
["ui.router","ui.bootstrap","ngRoute","angularModalService", "checklist-model", "ngCookies","cfp.loadingBar","ngMessages", "angular-autogrow"])
.config(["$compileProvider", "$provide", function ($compileProvider, $provide) {
$compileProvider.debugInfoEnabled(false);
$provide.decorator('$window', function($delegate) {
Object.defineProperty($delegate, 'history', {get: function(){ return null; }});
return $delegate;
});
}]); |
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
// Node module: generator-loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var url = require('url');
var chalk = require('chalk');
var generator = require('loopback-swagger');
var request = require('request');
var yaml = require('js-yaml');
var fs = require('fs');
var async = require('async');
function buildUrl(base, path) {
if (path.indexOf('/') === 0) {
path = path.substring(1);
}
var baseUrl = url.parse(base);
var pathName = baseUrl.pathname;
if (pathName.substring(pathName.length - 1) !== '/') {
pathName = pathName + '/';
}
base = url.resolve(base, pathName);
return url.resolve(base, path);
}
/**
* Load swagger specs from the given url or file path; handle yml or json
* @param {String} specUrlStr The url or file path to the swagger spec
* @param cb
*/
function loadSpec(specUrlStr, log, cb) {
log(chalk.blue('Loading ' + specUrlStr + '...'));
var specUrl = url.parse(specUrlStr);
specUrl.pathname = encodeURI(specUrl.pathname);
if (specUrl.protocol === 'http:' || specUrl.protocol === 'https:') {
var options = {
url: url.format(specUrl),
headers: {
'Accept': 'application/json'
}
};
request.get(options, function (err, res, body) {
if (err) {
return cb(err);
}
if (res.statusCode === 200) {
var spec;
try {
if (typeof body === 'string') {
spec = JSON.parse(body);
} else {
spec = body;
}
}
catch (err) {
return cb(err);
}
cb(null, spec);
} else {
err = new Error('HTTP status: ' + res.statusCode +
' [' + specUrlStr + ']');
err.details = body;
cb(err);
}
});
} else {
if (specUrl.href.match(/\.(yaml|yml)$/)) {
try {
var spec = yaml.safeLoad(fs.readFileSync(specUrl.href, 'utf8'));
cb(null, spec);
} catch (err) {
cb(err);
}
} else {
fs.readFile(specUrl.href, 'UTF-8', function (err, body) {
if (err) {
return cb(err);
}
try {
var spec = JSON.parse(body);
cb(null, spec);
} catch (err) {
cb(err);
}
});
}
}
}
/**
* Parse the spec. For v1.2, it will recursively load all the api specs
* @param {String} base The base url/path
* @param {Object} spec The swagger v1.2 resource listing or v2 spec
* @param cb
*/
function parseSpec(base, spec, log, cb) {
if (spec.swaggerVersion === '1.2') {
if (Array.isArray(spec.apis)) {
if (spec.apis[0] && spec.apis[0].operations) {
process.nextTick(function () {
cb(null, [spec]);
});
return;
}
var specs = [];
async.each(spec.apis, function (api, done) {
var apiUrl = buildUrl(base, api.path);
loadSpec(apiUrl, log, function (err, spec) {
specs.push(spec);
done(err);
});
}, function (err) {
cb(err, specs);
});
}
} else if (spec.swagger === '2.0') {
process.nextTick(function () {
cb(null, [spec]);
});
} else {
process.nextTick(function () {
var err = new Error('Invalid/unsupported swagger spec');
cb(err);
});
}
}
/**
* Generate code from a spec http/https url or file path
* @param {String} specUrl swagger spec http/https url or file path
* @param cb
*/
function generate(specUrl, log, cb) {
var apis = [];
loadSpec(specUrl, log, function (err, spec) {
if (err) {
return cb(err);
}
parseSpec(specUrl, spec, log, function (err, apiSpecs) {
if (err) {
return cb(err);
}
async.each(apiSpecs, function (apiSpec, done) {
var code = generator.generateRemoteMethods(apiSpec,
{modelName: 'SwaggerApi'});
var models = generator.generateModels(apiSpec);
var api = {
code: code,
models: models,
spec: apiSpec
};
apis.push(api);
done(null);
}, function (err) {
cb(err, apis);
});
});
});
}
module.exports = generate;
|
'use strict';
var paths = require('../options/paths.js');
var tslint = require('gulp-tslint');
var scsslint = require('gulp-scss-lint');
module.exports = function (gulp) {
gulp.task('lint:ts', function () {
return gulp.src(paths.src.typescript_lint)
.pipe(tslint())
.pipe(tslint.report('prose', {
emitError: false,
summarizeFailureOutput: true
}));
});
gulp.task('lint:sass', function () {
return gulp.src(paths.src.sass)
.pipe(scsslint({ 'config': paths.src.sass_lint }));
});
gulp.task('lint', ['lint:ts', 'lint:sass']);
}; |
/**
* Generic non bubling event system for core classes.
*/
(function() {
core.Class("lowland.base.Events", {
implement : [core.property.IEvent],
members : {
/**
* Fire event @type {String} on this class with special @value {var} and @old {var} parameter.
* This method is used by core property system to fire change events.
*/
fireEvent : function(type, value, old) {
return this.fireSpecialEvent(type, [value, old]);
},
/**
* Fire DIRECT event @type {String} on this class with special @value {var} and @old {var} parameter.
* This should only be used if button execution context have to be the same like in request for
* FullScreen mode.
*/
fireDirectEvent : function(type, value, old) {
return this.fireSpecialEvent(type, [value, old], true);
},
/**
* Fire event @type {String} on this class with @args {Array} as event parameters.
* If @direct {Boolean} is true an synchronous direct event is fired and executed
* immediately.
*/
fireSpecialEvent : function(type, args, direct) {
var events = core.Class.getEvents(this.constructor);
var cls = events[type] || lowland.events.Event;
return lowland.events.EventManager.fireEvent(this, type, cls, args, direct);
},
/**
* Add event listener on @event {String} to this class. If the event is fired the
* @callback {Function} is executed in @context {var?null}.
*/
addListener : function(event, callback, context) {
if (jasy.Env.getValue("debug")) {
var cls = core.Class.getEvents(this.constructor)[event];
if (!cls || !core.Class.isClass(cls)) {
//throw new Error("Class " + this.constructor + " has no event " + type);
console.warn("Class " + this.constructor + " has no event " + event + " to listen on");
}
}
lowland.events.EventManager.addListener(this, event, callback, context);
},
/**
* Add event listener on @event {String} to this class that is only executed once and removed afterwards.
* If the event is fired the @callback {Function} is executed in @context {var?null}.
*/
addListenerOnce : function(event, callback, context) {
if (jasy.Env.getValue("debug")) {
var cls = core.Class.getEvents(this.constructor)[event];
if (!cls || !core.Class.isClass(cls)) {
//throw new Error("Class " + this.constructor + " has no event " + type);
console.warn("Class " + this.constructor + " has no event " + event + " to listen on");
}
}
var self = this;
var cb = function() {
lowland.events.EventManager.removeListener(self, event, cb, context);
callback.apply(context, arguments);
};
lowland.events.EventManager.addListener(this, event, cb, context);
},
/**
* Remove event listener on @event {String} from this class that has @callback {Function?null} and @context {var?null} given.
*/
removeListener : function(event, callback, context) {
lowland.events.EventManager.removeListener(this, event, callback, context);
},
/**
* {Boolean} Returns if an event listener listens on @event {String} that has @callback {Function?null} and @context {var?null} given.
*/
hasListener : function(event, callback, context) {
return lowland.events.EventManager.hasListener(this, event, callback, context);
},
/**
* Disposed events on class. All listeners are removed.
*/
dispose : function() {
lowland.events.EventManager.removeAllListener(this);
},
/**
* Add event listener on @event {String} to @element {Element}. If the event is fired the
* @callback {Function} is executed in @context {var?null}.
*/
addNativeListener : function(element, event, callback, context, capture) {
var boundCallback;
if (!context) {
context = this;
}
lowland.bom.Events.listen(element, event, core.Function.bind(callback, context), capture);
},
/**
* Remove event listener on @event {String} from @element {Element} that has @callback {Function?null} and @context {var?null} given.
*/
removeNativeListener : function(element, event, callback, context, capture) {
if (!context) {
context = this;
}
lowland.bom.Events.unlisten(element, event, core.Function.bind(callback, context), capture);
}
}
});
})();
|
var assert = require('assert')
, svgicons2svgfont = require(__dirname + '/../src/index.js')
, Fs = require('fs')
, StringDecoder = require('string_decoder').StringDecoder
, Path = require("path");
// Helpers
function generateFontToFile(options, done, fileSuffix) {
var codepoint = 0xE001
, dest = __dirname + '/results/' + options.fontName
+ (fileSuffix || '') + '.svg'
, stream = svgicons2svgfont(Fs.readdirSync(__dirname + '/fixtures/' + options.fontName)
.map(function(file) {
var matches = file.match(/^(?:u([0-9a-f]{4})\-)?(.*).svg$/i);
return {
codepoint: (matches[1] ? parseInt(matches[1], 16) : codepoint++),
name: matches[2],
stream: Fs.createReadStream(__dirname + '/fixtures/' + options.fontName + '/' + file)
};
}), options);
stream.pipe(Fs.createWriteStream(dest)).on('finish', function() {
assert.equal(
Fs.readFileSync(__dirname + '/expected/' + options.fontName
+ (fileSuffix || '') + '.svg',
{encoding: 'utf8'}),
Fs.readFileSync(dest,
{encoding: 'utf8'})
);
done();
});
}
function generateFontToMemory(options, done) {
var content = ''
, decoder = new StringDecoder('utf8')
, codepoint = 0xE001
, stream = svgicons2svgfont(Fs.readdirSync(__dirname + '/fixtures/' + options.fontName)
.map(function(file) {
var matches = file.match(/^(?:u([0-9a-f]{4})\-)?(.*).svg$/i);
return {
codepoint: (matches[1] ? parseInt(matches[1], 16) : codepoint++),
name: matches[2],
stream: Fs.createReadStream(__dirname + '/fixtures/' + options.fontName + '/' + file)
};
}), options);
stream.on('data', function(chunk) {
content += decoder.write(chunk);
});
stream.on('finish', function() {
assert.equal(
Fs.readFileSync(__dirname + '/expected/' + options.fontName + '.svg',
{encoding: 'utf8'}),
content
);
done();
});
}
// Tests
describe('Generating fonts to files', function() {
it("should work for simple SVG", function(done) {
generateFontToFile({
fontName: 'originalicons'
}, done);
});
it("should work for simple fixedWidth and normalize option", function(done) {
generateFontToFile({
fontName: 'originalicons',
fixedWidth: true,
normalize: true
}, done, 'n');
});
it("should work for simple SVG", function(done) {
generateFontToFile({
fontName: 'cleanicons'
}, done);
});
it("should work for codepoint mapped SVG icons", function(done) {
generateFontToFile({
fontName: 'prefixedicons',
callback: function(){}
}, done);
});
it("should work with multipath SVG icons", function(done) {
generateFontToFile({
fontName: 'multipathicons'
}, done);
});
it("should work with simple shapes SVG icons", function(done) {
generateFontToFile({
fontName: 'shapeicons'
}, done);
});
it("should work with variable height icons", function(done) {
generateFontToFile({
fontName: 'variableheighticons'
}, done);
});
it("should work with variable height icons and the normalize option", function(done) {
generateFontToFile({
fontName: 'variableheighticons',
normalize: true
}, done, 'n');
});
it("should work with variable width icons", function(done) {
generateFontToFile({
fontName: 'variablewidthicons'
}, done);
});
it("should work with centered variable width icons and the fixed width option", function(done) {
generateFontToFile({
fontName: 'variablewidthicons',
fixedWidth: true,
centerHorizontally: true
}, done, 'n');
});
it("should not display hidden pathes", function(done) {
generateFontToFile({
fontName: 'hiddenpathesicons'
}, done);
});
it("should work with real world icons", function(done) {
generateFontToFile({
fontName: 'realicons'
}, done);
});
it("should work with rendering test SVG icons", function(done) {
generateFontToFile({
fontName: 'rendricons'
}, done);
});
it("should work with a single SVG icon", function(done) {
generateFontToFile({
fontName: 'singleicon'
}, done);
});
it("should work with transformed SVG icons", function(done) {
generateFontToFile({
fontName: 'transformedicons'
}, done);
});
it("should work when horizontally centering SVG icons", function(done) {
generateFontToFile({
fontName: 'tocentericons',
centerHorizontally: true
}, done);
});
});
describe('Generating fonts to memory', function() {
it("should work for simple SVG", function(done) {
generateFontToMemory({
fontName: 'originalicons'
}, done);
});
it("should work for simple SVG", function(done) {
generateFontToMemory({
fontName: 'cleanicons'
}, done);
});
it("should work for codepoint mapped SVG icons", function(done) {
generateFontToMemory({
fontName: 'prefixedicons'
}, done);
});
it("should work with multipath SVG icons", function(done) {
generateFontToMemory({
fontName: 'multipathicons'
}, done);
});
it("should work with simple shapes SVG icons", function(done) {
generateFontToMemory({
fontName: 'shapeicons'
}, done);
});
});
describe('Using options', function() {
it("should work with fixedWidth option set to true", function(done) {
generateFontToFile({
fontName: 'originalicons',
fixedWidth: true
}, done, '2');
});
it("should work with custom fontHeight option", function(done) {
generateFontToFile({
fontName: 'originalicons',
fontHeight: 800
}, done, '3');
});
it("should work with custom descent option", function(done) {
generateFontToFile({
fontName: 'originalicons',
descent: 200
}, done, '4');
});
it("should work with fixedWidth set to true and with custom fontHeight option", function(done) {
generateFontToFile({
fontName: 'originalicons',
fontHeight: 800,
fixedWidth: true
}, done, '5');
});
it("should work with fixedWidth and centerHorizontally set to true and with custom fontHeight option", function(done) {
generateFontToFile({
fontName: 'originalicons',
fontHeight: 800,
fixedWidth: true,
centerHorizontally: true
}, done, '6');
});
it("should work with fixedWidth, normalize and centerHorizontally set to true and with custom fontHeight option", function(done) {
generateFontToFile({
fontName: 'originalicons',
fontHeight: 800,
normalize: true,
fixedWidth: true,
centerHorizontally: true
}, done, '7');
});
});
describe('Testing CLI', function() {
it("should work for simple SVG", function(done) {
(require('child_process').exec)(
'node '+__dirname+'../bin/svgicons2svgfont.js '
+ __dirname + '/expected/originalicons.svg '
+ __dirname + '/results/originalicons.svg',
function() {
assert.equal(
Fs.readFileSync(__dirname + '/expected/originalicons.svg',
{encoding: 'utf8'}),
Fs.readFileSync(__dirname + '/results/originalicons.svg',
{encoding: 'utf8'})
);
done();
}
);
});
});
describe('Providing bad glyphs', function() {
it("should fail when not providing glyph name", function() {
var hadError = false;
try {
svgicons2svgfont([{
stream: Fs.createReadStream('/dev/null'),
codepoint: 0xE001
}]);
} catch(err) {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'Please provide a name for the glyph at index 0');
hadError = true;
}
assert.equal(hadError, true);
});
it("should fail when not providing codepoints", function() {
var hadError = false;
try {
svgicons2svgfont([{
stream: Fs.createReadStream('/dev/null'),
name: 'test'
}]);
} catch(err) {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'Please provide a codepoint for the glyph "test"');
hadError = true;
}
assert.equal(hadError, true);
});
it("should fail when providing the same codepoint twice", function() {
var hadError = false;
try {
svgicons2svgfont([{
stream: Fs.createReadStream('/dev/null'),
name: 'test',
codepoint: 0xE001
},{
stream: Fs.createReadStream('/dev/null'),
name: 'test2',
codepoint: 0xE001
}]);
} catch(err) {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'The glyph "test" codepoint seems to be used already elsewhere.');
hadError = true;
}
assert.equal(hadError, true);
});
it("should fail when providing the same name twice", function() {
var hadError = false;
try {
svgicons2svgfont([{
stream: Fs.createReadStream('/dev/null'),
name: 'test',
codepoint: 0xE001
},{
stream: Fs.createReadStream('/dev/null'),
name: 'test',
codepoint: 0xE002
}]);
} catch(err) {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'The glyph name "test" must be unique.');
hadError = true;
}
assert.equal(hadError, true);
});
});
|
import React from 'react'
import { CreditCardForm } from './index'
import { DefaultExample, CustomExample } from './examples'
import { DocsPage } from 'storybook/docs-page'
export default {
title: 'Form/CreditCardForm',
component: CreditCardForm,
parameters: {
docs: {
page: () => (
<DocsPage
filepath={__filename}
filenames={[
'index.js',
'components/cvc.js',
'components/expiry.js',
'components/helpers.js',
'components/number.js',
]}
importString="CreditCardForm"
/>
),
},
},
decorators: [story => <div className="story-Container">{story()}</div>],
}
export const Default = args => <DefaultExample {...args} />
export const withCustomComponents = args => <CustomExample {...args} />
|
let appKey='kid_HkPyH6eX7';
let appSecret='5110fa2733374292b1793f24a16abddd'
let hostUrl='https://baas.kinvey.com';
let masterSecret='9c397b386b744aa5afa3828a84f46899'
let requester={
register: payload=>{
return fetch(`${hostUrl}/user/${appKey}`,{
method:'POST',
headers:{
'Authorization': 'Basic ' + btoa(`${appKey}:${appSecret}`),
'Content-Type': 'application/json'
},
body:JSON.stringify({
'username':payload.username,
'password':payload.password,
'role':payload.role
})
}).then(res=>{
return res.json()
})
},
login: payload=>{
return fetch(`${hostUrl}/user/${appKey}/login`,{
method:'POST',
headers:{
'Authorization': 'Basic ' + btoa(`${appKey}:${appSecret}`),
'Content-Type': 'application/json'
},
body:JSON.stringify({
'username':payload.username,
'password':payload.password,
})
}).then(res=>{
return res.json()
})
},
addPost: payload=>{
return fetch(`${hostUrl}/appdata/${appKey}/posts`,{
method:'POST',
headers:{
'Authorization': 'Kinvey ' +localStorage.getItem('token'),
'Content-Type': 'application/json'
},
body:JSON.stringify({
'title':payload.title,
'description':payload.description,
'typeAnimal':payload.typeAnimal,
'price':payload.price,
'imageUrl':payload.imageUrl,
'author':payload.author
})
}).then(res=>{
return res.json()
})
},
listAllPosts: function(){
return fetch(`${hostUrl}/appdata/${appKey}/posts?query={}&sort={"_kmd.ect": -1}`,{
method:'GET',
headers:{
'Authorization': 'Basic ' + btoa(`${appKey}:${masterSecret}`),
}
}).then(res=>{
return res.json()
})
},
listMyPosts: username=>{
return fetch(`${hostUrl}/appdata/${appKey}/posts?query={"author":"${username}"}&sort={"_kmd.ect": -1}`,{
method:'GET',
headers:{
'Authorization': 'Basic ' + btoa(`${appKey}:${masterSecret}`),
}
}).then(res=>{
return res.json()
})
},
deletePost: id=>{
return fetch(`${hostUrl}/appdata/${appKey}/posts/${id}`,{
method:'DELETE',
headers:{
'Authorization': 'Basic ' + btoa(`${appKey}:${masterSecret}`),
}
}).then(res=>{
return res.json()
})
},
getPost: function(id){
return fetch(`${hostUrl}/appdata/${appKey}/posts/${id}`,{
method:'GET',
headers:{
'Authorization': 'Kinvey ' +localStorage.getItem('token'),
}
}).then(res=>{
return res.json()
})
},
editPost: function(id,payload){
return fetch(`${hostUrl}/appdata/${appKey}/posts/${id}`,{
method:'PUT',
headers:{
'Authorization': 'Basic ' + btoa(`${appKey}:${masterSecret}`),
'Content-Type': 'application/json'
},
body:JSON.stringify({
'title':payload.title,
'description':payload.description,
'typeAnimal':payload.typeAnimal,
'price':payload.price,
'imageUrl':payload.imageUrl,
'author':payload.author
})
}).then(res=>{
return res.json()
})
},
//admin func
adminDeletePost: id=>{
return fetch(`${hostUrl}/appdata/${appKey}/posts/${id}`,{
method:'DELETE',
headers:{
'Authorization': 'Basic ' +localStorage.getItem('token'),
}
}).then(res=>{
return res.json()
})
},
}
export default requester |
var instagramPictures = new Array();
function refreshInstagram(){
$.get("getInstagram.php").done(function(data){
instagramPictures = new Array();
var instagramData = jQuery.parseJSON(data);
console.log("Amount of Instagrams: " + instagramData.length);
for (var i = 0; i < instagramData.length; i++) {
console.log("adding instagram picture: "+i);
instagramPictures[i] =("<img src='" + instagramData[i].image +"' ></img><br/>"
+"<div class='social_username'><img class='social_username' src=" + instagramData[i].profile_picture+ "></img> @"
+ instagramData[i].user + "</div><br/>"
+ instagramData[i].text);
}
});
}
var currentInstagramPicture = 0;
function rotateInstagram() {
if(instagramPictures.length > 0){ //added this as the instagram pictures may still be loading on first run
console.log ("shown picture" + currentInstagramPicture + "of "+ instagramPictures.length);
$(".instagram_logo").show();
$(".twitter_logo").hide();
$(".social").html(instagramPictures[currentInstagramPicture]);
currentInstagramPicture = (currentInstagramPicture==instagramPictures.length-1) ? 0 : currentInstagramPicture + 1;
}
}
|
Ext.define('cat.view.Main', {
extend: "Ext.Map",
xtype: 'mapview',
id:'map11',
config: {
mapOptions: {
center: new google.maps.LatLng(26.6300, 92.8000),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
zoom:6,
},
}
}); |
var util = require('util');
var User = require('../entities/User');
var MainModel = require('../../../lib/main/main-model');
/**
* @author Macky Dieng
* @license MIT - http://opensource.org/licenses/MIT
* @copyright 2016 the author
*
* Represents a UserModel
* @constructor
*/
function UserModel() {
/**
* The collection to use for this manager
*/
var collection = 'users';
/***
* Calling the super manager constructor
*/
MainModel.call(this, collection, User);
}
/*******************
* Bind your manager to the super manager here by completing the first parameter
*******************/
util.inherits(UserModel,MainModel);
/******Exporting the module**********/
module.exports = UserModel;
|
'use strict';
app.factory('organizerData', function ($resource, $http, $q) {
var url = 'http://localhost:9274/';
function parseErrors (serverError) {
var errors = [];
if (serverError && serverError.error_description) {
errors.push(serverError.error_description);
}
if (serverError && serverError.modelState) {
var modelStateErrors = serverError.modelState;
for (var propertyName in modelStateErrors) {
var errorMessages = modelStateErrors[propertyName];
var trimmedName = propertyName.substr(propertyName.indexOf('.') + 1);
for (var i = 0; i < errorMessages.length; i++) {
var currentError = errorMessages[i];
errors.push(trimmedName + ' - ' + currentError);
}
}
}
if (errors.length > 0) {
var msg = "<br>" + errors.join("<br>");
return msg;
}
}
function register (username, password) {
var deferred = $q.defer();
$http.post(url + 'api/Account/Register', {
Username: username,
Password: password,
ConfirmPassword: password
},
{
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(parseErrors(data));
});
return deferred.promise;
};
function login (username, password) {
var deferred = $q.defer();
$http.post(url + 'Token', {
username: username,
password: password,
grant_type: "password"
},
{
transformRequest : function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(parseErrors(data));
});
return deferred.promise;
};
function postOraganizerTask (access_token, organizerTask) {
var deferred = $q.defer();
$http.post(url + 'api/OrganizerTasks/Post',
organizerTask,
{
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': 'Bearer ' + access_token
}
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(parseErrors(data));
});
return deferred.promise;
}
function getOraganizerTasks(access_token) {
var deferred = $q.defer();
$http.get(url + 'api/OrganizerTasks/Get',
{
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': 'Bearer ' + access_token
}
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(parseErrors(data));
});
return deferred.promise;
}
function getOraganizerTaskById(access_token, taskId) {
var deferred = $q.defer();
$http.get(url + 'api/OrganizerTasks/Get/' + taskId,
{
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': 'Bearer ' + access_token
}
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(parseErrors(data));
});
return deferred.promise;
}
function putOraganizerTask (access_token, organizerTask) {
var deferred = $q.defer();
$http.put(url + 'api/OrganizerTasks/Put/' + organizerTask.id,
organizerTask,
{
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': 'Bearer ' + access_token
}
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(parseErrors(data));
});
return deferred.promise;
}
function deleteOraganizerTask (access_token, taskId) {
var deferred = $q.defer();
$http.delete(url + 'api/OrganizerTasks/Delete/' + taskId,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': 'Bearer ' + access_token
}
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(parseErrors(data));
});
return deferred.promise;
}
return {
account: {
register: register,
login: login
},
organizerTask: {
postOraganizerTask: postOraganizerTask,
getOrganizerTasks: getOraganizerTasks,
deleteOraganizerTask: deleteOraganizerTask,
getOraganizerTaskById: getOraganizerTaskById,
putOraganizerTask: putOraganizerTask
}
};
});
|
const copyThemeDir = require('../../lib/copy-theme-dir')
exports.command = 'theme-init [dirName]'
exports.describe = 'Copy theme directory to working directory.'
exports.builder = yargs => {
yargs.options({
d: {
alias: 'destDir',
default: 'theme',
requiresArg: true,
describe: 'Path of directory to write out converted html',
type: 'string',
},
})
}
exports.handler = argv => {
copyThemeDir(argv.destDir)
}
|
var FiltersModule = angular.module('FiltersModule');
FiltersModule.filter('VisibilityToButtonStyleFilter', function ()
{
return function (input)
{
return input ? 'btn btn-danger' : 'btn btn-primary';
};
}); |
import $ from 'jquery';
import _ from 'underscore';
import People from './people';
export default class Area {
constructor(name) {
this.name = name;
this.people = new People;
}
load(people) {
_.each(people, (value, key) => {
this.people.addAge(value.age, value.man, value.female);
});
}
}
|
import { module, test } from 'qunit';
import { currentURL, visit } from '@ember/test-helpers';
import { find } from 'ember-native-dom-helpers';
import { setupApplicationTest } from 'ember-qunit';
const styleString = 'touch-action: manipulation; -ms-touch-action: manipulation; cursor: pointer;';
module('Acceptance | index', function(hooks) {
setupApplicationTest(hooks);
test('visiting /index, ensures we hooked everything up appropriately', async function(assert) {
await visit('/');
assert.equal(currentURL(), '/');
let linkComponent = find('#indexLink').getAttribute('style');
let clickComponent = find('#clickComponent').getAttribute('style');
let nativeLink = find('#nativeLink').getAttribute('style');
let onClickElement = find('#actionOnClick').getAttribute('style');
let actionElement = find('#actionElement').getAttribute('style');
assert.equal(linkComponent, styleString, `Actual Link Style: ${linkComponent}`);
assert.equal(clickComponent, styleString, `Actual Click Component Style: ${clickComponent}`);
assert.equal(nativeLink, styleString, `Actual Anchor Style: ${nativeLink}`);
assert.equal(onClickElement, styleString, `Actual onClick Element Style: ${onClickElement}`);
assert.equal(actionElement, styleString, `Actual action Element Style: ${actionElement}`);
});
});
|