<commit_before>/*global psc jQuery */
psc.namespace("template.mpa");

psc.template.mpa.Presentation = (function ($) {
  function syncVertical() {
    var target = $('#days').scrollTop();
    $('#activities, #notes').scrollTop(target);
  }

  function syncHorizontal() {
    var target = $('#days').scrollLeft();
    $('#days-heading').scrollLeft(target);
  }

  function showSelectedTool(evt, data) {
    $('#tools-section .tool-selector').removeClass('selected');
    $('#' + data.name + "-tool").addClass('selected');

    $('#tools-section .tool-detail').stop().hide();
    $('#' + data.name + '-tool-detail').
      find('span.step-' + data.step).show().end().
      find('span:not(.step-' + data.step + ')').hide().end().
      fadeIn(250);

    $('body').attr('class', $('body').attr('class').replace(/action-\w+/g, ''));
    $('body').addClass('action-' + data.name);

    $('body').attr('class', $('body').attr('class').replace(/step-\w+/g, ''));
    $('body').addClass('step-' + data.step);
  }

  function selectTool() {
    var data = {
      name: $(this).attr('id').replace('-tool', ''),
      step: 0
    };
    $('#days').trigger('action-changed', data);
    return false;
  }

  function showSelectedNotes(noteType) {
    if (!noteType) {
      noteType = $('#notes-heading li.selected').text().toLowerCase();
    } else {
      $('#notes-heading li').removeClass('selected');
      $('#notes-heading li.' + noteType).addClass('selected');
    }

    $('#notes .note').stop().hide();
    $('#notes .' + noteType).fadeIn(250);
  }

  function selectNoteTab() {
    showSelectedNotes($(this).attr('href').replace(/^#/, ''));
  }

  function setMessage(text, klass) {
    $('#message').attr('class', '').text(text);
    if (klass) {
      $('#message').addClass(klass);
    }
  }

  function reportError(evt, data) {
    psc.template.mpa.Presentation.error(data.message);
  }

  var gridUpdates = {
    'action-started': {
      'add,0': function (evt, data) {
        var pop = data.population ? data.population : '×';
        $(data.cell).addClass('in-progress').
          empty().append("
" + pop + "
");
      },

      'move,0': function (evt, data) {
        $(data.cell).addClass('in-progress').addClass('moving').
          parent('tr').addClass('moving');
      },

      'move,1': function (evt, data) {
        var src = $(data.cell).parent('tr').find('td.cell.moving');
        src.removeClass('moving').parent('tr').removeClass('moving');
        $(data.cell).addClass('in-progress').empty().
          append(src.find('.marker'));
      },

      'update-notes,0': function (evt, data) {
        $(data.cell).addClass('in-progress');
      },

      'delete,0': function (evt, data) {
        $(data.cell).addClass('in-progress');
      }
    },

    'action-completed': {
      'add,0': function (evt, data) {
        $(data.cell).removeClass('in-progress').
          find('.marker').attr('resource-href', data.href);
      },

      'move,1': function (evt, data) {
        $(data.cell).removeClass('in-progress').parent('tr').
          find('td.cell:eq(' + data.startColumn + ')').removeClass('in-progress');
      },

      'update-notes,0': function (evt, data) {
        $(data.cell).removeClass('in-progress');
      },

      'delete,0': function (evt, data) {
        $(data.cell).removeClass('in-progress').empty();
      }
    },

    'action-error': {
      'add,0': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).removeClass('in-progress').
            addClass('error').empty();
        }
      },

      'move,1': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).addClass('error').removeClass('in-progress').
            parent('tr').find('td.cell:eq(' + data.startColumn + ')').
              addClass('error').removeClass('in-progress').
              empty().append($(data.cell).find('.marker'));
        }
      },

      'update-notes,0': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).removeClass('in-progress').addClass('error');
        }
      },

      'delete,0': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).removeClass('in-progress').addClass('error');
        }
      }
    }
  }

  function routeGridAction(evt, data) {
    if (evt.type in gridUpdates) {
      if (!(data.action && data.action.name)) {
        return;
      }
      var actionStepKey = data.action.name + ',' + data.action.step

      if (actionStepKey in gridUpdates[evt.type]) {
        gridUpdates[evt.type][actionStepKey](evt, data);
      } else {
        throw "Unknown action " + actionStepKey +
          " received in an " + evt.type + " event";
      }
    } else {
      throw "Attempting to route unknown event: " + evt.type;
    }
  }

  function cancelMove(evt, data) {
    if (data.name != 'move' || data.step != 1) {
      $('tr.moving').
        find('td.in-progress.moving').removeClass('in-progress').removeClass('moving').end().
        removeClass('moving');
    }
  }

  function unnew() {
    $('.new-row').removeClass('new-row')
  }

  return {
    init: function (hash) {
      $('#days').scroll(syncVertical).scroll(syncHorizontal).
        click(unnew);

      $('#days').bind('action-changed', showSelectedTool);
      $('.tool-selector').click(selectTool);
      $('#add-tool').click(); // default

      $('#days').bind('action-error', reportError).
        bind('action-started', this.clearMessage);

      $('#days').bind('action-started', routeGridAction).
        bind('action-completed', routeGridAction).
        bind('action-error', routeGridAction);
      $('#days').bind('action-changed', cancelMove).
        bind('row-added', function () {
          showSelectedNotes(null);
        }).bind('row-added', this.clearMessage).
        bind('action-started', unnew);

      $('#notes-heading li a').click(selectNoteTab);
      if (hash) {
        showSelectedNotes(hash.replace(/^#/, ''));
      } else {
        showSelectedNotes('details');
      }
    },

    error: function (message) {
      setMessage(message, 'error');
    },

    info: function (message) {
      setMessage(message, 'info');
    },

    clearMessage: function () {
      setMessage("");
    }
  };
}(jQuery));<commit_msg>Moved the code which hides the value of each of right panels to the tab selection function. This will make default panel data to be displayed for new added activity. Fixes #946.<commit_after>/*global psc jQuery */
psc.namespace("template.mpa");

psc.template.mpa.Presentation = (function ($) {
  function syncVertical() {
    var target = $('#days').scrollTop();
    $('#activities, #notes').scrollTop(target);
  }

  function syncHorizontal() {
    var target = $('#days').scrollLeft();
    $('#days-heading').scrollLeft(target);
  }

  function showSelectedTool(evt, data) {
    $('#tools-section .tool-selector').removeClass('selected');
    $('#' + data.name + "-tool").addClass('selected');

    $('#tools-section .tool-detail').stop().hide();
    $('#' + data.name + '-tool-detail').
      find('span.step-' + data.step).show().end().
      find('span:not(.step-' + data.step + ')').hide().end().
      fadeIn(250);

    $('body').attr('class', $('body').attr('class').replace(/action-\w+/g, ''));
    $('body').addClass('action-' + data.name);

    $('body').attr('class', $('body').attr('class').replace(/step-\w+/g, ''));
    $('body').addClass('step-' + data.step);
  }

  function selectTool() {
    var data = {
      name: $(this).attr('id').replace('-tool', ''),
      step: 0
    };
    $('#days').trigger('action-changed', data);
    return false;
  }

  function showSelectedNotes(noteType) {
    if (!noteType) {
      noteType = $('#notes-heading li.selected').text().toLowerCase();
    } else {
      $('#notes-heading li').removeClass('selected');
      $('#notes-heading li.' + noteType).addClass('selected');
    }

    $('#notes .' + noteType).fadeIn(250);
  }

  function selectNoteTab() {
    $('#notes .note').stop().hide()
    showSelectedNotes($(this).attr('href').replace(/^#/, ''));
  }

  function setMessage(text, klass) {
    $('#message').attr('class', '').text(text);
    if (klass) {
      $('#message').addClass(klass);
    }
  }

  function reportError(evt, data) {
    psc.template.mpa.Presentation.error(data.message);
  }

  var gridUpdates = {
    'action-started': {
      'add,0': function (evt, data) {
        var pop = data.population ? data.population : '×';
        $(data.cell).addClass('in-progress').
          empty().append("
" + pop + "
");
      },

      'move,0': function (evt, data) {
        $(data.cell).addClass('in-progress').addClass('moving').
          parent('tr').addClass('moving');
      },

      'move,1': function (evt, data) {
        var src = $(data.cell).parent('tr').find('td.cell.moving');
        src.removeClass('moving').parent('tr').removeClass('moving');
        $(data.cell).addClass('in-progress').empty().
          append(src.find('.marker'));
      },

      'update-notes,0': function (evt, data) {
        $(data.cell).addClass('in-progress');
      },

      'delete,0': function (evt, data) {
        $(data.cell).addClass('in-progress');
      }
    },

    'action-completed': {
      'add,0': function (evt, data) {
        $(data.cell).removeClass('in-progress').
          find('.marker').attr('resource-href', data.href);
      },

      'move,1': function (evt, data) {
        $(data.cell).removeClass('in-progress').parent('tr').
          find('td.cell:eq(' + data.startColumn + ')').removeClass('in-progress');
      },

      'update-notes,0': function (evt, data) {
        $(data.cell).removeClass('in-progress');
      },

      'delete,0': function (evt, data) {
        $(data.cell).removeClass('in-progress').empty();
      }
    },

    'action-error': {
      'add,0': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).removeClass('in-progress').
            addClass('error').empty();
        }
      },

      'move,1': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).addClass('error').removeClass('in-progress').
            parent('tr').find('td.cell:eq(' + data.startColumn + ')').
              addClass('error').removeClass('in-progress').
              empty().append($(data.cell).find('.marker'));
        }
      },

      'update-notes,0': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).removeClass('in-progress').addClass('error');
        }
      },

      'delete,0': function (evt, data) {
        if ($(data.cell).is('.in-progress')) {
          $(data.cell).removeClass('in-progress').addClass('error');
        }
      }
    }
  }

  function routeGridAction(evt, data) {
    if (evt.type in gridUpdates) {
      if (!(data.action && data.action.name)) {
        return;
      }
      var actionStepKey = data.action.name + ',' + data.action.step

      if (actionStepKey in gridUpdates[evt.type]) {
        gridUpdates[evt.type][actionStepKey](evt, data);
      } else {
        throw "Unknown action " + actionStepKey +
          " received in an " + evt.type + " event";
      }
    } else {
      throw "Attempting to route unknown event: " + evt.type;
    }
  }

  function cancelMove(evt, data) {
    if (data.name != 'move' || data.step != 1) {
      $('tr.moving').
        find('td.in-progress.moving').removeClass('in-progress').removeClass('moving').end().
        removeClass('moving');
    }
  }

  function unnew() {
    $('.new-row').removeClass('new-row')
  }

  return {
    init: function (hash) {
      $('#days').scroll(syncVertical).scroll(syncHorizontal).
        click(unnew);

      $('#days').bind('action-changed', showSelectedTool);
      $('.tool-selector').click(selectTool);
      $('#add-tool').click(); // default

      $('#days').bind('action-error', reportError).
        bind('action-started', this.clearMessage);

      $('#days').bind('action-started', routeGridAction).
        bind('action-completed', routeGridAction).
        bind('action-error', routeGridAction);
      $('#days').bind('action-changed', cancelMove).
        bind('row-added', function () {
          showSelectedNotes(null);
        }).bind('row-added', this.clearMessage).
        bind('action-started', unnew);

      $('#notes-heading li a').click(selectNoteTab);
      if (hash) {
        showSelectedNotes(hash.replace(/^#/, ''));
      } else {
        showSelectedNotes('details');
      }
    },

    error: function (message) {
      setMessage(message, 'error');
    },

    info: function (message) {
      setMessage(message, 'info');
    },

    clearMessage: function () {
      setMessage("");
    }
  };
}(jQuery));<|endoftext|>


