<commit_before>var expect = require('unexpected')
    .clone()
    .installPlugin(require('./lib/unexpectedExpress'));

function myMiddleware(req, res, next) {
    res.setHeader('Content-Type', req.headers['content-type']);
    res.send('Here goes ' + req.url);
}

describe('myMiddleware', function (done) {
    it('should handle a simple request', function (done) {
        expect(require('express')().use(myMiddleware), 'to be middleware that processes', {
            request: {
                url: '/blah',
                headers: {
                    Accept: 'text/plain'
                }
            },
            response: {
                statusCode: 200,
                body: 'Here goes /blah in the form of text/plain',
                headers: {
                    'Content-Type': 'text/plain'
                }
            }
        }, done);
    });
});
<commit_msg>Removed accidentally committed file.<commit_after><|endoftext|>


<commit_before><commit_msg>debugging<commit_after><|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2015 Cheng Fan
 * 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.
 */
define(['Knockout', 'Sugar'], function (ko) {

    var initialValues = {};

    var PageDisposer = {
        init: function (page) {
            initialValues = {};
            Object.each(page, function (key, value) {
                if (ko.isObservable(value) && !ko.isComputed(value)) {
                    initialValues[key] = value();
                } else if ((value === null) || (value === undefined) || Object.isString(value) || Object.isNumber(value)) {
                    initialValues[key] = value;
                }
            });
        },
        dispose: function (page) {
            Object.each(initialValues, function (key, value) {
                if (page.hasOwnProperty(key)) {
                    if (Object.isFunction(page[key])) {
                        page[key](value);
                    } else {
                        page[key] = value;
                    }
                }
            });
            initialValues = {};
        }
    };

    return PageDisposer;

});
<commit_msg>Auto-dispose booleans as well.<commit_after>/**
 * @license Copyright (c) 2015 Cheng Fan
 * 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.
 */
define(['Knockout', 'Sugar'], function (ko) {

    var initialValues = {};

    var PageDisposer = {
        init: function (page) {
            initialValues = {};
            Object.each(page, function (key, value) {
                if (ko.isObservable(value) && !ko.isComputed(value)) { /* non-computed observables */
                    initialValues[key] = value();
                } else if ((value === null) || (value === undefined) || Object.isString(value) || Object.isNumber(value) || Object.isBoolean(value)) { /* primitives */
                    initialValues[key] = value;
                }
            });
        },
        dispose: function (page) {
            Object.each(initialValues, function (key, value) {
                if (page.hasOwnProperty(key)) {
                    if (Object.isFunction(page[key])) {
                        page[key](value);
                    } else {
                        page[key] = value;
                    }
                }
            });
            initialValues = {};
        }
    };

    return PageDisposer;

});

<|endoftext|>


<commit_before>/**
 * [XMLvalidation evaluates an MODS XML file and ensures it meets standards set here: https://wiki.lib.utk.edu/display/DLP/UTK+Data+Dictionary]
 * @param {[String]} input [MODS XML filename]
 * @return {[Array]}       [Success] or [Filename, Error 1, Error 2, Error 3, ...]
 * inputs
 * outputs
 */

var fs = require('fs');
var parser = require('xml2json');
var jp = require('jsonpath');
var status = [];

const IbuErrorDoc = require('./schema');
const db = require('../config/db');

//let stream = IbuErrorDoc.find().stream();
let stream = IbuErrorDoc.find({}).where({"XMLerrors":[]}).where({"filePathXML":{$exists:true,$ne:""}}).stream();

function findmesome(){
  stream.on('data', function(doc) {
    startProcessing(doc.filePathXML)
  }).on('error', function(err) {
    console.log('err: ' + err);
  }).on('close', function() {

  });

}

//IbuErrorDoc.find({ filename: "9733.2309.4609.0.xml"}.exec( function(x) {console.log('x output: ' + x)}))

function fileRead(err, data) {
  var message;
  if (err) {
    message = 'Cannot read file';
    console.log('Cannot read file');
  }
  else {
    message = 'Successfully read file';
    console.log('Successfully read file');
  }
  console.log('message :' + message);
  postResults(message, data);
}

function postResults(x, data) {
  switch(x) {
    case 'Cannot read file':
      console.log('CANNOT');
      break;
    case 'Successfully read file':
      console.log('CAN');
      //readMODS(data);
      //return data;
      break;
  }
}

