code stringlengths 2 1.05M |
|---|
/* */
var stream = require("readable-stream");
var duplexer2 = require("./index");
var writable = new stream.Writable({objectMode: true}),
readable = new stream.Readable({objectMode: true});
writable._write = function _write(input, encoding, done) {
if (readable.push(input)) {
return done();
} else {
readable.once("drain", done);
}
};
readable._read = function _read(n) {};
writable.once("finish", function() {
setTimeout(function() {
readable.push(null);
}, 500);
});
var duplex = duplexer2(writable, readable);
duplex.on("data", function(e) {
console.log("got data", JSON.stringify(e));
});
duplex.on("finish", function() {
console.log("got finish event");
});
duplex.on("end", function() {
console.log("got end event");
});
duplex.write("oh, hi there", function() {
console.log("finished writing");
});
duplex.end(function() {
console.log("finished ending");
});
|
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var QuoteSchema = new Schema({
Symbol: String,
'Date': Date,
Open: Number,
High: Number,
Low: Number,
Close: Number,
Volume: Number,
Adj_Close: Number
});
module.exports = mongoose.model('Quote', QuoteSchema); |
var InspectletAPI = require('../lib/inspectletapi.js');
var config = require('./config.json');
var insp = new InspectletAPI(config.username, config.password, false);
insp.logIn(function (logInError, logInData) {
console.log('logged in');
insp.getSites(function (error, data) {
console.log(data);
insp.logOut(function (logOutError, logOutData) {
console.log('logged out');
});
});
}); |
/**
* Copyright reelyActive 2015-2016
* We believe in an open Internet of Things
*/
var util = require('util');
var events = require('events');
var midimaps = require('./utils/midimaps');
var channelmaps = require('./utils/channelmaps');
var DEFAULT_MIDI_MAP = 'cMaj';
var DEFAULT_CHANNEL_MAP = 'allOnOne';
var DEFAULT_CHANNEL = 0;
var DEFAULT_DURATION = 60;
var DEFAULT_ON = { realTime: true, periodic: false };
/**
* DevicesManager Class
* Maintains the state of devices and manages their events
* @param {Object} options The options as a JSON object.
* @constructor
*/
function DevicesManager(options) {
var self = this;
self.midiMap = options.midiMap || DEFAULT_MIDI_MAP;
self.channelMap = options.channelMap || DEFAULT_CHANNEL_MAP;
self.defaultDuration = options.defaultDuration || DEFAULT_DURATION;
self.defaultOn = options.defaultOn || DEFAULT_ON;
self.devices = {};
self.controls = { mute: false, midiMap: DEFAULT_MIDI_MAP,
channelMap: DEFAULT_CHANNEL_MAP, solo: null };
events.EventEmitter.call(this);
}
util.inherits(DevicesManager, events.EventEmitter);
/**
* Handle an event, update the state of the associated device.
* @param {String} type The type of event.
* @param {Object} tiraid The tiraid object.
* @param {callback} callback Function to call on completion.
*/
DevicesManager.prototype.handleEvent = function(type, tiraid, callback) {
var self = this;
var id = tiraid.identifier.value;
// For Nearables, use the Nearable ID instead of the advertiser address
if(isNearable(tiraid)) {
id = tiraid.identifier.advData.manufacturerSpecificData.nearable.id;
}
// Remove devices that have disappeared, except Nearables
if((type === 'disappearance') && self.devices.hasOwnProperty(id) &&
!isNearable(tiraid)) {
delete self.devices[id];
return callback( { id: id, disappearance: true, valid: true } );
}
if(!tiraid.radioDecodings[0].identifier) {
return;
}
var rssi = tiraid.radioDecodings[0].rssi;
var strongestDecoder = tiraid.radioDecodings[0].identifier.value;
var decoders = tiraid.radioDecodings.length;
var decodings = {};
for(var cDecoding = 0; cDecoding < decoders; cDecoding++) {
if(!tiraid.radioDecodings[cDecoding].identifier) {
return;
}
var decoderId = tiraid.radioDecodings[cDecoding].identifier.value;
var decoderRssi = tiraid.radioDecodings[cDecoding].rssi;
decodings[decoderId] = decoderRssi;
}
// New device, initialise with random key
if(!self.devices.hasOwnProperty(id)) {
var key = midimaps.randomKey(parseInt(id, 16), self.midiMap);
var channel = channelmaps.randomChannel(parseInt(id, 16), self.channelMap);
var category = 'Instrument';
if(isNearable(tiraid)) {
category = 'Controller';
key = midimaps.randomKey(parseInt(id, 16) / 1000, 'allNotes');
}
self.devices[id] = { channel: channel, key: key,
duration: self.defaultDuration,
useBarnowl: self.defaultOn.realTime,
useBarnacles: self.defaultOn.periodic,
category: category, audio: "None" };
}
self.devices[id].rssi = rssi;
self.devices[id].strongestDecoder = strongestDecoder;
if(isNearable(tiraid)) {
self.devices[id].velocity = Math.max(Math.min(Math.round(63 * (1 +
tiraid.identifier.advData.manufacturerSpecificData.nearable.accelerationZ)),
127), 0);
}
else {
self.devices[id].velocity = Math.min(127, Math.max(rssi-135,1) * 3);
}
var status = self.devices[id];
status.id = id;
status.valid = false;
if(self.controls.mute) {
if((self.devices[id].category === 'Tap Tempo') && (type === 'decoding')) {
status.valid = true;
status.channel = 15;
status.key = 0;
}
else if(self.devices[id].category === 'Controller') {
status.valid = true;
}
}
else if(self.controls.solo && (self.controls.solo !== id)) { }
else if(self.devices[id].useBarnowl && (type === 'decoding')) {
status.valid = true;
}
else if(self.devices[id].useBarnacles && ((type === 'appearance') ||
(type === 'keep-alive') ||
(type === 'displacement'))) {
status.valid = true;
}
callback(status);
};
/**
* Update the given device settings.
* @param {Object} device The device settings.
*/
DevicesManager.prototype.update = function(device) {
var self = this;
var id = device.id;
if(!self.devices.hasOwnProperty(id)) {
return;
}
self.devices[id].key = device.key;
self.devices[id].duration = device.duration;
self.devices[id].channel = device.channel;
self.devices[id].useBarnowl = device.useBarnowl;
self.devices[id].useBarnacles = device.useBarnacles;
self.devices[id].category = device.category;
self.devices[id].audio = device.audio;
};
/**
* Update the global control settings.
* @param {Object} controls The controls settings.
*/
DevicesManager.prototype.control = function(controls) {
var self = this;
self.controls.mute = controls.mute;
self.controls.solo = controls.solo;
self.midiMap = controls.midiMap;
self.channelMap = controls.channelMap;
};
/**
* Is the given tiraid a nearable?
* @param {Object} tiraid The given tiraid.
*/
function isNearable(tiraid) {
if(tiraid.identifier.hasOwnProperty('advData') &&
tiraid.identifier.advData.hasOwnProperty('manufacturerSpecificData') &&
tiraid.identifier.advData.manufacturerSpecificData.hasOwnProperty(
'nearable')) {
return true;
}
return false;
}
module.exports = DevicesManager;
|
module.exports = {
'selectors': [
'*',
'[attribute]',
'.class',
'.class:hover',
'.class::before',
'.class:first-child',
'.class:not(.class8)',
'.class + .class5',
'.class .class3',
'.class > .class4',
'.class ~ .class6',
'.class.class2',
'.class7',
'div',
'#id',
'#id2',
'span'
],
'simpleSelectors': {
'all': [
'*',
'[attribute]',
'.class',
'.class2',
'.class3',
'.class4',
'.class5',
'.class6',
'.class7',
'.class8',
'div',
'#id',
'#id2',
'span'
],
'ids': [
'#id',
'#id2'
],
'classes': [
'.class',
'.class2',
'.class3',
'.class4',
'.class5',
'.class6',
'.class7',
'.class8'
],
'attributes': [
'[attribute]'
],
'types': [
'div',
'span'
]
}
};
|
'use strict';
var debug = require('../../debug');
var dbman = require('../../dbman');
var log = debug.getLogger({ prefix: '[route.tool]- ' });
var tools = dbman.getCollection('tools');
var jobsites = dbman.getCollection('jobsites');
var ObjectId = dbman.getObjectId();
module.exports = {
get: function (req, res) {
res.render('tool', {
title: 'Add Tool'
});
},
post: function (req, res) {
var newRecord = req.body;
//set the name to all lower case for checking purposes. Saw and saw are the same thing
newRecord.name = newRecord.name.toLowerCase();
//check to see if the checkbox was checked. If it was not checked there will be no field for it in the record. Add one
if(!newRecord.maxRequest)
{
newRecord.maxRequest = 'off';
}
//check to see if we already have a tool by this name
log('POST: Checking for name -- %s', newRecord.name);
tools.findOne({name: newRecord.name}, function(error, oldRecord){
if(error)
{
log('POST: Error checking database for tool', error);
res.send(400, 'Error');
}
else if(!oldRecord)
{
log('POST: Tool not found -> adding new entry to database');
//insert new entry
tools.insert(newRecord, { w: 1 }, function (err, records) {
if (err || !records) {
log('POST: Error adding new record:\n\n%s\n\n', err);
res.send(400);
} else {
log('POST: New record successfully added to database');
res.send(200, {id: records[0]._id});
}
});
}
else
{
log('POST: Found an entry -> notifying user');
res.send(400, 'Entry Found');
}
});
},
success: function (req, res) {
res.render('hero-unit', {
title: 'Tool Added',
header: 'Tool Added',
message: 'Tool was added successfully.'
});
},
failure: function (req, res) {
res.render('hero-unit', {
title: 'Could Not Add Tool',
header: 'Sorry!',
message: 'There was a problem adding your tool. Please try again later.'
});
},
review: {
get: function(req, res){
var id = req.params.id;
log('TOOL.REVIEW.GET: Get Tool with _id: %s', id);
tools.findOne({ _id: new ObjectId(id)}, function(error, record){
if(error){
log('TOOL.REVIEW.GET: Error looking for record with _id: %s', id);
res.render('hero-unit', {
title: 'Error getting tool for review.',
header: 'Error',
message: 'There was an unknown error retrieving tool from database.'
});
}
else if(!record){
log('TOOL.REVIEW.GET: Unable to find record with _id: %s', id);
res.render('hero-unit', {
title: 'Could not find Tool in datbase.',
header: 'Tool Not Found',
message: 'Did not find the tool in the database.'
});
}
else{
log('TOOL.REVIEW.GET: Found record with id: %s', id);
//we need to loop through jobsites to determine how many of each tool
//is needed
var numNeeded = 0;
jobsites.find().toArray(function(jerr, jobSiteArray){
for(var i=0; i<jobSiteArray.length; i++)
{
if(jobSiteArray[i].evaluation)
{
var evalToolList = jobSiteArray[i].evaluation.tools;
for(var j=0; j<evalToolList.length; j++)
{
var evalTool = evalToolList[j];
if(evalTool.name === record.name)
{
numNeeded += evalTool.quantity;
}
}
}
}
});
//add the number needed to the record
record.numberNeeded = numNeeded;
res.render('toolReview', {
title: 'Edit Tool',
record: record,
numNeeded: numNeeded
});
}
});
},
post: function(req, res){
var newRecord = req.body;
var id = req.params.id;
log('TOOL.REVIEW.POST Trying to update tool with _id: %s', id);
//check to see if the checkbox was checked. If it was not checked there will be no field for it in the record. Add one
if(!newRecord.maxRequest)
{
newRecord.maxRequest = 'off';
//just in case there was a request limit before this was turned off we need to update the limit to 0
newRecord.maxRequestValue = 0;
}
var query = { _id: new ObjectId(id) };
var cmd = { $set: newRecord };
var opt = { w: 1 };
tools.update(query, cmd, opt, function (err, result) {
if(err) {
log('TOOL.REVOIEW.POST: Update error, tool:\n\n%s\n\n', err);
res.send(400);
}
else if(!result){
log('TOOL.REVIEW.POST: Could not find tool, _id:\n\n%s\n\n', id);
res.send(400);
}
else {
log('TOOL.REVIEW.POST: Updated tool with _id %s', id);
res.send(200);
}
});
},
delete: function (req, res){
var id = req.params.id;
var query = { _id: new ObjectId(id)};
log('DELETE: Attempting to remove tool.');
tools.remove(query, function(err, numberRemoved){
if(err)
{
log('DELETE: Unable to remove tool with id: %s', id);
res.render('hero-unit', {
title: 'Could Not Delete Tool',
header: 'Sorry!',
message: 'There was a problem deleting the tool. Please try again later.'
});
}
else
{
log('DELETE: Operation complete. Removed %s entries. Redirecting to the staff home page...', numberRemoved);
res.render('hero-unit', {
title: 'Success',
header: 'Tool Deleted!',
message: 'The tool was successfully deleted.'
});
}
});
},
success: function (req, res) {
res.render('hero-unit', {
title: 'Success',
header: 'Tool Updated',
message: 'You successfully updated the Tool.'
});
},
failure: function (req, res) {
res.render('hero-unit', {
title: 'Could Not Update Tool',
header: 'Sorry!',
message: 'There was a problem updating the tool. Please try again later.'
});
},
unableToDelete: function (req, res){
res.render('hero-unit', {
title: 'Could Not Delete Tool',
header: 'Sorry!',
message: 'There was a problem deleting the tool. Please try again later.'
});
}
}
};
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: '<json:package.json>',
test: {
files: ['test/**/*.js']
},
lint: {
files: ['grunt.js', '*.js', 'lib/**/*.js', 'test/**/*.js'],
aftermin: ['<config:min.dist.dest']
},
watch: {
main: {
files: '<config:lint.files>',
tasks: 'default'
},
javascript: {
files: '<config:concat:dist:src>',
tasks: 'prep'
}
},
jshint: {
options: {
curly: true,
//eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
node: true,
es5: true
},
globals: {
exports: true
}
},
concat: {
dist: {
src: ['public/js/libs/jquery-1.7.1.js', 'public/js/plugins.js', 'public/js/script.js'],
dest: 'public/js/scripts.js'
}
},
min: {
dist: {
src: ['public/js/scripts.js'],
dest: 'public/js/scripts.min.js'
}
}
});
// Default task.
grunt.registerTask('default', 'lint:files test');
grunt.registerTask('prep', 'concat min lint:aftermin');
}; |
export default class PageService {
constructor ($resource, $cacheFactory) {
'ngInject';
const pageCache = $cacheFactory('Pages');
return $resource(
constants.apiUrl + 'pages/:ID',
{ID: '@id'},
{
'get': {
method:'GET',
cache: pageCache
},
'query': {
method:'GET',
cache: pageCache,
isArray:true
}
}
);
}
} |
'use strict';
var t = require('tcomb-react');
var Factory = require('react-bootstrap/Glyphicon');
var name = t.react.getDisplayName(Factory);
var Glyph = require('./util/Glyph');
var Type = t.struct({
__tag__: t.enums.of(name, name),
glyph: Glyph
}, name);
module.exports = t.react.bind(Factory, Type, {strict: false});
|
const assert = require('assert');
const app = require('../../src/app');
describe('\'queue\' service', () => {
it('registered the service', () => {
const service = app.service('queue');
assert.ok(service, 'Registered the service');
});
});
|
"use strict";
const $ = wfl.jquery;
const Action = require('./Action');
const ActionPerformer = {
do: (type, data, reversable, direction, state) => {
let action;
if (type instanceof Action) {
action = type;
} else {
action = new Action(type, data, reversable, direction, state);
}
$(ActionPerformer).trigger(Action.Event.DEFAULT, action);
},
undo: (action) => {
let reversedAction = ActionPerformer._reverse(action);
reversedAction.reversable = false;
reversedAction.direction = Action.Direction.UNDO;
ActionPerformer.do(reversedAction);
},
redo: (action) => {
action.reversable = false;
action.direction = Action.Direction.REDO;
action.state = Action.State.IN_PROGRESS;
ActionPerformer.do(action);
},
_reverse: (action) => {
let {data} = action;
let revAction;
switch (action.type) {
case Action.Type.PROJECT_TILE_WIDTH_CHANGE:
revAction = new Action(
Action.Type.PROJECT_TILE_WIDTH_CHANGE,
{
prevTileWidth: data.tileWidth,
tileWidth: data.prevTileWidth
}
);
break;
case Action.Type.PROJECT_TILE_HEIGHT_CHANGE:
revAction = new Action(
Action.Type.PROJECT_TILE_HEIGHT_CHANGE,
{
prevTileHeight: data.tileHeight,
tileHeight: data.prevTileHeight
}
);
break;
case Action.Type.PROJECT_DYNAMIC_Z_ORDER_CHANGE:
revAction = new Action(
Action.Type.PROJECT_DYNAMIC_Z_ORDER_CHANGE,
{
value: !data.value
}
);
break;
case Action.Type.LAYER_ADD:
revAction = new Action(
Action.Type.LAYER_REMOVE,
data
);
break;
case Action.Type.LAYER_REMOVE:
revAction = new Action(
Action.Type.LAYER_ADD,
data
);
break;
case Action.Type.LAYER_LOCK:
revAction = new Action(
Action.Type.LAYER_UNLOCK,
data
);
break;
case Action.Type.LAYER_UNLOCK:
revAction = new Action(
Action.Type.LAYER_LOCK,
data
);
break;
case Action.Type.ENTITY_ADD:
revAction = new Action(
Action.Type.ENTITY_REMOVE,
data
);
break;
case Action.Type.WORLD_ENTITY_ADD:
revAction = new Action(
Action.Type.WORLD_ENTITY_REMOVE,
data
);
break;
case Action.Type.WORLD_ENTITY_REMOVE:
revAction = new Action(
Action.Type.WORLD_ENTITY_ADD,
data
);
break;
case Action.Type.WORLD_ENTITY_ADD_BATCH:
revAction = new Action(
Action.Type.WORLD_ENTITY_REMOVE_BATCH,
data
);
break;
case Action.Type.WORLD_ENTITY_REMOVE_BATCH:
revAction = new Action(
Action.Type.WORLD_ENTITY_ADD_BATCH,
data
);
break;
case Action.Type.WORLD_SELECTION_MOVE:
revAction = new Action(
Action.Type.WORLD_SELECTION_MOVE,
{
gameObjects: data.gameObjects,
dx: -data.dx,
dy: -data.dy
}
);
break;
case Action.Type.WORLD_SELECTION_ALIGN:
revAction = new Action(
Action.Type.WORLD_SELECTION_ALIGN,
{
gameObjects: data.gameObjects,
dxList: data.dxList.map((dx) => -dx),
dyList: data.dyList.map((dy) => -dy)
}
);
break;
case Action.Type.WORLD_SELECTION_ROTATE:
revAction = new Action(
Action.Type.WORLD_SELECTION_ROTATE,
{
gameObjects: data.gameObjects,
dThetaList: data.dThetaList.map((dTheta) => -dTheta),
unique: data.unique
}
);
break;
case Action.Type.PROPERTY_CHANGE_NAME:
case Action.Type.PROPERTY_CHANGE_SOLID:
case Action.Type.PROPERTY_CHANGE_FIXED:
case Action.Type.PROPERTY_CHANGE_PERSISTS:
case Action.Type.PROPERTY_CHANGE_MASS:
case Action.Type.PROPERTY_CHANGE_FRICTION:
case Action.Type.PROPERTY_CHANGE_RESTITUTION:
revAction = new Action(
action.type,
{
gameObjects: data.gameObjects,
prevValues: data.values,
values: data.prevValues
}
);
break;
case Action.Type.PROPERTY_ADD_BEHAVIOR:
revAction = new Action(
Action.Type.PROPERTY_REMOVE_BEHAVIOR,
data
);
break;
case Action.Type.PROPERTY_REMOVE_BEHAVIOR:
revAction = new Action(
Action.Type.PROPERTY_ADD_BEHAVIOR,
data
);
break;
case Action.Type.PROPERTY_CHANGE_BEHAVIOR:
revAction = new Action(
action.type,
{
gameObjects: data.gameObjects,
prevValues: data.values,
values: data.prevValues,
behaviorData: data.behaviorData,
propertyName: data.propertyName
}
);
break;
default:
console.error("Missing Reverse Action for: " + action.type);
revAction = new Action();
}
return revAction;
}
};
module.exports = ActionPerformer; |
version https://git-lfs.github.com/spec/v1
oid sha256:7be55b1f6dc5066020291688ca9a8613b80df085a674238d26932c12a14efa30
size 689165
|
import {msg} from 'translate'
export const createValuesFeatureLayerSource = () => ({
id: 'values',
type: 'Values',
description: msg('featureLayerSources.Values.description')
})
|
var esprima = require('esprima');
var babelJscs = require('babel-jscs');
var Errors = require('./errors');
var JsFile = require('./js-file');
var Configuration = require('./config/configuration');
var MAX_FIX_ATTEMPTS = 5;
function getErrorMessage(rule, e) {
return 'Error running rule ' + rule + ': ' +
'This is an issue with JSCS and not your codebase.\n' +
'Please file an issue (with the stack trace below) at: ' +
'https://github.com/jscs-dev/node-jscs/issues/new\n' + e;
}
/**
* Starts Code Style checking process.
*
* @name StringChecker
*/
var StringChecker = function() {
this._configuredRules = [];
this._errorsFound = 0;
this._maxErrorsExceeded = false;
// Need to be defined here because Configuration module can choose
// custom esprima or chose parsers based on "esnext" option
this._esprima = esprima;
this._configuration = this._createConfiguration();
this._configuration.registerDefaultPresets();
};
StringChecker.prototype = {
/**
* Registers single Code Style checking rule.
*
* @param {Rule} rule
*/
registerRule: function(rule) {
this._configuration.registerRule(rule);
},
/**
* Registers built-in Code Style checking rules.
*/
registerDefaultRules: function() {
this._configuration.registerDefaultRules();
},
/**
* Get processed config.
*
* @return {Object}
*/
getProcessedConfig: function() {
return this._configuration.getProcessedConfig();
},
/**
* Loads configuration from JS Object. Activates and configures required rules.
*
* @param {Object} config
*/
configure: function(config) {
this._configuration.load(config);
if (this._configuration.hasCustomEsprima()) {
this._esprima = this._configuration.getCustomEsprima();
} else if (this._configuration.isESNextEnabled()) {
this._esprima = babelJscs;
}
this._verbose = this._configuration.getVerbose();
this._configuredRules = this._configuration.getConfiguredRules();
this._maxErrors = this._configuration.getMaxErrors();
},
/**
* Checks file provided with a string.
*
* @param {String} source
* @param {String} [filename='input']
* @returns {Errors}
*/
checkString: function(source, filename) {
filename = filename || 'input';
var file = this._createJsFileInstance(filename, source);
var errors = new Errors(file, this._verbose);
file.getParseErrors().forEach(function(parseError) {
if (!this._maxErrorsExceeded) {
this._addParseError(errors, parseError);
}
}, this);
// Do not check empty strings
if (file.getFirstToken().type === 'EOF') {
return errors;
}
this._checkJsFile(file, errors);
return errors;
},
/**
* Fix provided error.
*
* @param {JsFile} file
* @param {Errors} errors
* @protected
*/
_fixJsFile: function(file, errors) {
var list = errors.getErrorList();
var configuration = this.getConfiguration();
list.forEach(function(error) {
if (error.fixed) {
return;
}
var instance = configuration.getConfiguredRule(error.rule);
if (instance && instance._fix) {
try {
// "error.fixed = true" should go first, so rule can
// decide for itself (with "error.fixed = false")
// if it can fix this particular error
error.fixed = true;
instance._fix(error);
} catch (e) {
error.fixed = undefined;
errors.add(getErrorMessage(error.rule, e), 1, 0);
}
}
});
},
/**
* Checks a file specified using JsFile instance.
* Fills Errors instance with validation errors.
*
* @param {JsFile} file
* @param {Errors} errors
* @protected
*/
_checkJsFile: function(file, errors) {
if (this._maxErrorsExceeded) {
return;
}
var errorFilter = this._configuration.getErrorFilter();
this._configuredRules.forEach(function(rule) {
errors.setCurrentRule(rule.getOptionName());
try {
rule.check(file, errors);
} catch (e) {
errors.add(getErrorMessage(rule.getOptionName(), e.stack), 1, 0);
}
}, this);
this._configuration.getUnsupportedRuleNames().forEach(function(rulename) {
errors.add('Unsupported rule: ' + rulename, 1, 0);
});
// sort errors list to show errors as they appear in source
errors.getErrorList().sort(function(a, b) {
return (a.line - b.line) || (a.column - b.column);
});
if (errorFilter) {
errors.filter(errorFilter);
}
if (this._maxErrorsEnabled()) {
this._maxErrorsExceeded = this._errorsFound + errors.getErrorCount() > this._maxErrors;
errors.stripErrorList(Math.max(0, this._maxErrors - this._errorsFound));
}
this._errorsFound += errors.getErrorCount();
},
/**
* Adds parse error to the error list.
*
* @param {Errors} errors
* @param {Error} parseError
* @private
*/
_addParseError: function(errors, parseError) {
if (this._maxErrorsExceeded) {
return;
}
errors.setCurrentRule('parseError');
errors.add(parseError.description, parseError.lineNumber, parseError.column);
if (this._maxErrorsEnabled()) {
this._errorsFound += 1;
this._maxErrorsExceeded = this._errorsFound >= this._maxErrors;
}
},
/**
* Creates configured JsFile instance.
*
* @param {String} filename
* @param {String} source
* @private
*/
_createJsFileInstance: function(filename, source) {
return new JsFile({
filename: filename,
source: source,
esprima: this._esprima,
esprimaOptions: this._configuration.getEsprimaOptions(),
es3: this._configuration.isES3Enabled(),
es6: this._configuration.isESNextEnabled()
});
},
/**
* Checks file provided with a string.
*
* @param {String} source
* @param {String} [filename='input']
* @returns {{output: String, errors: Errors}}
*/
fixString: function(source, filename) {
filename = filename || 'input';
var file = this._createJsFileInstance(filename, source);
var errors = new Errors(file, this._verbose);
var parseErrors = file.getParseErrors();
if (parseErrors.length > 0) {
parseErrors.forEach(function(parseError) {
this._addParseError(errors, parseError);
}, this);
return {output: source, errors: errors};
} else {
var attempt = 0;
do {
// Changes to current sources are made in rules through assertions.
this._checkJsFile(file, errors);
// If assertions weren't used but rule has "fix" method,
// which we could use.
this._fixJsFile(file, errors);
var hasFixes = errors.getErrorList().some(function(err) {
return err.fixed;
});
if (!hasFixes) {
break;
}
file = this._createJsFileInstance(filename, file.render());
errors = new Errors(file, this._verbose);
attempt++;
} while (attempt < MAX_FIX_ATTEMPTS);
return {output: file.getSource(), errors: errors};
}
},
/**
* Returns `true` if max erros limit is enabled.
*
* @returns {Boolean}
*/
_maxErrorsEnabled: function() {
return this._maxErrors !== null;
},
/**
* Returns `true` if error count exceeded `maxErrors` option value.
*
* @returns {Boolean}
*/
maxErrorsExceeded: function() {
return this._maxErrorsExceeded;
},
/**
* Returns new configuration instance.
*
* @protected
* @returns {Configuration}
*/
_createConfiguration: function() {
return new Configuration();
},
/**
* Returns current configuration instance.
*
* @returns {Configuration}
*/
getConfiguration: function() {
return this._configuration;
},
/**
* Returns the current esprima parser
*
* @return {Esprima}
*/
getEsprima: function() {
return this._esprima || this._configuration.getCustomEsprima();
}
};
module.exports = StringChecker;
|
let mix = require('laravel-mix')
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/assets/js/polyfill.js', 'public/assets')
mix.js('resources/assets/js/admin.js', 'public/assets')
mix.js('resources/assets/js/live.js', 'public/assets')
mix.sass('resources/assets/sass/admin.scss', 'public/assets')
mix.sass('resources/assets/sass/live.scss', 'public/assets')
mix.webpackConfig({
output: {
publicPath: Mix.isUsing('hmr') ? 'http://localhost:8080/' : '/',
chunkFilename: mix.inProduction() ? 'assets/[name].[chunkhash].app.js' : 'assets/[name].js'
}
})
mix.options({
postCss: [
require('postcss-flexbugs-fixes')()
]
}); |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//= require jquery-1.11.3.min.js
//= require turbolinks
//= require three.min
//= require roofpig
|
/**
* Options
*
* @param {String} arg Pin address.
* @param {Number} arg Pin address.
* @param {Array} arg List of Pin addresses.
*
* @return {Options} normalized board options instance.
*/
function Options(arg) {
if (!(this instanceof Options)) {
return new Options(arg);
}
var opts = {};
if (typeof arg === "number" ||
typeof arg === "string") {
opts.pin = arg;
} else if (Array.isArray(arg)) {
opts.pins = arg;
} else {
opts = arg;
}
Object.assign(this, opts);
}
module.exports = Options;
|
/*
* Author: Abdullah A Almsaeed
* Date: 4 Jan 2014
* Description:
* This is a demo file used only for the main dashboard (index.html)
**/
$(function () {
"use strict";
//Make the dashboard widgets sortable Using jquery UI
$(".connectedSortable").sortable({
placeholder: "sort-highlight",
connectWith: ".connectedSortable",
handle: ".box-header, .nav-tabs",
forcePlaceholderSize: true,
zIndex: 999999
});
$(".connectedSortable .box-header, .connectedSortable .nav-tabs-custom").css("cursor", "move");
//jQuery UI sortable for the todo list
$(".todo-list").sortable({
placeholder: "sort-highlight",
handle: ".handle",
forcePlaceholderSize: true,
zIndex: 999999
});
//bootstrap WYSIHTML5 - text editor
$(".textarea").wysihtml5();
$('.daterange').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate: moment()
}, function (start, end) {
window.alert("You chose: " + start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
});
/* jQueryKnob */
$(".knob").knob();
//jvectormap data
var visitorsData = {
"US": 398, //USA
"SA": 400, //Saudi Arabia
"CA": 1000, //Canada
"DE": 500, //Germany
"FR": 760, //France
"CN": 300, //China
"AU": 700, //Australia
"BR": 600, //Brazil
"IN": 800, //India
"GB": 320, //Great Britain
"RU": 3000 //Russia
};
//World map by jvectormap
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "transparent",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
}
},
series: {
regions: [{
values: visitorsData,
scale: ["#92c1dc", "#ebf4f9"],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function (e, el, code) {
if (typeof visitorsData[code] != "undefined")
el.html(el.html() + ': ' + visitorsData[code] + ' new visitors');
}
});
//Sparkline charts
var myvalues = [1000, 1200, 920, 927, 931, 1027, 819, 930, 1021];
$('#sparkline-1').sparkline(myvalues, {
type: 'line',
lineColor: '#92c1dc',
fillColor: "#ebf4f9",
height: '50',
width: '80'
});
myvalues = [515, 519, 520, 522, 652, 810, 370, 627, 319, 630, 921];
$('#sparkline-2').sparkline(myvalues, {
type: 'line',
lineColor: '#92c1dc',
fillColor: "#ebf4f9",
height: '50',
width: '80'
});
myvalues = [15, 19, 20, 22, 33, 27, 31, 27, 19, 30, 21];
$('#sparkline-3').sparkline(myvalues, {
type: 'line',
lineColor: '#92c1dc',
fillColor: "#ebf4f9",
height: '50',
width: '80'
});
//The Calender
$("#calendar").datepicker();
//SLIMSCROLL FOR CHAT WIDGET
$('#chat-box').slimScroll({
height: '250px'
});
/* Morris.js Charts */
// Sales chart
var area = new Morris.Area({
element: 'revenue-chart',
resize: true,
data: [
{y: '2011 Q1', item1: 2666, item2: 2666},
{y: '2011 Q2', item1: 2778, item2: 2294},
{y: '2011 Q3', item1: 4912, item2: 1969},
{y: '2011 Q4', item1: 3767, item2: 3597},
{y: '2012 Q1', item1: 6810, item2: 1914},
{y: '2012 Q2', item1: 5670, item2: 4293},
{y: '2012 Q3', item1: 4820, item2: 3795},
{y: '2012 Q4', item1: 15073, item2: 5967},
{y: '2013 Q1', item1: 10687, item2: 4460},
{y: '2013 Q2', item1: 8432, item2: 5713}
],
xkey: 'y',
ykeys: ['item1', 'item2'],
labels: ['Item 1', 'Item 2'],
lineColors: ['#a0d0e0', '#24b798'],
hideHover: 'auto'
});
var line = new Morris.Line({
element: 'line-chart',
resize: true,
data: [
{y: '2011 Q1', item1: 2666},
{y: '2011 Q2', item1: 2778},
{y: '2011 Q3', item1: 4912},
{y: '2011 Q4', item1: 3767},
{y: '2012 Q1', item1: 6810},
{y: '2012 Q2', item1: 5670},
{y: '2012 Q3', item1: 4820},
{y: '2012 Q4', item1: 15073},
{y: '2013 Q1', item1: 10687},
{y: '2013 Q2', item1: 8432}
],
xkey: 'y',
ykeys: ['item1'],
labels: ['Item 1'],
lineColors: ['#efefef'],
lineWidth: 2,
hideHover: 'auto',
gridTextColor: "#fff",
gridStrokeWidth: 0.4,
pointSize: 4,
pointStrokeColors: ["#efefef"],
gridLineColor: "#efefef",
gridTextFamily: "Open Sans",
gridTextSize: 10
});
//Donut Chart
var donut = new Morris.Donut({
element: 'sales-chart',
resize: true,
colors: ["#24b798", "#f56954", "#24b798"],
data: [
{label: "Download Sales", value: 12},
{label: "In-Store Sales", value: 30},
{label: "Mail-Order Sales", value: 20}
],
hideHover: 'auto'
});
//Fix for charts under tabs
$('.box ul.nav a').on('shown.bs.tab', function () {
area.redraw();
donut.redraw();
line.redraw();
});
/* The todo list plugin */
$(".todo-list").todolist({
onCheck: function (ele) {
window.console.log("The element has been checked");
return ele;
},
onUncheck: function (ele) {
window.console.log("The element has been unchecked");
return ele;
}
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:f130cf13122eb650674d17203d62a2a16b40821bbef3ca4b0d2e5038bb44ccc0
size 349729
|
/* global Fae, modal, FCH */
/**
* Fae modals
* @namespace
*/
Fae.modals = {
ready: function() {
this.$body = $('body');
this.openClass = 'modal-open';
this.modalClass = 'MODAL_ID-modal-open';
this.showEvent = 'modal:show';
this.shownEvent = 'modal:shown';
this.closeEvent = 'modal:close';
this.closedEvent = 'modal:closed';
this.modalOpen = false;
this.imageModals();
this.markdownModalListener();
this.ajaxModalListener();
},
/**
* Click event to open modal with only an image
*/
imageModals: function() {
$('#js-main-content').on('click', '.js-image-modal', function(e) {
e.preventDefault();
var $this = $(this);
// create invisi-image to get natural width/height
var image = new Image();
image.src = $this.attr('src');
var image_width = image.width + 55;
var image_height = image.height + 55;
$this.modal({
minHeight: image_height,
minWidth: image_width,
overlayClose: true
});
});
},
/**
* Display markdown guide in a modal
* @see {@link form.text.overrideMarkdownDefaults}
* @see {@link modals.markdownModalListener}
* @has_test {features/form_helpers/fae_input_spec.rb}
*/
markdownModal: function() {
var markdown_hint_width = $('.markdown-hint').width() + 40;
$('.markdown-hint-wrapper').modal({
minHeight: 430,
minWidth: markdown_hint_width,
overlayClose: true,
zIndex: 1100
});
},
/**
* Markdown guide shown on document click of "markdown-support" so as to support AJAX'd markdown-support fields.
* @fires {@link modals.markdownModal}
* @has_test {features/form_helpers/fae_input_spec.rb}
*/
markdownModalListener: function() {
FCH.$document.on('click', '.markdown-support', this.markdownModal);
},
/**
* load remote data, open modal view
* @see {@link modals.formModalListener}
* @has_test {features/form_helpers/fae_input_spec.rb}
*/
openAjaxModal: function (remoteUrl, relatedTarget) {
var _this = this;
$.get(remoteUrl, function (data) {
//Open remote url content in modal window
$(data).modal({
minHeight: "75%",
minWidth: "75%",
overlayClose: true,
zIndex: 1100,
containerId: "fae-modal",
persist: true,
opacity: 70,
overlayCss: { backgroundColor: "#000" },
onOpen: function (dialog) {
// Fade in modal + show data
dialog.overlay.fadeIn();
dialog.container.fadeIn(function() {
var shownEvent = $.Event(_this.shownEvent, { dialog: dialog, relatedTarget: relatedTarget });
_this.$body.trigger(shownEvent);
});
dialog.data.show();
var modalClasses = [_this.createClassFromModalId(relatedTarget.attr('id')), _this.openClass].join(' ');
_this.modalOpen = true;
_this.$body.addClass(modalClasses);
},
onShow: function (dialog) {
var showEvent = $.Event(_this.showEvent, { dialog: dialog, relatedTarget: relatedTarget });
_this.$body.trigger(showEvent);
$(dialog.container).css('height', 'auto')
},
onClose: function (dialog) {
var closeEvent = $.Event(_this.closeEvent, { dialog: dialog, relatedTarget: relatedTarget });
_this.$body.trigger(closeEvent);
// Fade out modal and close
dialog.container.fadeOut();
dialog.overlay.fadeOut(function () {
$.modal.close(); // must call this!
var closedEvent = $.Event(_this.closedEvent, { dialog: dialog, relatedTarget: relatedTarget });
var modalClasses = [_this.createClassFromModalId(relatedTarget.attr('id')), _this.openClass].join(' ');
_this.modalOpen = false;
_this.$body.removeClass(modalClasses);
_this.$body.trigger(closedEvent);
});
}
});
});
},
/**
* Click event listener for ajax modal links triggering specific view within modal popup
* @fires {@link modals.ajaxModal}
* @has_test {features/form_helpers/fae_input_spec.rb}
*/
ajaxModalListener: function () {
var _this = this;
FCH.$document.on('click', '.js-fae-modal', function (e) {
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
var id = $this.attr('id');
_this.openAjaxModal(url, $this)
});
},
createClassFromModalId: function(modalId) {
return this.modalClass.replace('MODAL_ID', modalId);
}
};
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Web Client
* Copyright (C) 2005, 2006, 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
/**
*
* @private
*/
DwtListViewActionEvent = function() {
DwtMouseEvent.call(this);
this.reset(true);
}
DwtListViewActionEvent.prototype = new DwtMouseEvent;
DwtListViewActionEvent.prototype.constructor = DwtListViewActionEvent;
DwtListViewActionEvent.prototype.toString =
function() {
return "DwtListViewActionEvent";
}
DwtListViewActionEvent.prototype.reset =
function(dontCallParent) {
if (!dontCallParent)
DwtMouseEvent.prototype.reset.call(this);
this.field = null;
this.item = null;
this.detail = null;
} |
window.WebFontConfig = {
google: { families: [ 'Open+Sans::latin', 'Raleway::latin' ] }
};
(function() {
let wf = document.createElement('script');
wf.src = ('https:' === document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
let s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
|
// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from 'utils/asyncInjectors';
const errorLoading = (err) => {
console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};
const loadModule = (cb) => (componentModule) => {
cb(null, componentModule.default);
};
export default function createRoutes(store) {
// Create reusable async injectors using getAsyncInjectors factory
const { injectReducer, injectSagas } = getAsyncInjectors(store); // eslint-disable-line no-unused-vars
return [
{
path: '/configure',
name: 'configure',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/ConfigureAddressPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([component]) => {
renderRoute(component);
});
importModules.catch(errorLoading);
},
},
{
path: '/',
name: 'home',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/HomePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([component]) => {
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '*',
name: 'notfound',
getComponent(nextState, cb) {
System.import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
];
}
|
const moduleNotFound = require('../../../src/formatters/moduleNotFound');
const expect = require('expect');
it('Formats module-not-found errors', () => {
const error = { type: 'module-not-found', module: 'redux' };
expect(moduleNotFound([error])).toEqual([
'This dependency was not found:',
'',
'* redux',
'',
'To install it, you can run: npm install --save redux'
]);
});
it('Groups all module-not-found into one', () => {
const reduxError = { type: 'module-not-found', module: 'redux' };
const reactError = { type: 'module-not-found', module: 'react' };
expect(moduleNotFound([reduxError, reactError])).toEqual([
'These dependencies were not found:',
'',
'* redux',
'* react',
'',
'To install them, you can run: npm install --save redux react'
]);
});
it('Groups same module in module-not-found with 2 files', () => {
const reduxError = { type: 'module-not-found', module: 'redux' };
const reactError1 = { type: 'module-not-found', module: 'react', file: './src/file1.js' };
const reactError2 = { type: 'module-not-found', module: 'react', file: '../src/file2.js' };
expect(moduleNotFound([reduxError, reactError1, reactError2])).toEqual([
'These dependencies were not found:',
'',
'* redux',
'* react in ./src/file1.js, ../src/file2.js',
'',
'To install them, you can run: npm install --save redux react'
]);
});
it('Groups same module in module-not-found with 3 files', () => {
const reduxError = { type: 'module-not-found', module: 'redux' };
const reactError1 = { type: 'module-not-found', module: 'react', file: './src/file1.js' };
const reactError2 = { type: 'module-not-found', module: 'react', file: './src/file2.js' };
const reactError3 = { type: 'module-not-found', module: 'react', file: './src/file3.js' };
expect(moduleNotFound([reduxError, reactError1, reactError2, reactError3])).toEqual([
'These dependencies were not found:',
'',
'* redux',
'* react in ./src/file1.js, ./src/file2.js and 1 other',
'',
'To install them, you can run: npm install --save redux react'
]);
});
it('Groups same module in module-not-found with 4 files', () => {
const reduxError = { type: 'module-not-found', module: 'redux' };
const reactError1 = { type: 'module-not-found', module: 'react', file: './src/file1.js' };
const reactError2 = { type: 'module-not-found', module: 'react', file: './src/file2.js' };
const reactError3 = { type: 'module-not-found', module: 'react', file: './src/file3.js' };
const reactError4 = { type: 'module-not-found', module: 'react', file: './src/file4.js' };
expect(moduleNotFound([reduxError, reactError1, reactError2, reactError3, reactError4])).toEqual([
'These dependencies were not found:',
'',
'* redux',
'* react in ./src/file1.js, ./src/file2.js and 2 others',
'',
'To install them, you can run: npm install --save redux react'
]);
});
it('Does not format other errors', () => {
const otherError = { type: 'other-error', module: 'foo' };
expect(moduleNotFound([otherError])).toEqual([]);
});
|
var util = require('util'),
events = require('events'),
steam = require('./main');
function Session(opt) {
opt = opt || {};
this.access_token = null;
this.umqid = null;
this.steamid = null;
this.messagelast = 0;
this.scope = opt.scope || ['read_profile', 'write_profile', 'read_client', 'write_client'];
// public: DE45CD61, beta: 7DC60112, dev: E77327FA
this.client_id = opt.client_id || 'DE45CD61';
this.next_poll = null;
}
util.inherits(Session, events.EventEmitter);
module.exports = Session;
Session.prototype.connected = function () {
return !!this.umqid;
};
Session.prototype.connect = function (opt, success) {
var self = this;
if (self.connected()) {
return;
}
opt = opt || {};
self.access_token = opt.access_token || self.access_token;
if (self.access_token) {
self.logon(function (d) {
var data = {
steamid: d.steamid,
access_token: self.access_token
};
if (success) {
success(data);
}
var poll_loop = function () {
self.poll(poll_loop);
};
poll_loop();
self.emit('connect', data);
});
} else if (opt.username && opt.password) {
self.authenticate({
username: opt.username,
password: opt.password,
authcode: opt.authcode
}, function (d) {
self.connect(null, success);
});
}
};
Session.prototype.authenticate = function (opt, success) {
var self = this;
if (self.connected()) {
return;
}
opt = opt || {};
steam.request({
interface: 'ISteamOAuth2',
method: 'GetTokenWithCredentials',
post: {
client_id: self.client_id,
grant_type: 'password',
username: opt.username,
password: opt.password,
x_emailauthcode: opt.emailauthcode,
scope: self.scope.join(' ')
}
}, function (e, d) {
if (e) {
if (e.type !== 'steam') {
self.emit('error', {
error: e,
data: d
});
} else {
self.emit('auth_error', {
code: d.x_errorcode,
description: d.description
});
}
} else {
self.access_token = d.access_token;
var data = {
access_token: d.access_token
};
if (success) {
success(data);
}
self.emit('authenticate', data);
}
});
};
Session.prototype.logon = function (success) {
var self = this;
if (self.connected()) {
return;
}
steam.request({
interface: 'ISteamWebUserPresenceOAuth',
method: 'Logon',
post: {
access_token: self.access_token
}
}, function (e, d) {
if (e) {
self.emit('error', {
error: e,
data: d
});
} else {
self.umqid = d.umqid;
self.steamid = d.steamid;
self.messagelast = d.message;
var data = {
steamid: d.steamid
};
if (success) {
success(data);
}
self.emit('logon', data);
}
});
};
Session.prototype.poll = function (callback) {
var self = this;
if (!self.connected()) {
return;
}
if (!self.next_poll) {
self.next_poll = self.poll_status;
}
self.next_poll(function (d) {
if (d.secure) {
self.next_poll = self.poll_secure;
} else {
self.next_poll = self.poll_status;
}
if (callback) {
callback(d);
}
self.emit('poll', d);
});
};
Session.prototype.poll_status = function (callback) {
var self = this;
if (!self.connected()) {
return;
}
steam.request({
interface: 'ISteamWebUserPresenceOAuth',
method: 'PollStatus',
secure: 'false',
post: {
steamid: self.steamid,
umqid: self.umqid,
message: self.messagelast
}
}, function (e, d) {
var data = {
secure: false
};
if (e && !(e.type === 'steam' && e.info === 'Timeout')) {
data.error = e;
self.emit('error', {
error: e,
data: d
});
} else {
if (d.messages) {
d.messages.forEach(function (m) {
if (m.secure_message_id) {
data.secure = true;
}
});
}
self.emit('poll_status', d);
}
if (callback) {
callback(data);
}
});
};
Session.prototype.poll_secure = function (callback) {
var self = this;
if (!self.connected()) {
return;
}
steam.request({
interface: 'ISteamWebUserPresenceOAuth',
method: 'Poll',
post: {
access_token: self.access_token,
umqid: self.umqid,
message: self.messagelast
}
}, function (e, d) {
var data = {
secure: false
};
if (e && !(e.type === 'steam' && e.info === 'Timeout')) {
data.error = e;
self.emit('error', {
error: e,
data: d
});
} else {
d.messages.forEach(function (m) {
self.emit('message', m);
self.emit('message_' + m.type, m);
});
self.messagelast = d.messagelast;
self.emit('poll_secure', d);
}
if (callback) {
callback(data);
}
});
};
Session.prototype.message = function (opt) {
var self = this;
steam.request({
interface: 'ISteamWebUserPresenceOAuth',
method: 'Message',
post: {
access_token: self.access_token,
umqid: self.umqid,
type: opt.type || 'saytext',
text: opt.text,
steamid_dst: opt.steamid
}
}, function (e, d) {
if (e) {
self.emit('error', {
error: e,
data: d
});
}
});
}; |
define([
"../core",
"../queue",
"../effects" // Delay is optional because of this dependency
], function( chadQuery ) {
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/chadquery-delay/
chadQuery.fn.delay = function( time, type ) {
time = chadQuery.fx ? chadQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
return chadQuery.fn.delay;
});
|
angular.module('ngCordova.plugins.deviceOrientation', [])
.factory('$cordovaDeviceOrientation', ['$q', function($q) {
return {
watchHeading: function(options) {
var q = $q.defer();
navigator.compass.watchHeading(function(result) {
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
}]);
|
var Map = function(container, model, opt_imagepath) {
var self = this,
baseLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}),
map = L.map(container[0], {
center: new L.LatLng(48.2, 16.4),
zoom: 12,
layers: [ baseLayer ]
}),
markers = L.featureGroup().addTo(map),
markerIndex = {},
onSelect = function(results) {
self.fireEvent('select', results);
if (results.length > 0)
selectFirst(results[0]);
},
clear = function() {
markerIndex = {};
markers.clearLayers();
},
render = function() {
map.invalidateSize();
clear();
jQuery.each(model.getResultsByCoordinate(), function(idx, tuple) {
// Create marker
var marker = L.marker([tuple.lat, tuple.lon])
.on('click', onSelect.bind(null, tuple.results))
.addTo(markers);
// Add results to index
jQuery.each(tuple.results, function(idx, result) {
markerIndex[result.key] = marker;
});
});
if (markers.getLayers().length > 0)
map.fitBounds(markers.getBounds());
},
selectFirst = function(results) {
if (results && results.length > 0) {
var marker = markerIndex[results[0].key];
if (marker) {
marker
.bindPopup('<strong>' + results[0].title + '</strong>')
.openPopup();
} else {
map.closePopup();
}
} else {
map.closePopup();
}
};
if (opt_imagepath)
L.Icon.Default.imagePath = opt_imagepath;
this.render = render;
this.selectFirst = selectFirst;
HasEvents.apply(this);
};
Map.prototype = Object.create(HasEvents.prototype);
|
angular.module('JWTDemoApp')
// Creating the Angular Controller
.controller('LoginController', function($http, $scope, $state, AuthService, $rootScope) {
// method for login
$scope.login = function() {
// requesting the token by usename and passoword
$http({
url : 'authenticate',
method : "POST",
params : {
username : $scope.username,
password : $scope.password
}
}).then(function(response) {
var res = response.data;
$scope.password = null;
// checking if the token is available in the response
if (res.token) {
$scope.message = '';
// setting the Authorization Bearer token with JWT token
$http.defaults.headers.common['Authorization'] = 'Bearer ' + res.token;
// setting the user in AuthService
AuthService.user = res.user;
$rootScope.$broadcast('LoginSuccessful');
// going to the home page
$state.go('home');
} else {
// if the token is not present in the response then the
// authentication was not successful. Setting the error message.
$scope.message = 'Authetication Failed !';
}
}, function(error) {
// if authentication was not successful. Setting the error message.
$scope.message = 'Authetication Failed !';
});
};
});
|
angular.module('directives').directive('recommendationBox', function ($api, $location, Recommendation) {
return {
restrict: "E",
templateUrl: "common/directives/recommendationBox/recommendationBox.html",
replace: true,
link: function (scope, element, attrs) {
var recbox = scope.recbox = {
load: function() {
if (scope.current_person) {
recbox.refresh();
}
},
refresh: function() {
recbox.last_refresh = new Date();
Recommendation.query({
location: 'homepage' // not used yet
}, function(results) {
recbox.recommendations = results;
recbox.show_next();
});
},
refresh_if_necessary: function() {
if (recbox.last_refresh && (((new Date()) - recbox.last_refresh) > 60*1000)) {
recbox.refresh();
}
},
skip: function() {
recbox.record('skip');
recbox.show_next();
},
show_next: function() {
if (!scope.recommendation || !angular.equals(scope.recommendation, recbox.recommendations[0])) {
scope.recommendation = recbox.recommendations.shift();
if (scope.recommendation) {
recbox.record('show');
}
}
scope.next_recommendation = recbox.recommendations[0];
},
record: function(event) {
Recommendation.create({
event: event,
recommendation: scope.recommendation
});
},
add_bounty_to_cart: function(amount) {
recbox.record('add_to_cart:' + amount);
}
};
scope.$watch('current_person', recbox.load);
scope.$on('$viewContentLoaded', recbox.refresh_if_necessary);
}
};
});
|
// flow-typed signature: f0fa30a5aa3fb573cd7f5c56d1892016
// flow-typed version: <<STUB>>/file-loader_v0.11.2/flow_v0.56.0
/**
* This is an autogenerated libdef stub for:
*
* 'file-loader'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'file-loader' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'file-loader/index' {
declare module.exports: $Exports<'file-loader'>;
}
declare module 'file-loader/index.js' {
declare module.exports: $Exports<'file-loader'>;
}
|
'use strict';
exports.buildEACCES = path => Object.assign(new Error(`EACCES: permission denied '${path}'`), {
errno: -13,
code: 'EACCES',
path
});
exports.buildENOSPC = () => Object.assign(new Error('ENOSPC, write'), {
errno: -28,
code: 'ENOSPC'
});
exports.buildENOENT = path => Object.assign(new Error(`ENOENT: no such file or directory '${path}'`), {
errno: -2,
code: 'ENOENT',
path
});
exports.buildEIO = () => Object.assign(new Error('EIO: i/o error, read errno: -5'), {
errno: -5,
code: 'EIO'
});
exports.buildERRSTREAMWRITEAFTEREND = () => Object.assign(new Error('ERR_STREAM_WRITE_AFTER_END'), {
code: 'ERR_STREAM_WRITE_AFTER_END'
});
exports.buildEBADF = () => Object.assign(new Error('EBADF: bad file descriptor'), {
errno: -9,
code: 'EBADF'
});
exports.buildEPERM = (path, method) => Object.assign(new Error(`EPERM: ${method} '${path}''`), {
errno: 50,
code: 'EPERM'
});
|
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var jade = require('gulp-jade');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
var browserSync = require('browser-sync');
var watch = require('gulp-watch');
var plumber = require('gulp-plumber');
var reload = browserSync.reload;
gulp.task('sass', function () {
return sass('src/scss/main.scss', {sourcemap: true})
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(autoprefixer())
.pipe(sourcemaps.write('/maps', {
includeContent: false,
sourceRoot: 'src/scss'
}))
.pipe(gulp.dest('dist/css'))
.pipe(reload({ stream: true }));
});
gulp.task('js', function () {
return gulp.src('src/js/*.js')
.pipe(plumber())
.pipe(babel())
.pipe(gulp.dest('dist/js'));
});
gulp.task('assets', function () {
return gulp.src('src/img/*')
.pipe(plumber())
.pipe(gulp.dest('dist/img'));
});
gulp.task('fonts', function () {
return gulp.src('src/fonts/*')
.pipe(plumber())
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('jade', function () {
return gulp.src(['src/templates/**/*.jade', '!src/templates/includes/*'])
.pipe(plumber())
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('jade-watch', ['jade'], reload);
gulp.task ('watch', function(){
return watch('src/scss/**/*.scss', ['sass']);
return watch('src/js/**/*.js', ['js']).on('change', reload);
return watch('src/templates/**/*.jade', ['jade-watch']);
return watch('src/img/*', ['assets']).on('change', reload);
return watch('src/fonts/*', ['fonts']).on('change', reload);
});
// Main dev task
gulp.task('serve', ['sass', 'js', 'jade', 'assets', 'fonts'], function () {
browserSync({
server: {
baseDir: 'dist',
}
});
gulp.watch('src/scss/**/*.scss', ['sass']);
gulp.watch('src/js/**/*.js', ['js']).on('change', reload);
gulp.watch('src/templates/**/*.jade', ['jade-watch']);
gulp.watch('src/img/*', ['assets']).on('change', reload);
});
|
'use strict';
var __ = require('underscore'),
Backbone = require('backbone'),
$ = require('jquery'),
usersShortCollection = require('../collections/usersShortCl'),
userShortView = require('./userShortVw'),
simpleMessageView = require('./simpleMessageVw');
module.exports = Backbone.View.extend({
initialize: function(options){
this.options = options || {};
/*expected options:
options.title: title for no users found
options.message: message for no users found
options.serverUrl: server url to pass into each user view
options.ownFollowing: array of guids this user is following
options.hideFollow: boolean, hide follow button
options.reverse: should the list of users be reversed?
options.perFetch: the number of users returned per fetch (optional, only applies to the get_followers api)
options.followerCount: the total number of followers (optional, only applise to the get_followers api)
*/
//the model must be passed in by the constructor
this.usersShort = new usersShortCollection(this.model);
this.options.reverse && this.usersShort.models.reverse();
this.subViews = [];
this.showPerScroll = 30;
this.nextUserToShow = 0;
this.fetchedUsers = this.usersShort.length;
this.totalUsers = this.options.followerCount;
this.$container = $('#obContainer');
//listen to scrolling on container
this.scrollHandler = __.bind(
__.throttle(this.onScroll, 100), this
);
this.$container.on('scroll', this.scrollHandler);
this.listenTo(this.usersShort, 'add', ()=>{
this.fetchedUsers = this.usersShort.length;
this.renderUserSet(this.nextUserToShow, this.nextUserToShow + this.showPerScroll);
});
this.render();
},
render: function(){
var self = this;
if (this.usersShort.models.length > 0) {
this.listWrapper = $('<div class="list flexRow flexExpand border0 custCol-border"></div>');
this.renderUserSet(this.nextUserToShow, this.showPerScroll);
this.$el.html(this.listWrapper);
} else {
self.renderNoneFound();
}
},
renderUserSet: function(start, end){
var self = this,
renderSet = __.filter(this.usersShort.models, function(value, index){
return (index >= start) && (index < end);
});
__.each(renderSet, function(user) {
user.set('avatarURL', self.options.serverUrl+"get_image?hash="+user.get('avatar_hash')+"&guid="+user.get('guid'));
if (self.options.ownFollowing.indexOf(user.get('guid')) != -1){
user.set("ownFollowing", true);
}
user.set('hideFollow', self.options.hideFollow);
self.renderUser(user);
}, this);
//if at least one user was added, trigger call so parent can refresh searches
if (renderSet.length > 0){
this.trigger('usersAdded');
}
this.nextUserToShow = this.nextUserToShow >= this.fetchedUsers ? this.nextUserToShow : this.nextUserToShow + this.showPerScroll;
if (this.fetchedUsers < this.totalUsers && this.$el.is(':visible')){
this.trigger('fetchMoreUsers');
}
},
renderUser: function(item){
var storeShort = new userShortView({
model: item
});
this.subViews.push(storeShort);
this.listWrapper.append(storeShort.el);
},
onScroll: function(){
if (this.$container[0].scrollTop + this.$container[0].clientHeight + 200 > this.$container[0].scrollHeight &&
this.listWrapper && this.listWrapper[0].hasChildNodes() && this.listWrapper.is(":visible")) {
this.renderUserSet(this.nextUserToShow, this.nextUserToShow + this.showPerScroll);
}
},
addUsers: function(model) {
//add more users to the collection
this.usersShort.add(model);
},
renderNoneFound: function(){
var simpleMessage = new simpleMessageView({title: this.options.title, message: this.options.message, el: this.$el});
this.subViews.push(simpleMessage);
},
close: function(){
__.each(this.subViews, function(subView) {
if (subView.close){
subView.close();
} else {
subView.unbind();
subView.remove();
}
});
this.unbind();
this.remove();
this.scrollHandler && this.$container.off('scroll', this.scrollHandler);
}
});
|
module.exports = {
env: {
es6: true,
node: true,
mocha: true
},
extends: 'standard',
rules: {
indent: ['error', 2],
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'always'],
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'space-before-function-paren': 0,
'no-useless-escape': 0,
'no-unused-vars': process.env.NODE_ENV === 'production' ? 2 : 1
}
};
|
//Vue.config.debug = true;
var vm = new Vue({
el: '#app',
data:{
nodeList: [],
nodeTotal: 0,
partitionList: [],
updateTimer: 0,
},
components: {
},
methods: {
update: function()
{
var self = this;
var client = new meta_sApp("http://"+localStorage['target_meta_server']);
result = client.list_nodes({
args: new configuration_list_nodes_request({
'node_status': 'NS_INVALID'
}),
async: true,
on_success: function (nodedata){
try {
nodedata = new configuration_list_nodes_response(nodedata);
// console.log(JSON.stringify(nodedata));
self.$set('nodeList', nodedata);
}
catch(err) {
}
if(self.nodeTotal !=self.nodeList.infos.length)
{
self.nodeTotal = self.nodeList.infos.length;
self.partitionList = [];
}
var index = 0;
for (index = 0; index < self.nodeList.infos.length; ++index)
{
(function(nodeIndex){
result = client.query_configuration_by_node({
args: new configuration_query_by_node_request({
'node': new rpc_address({host:self.nodeList.infos[nodeIndex].address.host,port:self.nodeList.infos[nodeIndex].address.port})
}),
async: true,
on_success: function (servicedata){
try {
servicedata = new configuration_query_by_node_response(servicedata);
// console.log(JSON.stringify(servicedata));
self.partitionList.$set(nodeIndex, servicedata);
}
catch(err) {
return;
}
var index = 0;
for (index = 0; index < self.partitionList[nodeIndex].partitions.length; ++index)
{
var par = self.partitionList[nodeIndex].partitions[index];
par.role = '';
par.working_point = '';
var addressList = {};
addressList['primary'] = par.config.primary.host+':'+par.config.primary.port;
addressList['secondaries'] = [];
for (secondary in par.config.secondaries)
{
addressList['secondaries'][secondary] = par.config.secondaries[secondary].host +':'+ par.config.secondaries[secondary].port;
}
addressList['last_drops'] = [];
for (drop in par.config.last_drops)
{
addressList['last_drops'][drop] = par.config.last_drops[drop].host +':'+ par.config.last_drops[drop].port;
}
if(par.info.is_stateful==true)
{
//stateful service
if (addressList.primary== self.nodeList.infos[nodeIndex].address.host+':'+self.nodeList.infos[nodeIndex].address.port)
{
par['role'] = 'primary';
}
else if (addressList.secondaries.indexOf(
self.nodeList.infos[nodeIndex].address.host+':'+self.nodeList.infos[nodeIndex].address.port) > -1)
{
par['role'] = 'secondary';
}
else if (addressList.last_drops.indexOf(
self.nodeList.infos[nodeIndex].address.host+':'+self.nodeList.infos[nodeIndex].address.port) > -1)
{
par['role'] = 'drop';
}
else
par['role'] = 'undefined';
}
else
{
par['working_point'] = par.last_drops[addressList.secondaries.indexOf(
self.nodeList.infos[nodeIndex].address.host +':'+
self.nodeList.infos[nodeIndex].address.port)];
}
}
},
on_fail: function (xhr, textStatus, errorThrown) {}
});
})(index);
}
},
on_fail: function (xhr, textStatus, errorThrown) {}
});
},
del: function (address, role, gpid)
{
/*
var self = this;
console.log(((role!='')?'replica.':'daemon.') + "kill_partition " + gpid.app_id + " " + gpid.pidx);
var client = new cliApp("http://"+localStorage['target_meta_server']);
result = client.call({
args: new command({
cmd: ((role!='')?'replica.':'daemon.') + "kill_partition",
arguments: [gpid.app_id,gpid.pidx]
}),
async: true,
on_success: function (data){
console.log(data);
},
on_fail: function (xhr, textStatus, errorThrown) {}
});
*/
alert('This function not available now');
}
},
ready: function ()
{
var self = this;
self.update();
//query each machine their service state
self.updateTimer = setInterval(function () {
self.update();
}, 3000);
}
});
|
module.exports = {
input: `# Heading one\n---\n# Heading two`,
output: [
{
type: 'h1',
text: 'Heading one'
},
{
type: 'hr'
},
{
type: 'h1',
text: 'Heading two'
}
]
};
|
function renderLastTrackerItems(items) {
let template = `
<table class="ui red striped table">
<thead>
<th>Reference Number</th>
<th>Status</th>
<th>Track point</th>
<th>Next checking</th>
</thead>
<tbody>
{{lines}}
</tbody>
</table>
`;
const lines = items.map( item => {
return `<tr>
<td>${item.referenceNumber}</td>
<td><span class="ui small ${statusesClass[item.lastStatus.toUpperCase()] || 'primary'} label">${item.lastStatus}</span></td>
<td>${item.tracks.length ? item.tracks[0].trackPoint : ''}</td>
<td>${formatDate(item.nextCheck)}</td>
</tr>`
}).join('');
if(lines) {
template = template.replace(/{{lines}}/g, lines);
}
else {
template = '<div class="ui info message"><p>You have no item, please click on the button below to configure one.</p></div>';
}
return template;
}
function loadLastTrackerItems() {
getTrackItems().then( (items) => {
document.getElementById('trackItems').innerHTML = renderLastTrackerItems(items);
});
}
document.getElementById('configureItems').addEventListener('click', () => {
chrome.tabs.create({'url': chrome.extension.getURL('../options.html')});
});
loadLastTrackerItems();
|
var mythosApp = angular.module('mythosApp', [
'ngRoute',
'mythosControllers',
'ui.bootstrap'
]);
mythosApp.config(['$routeProvider',
function($routeProvider) {
// Dashboard
$routeProvider.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'DashboardCtrl'
// Article detail
}).when('/article/:articleId', {
templateUrl: 'article.html',
controller: 'ArticleDetailCtrl'
// Article list
}).when('/article-list', {
templateUrl: 'article-list.html',
controller: 'ArticlesCtrl'
// Logout
}).when('/logout', {
templateUrl: 'login.html',
controller: 'LogoutCtrl'
// Default
}).otherwise({
redirectTo: '/logout'
});
}
]);
/**
* ===============================================
* Binding directives
* ===============================================
*/
/**
* Translations
* @return void
*/
mythosApp.directive('translate', function() {
return function(scope, element) {
Mythos.translator.init(Mythos.settings.defaultLanguage);
};
});
/**
* Metis menu
* @return void
*/
mythosApp.directive('metisMenu', function() {
return function(scope, element, attrs) {
$(element).metisMenu();
$(window).bind("load resize", function() {
var topOffset = 50,
width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
if (width < 768) {
$('div.navbar-collapse').addClass('collapse');
topOffset = 100; // 2-row-menu
} else {
$('div.navbar-collapse').removeClass('collapse');
}
height = (this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height;
height = height - topOffset;
if (height < 1) height = 1;
if (height > topOffset) {
$("#page-wrapper").css("min-height", (height) + "px");
}
});
};
});
/**
* Form validation
* @return void
*/
mythosApp.directive('formValidator', function() {
return function (scope, element, attrs) {
setTimeout(function() {
$.validate();
}, 300);
}
});
/**
* Summernote
* @return void
*/
mythosApp.directive('summerNote', function() {
return function(scope, element, attrs) {
$('.summernote').summernote({
height: 300,
toolbar: [
['misc', ['codeview', 'fullscreen']],
['style', ['bold', 'italic', 'underline', 'clear']],
['font', ['strikethrough', 'fontsize']],
['para', ['ul', 'ol', 'paragraph']],
['insert', ['picture']]
],
onpaste: function(e) {
var note = $(this),
updateContent = function (note) {
var content = note.html(),
clean = Mythos.stripTags(content);
note.code('').html(clean);
};
setTimeout(function() {
updateContent(note);
}, 100);
}
});
}
});
/**
* Tab bindings
* @return void
*/
mythosApp.directive('bootstrapTabs', function() {
return function (scope, element, attrs) {
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(this).attr('data-href');
$('.tab-pane').removeClass('in active');
$(target).addClass('in active');
});
}
});
/**
* Url proccessing
* @return void
*/
mythosApp.directive('processUrl', function() {
return function (scope, element, attrs) {
// Process title to url
$('input[name="title"]').on('change', function() {
var urlValue = '',
lang = $(this).attr('data-lang'),
urlHolder = $('input[name="url"][data-lang="' + lang + '"]').length !== 0 ? $('input[name="url"][data-lang="' + lang + '"]') : null;
if (typeof Mythos !== "undefined") {
urlValue = Mythos.toUrl($(this).val());
if (urlHolder !== null) {
urlHolder.val(urlValue);
}
}
});
}
});
/**
* Bootstrap accordion bindings
* @return void
*/
mythosApp.directive('bootstrapAccordion', function() {
return function(scope, element, attrs) {
$('a[data-toggle="collapse"]').on('click', function(e) {
var target = $(this).attr('data-href');
$('.collapse.in').collapse('hide');
$(target).collapse('show');
});
}
});
/**
* Datetime picker bindings
* @return void
*/
mythosApp.directive('dateTimePicker', function() {
return function(scope, element, attrs) {
$('.dateTimePicker').datetimepicker();
}
});
/**
* Ligthbox bindings
* @return void
*/
mythosApp.directive('lightBox', function() {
return function(scope, element, attrs) {
$(element).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
}
});
/**
* Google analytics embed API
* @return void
*/
mythosApp.directive('googleAnalytics', function() {
return function(scope, element, attrs) {
var tableId = attrs.googleAnalytics,
clientId = scope.googleClientId;
gapi.analytics.ready(function() {
/**
* Authorize the user immediately if the user has already granted access.
* If no access has been created, render an authorize button inside the
* element with the ID "embed-api-auth-container".
*/
if (gapi.analytics.auth.isAuthorized() === false) {
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: clientId,
});
}
/**
* Create a new DataChart instance with the given query parameters
* and Google chart options. It will be rendered inside an element
* with the id "chart-container".
*/
var dataChart = new gapi.analytics.googleCharts.DataChart({
query: {
ids: 'ga:93592315',
metrics: 'ga:sessions',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday'
},
chart: {
container: 'chart-container',
type: 'LINE',
options: {
width: '100%'
}
}
});
dataChart.set({query: {ids: tableId}}).execute();
$( window ).resize(function() {
dataChart.set({query: {ids: tableId}}).execute();
});
});
};
}); |
describe('toFixed', function () {
beforeEach(module('xt'));
it('assigns a name', [
'toFixed',
function (toFixed) {
expect(toFixed).toBeDefined();
}
]);
}); |
/*!
* Fierce Planet - Event
*
* Copyright (C) 2011 Liam Magee
* MIT Licensed
*/
var FiercePlanet = FiercePlanet || {};
/**
* Possible events:
* - Lifecycle events
* - Agent events (create, change, destroy)
* - Resource events (create, change, destroy)
*
* Event listeners:
* - Logging
* - Recording
* - Notifying
*
* Event structure:
* - Source (game, world, agent, resource)
* - Event (new, complete, change)
* - Data
* - Time (gameCounter)
* - Context (currentWorld)
*
* @constructor
* @param type
* @param source
* @param event
* @param time
* @param worldContext
* @param data
*/
function Event(type, source, event, time, worldContext, data){
this.type = type;
this.source = source;
this.event = event;
this.time = time;
this.worldContext = worldContext;
this.data = data;
}
//Copyright (c) 2010 Nicholas C. Zakas. All rights reserved.
//MIT License
/**
* @constructor
*/
function EventTarget(){
this.listeners = {};
}
EventTarget.prototype = {
constructor: EventTarget,
addListener: function(type, listener){
if (_.isUndefined(this.listeners[type])) {
this.listeners[type] = [];
}
this.listeners[type].push(listener);
},
fire: function(event){
if (typeof event == "string"){
event = { type: event };
}
if (!event.target){
event.target = this;
}
if (!event.type){ //falsy
throw new Error("Event object missing 'type' property.");
}
if (this.listeners[event.type] instanceof Array){
var listeners = this.listeners[event.type];
for (var i=0, len=listeners.length; i < len; i++){
listeners[i].call(this, event);
}
}
},
removeListener: function(type, listener){
if (this.listeners[type] instanceof Array){
var listeners = this.listeners[type];
for (var i=0, len=listeners.length; i < len; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
break;
}
}
}
}
};
/**
* @namespace Contains event functions
*/
FiercePlanet.Event = FiercePlanet.Event || {};
(function() {
/**
* Hooks up custom events
*/
this.hookUpCustomEventListeners = function() {
// Add logging event listeners
FiercePlanet.Game.eventTarget.addListener("game", function(e) {
if (_.isUndefined(console))
console.log("Game event " + e.event + " logged at:" + e.time);
});
// Add notice event listeners
// FiercePlanet.eventTarget.addListener("game", function(e) {
// if (e._event == "newWave" && e._time == 0) {
// FiercePlanet.Game.currentNotice = e._worldContext.getTip();
// }
// });
// Add resource listener
FiercePlanet.Game.eventTarget.addListener("resource", function(e) {
var resource = e.source;
var world = e.worldContext;
if (world.id == 1) {
var resourceCategory = resource.category;
var resourceCategoryName = resourceCategory.name;
var resourceCategoryColor = resourceCategory.color;
var resourceCategoryCode = resourceCategory.code;
var categoryCount = Lifecycle.currentWorld.resourceCategoryCounts[resourceCategoryCode];
if (categoryCount == 1) {
Log.info("Well done! You've added your first " + resourceCategoryName + " resource!");
/*
FiercePlanet.Game.currentNotice = new Notice("Well done! You've added your first " + resourceCategoryName + " resource!");
FiercePlanet.Game.currentNotice.height = 80;
FiercePlanet.Game.currentNotice.foregroundColor = 'rgba(0, 0, 0)';
FiercePlanet.Game.currentNotice.backgroundColor = resourceCategoryColor;
*/
}
}
});
};
}).apply(FiercePlanet.Event);
|
/**
* @param {number} N
* @return {number}
*/
const binaryGap = function (N) {
let max = 0, findFirst = false, dist = 0;
for (let i = 0; i < 32; ++i) {
if (N & 1) {
if (findFirst) {
max = Math.max(max, dist);
} else {
findFirst = true;
}
dist = 1;
} else {
if (findFirst) {
++dist;
}
}
N >>= 1;
}
return max;
};
module.exports = binaryGap; |
import thunk from 'redux-thunk';
import rootReducer from './rootReducer';
import schedulerSaga from 'sagas/scheduler';
import { Subject } from 'rxjs';
import { routerMiddleware } from 'react-router-redux';
import {
applyMiddleware,
compose,
createStore
} from 'redux';
const sagaMiddleware = (saga) => {
const subject = new Subject();
return (store) => {
saga(subject).subscribe((dispatchable) => store.dispatch(dispatchable));
return (next) => (action) => {
next(action);
subject.next({action: action, store: store.getState()});
};
};
};
export default function configureStore (initialState = {}, history) {
// Compose final middleware and use devtools in debug environment
let middleware = applyMiddleware(
thunk,
routerMiddleware(history),
sagaMiddleware(schedulerSaga)
);
if (__DEBUG__) {
const devTools = window.devToolsExtension
? window.devToolsExtension()
: require('containers/DevTools').default.instrument();
middleware = compose(middleware, devTools);
}
// Create final store and subscribe router in debug env ie. for devtools
const store = middleware(createStore)(rootReducer, initialState);
if (module.hot) {
module.hot.accept('./rootReducer', () => {
const nextRootReducer = require('./rootReducer').default;
store.replaceReducer(nextRootReducer);
});
}
return store;
}
|
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jwt-simple');
const auth = require('./auth.js')();
const auth_helpers = require('./auth_helpers.js');
const users = require('./users.js');
const tokens = require('./token_helpers.js');
const wines = require('./wines.js');
const cfg = require('./config.js');
const app = express();
const moment = require('moment');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(auth.initialize());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, HEAD');
next();
});
app.get('/', function (req, res) {
res.json({
status: 'OK!'
});
});
app.get('/api/user', auth.authenticate(), function (req, res) {
res.json({
data: users[req.user.id]
});
});
app.get('/api/wines', auth.authenticate(), function (req,res) {
res.json(wines);
})
app.post('/api/auth/login', function (req, res) {
if (req.body.email && req.body.password) {
var email = req.body.email;
var password = req.body.password;
var user = users.find(function (u) {
return u.email === email && u.password === password;
});
if (user) {
return res.json({
data: {
message: 'Successfully logged in!',
token: tokens.createAccessToken(user),
}
});
}
}
return res.status(401).json({
data: {
error: 'Login/password combination is not correct'
}
});
});
app.post('/api/auth/token', function (req, res) {
if (req.body.username && req.body.password) {
var email = decodeURIComponent(req.body.username);
var password = req.body.password;
var user = users.find(function (u) {
return u.email === email && u.password === password;
});
if (user) {
return res.json({
token_type: 'Bearer',
access_token: tokens.createAccessToken(user),
expires_in: cfg.accessTokenExpiresIn,
refresh_token: tokens.createRefreshToken(user),
});
}
}
return res.status(401).json({
error: 'invalid_client',
error_description: 'Invalid Login/Password combination.'
});
});
app.post('/api/auth/register', function (req, res) {
if (req.body.email && req.body.password && req.body.password === req.body.confirmPassword) {
var user = {
id: 2
};
if (user) {
var payload = {
id: user.id,
email: user.email,
role: 'user',
};
var token = jwt.encode(payload, cfg.jwtSecret);
return res.json({
data: {
message: 'Successfully registered!',
token: token
}
});
}
}
return res.status(401).json({
data: {
error: 'Something went wrong while registering your account. Please check the form and try again.'
}
});
});
app.post('/api/auth/request-pass', function (req, res) {
return res.json({
data: {
message: 'Email with instruction has been sent!'
}
});
});
app.put('/api/auth/reset-pass', function (req, res) {
if (req.body.reset_password_token) {
return res.json({
data: {
message: 'Password successfully reset!'
}
});
}
return res.status(401).json({
data: {
error: 'Token is not correct.'
}
});
});
app.delete('/api/auth/logout', function (req, res) {
return res.json({
data: {
message: 'Successfully logged out!'
}
});
});
app.post('/api/auth/refresh-token', function (req, res) {
// token issued by oauth2 strategy
if (req.body.refresh_token) {
var token = req.body.refresh_token;
var parts = token.split('.');
if (parts.length !== 3) {
return res.status(401).json({
error: 'invalid_token',
error_description: 'Invalid refresh token'
});
}
var payload = JSON.parse(auth_helpers.urlBase64Decode(parts[1]));
var exp = payload.exp;
var userId = payload.sub;
var now = moment().unix();
if (now > exp) {
return res.status(401).json({
error: 'unauthorized',
error_description: 'Refresh Token expired.'
})
} else {
return res.json({
token_type: 'Bearer',
access_token: tokens.createAccessToken(users[userId - 1]),
expires_in: cfg.accessTokenExpiresIn,
});
}
}
// token issued via email strategy
if (req.body.token) {
return res.json({
data: {
message: 'Successfully refreshed token!',
token: tokens.createAccessToken(users[0]),
}
});
};
});
app.listen(4400, function () {
console.log('ngx-admin sample API is running on 4400');
});
module.exports = app;
|
import { WebSocket as MockWebSocket, Server as MockServer } from 'mock-socket';
import { adapters } from '@rails/actioncable';
function startPing(socket) {
setTimeout(() => {
socket.send(
JSON.stringify({ type: 'ping', message: new Date().getTime() })
);
startPing(socket);
}, 3000);
}
function sendWelcomeMessage(socket) {
socket.send(JSON.stringify({ type: 'welcome' }));
}
function processMessage(socket, data) {
let message = JSON.parse(data);
if (message.command == 'subscribe') {
let payload = {
identifier: message.identifier,
type: 'confirm_subscription',
};
socket.send(JSON.stringify(payload));
} else if (message.command == 'message') {
let payload = {
identifier: message.identifier,
message: message.data,
};
socket.send(JSON.stringify(payload));
}
}
function createActionCableMockServer(url) {
const actionCableMockServer = new MockServer(url);
actionCableMockServer.on('connection', (socket) => {
sendWelcomeMessage(socket);
startPing(socket);
socket.on('message', (data) => {
processMessage(socket, data);
});
});
adapters.WebSocket = MockWebSocket;
adapters.actionCableMockServer = actionCableMockServer;
}
export default function () {
if (adapters.actionCableMockServer) {
adapters.actionCableMockServer.stop();
delete adapters.actionCableMockServer;
}
createActionCableMockServer('ws://localhost:4200/cable');
}
|
// build-dependencies: scan, concat, once
Bacon.Property.prototype.startWith = function(seed) {
return withDesc(new Bacon.Desc(this, "startWith", [seed]),
this.scan(seed, (prev, next) => next));
};
Bacon.EventStream.prototype.startWith = function(seed) {
return withDesc(new Bacon.Desc(this, "startWith", [seed]),
Bacon.once(seed).concat(this));
};
|
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* Tabulator v4.6.1 (c) Oliver Folkerd */
var Mutator = function Mutator(table) {
this.table = table; //hold Tabulator object
this.allowedTypes = ["", "data", "edit", "clipboard"]; //list of muatation types
this.enabled = true;
};
//initialize column mutator
Mutator.prototype.initializeColumn = function (column) {
var self = this,
match = false,
config = {};
this.allowedTypes.forEach(function (type) {
var key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
mutator;
if (column.definition[key]) {
mutator = self.lookupMutator(column.definition[key]);
if (mutator) {
match = true;
config[key] = {
mutator: mutator,
params: column.definition[key + "Params"] || {}
};
}
}
});
if (match) {
column.modules.mutate = config;
}
};
Mutator.prototype.lookupMutator = function (value) {
var mutator = false;
//set column mutator
switch (typeof value === "undefined" ? "undefined" : _typeof(value)) {
case "string":
if (this.mutators[value]) {
mutator = this.mutators[value];
} else {
console.warn("Mutator Error - No such mutator found, ignoring: ", value);
}
break;
case "function":
mutator = value;
break;
}
return mutator;
};
//apply mutator to row
Mutator.prototype.transformRow = function (data, type, updatedData) {
var self = this,
key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
value;
if (this.enabled) {
self.table.columnManager.traverse(function (column) {
var mutator, params, component;
if (column.modules.mutate) {
mutator = column.modules.mutate[key] || column.modules.mutate.mutator || false;
if (mutator) {
value = column.getFieldValue(typeof updatedData !== "undefined" ? updatedData : data);
if (type == "data" || typeof value !== "undefined") {
component = column.getComponent();
params = typeof mutator.params === "function" ? mutator.params(value, data, type, component) : mutator.params;
column.setFieldValue(data, mutator.mutator(value, data, type, params, component));
}
}
}
});
}
return data;
};
//apply mutator to new cell value
Mutator.prototype.transformCell = function (cell, value) {
var mutator = cell.column.modules.mutate.mutatorEdit || cell.column.modules.mutate.mutator || false,
tempData = {};
if (mutator) {
tempData = Object.assign(tempData, cell.row.getData());
cell.column.setFieldValue(tempData, value);
return mutator.mutator(value, tempData, "edit", mutator.params, cell.getComponent());
} else {
return value;
}
};
Mutator.prototype.enable = function () {
this.enabled = true;
};
Mutator.prototype.disable = function () {
this.enabled = false;
};
//default mutators
Mutator.prototype.mutators = {};
Tabulator.prototype.registerModule("mutator", Mutator); |
import React from 'react'
import Helmet from "react-helmet"
import { prefixLink } from 'gatsby-helpers'
import { TypographyStyle, GoogleFont } from 'react-typography'
import typography from './utils/typography'
const BUILD_TIME = Date.now();
module.exports = React.createClass({
propTypes () {
return {
body: React.PropTypes.string,
}
},
render () {
const head = Helmet.rewind();
let css;
const production = process.env.NODE_ENV === 'production';
if (production) {
css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} />
}
const customTypography = false;
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
{head.title.toComponent()}
{head.meta.toComponent()}
{customTypography && <TypographyStyle typography={typography} />}
{customTypography && <GoogleFont typography={typography} />}
{css}
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />
<script src={prefixLink(`/bundle.js${production ? '' : 't='+BUILD_TIME}`)} />
</body>
</html>
)
},
});
|
/**
* Fusion.Widget.Legend
*
* $Id$
*
* Copyright (c) 2007, DM Solutions Group Inc.
* 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.
*/
/********************************************************************
* Class: Fusion.Widget.Legend
*
* A widget to display a legend of all layers.
*
* **********************************************************************/
Fusion.Widget.Legend = OpenLayers.Class(Fusion.Widget, {
/**
* Constant: defaultLayerDWFIcon
* {String} The default image for DWF layer
*/
defaultLayerDWFIcon: 'images/icons/legend-DWF.png',
/**
* Constant: defaultLayerRasterIcon
* {String} The default image for Raster layer
*/
defaultLayerRasterIcon: 'images/icons/legend-raster.png',
/**
* Constant: defaultLayerThemeIcon
* {String} The default image for layers that are currently themed.
*/
defaultLayerThemeIcon: 'images/icons/legend-theme.png',
/**
* Constant: defaultDisabledLayerIcon
* {String} The default image for layers that are out of scale.
*/
defaultDisabledLayerIcon: 'images/icons/legend-layer.png',
/**
* Constant: defaultRootFolderIcon
* {String} The default image for the root folder
*/
defaultRootFolderIcon: 'images/icons/legend-map.png',
/**
* Constant: defaultLayerInfoIcon
* {String} The default image for layer info
*/
defaultLayerInfoIcon: 'images/icons/layer-info.png',
/**
* Constant: defaultGroupInfoIcon
* {String} The default image for groupd info
*/
defaultGroupInfoIcon: 'images/icons/group-info.png',
initializeWidget: function(widgetTag) {
// TODO: maybe it's a good idea to do a function like Fusion.Widget.BindRenderer.. for limit the code
// duplication if we plan to apply this pattern to others widgets
Fusion.addWidgetStyleSheet(widgetTag.location + 'Legend/Legend.css');
// TODO: maybe it's a good idea to do a function like Fusion.Widget.BindRenderer.. for limit the code
// duplication if we plan to apply this pattern to others widgets
var json = widgetTag.extension;
if (json.LegendRenderer)
{
var renderer = eval(json.LegendRenderer[0]);
if (renderer && renderer.prototype.CLASS_NAME
&& renderer.prototype.CLASS_NAME == "Fusion.Widget.Legend.LegendRenderer") {
this.renderer = new renderer(this, widgetTag);
} else if (typeof renderer == "function") {
var renderFunction = renderer;
this.renderer = new Fusion.Widget.Legend.LegendRenderer(this);
this.renderer.mapLoaded = renderFunction;
this.renderer.mapReloaded = renderFunction;
this.renderer.mapLoading = false;
} else {
this.renderer = new Fusion.Widget.Legend.LegendRendererDefault(this, widgetTag);
}
} else {
this.renderer = new Fusion.Widget.Legend.LegendRendererDefault(this, widgetTag);
}
if (this.renderer.mapReloaded)
this.getMap().registerForEvent(Fusion.Event.MAP_RELOADED,
OpenLayers.Function.bind(this.renderer.mapReloaded, this.renderer));
if (this.renderer.mapLoading)
this.getMap().registerForEvent(Fusion.Event.MAP_LOADING,
OpenLayers.Function.bind(this.renderer.mapLoading,this.renderer));
if (this.renderer.mapLoaded)
this.getMap().registerForEvent(Fusion.Event.MAP_LOADED,
OpenLayers.Function.bind(this.renderer.mapLoaded, this.renderer));
if (this.renderer.scaleRangesLoaded)
this.getMap().registerForEvent(Fusion.Event.MAP_SCALE_RANGE_LOADED,
OpenLayers.Function.bind(this.renderer.scaleRangesLoaded, this.renderer));
}
});
/* Class: Fusion.Widget.Legend.LegendRenderer
* This is a class designed to help users to create their own renderer
* for customize the legend.
*/
Fusion.Widget.Legend.LegendRenderer = OpenLayers.Class(
{
/**
* Property: oLegend
* {<Fusion.Widget.Legend>} The parent widget that uses
* the renderer.
*/
oLegend: null,
/**
* Property: layerRoot
* {Groups} The groups of all layers.
*
*/
layerRoot: null,
initialize: function(legend) {
this.oLegend = legend;
this.layerRoot = this.getMap().layerRoot;
},
/**
* Method: renderLegend
* Abstract method that have the main purpose to draw the legend. This method
* should be implemented by all concrete class.
*
*/
renderLegend: function() {},
/**defaultDisabledLayerIcon
* Method: mapLoading
* Abstract method that handle the event: Fusion.Event.MAP_LOADING. This method
* is optional.
*
*/
mapLoading: function() {},
/**
* Method: mapLoaded
* Abstract method that handle the event: Fusion.Event.MAP_LOADED. This method
* occur only at the first load of the map and should be implemented by all concrete class.
*
*/
mapLoaded: function() {},
/**
* Method: mapReloaded
* Abstract method that handle the event: Fusion.Event.MAP_RELOADED. This method
* should be implemented by all concrete class.
*
*/
mapReloaded: function() {},
/**
* Method: mapRefresh
* Abstract method that handle the event: Fusion.Event.MAP_LAYER_ORDER_CHANGED. This method
* should be implemented by all concrete class.
*
*/
mapRefresh: function() {},
/**
* Method: getMap
* Helper method to obtains the map.
*
* Returns:
* {<Fusion.Maps>} The map that uses the SelectionPanel Widget.
*/
getMap: function() {
return this.oLegend.getMap();
},
CLASS_NAME: "Fusion.Widget.Legend.LegendRenderer"
});
/* Class: Fusion.Widget.Legend.LegendRendererDefault
* This class provide a default legend as a collapsable tree.
*
*/
Fusion.Widget.Legend.LegendRendererDefault = OpenLayers.Class(Fusion.Widget.Legend.LegendRenderer,
{
/**
* Property: showRootFolder
* {Boolean} This controls whether the tree will have a single root node that
* contains the name of the map as its label. By default, the root node does
* not appear. Set to "true" or "1" to make the root node appear.
*/
showRootFolder: false,
/**
* Property: currentNode
* {Jx.TreeNode} The current selected node.
*/
currentNode: null,
/**
* Property: bIsDrawn
* {Boolean} Determine if the map is drawn.
*/
bIsDrawn: false,
/**
* Property: updateDelay
* {Integer} number of milliseconds to delay the update of legend
*/
updateDelay: 500,
/**
* Property: targetFolder
* {Jx.TreeFolder} The current TreeFolder that the mouse will interact with.
*/
targetFolder: null,
/**
* Property: bIncludeVisToggle
* {Boolean} Determine if non-visible layer must be draw in the legend.
*/
bIncludeVisToggle: true,
offsetsCalculated: false,
initialize: function(legend, widgetTag) {
Fusion.Widget.Legend.LegendRenderer.prototype.initialize.apply(this, [legend]);
var json = widgetTag.extension;
this.imgLayerDWFIcon = json.LayerDWFIcon ? json.LayerDWFIcon[0] : this.oLegend.defaultLayerDWFIcon;
this.imgLayerRasterIcon = json.LayerRasterIcon ? json.LayerRasterIcon[0] : this.oLegend.defaultLayerRasterIcon;
this.imgLayerThemeIcon = json.LayerThemeIcon ? json.LayerThemeIcon[0] : this.oLegend.defaultLayerThemeIcon;
this.imgDisabledLayerIcon = json.DisabledLayerIcon ? json.DisabledLayerIcon[0] : this.oLegend.defaultDisabledLayerIcon;
this.imgLayerInfoIcon = json.LayerInfoIcon ? json.LayerInfoIcon[0] : this.oLegend.defaultLayerInfoIcon;
this.imgGroupInfoIcon = json.GroupInfoIcon ? json.GroupInfoIcon[0] : this.oLegend.defaultGroupInfoIcon;
//not used?
//this.layerInfoURL = json.LayerInfoURL ? json.LayerInfoURL[0] : '';
this.selectedLayer = null;
this.selection = new Jx.Selection({
onSelect: function(item) {
var treeItem = item.retrieve('jxTreeItem');
var data = treeItem.options.data;
if (data instanceof Fusion.Layers.Group) {
this.getMap().setActiveLayer(null);
} else {
this.getMap().setActiveLayer(data);
}
}.bind(this)
});
this.oTree = new Jx.Tree({
template: '<ul class="jxTreeRoot fusionLegendTreeRoot"></ul>',
selection:this.selection
}).addTo(this.oLegend.domObj);
this.hideInvisibleLayers = (json.HideInvisibleLayers && json.HideInvisibleLayers[0]) == 'true' ? true : false;
//don't show the root folder by default
this.showRootFolder = (json.ShowRootFolder && json.ShowRootFolder[0] == 'true') ? true:false;
//do show the map folder by default
this.showMapFolder = (json.ShowMapFolder && json.ShowMapFolder[0] == 'false') ? false:true;
if (!this.showRootFolder) {
//console.log('supressing root folder');
this.oRoot = this.oTree;
} else {
// console.log('showing root folder');
var opt = {
label: OpenLayers.i18n('defaultMapTitle'),
// contextMenu: this.getContextMenu(),
open: true
};
this.oRoot = new Jx.TreeFolder(opt);
this.oTree.add(this.oRoot);
// this.oRoot.options.contextMenu.add([
// new Jx.Menu.Item({
// label: OpenLayers.i18n('collapse'),
// onClick: OpenLayers.Function.bind(this.collapseBranch, this, this.oRoot)
// }),
// new Jx.Menu.Item({
// label: OpenLayers.i18n('expand'),
// onClick: OpenLayers.Function.bind(this.expandBranch, this, this.oRoot)
// })]
// );
}
this.extentsChangedWatcher = this.update.bind(this);
},
getContextMenu: function() {
return new Jx.Menu.Context(this.name).add([
new Jx.Menu.Item({
label: OpenLayers.i18n('refresh'),
onClick: OpenLayers.Function.bind(this.update, this)
}),
new Jx.Menu.Item({
label: OpenLayers.i18n('collapseAll'),
onClick: OpenLayers.Function.bind(this.collapseAll, this)
}),
new Jx.Menu.Item({
label: OpenLayers.i18n('expandAll'),
onClick: OpenLayers.Function.bind(this.expandAll, this)
})]
);
},
expandAll: function(folder) {
this.oTree.items().each(function(item){
if (item instanceof Jx.TreeFolder) {
this.recurseTree('expand', item);
}
},this);
if (this.showRootFolder) {
this.oRoot.expand();
}
},
collapseAll: function(folder) {
this.oTree.items().each(function(item){
if (item instanceof Jx.TreeFolder) {
this.recurseTree('collapse', item);
}
},this);
if (this.showRootFolder) {
this.oRoot.collapse();
}
},
collapseBranch: function(folder) {
folder.collapse();
},
expandBranch: function(folder) {
folder.expand();
},
/**
* recursively descend the tree applying the request operation which is either 'collapse' or 'expand'
*
* @param op the operation to execute
* @param the folder to operate on
*/
recurseTree: function(op, folder) {
folder.items().each(function(item){
if (item instanceof Jx.TreeFolder) {
this.recurseTree(op, item);
item[op]();
}
},this);
},
scaleRangesLoaded: function() {
this.layerRoot = this.getMap().layerRoot;
this.renderLegend();
},
mapLoading: function() {
this.getMap().deregisterForEvent(Fusion.Event.MAP_EXTENTS_CHANGED, this.extentsChangedWatcher);
this.clear();
},
mapLoaded: function() {
this.getMap().registerForEvent(Fusion.Event.MAP_EXTENTS_CHANGED, this.extentsChangedWatcher);
var baseLayer = this.oLegend.getMapLayer();
baseLayer.registerForEvent(Fusion.Event.MAP_LAYER_ORDER_CHANGED, OpenLayers.Function.bind(this.mapRefresh, this));
this.layerRoot = this.getMap().layerRoot;
//this.renderLegend();
},
mapReloaded: function() {
this.layerRoot = this.getMap().layerRoot;
this.renderLegend();
},
mapRefresh: function() {
var baseLayer = this.oLegend.getMapLayer();
baseLayer.parseLayers();
this.layerRoot = this.getMap().layerRoot;
this.renderLegend();
},
/**
* Callback for legend XML response. Creates a list of layers and sets up event
* handling. Create groups if applicable.
* TODO: error handling
*
* @param r Object the reponse xhr object
*/
renderLegend: function(r) {
this.bIsDrawn = false;
this.clear();
if (this.showRootFolder) {
this.oRoot.setLabel(this.oLegend.getMapLayer().getMapTitle());
}
var startGroup = this.layerRoot;
if (!this.showMapFolder) {
startGroup = this.layerRoot.groups[0];
}
if (!startGroup.legend) {
startGroup.legend = {};
startGroup.legend.treeItem = this.oRoot;
}
for (var i=0; i<startGroup.groups.length; i++) {
//startGroup.groups[i].visible = true;
this.processMapGroup(startGroup.groups[i], this.oRoot);
}
for (var i=0; i<startGroup.layers.length; i++) {
this.processMapLayer(startGroup.layers[i], this.oRoot);
}
this.bIsDrawn = true;
this.update();
},
processMapGroup: function(group, folder) {
if (group.displayInLegend) {
/* make a 'namespace' on the group object to store legend-related info */
group.legend = {};
var opt = {
label: group.legendLabel,
open: group.expandInLegend,
// contextMenu: this.getContextMenu(),
checked: group.visible
};
var treeItem = new Fusion.Widget.Legend.TreeFolder(opt);
treeItem.options.data = group;
group.legend.treeItem = treeItem;
// treeItem.options.contextMenu.add(
// new Jx.Menu.Item({
// label: OpenLayers.i18n('collapse'),
// onClick: OpenLayers.Function.bind(this.collapseBranch, this, treeItem)
// }),
// new Jx.Menu.Item({
// label: OpenLayers.i18n('expand'),
// onClick: OpenLayers.Function.bind(this.expandBranch, this, treeItem)
// })
// );
folder.add(treeItem);
var groupInfo = group.oMap.getGroupInfoUrl(group.groupName);
if (groupInfo) {
treeItem.setGroupInfo(groupInfo, this.imgGroupInfoIcon);
}
for (var i=0; i<group.groups.length; i++) {
this.processMapGroup(group.groups[i], treeItem);
}
for (var i=0; i<group.layers.length; i++) {
this.processMapLayer(group.layers[i], treeItem);
}
}
},
processMapLayer: function(layer, folder) {
/* make a 'namespace' on the layer object to store legend-related info */
layer.legend = {};
layer.legend.parentItem = folder;
layer.legend.currentRange = null;
layer.oMap.registerForEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, OpenLayers.Function.bind(this.layerPropertyChanged, this));
},
layerPropertyChanged: function(eventID, layer) {
layer.legend.treeItem.check(layer.isVisible());
},
updateTimer: null,
update: function() {
if (this.bIsDrawn) {
if (this.updateTimer) {
window.clearTimeout(this.updateTimer);
this.updateTimer = null;
}
this.updateTimer = window.setTimeout(OpenLayers.Function.bind(this._update, this), this.updateDelay);
}
},
/**
* update the tree when the map scale changes
*/
_update: function() {
this.updateTimer = null;
var map = this.getMap();
var currentScale = map.getScale();
for (var i=0; i<map.layerRoot.groups.length; i++) {
this.updateGroupLayers(map.layerRoot.groups[i], currentScale);
}
for (var i=0; i<map.layerRoot.layers.length; i++) {
this.updateLayer(map.layerRoot.layers[i], currentScale);
}
},
/**
* remove the dom objects representing the legend layers and groups
*/
clear: function() {
//console.log('clear legend');
var map = this.getMap();
for (var i=0; i<map.layerRoot.groups.length; i++) {
this.clearGroup(map.layerRoot.groups[i]);
}
for (var i=0; i<map.layerRoot.layers.length; i++) {
if (map.layerRoot.layers[i].legend) {
map.layerRoot.layers[i].legend.treeItem = null;
map.layerRoot.layers[i].legend.checkbox = null;
map.layerRoot.layers[i].legend.currentRange = null;
}
}
this.oRoot.empty();
},
clearGroup: function(group) {
for (var i=0; i<group.groups.length; i++) {
this.clearGroup(group.groups[i]);
}
for (var i=0; i<group.layers.length; i++) {
if (group.layers[i].legend) {
group.layers[i].legend.treeItem = null;
group.layers[i].legend.currentRange = null;
}
}
},
updateGroupLayers: function(group, fScale) {
for (var i=0; i<group.groups.length; i++) {
this.updateGroupLayers(group.groups[i], fScale);
}
for (var i=0; i<group.layers.length; i++) {
this.updateLayer(group.layers[i], fScale);
}
},
updateLayer: function(layer, fScale) {
/* no need to do anything if we are hiding the layer */
if (!layer.displayInLegend || !layer.legend) {
return;
}
/* check the layer's current scale range against the previous one
* if the range hasn't changed, don't do anything
*/
var range = layer.getScaleRange(fScale);
if (range == layer.legend.currentRange && layer.legend.treeItem) {
return;
}
/* remember the range we are now representing for the next update */
layer.legend.currentRange = range;
/* if layer is in range and has at least one style */
if (range != null && range.styles && range.styles.length > 0) {
/* if it has more than one style, we represent it as a folder
* with classes as items in it
*/
if (range.styles.length > 1) {
//tree item needs to be a folder
if (!layer.legend.treeItem) {
layer.legend.treeItem = this.createFolderItem(layer);
layer.parentGroup.legend.treeItem.add(layer.legend.treeItem);
} else if (layer.legend.treeItem instanceof Fusion.Widget.Legend.TreeItem) {
this.clearTreeItem(layer);
layer.legend.treeItem = this.createFolderItem(layer);
layer.parentGroup.legend.treeItem.add(layer.legend.treeItem);
} else {
layer.legend.treeItem.empty();
}
//This style range has the compression flag set. This would have been set server-side
//if it contains more than a pre-defined number of style rules (see LoadScaleRanges.php for
//more information)
if (range.isCompressed) {
//Attach required data for theme expansion later on
layer.legend.treeItem.layer = layer;
layer.legend.treeItem.range = range;
layer.legend.treeItem.scale = fScale;
layer.legend.treeItem.hasDecompressedTheme = false;
//console.assert(range.styles.length > 2);
layer.legend.treeItem.add(this.createTreeItem(layer, range.styles[0], fScale, false));
layer.legend.treeItem.add(this.createThemeCompressionItem(range.styles.length - 2, layer.legend.treeItem));
layer.legend.treeItem.add(this.createTreeItem(layer, range.styles[range.styles.length-1], fScale, false));
} else {
//FIXME: JxLib really needs an API to add these in a single batch that doesn't hammer
//the DOM (if it's even possible)
for (var i=0; i<range.styles.length; i++) {
var item = this.createTreeItem(layer, range.styles[i], fScale, false);
layer.legend.treeItem.add(item);
}
}
/* if there is only one style, we represent it as a tree item */
} else {
var style = range.styles[0];
if (!style.legendLabel) {
style.legendLabel = layer.legendLabel;
}
if (!layer.legend.treeItem) {
layer.legend.treeItem = this.createTreeItem(layer, style, fScale, true);
layer.parentGroup.legend.treeItem.add(layer.legend.treeItem);
} else if (layer.legend.treeItem instanceof Fusion.Widget.Legend.TreeFolder) {
this.clearTreeItem(layer);
layer.legend.treeItem = this.createTreeItem(layer, style, fScale, true);
layer.parentGroup.legend.treeItem.add(layer.legend.treeItem);
} else {
if (range.styles.length > 0) {
var url = layer.oMap.getLegendImageURL(fScale, layer, range.styles[0]);
layer.legend.treeItem.setImage(url);
layer.legend.treeItem.enable(true);
} else {
layer.legend.treeItem.enable(false);
}
}
}
} else {
/* the layer is to be displayed but is not visible in the map
* at the current map scale so disable it and display as a tree
* item or hide it altogether if necessary;
*/
if (this.hideInvisibleLayers) {
if (layer.legend.treeItem) {
layer.parentGroup.legend.treeItem.remove(layer.legend.treeItem);
layer.legend.treeItem = null;
}
} else {
var newTreeItem = this.createTreeItem(layer, {legendLabel: layer.legendLabel}, null, true);
if (layer.legend.treeItem) {
layer.parentGroup.legend.treeItem.replace(newTreeItem, layer.legend.treeItem);
layer.legend.treeItem.finalize();
} else {
layer.parentGroup.legend.treeItem.add(newTreeItem);
}
layer.legend.treeItem = newTreeItem;
}
}
if (layer.legend.treeItem) {
layer.legend.treeItem.options.data = layer;
layer.legend.treeItem.check(layer.visible);
}
},
getThemeExpandContextMenu: function(node) {
return new Jx.Menu.Context(this.name).add([
new Jx.Menu.Item({
label: OpenLayers.i18n('expandTheme'),
onClick: OpenLayers.Function.bind(function() { this.expandTheme(node); }, this)
})]
);
},
expandTheme: function(node) {
if (node.hasDecompressedTheme !== true && confirm(OpenLayers.i18n('expandCompressedThemeConfirmation'))) {
var range = node.range;
var layer = node.layer;
var fScale = node.scale;
node.empty();
//FIXME: JxLib really needs an API to add these in a single batch that doesn't hammer
//the DOM (if it's even possible)
for (var i = 0; i < range.styles.length; i++) {
var item = this.createTreeItem(layer, range.styles[i], fScale, false);
node.add(item);
}
node.hasDecompressedTheme = true;
}
},
createThemeCompressionItem: function(number, node) {
var opt = {
label: OpenLayers.i18n('otherThemeItems', { count: number }),
draw: this.renderItem,
contextMenu: this.getThemeExpandContextMenu(node),
image: this.imgBlankIcon
};
var item = new Jx.TreeItem(opt);
return item;
},
createFolderItem: function(layer) {
var opt = {
label: layer.legendLabel == '' ? ' ' : layer.legendLabel,
isOpen: layer.expandInLegend,
// contextMenu: this.getContextMenu(),
image: this.imgLayerThemeIcon
};
if (layer.metadata) {
opt.selectable = !layer.metadata.jxUnselectable || (layer.metadata.jxUnselectable && layer.metadata.jxUnselectable != 'true');
} else {
opt.selectable = false;
}
var folder = new Fusion.Widget.Legend.TreeFolder(opt);
var img = folder.elements.get('jxTreeIcon');
img.style.backgroundPosition = '0px 0px';
// folder.options.contextMenu.add([
// new Jx.Menu.Item({
// label: OpenLayers.i18n('collapse'),
// onClick: OpenLayers.Function.bind(this.collapseBranch, this, folder)
// }),
// new Jx.Menu.Item({
// label: OpenLayers.i18n('expand'),
// onClick: OpenLayers.Function.bind(this.expandBranch, this, folder)
// })]
// );
var layerInfo = layer.oMap.getLayerInfoUrl(layer.layerName);
if (layerInfo) {
folder.setLayerInfo(layerInfo, this.imgLayerInfoIcon);
}
return folder;
},
createTreeItem: function(layer, style, scale, checkbox) {
var opt = {};
opt.statusIsDefault = layer.statusDefault;
opt.label = style.legendLabel == '' ? ' ' : style.legendLabel;
if (layer.metadata) {
opt.selectable = !layer.metadata.jxUnselectable || (layer.metadata.jxUnselectable && layer.metadata.jxUnselectable != 'true');
} else {
opt.selectable = false;
}
if (!style) {
opt.image = this.imgDisabledLayerIcon;
opt.enabled = false;
} else {
var defaultIcon = this.imgDisabledLayerIcon;
if (layer.layerTypes[0] == 4) {
if (style.staticIcon == Fusion.Constant.LAYER_DWF_TYPE) {
defaultIcon = this.imgLayerDWFIcon;
} else {
defaultIcon = this.imgLayerRasterIcon;
}
}
if (style.iconOpt && style.iconOpt.url) {
//if (style.iconOpt.url.indexOf("data:image") >= 0)
// console.log("Fetching pre-cached icon");
opt.image = style.iconOpt.url;
} else {
opt.image = layer.oMap.getLegendImageURL(scale, layer, style);
}
}
var item;
if (checkbox) {
// opt.contextMenu = this.getContextMenu();
item = new Fusion.Widget.Legend.TreeItem(opt);
/* only need to add layer info if it has a check box too */
var layerInfo = layer.oMap.getLayerInfoUrl(layer.layerName);
if (layerInfo) {
item.setLayerInfo(layerInfo, this.imgLayerInfoIcon);
}
} else {
opt.selectable = false;
item = new Jx.TreeItem(opt);
}
var iconX = 0;
var iconY = 0;
var img = item.elements.get('jxTreeIcon');
if (style && style.iconX >= 0 && style.iconY >= 0) {
/* calculate the size of the image that holds the icon
* only once and cache the values as it is an expensive operation
* We use the size to center the class/layer icon as a background
* image inside the image that holds it so that if the icon is
* not the same size it is represented in a reasonable way
*/
if (!this.offsetsCalculated) {
var parent = img.parentNode;
var sibling = img.getPrevious();
var d = new Element('div', {'class':'fusionLegendTreeRoot'});
img.setStyle('visiblity','hidden');
img.inject(d);
//TODO: img.getStyle doesn't seem to work for IE, need another solution here
var w = 16;//img.getStyle('width').toInt();
var h = 16;//img.getStyle('height').toInt();
if (!sibling) {
img.inject(parent,'top');
} else {
img.inject(sibling, 'after');
}
img.setStyle('visibility','visible');
this.iconWidth = ((style.iconOpt?style.iconOpt.width:16) - w)/2;
this.iconHeight = ((style.iconOpt?style.iconOpt.height:16) - h)/2;
//alert(w+":"+h);
this.offsetsCalculated = true;
}
iconX = -1 * (style.iconX + this.iconWidth);
iconY = -1 * (style.iconY + this.iconHeight);
}
img.style.backgroundPosition = iconX + 'px ' + iconY + 'px';
return item;
},
clearTreeItem: function(layer) {
if (layer.legend.treeItem && layer.legend.treeItem.owner) {
layer.legend.treeItem.owner.remove(layer.legend.treeItem);
// layer.legend.treeItem.finalize();
layer.legend.treeItem.destroy();
layer.legend.treeItem = null;
}
}
});
Fusion.Widget.Legend.TreeItem = new Class({
Extends: Jx.TreeItem,
options: {
template: '<li class="jxTreeContainer jxTreeLeaf"><img class="jxTreeImage" src="'+Jx.aPixel.src+'" alt="" title=""><span class="fusionLegendCheckboxContainer"><input type="checkbox" class="fusionLegendCheckboxInput"></span><a class="fusionLayerInfo" target="_blank"><img class="fusionLayerInfoIcon" src="'+Jx.aPixel.src+'"></a><a class="jxTreeItem fusionCheckboxItem" href="javascript:void(0);"><img class="jxTreeIcon" src="'+Jx.aPixel.src+'" alt="" title=""><span class="jxTreeLabel" alt="" title=""></span></a></li>'
},
classes: new Hash({
domObj: 'jxTreeContainer',
domA: 'jxTreeItem',
domImg: 'jxTreeImage',
domIcon: 'jxTreeIcon',
domLabel: 'jxTreeLabel',
checkbox: 'fusionLegendCheckboxInput',
layerInfo: 'fusionLayerInfo',
layerInfoIcon: 'fusionLayerInfoIcon'
}),
init: function() {
this.bound.onClick = function(e){
if (this.options.data) {
if (e.target.checked && this.options.data.show) {
this.options.data.show();
} else if (!e.target.checked && this.options.data.hide) {
this.options.data.hide();
}
}
}.bind(this);
this.bound.enabled = function() {
this.checkbox.disabled = false;
}.bind(this);
this.bound.disabled = function() {
this.checkbox.disabled = true;
}.bind(this);
this.parent();
},
render: function() {
this.parent();
this.domLabel.set('alt', this.options.label);
this.domLabel.set('title', this.options.label);
if (this.checkbox) {
if ($defined(this.options.checked)) {
this.check(this.options.checked);
}
this.checkbox.addEvent('click', this.bound.onClick);
this.addEvents({
enabled: this.bound.enabled,
disabled: this.bound.disabled
});
}
},
cleanup: function() {
this.removeEvents({
enabled: this.bound.enabled,
disabled: this.bound.disabled
});
if (this.checkbox) {
this.checkbox.removeEvent('click', this.bound.onClick);
}
this.bound.onClick = null;
this.bound.enabled = null;
this.bound.disabled = null;
this.parent();
},
check: function(state) {
if (this.checkbox) {
this.checkbox.set('checked', state);
}
},
isChecked: function() {
return this.checkbox && this.checkbox.checked;
},
setLayerInfo: function(url, icon) {
//change class to make fusionLayerInfo display block
this.domObj.addClass('fusionShowLayerInfo');
if (this.layerInfo) {
this.layerInfo.set('href', url);
}
if (this.layerInfoIcon) {
this.layerInfoIcon.set('src', icon);
}
}
});
Fusion.Widget.Legend.TreeFolder = new Class({
Extends: Jx.TreeFolder,
options: {
template: '<li class="jxTreeContainer jxTreeBranch"><img class="jxTreeImage" src="'+Jx.aPixel.src+'" alt="" title=""><span class="fusionLegendCheckboxContainer"><input type="checkbox" class="fusionLegendCheckboxInput"></span><a class="jxTreeItem fusionCheckboxItem" href="javascript:void(0);"><img class="jxTreeIcon" src="'+Jx.aPixel.src+'" alt="" title=""><span class="jxTreeLabel" alt="" title=""></span></a><a class="fusionGroupInfo"><img class="fusionGroupInfoIcon" src="'+Jx.aPixel.src+'"></a><a class="fusionLayerInfo"><img class="fusionLayerInfoIcon" src="'+Jx.aPixel.src+'"></a><ul class="jxTree"></ul></li>'
},
classes: new Hash({
domObj: 'jxTreeContainer',
domA: 'jxTreeItem',
domImg: 'jxTreeImage',
domIcon: 'jxTreeIcon',
domLabel: 'jxTreeLabel',
domTree: 'jxTree',
checkbox: 'fusionLegendCheckboxInput',
layerInfo: 'fusionLayerInfo',
layerInfoIcon: 'fusionLayerInfoIcon',
groupInfo: 'fusionGroupInfo',
groupInfoIcon: 'fusionGroupInfoIcon'
}),
init: function() {
this.bound.onClick = function(e){
if (this.options.data) {
if (e.target.checked && this.options.data.show) {
this.options.data.show();
} else if (!e.target.checked && this.options.data.hide) {
this.options.data.hide();
}
}
}.bind(this);
this.bound.enabled = function() {
this.checkbox.disabled = false;
}.bind(this);
this.bound.disabled = function() {
this.checkbox.disabled = true;
}.bind(this);
this.parent();
},
render: function() {
this.parent();
this.domLabel.set('alt', this.options.label);
this.domLabel.set('title', this.options.label);
if (this.checkbox) {
if ($defined(this.options.checked)) {
this.check(this.options.checked);
}
this.checkbox.addEvent('click', this.bound.onClick);
this.addEvents({
enabled: this.bound.enabled,
disabled: this.bound.disabled
});
}
},
cleanup: function() {
this.removeEvents({
enabled: this.bound.enabled,
disabled: this.bound.disabled
});
if (this.checkbox) {
this.checkbox.removeEvent('click', this.bound.onClick);
}
this.bound.onClick = null;
this.bound.enabled = null;
this.bound.disabled = null;
this.parent();
},
check: function(state) {
if (this.checkbox) {
this.checkbox.set('checked', state);
}
},
isChecked: function() {
return this.checkbox && this.checkbox.checked;
},
setLayerInfo: function(url, icon) {
//change class to make fusionLayerInfo display block
this.domObj.addClass('fusionShowLayerInfo');
if (this.layerInfo) {
this.layerInfo.set('href', url);
}
if (this.layerInfoIcon) {
this.layerInfoIcon.set('src', icon);
}
},
setGroupInfo: function(url, icon) {
//change class to make fusionGroupInfo display block
this.domObj.addClass('fusionShowGroupInfo');
if (this.groupInfo) {
this.groupInfo.set('href', url);
}
if (this.groupInfoIcon) {
this.groupInfoIcon.set('src', icon);
}
}
}); |
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import rootReducer from './rootReducer';
export default function configureStore(initialState = {}, history) {
// Compose final middleware and use devtools in debug environment
let middleware = applyMiddleware(thunk, routerMiddleware(history));
if (__DEBUG__) {
const devTools = window.devToolsExtension
? window.devToolsExtension()
: require('containers/DevTools').default.instrument();
middleware = compose(middleware, devTools);
}
// Create final store and subscribe router in debug env ie. for devtools
const store = middleware(createStore)(rootReducer, initialState);
if (module.hot) {
module.hot.accept('./rootReducer', () => {
const nextRootReducer = require('./rootReducer').default;
store.replaceReducer(nextRootReducer);
});
}
return store;
}
|
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
import { BigNumberDependencies } from './dependenciesBigNumberClass.generated';
import { createE } from '../../factoriesAny.js';
export var eDependencies = {
BigNumberDependencies: BigNumberDependencies,
createE: createE
}; |
/**
* Created by Michał on 2017-09-02.
*/
//script runs after submitting the answer
$("#answer_form").submit(function (event) {
event.preventDefault();
searchViaAjax();
});
//AJAX request and its configuration
function searchViaAjax() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/processAnswer?answer=" + $("#wordInEnglish").val(),
dataType: 'json',
timeout: 100000,
success: function (data) {
console.log("SUCCESS: ", data);
displayResponse(data);
},
error: function (e) {
console.log("ERROR: ", e);
displayScoreAndNextWord(e);
},
done: function () {
console.log("DONE");
}
});
}
//function responsible for displaying data
function displayResponse(data) {
const response = JSON.parse(JSON.stringify(data, null, 4));
$('#word_to_translate').text(response.nextWord);
$('#is_correct').text(response.isCorrect);
$('#correct_answer').text(response.correctAnswer);
$('#points').text(response.points);
modifyApp();
}
//function responsible for displaying score
function displayScoreAndNextWord(data) {
const tab = data.responseText.split(" ");
$('#word_to_translate').text(tab[1]);
$('#is_correct').text("");
$('#correct_answer').text("");
$('#points').text("");
alert("Koniec ćwiczenia. \nZdobyłeś: " + tab[0] + "/20.");
} |
this.NesDb = this.NesDb || {};
NesDb[ 'FF4E61F3D48E54FCE35E8A4E5DF8BCC92440CD2F' ] = {
"$": {
"name": "Day Dreamin' Davey",
"class": "Licensed",
"catalog": "NES-6D-USA",
"publisher": "HAL Laboratory",
"developer": "Sculptured Software",
"region": "USA",
"players": "1",
"date": "1992-06"
},
"cartridge": [
{
"$": {
"system": "NES-NTSC",
"crc": "E145B441",
"sha1": "FF4E61F3D48E54FCE35E8A4E5DF8BCC92440CD2F",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2006-02-19"
},
"board": [
{
"$": {
"type": "NES-SLROM",
"pcb": "NES-SLROM-06",
"mapper": "1"
},
"prg": [
{
"$": {
"name": "NES-6D-0 PRG",
"size": "256k",
"crc": "EDD6D29B",
"sha1": "7630B8054F95B1C74B35EFFDFE3AD06E7C30A5BB"
}
}
],
"chr": [
{
"$": {
"name": "NES-6D-0 CHR",
"size": "128k",
"crc": "99461FF6",
"sha1": "B6854EAF9ABC12FAE7CD976D80B930486CB40A2A"
}
}
],
"chip": [
{
"$": {
"type": "MMC1B2"
}
}
],
"cic": [
{
"$": {
"type": "6113B1"
}
}
]
}
]
}
]
};
|
var music = document.getElementById('audio');
function playAudio() {
if (music.paused) {
music.play();
pButton.className = 'pause';
} else {
music.pause();
pButton.className = 'play';
}
}
|
/**
* New node file
*/
require("rapid-core");
require("rapid-httpserver");
//自动检测配置目录并载入
rapid.autoConfig(); |
import express from 'express';
import serialize from 'serialize-javascript';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { createMemoryHistory, match, RouterContext } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { configureStore } from './redux/store';
import routes from './routes';
import { StyleRoot } from 'radium';
import api from './api';
import { loadData } from './api/github';
const app = express();
/** 'api' folder handles '/api' routes */
app.use('/api', api);
/** Render public folder for static assets. */
app.use('/public', express.static(`${__dirname}./../public`));
/** React Component that renders the appropriate HTML,
given an HTML content and a store */
const HTML = ({ content, store }) => (
<html>
<head>
<title>lachlankermode.com</title>
<link href="https://fonts.googleapis.com/css?family=PT+Serif" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="/public/styles.css" />
</head>
<body>
<div className="container">
<div id="app" dangerouslySetInnerHTML={{ __html: content }}></div>
</div>
<script dangerouslySetInnerHTML={
{ __html: `window.__initialState__=${serialize(store.getState())};` }
}
/>
<script src="/public/bundle.js" />
</body>
</html>
);
/** General handler for all routes. This handler will match React Router routes,
render the app serverside, and then stringify it and send it to the client. */
app.use((req, res) => {
/** Create store. Must use memory history without browser */
const memoryHistory = createMemoryHistory(req.path);
let store = configureStore(memoryHistory);
const history = syncHistoryWithStore(memoryHistory, store);
/** Match history */
match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
/** Error in matching routes */
if (error) {
res.status(500).send(error.message);
/** Specified Redirect */
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
/** Successful match, render app serverside */
} else if (renderProps) {
// NB, TODO: hits here twice per request for some reason...
loadData().then(state => {
store = configureStore(memoryHistory, state);
const content = (
<Provider store={store}>
<StyleRoot>
<RouterContext {...renderProps} />
</StyleRoot>
</Provider>
);
res.send(`<!doctype html>\n${renderToString(<HTML content={content} store={store} />)}`);
});
}
});
});
/* eslint-disable no-console */
app.listen(process.env.PORT, err => {
if (err) {
console.log('We\'ve got an error.');
console.log(err);
return;
}
console.log(`Listening on port ${process.env.PORT}`);
console.log('-------');
console.log(
`Note that there are no Redux devTools with server-side rendering.
If you need devtools, use 'npm run dev' instead.`
);
});
/* eslint-enable no-console */
|
import React, {Component, PropTypes} from 'react';
import transitions from '../styles/transitions';
import SlideInTransitionGroup from '../internal/SlideIn';
function getStyles(props, context, state) {
const {datePicker} = context.muiTheme;
const {selectedYear} = state;
const styles = {
root: {
backgroundColor: datePicker.selectColor,
borderTopLeftRadius: 2,
borderTopRightRadius: 2,
color: datePicker.textColor,
height: 60,
padding: 20,
},
monthDay: {
display: 'inline-block',
fontSize: 36,
fontWeight: '400',
lineHeight: '36px',
height: props.mode === 'landscape' ? 76 : 38,
opacity: selectedYear ? 0.7 : 1,
transition: transitions.easeOut(),
width: '100%',
},
monthDayTitle: {
cursor: !selectedYear ? 'default' : 'pointer',
},
year: {
margin: 0,
fontSize: 16,
fontWeight: '400',
lineHeight: '16px',
height: 16,
opacity: selectedYear ? 1 : 0.7,
transition: transitions.easeOut(),
marginBottom: 10,
},
yearTitle: {
cursor: (!selectedYear && !props.disableYearSelection) ? 'pointer' : 'default',
},
};
return styles;
}
class DateDisplay extends Component {
static propTypes = {
DateTimeFormat: PropTypes.func.isRequired,
disableYearSelection: PropTypes.bool,
locale: PropTypes.string.isRequired,
mode: PropTypes.oneOf(['portrait', 'landscape']),
monthDaySelected: PropTypes.bool,
onTouchTapMonthDay: PropTypes.func,
onTouchTapYear: PropTypes.func,
selectedDate: PropTypes.object.isRequired,
style: PropTypes.object,
weekCount: PropTypes.number,
};
static defaultProps = {
disableYearSelection: false,
monthDaySelected: true,
weekCount: 4,
};
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
state = {
selectedYear: !this.props.monthDaySelected,
transitionDirection: 'up',
};
componentWillReceiveProps(nextProps) {
if (nextProps.selectedDate !== this.props.selectedDate) {
const direction = nextProps.selectedDate > this.props.selectedDate ? 'up' : 'down';
this.setState({
transitionDirection: direction,
});
}
if (nextProps.monthDaySelected !== undefined) {
this.setState({
selectedYear: !nextProps.monthDaySelected,
});
}
}
handleTouchTapMonthDay = () => {
if (this.props.onTouchTapMonthDay && this.state.selectedYear) {
this.props.onTouchTapMonthDay();
}
this.setState({selectedYear: false});
};
handleTouchTapYear = () => {
if (this.props.onTouchTapYear && !this.props.disableYearSelection && !this.state.selectedYear) {
this.props.onTouchTapYear();
}
if (!this.props.disableYearSelection) {
this.setState({selectedYear: true});
}
};
render() {
const {
DateTimeFormat,
locale,
selectedDate,
style,
...other,
} = this.props;
const {prepareStyles} = this.context.muiTheme;
const year = selectedDate.getFullYear();
const styles = getStyles(this.props, this.context, this.state);
const dateTimeFormatted = new DateTimeFormat(locale, {
month: 'short',
weekday: 'short',
day: '2-digit',
}).format(selectedDate);
return (
<div {...other} style={prepareStyles(Object.assign(styles.root, style))}>
<SlideInTransitionGroup
style={styles.year}
direction={this.state.transitionDirection}
>
<div key={year} style={styles.yearTitle} onTouchTap={this.handleTouchTapYear}>
{year}
</div>
</SlideInTransitionGroup>
<SlideInTransitionGroup
style={styles.monthDay}
direction={this.state.transitionDirection}
>
<div
key={dateTimeFormatted}
style={styles.monthDayTitle}
onTouchTap={this.handleTouchTapMonthDay}
>
{dateTimeFormatted}
</div>
</SlideInTransitionGroup>
</div>
);
}
}
export default DateDisplay;
|
'use strict';
const parser = require('./parser');
const autoParser = require('./auto-parser');
function parse (source, opts) {
if (!opts.syntax) {
opts.syntax = this;
}
return parser(source, opts) || autoParser(source, opts);
}
module.exports = parse;
|
import defaultParams from './params.js'
import { toArray, capitalizeFirstLetter, warn } from './utils.js'
const swalStringParams = ['swal-title', 'swal-html', 'swal-footer']
export const getTemplateParams = (params) => {
const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template
if (!template) {
return {}
}
const templateContent = template.content
showWarningsForElements(templateContent)
const result = Object.assign(
getSwalParams(templateContent),
getSwalButtons(templateContent),
getSwalImage(templateContent),
getSwalIcon(templateContent),
getSwalInput(templateContent),
getSwalStringParams(templateContent, swalStringParams),
)
return result
}
const getSwalParams = (templateContent) => {
const result = {}
toArray(templateContent.querySelectorAll('swal-param')).forEach((param) => {
showWarningsForAttributes(param, ['name', 'value'])
const paramName = param.getAttribute('name')
let value = param.getAttribute('value')
if (typeof defaultParams[paramName] === 'boolean' && value === 'false') {
value = false
}
if (typeof defaultParams[paramName] === 'object') {
value = JSON.parse(value)
}
result[paramName] = value
})
return result
}
const getSwalButtons = (templateContent) => {
const result = {}
toArray(templateContent.querySelectorAll('swal-button')).forEach((button) => {
showWarningsForAttributes(button, ['type', 'color', 'aria-label'])
const type = button.getAttribute('type')
result[`${type}ButtonText`] = button.innerHTML
result[`show${capitalizeFirstLetter(type)}Button`] = true
if (button.hasAttribute('color')) {
result[`${type}ButtonColor`] = button.getAttribute('color')
}
if (button.hasAttribute('aria-label')) {
result[`${type}ButtonAriaLabel`] = button.getAttribute('aria-label')
}
})
return result
}
const getSwalImage = (templateContent) => {
const result = {}
const image = templateContent.querySelector('swal-image')
if (image) {
showWarningsForAttributes(image, ['src', 'width', 'height', 'alt'])
if (image.hasAttribute('src')) {
result.imageUrl = image.getAttribute('src')
}
if (image.hasAttribute('width')) {
result.imageWidth = image.getAttribute('width')
}
if (image.hasAttribute('height')) {
result.imageHeight = image.getAttribute('height')
}
if (image.hasAttribute('alt')) {
result.imageAlt = image.getAttribute('alt')
}
}
return result
}
const getSwalIcon = (templateContent) => {
const result = {}
const icon = templateContent.querySelector('swal-icon')
if (icon) {
showWarningsForAttributes(icon, ['type', 'color'])
if (icon.hasAttribute('type')) {
result.icon = icon.getAttribute('type')
}
if (icon.hasAttribute('color')) {
result.iconColor = icon.getAttribute('color')
}
result.iconHtml = icon.innerHTML
}
return result
}
const getSwalInput = (templateContent) => {
const result = {}
const input = templateContent.querySelector('swal-input')
if (input) {
showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value'])
result.input = input.getAttribute('type') || 'text'
if (input.hasAttribute('label')) {
result.inputLabel = input.getAttribute('label')
}
if (input.hasAttribute('placeholder')) {
result.inputPlaceholder = input.getAttribute('placeholder')
}
if (input.hasAttribute('value')) {
result.inputValue = input.getAttribute('value')
}
}
const inputOptions = templateContent.querySelectorAll('swal-input-option')
if (inputOptions.length) {
result.inputOptions = {}
toArray(inputOptions).forEach((option) => {
showWarningsForAttributes(option, ['value'])
const optionValue = option.getAttribute('value')
const optionName = option.innerHTML
result.inputOptions[optionValue] = optionName
})
}
return result
}
const getSwalStringParams = (templateContent, paramNames) => {
const result = {}
for (const i in paramNames) {
const paramName = paramNames[i]
const tag = templateContent.querySelector(paramName)
if (tag) {
showWarningsForAttributes(tag, [])
result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim()
}
}
return result
}
const showWarningsForElements = (template) => {
const allowedElements = swalStringParams.concat([
'swal-param',
'swal-button',
'swal-image',
'swal-icon',
'swal-input',
'swal-input-option',
])
toArray(template.children).forEach((el) => {
const tagName = el.tagName.toLowerCase()
if (allowedElements.indexOf(tagName) === -1) {
warn(`Unrecognized element <${tagName}>`)
}
})
}
const showWarningsForAttributes = (el, allowedAttributes) => {
toArray(el.attributes).forEach((attribute) => {
if (allowedAttributes.indexOf(attribute.name) === -1) {
warn([
`Unrecognized attribute "${attribute.name}" on <${el.tagName.toLowerCase()}>.`,
`${allowedAttributes.length ? `Allowed attributes are: ${allowedAttributes.join(', ')}` : 'To set the value, use HTML within the element.'}`
])
}
})
}
|
'use strict';
/*
* Feed Route
* path: /feed
*/
let express = require('express');
let router = express.Router();
router.get('/', (req, res, next) => {
console.log('entered feed')
res.send('OK')
})
module.exports = router;
|
export default function while(test, block){
var result = undefined;
while((test()|0) === 0x01){
result = block();
}
return result;
} |
version https://git-lfs.github.com/spec/v1
oid sha256:d3f3ad116b975b3f9ed3caf871eb872fd812854a11fa9e6755cf84cd28b5b9b7
size 11448
|
// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.
// Partial config
module.exports = {
// My plugins
plugins: [
// Theme
'hypermaterial-vibrancy',
// Adds system resource usage info at the bottom
'hyperline',
// Adds tab icons
'hyper-tab-icons'
],
};
|
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import './style.css'
import Container from 'gComponents/utility/container/Container.js'
import FirstSubscriptionContainer from 'gComponents/subscriptions/FirstSubscription/container.js'
import Plan from 'lib/config/plan.js'
import { connect } from 'react-redux';
function mapStateToProps(state) {
return {
me: state.me
}
}
@connect(mapStateToProps)
export default class FirstSubscriptionPage extends Component {
displayName: 'FirstSubscriptionPage'
static propTypes = {
planName: PropTypes.oneOf(['lite', 'premium'])
}
render() {
const {me, planName} = this.props
const planId = {lite: 'personal_lite', premium: 'personal_premium'}[planName]
const plan = Plan.find(planId)
return (
<Container>
<div className='FirstSubscriptionPage'>
<div className='row'>
<div className='col-sm-5 col-sm-offset-1'>
<div className='FirstSubscriptionPage-header'>
<h1> {`The ${this.props.planName.capitalizeFirstLetter()} Plan`}</h1>
<h2> <span className='number'> {plan.number()} </span> private models </h2>
</div>
<div className='FirstSubscriptionPage-sidebar'>
<h3> Privacy </h3>
<p> We will not sell or distribute your contact information. Read our Privacy Policy.</p>
<h3> Cancellations </h3>
<p> You cancel at any time with our payment portal. </p>
</div>
</div>
<div className='col-sm-5'>
{!!me.id && planId &&
<FirstSubscriptionContainer planId={planId}/>
}
{!!me.id && !planId &&
<h2> Plan Invalid </h2>
}
{!me.id &&
<h2> Log in to view this page </h2>
}
</div>
</div>
</div>
</Container>
)
}
}
|
(function(window) {
"use strict";
var
prev = window.oops || null,
curr = function(){};
propertyExpand( curr, {
core: {
expand: propertyExpand
},
typing: {
isObject: isObject,
isCallable: function( value ){
return (typeof value === 'function');
},
isArray: Array.isArray,
isString: function( value ) { return (typeof value === 'string'); }
},
prev: function(){ return prev; },
async: function( callback, latency ){
latency = latency || 0;
if ( !oops.typing.isCallable( callback ) ) return;
setTimeout( callback, latency );
},
chain: function(){
var
queue = {},
portal = function( cate ) {
if ( !queue[ cate ] ) return;
var args = Array.prototype.slice.call( arguments, 1 );
queue[ cate ].forEach(function( item ){
var trigger = function(){
item.cb.apply( null, args );
};
if ( !item.async )
{
trigger();
return;
}
oops.async(trigger);
});
return portal;
};
oops.core.expand( portal, {
on: function( cate, responder, async ){
if ( !oops.typing.isCallable(responder) ) return;
async = (arguments.length > 2) ? !!async : true;
queue[ cate ] = queue[ cate ] || [];
queue[ cate ].push({
cb: responder,
async: async
});
return portal;
},
fire: portal
});
return portal;
},
util: {}
}, false );
propertyExpand( curr.util, {
loadScript: (function(){
var
head = document.getElementsByTagName( 'head' )[0];
return function( src, attributes, success, error ) {
if ( oops.typing.isCallable(attributes) )
{
error = success;
success = attributes;
attributes = undefined;
}
attributes = attributes || {};
var
script = document.createElement('script');
if ( oops.typing.isCallable( success ) )
script.onload = success;
if ( oops.typing.isCallable( error ) )
script.onerror = error;
script.type = "application/javascript";
script.src = src;
oops.util.each( attributes, function( val, key ){
script.setAttribute( key, val );
});
head.appendChild( script );
};
})(),
each: function( object, callable ){
if ( !oops.typing.isCallable( callable ) ) return;
if ( !oops.typing.isObject( object ) ) return;
if ( oops.typing.isArray( object ) )
{
object.forEach(callable);
return;
}
for ( var idx in object )
{
if ( !object.hasOwnProperty( idx ) ) continue;
callable( object[idx], idx );
}
},
limitExec: function( func, times ) {
if ( !oops.typing.isCallable( func ) )
return doNothing;
times = times || 1;
return function(){
if ( times <= 0 ) return;
times--;
func.apply( null, arguments );
};
}
}, true);
window.oops = curr;
(function(){
// INFO: PuhState Extension
var originalPushState = history.pushState || function(){};
curr.core.expand( window.history, {
pushState: function(state) {
originalPushState.apply( history, arguments );
oops.async(function(){
var event = document.createEvent( 'Event' );
event.state = state;
event.initEvent( 'pushstate', true, true );
window.dispatchEvent( event );
if ( curr.typing.isCallable( window.onpushstate ) )
window.onpushstate( event );
});
},
popState: function() {
history.back();
}
});
})();
// INFO: Supportive functions
function propertyExpand( target, source, overwrite ){
overwrite = overwrite || false;
if ( !isObject( source ) || !isObject( target ) ) return;
for ( var prop in source )
{
if ( !source.hasOwnProperty( prop ) ) continue;
if ( !overwrite && target.hasOwnProperty( prop ) ) continue;
target[ prop ] = source[ prop ];
}
}
function isObject( value, strict ) {
var result = ( typeof value === 'object' );
strict = strict || false;
result = result || ( strict ? false : (typeof value === 'function'));
result = result && ( strict ? !Array.isArray(value) : true );
return !!( value && result );
}
function doNothing(){}
})(window);
|
app.controller("teamPanelCtrl", function($scope,$rootScope,user,$firebaseArray,$window) {
/*initialzation and checking*/
var courses = firebase.database().ref("courses");
$scope.courseFB=$firebaseArray(courses);
var team = firebase.database().ref("Team");
$scope.teamFB=$firebaseArray(team);
var userAccount = firebase.database().ref("UserAccount");
$scope.userAccount = $firebaseArray(userAccount);
$scope.existedTeam=[];
$scope.existedTeamData=[];
$scope.ckey="";
$scope.studentList=[];
//team filter variables
$scope.query = {}
$scope.searchBy = '$'
$scope.orderProp="name";
$scope.recommendStudentList =[];
$scope.doRedirect=function(href)
{
$window.location.href=href;
}
//recommend students
//user should be 1 to many in list
$scope.recommendList = function(user,list)
{
//cant generate recommendList
if(typeof(user.tags)=="undefined" || list.length==0)
{
return false;
}
var recommendList = [];
for(var i=0;i<list.length;i++)
{
list[i].data.sameTags = [];
}
console.log(list);
//compare the tags, save the same tags to sameTags to list array
for(var i=0;i<user.tags.length;i++)
{
for(var j=0;j<list.length;j++)
{
if(typeof(list[j].data.tags)!="undefined")
{
for(var k=0;k<list[j].data.tags.length;k++)
{
if(user.tags[i]==list[j].data.tags[k])
{
list[j].data.sameTags.push(list[j].data.tags[k]);
}
}
}
}
}
for(var i=0;i<list.length;i++)
{
if(list[i].data.sameTags.length>0)
{
var temp = [];
temp.keys=list[i].key;
temp.data=list[i].data;
recommendList.push(temp);
}
}
recommendList.sort(function(a, b) {
return parseFloat(b.data.sameTags.length) - parseFloat(a.data.sameTags.length);
});
$scope.recommendStudentList = recommendList;
console.log(recommendList);
}
//load team forming detail in teacher panel
$scope.loadTeamFormingDetail=function()
{
$scope.loadStudentList($scope.ckey);
firebase.database().ref("courses/"+$scope.ckey).once('value', function(data) {
var tmp=[];
var courseData=data.val();
var teamList = courseData.team;
if(typeof(teamList)!="undefined")
{
for(var i=0;i<teamList.length;i++)
{
firebase.database().ref("Team/"+teamList[i]).once('value', function(data) {
var teamData=data.val();
var tempTeam=[];
tempTeam.name=teamData.name;
tempTeam.key=teamList[i];
tempTeam.member=teamData.member;
$scope.existedTeam.push(tempTeam);
})
}
}
console.log($scope.existedTeam);
});
}
$scope.updateRole=function()
{
$scope.email=user.email;
$scope.role=user.role;
$scope.userName=user.userName;
$scope.key=user.key;
$scope.course=user.course;
$scope.team=user.team;
}
$scope.currCourse={};
$scope.teamMember=[];
$scope.waitingList=[];
$scope.inviteList=[];
$scope.studentList=[];
$scope.ckey;
$scope.tkey;
$scope.tLeaderID;
$scope.tName;
$scope.tDesc;
$scope.tTag=[];
$scope.defaultTags=[];
$scope.addedTags;
$scope.isEdit=false;
$rootScope.$on("updateRole", function(){
$scope.updateRole();
$scope.loadcoursesInfo();
$scope.initTagList();
});
$scope.editTeamInfo=function(){
var name=$('#editTeamName').val();
var desc=$('#editTeamDesc').val();
if(name.trim()==""||desc.trim()=="")
{
alert("some data is missed");
return;
}
else
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data) {
var teamData=data.val();
teamData.name=name;
teamData.description=desc;
if(typeof($scope.addedTags)!="undefined"&&$scope.addedTags.length>0)
{
teamData.tags=$scope.addedTags;
}
else
{
if(teamData.hasOwnProperty('tags'))
{
delete teamData["tags"];
}
}
firebase.database().ref("Team/"+$scope.tkey).set(teamData).then(function(){
$scope.renderTeamInfo(0);
$scope.isEdit=!$scope.isEdit;
$scope.$apply();
});
});
}
}
$scope.editInfoForm=function()
{
$scope.isEdit=!$scope.isEdit;
setTimeout(function(){
$scope.initAutoComplete();
}, 1000);
}
$scope.cancelEditInfoForm=function()
{
$scope.isEdit=!$scope.isEdit;
$scope.addedTags=$scope.tTag;
}
$scope.deleteInviteRequest=function(email,uKey)
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data) {
var teamData=data.val();
$scope.removeElementFromArrayByValue(email,teamData.invite);
firebase.database().ref("Team/"+$scope.tkey).set(teamData).then(function(){
userAccount.orderByChild("email").equalTo(email).on("child_added", function(data)
{
var userData=data.val();
$scope.removeElementFromArrayByValue(email,userData.invite[$scope.ckey]);
if(jQuery.isEmptyObject(userData.invite))
{
delete userData["invite"];
}
firebase.database().ref("UserAccount/"+uKey).set(userData).then(function(){
$scope.loadInviteList(teamData);
});
});
});
});
}
$scope.addInviteRequest=function(userData,key)
{
if(typeof(userData.invite)=="undefined")
{
userData.invite=[];
}
if(typeof(userData.invite[$scope.ckey])=="undefined")
{
userData.invite[$scope.ckey]=[];
}
userData.invite[$scope.ckey].push($scope.tkey);
firebase.database().ref("UserAccount/"+key).set(userData).then(function(){
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data) {
var teamData=data.val();
if(typeof(teamData.invite)=="undefined")
{
teamData.invite=[];
}
teamData.invite.push(userData.email);
firebase.database().ref("Team/"+$scope.tkey).set(teamData).then(function(){
//handle ...
$scope.loadInviteList(teamData);
$.fancybox.close();
});
});
});
}
$scope.inviteValidCheck=function(key,email)
{
if($scope.email==email)
{
alert("you can't invite yourself");
return;
}
else
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data) {
var teamData=data.val();
if(typeof(teamData.invite)!="undefined"&&teamData.invite.indexOf(email)>-1)
{
alert("you have invited this student alredy");
}
else
{
firebase.database().ref("UserAccount/"+key).once('value', function(data) {
var userData=data.val();
if(typeof(userData.team)!="undefined")
{
if(userData.team.hasOwnProperty($scope.ckey))
{
alert("this student has a team already");
return;
}
else
{
$scope.addInviteRequest(userData,key);
}
}
else
{
$scope.addInviteRequest(userData,key)
}
});
}
});
}
}
$scope.inviteHandler=function(operation,key,email)//0 is invite,1 is delete invite
{
if(operation==0)
{
$scope.inviteValidCheck(key,email);
}
else
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data) {
var teamData=data.val();
if(typeof(teamData.invite)!="undefined")
{
if(teamData.invite.indexOf(email)>-1)
{
$scope.deleteInviteRequest(email,key);
}
else
{
alert("that student not in the invite list");
}
}
else
{
alert("that student not in the invite list");
}
});
}
}
/*quit team flow*/
/*
1.delete the user email for the team array in Team table
2.delete the entry with the course id (key) in team object in UserAccount table
*/
$scope.quitTeam=function()
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data)
{
var newTeamData=data.val();
$scope.removeElementFromArrayByValue($scope.email,newTeamData.member);
firebase.database().ref("Team/"+$scope.tkey).set(newTeamData);
});
userAccount.orderByChild("email").equalTo($scope.email).on("child_added", function(data)
{
var newUserData=data.val();
delete newUserData.team[$scope.ckey];
if(jQuery.isEmptyObject(newUserData.team))
{
delete newUserData["team"];
}
firebase.database().ref("UserAccount/"+data.getKey()).set(newUserData).then(function()
{
$window.location.href="index.html";
});
});
}
//delete all the data that related to the team waiting request
$scope.deleteAllWaitingList=function(teamData)
{
if(typeof(teamData.request)!="undefined")
{
for(i=0;i<teamData.request.length;i++)
{
var email=teamData.request[i];
userAccount.orderByChild("email").equalTo(email).on("child_added", function(data)
{
$scope.requestHandler(1,1,email,data.getKey());
});
}
}
}
$scope.deleteAllTeamMember=function(teamData)
{
for(i=0;i<teamData.member.length;i++)
{
var email=teamData.member[i];
userAccount.orderByChild("email").equalTo(email).on("child_added", function(data)
{
$scope.deleteMember(1,email,data.getKey());
});
}
}
$scope.deleteAllInviteList=function(teamData)
{
if(typeof(teamData.invite)!="undefined")
{
for(i=0;i<teamData.invite.length;i++)
{
var email=teamData.invite[i];
userAccount.orderByChild("email").equalTo(email).on("child_added", function(data)
{
$scope.deleteInviteRequest(data.val().email,data.getKey());
});
}
}
}
$scope.deleteTeam=function()
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data) {
var teamData=data.val();
$.when($scope.deleteAllTeamMember(teamData)).done(function(){
$.when($scope.deleteAllWaitingList(teamData)).done(function()
{
$.when($scope.deleteAllInviteList(teamData)).done(function()
{
firebase.database().ref("Team/"+$scope.tkey).remove();
firebase.database().ref("courses/"+$scope.ckey).once('value', function(data)
{
var newCourseData=data.val();
$scope.removeElementFromArrayByValue($scope.tkey,newCourseData.team);
firebase.database().ref("courses/"+$scope.ckey).set(newCourseData).then(function(){
$window.location.href="index.html";
});
});
});
});
});
});
}
$scope.deleteMember=function(operation,email,memberID)
{
if(operation==0&&$scope.tLeaderID==email)
{
alert("you can't delete the owner")
}
else
{
if(operation==0)
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data)
{
var newTeamData=data.val();
$scope.removeElementFromArrayByValue(email,newTeamData.member);
firebase.database().ref("Team/"+$scope.tkey).set(newTeamData);
});
}
firebase.database().ref("UserAccount/"+memberID).once('value', function(data)
{
var newUserData=data.val();
delete newUserData.team[$scope.ckey];
if(jQuery.isEmptyObject(newUserData.team))
{
delete newUserData["team"];
}
firebase.database().ref("UserAccount/"+memberID).set(newUserData);
});
if(operation==0)
{
$scope.removeUserList($scope.teamMember,memberID);
}
}
}
$scope.requestHandler=function(operation,type,email,waitingID)
{
firebase.database().ref("Team/"+$scope.tkey).once('value', function(data)
{
var newTeamData=data.val();
if(operation==0)//0 is accept
{
var maxSize=$scope.currCourse.max;
var memberNumber=newTeamData.member.length;
if(memberNumber+1<=maxSize)
{
$scope.removeElementFromArrayByValue(email,newTeamData.request);
newTeamData.member.push(email);
firebase.database().ref("Team/"+$scope.tkey).set(newTeamData).then(function()
{
firebase.database().ref("UserAccount/"+waitingID).once('value', function(data)
{
var newUserData=data.val();
$scope.removeElementFromArrayByValue($scope.tkey,newUserData.request[$scope.ckey]);
if(typeof(newUserData.team)=="undefined")
{
newUserData.team={};
}
newUserData.team[$scope.ckey]=$scope.tkey
$.when($scope.deleteAllUserInvitedRequest(newUserData)).done(function()
{
$.when($scope.deleteAllJoiningRequest(newUserData)).done(function()
{
if(typeof(newUserData.request)!="undefined"&&typeof(newUserData.request[$scope.ckey])!="undefined")
{
delete newUserData.request[$scope.ckey];
if(jQuery.isEmptyObject(newUserData.request))
{
delete newUserData["request"];
}
}
if(typeof(newUserData.invite)!="undefined"&&typeof(newUserData.invite[$scope.ckey])!="undefined")
{
delete newUserData.invite[$scope.ckey];
if(jQuery.isEmptyObject(newUserData.invite))
{
delete newUserData["invite"];
}
}
firebase.database().ref("UserAccount/"+waitingID).set(newUserData).then(function()
{
$scope.renderTeamInfo(1);
});
});
});
});
});
}
else
{
alert("exceed max limitation");
}
}
else
{
$scope.removeElementFromArrayByValue(email,newTeamData.request);
firebase.database().ref("Team/"+$scope.tkey).set(newTeamData);
firebase.database().ref("UserAccount/"+waitingID).once('value', function(data)
{
var newUserData=data.val();
$scope.removeElementFromArrayByValue($scope.tkey,newUserData.request[$scope.ckey]);
firebase.database().ref("UserAccount/"+waitingID).set(newUserData);
});
if(type==0)
{
$scope.updateUserList(newTeamData);
}
}
});
}
$scope.deleteAllJoiningRequest=function(userData)
{
if(typeof(userData.request!="undefined")&&typeof(userData.request[$scope.ckey])!="undefined")
{
for(i=0;i<userData.request[$scope.ckey].length;i++)
{
firebase.database().ref("Team/"+userData.request[$scope.ckey][i]).once('value', function(data) {
var teamData=data.val();
$scope.removeElementFromArrayByValue(userData.email,teamData.request);
firebase.database().ref("Team/"+data.getKey()).set(teamData);
});
}
}
}
$scope.deleteAllUserInvitedRequest=function(userData)
{
if(typeof(userData.invite)!="undefined"&&typeof(userData.invite[$scope.ckey])!="undefined")
{
for(i=0;i<userData.invite[$scope.ckey].length;i++)
{
firebase.database().ref("Team/"+userData.invite[$scope.ckey][i]).once('value', function(data) {
var teamData=data.val();
$scope.removeElementFromArrayByValue(userData.email,teamData.invite);
firebase.database().ref("Team/"+data.getKey()).set(teamData);
});
}
}
}
$scope.updateUserList=function(newTeamData)
{
var tmpMember=[];
var tmpWaiting=[];
for(i=0;i<newTeamData.member.length;i++)
{
$scope.userObjectArrayPush(newTeamData.member[i],tmpMember);
}
$scope.teamMember=tmpMember;
if(typeof(newTeamData.request.length)!="undefined")
{
for(i=0;i<newTeamData.request.length;i++)
{
$scope.userObjectArrayPush(newTeamData.request[i],tmpWaiting);
}
}
$scope.waitingList=tmpWaiting;
}
$scope.removeUserList=function(array,userID)
{
for(i=0;i<array.length;i++)
{
if(array[i].key==userID)
{
array.splice(i, 1);
break;
}
}
}
$scope.removeElementFromArrayByValue=function(value,array)
{
array.splice(array.indexOf(value), 1);
}
$scope.userObjectArrayPush=function(email,array)
{
userAccount.orderByChild("email").equalTo(email).on("child_added", function(data)
{
var tmp=data.val();
if(typeof(tmp.icon)=="undefined")
{
tmp.icon="image/usericon.png";
}
array.push({"key":data.getKey(),"data":tmp});
});
}
$scope.loadStudentList=function(key)
{
firebase.database().ref("courses/"+key).once('value', function(data) {
var tmp=[];
var courseData=data.val();
for(i=0;i<courseData.student.length;i++)
{
$scope.userObjectArrayPush(courseData.student[i],tmp);
}
$scope.studentList=tmp;
});
}
$scope.loadInviteList=function(teamData)
{
var tmp=[];
if(typeof(teamData.invite)!="undefined")
{
for(i=0;i<teamData.invite.length;i++)
{
$scope.userObjectArrayPush(teamData.invite[i],tmp);
}
}
$scope.inviteList=tmp;
$scope.$apply();
}
$scope.loadWaitingList=function(teamData)
{
var tmp=[];
if(typeof(teamData.request)!="undefined")
{
for(i=0;i<teamData.request.length;i++)
{
$scope.userObjectArrayPush(teamData.request[i],tmp);
}
}
$scope.waitingList=tmp;
$scope.$apply();
}
$scope.loadTeamMember=function(teamData)
{
var tmp=[];
for(i=0;i<teamData.member.length;i++)
{
$scope.userObjectArrayPush(teamData.member[i],tmp);
}
$scope.teamMember=tmp;
$scope.$apply();
}
$scope.renderTeamInfo=function(flag)
{
firebase.database().ref("Team/"+$scope.team[$scope.ckey]).once('value', function(data) {
var teamData=data.val();
if(flag==0)
{
$scope.tkey=data.getKey();
$scope.tLeaderID=data.val().leaderID;
$scope.tName=data.val().name;
$scope.tDesc=data.val().description;
if(typeof(data.val().tags)!="undefined")
{
$scope.addedTags=[];
$scope.addedTags=data.val().tags;
$scope.tTag=[];
$scope.tTag=data.val().tags;
}
if($scope.tLeaderID==$scope.email)
{
$scope.isOwner=true;
}
else
{
$scope.isOwner=false;
}
}
$scope.loadTeamMember(teamData);
$scope.loadWaitingList(teamData);
$scope.loadInviteList(teamData);
//$scope.loadStudentList($scope.ckey);
});
}
$scope.roleAccessCheck=function()
{
if($scope.role=="0")
{
if(typeof($scope.team)=="undefined"||!$scope.team.hasOwnProperty($scope.currCourse.key) )
{
console.log("no team in this course");
$window.location.href="index.html";
}
$scope.renderTeamInfo(0);
}
else
{
if($scope.currCourse.owner!=$scope.email)
{
console.log("you are teacher but not the course owner");
$window.location.href="index.html";
}
}
}
$scope.inviteForm=function()
{
$scope.loadStudentList($scope.ckey);
if($scope.tTag.length>0 && $scope.studentList.length>0)
{
var team =[];
var tempStudentList=$scope.studentList;
team.tags=$scope.tTag;
console.log(team);
$scope.recommendList(team,tempStudentList);
}
$.fancybox.open("#studentList");
}
$scope.gup=function( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
$scope.pathStringCheck=function()
{
var invalidSet=['.','#','$','[',']'];
for(i=0;i<invalidSet.length;i++)
{
if($scope.ckey.indexOf(invalidSet[i])>-1)
{
return true;
}
}
return false;
}
$scope.loadcoursesInfo=function()
{
$scope.ckey=$scope.gup('c', window.location.href);
if($scope.ckey==null||$scope.ckey==""||$scope.pathStringCheck())
{
$scope.doRedirect("index.html");
}
else
{
firebase.database().ref("courses/"+$scope.ckey).once('value', function(data) {
if(data.val()==null)
{
console.log("invalid input of course id");
$scope.doRedirect("index.html");
}
else
{
$scope.currCourse=data.val();
$scope.currCourse.key=data.getKey();
$scope.courseInfo.image=$scope.currCourse.image;
$scope.roleAccessCheck();
}
});
}
}
$scope.removeTag=function(tag)
{
$scope.removeElementFromArrayByValue(tag,$scope.addedTags);
}
$scope.addTag=function()
{
var tmpTag=$('#autoComplete').val();
if(typeof(tmpTag)=="undefined"||tmpTag.trim()=="")
{
alert("you should enter a valid tag");
return;
}
if(typeof($scope.addedTags)=="undefined"||$scope.addedTags.length==0)
{
$scope.addedTags=[];
$scope.addedTags.push(tmpTag);
}
else
{
if($scope.addedTags.indexOf(tmpTag.trim())>-1)
{
alert("you have adde this tag already");
return;
}
else
{
$scope.addedTags.push(tmpTag);
}
}
$('#autoComplete').val('');
//$('#autoComplete').focus();
}
$scope.initTagList=function ()
{
$.getJSON('tags.json', function(data) {
$scope.defaultTags=data.data;
for(var i=0;i<$scope.defaultTags.length;i++)
{
$scope.defaultTags[i]=$scope.defaultTags[i]+" ";
}
});
}
$scope.initAutoComplete=function ()
{
$("#autoComplete").autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter($scope.defaultTags, request.term);
for(var i=0;i<results.length;i++)
{
results[i]=results[i].trim();
}
response(results.slice(0, 10));
}
}).focus(function() {
$(this).autocomplete("search"," ");
$(this).autocomplete( "option", "minLength", 0 );
});;
}
/**********************************teacher update info********************************************************/
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result)
};
reader.onerror = function(e) {
callback(null);
};
reader.readAsDataURL(this);
};
$scope.fileNameChanged = function (ele)
{
var file = ele.files[0];
if(file.type.length>0&&file.type.substr(0,5)=="image")
{
file.convertToBase64(function(base64){
$scope.courseInfo.image=base64;
$scope.fileName=file.name;
$('#base64PicURL').attr('src',base64);
$('#base64Name').html(file.name);
$('#removeURL').show();
$('#profilePic').val('');
});
}
else
{
alert("invliad file format");
// $scope.removeImg();
$('#profilePic').val('');
}
}
$scope.courseInfo=
{
title:"",
image:"",
owner:"",
message:"",
max:"",
min:"",
date:""
}
$scope.fileName;
$scope.removeImg=function(){
$('#removeURL').hide();
$('#base64Name').html('');
$scope.courseInfo.image='image/grey.png';
$scope.fileName='';
$('#base64PicURL').attr('src','');
}
$scope.validInput=function ()
{
$scope.courseInfo.title=$scope.currCourse.title;
$scope.courseInfo.message=$scope.currCourse.message;
$scope.courseInfo.max=$scope.currCourse.max;
$scope.courseInfo.min=$scope.currCourse.min;
$scope.courseInfo.date=$scope.currCourse.date;
$scope.courseInfo.random=$scope.currCourse.random;
$scope.courseInfo.owner=$scope.email;
if(typeof($scope.courseInfo.image)=="undefined"||$scope.courseInfo.image=="")
{
$scope.courseInfo.image='image/grey.png';
}
if(typeof($scope.courseInfo.title)=="undefined"||typeof($scope.courseInfo.message)=="undefined")
{
//alert("some missing data");
return false;
}
return true;
}
$scope.editCourse = function() {
if($scope.validInput())
{
firebase.database().ref("courses/"+$scope.ckey).once('value', function(data)
{
if(typeof(data.val().team)!="undefined")
{
$scope.courseInfo.team=data.val().team;
}
firebase.database().ref("courses/"+$scope.ckey).set($scope.courseInfo).then(function(){
$window.location.href="index.html";
});
});
}else
{
alert("some missing data");
}
}
});
|
import { assert, expect } from 'meteor/practicalmeteor:chai';
import { populateULRModuleFixture,
dePopulateModuleFixture } from '../../../../test-fixtures/modules';
import { populateULRFixture,
dePopulatePlannerFixture } from '../../../../test-fixtures/planner';
import { populateULRModuleFulfilment,
dePopulateModuleFulfilmentFixture } from '../../../../test-fixtures/moduleFulfilment';
import { populateGraduationRequirementsFixture,
dePopulateGraduationRequirementsFixture } from '../../../../test-fixtures/graduationRequirements';
import { getGradRequirementModules,
getGradRequirementMCs } from '../../../../database-controller/graduation-requirement/methods';
import { getAllSemestersInPlanner } from '../../../../student-logic-controller/crud-controller/semester/methods';
import { findULRRequirementModules } from './methods';
describe('grad-checker-ULR', function() {
let plannerIDs = [];
let graduationIDs = [];
let fulfilmentIDs = [];
beforeEach(function (done) {
this.timeout(10000);
populateULRModuleFixture();
plannerIDs = populateULRFixture();
graduationIDs = populateGraduationRequirementsFixture();
fulfilmentIDs = populateULRModuleFulfilment();
done();
});
afterEach(function (done) {
dePopulateModuleFixture();
dePopulatePlannerFixture(plannerIDs);
dePopulateGraduationRequirementsFixture(graduationIDs);
dePopulateModuleFulfilmentFixture(fulfilmentIDs);
done();
});
it ('checks if find modules correct boolean values', function() {
const modules = ['Human Cultures', 'Asking Questions', 'Quantitative Reasoning',
'Singapore Studies', 'Thinking and Expression'];
const studentInfoObject = {
studentAcademicCohort: 'AY 2016/2017',
studentSemesters: getAllSemestersInPlanner(plannerIDs[0]),
studentExemptedModules: {},
studentWaivedModules: {},
moduleChecked: {}
}
const requirementName = 'University Level Requirement';
const ULRModules = getGradRequirementModules(graduationIDs)[requirementName];
const requiredMCs = getGradRequirementMCs(graduationIDs)[requirementName];
const markedULRModulesAndMCs = findULRRequirementModules(studentInfoObject, ULRModules, requiredMCs);
assert.isTrue(markedULRModulesAndMCs.markedULRModules[modules[0]], 'GEH1001 fulfiled');
assert.isTrue(markedULRModulesAndMCs.markedULRModules[modules[1]], 'GEQ1917 fulfiled');
assert.isTrue(markedULRModulesAndMCs.markedULRModules[modules[2]], 'GER1000 fulfiled');
assert.isTrue(markedULRModulesAndMCs.markedULRModules[modules[3]], 'GES1002 fulfiled');
assert.isTrue(markedULRModulesAndMCs.markedULRModules[modules[4]], 'GET1006 fulfiled');
assert.isTrue(markedULRModulesAndMCs.moduleChecked['GEH1001'], 'GEH1001 checked');
assert.isTrue(markedULRModulesAndMCs.moduleChecked['GEQ1917'], 'GEQ1917 checked');
assert.isTrue(markedULRModulesAndMCs.moduleChecked['GER1000'], 'GER1000 checked');
assert.isTrue(markedULRModulesAndMCs.moduleChecked['GES1002'], 'GES1002 checked');
assert.isTrue(markedULRModulesAndMCs.moduleChecked['GET1006'], 'GET1006 checked');
assert.equal(markedULRModulesAndMCs.numberOfULRMarkedTrue, 5);
assert.equal(markedULRModulesAndMCs.totalModuleMCs, 20);
})
});
|
/**
* response.js
* ----------------------------
* The response wraps the standard http
* response object and allows the framework
* to add additional behaviour & data.
*/
// Dependencies
var http = require("http");
var js2xmlparser = require("js2xmlparser");
/**
* Ctor
**/
function Response(res) {
this.prototype = http.ServerResponse.prototype;
this.response = res;
// default response format
this.response.statusCode = 200;
this.format = 'json';
}
/**
* Change/Set the response status code
**/
Response.prototype.statusCode = function(code) {
this.response.statusCode = code;
return this;
}
/**
* Parse the message into the appropriate format
* set the necessary headers and send the message
* in the require representation.
*/
Response.prototype.send = function(message) {
var body = message;
var status_code;
var contentType;
if(this.response.statusCode === undefined) this.response.statusCode = 500;
if(body === null) return this.send({ status_code: 500, description: 'someting went wrong and your request cannot be handled'});
if(message.status_code != null) this.response.statusCode = message.status_code;
/**
* Set the appropriate headers and parse the body into the correct format
**/
switch (typeof body) {
case 'string':
contentType = "text/html";
break;
case 'object':
if(this.format === 'json') {
contentType = "application/json";
body = JSON.stringify(body, null, 2);
break;
} else if(this.format === 'xml') {
console.log("generating xml");
contentType = "application/xml";
body = js2xmlparser(body.type, JSON.stringify(body));
break;
}
default:
// if an unsupported type return an error
contentType = "application/json";
this.response.statusCode = 500;
body = JSON.stringify({ status_code: 500, description: 'unsupported content-type'}, null, 2);
}
// compile the response and send
this.response.writeHead(this.response.statusCode, {"Content-Type": contentType });
this.response.write(body);
this.response.end();
}
module.exports = Response; |
var mysql = require('mysql');
var pool = mysql.createPool(require('../config/database').connection);
var results = {
getAllByUserId: function(req, res, next) {
pool.query('CALL results_find_by_user_id(?)', [req.user.userId], function(error, rows) {
if (error) {
res.status(500).send({ message: error.message });
return next(error);
};
if (!rows[0].length) {
res.status(204).send();
} else {
res.send(rows[0]);
}
});
},
getAll: function(req, res, next) {
pool.query('CALL get_all_results()', [], function(error, rows) {
if (error) {
res.status(500).send({ message: error.message });
return next(error);
};
if (!rows[0].length) {
res.status(204).send();
} else {
res.send(rows[0]);
}
});
}
};
module.exports = results; |
var extend = require('deap/shallow'),
async = require('async'),
redis = require('redis');
var Store = module.exports = function(config) {
var self = this;
this.type = 'redis';
//apply defaults
config = extend(
{
host: 'localhost',
port: 6379,
options: {},
log: empty,
error: empty
},
config||{}
);
this.log = config.log;
this.error = config.error;
this.client = redis.createClient(
config.port,
config.host,
config.options
);
if(config.database !== undefined) {
this.client.on('ready', function() {
self.client.select(config.database, function(err) {
if(err) self.error('Error selecting db: ' + err.toString);
});
});
}
this.client.on('error', function(err) {
self.error('Redis cache error: ' + err.toString());
});
};
Store.prototype = {
get: function(key, done) {
var self = this;
this.client.get(key, function(err, data) {
if(err) return done(err);
// cache miss
if(data === null) {
self.log('cache miss: ' + key);
return done(null, undefined);
}
// cache hit
self.log('cache hit: ' + key);
done(null, JSON.parse(data));
});
return this;
},
set: function(key, value, tags, ttl, done) {
this.log('cache set: ' +key);
var client = this.client,
self = this;
var multi = client.multi()
.set(key, JSON.stringify(value));
if(ttl !== undefined) multi.expire(key, ttl);
if(tags) {
tags.forEach(function(tag) {
multi.sadd(tag, key);
});
}
multi.exec(function(err, replies) {
done(err, replies[0] === 'OK');
});
return this;
},
mget: function(keys, done) {
this.client.mget(keys, function(err, values) {
if(err) return done(err);
done(null, values && values.map(function(value) {
// cache miss
if(value === null) return undefined;
// cache hit
return JSON.parse(value);
}));
});
return this;
},
mset: function(hash, tagMap, ttl, done) {
var self = this,
setValues = [];
if(hash === undefined) return done(null);
// convert key/value hash into key,value,key2,value2... array that redis expects
Object.keys(hash).forEach(function(key) {
setValues.push(key, JSON.stringify(hash[key]));
});
var multi = this.client.multi()
.mset(setValues);
// add expire commands for each key
if(ttl !== undefined) {
Object.keys(hash).forEach(function(key) {
multi.expire(key, ttl);
});
}
if(tagMap) {
Object.keys(tagMap).forEach(function(key) {
tagMap[key].forEach(function(tag) {
multi.sadd(tag, key);
});
});
}
multi.exec(function(err, replies) {
done(err, replies[0] === 'OK');
});
return this;
},
expire: function(key, ttl, done) {
function handleResponse(err, result) {
done(err, !err && result ===1);
}
var result = (ttl === undefined)
? this.client.del(key, handleResponse)
: this.client.expire(key, ttl, handleResponse);
return this;
},
getKeys: function(tags, done) {
this.client.sunion(tags, done);
}
};
function setTags(key, tags, done) {
var self = this;
async.parallel(
tags.map(function(tag) {
return function(cb) {self.client.sadd(tag, key, cb); };
}),
done
);
}
function empty() {}
|
describe('Executing `connectEvents` with a hash as the first argument', function() {
var
ch,
label1 = 'one',
label2 = 'two',
cbOne,
cbTwo,
p,
ret,
eventsHash;
beforeEach(function() {
cbOne = function() {};
cbTwo = function() {};
ch = Wreqr.radio.channel('test');
eventsHash = {};
eventsHash[label2] = cbOne;
eventsHash[label1] = cbTwo;
ret = ch.connectEvents( eventsHash );
p = ch.vent._events || {};
});
afterEach(function() {
ch.reset();
});
it( 'should attach the listeners to the Channel', function() {
expect(_.keys(p)).toEqual( [label2, label1] );
});
it( 'should return the Channel', function() {
expect( ret ).toBe( ch );
});
});
|
(function () {
'use strict';
angular
.module('bulma.toast', []);
})(); |
//= require affix
//= require alert
//= require button
//= require carousel
//= require collapse
//= require dropdown
//= require tab
//= require transition
//= require scrollspy
//= require modal
//= require tooltip
//= require popover
|
'use strict'
var BaseModel = require('model-toolkit').BaseModel;
module.exports = class Bank extends BaseModel {
constructor(source) {
super('bank', '1.0.0');
this.code = '';
this.name = '';
this.description = '';
this.copy(source);
}
} |
var Big = require('big.js'),
db = require('../db')
module.exports = function updateItem(store, data, cb) {
store.getTable(data.TableName, function(err, table) {
if (err) return cb(err)
var key = db.validateKey(data.Key, table), itemDb = store.getItemDb(data.TableName)
if (key instanceof Error) return cb(key)
if (data.AttributeUpdates) {
for (var i = 0; i < table.KeySchema.length; i++) {
var keyName = table.KeySchema[i].AttributeName
if (data.AttributeUpdates[keyName])
return cb(db.validationError('One or more parameter values were invalid: ' +
'Cannot update attribute ' + keyName + '. This attribute is part of the key'))
}
}
itemDb.lock(key, function(release) {
cb = release(cb)
itemDb.get(key, function(err, oldItem) {
if (err && err.name != 'NotFoundError') return cb(err)
if ((err = db.checkConditional(data, oldItem)) != null) return cb(err)
var attr, type, returnObj = {}, item = data.Key
if (oldItem) {
for (attr in oldItem) {
item[attr] = oldItem[attr]
}
if (data.ReturnValues == 'ALL_OLD') {
returnObj.Attributes = oldItem
} else if (data.ReturnValues == 'UPDATED_OLD') {
returnObj.Attributes = {}
for (attr in data.AttributeUpdates) {
if (oldItem[attr] != null) {
returnObj.Attributes[attr] = oldItem[attr]
}
}
}
}
for (attr in data.AttributeUpdates) {
if (data.AttributeUpdates[attr].Action == 'PUT' || data.AttributeUpdates[attr].Action == null) {
item[attr] = data.AttributeUpdates[attr].Value
} else if (data.AttributeUpdates[attr].Action == 'ADD') {
if (data.AttributeUpdates[attr].Value.N) {
if (item[attr] && !item[attr].N)
return cb(db.validationError('Type mismatch for attribute to update'))
if (!item[attr]) item[attr] = {N: '0'}
item[attr].N = new Big(item[attr].N).plus(data.AttributeUpdates[attr].Value.N).toFixed()
} else {
type = Object.keys(data.AttributeUpdates[attr].Value)[0]
if (item[attr] && !item[attr][type])
return cb(db.validationError('Type mismatch for attribute to update'))
if (!item[attr]) item[attr] = {}
if (!item[attr][type]) item[attr][type] = []
item[attr][type] = item[attr][type].concat(data.AttributeUpdates[attr].Value[type].filter(function(a) { // eslint-disable-line no-loop-func
return !~item[attr][type].indexOf(a)
}))
}
} else if (data.AttributeUpdates[attr].Action == 'DELETE') {
if (data.AttributeUpdates[attr].Value) {
type = Object.keys(data.AttributeUpdates[attr].Value)[0]
if (item[attr] && !item[attr][type])
return cb(db.validationError('Type mismatch for attribute to update'))
if (item[attr] && item[attr][type]) {
item[attr][type] = item[attr][type].filter(function(val) { // eslint-disable-line no-loop-func
return !~data.AttributeUpdates[attr].Value[type].indexOf(val)
})
if (!item[attr][type].length) delete item[attr]
}
} else {
delete item[attr]
}
}
}
if (db.itemSize(item) > db.MAX_SIZE)
return cb(db.validationError('Item size to update has exceeded the maximum allowed size'))
if (data.ReturnValues == 'ALL_NEW') {
returnObj.Attributes = item
} else if (data.ReturnValues == 'UPDATED_NEW') {
returnObj.Attributes = {}
for (attr in data.AttributeUpdates) {
if (item[attr]) returnObj.Attributes[attr] = item[attr]
}
}
if (~['TOTAL', 'INDEXES'].indexOf(data.ReturnConsumedCapacity))
returnObj.ConsumedCapacity = {
CapacityUnits: Math.max(db.capacityUnits(oldItem), db.capacityUnits(item)),
TableName: data.TableName,
Table: data.ReturnConsumedCapacity == 'INDEXES' ?
{CapacityUnits: Math.max(db.capacityUnits(oldItem), db.capacityUnits(item))} : undefined,
}
itemDb.put(key, item, function(err) {
if (err) return cb(err)
cb(null, returnObj)
})
})
})
})
}
|
App.NodesEditorController = App.EditorController.extend({
editorDialogBody : 'dialog/nodeEditorBody',
editorDialogTabs : 'dialog/nodeEditorTabs',
title : Ember.I18n.translate("nodeDetails"),
generalTabActive : function() {
return this.get('tabsConfig')[0].isActive;
}.property('tabsConfig.@each.isActive'),
advancedTabActive : function(key, value) {
return this.get('tabsConfig')[1].isActive;
}.property('tabsConfig.@each.isActive'),
tabsConfig : [
Ember.Object.create({
id :'general',
isActive : true,
title : Ember.I18n.translate("general_camel_case")
}),
Ember.Object.create({
id :'advanced',
isActive : false,
title : Ember.I18n.translate("advanced_camel_case")
})
],
propertyChanged : function(controller, key) {
this.set('changedProperties.' + key, this.get(key));
}.observes('data.name', 'data.node'),
saveChanges : function() {
var changedProperties = this.get('changedProperties');
//TODO: add changedProperties to the url and send request
this.trigger('close');
}
}); |
import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './DoctrineOriginalWordmark.svg'
/** DoctrineOriginalWordmark */
function DoctrineOriginalWordmark({ width, height, className }) {
return (
<SVGDeviconInline
className={'DoctrineOriginalWordmark' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
DoctrineOriginalWordmark.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default DoctrineOriginalWordmark
|
// Compiled by ClojureScript 0.0-2322
goog.provide('clojure.browser.net');
goog.require('cljs.core');
goog.require('goog.Uri');
goog.require('goog.net.xpc.CrossPageChannel');
goog.require('goog.net.xpc.CfgFields');
goog.require('goog.net.EventType');
goog.require('goog.net.XhrIo');
goog.require('goog.json');
goog.require('goog.json');
goog.require('clojure.browser.event');
goog.require('clojure.browser.event');
clojure.browser.net._STAR_timeout_STAR_ = (10000);
clojure.browser.net.event_types = cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,(function (p__10774){var vec__10775 = p__10774;var k = cljs.core.nth.call(null,vec__10775,(0),null);var v = cljs.core.nth.call(null,vec__10775,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
}),cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.net.EventType))));
clojure.browser.net.IConnection = (function (){var obj10777 = {};return obj10777;
})();
clojure.browser.net.connect = (function() {
var connect = null;
var connect__1 = (function (this$){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$1;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$1(this$);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$);
}
});
var connect__2 = (function (this$,opt1){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$2;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$2(this$,opt1);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$,opt1);
}
});
var connect__3 = (function (this$,opt1,opt2){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$3;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$3(this$,opt1,opt2);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$,opt1,opt2);
}
});
var connect__4 = (function (this$,opt1,opt2,opt3){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$4;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$4(this$,opt1,opt2,opt3);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$,opt1,opt2,opt3);
}
});
connect = function(this$,opt1,opt2,opt3){
switch(arguments.length){
case 1:
return connect__1.call(this,this$);
case 2:
return connect__2.call(this,this$,opt1);
case 3:
return connect__3.call(this,this$,opt1,opt2);
case 4:
return connect__4.call(this,this$,opt1,opt2,opt3);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
connect.cljs$core$IFn$_invoke$arity$1 = connect__1;
connect.cljs$core$IFn$_invoke$arity$2 = connect__2;
connect.cljs$core$IFn$_invoke$arity$3 = connect__3;
connect.cljs$core$IFn$_invoke$arity$4 = connect__4;
return connect;
})()
;
clojure.browser.net.transmit = (function() {
var transmit = null;
var transmit__2 = (function (this$,opt){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$2;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$2(this$,opt);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt);
}
});
var transmit__3 = (function (this$,opt,opt2){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$3;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$3(this$,opt,opt2);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2);
}
});
var transmit__4 = (function (this$,opt,opt2,opt3){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$4;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$4(this$,opt,opt2,opt3);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2,opt3);
}
});
var transmit__5 = (function (this$,opt,opt2,opt3,opt4){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$5;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$5(this$,opt,opt2,opt3,opt4);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2,opt3,opt4);
}
});
var transmit__6 = (function (this$,opt,opt2,opt3,opt4,opt5){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$6;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$6(this$,opt,opt2,opt3,opt4,opt5);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2,opt3,opt4,opt5);
}
});
transmit = function(this$,opt,opt2,opt3,opt4,opt5){
switch(arguments.length){
case 2:
return transmit__2.call(this,this$,opt);
case 3:
return transmit__3.call(this,this$,opt,opt2);
case 4:
return transmit__4.call(this,this$,opt,opt2,opt3);
case 5:
return transmit__5.call(this,this$,opt,opt2,opt3,opt4);
case 6:
return transmit__6.call(this,this$,opt,opt2,opt3,opt4,opt5);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
transmit.cljs$core$IFn$_invoke$arity$2 = transmit__2;
transmit.cljs$core$IFn$_invoke$arity$3 = transmit__3;
transmit.cljs$core$IFn$_invoke$arity$4 = transmit__4;
transmit.cljs$core$IFn$_invoke$arity$5 = transmit__5;
transmit.cljs$core$IFn$_invoke$arity$6 = transmit__6;
return transmit;
})()
;
clojure.browser.net.close = (function close(this$){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$IConnection$close$arity$1;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$close$arity$1(this$);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.close[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.close["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.close",this$);
}
}
})().call(null,this$);
}
});
goog.net.XhrIo.prototype.clojure$browser$event$IEventType$ = true;
goog.net.XhrIo.prototype.clojure$browser$event$IEventType$event_types$arity$1 = (function (this$){var this$__$1 = this;return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,((function (this$__$1){
return (function (p__10778){var vec__10779 = p__10778;var k = cljs.core.nth.call(null,vec__10779,(0),null);var v = cljs.core.nth.call(null,vec__10779,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
});})(this$__$1))
,cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.net.EventType))));
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$ = true;
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$2 = (function (this$,uri){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,"GET",null,null,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$3 = (function (this$,uri,method){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,method,null,null,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$4 = (function (this$,uri,method,content){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,method,content,null,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$5 = (function (this$,uri,method,content,headers){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,method,content,headers,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$6 = (function (this$,uri,method,content,headers,timeout){var this$__$1 = this;this$__$1.setTimeoutInterval(timeout);
return this$__$1.send(uri,method,content,headers);
});
clojure.browser.net.xpc_config_fields = cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,(function (p__10780){var vec__10781 = p__10780;var k = cljs.core.nth.call(null,vec__10781,(0),null);var v = cljs.core.nth.call(null,vec__10781,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
}),cljs.core.js__GT_clj.call(null,goog.net.xpc.CfgFields)));
/**
* Returns an XhrIo connection
*/
clojure.browser.net.xhr_connection = (function xhr_connection(){return (new goog.net.XhrIo());
});
clojure.browser.net.ICrossPageChannel = (function (){var obj10783 = {};return obj10783;
})();
clojure.browser.net.register_service = (function() {
var register_service = null;
var register_service__3 = (function (this$,service_name,fn){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$3;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$3(this$,service_name,fn);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.register_service[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.register_service["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"ICrossPageChannel.register-service",this$);
}
}
})().call(null,this$,service_name,fn);
}
});
var register_service__4 = (function (this$,service_name,fn,encode_json_QMARK_){if((function (){var and__5785__auto__ = this$;if(and__5785__auto__)
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$4;
} else
{return and__5785__auto__;
}
})())
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$4(this$,service_name,fn,encode_json_QMARK_);
} else
{var x__6713__auto__ = (((this$ == null))?null:this$);return (function (){var or__5801__auto__ = (clojure.browser.net.register_service[goog.typeOf(x__6713__auto__)]);if(or__5801__auto__)
{return or__5801__auto__;
} else
{var or__5801__auto____$1 = (clojure.browser.net.register_service["_"]);if(or__5801__auto____$1)
{return or__5801__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"ICrossPageChannel.register-service",this$);
}
}
})().call(null,this$,service_name,fn,encode_json_QMARK_);
}
});
register_service = function(this$,service_name,fn,encode_json_QMARK_){
switch(arguments.length){
case 3:
return register_service__3.call(this,this$,service_name,fn);
case 4:
return register_service__4.call(this,this$,service_name,fn,encode_json_QMARK_);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
register_service.cljs$core$IFn$_invoke$arity$3 = register_service__3;
register_service.cljs$core$IFn$_invoke$arity$4 = register_service__4;
return register_service;
})()
;
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$ = true;
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$1 = (function (this$){var this$__$1 = this;return clojure.browser.net.connect.call(null,this$__$1,null);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$2 = (function (this$,on_connect_fn){var this$__$1 = this;return this$__$1.connect(on_connect_fn);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$3 = (function (this$,on_connect_fn,config_iframe_fn){var this$__$1 = this;return clojure.browser.net.connect.call(null,this$__$1,on_connect_fn,config_iframe_fn,document.body);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$4 = (function (this$,on_connect_fn,config_iframe_fn,iframe_parent){var this$__$1 = this;this$__$1.createPeerIframe(iframe_parent,config_iframe_fn);
return this$__$1.connect(on_connect_fn);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$transmit$arity$3 = (function (this$,service_name,payload){var this$__$1 = this;return this$__$1.send(cljs.core.name.call(null,service_name),payload);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$close$arity$1 = (function (this$){var this$__$1 = this;return this$__$1.close();
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$ICrossPageChannel$ = true;
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$ICrossPageChannel$register_service$arity$3 = (function (this$,service_name,fn){var this$__$1 = this;return clojure.browser.net.register_service.call(null,this$__$1,service_name,fn,false);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$ICrossPageChannel$register_service$arity$4 = (function (this$,service_name,fn,encode_json_QMARK_){var this$__$1 = this;return this$__$1.registerService(cljs.core.name.call(null,service_name),fn,encode_json_QMARK_);
});
/**
* When passed with a config hash-map, returns a parent
* CrossPageChannel object. Keys in the config hash map are downcased
* versions of the goog.net.xpc.CfgFields enum keys,
* e.g. goog.net.xpc.CfgFields.PEER_URI becomes :peer_uri in the config
* hash.
*
* When passed with no args, creates a child CrossPageChannel object,
* and the config is automatically taken from the URL param 'xpc', as
* per the CrossPageChannel API.
*/
clojure.browser.net.xpc_connection = (function() {
var xpc_connection = null;
var xpc_connection__0 = (function (){var temp__4126__auto__ = (new goog.Uri(window.location.href)).getParameterValue("xpc");if(cljs.core.truth_(temp__4126__auto__))
{var config = temp__4126__auto__;return (new goog.net.xpc.CrossPageChannel(goog.json.parse(config)));
} else
{return null;
}
});
var xpc_connection__1 = (function (config){return (new goog.net.xpc.CrossPageChannel(cljs.core.reduce.call(null,(function (sum,p__10789){var vec__10790 = p__10789;var k = cljs.core.nth.call(null,vec__10790,(0),null);var v = cljs.core.nth.call(null,vec__10790,(1),null);var temp__4124__auto__ = cljs.core.get.call(null,clojure.browser.net.xpc_config_fields,k);if(cljs.core.truth_(temp__4124__auto__))
{var field = temp__4124__auto__;var G__10791 = sum;(G__10791[field] = v);
return G__10791;
} else
{return sum;
}
}),(function (){var obj10793 = {};return obj10793;
})(),config)));
});
xpc_connection = function(config){
switch(arguments.length){
case 0:
return xpc_connection__0.call(this);
case 1:
return xpc_connection__1.call(this,config);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
xpc_connection.cljs$core$IFn$_invoke$arity$0 = xpc_connection__0;
xpc_connection.cljs$core$IFn$_invoke$arity$1 = xpc_connection__1;
return xpc_connection;
})()
;
|
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import Component from './button'
const mapDispatchToProps = (dispatch, { name, href, type, onClick }) => {
return {
onClick: (e) => {
if (onClick) onClick()
if (!href && type !== 'submit') e.preventDefault()
e.stopPropagation()
dispatch({ type: `BTN_CLICKED_${name}` })
},
}
}
const ConnectedComponent = connect(undefined, mapDispatchToProps)(Component)
ConnectedComponent.propTypes = {
name: PropTypes.string.isRequired,
}
export default ConnectedComponent
|
//=require modernizr-base
tests['cssgradients'] = function() {
/**
* For CSS Gradients syntax, please see:
* webkit.org/blog/175/introducing-css-gradients/
* developer.mozilla.org/en/CSS/-moz-linear-gradient
* developer.mozilla.org/en/CSS/-moz-radial-gradient
* dev.w3.org/csswg/css3-images/#gradients-
*/
var str1 = 'background-image:',
str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
str3 = 'linear-gradient(left top,#9f9, white);';
setCss(
// legacy webkit syntax (FIXME: remove when syntax not in use anymore)
(str1 + '-webkit- '.split(' ').join(str2 + str1) +
// standard syntax // trailing 'background-image:'
prefixes.join(str3 + str1)).slice(0, -str1.length)
);
return contains(mStyle.backgroundImage, 'gradient');
};
|
module.exports = function({{from.column}}, {{to.column}}, request, response) {
var filter = '{{from.column}} = ' + {{from.column}} + ' AND {{to.column}} = ' + {{to.column}};
if({{from.column}} === 0) {
filter = '{{to.column}} = ' + {{to.column}};
} else if({{to.column}} === 0) {
filter = '{{from.column}} = ' + {{from.column}};
}
this.database().removeRows('{{name}}', filter, function(error) {
//if there are errors
if(error) {
//trigger an error
this.trigger('{{name}}-remove-error', error, request, response);
return;
}
//trigger that we are good
this.trigger('{{name}}-remove-success', request, response);
}.bind(this));
}; |
'use strict';
module.exports = function (done) {
$.router.get('/api/login_user', async function (req, res, next) {
res.apiSuccess({user: req.session.user, token: req.session.logout_token});
});
$.router.post('/api/login', async function (req, res, next) {
if (!req.body.password) return next(new Error('missing password'));
// 频率限制
const key = `login:${req.body.name}:${$.utils.date('Ymd')}`;
{
const limit = 5;
const ok = await $.limiter.incr(key, limit);
if (!ok) throw new Error('out of limit');
}
const user = await $.method('user.get').call(req.body);
if (!user) return next(new Error('user does not exists'));
if (!$.utils.validatePassword(req.body.password, user.password)) {
return next(new Error('incorrect password'));
}
req.session.user = user;
req.session.logout_token = $.utils.randomString(20);
if (req.session.github_user) {
await $.method('user.update').call({
_id: user._id,
githubUsername: req.session.github_user.username,
});
delete req.session.github_user;
}
await $.limiter.reset(key);
res.apiSuccess({token: req.session.logout_token});
});
$.router.get('/api/logout', async function (req, res, next) {
if (req.session.logout_token && req.query.token !== req.session.logout_token) {
return next(new Error('invalid token'));
}
delete req.session.user;
delete req.session.logout_token;
res.apiSuccess({});
});
$.router.post('/api/logout', async function (req, res, next) {
delete req.session.user;
delete req.session.logout_token;
res.apiSuccess({});
});
$.router.post('/api/signup', async function (req, res, next) {
// 频率限制
{
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const key = `signup:${ip}:${$.utils.date('Ymd')}`;
const limit = 2;
const ok = await $.limiter.incr(key, limit);
if (!ok) throw new Error('out of limit');
}
const user = await $.method('user.add').call(req.body);
$.method('mail.sendTemplate').call({
to: user.email,
subject: '欢迎',
template: 'welcome',
data: user,
}, err => {
if (err) console.error(err);
});
res.apiSuccess({user: user});
});
done();
};
|
const DrawCard = require('../../drawcard.js');
class FrozenSolid extends DrawCard {
setupCardAbilities(ability) {
this.attachmentRestriction(card => card.getType() === 'location' && !card.isLimited() && card.getPrintedCost() <= 3);
this.whileAttached({
effect: ability.effects.blankExcludingTraits
});
}
}
FrozenSolid.code = '03021';
module.exports = FrozenSolid;
|
// function rippleDuoshuo(){
$(".ds-post-button").attr("ripple","0");
// } |
var request = require('request')
, cheerio = require('cheerio')
, fs = require('fs')
, querystring = require('querystring')
, util = require('util');
var linkSel = 'h3.r a'
, descSel = 'div.s'
, itemSel = 'li.g'
, nextSel = 'td.b a span'
, noneFoundSel = ".med:contains(No results)";
var URL = 'http://www.google.com/search?hl=en&q=%s&start=%s&sa=N&num=%s&ie=UTF-8&oe=UTF-8';
function google(query, callback) {
igoogle(query, 0, callback);
}
google.resultsPerPage = 10;
var igoogle = function(query, start, callback) {
var opt;
if (typeof query === 'object') {
opt = {
query: querystring.escape(query.query),
proxy: query.proxy
};
} else {
opt = {
query: querystring.escape(query)
};
}
//console.log("google:options")
//console.log(opt);
if (google.resultsPerPage > 100) google.resultsPerPage = 100; //Google won't allow greater than 100 anyway
var newUrl = util.format(URL, opt.query, start, google.resultsPerPage);
var rOpt = {
url: newUrl,
proxy: opt.proxy
};
request(rOpt, function(err, resp, body) {
if ((err === null) && resp.statusCode === 200) {
if (!body || body.indexOf("No results found for ") !== -1){
return callback(null, null, []);
}
var $ = cheerio.load(body)
, links = []
, text = [];
$(itemSel).each(function(i, elem) {
var linkElem = $(elem).find(linkSel)
, descElem = $(elem).find(descSel)
, item = {title: $(linkElem).text(), link: null, description: null, href: null}
, qsObj = querystring.parse($(linkElem).attr('href'));
if (qsObj['/url?q']) {
item.link = qsObj['/url?q'];
item.href = item.link;
}
else if (!!(Object.keys(qsObj))[0]) {
item.href = (Object.keys(qsObj))[0];
}
$(descElem).find('div').remove();
item.description = $(descElem).text();
if (!!item.href){
if (item.href.substring(0,4) === "http"){
links.push(item);
}
}
});
var nextFunc = null;
if ($(nextSel).last().text() === 'Next'){
nextFunc = function() {
igoogle(opt.query, start + google.resultsPerPage, callback);
};
}
callback(null, nextFunc, links);
} else {
e = new Error();
if (!!resp) { e.status = resp.statusCode; }
else if (!!err) { e = err; }
callback(e, null, null);
//callback(new Error('Error on response (' + resp.statusCode + '):' + err +" : " + body), null, null);
}
});
};
module.exports = google;
|
var CONFIG;
var Q = require('q');
var fs = require('fs');
var crypto = require('crypto');
var paths = require('./routePaths');
var cachedHashes = $H({});
var path = require('path');
exports.Mangler = new Class({
initialize : function()
{
this.urls = $H({});
this.hashes = $H({});
if (!CONFIG) CONFIG = require('./config').CONFIG;
},
start : function()
{
if (!CONFIG.builderCache)
{
this.urls = $H({});
this.hashes = $H({});
}
},
md5Hash : function(data)
{
var md5sum = crypto.createHash('md5');
md5sum.update(data);
return md5sum.digest('hex');
},
hashUrl : function(url)
{
url = url.split('?')[0];
var deferred = Q.defer();
var filename = paths.urlPathToFilePath(url);
var modifiedDate = Date.now();
if (cachedHashes[url] != undefined && CONFIG.builderCache)
{
this.hashes.set(url, cachedHashes[url]);
return Q(this.hashes.get(url));
}
fs.stat(filename, function(err, stat)
{
if (err)
{
deferred.resolve(null);
}
else
{
modifiedDate = new Date(stat.mtime).getTime()
var hash = modifiedDate.toString().pad(13, '0', 'left');
this.hashes.set(url, hash);
cachedHashes[url] = hash;
deferred.resolve(this.hashes.get(url));
}
}.bind(this));
return deferred.promise;
},
hashUrls : function(urls)
{
var promises = [];
urls.each(function(url)
{
promises.push(this.hashUrl(url));
}, this);
return Q.all(promises);
},
mangleUrls : function(urls)
{
return this.hashUrls(urls);
},
mangle : function(name)
{
if (name === '') return '';
if (name.indexOf(':') !== -1) return name;
var prefix = CONFIG.manglePrefix?CONFIG.manglePrefix:'';
var hash = this.hashes.get(name);
var url = '';
var filename = path.basename(name);
var parts = filename.split('.');
var ext = parts.pop();
if (hash)
{
parts.push('v' + hash);
}
parts.push(ext);
filename = parts.join('.');
if (name.indexOf(prefix) != 0) url += prefix + name;
else url = name;
parts = url.split('/');
parts.pop();
parts.push(filename);
url = parts.join('/');
return url;
},
demangle : function(name)
{
var prefix = CONFIG.manglePrefix?CONFIG.manglePrefix:'';
if (prefix != '')
{
if (name.indexOf(prefix) == 0)
name = name.substring(prefix.length);
}
name = name.replace(/\.v[0-9]{13}\./, '.');
return name;
},
});
|
'use strict';
// Jobs controller
angular.module('jobs').controller('JobsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Jobs', '$anchorScroll',
function($scope, $stateParams, $location, Authentication, Jobs, $anchorScroll ) {
$scope.authentication = Authentication;
// Create new Job
$scope.create = function() {
// Create new Job object
var job = new Jobs ({
name: this.name,
responsibilities: this.responsibilities,
description: this.description,
qualifications: this.qualifications
});
// Redirect after save
job.$save(function(response) {
$location.path('jobs/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
// Clear form fields
this.name = '';
this.responsibilities = '';
this.description = '';
this.qualifications = '';
};
// Remove existing Job
$scope.remove = function( job ) {
if ( job ) { job.$remove();
for (var i in $scope.jobs ) {
if ($scope.jobs [i] === job ) {
$scope.jobs.splice(i, 1);
}
}
} else {
$scope.job.$remove(function() {
$location.path('jobs');
});
}
};
// Update existing Job
$scope.update = function() {
var job = $scope.job ;
job.$update(function() {
$location.path('jobs/' + job._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Jobs
$scope.find = function() {
$scope.jobs = Jobs.query();
};
// Find existing Job
$scope.findOne = function() {
$scope.job = Jobs.get({
jobId: $stateParams.jobId
});
};
$scope.scrollToJob = function(id) {
$location.hash(id);
$anchorScroll();
};
}
]);
|
import { Indicator, IndicatorInput } from '../indicator/indicator';
export class VolumeProfileInput extends IndicatorInput {
}
export class VolumeProfileOutput {
}
export function priceFallsBetweenBarRange(low, high, low1, high1) {
return (low <= low1 && high >= low1) || (low1 <= low && high1 >= low);
}
export class VolumeProfile extends Indicator {
constructor(input) {
super(input);
var highs = input.high;
var lows = input.low;
var closes = input.close;
var opens = input.open;
var volumes = input.volume;
var bars = input.noOfBars;
if (!((lows.length === highs.length) && (highs.length === closes.length) && (highs.length === volumes.length))) {
throw ('Inputs(low,high, close, volumes) not of equal size');
}
this.result = [];
var max = Math.max(...highs, ...lows, ...closes, ...opens);
var min = Math.min(...highs, ...lows, ...closes, ...opens);
var barRange = (max - min) / bars;
var lastEnd = min;
for (let i = 0; i < bars; i++) {
let rangeStart = lastEnd;
let rangeEnd = rangeStart + barRange;
lastEnd = rangeEnd;
let bullishVolume = 0;
let bearishVolume = 0;
let totalVolume = 0;
for (let priceBar = 0; priceBar < highs.length; priceBar++) {
let priceBarStart = lows[priceBar];
let priceBarEnd = highs[priceBar];
let priceBarOpen = opens[priceBar];
let priceBarClose = closes[priceBar];
let priceBarVolume = volumes[priceBar];
if (priceFallsBetweenBarRange(rangeStart, rangeEnd, priceBarStart, priceBarEnd)) {
totalVolume = totalVolume + priceBarVolume;
if (priceBarOpen > priceBarClose) {
bearishVolume = bearishVolume + priceBarVolume;
}
else {
bullishVolume = bullishVolume + priceBarVolume;
}
}
}
this.result.push({
rangeStart, rangeEnd, bullishVolume, bearishVolume, totalVolume
});
}
}
;
nextValue(price) {
throw ('Next value not supported for volume profile');
}
;
}
VolumeProfile.calculate = volumeprofile;
export function volumeprofile(input) {
Indicator.reverseInputs(input);
var result = new VolumeProfile(input).result;
if (input.reversedInput) {
result.reverse();
}
Indicator.reverseInputs(input);
return result;
}
;
|
// Find an element in a sorted array of integers.
// Array may contain duplicate elements.
// Find the first occurence of the element.
// Author: Tanvir Aslam Mohammed
const binSearchDups = (arr, target) => {
if (!arr || arr.length === 0 || typeof target !== "number") return -1;
const len = arr.length;
let start = 0,
end = len - 1;
while (start <= end) {
let mid = start + Math.floor((end - start) / 2);
if (
arr[mid] > target ||
(arr[mid] === target && mid > 0 && arr[mid - 1] === target)
) {
end = mid - 1;
} else if (arr[mid] < target) {
start = mid + 1;
} else return mid;
}
return -1;
};
|
const $ = require('jquery');
const QUnit = require('qunit').QUnit;
const templr = require('./../../src/templr-browser');
QUnit.module('templr');
QUnit.test('appendTo - remote source', function (assert) {
const done = assert.async();
const src = '/tpl/appendTo.html';
const param = {
items: [
{name: 'item1', show: true},
{name: 'item2', show: false},
{name: 'item3', show: true},
],
};
$.ajax({
url: src,
success: (response) => {
const rendered = templr.render(response, param);
$(rendered).appendTo($('#template-appendTo'));
const li = $('#template-appendTo > ul:first > li');
assert.strictEqual(li.eq(0).text(), 'item1', 'li.eq(0).text() is "item1"');
assert.strictEqual(li.eq(1).text(), 'item3', 'li.eq(1).text() is "item3"');
done();
},
});
});
QUnit.test('insertBefore - remote source', function (assert) {
const done = assert.async();
const src = '/tpl/insertBefore.html';
const param = {
foo: {
bar: {
key1: 'value1',
key2: '',
key3: null,
},
},
};
$.ajax({
url: src,
success: (response) => {
const rendered = templr.render(response, param);
$(rendered).insertBefore($('#template-insertBefore-child'));
const div = $('#template-insertBefore > div:first');
const li = div.find('ul:first').find('li');
assert.strictEqual(div.attr('id'), 'template-insertBefore-target');
assert.strictEqual(li.eq(0).text(), 'value1', 'li.eq(0).text() is "value1"');
assert.strictEqual(li.eq(1).text(), '', 'li.eq(1).text() is ""');
assert.strictEqual(li.eq(2).text(), 'null', 'li.eq(1).text() is "null"');
assert.strictEqual(li.eq(3).text(), 'undefined', 'li.eq(1).text() is "undefined"');
done();
},
});
});
QUnit.test('appendTo - embedded source - textarea', function (assert) {
const src = '#textarea';
const target = '#template-textarea';
const div = $(target);
const output = templr.render($(src).val(), {
items: [{
title: 'title1',
tags: ['tag1', 'tag2', 'tag3'],
}, {
title: 'title2',
tags: [],
}],
});
$(output).appendTo(target);
assert.strictEqual(div.find('.item').length, 2, 'div.find(\'.item\').length is 2');
assert.strictEqual('title1', $('p:first', div.eq(0)).text(), '$(\'p:first\', div.eq(0)).text() is \'title1\'');
assert.strictEqual(3, $('li', div.eq(0)).length, '$(\'li\', div.eq(0)).length is 3');
assert.strictEqual(0, $('ul', div.eq(1)).length, '$(\'ul\', div.eq(1)).length is 0');
});
/**
QUnit.asyncTest("preFetch", function() {
var template = smodules.template(),
stringSrc = "<p>hoge</p>",
remoteSrc = "/javascript-smodules/browser-test/tpl/template.html",
cacheList;
template.preFetch([stringSrc, remoteSrc], function() {
cacheList = template.getTemplateCacheList();
strictEqual(2, cacheList.length, "template cache size is 2.");
strictEqual(true, cacheList.indexOf(stringSrc) >= 0, "template cache has string source.");
strictEqual(true, cacheList.indexOf(remoteSrc) >= 0, "template cache has remote source.");
start();
});
cacheList = template.getTemplateCacheList();
strictEqual(1, cacheList.length, "template cache size is 1.");
strictEqual(true, cacheList.indexOf(stringSrc) >= 0, "template cache has string source.");
});
QUnit.asyncTest("preFetch - bind - get - without callback", function() {
var template = smodules.template(),
src = "/javascript-smodules/browser-test/tpl/template.html",
param = { tag: "div", message: "test" },
output;
template.preFetch(src, function() {
var output = $.trim(template.bind(src, param).get());
strictEqual("<div>test</div>", output, "by using preFetch(), bind() can be used synchronously.");
start();
});
});
**/
|
'use strict';
var angular = require('angular');
var tartan = require('tartan');
var ngTartan = require('../../module');
function makeDraggable(window, canvas, getOffset, repaint) {
var document = window.document;
var drag = null;
var dragTarget = document.releaseCapture ? canvas : window;
function onMouseDown(event) {
event = event || window.event;
if (event.target !== canvas) {
return;
}
if (event.buttons == 1) {
event.preventDefault();
drag = {
x: event.clientX,
y: event.clientY
};
if (event.target && event.target.setCapture) {
// Only IE and FF
event.target.setCapture();
}
}
}
function onMouseMove(event) {
event = event || window.event;
if (drag) {
if (event.buttons != 1) {
drag = null;
if (document.releaseCapture) {
// Only IE and FF
document.releaseCapture();
}
} else {
var offset = getOffset();
offset.x += event.clientX - drag.x;
offset.y += event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
event.preventDefault();
}
repaint();
}
}
function onMouseUp(event) {
event = event || window.event;
if (event.buttons == 1) {
drag = null;
if (document.releaseCapture) {
// Only IE and FF
document.releaseCapture();
}
}
repaint();
}
function onLoseCapture() {
// Only IE and FF
drag = null;
}
dragTarget.addEventListener('mousedown', onMouseDown);
dragTarget.addEventListener('mousemove', onMouseMove);
dragTarget.addEventListener('mouseup', onMouseUp);
canvas.addEventListener('losecapture', onLoseCapture);
return function() {
dragTarget.removeEventListener('mousedown', onMouseDown);
dragTarget.removeEventListener('mousemove', onMouseMove);
dragTarget.removeEventListener('mouseup', onMouseUp);
canvas.removeEventListener('losecapture', onLoseCapture);
};
}
function makeResizable(window, update) {
function onResize() {
if (angular.isFunction(update)) {
update();
}
}
window.addEventListener('resize', onResize);
return function() {
window.removeEventListener('resize', onResize);
};
}
ngTartan.directive('tartanPreviewControl', [
'$window', '$timeout',
function($window, $timeout) {
return {
restrict: 'E',
require: '^^tartan',
template:
'<div class="tartan-preview-control">' +
'<canvas></canvas>' +
'</div>',
replace: true,
scope: {
weave: '=?',
repeat: '=?',
offset: '=?',
metrics: '=?',
interactive: '=?',
zoom: '=?',
renderer: '=?'
},
link: function($scope, element, attr, controller) {
element.css({
position: 'relative'
});
var target = element.find('canvas');
var canvas = target.get(0);
var parent = target.parent().get(0);
var render = null;
var currentState = null;
var offset = {x: 0, y: 0};
$scope.interactiveOptions = {
resize: false,
drag: false
};
function updateOffset() {
$scope.offset = angular.extend({}, offset);
}
var repaint = tartan.utils.repaint(function() {
if (!$scope.interactive) {
offset = {x: 0, y: 0};
}
offset = render(canvas, offset, !!$scope.repeat);
$timeout(updateOffset);
});
function update() {
var options = {
zoom: $scope.zoom,
weave: $scope.weave,
defaultColors: currentState.colors,
transformSyntaxTree: tartan.transform.flatten()
};
var renderer = tartan.render[$scope.renderer];
if (!angular.isFunction(renderer)) {
renderer = tartan.render.canvas;
if (angular.isString($scope.renderer)) {
for (var key in tartan.render) {
if (
angular.isFunction(tartan.render[key]) &&
angular.isString(tartan.render[key].id) &&
(tartan.render[key].id == $scope.renderer)
) {
renderer = tartan.render[key];
break;
}
}
}
}
render = renderer(currentState.sett, options);
$scope.metrics = render.metrics;
updateCanvasSize();
}
function tartanChanged(state) {
currentState = state;
update();
$scope.$applyAsync();
}
controller.on('tartan.changed', tartanChanged);
controller.requestUpdate(tartanChanged);
['weave', 'repeat', 'zoom', 'renderer'].forEach(function(name) {
$scope.$watch(name, function(newValue, oldValue) {
if (newValue !== oldValue) {
update();
}
}, true);
});
$scope.$watch('offset', function(newValue, oldValue) {
if (newValue !== oldValue) {
var temp = angular.extend({}, offset, newValue);
if ((temp.x != offset.x) || (temp.y != offset.y)) {
offset = temp;
repaint();
}
}
}, true);
var disableResize = null;
var disableDrag = null;
$scope.$watch('interactive', function() {
var interactive = angular.extend({
resize: false,
drag: false
}, $scope.interactive === true ? {
resize: true,
drag: true
} : $scope.interactive);
$scope.interactiveOptions = interactive;
var disable = [];
if (interactive.resize) {
if (!disableResize) {
disableResize = makeResizable($window, updateCanvasSize);
}
} else if (disableResize) {
// Disable it later, but NULL it now
disable.push(disableResize);
disableResize = null;
}
if (interactive.drag) {
if (!disableDrag) {
disableDrag = makeDraggable($window, canvas, function() {
return offset;
}, repaint);
}
} else if (disableDrag) {
// Disable it later, but NULL it now
disable.push(disableDrag);
disableDrag = null;
}
repaint();
// Safely run each callback - even if one of them will
// crash - it doesn't matter at the moment
disable.forEach(function(disable) {
disable();
});
});
function updateCanvasSize() {
var w = Math.ceil(parent.offsetWidth);
var h = Math.ceil(parent.offsetHeight);
target.css({
position: 'absolute',
left: '0px',
top: '0px',
width: w + 'px',
height: h + 'px'
});
if (canvas.width != w) {
canvas.width = w;
}
if (canvas.height != h) {
canvas.height = h;
}
repaint();
}
$scope.$on('$destroy', function() {
controller.off('tartan.changed', tartanChanged);
if (disableDrag) {
disableDrag();
}
if (disableResize) {
disableResize();
}
});
}
};
}
]);
|
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"angular": "github:angular/bower-angular@1.5.5",
"angular-ui-router": "github:angular-ui/ui-router@0.2.18",
"babel": "npm:babel-core@5.8.38",
"babel-runtime": "npm:babel-runtime@5.8.38",
"bootstrap": "github:twbs/bootstrap@3.3.6",
"core-js": "npm:core-js@1.2.6",
"css": "github:systemjs/plugin-css@0.1.20",
"jquery": "npm:jquery@2.2.3",
"github:angular-ui/ui-router@0.2.18": {
"angular": "github:angular/bower-angular@1.5.5"
},
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.3.0"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.2"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:twbs/bootstrap@3.3.6": {
"jquery": "github:components/jquery@2.2.1"
},
"npm:assert@1.3.0": {
"util": "npm:util@0.10.3"
},
"npm:babel-runtime@5.8.38": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:core-js@1.2.6": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:process@0.11.2": {
"assert": "github:jspm/nodelibs-assert@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
}
}
});
|
'use strict';
const processors = require('../processors.js');
module.exports = {
help: 'Iterate over the JSON input, returning only objects that match the given Javascript predicate.',
usage: '<predicate>',
minPositionalArguments: 1,
maxPositionalArguments: 1,
outputsObject: true,
needsSandbox: true,
hasWithClauseOpt: true,
handler: whereCommandHandler
};
function whereCommandHandler(runtimeSettings, config, opts)
{
let res = [];
processors.runPredicate(opts._args[0], runtimeSettings, match => {
res.push(match);
return true;
});
return res;
}
|
var test = require("tape")
var path = require("path")
var fs = require("fs")
var readimage = require("readimage")
var writepng = require("../writepng")
function readfile(filename, cb) {
var buf = fs.readFileSync(path.join(__dirname, filename))
readimage(buf, cb)
}
var pngHeader = new Buffer([137, 80, 78, 71])
test("convert", function (t) {
readfile("../examples/doge_jump2.gif", function (err, gif) {
t.notOk(err)
writepng(gif, function (err, png) {
t.notOk(err)
t.equals(png.slice(0, 4).toString(), pngHeader.toString())
t.end()
})
})
})
|
$(document).ready(function() {
var now = new Date();
var today = (now.getMonth() + 1) + '-' + now.getDate();
$('#Brewday').val(today);
});
$(document)
.one('focus.textarea', '.autoExpand', function() {
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.textarea', '.autoExpand', function() {
var minRows = this.getAttribute('data-min-rows') | 7,
rows;
this.rows = minRows;
console.log(this.scrollHeight, this.baseScrollHeight);
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 17);
this.rows = minRows + rows;
});
var BatchVol, BoilRate, coefficient, DHop, EBoil, EstBrewhEff, EstConvWt, EstLauterEff, EstMashEff, ExConv, ExPot, FirstRun, Gabs, GalH, GBill,
Habs, HBill, HChilled, HFirstRun, HMash, HPost, HPre, HSecRun, HStart, HStrike, HTot, KettleID, LossBoil, LossFermTrub, LossGrain, LossHop, LossTot, LossTrub,
MAGDryG, MAGEstConv, MAGFine, MAGMoist, MAGPot, MAGRunRatio, MAGTotWater, MAGVolWater, MAGWtWater, MashAdj, MashSugarWt2, MashThick, MashWaterWt1,
MeasBrewhEff, MeasConv, MeasGabs, MeasLautEff, MeasLautWT, MeasMashEff, MeasMashGrav2, MeasMashPlato, MeasMashSugarWT, MeasMashWortWT, MeasMashWT,
MeasPostSG, MeasPrebGrav2, MeasPrebPlato, MeasPrebSugarWT, MeasPrebWT, MeasSecRunPlato, MeasSecRunSG, MeasSecRunWT,
MSW1, MWT2, Plato1, Plato2, PlatoPost, PlatoPre, PotSize, preradio, radio, RCSTot, RCWT2, RCWtr1, RecW2, RetS1, RetS2, RetSF, RetWat1, RetWat2, RS1, RS2, RW1, SecRun, SG1, SG2, SGPost, SGPre, SGSuccrose,
StrikeAdj, SugarTot, Temp_Coeff, TempGrain, TempMash, TempMashout, TempSparge, TempStrike, TotalPoints, TotalPot, TrueAbs1, TrueAbs2, Units_BoilOff, Units_DHop, Units_EBoil, Units_FirstRun, Units_FTrub_Volume,
Units_Gabs, Units_GallonHeight, Units_GBill, Units_GTemp, Units_Habs, Units_HChilled, Units_HFirstRun, Units_Hop, Units_HPost, Units_HPre, Units_HSecondRun, Units_HStrike, Units_HTot, Units_HVolMash, Units_HVolStart,
Units_KettleVolume, Units_KettleWidth, Units_LossTot, Units_MashoutTemp, Units_MashThickness, Units_MashThickness2, Units_MeasuredGabs, Units_MinSparge, Units_MTemp, Units_MTrub_Volume, Units_Post, Units_Pre,
Units_PreboilVolume, Units_SecondRun, Units_Sparge, Units_STemp, Units_TempStrike, Units_Trub_Volume, Units_VChilled, Units_VolMash, Units_VolStart, Units_VolStrike, Units_VPackaged, Units_WaterTot,
VolChilled, VolMash, VolMinSparge, VolPackaged, VolPost, VolPre, VolSparge, VolSparge2, VolStart, VolStrike, Volume_Coeff, Volumes, WaterTot, Weight_Coeff, Weight_Small_Coeff, YeastPitch, OGDifference, TargetOG;
$(document).ready(function() {
$('#calcForm').delegate('input[type=text]', 'change', function() {
if (validateField(this)) {
updateCalc();
}
}).submit(function(e) {
e.defaultPrevented;
updateCalc();
});
radioSelect(byId('grams'));
$('#GBill').focus();
});
function allFieldsValid() {
var fields = [
'BatchVol',
'GBill',
'HBill',
'DHop',
'BoilTime',
'BoilRate',
'TempGrain',
'TempMash',
'VolSparge',
'PotSize',
'KettleID',
'LossTrub',
'LossFermTrub',
'HChilled',
'VolPackaged',
'Gabs',
'Habs',
'EBoil',
];
for (i = 0; i < fields.length; i++) {
if (!$('#' + fields[i]).val().match(/^d*(.\d+)?/)) {
return false;
}
}
return true;
}
function byId(id) {
return (document.getElementById(id));
}
function radioSelect(elem) {
uarr = elem.getAttribute('data-units').split("|");
Weights_Big = uarr[0];
Units_GBill = Weights_Big;
Volumes = uarr[1];
Units_Sparge = Volumes;
Units_Trub_Volume = Volumes;
Units_FTrub_Volume = Volumes;
Units_MTrub_Volume = Volumes;
Units_LossTot = Volumes;
Units_KettleVolume = Volumes;
Units_PreboilVolume = Volumes;
Units_MinSparge = Volumes;
Units_VolStart = Volumes;
Units_VolStrike = Volumes;
Units_FirstRun = Volumes;
Units_SecondRun = Volumes;
Units_Pre = Volumes;
Units_Post = Volumes;
Units_VChilled = Volumes;
Units_VPackaged = Volumes;
Units_VolMash = Volumes;
Units_WaterTot = Volumes;
Weights_Small = uarr[2];
Units_Hop = Weights_Small;
Units_DHop = Weights_Small;
Temps = uarr[3];
Units_MTemp = Temps;
Units_GTemp = Temps;
Units_STemp = Temps;
Units_MashoutTemp = Temps;
Units_TempStrike = Temps;
Units_BoilOff = uarr[4];
Units_EBoil = Units_BoilOff;
Units_Gabs = uarr[5];
Units_MeasuredGabs = Units_Gabs;
Units_MashThickness = uarr[6];
Units_MashThickness2 = Units_MashThickness;
Units_Habs = uarr[7];
Units_KettleWidth = uarr[8];
Units_HTot = Units_KettleWidth;
Units_GallonHeight = Units_KettleWidth;
Units_HVolStart = Units_KettleWidth;
Units_HStrike = Units_KettleWidth;
Units_HVolMash = Units_KettleWidth;
Units_HFirstRun = Units_KettleWidth;
Units_HSecondRun = Units_KettleWidth;
Units_HPre = Units_KettleWidth;
Units_HPost = Units_KettleWidth;
Units_HChilled = Units_KettleWidth;
radio = elem.id;
updateInputs();
}
function updateInputs() {
BatchVol = parseFloat($('#BatchVol').val());
GBill = parseFloat($('#GBill').val());
MeasMashGrav = parseFloat($('#MeasMashGrav').val());
MeasPrebGrav = parseFloat($('#MeasPrebGrav').val());
MAGEstConv = parseFloat($('#MAGEstConv').val());
LossTunTrub = parseFloat($('#LossTunTrub').val());
HBill = parseFloat($('#HBill').val());
DHop = parseFloat($('#DHop').val());
MeasPrebVolume = parseFloat($('#MeasPrebVolume').val());
TempSparge = parseFloat($('#TempSparge').val());
BoilTime = parseFloat($('#BoilTime').val());
BoilRate = parseFloat($('#BoilRate').val());
TempGrain = parseFloat($('#TempGrain').val());
TempMash = parseFloat($('#TempMash').val());
VolSparge = parseFloat($('#VolSparge').val());
PotSize = parseFloat($('#PotSize').val());
KettleID = parseFloat($('#KettleID').val());
LossTrub = parseFloat($('#LossTrub').val());
Gabs = parseFloat($('#Gabs').val());
Habs = parseFloat($('#Habs').val());
MashAdj = parseFloat($('#MashAdj').val());
StrikeAdj = parseFloat($('#StrikeAdj').val());
LossFermTrub = parseFloat($('#LossFermTrub').val());
MashThickness = parseFloat($('#MashThickness').val());
if (radio == 'imperial') {
if (preradio == 'metric') {
BatchVol = BatchVol * 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate * 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge * 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub * 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub * 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
HBill = HBill * 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop * 0.035274;
DHop = DHop.toFixed(2);
TempSparge = (TempSparge * 1.8) + 32;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain * 1.8) + 32;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness * 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill * 2.20462;
GBill = GBill.toFixed(2);
TempMash = (TempMash * 1.8) + 32;
TempMash = TempMash.toFixed(1);
Gabs = Gabs / 8.3454;
Habs = Habs / 0.133526;
Habs = Habs.toFixed(3);
} else if (preradio == 'grams') {
HBill = HBill * 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop * 0.035274;
DHop = DHop.toFixed(2);
Habs = Habs / 0.035274;
Habs = Habs.toFixed(3);
} else {
HBill = HBill * 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop * 0.035274;
DHop = DHop.toFixed(2);
Habs = Habs / 0.035274;
Habs = Habs.toFixed(3);
}
}
if (radio == 'grams') {
if (preradio == 'metric') {
BatchVol = BatchVol * 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate * 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge * 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub * 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub * 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge * 1.8) + 32;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain * 1.8) + 32;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness * 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill * 2.20462;
GBill = GBill.toFixed(2);
TempMash = (TempMash * 1.8) + 32;
TempMash = TempMash.toFixed(1);
Gabs = Gabs / 8.3454;
Habs = Habs * 0.264172;
Habs = Habs.toFixed(4);
} else if (preradio == 'imperial') {
HBill = HBill / 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop / 0.035274;
DHop = DHop.toFixed(2);
Habs = Habs * 0.035274;
Habs = Habs.toFixed(4);
}
}
if (radio == 'metric') {
if (preradio == 'grams') {
BatchVol = BatchVol / 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate / 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge / 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub / 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub / 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge - 32) / 1.8;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain - 32) / 1.8;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness / 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill / 2.20462;
GBill = GBill.toFixed(2);
HopRatio = HBill / BatchVol;
TempMash = (TempMash - 32) / 1.8;
TempMash = TempMash.toFixed(1);
Gabs = Gabs * 8.3454;
Habs = Habs * 3.78541;
Habs = Habs.toFixed(4);
} else if (preradio == 'imperial') {
BatchVol = BatchVol / 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate / 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge / 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub / 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub / 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge - 32) / 1.8;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain - 32) / 1.8;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness / 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill / 2.20462;
GBill = GBill.toFixed(2);
HopRatio = HBill / BatchVol;
TempMash = (TempMash - 32) / 1.8;
TempMash = TempMash.toFixed(1);
HBill = HBill / 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop / 0.035274;
DHop = DHop.toFixed(2);
Gabs = Gabs * 8.3454;
Habs = Habs * 0.133526;
Habs = Habs.toFixed(4);
} else {
BatchVol = BatchVol / 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate / 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge / 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub / 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub / 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge - 32) / 1.8;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain - 32) / 1.8;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness / 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill / 2.20462;
GBill = GBill.toFixed(2);
HopRatio = HBill / BatchVol;
TempMash = (TempMash - 32) / 1.8;
TempMash = TempMash.toFixed(1);
Gabs = Gabs * 8.3454;
Habs = Habs * 3.78541;
Habs = Habs.toFixed(4);
}
}
byId('BatchVol').value = BatchVol;
byId('GBill').value = GBill;
byId('HBill').value = HBill;
byId('DHop').value = DHop;
byId('BoilRate').value = BoilRate;
byId('TempGrain').value = TempGrain;
byId('TempMash').value = TempMash;
byId('VolSparge').value = VolSparge;
byId('TempSparge').value = TempSparge;
byId('PotSize').value = PotSize;
byId('KettleID').value = KettleID;
byId('LossTrub').value = LossTrub;
byId('LossFermTrub').value = LossFermTrub;
byId('LossTunTrub').value = LossTunTrub;
byId('Gabs').value = Gabs;
byId('Habs').value = Habs;
byId('MashThickness').value = MashThickness;
updateCalc();
}
function updateDisplay() {
byId('Unit_BatchVol').innerHTML = Volumes;
byId('Unit_WaterTot').innerHTML = Units_WaterTot;
byId('Unit_VolStrike').innerHTML = Units_VolStrike;
byId('Unit_VolStart').innerHTML = Units_VolStart;
byId('Unit_FirstRun').innerHTML = Units_FirstRun;
byId('Unit_SecondRun').innerHTML = Units_SecondRun;
byId('Unit_Pre').innerHTML = Units_Pre;
byId('Unit_Post').innerHTML = Units_Post;
byId('Unit_VChilled').innerHTML = Units_VChilled;
byId('Unit_VPackaged').innerHTML = Units_VPackaged;
byId('Unit_VolMash').innerHTML = Units_VolMash;
byId('Unit_MinSparge').innerHTML = Units_MinSparge;
byId('Unit_KettleVolume').innerHTML = Units_KettleVolume;
byId('Unit_PreboilVolume').innerHTML = Units_PreboilVolume;
byId('Unit_TempStrike').innerHTML = Units_TempStrike;
byId('Unit_Sparge').innerHTML = Units_Sparge;
byId('Unit_HTot').innerHTML = Units_HTot;
byId('Unit_GallonHeight').innerHTML = Units_GallonHeight;
byId('Unit_HVolStart').innerHTML = Units_HVolStart;
byId('Unit_HStrike').innerHTML = Units_HStrike;
byId('Unit_HVolMash').innerHTML = Units_HVolMash;
byId('Unit_HFirstRun').innerHTML = Units_HFirstRun;
byId('Unit_HSecondRun').innerHTML = Units_HSecondRun;
byId('Unit_HPre').innerHTML = Units_HPre;
byId('Unit_HPost').innerHTML = Units_HPost;
byId('Unit_HChilled').innerHTML = Units_HChilled;
byId('Unit_GBill').innerHTML = Units_GBill;
byId('Unit_Hop').innerHTML = Units_Hop;
byId('Unit_DHop').innerHTML = Units_DHop;
byId('Unit_Gabs').innerHTML = Units_Gabs;
byId('Unit_MeasuredGabs').innerHTML = Units_MeasuredGabs;
byId('Unit_Habs').innerHTML = Units_Habs;
byId('Unit_MTemp').innerHTML = Units_MTemp;
byId('Unit_GTemp').innerHTML = Units_GTemp;
byId('Unit_STemp').innerHTML = Units_STemp;
byId('Unit_MashoutTemp').innerHTML = Units_MashoutTemp;
byId('Unit_MashThickness2').innerHTML = Units_MashThickness2;
byId('Unit_EBoil').innerHTML = Units_EBoil;
byId('Unit_KettleWidth').innerHTML = Units_KettleWidth;
byId('Unit_BoilOff').innerHTML = Units_BoilOff;
byId('Unit_Trub_Volume').innerHTML = Units_Trub_Volume;
byId('Unit_FTrub_Volume').innerHTML = Units_FTrub_Volume;
byId('Unit_LossTot').innerHTML = Units_LossTot;
byId('Unit_MTrub_Volume').innerHTML = Units_MTrub_Volume;
byId('Unit_MashThickness').innerHTML = Units_MashThickness;
$('#WaterTot').text(WaterTot.toFixed(2));
byId('GBill').value = GBill;
$('#YeastPitch').text(YeastPitch.toFixed(0));
$('#MeasConv').text(MeasConv.toFixed(1));
$('#MeasSecRunWT').text(MeasSecRunWT.toFixed(1));
$('#MeasMashSugarWT').text(MeasMashSugarWT.toFixed(1));
$('#MeasSecRunSG').text(MeasMashWortWT.toFixed(1));
$('#MeasMashEff').text(MeasMashEff.toFixed(1));
$('#MeasPostSG').text(MeasPostSG.toFixed(4));
$('#MeasMashGrav2').text(MeasMashGrav2.toFixed(4));
$('#MeasSecRunSG').text(MeasSecRunSG.toFixed(4));
$('#MeasPrebSugarWT').text(MeasPrebSugarWT.toFixed(4));
$('#MeasSecRunPlato').text(MeasSecRunPlato.toFixed(4));
$('#MeasGabs').text(MeasGabs.toFixed(3));
$('#MeasBrewhEff').text(MeasBrewhEff.toFixed(1));
$('#MeasMashWT').text(MeasMashWT.toFixed(1));
$('#MeasMashEff').text(MeasMashEff.toFixed(1));
$('#EstBrewhEff').text(EstBrewhEff.toFixed(1));
$('#MeasPrebWT').text(MeasPrebWT.toFixed(2));
$('#MeasLautEff').text(MeasLautEff.toFixed(1));
$('#MeasLautWT').text(MeasLautWT.toFixed(2));
$('#EstConvWt').text(EstConvWt.toFixed(2));
$('#MeasMashPlato').text(MeasMashPlato.toFixed(2));
$('#MeasPrebPlato').text(MeasPrebPlato.toFixed(2));
$('#TempMashout').text(TempMashout.toFixed(2));
$('#VolStrike').text(VolStrike.toFixed(2));
$('#VolSparge2').text(VolSparge2.toFixed(2));
$('#LossBoil').text(LossBoil.toFixed(2));
$('#LossHop').text(LossHop.toFixed(2));
$('#LossGrain').text(LossGrain.toFixed(2));
$('#LossTot').text(LossTot.toFixed(2));
$('#LossFermTrub').text(LossFermTrub.toFixed(2));
$('#VolStart').text(VolStart.toFixed(2));
$('#VolMash').text(VolMash.toFixed(2));
$('#VolPre').text(VolPre.toFixed(2));
$('#VolPost').text(VolPost.toFixed(2));
$('#TempStrike').text(TempStrike.toFixed(2));
$('#MashAdj').text(MashAdj.toFixed(12));
$('#Strikeadj').text(StrikeAdj.toFixed(12));
$('#GalH').text(GalH.toFixed(3));
$('#HTot').text(HTot.toFixed(2));
$('#HStart').text(HStart.toFixed(2));
$('#HStrike').text(HStrike.toFixed(2));
$('#HMash').text(HMash.toFixed(2));
$('#HPre').text(HPre.toFixed(2));
$('#HPost').text(HPost.toFixed(2));
$('#DHop').text(DHop.toFixed(2));
$('#HChilled').text(HChilled.toFixed(2));
$('#MashThick').text(MashThick.toFixed(2));
$('#VolMinSparge').text(VolMinSparge.toFixed(2));
$('#VolChilled').text(VolChilled.toFixed(2));
$('#VolPackaged').text(VolPackaged.toFixed(2));
$('#FirstRun').text(FirstRun.toFixed(2));
$('#HFirstRun').text(HFirstRun.toFixed(2));
$('#HSecRun').text(HSecRun.toFixed(2));
$('#SecRun').text(SecRun.toFixed(2));
$('#EBoil').text(EBoil.toFixed(2));
$('#MAGPot').text(MAGPot.toFixed(2));
$('#MAGFine').text(MAGFine.toFixed(2));
$('#MAGMoist').text(MAGMoist.toFixed(2));
$('#MAGEstConv').text(MAGEstConv.toFixed(2));
$('#MAGRunRatio').text(MAGRunRatio.toFixed(2));
$('#SGSuccrose').text(SGSuccrose.toFixed(2));
$('#MeasPrebGrav2').text(MeasPrebGrav2.toFixed(4));
$('#MAGDryG').text(MAGDryG.toFixed(2));
$('#MAGVolWater').text(MAGVolWater.toFixed(2));
$('#MAGWtWater').text(MAGWtWater.toFixed(2));
$('#MAGTotWater').text(MAGTotWater.toFixed(2));
$('#ExPot').text(ExPot.toFixed(2));
$('#ExConv').text(ExConv.toFixed(2));
$('#TotalPot').text(TotalPot.toFixed(2));
$('#MashWaterWt1').text(MashWaterWt1.toFixed(2));
$('#MWT2').text(MWT2.toFixed(2));
$('#MSW1').text(MSW1.toFixed(2));
$('#Plato1').text(Plato1.toFixed(3));
$('#SG1').text(SG1.toFixed(4));
$('#RW1').text(RW1.toFixed(2));
$('#RS1').text(RS1.toFixed(2));
$('#RCWtr1').text(RCWtr1.toFixed(2));
$('#RetS1').text(RetS1.toFixed(2));
$('#RetWat1').text(RetWat1.toFixed(2));
$('#TrueAbs1').text(TrueAbs1.toFixed(3));
$('#MashSugarWt2').text(MashSugarWt2.toFixed(2));
$('#Plato2').text(Plato2.toFixed(3));
$('#SG2').text(SG2.toFixed(4));
$('#RecW2').text(RecW2.toFixed(2));
$('#RS2').text(RS2.toFixed(2));
$('#RCWT2').text(RCWT2.toFixed(2));
$('#RetS2').text(RetS2.toFixed(2));
$('#RetWat2').text(RetWat2.toFixed(2));
$('#TrueAbs2').text(TrueAbs2.toFixed(3));
$('#RCSTot').text(RCSTot.toFixed(2));
$('#EstLauterEff').text(EstLauterEff.toFixed(1));
$('#EstMashEff').text(EstMashEff.toFixed(1));
$('#PlatoPre').text(PlatoPre.toFixed(3));
$('#SGPre').text(SGPre.toFixed(4));
$('#BoilRate').text(BoilRate.toFixed(4));
$('#TotalPoints').text(TotalPoints.toFixed(0));
$('#PlatoPost').text(PlatoPost.toFixed(0));
$('#SGPost').text(SGPost.toFixed(4));
$('#SugarTot').text(SugarTot.toFixed(4));
$('#RetSF').text(RetSF.toFixed(4));
$('#OGDifference').text(OGDifference.toFixed(4));
}
function updateCalc() {
if (!allFieldsValid()) {
return;
}
TargetOG = parseFloat($('#TargetOG').val());
BatchVol = parseFloat($('#BatchVol').val());
GBill = parseFloat($('#GBill').val());
MeasMashGrav = parseFloat($('#MeasMashGrav').val());
MeasPrebGrav = parseFloat($('#MeasPrebGrav').val());
MAGEstConv = parseFloat($('#MAGEstConv').val());
LossTunTrub = parseFloat($('#LossTunTrub').val());
HBill = parseFloat($('#HBill').val());
DHop = parseFloat($('#DHop').val());
MeasPrebVolume = parseFloat($('#MeasPrebVolume').val());
TempSparge = parseFloat($('#TempSparge').val());
BoilTime = parseFloat($('#BoilTime').val());
BoilRate = parseFloat($('#BoilRate').val());
TempGrain = parseFloat($('#TempGrain').val());
TempMash = parseFloat($('#TempMash').val());
VolSparge = parseFloat($('#VolSparge').val());
PotSize = parseFloat($('#PotSize').val());
KettleID = parseFloat($('#KettleID').val());
LossTrub = parseFloat($('#LossTrub').val());
TargetOG = parseFloat($('#TargetOG').val());
Gabs = parseFloat($('#Gabs').val());
Habs = parseFloat($('#Habs').val());
MashAdj = parseFloat($('#MashAdj').val());
StrikeAdj = parseFloat($('#StrikeAdj').val());
LossFermTrub = parseFloat($('#LossFermTrub').val());
MashThickness = parseFloat($('#MashThickness').val());
HopRatio = HBill / BatchVol;
LossBoil = BoilTime * BoilRate / 60;
LossHop = HBill * Habs;
LossGrain = GBill * Gabs;
LossTot = LossGrain + LossHop + LossBoil + LossTrub + LossTunTrub;
WaterTot = BatchVol + LossTot;
MashThick = (WaterTot - VolSparge) * 4 / GBill;
if (MashThickness == 0) {
VolSparge2 = 0;
} else {
VolSparge2 = WaterTot - (GBill * MashThickness / 4);
MashThick = MashThickness;
VolSparge = VolSparge2;
}
VolStart = (WaterTot - VolSparge);
TempStrike = TempMash + (0.05 * GBill / VolStart) * (TempMash - TempGrain);
MashAdj = 1.022494888;
StrikeAdj = 1.025641026;
VolStrike = VolStart * StrikeAdj;
LossHop = HBill * Habs;
LossGrain = GBill * Gabs;
VolMash = (VolStart + GBill * 0.08) * MashAdj;
VolPre = (WaterTot - LossGrain - LossTunTrub) * 1.043841336;
VolPost = (WaterTot - LossTot + LossTrub) * 1.043841336;
VolChilled = (VolPost / 1.043841336) - LossTrub;
VolPackaged = VolChilled - LossFermTrub - (DHop * Habs);
GalH = 294.118334834 / (KettleID * KettleID);
HTot = GalH * WaterTot;
HStart = GalH * VolStart;
HStrike = GalH * VolStrike;
HMash = GalH * VolMash;
HPre = GalH * VolPre;
HChilled = GalH * VolChilled;
VolMinSparge = Math.max(0, ((WaterTot + GBill * 0.08) * MashAdj) - (PotSize - 0.1));
HPost = GalH * VolPost;
FirstRun = (VolStart - LossGrain - LossTunTrub) * MashAdj;
HFirstRun = FirstRun * GalH;
SecRun = VolSparge;
HSecRun = SecRun * GalH;
EBoil = (0.0058 * KettleID * KettleID) - (0.0009 * KettleID) + 0.0038;
MAGPot = 37.212;
MAGFine = 0.7797;
MAGMoist = 0.04;
MAGRunRatio = Math.max(SecRun / FirstRun, 0);
SGSuccrose = 46.173;
MAGDryG = (1 - MAGMoist) * GBill;
MAGVolWater = GBill * MAGMoist;
MAGWtWater = MAGVolWater;
MAGTotWater = WaterTot * 8.3304;
ExPot = MAGPot / SGSuccrose;
ExConv = ExPot * (MAGEstConv / 100);
TotalPot = GBill * MAGPot * (1 - MAGMoist);
MashWaterWt1 = (VolStart * 8.3304) + (GBill - MAGDryG);
SugarTot = MAGDryG * ExPot;
MSW1 = MAGDryG * ExConv;
Plato1 = (100 * MSW1) / (MSW1 + MashWaterWt1);
SG1 = 1 + (Plato1 / (258.6 - 0.879551 * Plato1));
RW1 = (SG1 * (FirstRun / 1.022494888) * 8.3304);
RS1 = (RW1 * Plato1) / 100;
RCWtr1 = RW1 - RS1;
RetS1 = MSW1 - RS1;
RetWat1 = VolStart * 8.3304 - RCWtr1;
MWT2 = ((VolSparge * 8.3304) + RetWat1);
TrueAbs1 = (RetS1 + RetWat1) / (SG1 * 8.3304 * GBill);
MashSugarWt2 = RetS1;
Plato2 = (100 * MashSugarWt2) / (MashSugarWt2 + MWT2);
SG2 = 1 + (Plato2 / (258.6 - 0.879551 * Plato2));
RCWT2 = SG2 * (SecRun / 1.022494888) * 8.3304;
RS2 = (RCWT2 * Plato2) / 100;
RecW2 = RCWT2 - RS2;
RetS2 = MashSugarWt2 - RS2;
RetWat2 = MWT2 - RecW2;
TrueAbs2 = (RetS2 + RetWat2) / (SG2 * 8.3304 * GBill);
RCSTot = RS1 + RS2;
EstLauterEff = 100 * (RCSTot / MSW1);
EstMashEff = EstLauterEff * MAGEstConv / 100;
PlatoPre = (100 * RCSTot) / (RCSTot + RecW2 + RCWtr1);
SGPre = 1 + (PlatoPre / (258.6 - 0.879551 * PlatoPre));
RetSF = RetS2;
EstConvWt = SugarTot * MAGEstConv / 100;
TotalPoints = ((VolPre / 1.044) * (SGPre - 1) * 1000);
PlatoPost = (100 * RCSTot) / (RCSTot + RecW2 + RCWtr1 - (BoilRate * 8.3304 * (BoilTime / 60)));
SGPost = 1 + (PlatoPost / (258.6 - 0.879551 * PlatoPost));
TempMashout = (TempMash * (GBill + 5 * (GBill * Gabs)) + (5 * TempSparge * VolSparge)) / (GBill + 5 * (VolSparge + (GBill * Gabs)));
MeasMashPlato = -616.868 + (1111.14 * MeasMashGrav) - (630.272 * MeasMashGrav * MeasMashGrav) + (135.997 * MeasMashGrav * MeasMashGrav * MeasMashGrav);
MeasGabs = Math.min(MeasPrebVolume, (WaterTot - (MeasPrebVolume) / 1.043841336) / GBill);
MeasMashWT = -((VolStart * 8.335 + (GBill * 0.04)) * MeasMashPlato) / (-100 + MeasMashPlato);
MeasConv = Math.max(100 * MeasMashWT / SugarTot, 0);
MeasPrebPlato = -616.868 + (1111.14 * MeasPrebGrav) - (630.272 * MeasPrebGrav * MeasPrebGrav) + (135.997 * MeasPrebGrav * MeasPrebGrav * MeasPrebGrav);
MeasPrebWortWT = MeasPrebGrav * (MeasPrebVolume / 1.043841336) * 8.3304;
MeasPrebSugarWT = (MeasPrebWortWT * MeasPrebPlato) / 100;
MeasPrebWaterWT = MeasPrebWortWT - MeasPrebSugarWT;
MeasPrebWT = -(MeasPrebWaterWT * MeasPrebPlato) / (-100 + MeasPrebPlato);
MeasMashEff = Math.max(0, 100 * MeasPrebWT / SugarTot);
MeasLautWT = Math.max(0, MeasPrebWT - MeasMashWT);
MeasLautEff = 100 * MeasPrebWT / EstConvWt;
EstBrewhEff = VolChilled / (VolPost / 1.043841336) * EstMashEff;
MeasBrewhEff = VolChilled / (VolPost / 1.043841336) * MeasMashEff;
MeasPrebGrav2 = MeasPrebGrav;
MeasMashGrav2 = MeasMashGrav;
MeasMashPlato2 = -616.868 + (1111.14 * MeasMashGrav2) - (630.272 * MeasMashGrav2 * MeasMashGrav2) + (135.997 * MeasMashGrav2 * MeasMashGrav2 * MeasMashGrav2);
MeasMashWortWT = MeasMashGrav2 * (VolStart - (GBill * MeasGabs)) * 8.3304;
MeasMashSugarWT = (MeasMashWortWT * MeasMashPlato2) / 100;
MeasSecRunWT = MeasPrebSugarWT - MeasMashSugarWT;
MeasSecRunPlato = (100 * MeasSecRunWT) / (MeasSecRunWT + VolSparge * 8.3304);
MeasSecRunSG = 1 + (MeasSecRunPlato / (258.6 - 0.879551 * MeasSecRunPlato));
MeasPostSG = 1 + ((((MeasPrebGrav2 - 1) * 1000) * (MeasPrebVolume / 1.043841336) / (VolPost / 1.043841336)) / 1000);
MeasPostPlato = -616.868 + (1111.14 * MeasPostSG) - (630.272 * MeasPostSG * MeasPostSG) + (135.997 * MeasPostSG * MeasPostSG * MeasPostSG);
if (MeasPostSG > 1) {
YeastPitch = .75 * 3785.41 * BatchVol * MeasPostPlato / 1000;
} else {
YeastPitch = .75 * 3785.41 * BatchVol * PlatoPost / 1000;
}
OGDifference = TargetOG - SGPost;
updateDisplay();
preradio = radio;
}
function AutoScale() {
while (OGDifference > 0.000001) {
GBill = GBill + 0.001;
byId('GBill').value = GBill;
updateCalc();
}
byId('GBill').value = GBill;
GBill = GBill.toFixed(3);
}
function SaveData() {
CreateSaved();
localStorage.setItem('Saved', Saved);
}
function CreateSaved()
{
BatchVol = byId('BatchVol').value;
BoilTime = byId('BoilTime').value;
TempGrain = byId('TempGrain').value;
MashThickness = byId('MashThickness').value;
VolSparge = byId('VolSparge').value;
Gabs = byId('Gabs').value;
Habs = byId('Habs').value;
BoilRate = byId('BoilRate').value;
PotSize = byId('PotSize').value;
KettleID = byId('KettleID').value;
LossTrub = byId('LossTrub').value;
LossFermTrub = byId('LossFermTrub').value;
LossTunTrub = byId('LossTunTrub').value;
MAGEstConv = byId('MAGEstConv').value;
SavedArray = [BatchVol,BoilTime,TempGrain,VolSparge,Gabs,Habs,BoilRate,PotSize,KettleID,LossTrub,LossFermTrub,LossTunTrub,MAGEstConv,MashThickness];
Saved = SavedArray.join();
}
function LoadData() {
Saved = localStorage.getItem('Saved');
SavedArray = Saved.split(",")
byId('BatchVol').value = SavedArray[0];
byId('BoilTime').value = SavedArray[1];
byId('TempGrain').value = SavedArray[2];
byId('VolSparge').value = SavedArray[3];
byId('Gabs').value = SavedArray[4];
byId('Habs').value = SavedArray[5];
byId('BoilRate').value = SavedArray[6];
byId('PotSize').value = SavedArray[7];
byId('KettleID').value = SavedArray[8];
byId('LossTrub').value = SavedArray[9];
byId('LossTunTrub').value = SavedArray[10];
byId('LossFermTrub').value = SavedArray[11];
byId('MAGEstConv').value = SavedArray[12];
byId('MashThickness').value = SavedArray[13];
}
function byId(id) {
return (document.getElementById(id));
}
function validateField(field) {
$field = $(field);
if ($field.val().match(/^d*(.\d+)?/)) {
$field.parents('div.control-group:first').removeClass('error');
return true;
}
$field.parents('div.control-group:first').addClass('error');
return false;
}
|
/*!
* jQuery dataAttributes - v1.0.0
* A fixed jQuery .data() method.
* https://github.com/marcofugaro/jquery-data-attributes
**/
!function(t){t.fn.dataAttributes=function(a,e){if(this.length){if(e)return this.attr("data-"+a,e);if(a)return this.attr("data-"+a);var i={};return t.each(this[0].attributes,function(t,a){a.name.indexOf("data-")>-1&&a.value&&(i[a.name.slice(5)]=a.value)}),i}}}(jQuery); |
function FrameRateService() {
var frameCountLimit = 30;
var frameEndTimes;
return {
reset: function() {
frameEndTimes = [];
var frameEndTime = new Date()
.getTime();
frameEndTimes.push(frameEndTime);
},
next: function() {
var newEndTime = new Date()
.getTime();
frameEndTimes.push(newEndTime);
if (frameEndTimes.length > frameCountLimit) {
frameEndTimes.shift();
}
return Math.floor(1 / ((newEndTime - frameEndTimes[0]) / 1000) * frameEndTimes.length);
}
};
}
angular.module('gameOfLife')
.factory('frameRateService', FrameRateService); |
/*
* jsPlumb
*
* Title:jsPlumb 1.3.11
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the HTML5 canvas renderers.
*
* Copyright (c) 2010 - 2012 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
// ********************************* CANVAS RENDERERS FOR CONNECTORS AND ENDPOINTS *******************************************************************
// TODO refactor to renderer common script. put a ref to jsPlumb.sizeCanvas in there too.
var _connectionBeingDragged = null,
_hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
_getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
_getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
_pageXY = function(el) { return jsPlumb.CurrentLibrary.getPageXY(el); },
_clientXY = function(el) { return jsPlumb.CurrentLibrary.getClientXY(el); };
/*
* Class:CanvasMouseAdapter
* Provides support for mouse events on canvases.
*/
var CanvasMouseAdapter = function() {
var self = this;
self.overlayPlacements = [];
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
jsPlumbUtil.EventGenerator.apply(this, arguments);
/**
* returns whether or not the given event is ojver a painted area of the canvas.
*/
this._over = function(e) {
var o = _getOffset(_getElementObject(self.canvas)),
pageXY = _pageXY(e),
x = pageXY[0] - o.left, y = pageXY[1] - o.top;
if (x > 0 && y > 0 && x < self.canvas.width && y < self.canvas.height) {
// first check overlays
for ( var i = 0; i < self.overlayPlacements.length; i++) {
var p = self.overlayPlacements[i];
if (p && (p[0] <= x && p[1] >= x && p[2] <= y && p[3] >= y))
return true;
}
// then the canvas
var d = self.canvas.getContext("2d").getImageData(parseInt(x), parseInt(y), 1, 1);
return d.data[0] != 0 || d.data[1] != 0 || d.data[2] != 0 || d.data[3] != 0;
}
return false;
};
var _mouseover = false, _mouseDown = false, _posWhenMouseDown = null, _mouseWasDown = false,
_nullSafeHasClass = function(el, clazz) {
return el != null && _hasClass(el, clazz);
};
this.mousemove = function(e) {
var pageXY = _pageXY(e), clientXY = _clientXY(e),
ee = document.elementFromPoint(clientXY[0], clientXY[1]),
eventSourceWasOverlay = _nullSafeHasClass(ee, "_jsPlumb_overlay");
var _continue = _connectionBeingDragged == null && (_nullSafeHasClass(ee, "_jsPlumb_endpoint") || _nullSafeHasClass(ee, "_jsPlumb_connector"));
if (!_mouseover && _continue && self._over(e)) {
_mouseover = true;
self.fire("mouseenter", self, e);
return true;
}
// TODO here there is a remote chance that the overlay the mouse moved onto
// is actually not an overlay for the current component. a more thorough check would
// be to ensure the overlay belonged to the current component.
else if (_mouseover && (!self._over(e) || !_continue) && !eventSourceWasOverlay) {
_mouseover = false;
self.fire("mouseexit", self, e);
}
self.fire("mousemove", self, e);
};
this.click = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("click", self, e);
_mouseWasDown = false;
};
this.dblclick = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("dblclick", self, e);
_mouseWasDown = false;
};
this.mousedown = function(e) {
if(self._over(e) && !_mouseDown) {
_mouseDown = true;
_posWhenMouseDown = _getOffset(_getElementObject(self.canvas));
self.fire("mousedown", self, e);
}
};
this.mouseup = function(e) {
_mouseDown = false;
self.fire("mouseup", self, e);
};
this.contextmenu = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("contextmenu", self, e);
_mouseWasDown = false;
};
};
var _newCanvas = function(params) {
var canvas = document.createElement("canvas");
params["_jsPlumb"].appendElement(canvas, params.parent);
canvas.style.position = "absolute";
if (params["class"]) canvas.className = params["class"];
// set an id. if no id on the element and if uuid was supplied it
// will be used, otherwise we'll create one.
params["_jsPlumb"].getId(canvas, params.uuid);
if (params.tooltip) canvas.setAttribute("title", params.tooltip);
return canvas;
};
var CanvasComponent = function(params) {
CanvasMouseAdapter.apply(this, arguments);
var displayElements = [ ];
this.getDisplayElements = function() { return displayElements; };
this.appendDisplayElement = function(el) { displayElements.push(el); };
};
/**
* Class:CanvasConnector
* Superclass for Canvas Connector renderers.
*/
var CanvasConnector = jsPlumb.CanvasConnector = function(params) {
CanvasComponent.apply(this, arguments);
var _paintOneStyle = function(dim, aStyle) {
self.ctx.save();
jsPlumb.extend(self.ctx, aStyle);
if (aStyle.gradient) {
var g = self.createGradient(dim, self.ctx);
for ( var i = 0; i < aStyle.gradient.stops.length; i++)
g.addColorStop(aStyle.gradient.stops[i][0], aStyle.gradient.stops[i][1]);
self.ctx.strokeStyle = g;
}
self._paint(dim, aStyle);
self.ctx.restore();
};
var self = this,
clazz = self._jsPlumb.connectorClass + " " + (params.cssClass || "");
self.canvas = _newCanvas({
"class":clazz,
_jsPlumb:self._jsPlumb,
parent:params.parent,
tooltip:params.tooltip
});
self.ctx = self.canvas.getContext("2d");
self.appendDisplayElement(self.canvas);
self.paint = function(dim, style) {
if (style != null) {
jsPlumb.sizeCanvas(self.canvas, dim[0], dim[1], dim[2], dim[3]);
if (style.outlineColor != null) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth),
outlineStyle = {
strokeStyle:style.outlineColor,
lineWidth:outlineStrokeWidth
};
_paintOneStyle(dim, outlineStyle);
}
_paintOneStyle(dim, style);
}
};
};
/**
* Class:CanvasEndpoint
* Superclass for Canvas Endpoint renderers.
*/
var CanvasEndpoint = function(params) {
var self = this;
CanvasComponent.apply(this, arguments);
var clazz = self._jsPlumb.endpointClass + " " + (params.cssClass || ""),
canvasParams = {
"class":clazz,
_jsPlumb:self._jsPlumb,
parent:params.parent,
tooltip:self.tooltip
};
self.canvas = _newCanvas(canvasParams);
self.ctx = self.canvas.getContext("2d");
self.appendDisplayElement(self.canvas);
this.paint = function(d, style, anchor) {
jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
if (style.outlineColor != null) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
var outlineStyle = {
strokeStyle:style.outlineColor,
lineWidth:outlineStrokeWidth
};
}
self._paint.apply(this, arguments);
};
};
jsPlumb.Endpoints.canvas.Dot = function(params) {
jsPlumb.Endpoints.Dot.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
var self = this,
parseValue = function(value) {
try { return parseInt(value); }
catch(e) {
if (value.substring(value.length - 1) == '%')
return parseInt(value.substring(0, value - 1));
}
},
calculateAdjustments = function(gradient) {
var offsetAdjustment = self.defaultOffset, innerRadius = self.defaultInnerRadius;
gradient.offset && (offsetAdjustment = parseValue(gradient.offset));
gradient.innerRadius && (innerRadius = parseValue(gradient.innerRadius));
return [offsetAdjustment, innerRadius];
};
this._paint = function(d, style, anchor) {
if (style != null) {
var ctx = self.canvas.getContext('2d'), orientation = anchor.getOrientation(self);
jsPlumb.extend(ctx, style);
if (style.gradient) {
var adjustments = calculateAdjustments(style.gradient),
yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0],
xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0],
g = ctx.createRadialGradient(d[4], d[4], d[4], d[4] + xAdjust, d[4] + yAdjust, adjustments[1]);
for (var i = 0; i < style.gradient.stops.length; i++)
g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
ctx.fillStyle = g;
}
ctx.beginPath();
ctx.arc(d[4], d[4], d[4], 0, Math.PI*2, true);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
}
};
};
jsPlumb.Endpoints.canvas.Rectangle = function(params) {
var self = this;
jsPlumb.Endpoints.Rectangle.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
this._paint = function(d, style, anchor) {
var ctx = self.canvas.getContext("2d"), orientation = anchor.getOrientation(self);
jsPlumb.extend(ctx, style);
/* canvas gradient */
if (style.gradient) {
// first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
var y1 = orientation[1] == 1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
var y2 = orientation[1] == -1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
var x1 = orientation[0] == 1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
var x2 = orientation[0] == -1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
var g = ctx.createLinearGradient(x1,y1,x2,y2);
for (var i = 0; i < style.gradient.stops.length; i++)
g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
ctx.fillStyle = g;
}
ctx.beginPath();
ctx.rect(0, 0, d[2], d[3]);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
};
};
jsPlumb.Endpoints.canvas.Triangle = function(params) {
var self = this;
jsPlumb.Endpoints.Triangle.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
this._paint = function(d, style, anchor)
{
var width = d[2], height = d[3], x = d[0], y = d[1],
ctx = self.canvas.getContext('2d'),
offsetX = 0, offsetY = 0, angle = 0,
orientation = anchor.getOrientation(self);
if( orientation[0] == 1 ) {
offsetX = width;
offsetY = height;
angle = 180;
}
if( orientation[1] == -1 ) {
offsetX = width;
angle = 90;
}
if( orientation[1] == 1 ) {
offsetY = height;
angle = -90;
}
ctx.fillStyle = style.fillStyle;
ctx.translate(offsetX, offsetY);
ctx.rotate(angle * Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(width/2, height/2);
ctx.lineTo(0, height);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
};
};
/*
* Canvas Image Endpoint: uses the default version, which creates an <img> tag.
*/
jsPlumb.Endpoints.canvas.Image = jsPlumb.Endpoints.Image;
/*
* Blank endpoint in all renderers is just the default Blank endpoint.
*/
jsPlumb.Endpoints.canvas.Blank = jsPlumb.Endpoints.Blank;
/*
* Canvas Bezier Connector. Draws a Bezier curve onto a Canvas element.
*/
jsPlumb.Connectors.canvas.Bezier = function() {
var self = this;
jsPlumb.Connectors.Bezier.apply(this, arguments);
CanvasConnector.apply(this, arguments);
this._paint = function(dimensions, style) {
self.ctx.beginPath();
self.ctx.moveTo(dimensions[4], dimensions[5]);
self.ctx.bezierCurveTo(dimensions[8], dimensions[9], dimensions[10], dimensions[11], dimensions[6], dimensions[7]);
self.ctx.stroke();
};
// TODO i doubt this handles the case that source and target are swapped.
this.createGradient = function(dim, ctx, swap) {
return /*(swap) ? self.ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : */self.ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
};
};
/*
* Canvas straight line Connector. Draws a straight line onto a Canvas element.
*/
jsPlumb.Connectors.canvas.Straight = function() {
var self = this,
segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ];
jsPlumb.Connectors.Straight.apply(this, arguments);
CanvasConnector.apply(this, arguments);
this._paint = function(dimensions, style) {
self.ctx.beginPath();
if (style.dashstyle && style.dashstyle.split(" ").length == 2) {
// only a very simple dashed style is supported - having two values, which define the stroke length
// (as a multiple of the stroke width) and then the space length (also as a multiple of stroke width).
var ds = style.dashstyle.split(" ");
if (ds.length != 2) ds = [2, 2];
var dss = [ ds[0] * style.lineWidth, ds[1] * style.lineWidth ],
m = (dimensions[6] - dimensions[4]) / (dimensions[7] - dimensions[5]),
s = jsPlumbUtil.segment([dimensions[4], dimensions[5]], [ dimensions[6], dimensions[7] ]),
sm = segmentMultipliers[s],
theta = Math.atan(m),
l = Math.sqrt(Math.pow(dimensions[6] - dimensions[4], 2) + Math.pow(dimensions[7] - dimensions[5], 2)),
repeats = Math.floor(l / (dss[0] + dss[1])),
curPos = [dimensions[4], dimensions[5]];
// TODO: the question here is why could we not support this in all connector types? it's really
// just a case of going along and asking jsPlumb for the next point on the path a few times, until it
// reaches the end. every type of connector supports that method, after all. but right now its only the
// bezier connector that gives you back the new location on the path along with the x,y coordinates, which
// we would need. we'd start out at loc=0 and ask for the point along the path that is dss[0] pixels away.
// we then ask for the point that is (dss[0] + dss[1]) pixels away; and from that one we need not just the
// x,y but the location, cos we're gonna plug that location back in in order to find where that dash ends.
//
// it also strikes me that it should be trivial to support arbitrary dash styles (having more or less than two
// entries). you'd just iterate that array using a step size of 2, and generify the (rss[0] + rss[1])
// computation to be sum(rss[0]..rss[n]).
for (var i = 0; i < repeats; i++) {
self.ctx.moveTo(curPos[0], curPos[1]);
var nextEndX = curPos[0] + (Math.abs(Math.sin(theta) * dss[0]) * sm[0]),
nextEndY = curPos[1] + (Math.abs(Math.cos(theta) * dss[0]) * sm[1]),
nextStartX = curPos[0] + (Math.abs(Math.sin(theta) * (dss[0] + dss[1])) * sm[0]),
nextStartY = curPos[1] + (Math.abs(Math.cos(theta) * (dss[0] + dss[1])) * sm[1])
self.ctx.lineTo(nextEndX, nextEndY);
curPos = [nextStartX, nextStartY];
}
// now draw the last bit
self.ctx.moveTo(curPos[0], curPos[1]);
self.ctx.lineTo(dimensions[6], dimensions[7]);
}
else {
self.ctx.moveTo(dimensions[4], dimensions[5]);
self.ctx.lineTo(dimensions[6], dimensions[7]);
}
self.ctx.stroke();
};
// TODO this does not handle the case that src and target are swapped.
this.createGradient = function(dim, ctx) {
return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
};
};
jsPlumb.Connectors.canvas.Flowchart = function() {
var self = this;
jsPlumb.Connectors.Flowchart.apply(this, arguments);
CanvasConnector.apply(this, arguments);
this._paint = function(dimensions, style) {
self.ctx.beginPath();
self.ctx.moveTo(dimensions[4], dimensions[5]);
// loop through extra points
for (var i = 0; i < dimensions[8]; i++) {
self.ctx.lineTo(dimensions[9 + (i*2)], dimensions[10 + (i*2)]);
}
// finally draw a line to the end
self.ctx.lineTo(dimensions[6], dimensions[7]);
self.ctx.stroke();
};
this.createGradient = function(dim, ctx) {
return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
};
};
// ********************************* END OF CANVAS RENDERERS *******************************************************************
jsPlumb.Overlays.canvas.Label = jsPlumb.Overlays.Label;
/**
* a placeholder right now, really just exists to mirror the fact that there are SVG and VML versions of this.
*/
var CanvasOverlay = function() {
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
};
var AbstractCanvasArrowOverlay = function(superclass, originalArgs) {
superclass.apply(this, originalArgs);
CanvasOverlay.apply(this, originalArgs);
this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
var ctx = connector.ctx;
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.moveTo(d.hxy.x, d.hxy.y);
ctx.lineTo(d.tail[0].x, d.tail[0].y);
ctx.lineTo(d.cxy.x, d.cxy.y);
ctx.lineTo(d.tail[1].x, d.tail[1].y);
ctx.lineTo(d.hxy.x, d.hxy.y);
ctx.closePath();
if (strokeStyle) {
ctx.strokeStyle = strokeStyle;
ctx.stroke();
}
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
};
};
jsPlumb.Overlays.canvas.Arrow = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
};
jsPlumb.Overlays.canvas.PlainArrow = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
};
jsPlumb.Overlays.canvas.Diamond = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
};
})(); |
var kue = require('kue');
var console = require('tracer').colorConsole();
var publisher = function (config, conn) {
var queue = null;
var jobs = {};
var start = function () {
queue = kue.createQueue();
startPublisher();
};
function setStatus(data, status) {
if (data) {
conn.query("UPDATE ?? SET `status` = ? where `id` = ? ;",
[data.key, status, data.id],
function (err) {
if (err) {
console.log('err', err)
} else {
console.log('status change')
}
});
}
}
function startPublisher() {
queue.on('job complete', function (id, type) {
console.log('job complete id', id, 'type', type);
setStatus(jobs[id], 'task complete');
delete jobs[id]
});
}
function publish(task, data, id) {
var jobData = {
id: id,
key: task.replace(config.kue.prefix, '')
};
var job = queue.create(task, data).save(function (err) {
if (err) {
console.log('err', err);
setStatus(jobData, 'task error');
} else {
jobs[job.id] = jobData;
}
});
}
start();
return {
publish: publish
}
};
module.exports = publisher; |
'use strict';
exports.mockSchemaObject = function (defaults, options) {
var ret = {
_obj: defaults || {},
_options: options || {},
_errors: []
};
ret._this = ret;
return ret;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.