<commit_before>var models = require('../models/models.js');
var por = '%';
var search;
var misearch;
var c = 0;

//GET /quizes/new
exports.new = function(req,res){
	var quiz = models.Quiz.build( //Crea un objeto Quiz
		{pregunta: "Pregunta", respuesta: "Respuesta"}
		);

	res.render('quizes/new', {quiz: quiz, errors: []});
};
// POST /quizes/create
exports.create = function(req, res) {
	var quiz = models.Quiz.build( req.body.quiz);
	quiz.validate().then(function(err){
		if(err){
			res.render('quizes/new',{quiz: quiz, errors: err.errors});
		}else{
	//Guarda en la DB los campos pregunta y respuesta de quiz
	quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
	}
		}
	);
};

//POST /quizes/:id/edit
exports.edit = function(req,res){
	var quiz = req.quiz;
	res.render('quizes/edit',{quiz: quiz, errors: []});
};

// PUT /quizes/:id
exports.update = function(req, res){
	req.quiz.pregunta = req.body.quiz.pregunta;
	req.quiz.respuesta = req.body.quiz.respuesta;

	req.quiz.validate().then(function(err){
		if(err) {
			res.render('quizes/edit',{quiz: req.quiz, errors: err.errors});
		}else{
			//Guarda en la DB los campos pregunta y respuesta de quiz
	req.quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
		}
	}
);
};

//DELETE /quizes/:id
exports.destroy = function(req,res){
	req.quiz.destroy().then(function(){
		res.redirect('/quizes');
	}).catch(function(error){next(error)});
};

//Autoload - factoriza el codigo si ruta incluye :quizId
exports.load = function(req, res, next, quizId){
	models.Quiz.find({
		where: {
			id: Number(quizId)
		},
		include: [{
		 model: models.Comment
		}]
	}).then(function(quiz) {
			if(quiz) {
				req.quiz = quiz;
				next();
			}else { next(new Error('No existe quizId='+ quizId))}
		}
	).catch(function(error) {next(error);});
};

//Get /quizes/index
exports.index = function(req, res, next) {
	misearch = req.query.search;
	search = por
	if(undefined === req.query.search){
		misearch = '.'

	}else{
	misearch = misearch.replace(/[^\w]/g,por);
	search = search.concat(misearch);
	search = search.concat(por);
	misearch = ' para "' + misearch +'".';
	}

	models.Quiz.findAll({
		where:["pregunta like ?", search], //ilike es case-INsensitive frente a like !! extension de postgreSQL
		order:'pregunta ASC',
		include: [{
		 model: models.Comment
		}]
		}).then(function(quizes){
		res.render('quizes/index.ejs', {quizes: quizes, errors: [], misearch: misearch, search: search});
	}).catch(function(error){next(error);});
};

//GEt /quizes/:id
exports.show = function(req,res) {
	models.Quiz.find(req.params.quizId).then(function(quiz){
		res.render('quizes/show' , {quiz: req.quiz, errors: []});
	})
};

//GEt /quizes/:id/answer
exports.answer = function(req,res) {
	var resultado = 'Incorrecto';
		if(req.query.respuesta.toLowerCase() === req.quiz.respuesta.toLowerCase()){
			resultado = 'Correcto';
		}
		res.render('quizes/answer',	{quiz: req.quiz, respuesta: resultado, errors: []});
};