function startProcessing(file) {
  var modsIn = fs.readFileSync(file, 'utf8');
  var modsObj = parser.toJson(modsIn, options = {object: true});

  var xmlValues = [];
  // only testing for fields that are required and/or non-repeating
  var xmlTargets = [0,   //collTitle (req if avail, non-repeating)
                    0,   //ms_arID (req if avail, non-repeating)
                    2,   //dateCreated*
                    0,   //dateIssued (optional, non-repeating)
                    1,   //digitalOrigin (req'd, non-repeating)
                    0,   //physicalDescription/extent (optional, non-repeating)
                    1,   //identifier[@type='filename'] (req'd, repeatable)
                    1,   //physicalDescription/form (req'd, repeatable)
                    1,   //physicalDescription/internetMediaType (req'd, non-repeating)
                    1,   //typeOfResource (req'd, non-repeating)
                    1,   //languageOfCataloging/languageTerm (req'd, non-repeating)
                    0,   //note[@type='ownership'] (optional, non-repeating)
                    1,   //recordInfo/recordOrigin (req'd, non-repeating)
                    0,   //recordInfo/recordContentSource (optional, non-repeating)
                    0,   //location/physicalLocation (req if avail, non-repeating)
                    1,   //rights! (required, non-repeating)
                    0,   //shelfLocator (optional, non-repeating)
                    1    //titleInfo/title (required, repeatable)

  ];
// fix this for cricket (xml##); not strings
  var xmlErrors = ["xml00",   //XML: too many collection titles
                   "xml01",   //XML: too many MS/AR numbers
                   "xml02",   //XML: please verify dateCreated elements and attributes
                   "xml03",   //XML: too many dateIssued elements
                   "xml04",   //XML: problems with digitalOrigin
                   "xml05",   //XML: too many extent elements
                   "xml06",   //XML: please verify identifier[@type=filename]
                   "xml07",   //XML: please verify physicalDescription/form
                   "xml08",   //XML: please verify internetMediaType
                   "xml09",   //XML: please verify typeOfResource
                   "xml10",   //XML: please verify languageOfCataloging/languageTerm
                   "xml11",   //XML: please check the number of note[@type=ownership]
                   "xml12",   //XML: please check the number of recordOrigin elements
                   "xml13",   //XML: please check the number of recordContentSource elements
                   "xml14",   //XML: please check the number of location/physicalLocation elements
                   "xml15",   //XML: please check the accessCondition element
                   "xml16",   //XML: please verify shelfLocator
                   "xml17"    //XML: please verify titleInfo/title

  ];

  xmlValues[0] = jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].titleInfo..title').length;
  xmlValues[1] = jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].identifier').length;
  xmlValues[2] = jp.query(modsObj, '$.mods.originInfo.dateCreated.*').length;
  xmlValues[3] = jp.query(modsObj, '$.mods.originInfo.dateIssued').length;
  xmlValues[4] = jp.query(modsObj, '$.mods.physicalDescription.digitalOrigin').length;
  xmlValues[5] = jp.query(modsObj, '$.mods.physicalDescription.extent').length;
  xmlValues[6] = jp.query(modsObj, '$.mods.identifier[?(@.type=="filename")]').length;
  xmlValues[7] = jp.query(modsObj, '$.mods.physicalDescription.form').length;
  xmlValues[8] = jp.query(modsObj, '$.mods.physicalDescription.internetMediaType').length;
  xmlValues[9] = jp.query(modsObj, '$.mods.typeOfResource').length;
  xmlValues[10] = jp.query(modsObj, '$.mods..languageOfCataloging.languageTerm').length;
  xmlValues[11] = jp.query(modsObj, '$.mods.note[?(@.type=="ownership")]').length;
  xmlValues[12] = jp.query(modsObj, '$.mods.recordInfo.recordOrigin').length;
  xmlValues[13] = jp.query(modsObj, '$.mods.recordInfo.recordContentSource').length;
  xmlValues[14] = jp.query(modsObj, '$.mods.location.physicalLocation').length;
  xmlValues[15] = jp.query(modsObj, '$.mods.accessCondition').length;
  xmlValues[16] = jp.query(modsObj, '$..shelfLocator').length;
  xmlValues[17] = jp.query(modsObj, '$.mods.titleInfo..title').length;

  console.log('IF:xmlValues:  ' + xmlValues + ' length: ' + xmlValues.length);
  console.log('IF:xmlTargets: ' + xmlTargets + ' length: ' + xmlTargets.length);

  for(i=0; i < xmlValues.length; i++) {
    // collection titles
    if((i==0) && (xmlValues[i]>xmlTargets[0]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // MS/AR numbers
    if((i==1) && (xmlValues[i]>xmlTargets[0]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // dateCreated
    if((i==2) && (xmlValues[i]<xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    } else if ((i==2) && ((xmlValues[i]==xmlTargets[i]) || (xmlValues[i]>xmlTargets[i]))) {
      for(n=0; n<xmlValues[i]; n++) {
        if((n==0) && ((!modsObj.mods.originInfo.dateCreated[n].keyDate) && (!modsObj.mods.originInfo.dateCreated[n].point))) {
          //console.log('first dateCreated is okay');
        } else if((n>0) && ((!modsObj.mods.originInfo.dateCreated[n].keyDate) && (!modsObj.mods.originInfo.dateCreated[n].point))) {
          // will push an error for every problematic dateCreated
          status.push(`${xmlErrors[i]}`);
        }
      }
    }
    // dateIssued
    if((i==3) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // digitalOrigin
    if((i==4) && (xmlValues[i]>xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // extent
    if((i==5) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // identifier[@type='filename']
    // TODO verify value(s) here?
    if((i==6) && (xmlValues[i]==0)) {
      status.push(`${xmlErrors[i]}`);
    }
    // physicalDescription/form
    if((i==7) && (xmlValues[i]<xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // physicalDescription/internetMediaType
    if((i==8) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // typeOfResource
    if((i==9) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // languageOfCataloging/languageTerm
    if((i==10) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // note[@type='ownership']
    if((i==11) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // recordInfo/recordOrigin
    if((i==12) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // recordInfo/recordContentSource
    if((i==13) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // location/physicalLocation
    if((i==14) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // rights!!
    if((i==15) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // shelfLocator
    if((i==16) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // titleInfo/title
    if((i==17) && (xmlValues[i]<xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
  }
}

//startProcessing(filename, fileRead);

export default findmesome;

// rename startProcessing function
<commit_msg>fix scope problem<commit_after>/**
 * [XMLvalidation evaluates an MODS XML file and ensures it meets standards set here: https://wiki.lib.utk.edu/display/DLP/UTK+Data+Dictionary]
 * @param {[String]} input [MODS XML filename]
 * @return {[Array]}       [Success] or [Filename, Error 1, Error 2, Error 3, ...]
 * inputs
 * outputs
 */

var fs = require('fs');
var parser = require('xml2json');
var jp = require('jsonpath');
var status = [];

const IbuErrorDoc = require('./schema');
const db = require('../config/db');

//let stream = IbuErrorDoc.find().stream();
let stream = IbuErrorDoc.find({}).where({"XMLerrors":[]}).where({"filePathXML":{$exists:true,$ne:""}}).stream();

function findmesome(){
  stream.on('data', function(doc) {
    var options;
    var modsIn = fs.readFileSync(doc.filePathXML, 'utf8');
    var modsObj = parser.toJson(modsIn, options = {object: true});

    var xmlValues = [];
    // only testing for fields that are required and/or non-repeating
    var xmlTargets = [0,   //collTitle (req if avail, non-repeating)
      0,   //ms_arID (req if avail, non-repeating)
      2,   //dateCreated*
      0,   //dateIssued (optional, non-repeating)
      1,   //digitalOrigin (req'd, non-repeating)
      0,   //physicalDescription/extent (optional, non-repeating)
      1,   //identifier[@type='filename'] (req'd, repeatable)
      1,   //physicalDescription/form (req'd, repeatable)
      1,   //physicalDescription/internetMediaType (req'd, non-repeating)
      1,   //typeOfResource (req'd, non-repeating)
      1,   //languageOfCataloging/languageTerm (req'd, non-repeating)
      0,   //note[@type='ownership'] (optional, non-repeating)
      1,   //recordInfo/recordOrigin (req'd, non-repeating)
      0,   //recordInfo/recordContentSource (optional, non-repeating)
      0,   //location/physicalLocation (req if avail, non-repeating)
      1,   //rights! (required, non-repeating)
      0,   //shelfLocator (optional, non-repeating)
      1    //titleInfo/title (required, repeatable)

    ];
// fix this for cricket (xml##); not strings
    var xmlErrors = ["xml00",   //XML: too many collection titles
      "xml01",   //XML: too many MS/AR numbers
      "xml02",   //XML: please verify dateCreated elements and attributes
      "xml03",   //XML: too many dateIssued elements
      "xml04",   //XML: problems with digitalOrigin
      "xml05",   //XML: too many extent elements
      "xml06",   //XML: please verify identifier[@type=filename]
      "xml07",   //XML: please verify physicalDescription/form
      "xml08",   //XML: please verify internetMediaType
      "xml09",   //XML: please verify typeOfResource
      "xml10",   //XML: please verify languageOfCataloging/languageTerm
      "xml11",   //XML: please check the number of note[@type=ownership]
      "xml12",   //XML: please check the number of recordOrigin elements
      "xml13",   //XML: please check the number of recordContentSource elements
      "xml14",   //XML: please check the number of location/physicalLocation elements
      "xml15",   //XML: please check the accessCondition element
      "xml16",   //XML: please verify shelfLocator
      "xml17"    //XML: please verify titleInfo/title

    ];

    xmlValues[0] = jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].titleInfo..title').length;
    xmlValues[1] = jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].identifier').length;
    xmlValues[2] = jp.query(modsObj, '$.mods.originInfo.dateCreated.*').length;
    xmlValues[3] = jp.query(modsObj, '$.mods.originInfo.dateIssued').length;
    xmlValues[4] = jp.query(modsObj, '$.mods.physicalDescription.digitalOrigin').length;
    xmlValues[5] = jp.query(modsObj, '$.mods.physicalDescription.extent').length;
    xmlValues[6] = jp.query(modsObj, '$.mods.identifier[?(@.type=="filename")]').length;
    xmlValues[7] = jp.query(modsObj, '$.mods.physicalDescription.form').length;
    xmlValues[8] = jp.query(modsObj, '$.mods.physicalDescription.internetMediaType').length;
    xmlValues[9] = jp.query(modsObj, '$.mods.typeOfResource').length;
    xmlValues[10] = jp.query(modsObj, '$.mods..languageOfCataloging.languageTerm').length;
    xmlValues[11] = jp.query(modsObj, '$.mods.note[?(@.type=="ownership")]').length;
    xmlValues[12] = jp.query(modsObj, '$.mods.recordInfo.recordOrigin').length;
    xmlValues[13] = jp.query(modsObj, '$.mods.recordInfo.recordContentSource').length;
    xmlValues[14] = jp.query(modsObj, '$.mods.location.physicalLocation').length;
    xmlValues[15] = jp.query(modsObj, '$.mods.accessCondition').length;
    xmlValues[16] = jp.query(modsObj, '$..shelfLocator').length;
    xmlValues[17] = jp.query(modsObj, '$.mods.titleInfo..title').length;

    //console.log('IF:xmlValues:  ' + xmlValues + ' length: ' + xmlValues.length);
    //console.log('IF:xmlTargets: ' + xmlTargets + ' length: ' + xmlTargets.length);

    var i = 0;
    for(; i < xmlValues.length; i++) {
      // collection titles
      if ((i == 0) && (xmlValues[i] > xmlTargets[0] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // MS/AR numbers
      if ((i == 1) && (xmlValues[i] > xmlTargets[0] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // dateCreated
      if ((i == 2) && (xmlValues[i] < xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      } else if ((i == 2) && ((xmlValues[i] == xmlTargets[i]) || (xmlValues[i] > xmlTargets[i]))) {
        var n = 0;
        for (; n < xmlValues[i]; n++) {
          if ((n == 0) && ((!modsObj.mods.originInfo.dateCreated[n].keyDate) && (!modsObj.mods.originInfo.dateCreated[n].point))) {
            //console.log('first dateCreated is okay');
          } else if ((n > 0) && ((!modsObj.mods.originInfo.dateCreated[n].keyDate) && (!modsObj.mods.originInfo.dateCreated[n].point))) {
            // will push an error for every problematic dateCreated
            status.push(`${xmlErrors[i]}`);
          }
        }
      }
      // dateIssued
      if ((i == 3) && (xmlValues[i] > xmlTargets[i] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // digitalOrigin
      if ((i == 4) && (xmlValues[i] > xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
      // extent
      if ((i == 5) && (xmlValues[i] > xmlTargets[i] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // identifier[@type='filename']
      // TODO verify value(s) here?
      if ((i == 6) && (xmlValues[i] == 0)) {
        status.push(`${xmlErrors[i]}`);
      }
      // physicalDescription/form
      if ((i == 7) && (xmlValues[i] < xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
      // physicalDescription/internetMediaType
      if ((i == 8) && (xmlValues[i] !== xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
      // typeOfResource
      if ((i == 9) && (xmlValues[i] !== xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
      // languageOfCataloging/languageTerm
      if ((i == 10) && (xmlValues[i] !== xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
      // note[@type='ownership']
      if ((i == 11) && (xmlValues[i] > xmlTargets[i] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // recordInfo/recordOrigin
      if ((i == 12) && (xmlValues[i] !== xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
      // recordInfo/recordContentSource
      if ((i == 13) && (xmlValues[i] > xmlTargets[i] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // location/physicalLocation
      if ((i == 14) && (xmlValues[i] > xmlTargets[i] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // rights!!
      if ((i == 15) && (xmlValues[i] !== xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
      // shelfLocator
      if ((i == 16) && (xmlValues[i] > xmlTargets[i] + 1)) {
        status.push(`${xmlErrors[i]}`);
      }
      // titleInfo/title
      if ((i == 17) && (xmlValues[i] < xmlTargets[i])) {
        status.push(`${xmlErrors[i]}`);
      }
    }
  }).on('error', function(err) {
    console.log('err: ' + err);
  }).on('close', function() {

  });

}

//IbuErrorDoc.find({ filename: "9733.2309.4609.0.xml"}.exec( function(x) {console.log('x output: ' + x)}))

function fileRead(err, data) {
  var message;
  if (err) {
    message = 'Cannot read file';
    console.log('Cannot read file');
  }
  else {
    message = 'Successfully read file';
    console.log('Successfully read file');
  }
  console.log('message :' + message);
  postResults(message, data);
}

function postResults(x, data) {
  switch(x) {
    case 'Cannot read file':
      console.log('CANNOT');
      break;
    case 'Successfully read file':
      console.log('CAN');
      //readMODS(data);
      //return data;
      break;
  }
}

function startProcessing(file) {
  var options;
  var modsIn = fs.readFileSync(file, 'utf8');
  var modsObj = parser.toJson(modsIn, options = {object: true});

  var xmlValues = [];
  // only testing for fields that are required and/or non-repeating
  var xmlTargets = [0,   //collTitle (req if avail, non-repeating)
                    0,   //ms_arID (req if avail, non-repeating)
                    2,   //dateCreated*
                    0,   //dateIssued (optional, non-repeating)
                    1,   //digitalOrigin (req'd, non-repeating)
                    0,   //physicalDescription/extent (optional, non-repeating)
                    1,   //identifier[@type='filename'] (req'd, repeatable)
                    1,   //physicalDescription/form (req'd, repeatable)
                    1,   //physicalDescription/internetMediaType (req'd, non-repeating)
                    1,   //typeOfResource (req'd, non-repeating)
                    1,   //languageOfCataloging/languageTerm (req'd, non-repeating)
                    0,   //note[@type='ownership'] (optional, non-repeating)
                    1,   //recordInfo/recordOrigin (req'd, non-repeating)
                    0,   //recordInfo/recordContentSource (optional, non-repeating)
                    0,   //location/physicalLocation (req if avail, non-repeating)
                    1,   //rights! (required, non-repeating)
                    0,   //shelfLocator (optional, non-repeating)
                    1    //titleInfo/title (required, repeatable)

  ];
// fix this for cricket (xml##); not strings
  var xmlErrors = ["xml00",   //XML: too many collection titles
                   "xml01",   //XML: too many MS/AR numbers
                   "xml02",   //XML: please verify dateCreated elements and attributes
                   "xml03",   //XML: too many dateIssued elements
                   "xml04",   //XML: problems with digitalOrigin
                   "xml05",   //XML: too many extent elements
                   "xml06",   //XML: please verify identifier[@type=filename]
                   "xml07",   //XML: please verify physicalDescription/form
                   "xml08",   //XML: please verify internetMediaType
                   "xml09",   //XML: please verify typeOfResource
                   "xml10",   //XML: please verify languageOfCataloging/languageTerm
                   "xml11",   //XML: please check the number of note[@type=ownership]
                   "xml12",   //XML: please check the number of recordOrigin elements
                   "xml13",   //XML: please check the number of recordContentSource elements
                   "xml14",   //XML: please check the number of location/physicalLocation elements
                   "xml15",   //XML: please check the accessCondition element
                   "xml16",   //XML: please verify shelfLocator
                   "xml17"    //XML: please verify titleInfo/title

  ];

  xmlValues[0] = jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].titleInfo..title').length;
  xmlValues[1] = jp.query(modsObj, '$.mods.relatedItem[?(@.displayLabel=="Collection")].identifier').length;
  xmlValues[2] = jp.query(modsObj, '$.mods.originInfo.dateCreated.*').length;
  xmlValues[3] = jp.query(modsObj, '$.mods.originInfo.dateIssued').length;
  xmlValues[4] = jp.query(modsObj, '$.mods.physicalDescription.digitalOrigin').length;
  xmlValues[5] = jp.query(modsObj, '$.mods.physicalDescription.extent').length;
  xmlValues[6] = jp.query(modsObj, '$.mods.identifier[?(@.type=="filename")]').length;
  xmlValues[7] = jp.query(modsObj, '$.mods.physicalDescription.form').length;
  xmlValues[8] = jp.query(modsObj, '$.mods.physicalDescription.internetMediaType').length;
  xmlValues[9] = jp.query(modsObj, '$.mods.typeOfResource').length;
  xmlValues[10] = jp.query(modsObj, '$.mods..languageOfCataloging.languageTerm').length;
  xmlValues[11] = jp.query(modsObj, '$.mods.note[?(@.type=="ownership")]').length;
  xmlValues[12] = jp.query(modsObj, '$.mods.recordInfo.recordOrigin').length;
  xmlValues[13] = jp.query(modsObj, '$.mods.recordInfo.recordContentSource').length;
  xmlValues[14] = jp.query(modsObj, '$.mods.location.physicalLocation').length;
  xmlValues[15] = jp.query(modsObj, '$.mods.accessCondition').length;
  xmlValues[16] = jp.query(modsObj, '$..shelfLocator').length;
  xmlValues[17] = jp.query(modsObj, '$.mods.titleInfo..title').length;

  //console.log('IF:xmlValues:  ' + xmlValues + ' length: ' + xmlValues.length);
  //console.log('IF:xmlTargets: ' + xmlTargets + ' length: ' + xmlTargets.length);

  var i = 0;
  for(; i < xmlValues.length; i++) {
    // collection titles
    if((i==0) && (xmlValues[i]>xmlTargets[0]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // MS/AR numbers
    if((i==1) && (xmlValues[i]>xmlTargets[0]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // dateCreated
    if((i==2) && (xmlValues[i]<xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    } else if ((i==2) && ((xmlValues[i]==xmlTargets[i]) || (xmlValues[i]>xmlTargets[i]))) {
      var n = 0;
      for(; n<xmlValues[i]; n++) {
        if((n==0) && ((!modsObj.mods.originInfo.dateCreated[n].keyDate) && (!modsObj.mods.originInfo.dateCreated[n].point))) {
          //console.log('first dateCreated is okay');
        } else if((n>0) && ((!modsObj.mods.originInfo.dateCreated[n].keyDate) && (!modsObj.mods.originInfo.dateCreated[n].point))) {
          // will push an error for every problematic dateCreated
          status.push(`${xmlErrors[i]}`);
        }
      }
    }
    // dateIssued
    if((i==3) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // digitalOrigin
    if((i==4) && (xmlValues[i]>xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // extent
    if((i==5) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // identifier[@type='filename']
    // TODO verify value(s) here?
    if((i==6) && (xmlValues[i]==0)) {
      status.push(`${xmlErrors[i]}`);
    }
    // physicalDescription/form
    if((i==7) && (xmlValues[i]<xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // physicalDescription/internetMediaType
    if((i==8) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // typeOfResource
    if((i==9) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // languageOfCataloging/languageTerm
    if((i==10) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // note[@type='ownership']
    if((i==11) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // recordInfo/recordOrigin
    if((i==12) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // recordInfo/recordContentSource
    if((i==13) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // location/physicalLocation
    if((i==14) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // rights!!
    if((i==15) && (xmlValues[i]!==xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
    // shelfLocator
    if((i==16) && (xmlValues[i]>xmlTargets[i]+1)) {
      status.push(`${xmlErrors[i]}`);
    }
    // titleInfo/title
    if((i==17) && (xmlValues[i]<xmlTargets[i])) {
      status.push(`${xmlErrors[i]}`);
    }
  }
}

//startProcessing(filename, fileRead);

export default findmesome;

// rename startProcessing function
<|endoftext|>


<commit_before>DDH.conversions = DDH.conversions || {};

(function(DDH) {
    "use strict";

    var localDOMInitialized = false;
    var initialized = false;

    // UI: the input / output fields
    var $convert_left,
        $convert_right,
        $select_right,
        $select_left,
        $unitSelector,
        $selects;

    // a capitalize method to string literals
    String.prototype.capitalize = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }

    var Converter = {

        // the local vars
        leftUnit:   "",
        rightUnit:  "",
        leftValue:  "",
        rightValue: "",

        setValues: function() {
            this.setLeftUnit();
            this.setRightUnit();
            this.setLeftValue();
            this.setRightValue();
        },

        setLeftUnit: function() {
            this.leftUnit = $select_left.val();
        },

        setLeftValue: function() {
            this.leftValue = $convert_left.val();
        },

        setRightUnit: function() {
            this.rightUnit = $select_right.val();
        },

        setRightValue: function() {
            this.rightValue = $convert_right.val();
        },

        eval: function( expression ) {
            return math.eval(expression).format({ precision: 6 }).split(" ")[0];
        },

        convert: function( side ) {

            this.setValues();
            if(side === "right") {
                var expression = this.leftValue + " " + this.leftUnit + " to " + this.rightUnit;
                $convert_right.val(this.eval(expression));
            } else {
                var expression = this.rightValue + " " + this.rightUnit + " to " + this.leftUnit;
                $convert_left.val(this.eval(expression));
            }
        },

        emptySelects: function() {
            // removes all the options
            $select_left.empty();
            $select_right.empty();
        },

        updateUnitSelectors: function( key ) {

            this.emptySelects();
            var formatted_option_name;

            // adds the new conversion units to the selects
            for(var i = 0 ; i < Units[key].units.length ; i++) {
                formatted_option_name = (Units[key].units[i].length > 3) ? Units[key].units[i].capitalize() : Units[key].units[i];
                $selects.append(
                    '<option value="' + Units[key].units[i] + '">'
                    + formatted_option_name
                    + '</option>'
                );
            }

            // set defaults. written this way for readability
            $select_left.val(Units[key].defaults[0]);
            $select_right.val(Units[key].defaults[1]);
        },

        updateBaseUnitSelector: function( startBase ) {
            // adds the different unit types to the selector
            var unitKeys = Object.keys(Units);
            $.each(unitKeys.sort(), function(_key, value) {
                $unitSelector.append(
                    '<option value="'+value+'"' + (value === startBase ? " selected='selected'" : "") + '>'
                    + Units[value].name
                    + '</option>'
                );
            });
        }
    } // Converter

    var Utils = {

        // caches the local DOM vars
        setUpLocalDOM: function() {
            var $root           = DDH.getDOM('conversions');
            $convert_left       = $root.find(".frm__input--left");
            $convert_right      = $root.find(".frm__input--right");
            $selects            = $root.find(".frm--top select");
            $select_right       = $root.find(".frm__select--right");
            $select_left        = $root.find(".frm__select--left");
            $unitSelector       = $root.find(".frm__select--bottom");
            localDOMInitialized = true;
        },
    } // Utils

    var Units = {
        length: {
            name: "Length",
            units: [
                'decameter',
                'millimeter',
                'micrometer',
                'nanometer',
                'picometer',
                'kilometer',
                'meter',
                'cm',
                'hectometer',
                'chains',
                'mm',
                'inch',
                'foot',
                'yard',
                'mile',
                'link',
                'rod',
                'angstrom',
                'mil'
            ],
            defaults: ['meter', 'cm']
        },
        area: {
            name: "Area",
            units: [
                'm2',
                'sqin',
                'sqft',
                'sqyd',
                'sqmi',
                'sqrd',
                'sqch',
                'sqmil',
                'acre',
                'hectare'
            ],
            defaults: ['m2', 'sqin']
        },
        volume: {
            name: "Volume",
            units: [
                'litre',
                'millilitre',
                'hectolitre',
                'decalitre',
                'deciliter',
                'centilitre',
                'cc',
                'cuin',
                'cuft',
                'cups',
                'cuyd',
                'pints',
                'teaspoon',
                'tablespoon'
            ],
            defaults: ['litre', 'millilitre']
        },
        liquid_volume: {
            name: "Liquid Volume",
            units: ['minim', 'fluiddram', 'fluidounce', 'gill', 'cup', 'pint', 'quart', 'gallon', 'beerbarrel', 'oilbarrel', 'hogshead', 'drop'],
            defaults: ['minim', 'fluiddram']
        },
        angle: {
            name: "Angle",
            units: [
                'rad',
                'deg',
                'grad',
                'cycle',
                'arcsec',
                'arcmin'
            ],
            defaults: ['deg', 'rad']
        },
        duration: {
            name: "Duration",
            units: [
                'nanosecond',
                'microsecond',
                'millisecond',
                'second',
                'minute',
                'hour',
                'day',
                'week',
                'month',
                'year',
                'decade',
                'century',
                'millennium'
            ],
            defaults: ['minute', 'second']
        },
        mass: {
            name: "Mass",
            units: [
                'microgram',
                'kilogram',
                'milligram',
                'gram',
                'ton',
                'grain',
                'dram',
                'ounce',
                'poundmass',
                'hundredweight',
                'stick',
                'stone'
            ],
            defaults: ['kilogram', 'gram']
        },
        temperature: {
            name: "Temperature",
            units: [
                'kelvin',
                'celsius',
                'fahrenheit',
                'rankine'
            ],
            defaults: ['celsius', 'fahrenheit']
        },
        force: {
            name: "Force",
            units: [
                'newton',
                'dyne',
                'poundforce',
                'kip'
            ],
            defaults: ['newton', 'dyne']
        },
        energy: {
            name: "Energy",
            units: [
                'joule',
                'Wh',
                'erg',
                'BTU',
                'electronvolt'
            ],
            defaults: ['joule', 'Wh']
        },
        power: {
            name: "Power",
            units: [
                'watt',
                'hp'
            ],
            defaults: ['watt', 'hp']
        },
        pressure: {
            name: "Pressure",
            units: [
                'Pa',
                'psi',
                'atm',
                'torr',
                'mmHg',
                'mmH2O',
                'cmH2O'
            ],
            defaults: ['Pa', 'psi']
        },
        electricity_magnetism: {
            name: "Electricity and magnetism",
            units: ['ampere', 'coulomb', 'watt', 'volt', 'ohm', 'farad', 'weber', 'tesla', 'henry', 'siemens', 'electronvolt'],
            defaults: ['ampere', 'coulomb']
        },
        // TODO: Support digital conversions. @pjhampton - there were math.js api issues
        // digital: {
        //     name: "Binary",
        //     units: ['bit', 'byte'],
        //     defaults: ['bit', 'byte']
        // }
    } // Units

    DDH.conversions.build = function(ops) {

        // just defaulting to `length` for now, will change when interacting with perl backend.
        var startBase = ops.data.physical_quantity || 'length';
        var leftUnit = ops.data.left_unit || Units[startBase].defaults[0];
        var rightUnit = ops.data.right_unit || Units[startBase].defaults[1];
        var rawInput = ops.data.raw_input || '1';
        var unitsSpecified = false;

        return {
            signal: "high",
            onShow: function() {
                DDG.require('math.js', function() {

                    if(!localDOMInitialized) {
                        Utils.setUpLocalDOM();
                    }

                    if(!initialized) {
                        Converter.updateUnitSelectors(startBase);
                        Converter.updateBaseUnitSelector(startBase);

                        // if no numbers provided, fall back on 1
                        if(!unitsSpecified) {
                            $convert_left.val(rawInput);
                            $select_left.val(leftUnit);
                            $select_right.val(rightUnit);
                            Converter.convert("right");
                        }

                        initialized = true;
                    }

                    $convert_left.keyup(function( _e ) {
                        if(this.value === "") {
                            $convert_right.val("");
                        }
                        if(this.value !== "" && $.isNumeric(this.value)) {
                            Converter.convert("right");
                        }
                    });

                    $convert_right.keyup(function( _e ) {
                        if(this.value === "") {
                            $convert_left.val("");
                        }
                        if(this.value !== "" && $.isNumeric(this.value)) {
                            Converter.convert("left");
                        }
                    });

                    $select_right.change(function() {
                        Converter.convert("right");
                    });

                    $select_left.change(function() {
                        Converter.convert("left");
                    });

                    // if the user changes the unit base
                    $unitSelector.change(function() {
                        Converter.updateUnitSelectors(this.value);
                        $convert_left.val("1");
                        Converter.convert("right");
                    });

                });

            }// on show
        }; // return
    }; // DDH.conversions.build

    // module.exports = { Converter: Converter, Utils: Utils };

})(DDH);
<commit_msg>Sorted select keys.<commit_after>DDH.conversions = DDH.conversions || {};

(function(DDH) {
    "use strict";

    var localDOMInitialized = false;
    var initialized = false;

    // UI: the input / output fields
    var $convert_left,
        $convert_right,
        $select_right,
        $select_left,
        $unitSelector,
        $selects;

    // a capitalize method to string literals
    String.prototype.capitalize = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }

    var Converter = {

        // the local vars
        leftUnit:   "",
        rightUnit:  "",
        leftValue:  "",
        rightValue: "",

        setValues: function() {
            this.setLeftUnit();
            this.setRightUnit();
            this.setLeftValue();
            this.setRightValue();
        },

        setLeftUnit: function() {
            this.leftUnit = $select_left.val();
        },

        setLeftValue: function() {
            this.leftValue = $convert_left.val();
        },

        setRightUnit: function() {
            this.rightUnit = $select_right.val();
        },

        setRightValue: function() {
            this.rightValue = $convert_right.val();
        },

        eval: function( expression ) {
            return math.eval(expression).format({ precision: 6 }).split(" ")[0];
        },

        convert: function( side ) {

            this.setValues();
            if(side === "right") {
                var expression = this.leftValue + " " + this.leftUnit + " to " + this.rightUnit;
                $convert_right.val(this.eval(expression));
            } else {
                var expression = this.rightValue + " " + this.rightUnit + " to " + this.leftUnit;
                $convert_left.val(this.eval(expression));
            }
        },

        emptySelects: function() {
            // removes all the options
            $select_left.empty();
            $select_right.empty();
        },

        updateUnitSelectors: function( key ) {

            this.emptySelects();
            var formatted_option_name;

            // sort the keys alphabetically
            Units[key].units.sort();

            // adds the new conversion units to the selects
            for(var i = 0 ; i < Units[key].units.length ; i++) {
                formatted_option_name = (Units[key].units[i].length > 3) ? Units[key].units[i].capitalize() : Units[key].units[i];
                $selects.append(
                    '<option value="' + Units[key].units[i] + '">'
                    + formatted_option_name
                    + '</option>'
                );
            }

            // set defaults. written this way for readability
            $select_left.val(Units[key].defaults[0]);
            $select_right.val(Units[key].defaults[1]);
        },

        updateBaseUnitSelector: function( startBase ) {
            // adds the different unit types to the selector
            var unitKeys = Object.keys(Units);
            $.each(unitKeys.sort(), function(_key, value) {
                $unitSelector.append(
                    '<option value="'+value+'"' + (value === startBase ? " selected='selected'" : "") + '>'
                    + Units[value].name
                    + '</option>'
                );
            });
        }
    } // Converter

    var Utils = {

        // caches the local DOM vars
        setUpLocalDOM: function() {
            var $root           = DDH.getDOM('conversions');
            $convert_left       = $root.find(".frm__input--left");
            $convert_right      = $root.find(".frm__input--right");
            $selects            = $root.find(".frm--top select");
            $select_right       = $root.find(".frm__select--right");
            $select_left        = $root.find(".frm__select--left");
            $unitSelector       = $root.find(".frm__select--bottom");
            localDOMInitialized = true;
        },
    } // Utils

    var Units = {
        length: {
            name: "Length",
            units: [
                'decameter',
                'millimeter',
                'micrometer',
                'nanometer',
                'picometer',
                'kilometer',
                'meter',
                'cm',
                'hectometer',
                'chains',
                'mm',
                'inch',
                'foot',
                'yard',
                'mile',
                'link',
                'rod',
                'angstrom',
                'mil'
            ],
            defaults: ['meter', 'cm']
        },
        area: {
            name: "Area",
            units: [
                'm2',
                'sqin',
                'sqft',
                'sqyd',
                'sqmi',
                'sqrd',
                'sqch',
                'sqmil',
                'acre',
                'hectare'
            ],
            defaults: ['m2', 'sqin']
        },
        volume: {
            name: "Volume",
            units: [
                'litre',
                'millilitre',
                'hectolitre',
                'decalitre',
                'deciliter',
                'centilitre',
                'cc',
                'cuin',
                'cuft',
                'cups',
                'cuyd',
                'pints',
                'teaspoon',
                'tablespoon'
            ],
            defaults: ['litre', 'millilitre']
        },
        liquid_volume: {
            name: "Liquid Volume",
            units: ['minim', 'fluiddram', 'fluidounce', 'gill', 'cup', 'pint', 'quart', 'gallon', 'beerbarrel', 'oilbarrel', 'hogshead', 'drop'],
            defaults: ['minim', 'fluiddram']
        },
        angle: {
            name: "Angle",
            units: [
                'rad',
                'deg',
                'grad',
                'cycle',
                'arcsec',
                'arcmin'
            ],
            defaults: ['deg', 'rad']
        },
        duration: {
            name: "Duration",
            units: [
                'nanosecond',
                'microsecond',
                'millisecond',
                'second',
                'minute',
                'hour',
                'day',
                'week',
                'month',
                'year',
                'decade',
                'century',
                'millennium'
            ],
            defaults: ['minute', 'second']
        },
        mass: {
            name: "Mass",
            units: [
                'microgram',
                'kilogram',
                'milligram',
                'gram',
                'ton',
                'grain',
                'dram',
                'ounce',
                'poundmass',
                'hundredweight',
                'stick',
                'stone'
            ],
            defaults: ['kilogram', 'gram']
        },
        temperature: {
            name: "Temperature",
            units: [
                'kelvin',
                'celsius',
                'fahrenheit',
                'rankine'
            ],
            defaults: ['celsius', 'fahrenheit']
        },
        force: {
            name: "Force",
            units: [
                'newton',
                'dyne',
                'poundforce',
                'kip'
            ],
            defaults: ['newton', 'dyne']
        },
        energy: {
            name: "Energy",
            units: [
                'joule',
                'Wh',
                'erg',
                'BTU',
                'electronvolt'
            ],
            defaults: ['joule', 'Wh']
        },
        power: {
            name: "Power",
            units: [
                'watt',
                'hp'
            ],
            defaults: ['watt', 'hp']
        },
        pressure: {
            name: "Pressure",
            units: [
                'Pa',
                'psi',
                'atm',
                'torr',
                'mmHg',
                'mmH2O',
                'cmH2O'
            ],
            defaults: ['Pa', 'psi']
        },
        electricity_magnetism: {
            name: "Electricity and magnetism",
            units: ['ampere', 'coulomb', 'watt', 'volt', 'ohm', 'farad', 'weber', 'tesla', 'henry', 'siemens', 'electronvolt'],
            defaults: ['ampere', 'coulomb']
        },
        // TODO: Support digital conversions. @pjhampton - there were math.js api issues
        // digital: {
        //     name: "Binary",
        //     units: ['bit', 'byte'],
        //     defaults: ['bit', 'byte']
        // }
    } // Units

    DDH.conversions.build = function(ops) {

        // just defaulting to `length` for now, will change when interacting with perl backend.
        var startBase = ops.data.physical_quantity || 'length';
        var leftUnit = ops.data.left_unit || Units[startBase].defaults[0];
        var rightUnit = ops.data.right_unit || Units[startBase].defaults[1];
        var rawInput = ops.data.raw_input || '1';
        var unitsSpecified = false;

        return {
            signal: "high",
            onShow: function() {
                DDG.require('math.js', function() {

                    if(!localDOMInitialized) {
                        Utils.setUpLocalDOM();
                    }

                    if(!initialized) {
                        Converter.updateUnitSelectors(startBase);
                        Converter.updateBaseUnitSelector(startBase);

                        // if no numbers provided, fall back on 1
                        if(!unitsSpecified) {
                            $convert_left.val(rawInput);
                            $select_left.val(leftUnit);
                            $select_right.val(rightUnit);
                            Converter.convert("right");
                        }

                        initialized = true;
                    }

                    $convert_left.keyup(function( _e ) {
                        if(this.value === "") {
                            $convert_right.val("");
                        }
                        if(this.value !== "" && $.isNumeric(this.value)) {
                            Converter.convert("right");
                        }
                    });

                    $convert_right.keyup(function( _e ) {
                        if(this.value === "") {
                            $convert_left.val("");
                        }
                        if(this.value !== "" && $.isNumeric(this.value)) {
                            Converter.convert("left");
                        }
                    });

                    $select_right.change(function() {
                        Converter.convert("right");
                    });

                    $select_left.change(function() {
                        Converter.convert("left");
                    });

                    // if the user changes the unit base
                    $unitSelector.change(function() {
                        Converter.updateUnitSelectors(this.value);
                        $convert_left.val("1");
                        Converter.convert("right");
                    });

                });

            }// on show
        }; // return
    }; // DDH.conversions.build

    // module.exports = { Converter: Converter, Utils: Utils };

})(DDH);
<|endoftext|>


<commit_before>/*
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

import Xen from '../../components/xen/xen.js';
import Arcs from '../lib/arcs.js';
import ArcsUtils from '../lib/arcs-utils.js';
import Firebase from './cloud-data/firebase.js';

const log = Xen.logFactory('ArcPlanner', '#104a91');
const error = Xen.logFactory('ArcPlanner', '#104a91', 'error');

// proposed:
// plans -> map of plans, generations
// plan -> map of plans, generations, (simple-)plan
// suggestions -> filtered array of (simple-)plans
// suggestion -> (simple-)plan

class ArcPlanner extends Xen.Debug(Xen.Base, log) {
  static get observedAttributes() {
    return ['config', 'arc', 'suggestion', 'search'];
  }
  _getInitialState() {
    return {
      pendingPlans: [],
      invalid: 0
    };
  }
  _willReceiveProps(props, state, oldProps) {
    const changed = name => props[name] !== oldProps[name];
    const {arc, suggestion, search} = props;
    if (suggestion && changed('suggestion')) {
      state.pendingPlans.push(suggestion.plan);
    }
    if (arc) {
      let {planificator} = state;
      if (planificator && changed('arc')) {
        // TODO(sjmiles): until `dispose` is fixed
        planificator._arc._scheduler.unregisterIdleCallback(planificator._schedulerCallback);
        //planificator.dispose();
        planificator = null;
      }
      if (!planificator) {
        planificator = this._createPlanificator(arc);
        planificator.setSearch(search);
      } else if (changed('search')) {
        planificator.setSearch(search);
      }
      this._setState({planificator});
    }
  }
  _update({arc, suggestions, search, planificator}, {pendingPlans}) {
    if (arc && pendingPlans.length) {
      this._instantiatePlan(arc, pendingPlans.shift());
    }
  }
  _createPlanificator(arc) {
    const planificator = new Arcs.Planificator(arc);
    planificator.registerPlansChangedCallback(current => this._plansChanged(current, planificator.getLastActivatedPlan()));
    planificator.registerSuggestChangedCallback(suggestions => this._suggestionsChanged(suggestions));
    return planificator;
  }
  _plansChanged(context, plan) {
    this._fire('plans', context);
    this._fire('plan', plan);
  }
  _suggestionsChanged(suggestions) {
    this._fire('suggestions', suggestions);
  }
  async _instantiatePlan(arc, plan) {
    log('instantiating plan', plan);
    await arc.instantiate(plan);
    // search term is used up
    this._fire('search', '');
    // need new suggestions
    this._fire('suggestions', null);
  }
}
customElements.define('arc-planner', ArcPlanner);
<commit_msg>Use planificator dispose method. (#1351)<commit_after>/*
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

import Xen from '../../components/xen/xen.js';
import Arcs from '../lib/arcs.js';
import ArcsUtils from '../lib/arcs-utils.js';
import Firebase from './cloud-data/firebase.js';

const log = Xen.logFactory('ArcPlanner', '#104a91');
const error = Xen.logFactory('ArcPlanner', '#104a91', 'error');

// proposed:
// plans -> map of plans, generations
// plan -> map of plans, generations, (simple-)plan
// suggestions -> filtered array of (simple-)plans
// suggestion -> (simple-)plan

class ArcPlanner extends Xen.Debug(Xen.Base, log) {
  static get observedAttributes() {
    return ['config', 'arc', 'suggestion', 'search'];
  }
  _getInitialState() {
    return {
      pendingPlans: [],
      invalid: 0
    };
  }
  _willReceiveProps(props, state, oldProps) {
    const changed = name => props[name] !== oldProps[name];
    const {arc, suggestion, search} = props;
    if (suggestion && changed('suggestion')) {
      state.pendingPlans.push(suggestion.plan);
    }
    if (arc) {
      let {planificator} = state;
      if (planificator && changed('arc')) {
        planificator.dispose();
        planificator = null;
      }
      if (!planificator) {
        planificator = this._createPlanificator(arc);
        planificator.setSearch(search);
      } else if (changed('search')) {
        planificator.setSearch(search);
      }
      this._setState({planificator});
    }
  }
  _update({arc, suggestions, search, planificator}, {pendingPlans}) {
    if (arc && pendingPlans.length) {
      this._instantiatePlan(arc, pendingPlans.shift());
    }
  }
  _createPlanificator(arc) {
    const planificator = new Arcs.Planificator(arc);
    planificator.registerPlansChangedCallback(current => this._plansChanged(current, planificator.getLastActivatedPlan()));
    planificator.registerSuggestChangedCallback(suggestions => this._suggestionsChanged(suggestions));
    return planificator;
  }
  _plansChanged(context, plan) {
    this._fire('plans', context);
    this._fire('plan', plan);
  }
  _suggestionsChanged(suggestions) {
    this._fire('suggestions', suggestions);
  }
  async _instantiatePlan(arc, plan) {
    log('instantiating plan', plan);
    await arc.instantiate(plan);
    // search term is used up
    this._fire('search', '');
    // need new suggestions
    this._fire('suggestions', null);
  }
}
customElements.define('arc-planner', ArcPlanner);
<|endoftext|>


<commit_before>module.exports = {
  'Drivers.ION': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Ion_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Ziv': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_ZIV_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.SL7000': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_SL7000_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Q1000': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Q1000_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Nexus': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Nexus_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.E3': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_E3_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Ansi': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Ansi_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Cylec': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Cylec_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Integracao.Wits': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Wits_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Tekpea': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Tekpea_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Way2 Abnt': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Abnt_Ci',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '.net4',
      'buildId': 'Drivers_AbntNet4_Ci',
      'buildBranch': '<default>'
    }
  ],
  'Manager': [
    {
      'branchDefinition': 'default',
      'buildId': 'PlataformaDeColeta_Manager_Release',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '%sprint.branch%',
      'buildId': 'PlataformaDeColeta_Manager_SprintCi',
      'buildBranch': '<default>'
    }
  ],
  'PlataformaDeColeta.Coletor': [
    {
      'branchDefinition': 'default',
      'buildId': 'PlataformaDeColeta_Coletor_Release',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '%sprint.branch%',
      'buildId': 'PlataformaDeColeta_Coletor_SprintCi',
      'buildBranch': '<default>'
    }
  ],
  'PlataformaDeColeta': [
    {
      'branchDefinition': 'default',
      'buildId': 'PlataformaDeColeta_Common_Release',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '%sprint.branch%',
      'buildId': 'PlataformaDeColeta_Common_SprintCi',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': /^#\d{4}$/,
      'buildId': 'PlataformaDeColeta_Common_Issue',
      'buildBranch': ''
    }
  ]
}
<commit_msg>Atualizar branch definition para reconhecer o formato de issues da Jira<commit_after>module.exports = {
  'Drivers.ION': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Ion_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Ziv': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_ZIV_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.SL7000': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_SL7000_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Q1000': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Q1000_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Nexus': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Nexus_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.E3': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_E3_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Ansi': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Ansi_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Cylec': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Cylec_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Integracao.Wits': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Wits_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Drivers.Tekpea': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Tekpea_Ci',
      'buildBranch': '<default>'
    },
  ],
  'Way2 Abnt': [
    {
      'branchDefinition': 'default',
      'buildId': 'Drivers_Abnt_Ci',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '.net4',
      'buildId': 'Drivers_AbntNet4_Ci',
      'buildBranch': '<default>'
    }
  ],
  'Manager': [
    {
      'branchDefinition': 'default',
      'buildId': 'PlataformaDeColeta_Manager_Release',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '%sprint.branch%',
      'buildId': 'PlataformaDeColeta_Manager_SprintCi',
      'buildBranch': '<default>'
    }
  ],
  'PlataformaDeColeta.Coletor': [
    {
      'branchDefinition': 'default',
      'buildId': 'PlataformaDeColeta_Coletor_Release',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '%sprint.branch%',
      'buildId': 'PlataformaDeColeta_Coletor_SprintCi',
      'buildBranch': '<default>'
    }
  ],
  'PlataformaDeColeta': [
    {
      'branchDefinition': 'default',
      'buildId': 'PlataformaDeColeta_Common_Release',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': '%sprint.branch%',
      'buildId': 'PlataformaDeColeta_Common_SprintCi',
      'buildBranch': '<default>'
    },
    {
      'branchDefinition': /^[A-Z0-9]+\-[0-9]+$/,
      'buildId': 'PlataformaDeColeta_Common_Issue',
      'buildBranch': ''
    }
  ]
}
<|endoftext|>


<commit_before>const TC = require('./task_collection.js');
const chalk = require('chalk');

exports.printTaskList = printTaskList;
function printTaskList(collection)
{
	const names = collection.getAllNames();
	let widthName = 0;
	let widthDesc = 0;

	names.forEach( (el, ix, ar)=>
	{
		widthName = (widthName > el.length) ? widthName : el.length;
		const t = collection.getByName(el);
		// console.log(`name: ${el} ${t}`);
		widthDesc = (widthDesc > t.description().length) ? widthDesc : t.description().length;
	})
	names.forEach((el, ix, ar) =>
	{
		const task = collection.getByName(el);
		console.log(`task : ${el}`);
		printTask(task, width);
	})
}

function pad(s, n)
{
	return " ".repeat(n);
}
function makeWidth(s, w)
{
	let s1 = s.trim();
	let s2 = (s1.length > w) ? s1.substring(0, w) : pad(s, w - s1.length);
	return  s2;
}

function printTask(task, widthName, widthDesc)
{
	const name = makeWidth(task.name(), widthName);
	const description = makeWidth(task.description(), widthDesc);
	const prereqs = task.prerequisites().join();
	const line = `${chalk.reset.bold(name)} \t ${chalk.reset.cyan(description)} \t [${prereqs}] }`;
	console.log(line);
}<commit_msg>first<commit_after>const TC = require('./task_collection.js');
const chalk = require('chalk');

exports.printTaskList = printTaskList;
function printTaskList(collection)
{
	const names = collection.getAllNames();
	let widthName = 0;
	let widthDesc = 0;

	names.forEach( (el, ix, ar)=>
	{
		widthName = (widthName > el.length) ? widthName : el.length;
		const t = collection.getByName(el);
		// console.log(`name: ${el} ${t}`);
		widthDesc = (widthDesc > t.description().length) ? widthDesc : t.description().length;
	})
	names.forEach((el, ix, ar) =>
	{
		const task = collection.getByName(el);
		console.log(`task : ${el}`);
		printTask(task, widthName, widthDesc);
	})
}

function pad(s, n)
{
	return " ".repeat(n);
}
function makeWidth(s, w)
{
	let s1 = s.trim();
	let s2 = (s1.length > w) ? s1.substring(0, w) : pad(s, w - s1.length);
	return  s2;
}

function printTask(task, widthName, widthDesc)
{
	const name = makeWidth(task.name(), widthName);
	const description = makeWidth(task.description(), widthDesc);
	const prereqs = task.prerequisites().join();
	const line = `${chalk.reset.bold(name)} \t ${chalk.reset.cyan(description)} \t [${prereqs}] }`;
	console.log(line);
}<|endoftext|>


<commit_before>require('date-utils');
var Q = require("q");
var fs = require('fs');
var request = require('request');
var conf = require("../../conf");
var SchoolServices = require("../../services/SchoolServices");
var UserServices = require("../../services/UserServices");
var TeacherServices = require("../../services/TeacherServices");
var ClassServices = require("../../services/ClassServices");

function ensure_school_is_bind (info, next) {
    if (info.session.failedCount === 5) {
        delete info.session.failedCount;
        info.ended = true;
        return next("抱歉，您的错误操作太多，请仔细阅读帮助文字。");
    }

    if (info.session.school) {
        return next();
    }

    if (info.is("text") && info.text.indexOf("SCHOOLBIND") >= 0) {
        return next();
    }

    SchoolServices.queryByOpenId(info.sp).then(function(school) {
        info.session.school = school;
        return next();
    }, function() {
        info.ended = true;
        return next("抱歉，该幼儿园的微信服务尚未激活。");
    });
}

function mobile_input_prompt(info, next) {
    info.ended = true;
    next("抱歉，本功能仅供本园家长及教师使用。\n如需认证，请点击左下角键盘图标后，直接回复您的【手机号】，例如13812345678");
}

function ensure_user_is_register (info, next) {
    if (info.session.parent || info.session.teacher) { return next(); }

    UserServices.queryByOpenId({schoolOpenId: info.sp, userOpenId: info.uid}).then(function(user) {
        switch(user.type + '') {
        case '0':
            info.session.parent = user;
            return next();
        break;
        case '1':
            info.session.teacher = user;
            if (info.session.teacher.isAdmin !== undefined) {
                return next();
            } else {
                TeacherServices.queryByUserId({userId: info.session.teacher.id}).then(function(teacher) {
                    info.session.teacher.isAdmin = teacher.is_admin;
                    ClassServices.queryBySchoolId({schoolId: info.session.school.id}).then(function(wxclasses) {
                        info.session.teacher.wxclasses = wxclasses;
                        return next();
                    }, function(err) {
                        return next(null, err);
                    });
                }, function(err) {
                    return next(null, err);
                });
            }
        break;
        default:
            return mobile_input_prompt(info, next);
        break;
        }
    }, function() {
        return mobile_input_prompt(info, next);
    });
}

function ensure_parent_is_register (info, next) {
    if (info.session.parent) {
        return next();
    } else {
        info.ended = true;
        return next("抱歉，您还不是该幼儿园的认证家长。");
    }
}

function ensure_teacher_is_register (info, next) {
    if (info.session.teacher) {
        return next();
    } else {
        info.ended = true;
        return next("抱歉，您还不是该幼儿园的认证老师。");
    }
}

function operation_is_failed(info, next) {
    if (info.session.failedCount) {
        info.session.failedCount += 1;
    } else {
        info.session.failedCount = 1;
    }
}

function createFolder(path) {
    var paths = path.split("/"), folder = conf.upload_root;
    for (var i=0; i<paths.length-1; i++) {
        folder += '/' + paths[i];
        if (!fs.existsSync(folder)) {
            fs.mkdirSync(folder, 0777);
            fs.chmodSync(folder, 0777);
        }
    }
}
function download_image(picUrl, localFile, callback) {
    createFolder(localFile);
    request.head(picUrl, function(err, res, body){
        var r = request(picUrl).pipe(fs.createWriteStream(conf.upload_root + '/' + localFile));
        r.on('finish', function () {
            fs.chmodSync(conf.upload_root + '/' + localFile, 0755);
            fs.chownSync(conf.upload_root + '/' + localFile, 48, 48)
            if (callback) { callback(); }
        });
    });
}

// Export校验功能函数
module.exports.ensure_school_is_bind = ensure_school_is_bind;

module.exports.ensure_user_is_register = ensure_user_is_register;

module.exports.ensure_parent_is_register = function (info, next) {
    if (info.session.school && info.session.parent) { return next(); }

    if (!info.session.school) {
	    ensure_school_is_bind(info, next);
    } else {
    	ensure_parent_is_register(info, next);
    }
}

module.exports.ensure_teacher_is_register = function (info, next) {
    if (info.session.school && info.session.teacher) { return next(); }

    if (!info.session.school) {
        ensure_school_is_bind(info, next);
    } else {
        ensure_teacher_is_register(info, next);
    }
}

module.exports.operation_is_failed = operation_is_failed;

module.exports.download_image = download_image;

module.exports.is_holiday = function(date) {
    var holidays = {
        '2014-01-01': true,
        '2014-01-26': false,
        '2014-01-31': true,
        '2014-02-01': true,
        '2014-02-02': true,
        '2014-02-03': true,
        '2014-02-04': true,
        '2014-02-05': true,
        '2014-02-06': true,
        '2014-02-08': false,
        '2014-04-05': true,
        '2014-04-06': true,
        '2014-04-07': true,
        '2014-05-01': true,
        '2014-05-02': true,
        '2014-05-03': true,
        '2014-05-04': false,
        '2014-05-31': true,
        '2014-06-01': true,
        '2014-06-02': true,
        '2014-09-06': true,
        '2014-09-07': true,
        '2014-09-08': true,
        '2014-09-28': false,
        '2014-10-01': true,
        '2014-10-02': true,
        '2014-10-03': true,
        '2014-10-04': true,
        '2014-10-05': true,
        '2014-10-06': true,
        '2014-10-07': true,
        '2014-10-11': false
    }
    if (holidays[date.toYMD()]) {
        return holidays[date.toYMD()];
    }
    if (date.getDay() === 0 || date.getDay() === 6) {
        return true;
    }
    return false;
}

<commit_msg>fix 777 issue<commit_after>require('date-utils');
var Q = require("q");
var fs = require('fs');
var request = require('request');
var conf = require("../../conf");
var SchoolServices = require("../../services/SchoolServices");
var UserServices = require("../../services/UserServices");
var TeacherServices = require("../../services/TeacherServices");
var ClassServices = require("../../services/ClassServices");

function ensure_school_is_bind (info, next) {
    if (info.session.failedCount === 5) {
        delete info.session.failedCount;
        info.ended = true;
        return next("抱歉，您的错误操作太多，请仔细阅读帮助文字。");
    }

    if (info.session.school) {
        return next();
    }

    if (info.is("text") && info.text.indexOf("SCHOOLBIND") >= 0) {
        return next();
    }

    SchoolServices.queryByOpenId(info.sp).then(function(school) {
        info.session.school = school;
        return next();
    }, function() {
        info.ended = true;
        return next("抱歉，该幼儿园的微信服务尚未激活。");
    });
}

function mobile_input_prompt(info, next) {
    info.ended = true;
    next("抱歉，本功能仅供本园家长及教师使用。\n如需认证，请点击左下角键盘图标后，直接回复您的【手机号】，例如13812345678");
}

function ensure_user_is_register (info, next) {
    if (info.session.parent || info.session.teacher) { return next(); }

    UserServices.queryByOpenId({schoolOpenId: info.sp, userOpenId: info.uid}).then(function(user) {
        switch(user.type + '') {
        case '0':
            info.session.parent = user;
            return next();
        break;
        case '1':
            info.session.teacher = user;
            if (info.session.teacher.isAdmin !== undefined) {
                return next();
            } else {
                TeacherServices.queryByUserId({userId: info.session.teacher.id}).then(function(teacher) {
                    info.session.teacher.isAdmin = teacher.is_admin;
                    ClassServices.queryBySchoolId({schoolId: info.session.school.id}).then(function(wxclasses) {
                        info.session.teacher.wxclasses = wxclasses;
                        return next();
                    }, function(err) {
                        return next(null, err);
                    });
                }, function(err) {
                    return next(null, err);
                });
            }
        break;
        default:
            return mobile_input_prompt(info, next);
        break;
        }
    }, function() {
        return mobile_input_prompt(info, next);
    });
}

function ensure_parent_is_register (info, next) {
    if (info.session.parent) {
        return next();
    } else {
        info.ended = true;
        return next("抱歉，您还不是该幼儿园的认证家长。");
    }
}

function ensure_teacher_is_register (info, next) {
    if (info.session.teacher) {
        return next();
    } else {
        info.ended = true;
        return next("抱歉，您还不是该幼儿园的认证老师。");
    }
}

function operation_is_failed(info, next) {
    if (info.session.failedCount) {
        info.session.failedCount += 1;
    } else {
        info.session.failedCount = 1;
    }
}

function createFolder(path) {
    var paths = path.split("/"), folder = conf.upload_root;
    for (var i=0; i<paths.length-1; i++) {
        folder += '/' + paths[i];
        if (!fs.existsSync(folder)) {
            fs.mkdirSync(folder, 0755);
            fs.chmodSync(folder, 0755);
            fs.chownSync(folder, 48, 48);
        }
    }
}
function download_image(picUrl, localFile, callback) {
    createFolder(localFile);
    request.head(picUrl, function(err, res, body){
        var r = request(picUrl).pipe(fs.createWriteStream(conf.upload_root + '/' + localFile));
        r.on('finish', function () {
            fs.chmodSync(conf.upload_root + '/' + localFile, 0755);
            fs.chownSync(conf.upload_root + '/' + localFile, 48, 48)
            if (callback) { callback(); }
        });
    });
}

// Export校验功能函数
module.exports.ensure_school_is_bind = ensure_school_is_bind;

module.exports.ensure_user_is_register = ensure_user_is_register;

module.exports.ensure_parent_is_register = function (info, next) {
    if (info.session.school && info.session.parent) { return next(); }

    if (!info.session.school) {
	    ensure_school_is_bind(info, next);
    } else {
    	ensure_parent_is_register(info, next);
    }
}

module.exports.ensure_teacher_is_register = function (info, next) {
    if (info.session.school && info.session.teacher) { return next(); }

    if (!info.session.school) {
        ensure_school_is_bind(info, next);
    } else {
        ensure_teacher_is_register(info, next);
    }
}

module.exports.operation_is_failed = operation_is_failed;

module.exports.download_image = download_image;

module.exports.is_holiday = function(date) {
    var holidays = {
        '2014-01-01': true,
        '2014-01-26': false,
        '2014-01-31': true,
        '2014-02-01': true,
        '2014-02-02': true,
        '2014-02-03': true,
        '2014-02-04': true,
        '2014-02-05': true,
        '2014-02-06': true,
        '2014-02-08': false,
        '2014-04-05': true,
        '2014-04-06': true,
        '2014-04-07': true,
        '2014-05-01': true,
        '2014-05-02': true,
        '2014-05-03': true,
        '2014-05-04': false,
        '2014-05-31': true,
        '2014-06-01': true,
        '2014-06-02': true,
        '2014-09-06': true,
        '2014-09-07': true,
        '2014-09-08': true,
        '2014-09-28': false,
        '2014-10-01': true,
        '2014-10-02': true,
        '2014-10-03': true,
        '2014-10-04': true,
        '2014-10-05': true,
        '2014-10-06': true,
        '2014-10-07': true,
        '2014-10-11': false
    }
    if (holidays[date.toYMD()]) {
        return holidays[date.toYMD()];
    }
    if (date.getDay() === 0 || date.getDay() === 6) {
        return true;
    }
    return false;
}

<|endoftext|>


<commit_before>function displayTemperature(temperature) {
    var displayTemperature = roundToOneDecimalPlace(temperature);
    document.getElementById("currentTemperature").innerHTML = displayTemperature + "°C";
    var ranges = [0,1,4,7,10,13,16,19,22,25];
    var i = 0;
    while(i < ranges.length) {
        if(displayTemperature < ranges[i]) break;
        ++i;
    }
    var tempClass = ranges[Math.max(i-1, 0)];
    document.getElementById("temperaturetile").title = tempClass;
}

function displayTodaysProgramme(programme) {
    var comfortPeriodsPanel = document.getElementById("comfortPeriods");
    var innerHtml = "";
    programme.todaysComfortPeriods.forEach(function(comfortPeriod) {
        innerHtml += " " + comfortPeriod.startTime + " – " + comfortPeriod.endTime + "
";
    });
    comfortPeriodsPanel.innerHTML = innerHtml;
}

function displayBattery(batteryVoltage) {
    $("#batteryLevelEmpty").addClass('hidden');
    $("#batteryLevelQuarter").addClass('hidden');
    $("#batteryLevelHalf").addClass('hidden');
    $("#batteryLevelThreeQuarters").addClass('hidden');
    $("#batteryLevelFull").addClass('hidden');
    if(batteryVoltage < 2.00) {
        $("#batteryLevelEmpty").removeClass('hidden');
        document.getElementById("batterytile").title = "Empty";
    } else if (batteryVoltage < 2.33) {
        $("#batteryLevelQuarter").removeClass('hidden');
        document.getElementById("batterytile").title = "Quarter";
    } else if (batteryVoltage < 2.66) {
        $("#batteryLevelHalf").removeClass('hidden');
        document.getElementById("batterytile").title = "Half";
    } else if (batteryVoltage < 2.99) {
        $("#batteryLevelThreeQuarters").removeClass('hidden');
        document.getElementById("batterytile").title = "ThreeQuarter";
    } else { // batteryVoltage >= 3
        $("#batteryLevelFull").removeClass('hidden');
        document.getElementById("batterytile").title = "Full";
    }

    var displayVoltage = roundToOneDecimalPlace(batteryVoltage)
    document.getElementById("currentBattery").innerHTML = displayVoltage + "V";
}

function displayElement(elementId, display) {
    if(display) {
        $("#" + elementId).removeClass('hidden');
        document.getElementById("modetile").title = elementId;
    }
    else {
        $("#" + elementId).addClass('hidden');
    }
}

function displayProgrammeMode(programme) {
    displayElement("currentModeSpin", false);
    displayElement("comfortMode", programme.heatingEnabled && programme.comfortLevelEnabled);
    displayElement("setbackMode", programme.heatingEnabled && !programme.comfortLevelEnabled);
    displayElement("offMode", !programme.heatingEnabled);
}

function toggleModeSelector(programme) {
    if(programme.heatingEnabled) {
        if(programme.inOverride) {
            if(programme.comfortLevelEnabled) {
                $("#comfortModeButton").button('toggle');
            }
            else {
                $("#setbackModeButton").button('toggle');
            }
        }
        else {
            $("#autoModeButton").button('toggle');
        }
    }
    else {
        $("#offModeButton").button('toggle');
    }
}

function displayView(viewData) {
    toggleModeSelector(viewData.programme);
    displayProgrammeMode(viewData.programme);
    displayTemperature(viewData.temperature);
    displayTodaysProgramme(viewData.programme);
    displayBattery(viewData.batteryVoltage);
}
function setModeViaApi(apiPath) {
    clearTimeout(reloadTimeout);
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if(xhr.status === 200) {
                // do nothing with response for now
            }
            loadView();
        }
    }
    xhr.open('GET', apiPath, true);
    xhr.send(null);
}
function onAutoModeButtonPressed() {
    setModeViaApi('api/programme/setMode/auto');
}
function onComfortModeButtonPressed() {
    setModeViaApi('api/programme/setMode/comfort');
}
function onSetbackModeButtonPressed() {
    setModeViaApi('api/programme/setMode/setback');
}
function onOffModeButtonPressed() {
    setModeViaApi('api/programme/setMode/heatingOff');
}
function bindButtons() {
    $('#autoModeButton').on('click', onAutoModeButtonPressed);
    $('#comfortModeButton').on('click', onComfortModeButtonPressed);
    $('#setbackModeButton').on('click', onSetbackModeButtonPressed);
    $('#offModeButton').on('click', onOffModeButtonPressed);
}

var reloadTimeout;

function scheduleReload() {
    reloadTimeout = window.setTimeout(loadView, 60000);
}
function initHomeView() {
    loadView();
    bindButtons();
}
function loadView() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if(xhr.status === 200) {
                var jsonResponse = JSON.parse(xhr.responseText);
                displayView(jsonResponse);
            }
            scheduleReload();
        }
    }
    xhr.open('GET', 'api/views/home', true);
    xhr.setRequestHeader("If-Modified-Since", "Mon, 27 Mar 1972 00:00:00 GMT");
    xhr.send(null);
}
<commit_msg>Split icon and text creation<commit_after>function displayTemperature(temperature) {
    var displayTemperature = roundToOneDecimalPlace(temperature);
    document.getElementById("currentTemperature").innerHTML = displayTemperature + "°C";
    var ranges = [0,1,4,7,10,13,16,19,22,25];
    var i = 0;
    while(i < ranges.length) {
        if(displayTemperature < ranges[i]) break;
        ++i;
    }
    var tempClass = ranges[Math.max(i-1, 0)];
    document.getElementById("temperaturetile").title = tempClass;
}

function displayTodaysProgramme(programme) {
    var comfortPeriodsPanel = document.getElementById("comfortPeriods");
    var innerHtml = "";
    programme.todaysComfortPeriods.forEach(function(comfortPeriod) {
        innerHtml += " ";
        innerHtml += comfortPeriod.startTime + " – " + comfortPeriod.endTime + "
";
    });
    comfortPeriodsPanel.innerHTML = innerHtml;
}

function displayBattery(batteryVoltage) {
    $("#batteryLevelEmpty").addClass('hidden');
    $("#batteryLevelQuarter").addClass('hidden');
    $("#batteryLevelHalf").addClass('hidden');
    $("#batteryLevelThreeQuarters").addClass('hidden');
    $("#batteryLevelFull").addClass('hidden');
    if(batteryVoltage < 2.00) {
        $("#batteryLevelEmpty").removeClass('hidden');
        document.getElementById("batterytile").title = "Empty";
    } else if (batteryVoltage < 2.33) {
        $("#batteryLevelQuarter").removeClass('hidden');
        document.getElementById("batterytile").title = "Quarter";
    } else if (batteryVoltage < 2.66) {
        $("#batteryLevelHalf").removeClass('hidden');
        document.getElementById("batterytile").title = "Half";
    } else if (batteryVoltage < 2.99) {
        $("#batteryLevelThreeQuarters").removeClass('hidden');
        document.getElementById("batterytile").title = "ThreeQuarter";
    } else { // batteryVoltage >= 3
        $("#batteryLevelFull").removeClass('hidden');
        document.getElementById("batterytile").title = "Full";
    }

    var displayVoltage = roundToOneDecimalPlace(batteryVoltage)
    document.getElementById("currentBattery").innerHTML = displayVoltage + "V";
}

function displayElement(elementId, display) {
    if(display) {
        $("#" + elementId).removeClass('hidden');
        document.getElementById("modetile").title = elementId;
    }
    else {
        $("#" + elementId).addClass('hidden');
    }
}

function displayProgrammeMode(programme) {
    displayElement("currentModeSpin", false);
    displayElement("comfortMode", programme.heatingEnabled && programme.comfortLevelEnabled);
    displayElement("setbackMode", programme.heatingEnabled && !programme.comfortLevelEnabled);
    displayElement("offMode", !programme.heatingEnabled);
}

function toggleModeSelector(programme) {
    if(programme.heatingEnabled) {
        if(programme.inOverride) {
            if(programme.comfortLevelEnabled) {
                $("#comfortModeButton").button('toggle');
            }
            else {
                $("#setbackModeButton").button('toggle');
            }
        }
        else {
            $("#autoModeButton").button('toggle');
        }
    }
    else {
        $("#offModeButton").button('toggle');
    }
}

function displayView(viewData) {
    toggleModeSelector(viewData.programme);
    displayProgrammeMode(viewData.programme);
    displayTemperature(viewData.temperature);
    displayTodaysProgramme(viewData.programme);
    displayBattery(viewData.batteryVoltage);
}
function setModeViaApi(apiPath) {
    clearTimeout(reloadTimeout);
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if(xhr.status === 200) {
                // do nothing with response for now
            }
            loadView();
        }
    }
    xhr.open('GET', apiPath, true);
    xhr.send(null);
}
function onAutoModeButtonPressed() {
    setModeViaApi('api/programme/setMode/auto');
}
function onComfortModeButtonPressed() {
    setModeViaApi('api/programme/setMode/comfort');
}
function onSetbackModeButtonPressed() {
    setModeViaApi('api/programme/setMode/setback');
}
function onOffModeButtonPressed() {
    setModeViaApi('api/programme/setMode/heatingOff');
}
function bindButtons() {
    $('#autoModeButton').on('click', onAutoModeButtonPressed);
    $('#comfortModeButton').on('click', onComfortModeButtonPressed);
    $('#setbackModeButton').on('click', onSetbackModeButtonPressed);
    $('#offModeButton').on('click', onOffModeButtonPressed);
}

var reloadTimeout;

function scheduleReload() {
    reloadTimeout = window.setTimeout(loadView, 60000);
}
function initHomeView() {
    loadView();
    bindButtons();
}
function loadView() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if(xhr.status === 200) {
                var jsonResponse = JSON.parse(xhr.responseText);
                displayView(jsonResponse);
            }
            scheduleReload();
        }
    }
    xhr.open('GET', 'api/views/home', true);
    xhr.setRequestHeader("If-Modified-Since", "Mon, 27 Mar 1972 00:00:00 GMT");
    xhr.send(null);
}
<|endoftext|>