//Get /quizes/statistics
exports.statistics = function(req,res){

/*Funciona en Local
	----------------------

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 	models.Quiz.count(
		 		{ distinct:"Comments.QuizId",
		 		  where: ["Comments.QuizId not like ?", "NULL"],
		 		  include: [models.Comment]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

	------------------------
*/

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 models.Quiz.count(
		 		{
		 			distinct:"Quiz.id",
		 		  where: ["Comments.QuizId like ?", "NULL"],
		 		  include: [models.Comment]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

};

/*
function contarComentarios(){
	models.Comment.count().then(function(nc){
		 c = nc;
	});
	return c ;
};
function contarPreguntas(){
	models.Quiz.count().then(function(q){
		 c = q;
	});
	return c ;
};
*/<commit_msg>arreglo2<commit_after>var models = require('../models/models.js');
var por = '%';
var search;
var misearch;
var c = 0;

//GET /quizes/new
exports.new = function(req,res){
	var quiz = models.Quiz.build( //Crea un objeto Quiz
		{pregunta: "Pregunta", respuesta: "Respuesta"}
		);

	res.render('quizes/new', {quiz: quiz, errors: []});
};
// POST /quizes/create
exports.create = function(req, res) {
	var quiz = models.Quiz.build( req.body.quiz);
	quiz.validate().then(function(err){
		if(err){
			res.render('quizes/new',{quiz: quiz, errors: err.errors});
		}else{
	//Guarda en la DB los campos pregunta y respuesta de quiz
	quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
	}
		}
	);
};

//POST /quizes/:id/edit
exports.edit = function(req,res){
	var quiz = req.quiz;
	res.render('quizes/edit',{quiz: quiz, errors: []});
};

// PUT /quizes/:id
exports.update = function(req, res){
	req.quiz.pregunta = req.body.quiz.pregunta;
	req.quiz.respuesta = req.body.quiz.respuesta;

	req.quiz.validate().then(function(err){
		if(err) {
			res.render('quizes/edit',{quiz: req.quiz, errors: err.errors});
		}else{
			//Guarda en la DB los campos pregunta y respuesta de quiz
	req.quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
		}
	}
);
};

//DELETE /quizes/:id
exports.destroy = function(req,res){
	req.quiz.destroy().then(function(){
		res.redirect('/quizes');
	}).catch(function(error){next(error)});
};

//Autoload - factoriza el codigo si ruta incluye :quizId
exports.load = function(req, res, next, quizId){
	models.Quiz.find({
		where: {
			id: Number(quizId)
		},
		include: [{
		 model: models.Comment
		}]
	}).then(function(quiz) {
			if(quiz) {
				req.quiz = quiz;
				next();
			}else { next(new Error('No existe quizId='+ quizId))}
		}
	).catch(function(error) {next(error);});
};

//Get /quizes/index
exports.index = function(req, res, next) {
	misearch = req.query.search;
	search = por
	if(undefined === req.query.search){
		misearch = '.'

	}else{
	misearch = misearch.replace(/[^\w]/g,por);
	search = search.concat(misearch);
	search = search.concat(por);
	misearch = ' para "' + misearch +'".';
	}

	models.Quiz.findAll({
		where:["pregunta like ?", search], //ilike es case-INsensitive frente a like !! extension de postgreSQL
		order:'pregunta ASC',
		include: [{
		 model: models.Comment
		}]
		}).then(function(quizes){
		res.render('quizes/index.ejs', {quizes: quizes, errors: [], misearch: misearch, search: search});
	}).catch(function(error){next(error);});
};

//GEt /quizes/:id
exports.show = function(req,res) {
	models.Quiz.find(req.params.quizId).then(function(quiz){
		res.render('quizes/show' , {quiz: req.quiz, errors: []});
	})
};

//GEt /quizes/:id/answer
exports.answer = function(req,res) {
	var resultado = 'Incorrecto';
		if(req.query.respuesta.toLowerCase() === req.quiz.respuesta.toLowerCase()){
			resultado = 'Correcto';
		}
		res.render('quizes/answer',	{quiz: req.quiz, respuesta: resultado, errors: []});
};

//Get /quizes/statistics
exports.statistics = function(req,res){

/*Funciona en Local
	----------------------

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 	models.Quiz.count(
		 		{ distinct:"Comments.QuizId",
		 		  where: ["Comments.QuizId not like ?", "NULL"],
		 		  include: [models.Comment]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

	------------------------
*/

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 models.Quiz.count(
		 		{
		 			distinct:"Quiz.id",
		 		  where: ["Comments.QuizId not like ?", "NULL"],
		 		  include: [{model: models.Comment,
		 		  			attributes:["QuizId"]}]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

};

/*
function contarComentarios(){
	models.Comment.count().then(function(nc){
		 c = nc;
	});
	return c ;
};
function contarPreguntas(){
	models.Quiz.count().then(function(q){
		 c = q;
	});
	return c ;
};
*/<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {
  browsers,
  flow,
  jsx,
  node,
  platforms,
  react,
  typeScript,
} from '../flags'
import {CONFIGS_DIR, PACKAGE_DIR} from '../paths'
import {join} from 'path'
import {exitOnError, runCommandSync} from '../system'
import {exitOnPackageNotFound} from '../util'

const CONFIG_PATH = join(CONFIGS_DIR, 'eslint', 'index.js')
const BASIC_ARGS = [
  `--config "${CONFIG_PATH}"`,
  `"${join(PACKAGE_DIR, 'src')}"`,
]

function builder(yargs) {
  browsers(yargs)
  flow(yargs)
  jsx(yargs)
  node(yargs)
  platforms(yargs)
  react(yargs)
  typeScript(yargs)

  yargs.option('fix', {
    description: 'Fix lint errors.',
  })
}

function lintSources(args) {
  let eslintArgs = [
    '--ignore-pattern "src/**/__tests__"',
    '--ignore-pattern "src/**/__tests__/**"',
    ...BASIC_ARGS,
  ]

  let {fix} = args
  if (fix)
    eslintArgs.push('--fix')

  return runCommandSync('eslint', {
    args: eslintArgs,
    env: args,
  })
}

function lintTests(args) {
  let eslintArgs = [
    '--ignore-pattern "src/**"',
    '--ignore-pattern "!**/__tests__"',
    '--ignore-pattern "!**/__tests__/**"',
    ...BASIC_ARGS,
  ]

  let {fix} = args
  if (fix)
    eslintArgs.push('--fix')

  return runCommandSync('eslint', {
    args: eslintArgs,
    env: {...args, jest: true}
  })
}

function handler(args) {
  exitOnPackageNotFound()

  console.log()
  console.log('[0/2] Linting sources...')
  let resultSources = lintSources(args)
  console.log('[1/2] Linting tests...')
  let resultTests = lintTests(args)
  console.log('[2/2] Done linting.')

  exitOnError(resultSources)
  exitOnError(resultTests)
}

export default {
  command: 'lint',
  description: 'Run ESLint',
  builder,
  handler,
}
<commit_msg>Fix linting error<commit_after>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {
  browsers,
  flow,
  jsx,
  node,
  platforms,
  react,
  typeScript,
} from '../flags'
import {CONFIGS_DIR, PACKAGE_DIR} from '../paths'
import {join} from 'path'
import {exitOnError, runCommandSync} from '../system'
import {exitOnPackageNotFound} from '../util'

const CONFIG_PATH = join(CONFIGS_DIR, 'eslint', 'index.js')
const BASIC_ARGS = [
  `--config "${CONFIG_PATH}"`,
  `"${join(PACKAGE_DIR, 'src')}"`,
]

function builder(yargs) {
  browsers(yargs)
  flow(yargs)
  jsx(yargs)
  node(yargs)
  platforms(yargs)
  react(yargs)
  typeScript(yargs)

  yargs.option('fix', {
    description: 'Fix lint errors.',
  })
}

function lintSources(args) {
  let eslintArgs = [
    '--ignore-pattern "src/**/__tests__"',
    '--ignore-pattern "src/**/__tests__/**"',
    ...BASIC_ARGS,
  ]

  let {fix} = args
  if (fix)
    eslintArgs.push('--fix')

  return runCommandSync('eslint', {
    args: eslintArgs,
    env: args,
  })
}

function lintTests(args) {
  let eslintArgs = [
    '--ignore-pattern "src/**"',
    '--ignore-pattern "!**/__tests__"',
    '--ignore-pattern "!**/__tests__/**"',
    ...BASIC_ARGS,
  ]

  let {fix} = args
  if (fix)
    eslintArgs.push('--fix')

  return runCommandSync('eslint', {
    args: eslintArgs,
    env: {...args, jest: true},
  })
}

function handler(args) {
  exitOnPackageNotFound()

  console.log()
  console.log('[0/2] Linting sources...')
  let resultSources = lintSources(args)
  console.log('[1/2] Linting tests...')
  let resultTests = lintTests(args)
  console.log('[2/2] Done linting.')

  exitOnError(resultSources)
  exitOnError(resultTests)
}

export default {
  command: 'lint',
  description: 'Run ESLint',
  builder,
  handler,
}
<|endoftext|>


<commit_before>/**
 * Crowi context class for client
 */

import axios from 'axios'
import io from 'socket.io-client'

export default class Crowi {
  constructor(context, window) {
    this.context = context
    this.config = {}
    this.csrfToken = context.csrfToken

    this.window = window
    this.location = window.location || {}
    this.document = window.document || {}
    this.localStorage = window.localStorage || {}

    this.fetchUsers = this.fetchUsers.bind(this)
    this.apiGet = this.apiGet.bind(this)
    this.apiPost = this.apiPost.bind(this)
    this.apiRequest = this.apiRequest.bind(this)

    // FIXME
    this.me = context.me

    this.users = []
    this.userByName = {}
    this.userById = {}
    this.draft = {}

    this.recoverData()

    this.socket = io()
  }

  getContext() {
    return context
  }

  setConfig(config) {
    this.config = config
  }

  getConfig() {
    return this.config
  }

  getWebSocket() {
    return this.socket
  }

  recoverData() {
    const keys = ['userByName', 'userById', 'users', 'draft']

    keys.forEach(key => {
      if (this.localStorage[key]) {
        try {
          this[key] = JSON.parse(this.localStorage[key])
        } catch (e) {
          this.localStorage.removeItem(key)
        }
      }
    })
  }

  fetchUsers() {
    const interval = 1000 * 60 * 15 // 15min
    const currentTime = new Date()
    if (this.localStorage.lastFetched && interval > currentTime - new Date(this.localStorage.lastFetched)) {
      return
    }

    this.apiGet('/users.list', {})
      .then(data => {
        this.users = data.users
        this.localStorage.users = JSON.stringify(data.users)

        let userByName = {}
        let userById = {}
        for (let i = 0; i < data.users.length; i++) {
          const user = data.users[i]
          userByName[user.username] = user
          userById[user._id] = user
        }
        this.userByName = userByName
        this.localStorage.userByName = JSON.stringify(userByName)

        this.userById = userById
        this.localStorage.userById = JSON.stringify(userById)

        this.localStorage.lastFetched = new Date()
      })
      .catch(err => {
        this.localStorage.removeItem('lastFetched')
        // ignore errors
      })
  }

  clearDraft(path) {
    delete this.draft[path]
    this.localStorage.draft = JSON.stringify(this.draft)
  }

  saveDraft(path, body) {
    this.draft[path] = body
    this.localStorage.draft = JSON.stringify(this.draft)
  }

  findDraft(path) {
    if (this.draft && this.draft[path]) {
      return this.draft[path]
    }

    return null
  }

  findUserById(userId) {
    if (this.userById && this.userById[userId]) {
      return this.userById[userId]
    }

    return null
  }

  findUserByIds(userIds) {
    let users = []
    for (let userId of userIds) {
      let user = this.findUserById(userId)
      if (user) {
        users.push(user)
      }
    }

    return users
  }

  findUser(username) {
    if (this.userByName && this.userByName[username]) {
      return this.userByName[username]
    }

    return null
  }

  apiGet(path, params) {
    return this.apiRequest('get', path, { params: params })
  }

  apiPost(path, params) {
    if (!params._csrf) {
      params._csrf = this.csrfToken
    }

    return this.apiRequest('post', path, params)
  }

  apiRequest(method, path, params) {
    return new Promise((resolve, reject) => {
      axios[method](`/_api${path}`, params)
        .then(res => {
          if (res.data.ok) {
            resolve(res.data)
          } else {
            // FIXME?
            reject(new Error(res.error))
          }
        })
        .catch(res => {
          // FIXME?
          reject(new Error('Error'))
        })
    })
  }

  static escape(html, encode) {
    return html
      .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/"/g, '"')
      .replace(/'/g, ''')
  }

  static unescape(html) {
    return html.replace(/&([#\w]+);/g, function(_, n) {
      n = n.toLowerCase()
      if (n === 'colon') return ':'
      if (n.charAt(0) === '#') {
        return n.charAt(1) === 'x'
          ? String.fromCharCode(parseInt(n.substring(2), 16))
          : String.fromCharCode(+n.substring(1))
      }
      return ''
    })
  }
}
<commit_msg>Fix an instance<commit_after>/**
 * Crowi context class for client
 */

import axios from 'axios'
import io from 'socket.io-client'

export default class Crowi {
  constructor(context, window) {
    this.context = context
    this.config = {}
    this.csrfToken = context.csrfToken

    this.window = window
    this.location = window.location || {}
    this.document = window.document || {}
    this.localStorage = window.localStorage || {}

    this.fetchUsers = this.fetchUsers.bind(this)
    this.apiGet = this.apiGet.bind(this)
    this.apiPost = this.apiPost.bind(this)
    this.apiRequest = this.apiRequest.bind(this)

    // FIXME
    this.me = context.me

    this.users = []
    this.userByName = {}
    this.userById = {}
    this.draft = {}

    this.recoverData()

    this.socket = io()
  }

  getContext() {
    return context
  }

  setConfig(config) {
    this.config = config
  }

  getConfig() {
    return this.config
  }

  getWebSocket() {
    return this.socket
  }

  recoverData() {
    const keys = ['userByName', 'userById', 'users', 'draft']

    keys.forEach(key => {
      if (this.localStorage[key]) {
        try {
          this[key] = JSON.parse(this.localStorage[key])
        } catch (e) {
          this.localStorage.removeItem(key)
        }
      }
    })
  }

  fetchUsers() {
    const interval = 1000 * 60 * 15 // 15min
    const currentTime = new Date()
    if (this.localStorage.lastFetched && interval > currentTime - new Date(this.localStorage.lastFetched)) {
      return
    }

    this.apiGet('/users.list', {})
      .then(data => {
        this.users = data.users
        this.localStorage.users = JSON.stringify(data.users)

        let userByName = {}
        let userById = {}
        for (let i = 0; i < data.users.length; i++) {
          const user = data.users[i]
          userByName[user.username] = user
          userById[user._id] = user
        }
        this.userByName = userByName
        this.localStorage.userByName = JSON.stringify(userByName)

        this.userById = userById
        this.localStorage.userById = JSON.stringify(userById)

        this.localStorage.lastFetched = new Date()
      })
      .catch(err => {
        this.localStorage.removeItem('lastFetched')
        // ignore errors
      })
  }

  clearDraft(path) {
    delete this.draft[path]
    this.localStorage.draft = JSON.stringify(this.draft)
  }

  saveDraft(path, body) {
    this.draft[path] = body
    this.localStorage.draft = JSON.stringify(this.draft)
  }

  findDraft(path) {
    if (this.draft && this.draft[path]) {
      return this.draft[path]
    }

    return null
  }

  findUserById(userId) {
    if (this.userById && this.userById[userId]) {
      return this.userById[userId]
    }

    return null
  }

  findUserByIds(userIds) {
    let users = []
    for (let userId of userIds) {
      let user = this.findUserById(userId)
      if (user) {
        users.push(user)
      }
    }

    return users
  }

  findUser(username) {
    if (this.userByName && this.userByName[username]) {
      return this.userByName[username]
    }

    return null
  }

  apiGet(path, params) {
    return this.apiRequest('get', path, { params: params })
  }

  apiPost(path, params) {
    if (!params._csrf) {
      params._csrf = this.csrfToken
    }

    return this.apiRequest('post', path, params)
  }

  apiRequest(method, path, params) {
    return new Promise((resolve, reject) => {
      axios[method](`/_api${path}`, params)
        .then(({ data }) => {
          if (data.ok) {
            resolve(data)
          } else {
            // FIXME?
            reject(new Error(data.error))
          }
        })
        .catch(res => {
          // FIXME?
          reject(new Error('Error'))
        })
    })
  }

  static escape(html, encode) {
    return html
      .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/"/g, '"')
      .replace(/'/g, ''')
  }

  static unescape(html) {
    return html.replace(/&([#\w]+);/g, function(_, n) {
      n = n.toLowerCase()
      if (n === 'colon') return ':'
      if (n.charAt(0) === '#') {
        return n.charAt(1) === 'x'
          ? String.fromCharCode(parseInt(n.substring(2), 16))
          : String.fromCharCode(+n.substring(1))
      }
      return ''
    })
  }
}
<|endoftext|>


<commit_before>module.exports = {
  extends: 'exponent/react',
  globals: {
    window: true,
  },
  env: {
    jasmine: true,
  },
};
<commit_msg>Remove .eslintrc.js to match internal<commit_after><|endoftext|>


<commit_before>// Raf polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// Adapted by Joe Esposito
// Origin: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
//         http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// MIT license

var raf = (function () {
  var requestAnimationFrame = typeof window !== 'undefined' ? window.requestAnimationFrame : null;
  var cancelAnimationFrame = typeof window !== 'undefined' ? window.cancelAnimationFrame : null;

  var vendors = ['ms', 'moz', 'webkit', 'o'];
  for(var x = 0; x < vendors.length && !requestAnimationFrame; ++x) {
    requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
  }

  if (!requestAnimationFrame) {
    var lastTime = 0;
    requestAnimationFrame = function(callback) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };

    cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
  }

  return {
    requestAnimationFrame: function(callback) { return requestAnimationFrame(callback); },
    cancelAnimationFrame: function(requestID) { return cancelAnimationFrame(requestID); }
  };
})();

module.exports = raf;
<commit_msg>Check for 'window' global in RAF and cleanup.<commit_after>// Raf polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
// Adapted to CommonJS by Joe Esposito
// Origin: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
//         https://gist.github.com/paulirish/1579671

var raf = (function () {
  var requestAnimationFrame = null;
  var cancelAnimationFrame = null;

  if (typeof window !== 'undefined') {
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    requestAnimationFrame = window.requestAnimationFrame;
    cancelAnimationFrame = window.cancelAnimationFrame;
    for(var x = 0; x < vendors.length && !requestAnimationFrame; ++x) {
      requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
      cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }
  }

  if (!requestAnimationFrame) {
    var lastTime = 0;
    requestAnimationFrame = function(callback) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };
    cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
  }

  return {
    requestAnimationFrame: function(callback) { return requestAnimationFrame(callback); },
    cancelAnimationFrame: function(requestID) { return cancelAnimationFrame(requestID); }
  };
})();

module.exports = raf;
<|endoftext|>


<commit_before>module.exports = {
   parser: 'babel-eslint',
   extends: 'eslint:recommended',
   env: {
      browser: true
   },
   rules: {
      semi: 2,
      strict: 0,
      'no-unused-vars': ["error", { "varsIgnorePattern": "MStepper" }]
   }
}
<commit_msg>Added env node to eslint<commit_after>module.exports = {
   parser: 'babel-eslint',
   extends: 'eslint:recommended',
   env: {
      browser: true,
      node: true
   },
   rules: {
      semi: 2,
      strict: 0,
      'no-unused-vars': ["error", { "varsIgnorePattern": "MStepper" }]
   }
}
<|endoftext|>


<commit_before>'use strict';

describe('Controller: SinglePlayerCtrl', function () {
  // load the controller's module
  beforeEach(module('twistedHangmanApp'));

  var ctrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    ctrl = $controller('SinglePlayerCtrl', {
      $scope: scope
    });
  }));

  it('initializes', function () {
  });
});

describe('Controller: TwoPlayerCtrl', function () {
  // load the controller's module
  beforeEach(module('twistedHangmanApp'));

  var ctrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    ctrl = $controller('TwoPlayerCtrl', {
      $scope: scope
    });
  }));

  it('initializes', function () {
  });
});

describe('Controller: MultiPlayerCtrl', function () {
  // load the controller's module
  beforeEach(module('twistedHangmanApp'));

  var ctrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    ctrl = $controller('MultiPlayerCtrl', {
      $scope: scope
    });
  }));

  it('initializes', function () {
  });
});
<commit_msg>tests<commit_after>'use strict';

describe('Controller: CreateCtrl', function () {
  // load the controller's module
  beforeEach(module('twistedHangmanApp'));

  var ctrl, scope, http;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, $httpBackend) {
    scope = $rootScope.$new();
    http = $httpBackend;
    ctrl = $controller('CreateCtrl', {
      $scope: scope
    });
  }));

  it('initializes', function () {
    expect(scope.url).toEqual('/api/player/MANUAL1/new');
    expect(scope.thieving).toEqual('Thieving');
    expect(scope.drawGallows).toEqual('');
    expect(scope.drawFace).toEqual('');
    expect(scope.gamePace).toEqual('');

    expect(scope.playerCount).toEqual('SinglePlayer');
    expect(scope.players).toEqual([]);
    expect(scope.gamePace).toEqual('');
    expect(scope.puzzleSetter).toEqual('SystemPuzzles');
    expect(scope.winners).toEqual('SingleWinner');
    expect(scope.h2hEnabled).toBe(false);
    expect(scope.alternatingEnabled).toBe(false);
    expect(scope.allFinishedEnabled).toBe(false);
    expect(scope.turnBasedEnabled).toBe(false);
  });

  it('resets to single player', function () {
    //  should not change
    scope.thieving = '';
    scope.drawGallows = 'DrawGallows';
    scope.drawFace = 'DrawFace';

    //  should change
    scope.playerCount = 'X';
    scope.gamePace = 'TurnBased';
    scope.players = ['1'];
    scope.puzzleSetter = '';
    scope.winners = '';
    scope.h2hEnabled = true;
    scope.alternatingEnabled = true;
    scope.alternatingEnabled = true;
    scope.turnBasedEnabled = true;

    scope.setSinglePlayer();

    expect(scope.url).toEqual('/api/player/MANUAL1/new');
    expect(scope.thieving).toEqual('');
    expect(scope.drawGallows).toEqual('DrawGallows');
    expect(scope.drawFace).toEqual('DrawFace');
    expect(scope.gamePace).toEqual('');

    expect(scope.playerCount).toEqual('SinglePlayer');
    expect(scope.players).toEqual([]);
    expect(scope.gamePace).toEqual('');
    expect(scope.puzzleSetter).toEqual('SystemPuzzles');
    expect(scope.winners).toEqual('SingleWinner');
    expect(scope.h2hEnabled).toBe(false);
    expect(scope.alternatingEnabled).toBe(false);
    expect(scope.allFinishedEnabled).toBe(false);
    expect(scope.turnBasedEnabled).toBe(false);
  });
});

<|endoftext|>


<commit_before>/**
* Meadow Endpoint - Create a Record
*
* @license MIT
*
* @author Steven Velozo <steven@velozo.com>
* @module Meadow
*/
/**
* Create a record using the Meadow DAL object
*/

var libAsync = require('async');

var doAPICreateEndpoint = function(pRequest, pResponse, fNext)
{
	// This state is the requirement for the UserRoleIndex value in the UserSession object... processed by default as >=
	// The default here is that any authenticated user can use this endpoint.
	pRequest.EndpointAuthorizationRequirement = pRequest.EndpointAuthorizationLevels.Create;

	if (pRequest.CommonServices.authorizeEndpoint(pRequest, pResponse, fNext) === false)
	{
		// If this endpoint fails, it's sent an error automatically.
		return;
	}

	libAsync.waterfall(
		[
			function(fStageComplete)
			{
				//1. Validate request body to ensure it is a valid record
				if (typeof(pRequest.body) !== 'object')
				{
					return pRequest.CommonServices.sendError('Record create failure - a valid record is required.', pRequest, pResponse, fNext);
				}

				pRequest.Record = pRequest.body;
<<<<<<< HEAD
				//Make sure record gets created with a customerID
				if (!pRequest.Record.hasOwnProperty('IDCustomer') &&
					pRequest.DAL.jsonSchema.properties.hasOwnProperty('IDCustomer'))
				{
					pRequest.Record.IDCustomer = pRequest.UserSession.CustomerID || 0;
				}
=======
                //Make sure record gets created with a customerID
                if (!pRequest.Record.hasOwnProperty('IDCustomer') &&
                    pRequest.DAL.jsonSchema.properties.hasOwnProperty('IDCustomer'))
                {
                    pRequest.Record.IDCustomer = pRequest.UserSession.CustomerID || 0;
                }
>>>>>>> stevenvelozo/master

				return fStageComplete(null);
			},
			function(fStageComplete)
			{
				pRequest.Authorizers.authorizeRequest('Create', pRequest, fStageComplete);
			},
			function(fStageComplete)
			{
				pRequest.BehaviorModifications.runBehavior('Create-PreOperation', pRequest, fStageComplete);
			},
			function (fStageComplete)
			{
				if (pRequest.MeadowAuthorization)
				{
					return fStageComplete(false);
				}

				// It looks like this record was not authorized.  Send an error.
				return fStageComplete({Code:405,Message:'UNAUTHORIZED ACCESS IS NOT ALLOWED'});
			},
			function(fStageComplete)
			{
				//3. Prepare create query
				var tmpQuery = pRequest.DAL.query;

				tmpQuery.setIDUser(pRequest.UserSession.UserID);
				tmpQuery.addRecord(pRequest.Record);

				return fStageComplete(null, tmpQuery);
			},
			// 3. INJECT: Query configuration
			function (tmpQuery, fStageComplete)
			{
				pRequest.Query = tmpQuery;
				pRequest.BehaviorModifications.runBehavior('Create-QueryConfiguration', pRequest, fStageComplete);
			},
			function(fStageComplete)
			{
				//4. Do the create operation
				pRequest.DAL.doCreate(pRequest.Query,
					function(pError, pQuery, pReadQuery, pRecord)
					{
						if (!pRecord)
						{
							return fStageComplete('Error in DAL create: '+pError);
						}

						pRequest.Record = pRecord;

						pRequest.CommonServices.log.info('Created a record with ID '+pRecord[pRequest.DAL.defaultIdentifier]+'.', {SessionID:pRequest.UserSession.SessionID, RequestID:pRequest.RequestUUID, RequestURL:pRequest.url, Action:pRequest.DAL.scope+'-Create'}, pRequest);

						return fStageComplete(null);
					});
			},
			function(fStageComplete)
			{
				return pRequest.BehaviorModifications.runBehavior('Create-PostOperation', pRequest, fStageComplete);
			},
			function(fStageComplete)
			{
				//5. Respond with the new record
				pResponse.send(pRequest.Record);
				return fStageComplete(null);
			}
		], function(pError)
		{
			if (pError)
			{
				return pRequest.CommonServices.sendCodedError('Error creating a record.', pError, pRequest, pResponse, fNext);
			}

			return fNext();
		});
};

module.exports = doAPICreateEndpoint;<commit_msg>revert<commit_after>/**
* Meadow Endpoint - Create a Record
*
* @license MIT
*
* @author Steven Velozo <steven@velozo.com>
* @module Meadow
*/
/**
* Create a record using the Meadow DAL object
*/

var libAsync = require('async');

var doAPICreateEndpoint = function(pRequest, pResponse, fNext)
{
	// This state is the requirement for the UserRoleIndex value in the UserSession object... processed by default as >=
	// The default here is that any authenticated user can use this endpoint.
	pRequest.EndpointAuthorizationRequirement = pRequest.EndpointAuthorizationLevels.Create;

	if (pRequest.CommonServices.authorizeEndpoint(pRequest, pResponse, fNext) === false)
	{
		// If this endpoint fails, it's sent an error automatically.
		return;
	}

	libAsync.waterfall(
		[
			function(fStageComplete)
			{
				//1. Validate request body to ensure it is a valid record
				if (typeof(pRequest.body) !== 'object')
				{
					return pRequest.CommonServices.sendError('Record create failure - a valid record is required.', pRequest, pResponse, fNext);
				}

				pRequest.Record = pRequest.body;
                //Make sure record gets created with a customerID
                if (!pRequest.Record.hasOwnProperty('IDCustomer') &&
                    pRequest.DAL.jsonSchema.properties.hasOwnProperty('IDCustomer'))
                {
                    pRequest.Record.IDCustomer = pRequest.UserSession.CustomerID || 0;
                }

				return fStageComplete(null);
			},
			function(fStageComplete)
			{
				pRequest.Authorizers.authorizeRequest('Create', pRequest, fStageComplete);
			},
			function(fStageComplete)
			{
				pRequest.BehaviorModifications.runBehavior('Create-PreOperation', pRequest, fStageComplete);
			},
			function (fStageComplete)
			{
				if (pRequest.MeadowAuthorization)
				{
					return fStageComplete(false);
				}

				// It looks like this record was not authorized.  Send an error.
				return fStageComplete({Code:405,Message:'UNAUTHORIZED ACCESS IS NOT ALLOWED'});
			},
			function(fStageComplete)
			{
				//3. Prepare create query
				var tmpQuery = pRequest.DAL.query;

				tmpQuery.setIDUser(pRequest.UserSession.UserID);
				tmpQuery.addRecord(pRequest.Record);

				return fStageComplete(null, tmpQuery);
			},
			// 3. INJECT: Query configuration
			function (tmpQuery, fStageComplete)
			{
				pRequest.Query = tmpQuery;
				pRequest.BehaviorModifications.runBehavior('Create-QueryConfiguration', pRequest, fStageComplete);
			},
			function(fStageComplete)
			{
				//4. Do the create operation
				pRequest.DAL.doCreate(pRequest.Query,
					function(pError, pQuery, pReadQuery, pRecord)
					{
						if (!pRecord)
						{
							return fStageComplete('Error in DAL create: '+pError);
						}

						pRequest.Record = pRecord;

						pRequest.CommonServices.log.info('Created a record with ID '+pRecord[pRequest.DAL.defaultIdentifier]+'.', {SessionID:pRequest.UserSession.SessionID, RequestID:pRequest.RequestUUID, RequestURL:pRequest.url, Action:pRequest.DAL.scope+'-Create'}, pRequest);

						return fStageComplete(null);
					});
			},
			function(fStageComplete)
			{
				return pRequest.BehaviorModifications.runBehavior('Create-PostOperation', pRequest, fStageComplete);
			},
			function(fStageComplete)
			{
				//5. Respond with the new record
				pResponse.send(pRequest.Record);
				return fStageComplete(null);
			}
		], function(pError)
		{
			if (pError)
			{
				return pRequest.CommonServices.sendCodedError('Error creating a record.', pError, pRequest, pResponse, fNext);
			}

			return fNext();
		});
};

module.exports = doAPICreateEndpoint;<|endoftext|>


<commit_before>var fs = require('fs');
var cheerio = require('cheerio');
var file = process.argv[2];
var doctemplatetype = process.argv[3];

fs.readFile(file, function processTemplates (err, contents) {
  $ = cheerio.load(contents, {
          xmlMode: true
        });

  //vars for target styles based on doctemplatetype
  if (doctemplatetype == 'rsuite') {
    var bookmakerinstruction_style = "Bookmaker-Processing-InstructionBpi";
    var imageholder_style = "Image-PlacementImg";
  } else {
    var bookmakerinstruction_style = "BookmakerProcessingInstructionbpi";
    var imageholder_style = "Illustrationholderill";
  }

  // evaluate processing instructions
  $("p." + bookmakerinstruction_style).each(function () {
      var val = $( this ).text();
      if (val == "Ebook-only") {
        $( this ).parent().attr('data-format','ebook');
      } else if (val == "Print-only") {
        $( this ).parent().attr('data-format','print');
      } else if (val.indexOf("TRIM:") > -1) {
        var trimsize = val.split(":").pop().replace(/\s+/g, '');
        trimsize = trimsize.replace(/x/g, ' ');
        console.log("TRIM: " + trimsize);
        var metabooktrim = '<meta name="size" content="' + trimsize + '"/>';
        $('head').append(metabooktrim);
      } else if (val.indexOf("TOC:") > -1) {
        var toctype = val.split(":").pop().toLowerCase().replace(/\s+/g, '');
        console.log("TOC: " + toctype);
        var metatoctype = '<meta name="toc" content="' + toctype + '"/>';
        $('head').append(metatoctype);
      } else if (val.indexOf("DATA:") > -1) {
        var datavalue = val.split("DATA:").pop().replace(/^\s+/g, '');
        var datatype = val.split("DATA:").shift().toLowerCase().replace(/\s+/g, '');
        console.log(datatype + ": " + datavalue);
        var metabookdata = '<meta name="' + datatype + '" content="' + datavalue + '"/>';
        $('head').append(metabookdata);
      } else if (val.indexOf("STYLES:") > -1) {
        var el = $(this);
        var stylearr = val.split(":").pop().split(" ").filter(Boolean);
        for (i = 0; i < stylearr.length; i++) {
          $(el).prev().addClass(stylearr[i]);
        };
      } else if (val.indexOf("LINKTO:") > -1) {
        var linkdest = val.split("LINKTO:").pop().replace(/^\s+/g, '');
        var that = this.previousSibling;
        var el2 = $("");
        $(that).prepend(el2);
        $(".temp").attr('href', linkdest);
        while (that.firstChild.nextSibling) {
            $(".temp").prepend(that.firstChild.nextSibling);
        }
        $(".temp").removeClass("temp");
      } else if (val.indexOf("IMAGE:") > -1) {
        if (val.indexOf("global") > -1) {
          var prev = $(this).prev();
          var eltype = $(prev).attr('class');
          var imagefile = val.split(":").pop().trim().split(" ").shift();
          var imagetag = "

";
          $("*[class=" + eltype + "]").after(imagetag);
          $("*[class=" + eltype + "]").remove();
          // This code will insert the custom image inside the existing paragraph, instead of as a standard figure tag.
          //var imagetag = "";
          //$("*[class=" + eltype + "]").empty().append(imagetag);
          //$("*[class=" + eltype + "]").addClass("customimage");
        } else {
          var prev = $(this).prev();
          var imagefile = val.split(":").pop().trim().split(" ").shift();
          var imagetag = "

";
          $(prev).after(imagetag);
          $(prev).remove();
          // This code will insert the custom image inside the existing paragraph, instead of as a standard figure tag.
          //var imagetag = "";
          //$(prev).empty().append(imagetag);
          //$(prev).addClass("customimage");
        }
      }
      $(this).remove();
  });

  $("section, div").children( ".notoc" ).parent().addClass("notoc");

  var output = $.html();
    fs.writeFile(file, output, function(err) {
	    if(err) {
	        return console.log(err);
	    }

	    console.log("Processing instructions have been evaluated!");
	});
});
<commit_msg>adding pitstop as a receivable PI<commit_after>var fs = require('fs');
var cheerio = require('cheerio');
var file = process.argv[2];
var doctemplatetype = process.argv[3];

fs.readFile(file, function processTemplates (err, contents) {
  $ = cheerio.load(contents, {
          xmlMode: true
        });

  //vars for target styles based on doctemplatetype
  if (doctemplatetype == 'rsuite') {
    var bookmakerinstruction_style = "Bookmaker-Processing-InstructionBpi";
    var imageholder_style = "Image-PlacementImg";
  } else {
    var bookmakerinstruction_style = "BookmakerProcessingInstructionbpi";
    var imageholder_style = "Illustrationholderill";
  }

  // evaluate processing instructions
  $("p." + bookmakerinstruction_style).each(function () {
      var val = $( this ).text();
      if (val == "Ebook-only") {
        $( this ).parent().attr('data-format','ebook');
      } else if (val == "Print-only") {
        $( this ).parent().attr('data-format','print');
      } else if (val.indexOf("TRIM:") > -1) {
        var trimsize = val.split(":").pop().replace(/\s+/g, '');
        trimsize = trimsize.replace(/x/g, ' ');
        console.log("TRIM: " + trimsize);
        var metabooktrim = '<meta name="size" content="' + trimsize + '"/>';
        $('head').append(metabooktrim);
      } else if (val.indexOf("TOC:") > -1) {
        var toctype = val.split(":").pop().toLowerCase().replace(/\s+/g, '');
        console.log("TOC: " + toctype);
        var metatoctype = '<meta name="toc" content="' + toctype + '"/>';
        $('head').append(metatoctype);
      } else if (val.indexOf("PITSTOP:") > -1) {
        var pitstopval = val.split(":").pop().toLowerCase().replace(/\s+/g, '');
        console.log("PITSTOP: " + pitstopval);
        var metapitstopval = '<meta name="pitstop" content="' + pitstopval + '"/>';
        $('head').append(metapitstopval);
      } else if (val.indexOf("DATA:") > -1) {
        var datavalue = val.split("DATA:").pop().replace(/^\s+/g, '');
        var datatype = val.split("DATA:").shift().toLowerCase().replace(/\s+/g, '');
        console.log(datatype + ": " + datavalue);
        var metabookdata = '<meta name="' + datatype + '" content="' + datavalue + '"/>';
        $('head').append(metabookdata);
      } else if (val.indexOf("STYLES:") > -1) {
        var el = $(this);
        var stylearr = val.split(":").pop().split(" ").filter(Boolean);
        for (i = 0; i < stylearr.length; i++) {
          $(el).prev().addClass(stylearr[i]);
        };
      } else if (val.indexOf("LINKTO:") > -1) {
        var linkdest = val.split("LINKTO:").pop().replace(/^\s+/g, '');
        var that = this.previousSibling;
        var el2 = $("");
        $(that).prepend(el2);
        $(".temp").attr('href', linkdest);
        while (that.firstChild.nextSibling) {
            $(".temp").prepend(that.firstChild.nextSibling);
        }
        $(".temp").removeClass("temp");
      } else if (val.indexOf("IMAGE:") > -1) {
        if (val.indexOf("global") > -1) {
          var prev = $(this).prev();
          var eltype = $(prev).attr('class');
          var imagefile = val.split(":").pop().trim().split(" ").shift();
          var imagetag = "

";
          $("*[class=" + eltype + "]").after(imagetag);
          $("*[class=" + eltype + "]").remove();
          // This code will insert the custom image inside the existing paragraph, instead of as a standard figure tag.
          //var imagetag = "";
          //$("*[class=" + eltype + "]").empty().append(imagetag);
          //$("*[class=" + eltype + "]").addClass("customimage");
        } else {
          var prev = $(this).prev();
          var imagefile = val.split(":").pop().trim().split(" ").shift();
          var imagetag = "

";
          $(prev).after(imagetag);
          $(prev).remove();
          // This code will insert the custom image inside the existing paragraph, instead of as a standard figure tag.
          //var imagetag = "";
          //$(prev).empty().append(imagetag);
          //$(prev).addClass("customimage");
        }
      }
      $(this).remove();
  });

  $("section, div").children( ".notoc" ).parent().addClass("notoc");

  var output = $.html();
    fs.writeFile(file, output, function(err) {
	    if(err) {
	        return console.log(err);
	    }

	    console.log("Processing instructions have been evaluated!");
	});
});
<|endoftext|>


<commit_before>import { createLocalVue, mount } from '@vue/test-utils';
import L from 'leaflet';
import LMarker from '@/components/LMarker.vue';
import LMap from '@/components/LMap.vue';

const localVue = createLocalVue();

function getWrapper (propsData) {
  const ParentMapVm = mount(LMap, {
    localVue
  }).vm;

  const wrapper = mount({
    ...LMarker,
    // trick from here https://github.com/vuejs/vue-test-utils/issues/560#issuecomment-461865315
    created () {
      this.$parent = ParentMapVm;
    }
  }, {
    localVue,
    propsData,
    sync: false // avoid warning, see
    // Removing sync mode #1137 https://github.com/vuejs/vue-test-utils/issues/1137
  });
  return wrapper;
}

describe('LMarker.vue', () => {
  test('LMarker.vue change prop latLng', async () => {
    const initLatlng = L.latLng([11, 22]);
    const wrapper = getWrapper({
      latLng: initLatlng
    });
    expect(wrapper.exists()).toBe(true);
    expect(wrapper.vm.mapObject.getLatLng().equals(initLatlng)).toBe(true);
    const newLatLng = L.latLng([1, 1]);
    wrapper.setProps({ latLng: newLatLng });
    await wrapper.vm.$nextTick();
    const curLatLng = wrapper.vm.mapObject.getLatLng();
    expect(curLatLng.equals(newLatLng)).toBe(true);
  });
});
<commit_msg>added getWrapperWithMap for wrap map component with root map<commit_after>import { createLocalVue, mount } from '@vue/test-utils';
import L from 'leaflet';
import LMarker from '@/components/LMarker.vue';
import LMap from '@/components/LMap.vue';

const localVue = createLocalVue();

function getWrapperWithMap (component, propsData, mountOptions) {
  const mapWrapper = mount(LMap, {
    localVue
  });

  const wrapper = mount({
    ...component,
    // trick from here https://github.com/vuejs/vue-test-utils/issues/560#issuecomment-461865315
    created () {
      this.$parent = mapWrapper.vm;
    }
  }, {
    localVue,
    propsData,
    sync: false, // avoid warning, see
    // Removing sync mode #1137 https://github.com/vuejs/vue-test-utils/issues/1137
    ...mountOptions
  });
  return {
    wrapper,
    mapWrapper
  };
}

describe('LMarker.vue', () => {
  test('LMarker.vue change prop latLng', async () => {
    const initLatlng = L.latLng([11, 22]);
    const wrapperAndMap = getWrapperWithMap(LMarker, {
      latLng: initLatlng
    });
    const wrapper = wrapperAndMap.wrapper;
    expect(wrapper.exists()).toBe(true);
    expect(wrapper.vm.mapObject.getLatLng().equals(initLatlng)).toBe(true);
    const newLatLng = L.latLng([1, 1]);
    wrapper.setProps({ latLng: newLatLng });
    await wrapper.vm.$nextTick();
    const curLatLng = wrapper.vm.mapObject.getLatLng();
    expect(curLatLng.equals(newLatLng)).toBe(true);
  });

  test('LMarker.vue default slot text', async () => {
    const markerText = 'Hello from marker!';
    const wrapperAndMap = getWrapperWithMap(LMarker, {
      latLng: [0, 0]
    }, {
      slots: {
        default: markerText
      }
    });
    const wrapper = wrapperAndMap.wrapper;
    const mapWrapper = wrapperAndMap.mapWrapper;
    expect(mapWrapper.text()).toContain('Leaflet');
    expect(wrapper.exists()).toBe(true);
    await wrapper.vm.$nextTick();
    expect(wrapper.text()).toEqual(markerText);
  });
});
<|endoftext|>


<commit_before>'use strict';

/*{}
*/

/*{
	"title": "Example Schema",
	"type": "object",
	"properties": {
		"firstName": {
			"type": "string"
		},
		"lastName": {
			"type": "string"
		},
		"age": {
			"description": "Age in years",
			"type": "integer",
			"minimum": 0
		}
	},
	"required": ["firstName", "lastName"]
}
 */

function reset() {
}

function clone(obj) {
	 return JSON.parse(JSON.stringify(obj));
}

function hoik(obj,target,key,newKey) {
	if (target && obj && (typeof obj[key] != 'undefined')) {
		if (!newKey) {
			newKey = key;
		}
		target[newKey] = clone(obj[key]);
		delete obj[key];
	}
}

function rename(obj,key,newName) {
	obj[newName] = obj[key];
	delete obj[key];
}

function mandate(obj,parent,key) {
	if (!parent.required) parent.required = [];
	parent.required.push(obj[key]);
}

function clean(obj,parent,key) {
	if (key == 'xs:element') rename(obj,key,'properties');
	if (key == '@elementFormDefault') delete obj[key];
	if (key == '@targetNamespace') delete obj[key];
	if (key == '@attributeFormDefault') delete obj[key];
	if (key == '@xmlns:xs') delete obj[key];
	if (key == '@xmlns') delete obj[key];

	if (key == 'xs:sequence') {
		hoik(obj,parent,'xs:sequence','properties'); //may leave empty complexType etc to be cleaned up later
	}

	if (key == '@minOccurs') {
		if (obj[key] > 0) mandate(obj,parent,key);
		delete obj[key];
	}
	if (key == '@maxOccurs') {
		delete obj[key];
	}
	//if (key.startsWith('xs:')) delete obj[key];
	if (key.startsWith('xs:')) rename(obj,key,key.replace('xs:','json:')); //temp
	if (key.startsWith('xmlns:')) rename(obj,key,key.replace('xmlns:','json:')); //temp
	if (key.startsWith('@xmlns:')) rename(obj,key,key.replace('@xmlns:','json:')); //temp
	//if (key.startsWith('@')) delete obj[key];
	if (key.startsWith('@')) rename(obj,key,key.replace('@','')); //temp
}

function postProcess(obj,parent,key) {
	if (key == 'json:required') {
		hoik(obj,parent,key,'required'); // as we put it one level too far down, in the properties
	}
	if (key == 'json:additionalProperties') {
		hoik(obj,parent,key,'additionalProperties'); // as we put it one level too far down, in the properties
	}
	if (key.startsWith('@')) {
		hoik(obj,obj.properties,key); // as we put it one level too far up, outside the properties
		if (obj.required) {
			if (!parent.required) {
				hoik(obj,parent,'required'); //?
			}
			else {
				obj.required = obj.required.concat(parent.required);
				delete parent.required;
			}
		}
	}
	if (key == 'ref') {
		obj[key] = '#/definitions/'+obj[key];
		rename(obj,key,'$ref');
	}

	if (key.startsWith('json:')) rename(obj,key,key.replace('json:',''));
}

function isEmpty(obj) {
	if (typeof obj !== 'object') return false;
    for (var prop in obj) {
        if ((obj.hasOwnProperty(prop) && (typeof obj[prop] !== 'undefined'))) {
			return false;
		}
    }
 	return true;
}

function removeEmpties(obj,parent,key) {
	if (isEmpty(obj[key])) {
		delete obj[key];
	}
	else {
		if (Array.isArray(obj[key])) {
			var newArray = [];
			for (var i=0;i<obj[key].length;i++) {
				if (typeof obj[key][i] !== 'undefined') {
					newArray.push(obj[key][i]);
				}
			}
			if (newArray.length == 0) {
				delete obj[key];
			}
			else {
				obj[key] = newArray;
			}
		}
	}
}

function elements(obj,parent,key) {
	var element = obj[key];

	if (typeof element == 'undefined') {
		console.log(key); // TODO what triggers this?
		return false;
	}

	var name = '';
	var type = 'object';
	var isAttribute = (key == 'xs:attribute');

	if (element['@name']) {
		name = element['@name'];
	}

	if ((element['@name']) && (element['@type'])) {
		name = element['@name'];
		type = element['@type'];
	}
	else if ((element['@name']) && (element['xs:simpleType'])) {
		name = element['@name'];
		type = element['xs:simpleType']['xs:restriction']['@base'];
	}

	if (name && type) {
		var orgName = name;
		var minOccurs = 1;
		var maxOccurs = 1;
		if (element['@minOccurs']) minOccurs = element['@minOccurs'];
		if (element['@maxOccurs']) maxOccurs = element['@maxOccurs'];
		if (maxOccurs == 'unbounded') maxOccurs = 2;
		if (isAttribute) {
			name = '@' + name;
			orgName = name;
			name = '@' + name;
			if ((!element['@use']) || (element['@use'] != 'required')) minOccurs = 0;
		}

		/*
			JSON Schema defines seven primitive types for JSON values:

			array   A JSON array.
			boolean A JSON boolean.
			integer A JSON number without a fraction or exponent part.
			number  Any JSON number. Number includes integer.
			null    The JSON null value.
			object  A JSON object.
			string  A JSON string.
		*/
		parent[name] = {};

		if (type == 'xs:integer') type = 'integer';
		if (type == 'xs:string') type = 'string';
		if (type == 'xs:boolean') type = 'boolean';
		if (type == 'xs:date') {
			type = 'string';
			parent[name].pattern = '^[1-9][0-9]{3}-[0-1][0-9]-[0-3][0-9].*';
		}
		if (type == 'xs:dateTime') {
			type = 'string';
			parent[name].pattern = '^[1-9][0-9]{3}-[0-1][0-9]-[0-3][0-9].*';
		}
		if (type == 'xs:positiveInteger') {
			type = 'integer';
			parent[name]["json:minimum"] = 0;
		}
		if (type == 'xs:decimal') type = 'number';
		if (type == 'xs:anyURI') {
			type = 'string';
			parent[name].pattern = '@[a-z]*://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?$@i';
		}

		if (element['xs:simpleType'] && element['xs:simpleType']['xs:restriction'] && element['xs:simpleType']['xs:restriction']['xs:enumeration']) {
			var source = element['xs:simpleType']['xs:restriction']['xs:enumeration'];
			parent[name]["enum"] = [];
			for (var i=0;i<source.length;i++) {
				parent[name]["enum"].push(source[i]);
			}
		}
		else {
			parent[name].type = type;
		}
		// TODO process restrictions, patterns

		if (!isAttribute) parent['json:additionalProperties'] = false;
		if (minOccurs >= 1) {
			if (!parent['json:required']) {
				parent['json:required'] = [];
			}
			parent['json:required'].push(orgName);
	}

		if (maxOccurs > 1) {
			var items = clone(parent[name]);
			parent[name] = {};
			parent[name].type = 'array';
			parent[name].items = items; // like a hoik downwards
		}

		if (type != 'object') delete obj[key];
	}
}

function extractDefinitions(obj,parent,top) {
	if (Array.isArray(obj.properties)) {
		var start = 0;
		if (isEmpty(parent)) start = 1;
		if (!top.definitions) top.definitions = {};
		for (var i=start;i<obj.properties.length;i++) {
			var o = obj.properties[i];
			if (o) {
				top.definitions[o.name] = {};
				top.definitions[o.name].type = 'object';
				top.definitions[o.name].properties = o.properties;
				if (o.required) {
					top.definitions[o.name].required = o.required;
				}
				var isArray = false;
				if (!parent.properties) {
					parent.properties = {};
				}
				if (parent.properties[o.name] && parent.properties[o.name].type) {
					if (parent.properties[o.name].type == 'array') isArray = true;
				}
				parent.properties[o.name] = {};
				if (isArray) {
					parent.properties[o.name].type = 'array';
					parent.properties[o.name].items = {};
					parent.properties[o.name].items['$ref'] = '#/definitions/'+o.name;
				}
				else {
					parent.properties[o.name]['$ref'] = '#/definitions/'+o.name;
				}
			}
		}
		if (start > 0) {
			obj.properties = obj.properties[0];
		}
		else {
			delete obj.properties;
		}
	}
}

function recurse(obj,parent,callback) {
	for (var key in obj) {
		// skip loop if the property is from prototype
		if (!obj.hasOwnProperty(key)) continue;

		var array = Array.isArray(obj);

		if (typeof obj[key] !== 'object') {
			// simple types
		}
		else {
			if (array) {
				for (var i in obj[key]) {
					recurse(obj[key][i],obj[key],callback);
				}
			}
			recurse(obj[key],obj,callback);
		}
		callback(obj,parent,key);

	}
	return obj;
}

module.exports = {
	getJsonSchema : function getJsonSchema(src,title) {
		var obj = clone(src);

		var id = src["xs:schema"]["@targetNamespace"];
		if (!id) {
			id = src["xs:schema"]["@xmlns"];
		}

		//initial root object transformations
		obj.title = title;
		obj.$schema = 'http://json-schema.org/schema#'; //for latest, or 'http://json-schema.org/draft-04/schema#' for v4
		if (id) {
			obj.id = id;
		}
		obj.type = 'object';

		var rootElementName = obj["xs:schema"]["xs:element"]["@name"];
		delete obj["xs:schema"]["xs:element"]["@name"]; // as it doesn't have a type it gets left hanging around
		obj.dummy = {};
		obj.dummy["json:required"] = [];
		obj.dummy["json:required"].push(rootElementName);
		obj.properties = {};
		hoik(obj["xs:schema"],obj.properties,'xs:element',rootElementName)

		recurse(obj,{},function(obj,parent,key) {
			elements(obj,parent,key);
		});

		recurse(obj,{},function(obj,parent,key) {
			clean(obj,parent,key);
		});

		hoik(obj['json:schema'],obj,'object');

		recurse(obj,{},function(obj,parent,key) {
			removeEmpties(obj,parent,key); // first pass
		});
		recurse(obj,{},function(obj,parent,key) {
			postProcess(obj,parent,key);
		});
		recurse(obj,{},function(obj,parent,key) {
			removeEmpties(obj,parent,key); // second pass to clean up anything emptied by first pass
		});

		recurse(obj,{},function(sub,parent,key) {
			extractDefinitions(sub,parent,obj);
		});

		obj.additionalProperties = false;
		return obj;
	}
};<commit_msg>More string types. Map unknown types > definitions<commit_after>'use strict';

/*{}
*/

/*{
	"title": "Example Schema",
	"type": "object",
	"properties": {
		"firstName": {
			"type": "string"
		},
		"lastName": {
			"type": "string"
		},
		"age": {
			"description": "Age in years",
			"type": "integer",
			"minimum": 0
		}
	},
	"required": ["firstName", "lastName"]
}
 */

function reset() {
}

function clone(obj) {
	 return JSON.parse(JSON.stringify(obj));
}

function hoik(obj,target,key,newKey) {
	if (target && obj && (typeof obj[key] != 'undefined')) {
		if (!newKey) {
			newKey = key;
		}
		target[newKey] = clone(obj[key]);
		delete obj[key];
	}
}

function rename(obj,key,newName) {
	obj[newName] = obj[key];
	delete obj[key];
}

function mandate(obj,parent,key) {
	if (!parent.required) parent.required = [];
	parent.required.push(obj[key]);
}

function clean(obj,parent,key) {
	if (key == 'xs:element') rename(obj,key,'properties');
	if (key == '@elementFormDefault') delete obj[key];
	if (key == '@targetNamespace') delete obj[key];
	if (key == '@attributeFormDefault') delete obj[key];
	if (key == '@xmlns:xs') delete obj[key];
	if (key == '@xmlns') delete obj[key];

	if (key == 'xs:sequence') {
		hoik(obj,parent,'xs:sequence','properties'); //may leave empty complexType etc to be cleaned up later
	}

	if (key == '@minOccurs') {
		if (obj[key] > 0) mandate(obj,parent,key);
		delete obj[key];
	}
	if (key == '@maxOccurs') {
		delete obj[key];
	}
	//if (key.startsWith('xs:')) delete obj[key];
	if (key.startsWith('xs:')) rename(obj,key,key.replace('xs:','json:')); //temp
	if (key.startsWith('xmlns:')) rename(obj,key,key.replace('xmlns:','json:')); //temp
	if (key.startsWith('@xmlns:')) rename(obj,key,key.replace('@xmlns:','json:')); //temp
	//if (key.startsWith('@')) delete obj[key];
	if (key.startsWith('@')) rename(obj,key,key.replace('@','')); //temp
}

function postProcess(obj,parent,key) {
	if (key == 'json:required') {
		hoik(obj,parent,key,'required'); // as we put it one level too far down, in the properties
	}
	if (key == 'json:additionalProperties') {
		hoik(obj,parent,key,'additionalProperties'); // as we put it one level too far down, in the properties
	}
	if (key.startsWith('@')) {
		hoik(obj,obj.properties,key); // as we put it one level too far up, outside the properties
		if (obj.required) {
			if (!parent.required) {
				hoik(obj,parent,'required'); //?
			}
			else {
				obj.required = obj.required.concat(parent.required);
				delete parent.required;
			}
		}
	}
	if (key == 'ref') {
		obj[key] = '#/definitions/'+obj[key];
		rename(obj,key,'$ref');
	}

	if (key.startsWith('json:')) rename(obj,key,key.replace('json:',''));
}

function isEmpty(obj) {
	if (typeof obj !== 'object') return false;
    for (var prop in obj) {
        if ((obj.hasOwnProperty(prop) && (typeof obj[prop] !== 'undefined'))) {
			return false;
		}
    }
 	return true;
}

function removeEmpties(obj,parent,key) {
	if (isEmpty(obj[key])) {
		delete obj[key];
	}
	else {
		if (Array.isArray(obj[key])) {
			var newArray = [];
			for (var i=0;i<obj[key].length;i++) {
				if (typeof obj[key][i] !== 'undefined') {
					newArray.push(obj[key][i]);
				}
			}
			if (newArray.length == 0) {
				delete obj[key];
			}
			else {
				obj[key] = newArray;
			}
		}
	}
}

function elements(obj,parent,key) {
	var element = obj[key];

	if (typeof element == 'undefined') {
		console.log(key); // TODO what triggers this?
		return false;
	}

	var name = '';
	var type = 'object';
	var isAttribute = (key == 'xs:attribute');

	if (element['@name']) {
		name = element['@name'];
	}

	if ((element['@name']) && (element['@type'])) {
		name = element['@name'];
		type = element['@type'];
	}
	else if ((element['@name']) && (element['xs:simpleType'])) {
		name = element['@name'];
		type = element['xs:simpleType']['xs:restriction']['@base'];
	}

	if (name && type) {
		var orgName = name;
		var minOccurs = 1;
		var maxOccurs = 1;
		if (element['@minOccurs']) minOccurs = element['@minOccurs'];
		if (element['@maxOccurs']) maxOccurs = element['@maxOccurs'];
		if (maxOccurs == 'unbounded') maxOccurs = 2;
		if (isAttribute) {
			name = '@' + name;
			orgName = name;
			name = '@' + name;
			if ((!element['@use']) || (element['@use'] != 'required')) minOccurs = 0;
		}

		/*
			JSON Schema defines seven primitive types for JSON values:

			array   A JSON array.
			boolean A JSON boolean.
			integer A JSON number without a fraction or exponent part.
			number  Any JSON number. Number includes integer.
			null    The JSON null value.
			object  A JSON object.
			string  A JSON string.
		*/
		parent[name] = {};

		if (type == 'xs:integer') type = 'integer';
		if (type == 'xs:string') type = 'string';
		if (type == 'xs:NMTOKEN') type = 'string';
		if (type == 'xs:NMTOKENS') type = 'string';
		if (type == 'xs:ENTITY') type = 'string';
		if (type == 'xs:ENTITIES') type = 'string';
		if (type == 'xs:ID') type = 'string';
		if (type == 'xs:IDREF') type = 'string';
		if (type == 'xs:IDREFS') type = 'string';
		if (type == 'xs:token') type = 'string';
		if (type == 'xs:lamguage') type = 'string';
		if (type == 'xs:Name') type = 'string';
		if (type == 'xs:NCName') type = 'string';
		if (type == 'xs:QName') type = 'string';
		if (type == 'xs:normalizedString') type = 'string';

		if (type == 'xs:boolean') type = 'boolean';
		if (type == 'xs:date') {
			type = 'string';
			parent[name].format = 'date-time';
		}
		if (type == 'xs:dateTime') {
			type = 'string';
			parent[name].format = 'date-time';
		}
		if (type == 'xs:positiveInteger') {
			type = 'integer';
			parent[name]["json:minimum"] = 0;
		}
		if (type == 'xs:decimal') type = 'number';
		if (type == 'xs:anyURI') {
			type = 'string';
			parent[name].format = 'uri';
		}

		if (element['xs:simpleType'] && element['xs:simpleType']['xs:restriction'] && element['xs:simpleType']['xs:restriction']['xs:enumeration']) {
			var source = element['xs:simpleType']['xs:restriction']['xs:enumeration'];
			parent[name]["enum"] = [];
			for (var i=0;i<source.length;i++) {
				parent[name]["enum"].push(source[i]);
			}
		}
		else {
			if ((type == 'string') || (type == 'boolean') || (type == 'array') || (type == 'object') || (type == 'integer')
				|| (type == 'number') || (type == 'null')) {
				parent[name].type = type;
			}
			else {
				parent[name]['$ref'] = '#/definitions/'+type;
			}
		}
		// TODO process restrictions, patterns, simple types

		if (!isAttribute) parent['json:additionalProperties'] = false;
		if (minOccurs >= 1) {
			if (!parent['json:required']) {
				parent['json:required'] = [];
			}
			parent['json:required'].push(orgName);
		}

		if (maxOccurs > 1) {
			var items = clone(parent[name]);
			parent[name] = {};
			parent[name].type = 'array';
			parent[name].items = items; // like a hoik downwards
		}

		if (type != 'object') delete obj[key];
	}
}

function extractDefinitions(obj,parent,top) {
	if (Array.isArray(obj.properties)) {
		var start = 0;
		if (isEmpty(parent)) start = 1;
		if (!top.definitions) top.definitions = {};
		for (var i=start;i<obj.properties.length;i++) {
			var o = obj.properties[i];
			if (o) {
				top.definitions[o.name] = {};
				top.definitions[o.name].type = 'object';
				top.definitions[o.name].properties = o.properties;
				if (o.required) {
					top.definitions[o.name].required = o.required;
				}
				var isArray = false;
				if (!parent.properties) {
					parent.properties = {};
				}
				if (parent.properties[o.name] && parent.properties[o.name].type) {
					if (parent.properties[o.name].type == 'array') isArray = true;
				}
				parent.properties[o.name] = {};
				if (isArray) {
					parent.properties[o.name].type = 'array';
					parent.properties[o.name].items = {};
					parent.properties[o.name].items['$ref'] = '#/definitions/'+o.name;
				}
				else {
					parent.properties[o.name]['$ref'] = '#/definitions/'+o.name;
				}
			}
		}
		if (start > 0) {
			obj.properties = obj.properties[0];
		}
		else {
			delete obj.properties;
		}
	}
}

function recurse(obj,parent,callback) {
	for (var key in obj) {
		// skip loop if the property is from prototype
		if (!obj.hasOwnProperty(key)) continue;

		var array = Array.isArray(obj);

		if (typeof obj[key] === 'object') {
			if (array) {
				for (var i in obj[key]) {
					recurse(obj[key][i],obj[key],callback);
				}
			}
			recurse(obj[key],obj,callback);
		}
		callback(obj,parent,key);

	}
	return obj;
}

module.exports = {
	getJsonSchema : function getJsonSchema(src,title) {
		var obj = clone(src);

		var id = src["xs:schema"]["@targetNamespace"];
		if (!id) {
			id = src["xs:schema"]["@xmlns"];
		}

		//initial root object transformations
		obj.title = title;
		obj.$schema = 'http://json-schema.org/schema#'; //for latest, or 'http://json-schema.org/draft-04/schema#' for v4
		if (id) {
			obj.id = id;
		}
		obj.type = 'object';

		var rootElementName = obj["xs:schema"]["xs:element"]["@name"];
		delete obj["xs:schema"]["xs:element"]["@name"]; // as it doesn't have a type it gets left hanging around
		obj.dummy = {};
		obj.dummy["json:required"] = [];
		obj.dummy["json:required"].push(rootElementName);
		obj.properties = {};
		hoik(obj["xs:schema"],obj.properties,'xs:element',rootElementName)

		recurse(obj,{},function(obj,parent,key) {
			elements(obj,parent,key);
		});

		recurse(obj,{},function(obj,parent,key) {
			clean(obj,parent,key);
		});

		hoik(obj['json:schema'],obj,'object');

		recurse(obj,{},function(obj,parent,key) {
			removeEmpties(obj,parent,key); // first pass
		});
		recurse(obj,{},function(obj,parent,key) {
			postProcess(obj,parent,key);
		});
		recurse(obj,{},function(obj,parent,key) {
			removeEmpties(obj,parent,key); // second pass to clean up anything emptied by first pass
		});

		recurse(obj,{},function(sub,parent,key) {
			extractDefinitions(sub,parent,obj);
		});

		obj.additionalProperties = false;
		return obj;
	}
};<|endoftext|>


<commit_before>module.exports = {
  'extends': 'eslint:recommended',
  'env': {
    'es6': true,
    'node': true,
    'browser': false
  },
  'rules': {
    'array-bracket-spacing': [2, 'never'],
    'block-scoped-var': 2,
    'brace-style': [2, '1tbs', { 'allowSingleLine': false }],
    'comma-dangle': [2, {
      'arrays': 'always-multiline',
      'objects': 'always-multiline',
      'imports': 'always-multiline',
      'exports': 'always-multiline',
      'functions': 'never'
    }],
    'comma-style': [2, 'last'],
    'computed-property-spacing': [2, 'never'],
    'curly': [2, 'all'],
    'eol-last': 2,
    'eqeqeq': [2, 'smart'],
    'guard-for-in': 2,
    'indent': [2, 2, { 'SwitchCase': 1 }],
    'key-spacing': [2, { 'beforeColon': false, 'afterColon': true }],
    'linebreak-style': [2, 'unix'],
    'lines-around-comment': [2, { 'beforeBlockComment': true, 'afterBlockComment': false }],
    'new-parens': 2,
    'no-array-constructor': 2,
    'no-caller': 2,
    'no-catch-shadow': 2,
    'no-dupe-keys': 2,
    'no-empty': 2,
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-extra-parens': [2, 'functions'],
    'no-implied-eval': 2,
    'no-iterator': 2,
    'no-label-var': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-loop-func': 2,
    'no-mixed-spaces-and-tabs': 2,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-native-reassign': 2,
    'no-nested-ternary': 2,
    'no-new-func': 2,
    'no-new-object': 2,
    'no-new-wrappers': 2,
    'no-octal-escape': 2,
    'no-process-exit': 2,
    'no-proto': 2,
    'no-return-assign': 2,
    'no-script-url': 2,
    'no-sequences': 2,
    'no-shadow-restricted-names': 2,
    'no-spaced-func': 2,
    'no-trailing-spaces': 2,
    'no-undef-init': 2,
    'no-undefined': 2,
    'no-unused-vars': [2, { 'vars': 'all', 'args': 'none' }],
    'no-with': 2,
    'object-curly-spacing': [2, 'always'],
    'one-var': [2, 'never'],
    'quote-props': [2, 'consistent-as-needed'],
    'quotes': [2, 'single', 'avoid-escape'],
    'semi': [2, 'always'],
    'semi-spacing': [2, { 'before': false, 'after': true }],
    'space-before-blocks': [2, 'always'],
    'space-before-function-paren': [2, { 'anonymous': 'always', 'named': 'always' }],
    'space-in-parens': [2, 'never'],
    'space-infix-ops': 2,
    'space-unary-ops': [2, { 'words': true, 'nonwords': false }],
    'spaced-comment': [2, 'always'],
    'strict': [2, 'never'],
    'yoda': [2, 'never'],
    'max-nested-callbacks': [1, 5],
    'valid-jsdoc': [1, {
      'prefer': {
        'arg': 'param',
        'argument': 'param',
        'class': 'constructor',
        'property': 'prop',
        'returns': 'return'
      }
    }]
  }
};
<commit_msg>Add jest eslint plugin<commit_after>module.exports = {
  'extends': 'eslint:recommended',
  'env': {
    'es6': true,
    'node': true,
    'browser': false,
    'jest': true,
  },
  'plugins': ['jest'],
  'rules': {
    'array-bracket-spacing': [2, 'never'],
    'block-scoped-var': 2,
    'brace-style': [2, '1tbs', { 'allowSingleLine': false }],
    'comma-dangle': [2, {
      'arrays': 'always-multiline',
      'objects': 'always-multiline',
      'imports': 'always-multiline',
      'exports': 'always-multiline',
      'functions': 'never'
    }],
    'comma-style': [2, 'last'],
    'computed-property-spacing': [2, 'never'],
    'curly': [2, 'all'],
    'eol-last': 2,
    'eqeqeq': [2, 'smart'],
    'guard-for-in': 2,
    'indent': [2, 2, { 'SwitchCase': 1 }],
    'key-spacing': [2, { 'beforeColon': false, 'afterColon': true }],
    'linebreak-style': [2, 'unix'],
    'lines-around-comment': [2, { 'beforeBlockComment': true, 'afterBlockComment': false }],
    'new-parens': 2,
    'no-array-constructor': 2,
    'no-caller': 2,
    'no-catch-shadow': 2,
    'no-dupe-keys': 2,
    'no-empty': 2,
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-extra-parens': [2, 'functions'],
    'no-implied-eval': 2,
    'no-iterator': 2,
    'no-label-var': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-loop-func': 2,
    'no-mixed-spaces-and-tabs': 2,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-native-reassign': 2,
    'no-nested-ternary': 2,
    'no-new-func': 2,
    'no-new-object': 2,
    'no-new-wrappers': 2,
    'no-octal-escape': 2,
    'no-process-exit': 2,
    'no-proto': 2,
    'no-return-assign': 2,
    'no-script-url': 2,
    'no-sequences': 2,
    'no-shadow-restricted-names': 2,
    'no-spaced-func': 2,
    'no-trailing-spaces': 2,
    'no-undef-init': 2,
    'no-undefined': 2,
    'no-unused-vars': [2, { 'vars': 'all', 'args': 'none' }],
    'no-with': 2,
    'object-curly-spacing': [2, 'always'],
    'one-var': [2, 'never'],
    'quote-props': [2, 'consistent-as-needed'],
    'quotes': [2, 'single', 'avoid-escape'],
    'semi': [2, 'always'],
    'semi-spacing': [2, { 'before': false, 'after': true }],
    'space-before-blocks': [2, 'always'],
    'space-before-function-paren': [2, { 'anonymous': 'always', 'named': 'always' }],
    'space-in-parens': [2, 'never'],
    'space-infix-ops': 2,
    'space-unary-ops': [2, { 'words': true, 'nonwords': false }],
    'spaced-comment': [2, 'always'],
    'strict': [2, 'never'],
    'yoda': [2, 'never'],
    'max-nested-callbacks': [1, 5],
    'valid-jsdoc': [1, {
      'prefer': {
        'arg': 'param',
        'argument': 'param',
        'class': 'constructor',
        'property': 'prop',
        'returns': 'return'
      }
    }]
  }
};
<|endoftext|>