<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

/* Derived from Python highlighing rules */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var FortranHighlightRules = function() {

    var keywords = (
        "call|case|contains|continue|cycle|do|else|elseif|end|enddo|endif|function|"+
        "if|implicit|in|include|inout|intent|module|none|only|out|print|program|return|"+
        "select|status|stop|subroutine|" +
        "return|then|use|while|write|"+
        "CALL|CASE|CONTAINS|CONTINUE|CYCLE|DO|ELSE|ELSEIF|END|ENDDO|ENDIF|FUNCTION|"+
        "IF|IMPLICIT|IN|INCLUDE|INOUT|INTENT|MODULE|NONE|ONLY|OUT|PRINT|PROGRAM|RETURN|"+
        "SELECT|STATUS|STOP|SUBROUTINE|" +
        "RETURN|THEN|USE|WHILE|WRITE"
    );

    var keywordOperators = (
        "and|or|not|eq|ne|gt|ge|lt|le|" +
        "AND|OR|NOT|EQ|NE|GT|GE|LT|LE"
    );

    var builtinConstants = (
        "true|false|TRUE|FALSE"
    );

    var builtinFunctions = (
        "abs|achar|acos|acosh|adjustl|adjustr|aimag|aint|all|allocate|"+
        "anint|any|asin|asinh|associated|atan|atan2|atanh|"+
        "bessel_j0|bessel_j1|bessel_jn|bessel_y0|bessel_y1|bessel_yn|"+
        "bge|bgt|bit_size|ble|blt|btest|ceiling|char|cmplx|conjg|cos|cosh|"+
        "count|cpu_time|cshift|date_and_time|dble|deallocate|digits|dim|dot_product|dprod|"+
        "dshiftl|dshiftr|dsqrt|eoshift|epsilon|erf|erfc|erfc_scaled|exp|float|floor|"+
        "format|fraction|gamma|input|len|lge|lgt|lle|llt|log|log10|maskl|maskr|matmul|max|maxloc|maxval|"+
        "merge|min|minloc|minval|mod|modulo|nint|not|norm2|null|nullify|pack|parity|popcnt|poppar|"+
        "precision|present|product|radix|random_number|random_seed|range|repeat|reshape|round|"+
        "rrspacing|same_type_as|scale|scan|selected_char_kind|selected_int_kind|selected_real_kind|"+
        "set_exponent|shape|shifta|shiftl|shiftr|sign|sin|sinh|size|sngl|spacing|spread|"+
        "sqrt|sum|system_clock|tan|tanh|tiny|trailz|transfer|transpose|trim|ubound|unpack|verify|" +
        "ABS|ACHAR|ACOS|ACOSH|ADJUSTL|ADJUSTR|AIMAG|AINT|ALL|ALLOCATE|"+
        "ANINT|ANY|ASIN|ASINH|ASSOCIATED|ATAN|ATAN2|ATANH|"+
        "BESSEL_J0|BESSEL_J1|BESSEL_JN|BESSEL_Y0|BESSEL_Y1|BESSEL_YN|"+
        "BGE|BGT|BIT_SIZE|BLE|BLT|BTEST|CEILING|CHAR|CMPLX|CONJG|COS|COSH|"+
        "COUNT|CPU_TIME|CSHIFT|DATE_AND_TIME|DBLE|DEALLOCATE|DIGITS|DIM|DOT_PRODUCT|DPROD|"+
        "DSHIFTL|DSHIFTR|DSQRT|EOSHIFT|EPSILON|ERF|ERFC|ERFC_SCALED|EXP|FLOAT|FLOOR|"+
        "FORMAT|FRACTION|GAMMA|INPUT|LEN|LGE|LGT|LLE|LLT|LOG|LOG10|MASKL|MASKR|MATMUL|MAX|MAXLOC|MAXVAL|"+
        "MERGE|MIN|MINLOC|MINVAL|MOD|MODULO|NINT|NOT|NORM2|NULL|NULLIFY|PACK|PARITY|POPCNT|POPPAR|"+
        "PRECISION|PRESENT|PRODUCT|RADIX|RANDOM_NUMBER|RANDOM_SEED|RANGE|REPEAT|RESHAPE|ROUND|"+
        "RRSPACING|SAME_TYPE_AS|SCALE|SCAN|SELECTED_CHAR_KIND|SELECTED_INT_KIND|SELECTED_REAL_KIND|"+
        "SET_EXPONENT|SHAPE|SHIFTA|SHIFTL|SHIFTR|SIGN|SIN|SINH|SIZE|SNGL|SPACING|SPREAD|"+
        "SQRT|SUM|SYSTEM_CLOCK|TAN|TANH|TINY|TRAILZ|TRANSFER|TRANSPOSE|TRIM|UBOUND|UNPACK|VERIFY"
    );

    var storageType = (
        "logical|character|integer|real|type|" +
        "LOGICAL|CHARACTER|INTEGER|REAL|TYPE"
    );

    var storageModifiers = (
        "allocatable|dimension|intent|parameter|pointer|target|private|public|" +
        "ALLOCATABLE|DIMENSION|INTENT|PARAMETER|POINTER|TARGET|PRIVATE|PUBLIC"
    );

    var keywordMapper = this.createKeywordMapper({
        "invalid.deprecated": "debugger",
        "support.function": builtinFunctions,
        "constant.language": builtinConstants,
        "keyword": keywords,
        "keyword.operator": keywordOperators,
        "storage.type": storageType,
        "storage.modifier" : storageModifiers
    }, "identifier");

    var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?";

    var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
    var octInteger = "(?:0[oO]?[0-7]+)";
    var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
    var binInteger = "(?:0[bB][01]+)";
    var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")";

    var exponent = "(?:[eE][+-]?\\d+)";
    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + exponent + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";

    var stringEscape =  "\\\\(x[0-9A-Fa-f]{2}|[0-7]{3}|[\\\\abfnrtv'\"]|U[0-9A-Fa-f]{8}|u[0-9A-Fa-f]{4})";

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "!.*$"
        }, {
            token : "string",           // multi line """ string start
            regex : strPre + '"{3}',
            next : "qqstring3"
        }, {
            token : "string",           // " string
            regex : strPre + '"(?=.)',
            next : "qqstring"
        }, {
            token : "string",           // multi line ''' string start
            regex : strPre + "'{3}",
            next : "qstring3"
        }, {
            token : "string",           // ' string
            regex : strPre + "'(?=.)",
            next : "qstring"
        }, {
            token : "constant.numeric", // imaginary
            regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // long integer
            regex : integer + "[lL]\\b"
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : "keyword", // pre-compiler directives
            regex : "#\\s*(?:include|import|define|undef|INCLUDE|IMPORT|DEFINE|UNDEF)\\b",
            next  : "directive"
        }, {
            token : "keyword", // special case pre-compiler directive
            regex : "#\\s*(?:endif|ifdef|else|elseif|ifndef|ENDIF|IFDEF|ELSE|ELSEIF|IFNDEF)\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "qqstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string", // multi line """ string end
            regex : '"{3}',
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string", // multi line """ string end
            regex : '"{3}',
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",  // multi line ''' string end
            regex : "'{3}",
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qqstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qqstring"
        }, {
            token : "string",
            regex : '"|$',
            next  : "start"
        }, {
            defaultToken: "string"
        }],
        "qstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qstring"
        }, {
            token : "string",
            regex : "'|$",
            next  : "start"
        }, {
            defaultToken: "string"
        }]
    };
};

oop.inherits(FortranHighlightRules, TextHighlightRules);

exports.FortranHighlightRules = FortranHighlightRules;
});
<commit_msg>Fixed qstring3 error<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

/* Derived from Python highlighing rules */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var FortranHighlightRules = function() {

    var keywords = (
        "call|case|contains|continue|cycle|do|else|elseif|end|enddo|endif|function|"+
        "if|implicit|in|include|inout|intent|module|none|only|out|print|program|return|"+
        "select|status|stop|subroutine|" +
        "return|then|use|while|write|"+
        "CALL|CASE|CONTAINS|CONTINUE|CYCLE|DO|ELSE|ELSEIF|END|ENDDO|ENDIF|FUNCTION|"+
        "IF|IMPLICIT|IN|INCLUDE|INOUT|INTENT|MODULE|NONE|ONLY|OUT|PRINT|PROGRAM|RETURN|"+
        "SELECT|STATUS|STOP|SUBROUTINE|" +
        "RETURN|THEN|USE|WHILE|WRITE"
    );

    var keywordOperators = (
        "and|or|not|eq|ne|gt|ge|lt|le|" +
        "AND|OR|NOT|EQ|NE|GT|GE|LT|LE"
    );

    var builtinConstants = (
        "true|false|TRUE|FALSE"
    );

    var builtinFunctions = (
        "abs|achar|acos|acosh|adjustl|adjustr|aimag|aint|all|allocate|"+
        "anint|any|asin|asinh|associated|atan|atan2|atanh|"+
        "bessel_j0|bessel_j1|bessel_jn|bessel_y0|bessel_y1|bessel_yn|"+
        "bge|bgt|bit_size|ble|blt|btest|ceiling|char|cmplx|conjg|cos|cosh|"+
        "count|cpu_time|cshift|date_and_time|dble|deallocate|digits|dim|dot_product|dprod|"+
        "dshiftl|dshiftr|dsqrt|eoshift|epsilon|erf|erfc|erfc_scaled|exp|float|floor|"+
        "format|fraction|gamma|input|len|lge|lgt|lle|llt|log|log10|maskl|maskr|matmul|max|maxloc|maxval|"+
        "merge|min|minloc|minval|mod|modulo|nint|not|norm2|null|nullify|pack|parity|popcnt|poppar|"+
        "precision|present|product|radix|random_number|random_seed|range|repeat|reshape|round|"+
        "rrspacing|same_type_as|scale|scan|selected_char_kind|selected_int_kind|selected_real_kind|"+
        "set_exponent|shape|shifta|shiftl|shiftr|sign|sin|sinh|size|sngl|spacing|spread|"+
        "sqrt|sum|system_clock|tan|tanh|tiny|trailz|transfer|transpose|trim|ubound|unpack|verify|" +
        "ABS|ACHAR|ACOS|ACOSH|ADJUSTL|ADJUSTR|AIMAG|AINT|ALL|ALLOCATE|"+
        "ANINT|ANY|ASIN|ASINH|ASSOCIATED|ATAN|ATAN2|ATANH|"+
        "BESSEL_J0|BESSEL_J1|BESSEL_JN|BESSEL_Y0|BESSEL_Y1|BESSEL_YN|"+
        "BGE|BGT|BIT_SIZE|BLE|BLT|BTEST|CEILING|CHAR|CMPLX|CONJG|COS|COSH|"+
        "COUNT|CPU_TIME|CSHIFT|DATE_AND_TIME|DBLE|DEALLOCATE|DIGITS|DIM|DOT_PRODUCT|DPROD|"+
        "DSHIFTL|DSHIFTR|DSQRT|EOSHIFT|EPSILON|ERF|ERFC|ERFC_SCALED|EXP|FLOAT|FLOOR|"+
        "FORMAT|FRACTION|GAMMA|INPUT|LEN|LGE|LGT|LLE|LLT|LOG|LOG10|MASKL|MASKR|MATMUL|MAX|MAXLOC|MAXVAL|"+
        "MERGE|MIN|MINLOC|MINVAL|MOD|MODULO|NINT|NOT|NORM2|NULL|NULLIFY|PACK|PARITY|POPCNT|POPPAR|"+
        "PRECISION|PRESENT|PRODUCT|RADIX|RANDOM_NUMBER|RANDOM_SEED|RANGE|REPEAT|RESHAPE|ROUND|"+
        "RRSPACING|SAME_TYPE_AS|SCALE|SCAN|SELECTED_CHAR_KIND|SELECTED_INT_KIND|SELECTED_REAL_KIND|"+
        "SET_EXPONENT|SHAPE|SHIFTA|SHIFTL|SHIFTR|SIGN|SIN|SINH|SIZE|SNGL|SPACING|SPREAD|"+
        "SQRT|SUM|SYSTEM_CLOCK|TAN|TANH|TINY|TRAILZ|TRANSFER|TRANSPOSE|TRIM|UBOUND|UNPACK|VERIFY"
    );

    var storageType = (
        "logical|character|integer|real|type|" +
        "LOGICAL|CHARACTER|INTEGER|REAL|TYPE"
    );

    var storageModifiers = (
        "allocatable|dimension|intent|parameter|pointer|target|private|public|" +
        "ALLOCATABLE|DIMENSION|INTENT|PARAMETER|POINTER|TARGET|PRIVATE|PUBLIC"
    );

    var keywordMapper = this.createKeywordMapper({
        "invalid.deprecated": "debugger",
        "support.function": builtinFunctions,
        "constant.language": builtinConstants,
        "keyword": keywords,
        "keyword.operator": keywordOperators,
        "storage.type": storageType,
        "storage.modifier" : storageModifiers
    }, "identifier");

    var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?";

    var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
    var octInteger = "(?:0[oO]?[0-7]+)";
    var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
    var binInteger = "(?:0[bB][01]+)";
    var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")";

    var exponent = "(?:[eE][+-]?\\d+)";
    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + exponent + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";

    var stringEscape =  "\\\\(x[0-9A-Fa-f]{2}|[0-7]{3}|[\\\\abfnrtv'\"]|U[0-9A-Fa-f]{8}|u[0-9A-Fa-f]{4})";

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "!.*$"
        }, {
            token : "string",           // multi line """ string start
            regex : strPre + '"{3}',
            next : "qqstring3"
        }, {
            token : "string",           // " string
            regex : strPre + '"(?=.)',
            next : "qqstring"
        }, {
            token : "string",           // multi line ''' string start
            regex : strPre + "'{3}",
            next : "qstring3"
        }, {
            token : "string",           // ' string
            regex : strPre + "'(?=.)",
            next : "qstring"
        }, {
            token : "constant.numeric", // imaginary
            regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // long integer
            regex : integer + "[lL]\\b"
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : "keyword", // pre-compiler directives
            regex : "#\\s*(?:include|import|define|undef|INCLUDE|IMPORT|DEFINE|UNDEF)\\b",
            next  : "directive"
        }, {
            token : "keyword", // special case pre-compiler directive
            regex : "#\\s*(?:endif|ifdef|else|elseif|ifndef|ENDIF|IFDEF|ELSE|ELSEIF|IFNDEF)\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "qqstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string", // multi line """ string end
            regex : '"{3}',
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string", // multi line """ string end
            regex : '"{3}',
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qqstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qqstring"
        }, {
            token : "string",
            regex : '"|$',
            next  : "start"
        }, {
            defaultToken: "string"
        }],
        "qstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qstring"
        }, {
            token : "string",
            regex : "'|$",
            next  : "start"
        }, {
            defaultToken: "string"
        }]
    };
};

oop.inherits(FortranHighlightRules, TextHighlightRules);

exports.FortranHighlightRules = FortranHighlightRules;
});
<|endoftext|>


<commit_before>/**
 * ConmceptsController
 *
 * @description :: Server-side logic for managing sdas
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

var jsonld = require('jsonld'),
  Promise = require('bluebird'),
  spawn = require('child_process').spawn,
  uuid = require('node-uuid'),
  path = require('path'),
  fs = require('fs');

module.exports = {
  physicalAssets: function(req, res) {
    console.log('[ConceptsController::physicalAssets] incoming request');

    var items = {
      "head": {
        "link": [],
        "vars": ["label", "latitude", 'longitude', 'description']
      },
      "results": {
        "distinct": false,
        "ordered": true,
        "bindings": [{
          "label": {
            "type": "uri",
            "value": "Haus 30"
          },
          "latitude": {
            "type": "uri",
            "value": "47"
          },
          "longitude": {
            "type": "uri",
            "value": "14"
          },
          "description": {
            "type": "uri",
            "value": "The legendary Haus 30."
          }
        }, {
          "label": {
            "type": "uri",
            "value": "Nygade"
          },
          "latitude": {
            "type": "uri",
            "value": "47.1"
          },
          "longitude": {
            "type": "uri",
            "value": "14.1"
          },
          "description": {
            "type": "uri",
            "value": "The legendary Nygade dataset."
          }
        }, {
          "label": {
            "type": "uri",
            "value": "Bygade"
          },
          "latitude": {
            "type": "uri",
            "value": "47.2"
          },
          "longitude": {
            "type": "uri",
            "value": "14.2"
          },
          "description": {
            "type": "uri",
            "value": "The legendary Bygade dataset."
          }
        }],
      }
    }

    res.send(items).status(200);
  }
};

function generateURI(buildm) {
  // console.log('type: ' + JSON.stringify(buildm['@type'], null, 4));

  var type = 'duraark';

  if (buildm['@type'] && buildm['@type'][0]) {
    type = buildm['@type'][0].split('/').pop().toLowerCase();
  }

  var uri = 'http://data.duraark.eu/' + type + '_' + uuid.v4();
  // console.log('uri: ' + uri);

  return uri;
}

function insertIntoSDAS(nquads) {
  return new Promise(function(resolve, reject) {

    var outputFile = path.join('/tmp', uuid.v4() + '.ttl');
    // outputFile = '/home/hecher/Projects/duraark-system/duraark-sda/scripts/rdf/books2.ttl';

    console.log('RDF file to store: ' + outputFile);

    fs.writeFileSync(outputFile, nquads);

    try {
      // FIXXME: read credentials and host from config file!
      var args = '--digest --user dba:dba --url http://duraark-sdas:8890/sparql-graph-crud-auth?graph-uri=http://fha.local/playground -X POST -T ' + outputFile;

      // console.log('args: ' + JSON.stringify(args.split(' '), null, 4));

      console.log('[SdasController::insertIntoSDAS] about to run: "curl ' + args + '"');

      var executable = spawn('curl', args.split(' '));

      executable.stdout.on('data', function(data) {
        console.log('stdout: ' + data);
      });

      executable.stderr.on('data', function(err) {
        console.log(err.toString());
        //  return reject('[SdasController::insertIntoSDAS] ERROR during program execution:\n\n' + err);
      });

      executable.on('close', function(code) {
        if (code !== 0) { // 'e57metadata' return '1' on success
          console.log('[SdasController::insertIntoSDAS] ERROR: exited with code:' + code);
          return reject('[SdasController::insertIntoSDAS] ERROR: exited with code: \n\n' + code + '\n');
        }

        console.log('[SdasController::insertIntoSDAS]     ... finished');
        resolve();
      });
    } catch (err) {
      console.log('[SdasController::insertIntoSDAS] ERROR on program start:\n\n' + err + '\n');
      return reject('[SdasController::insertIntoSDAS] ERROR on program start:\n\n' + err);
    }
  });
}
<commit_msg>changed gps coordinates<commit_after>/**
 * ConmceptsController
 *
 * @description :: Server-side logic for managing sdas
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

var jsonld = require('jsonld'),
  Promise = require('bluebird'),
  spawn = require('child_process').spawn,
  uuid = require('node-uuid'),
  path = require('path'),
  fs = require('fs');

module.exports = {
  physicalAssets: function(req, res) {
    console.log('[ConceptsController::physicalAssets] incoming request');

    var items = {
      "head": {
        "link": [],
        "vars": ["label", "latitude", 'longitude', 'description']
      },
      "results": {
        "distinct": false,
        "ordered": true,
        "bindings": [{
          "label": {
            "type": "uri",
            "value": "Haus 30"
          },
          "latitude": {
            "type": "uri",
            "value": "47"
          },
          "longitude": {
            "type": "uri",
            "value": "15.3"
          },
          "description": {
            "type": "uri",
            "value": "The legendary Haus 30."
          }
        }, {
          "label": {
            "type": "uri",
            "value": "Nygade"
          },
          "latitude": {
            "type": "uri",
            "value": "47"
          },
          "longitude": {
            "type": "uri",
            "value": "15.4"
          },
          "description": {
            "type": "uri",
            "value": "The legendary Nygade dataset."
          }
        }, {
          "label": {
            "type": "uri",
            "value": "Bygade"
          },
          "latitude": {
            "type": "uri",
            "value": "47"
          },
          "longitude": {
            "type": "uri",
            "value": "15.5"
          },
          "description": {
            "type": "uri",
            "value": "The legendary Bygade dataset."
          }
        }],
      }
    }

    res.send(items).status(200);
  }
};

function generateURI(buildm) {
  // console.log('type: ' + JSON.stringify(buildm['@type'], null, 4));

  var type = 'duraark';

  if (buildm['@type'] && buildm['@type'][0]) {
    type = buildm['@type'][0].split('/').pop().toLowerCase();
  }

  var uri = 'http://data.duraark.eu/' + type + '_' + uuid.v4();
  // console.log('uri: ' + uri);

  return uri;
}

function insertIntoSDAS(nquads) {
  return new Promise(function(resolve, reject) {

    var outputFile = path.join('/tmp', uuid.v4() + '.ttl');
    // outputFile = '/home/hecher/Projects/duraark-system/duraark-sda/scripts/rdf/books2.ttl';

    console.log('RDF file to store: ' + outputFile);

    fs.writeFileSync(outputFile, nquads);

    try {
      // FIXXME: read credentials and host from config file!
      var args = '--digest --user dba:dba --url http://duraark-sdas:8890/sparql-graph-crud-auth?graph-uri=http://fha.local/playground -X POST -T ' + outputFile;

      // console.log('args: ' + JSON.stringify(args.split(' '), null, 4));

      console.log('[SdasController::insertIntoSDAS] about to run: "curl ' + args + '"');

      var executable = spawn('curl', args.split(' '));

      executable.stdout.on('data', function(data) {
        console.log('stdout: ' + data);
      });

      executable.stderr.on('data', function(err) {
        console.log(err.toString());
        //  return reject('[SdasController::insertIntoSDAS] ERROR during program execution:\n\n' + err);
      });

      executable.on('close', function(code) {
        if (code !== 0) { // 'e57metadata' return '1' on success
          console.log('[SdasController::insertIntoSDAS] ERROR: exited with code:' + code);
          return reject('[SdasController::insertIntoSDAS] ERROR: exited with code: \n\n' + code + '\n');
        }

        console.log('[SdasController::insertIntoSDAS]     ... finished');
        resolve();
      });
    } catch (err) {
      console.log('[SdasController::insertIntoSDAS] ERROR on program start:\n\n' + err + '\n');
      return reject('[SdasController::insertIntoSDAS] ERROR on program start:\n\n' + err);
    }
  });
}
<|endoftext|>


<commit_before>$(function() {
    var jumboTron = {
        $headerField: $("#jHeader"),
        $bodyField: $("#jBody"),
        init: function(header, body) {
            this.header = header;
            this.body = body;
            this.render();
        },
        render: function() {
            this.$headerField.html(this.header);
            this.$bodyField.html(this.body);
        }
    }

    var historyTable = {
        $panel: $("#historyPanel"),
        $tableBody: $("#historyTableBody"),
        init: function(name, histories) {
            this.name = name;
            this.histories = histories;
            this.render();
        },
        render: function() {
            if(this.histories.length == 0) {
                this.$panel.css("display", "none");
            } else {
                this.$panel.css("display", "block");
                this.$tableBody.empty();
                for(var a = 0; a < Math.min(5, this.histories.length); a++) {
                    this.$tableBody.append(this.getTableRow(this.histories[a]));
                }
            }
        },
        getTableRow: function(history) {
            return "
"+this.name+" v"+history.versionNumber+"	"+history.lastRank+" of "+history.lastNumPlayers+"	"+(history.lastNumGames != null ? history.lastNumGames : "Not Recorded")+"
";
        }
    }

    var statTable = {
        $tableBody: $("#statTableBody"),
        stats: [],
        init: function(stats) {
            this.stats = stats;
            this.render();
        },
        render: function() {
            this.$tableBody.empty();
            for(var a = 0; a < this.stats.length; a++) {
                this.$tableBody.append(this.getTableRow(this.stats[a]));
            }
        },
        getTableRow: function(stat) {
            if(stat.mouseOverText != undefined && stat.mouseOverText != null) {
                return "
"+stat.name+"	"+stat.value+"
";
            } else {
                return "
"+stat.name+"	"+stat.value+"
";
            }
        }
    }

    var gameTable = {
        $tableHeader: $("#gameTableHeader"),
        $tableBody: $("#gameTableBody"),
        $loadButton: $("#loadButton"),
        games: [],
        init: function(userID, isMe, getNextGames) {
            this.userID = userID;
            this.getNextGames = getNextGames;
            this.games = getNextGames(this.userID);
            this.isMe = isMe;

            this.$loadButton.click(this, this.loadMore.bind(this));

            this.render();
        },
        render: function() {
            this.$tableHeader.html("Participants	Result	Dimensions	View	");
            if(this.isMe) this.$tableHeader.append("Error Log	");
            this.$tableBody.empty();
            for(var a = 0; a < this.games.length; a++) {
                this.$tableBody.append(this.getTableRow(this.games[a]));
            }
        },
        getTableRow: function(game) {
            var playersList = "
";
            var userID = this.userID;
            playersList += game.players.map(function(player) {
                if(player.userID == userID) {
                    return "
"+player.username+"
";
                } else {
                    return "
"+player.username+"
";
                }
            }).join(" ");

            playersList += "
";
            var $row = $("
"+playersList+"	"+game.result+"	"+game.mapWidth+"x"+game.mapHeight+"
");
            if(this.isMe) {
                var me = null;
                for(var a = 0; a < game.players.length; a++) {
                    if(game.players[a].userID == this.userID) {
                        me = game.players[a];
                        break;
                    }
                }
                if(me.errorLogName != undefined && me.errorLogName != null) $row.append("	");
                else $row.append("NA	");
            }
            return $row;
        },
        loadMore: function() {
            this.games = this.games.concat(this.getNextGames(this.userID, this.games[this.games.length-1].gameID));
            this.render();
        }
    }

    var session = getSession();

    var userID = getGET("userID");
    if(userID == null || userID == undefined) userID = parseInt(session.userID);

    var user = getUser(userID);
    user["score"] = Math.round(100*(user["mu"]-3*user["sigma"]))/100;
    user["didTimeout"] = (Math.round(1000*user["didTimeout"])/10) + "%";

    var numUsers = getNumActiveUsers();

    $(document).prop('title', user.username);

	$("#name").html(user['username']);
	$("#primary-info").html(user['rank']+" of "+numUsers+" | "+(Math.round((user['mu']-user['sigma']*3)*100)/100)+" points");
	$("#secondary-info").html("Made in "+user['language']+"
"+(user['organization']=='Other' ? "" : "Member of " + user['organization'] + "
")+user['numSubmissions']+" bots submitted
"+user['numGames']+" games played");

    gameTable.init(userID, session != null && parseInt(session.userID) == userID, function(userID, startingID) {
        console.log(startingID)
        var rawGames = getLatestGamesForUser(userID, 10, startingID);
        console.log(rawGames);
        var games = [];
        for(var a = 0; a < rawGames.length; a++) {
            var players = rawGames[a].users;
            players.sort(function(p1, p2) {
                return parseInt(p1.rank) - parseInt(p2.rank);
            });
            var thisUser = players.find(function(p){return parseInt(p.userID)==userID;});
            var result = thisUser.rank + " of " + players.length;

            games.push({
                gameID: rawGames[a].gameID,
                players: players,
                result: result,
                mapWidth: rawGames[a].mapWidth,
                mapHeight: rawGames[a].mapHeight,
                replayName: rawGames[a].replayName
            });
        }
        console.log(games)
        return games;
    });
    historyTable.init(user.username, getHistories(userID));
})
<commit_msg>Basic leagues<commit_after>$(function() {
    var jumboTron = {
        $headerField: $("#jHeader"),
        $bodyField: $("#jBody"),
        init: function(header, body) {
            this.header = header;
            this.body = body;
            this.render();
        },
        render: function() {
            this.$headerField.html(this.header);
            this.$bodyField.html(this.body);
        }
    }

    var historyTable = {
        $panel: $("#historyPanel"),
        $tableBody: $("#historyTableBody"),
        init: function(name, histories) {
            this.name = name;
            this.histories = histories;
            this.render();
        },
        render: function() {
            if(this.histories.length == 0) {
                this.$panel.css("display", "none");
            } else {
                this.$panel.css("display", "block");
                this.$tableBody.empty();
                for(var a = 0; a < Math.min(5, this.histories.length); a++) {
                    this.$tableBody.append(this.getTableRow(this.histories[a]));
                }
            }
        },
        getTableRow: function(history) {
            return "
"+this.name+" v"+history.versionNumber+"	"+history.lastRank+" of "+history.lastNumPlayers+"	"+(history.lastNumGames != null ? history.lastNumGames : "Not Recorded")+"
";
        }
    }

    var statTable = {
        $tableBody: $("#statTableBody"),
        stats: [],
        init: function(stats) {
            this.stats = stats;
            this.render();
        },
        render: function() {
            this.$tableBody.empty();
            for(var a = 0; a < this.stats.length; a++) {
                this.$tableBody.append(this.getTableRow(this.stats[a]));
            }
        },
        getTableRow: function(stat) {
            if(stat.mouseOverText != undefined && stat.mouseOverText != null) {
                return "
"+stat.name+"	"+stat.value+"
";
            } else {
                return "
"+stat.name+"	"+stat.value+"
";
            }
        }
    }

    var gameTable = {
        $tableHeader: $("#gameTableHeader"),
        $tableBody: $("#gameTableBody"),
        $loadButton: $("#loadButton"),
        games: [],
        init: function(userID, isMe, getNextGames) {
            this.userID = userID;
            this.getNextGames = getNextGames;
            this.games = getNextGames(this.userID);
            this.isMe = isMe;

            this.$loadButton.click(this, this.loadMore.bind(this));

            this.render();
        },
        render: function() {
            this.$tableHeader.html("Participants	Result	Dimensions	View	");
            if(this.isMe) this.$tableHeader.append("Error Log	");
            this.$tableBody.empty();
            for(var a = 0; a < this.games.length; a++) {
                this.$tableBody.append(this.getTableRow(this.games[a]));
            }
        },
        getTableRow: function(game) {
            var playersList = "
";
            var userID = this.userID;
            playersList += game.players.map(function(player) {
                if(player.userID == userID) {
                    return "
"+player.username+"
";
                } else {
                    return "
"+player.username+"
";
                }
            }).join(" ");

            playersList += "
";
            var $row = $("
"+playersList+"	"+game.result+"	"+game.mapWidth+"x"+game.mapHeight+"
");
            if(this.isMe) {
                var me = null;
                for(var a = 0; a < game.players.length; a++) {
                    if(game.players[a].userID == this.userID) {
                        me = game.players[a];
                        break;
                    }
                }
                if(me.errorLogName != undefined && me.errorLogName != null) $row.append("	");
                else $row.append("NA	");
            }
            return $row;
        },
        loadMore: function() {
            this.games = this.games.concat(this.getNextGames(this.userID, this.games[this.games.length-1].gameID));
            this.render();
        }
    }

    var session = getSession();

    var userID = getGET("userID");
    if(userID == null || userID == undefined) userID = parseInt(session.userID);

    var user = getUser(userID);
    user["score"] = Math.round(100*(user["mu"]-3*user["sigma"]))/100;
    user["didTimeout"] = (Math.round(1000*user["didTimeout"])/10) + "%";

    var numUsers = parseInt(getNumActiveUsers());
    var percentile = parseInt(user['rank']) / numUsers;
    var tier = "Bronze";
    if(percentile < 1/32) tier = "Diamond";
    if(percentile < 1/16) tier = "Gold";
    if(percentile < 1/4) tier = "Silver";

    $(document).prop('title', user.username);

    $("#name").html(user['username']);
    $("#primary-info").html(tier + " Tier | " + user['rank']+" of "+numUsers+" | "+(Math.round((user['mu']-user['sigma']*3)*100)/100)+" points");
    $("#secondary-info").html("Made in "+user['language']+"
"+(user['organization']=='Other' ? "" : "Member of " + user['organization'] + "
")+user['numSubmissions']+" bots submitted
"+user['numGames']+" games played");

    gameTable.init(userID, session != null && parseInt(session.userID) == userID, function(userID, startingID) {
        console.log(startingID)
        var rawGames = getLatestGamesForUser(userID, 10, startingID);
        console.log(rawGames);
        var games = [];
        for(var a = 0; a < rawGames.length; a++) {
            var players = rawGames[a].users;
            players.sort(function(p1, p2) {
                return parseInt(p1.rank) - parseInt(p2.rank);
            });
            var thisUser = players.find(function(p){return parseInt(p.userID)==userID;});
            var result = thisUser.rank + " of " + players.length;

            games.push({
                gameID: rawGames[a].gameID,
                players: players,
                result: result,
                mapWidth: rawGames[a].mapWidth,
                mapHeight: rawGames[a].mapHeight,
                replayName: rawGames[a].replayName
            });
        }
        console.log(games)
        return games;
    });
    historyTable.init(user.username, getHistories(userID));
})
<|endoftext|>


<commit_before>'use strict';

var Alexa = require('alexa-sdk');
var http = require('http');
var querystring = require('querystring');

var APP_ID = undefined; // TODO replace with your app ID (OPTIONAL).

var HeaterMeterHost=process.env.heatermeterHost;
var apiKey = process.env.apiKey;

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
   try {
       console.log("event.session.application.applicationId=" + event.session.application.applicationId);
       /**
        * Uncomment this if statement and populate with your skill's application ID to
        * prevent someone else from configuring a skill that sends requests to this function.
        */
       /*
       if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.[unique-value-here]") {
            context.fail("Invalid Application ID");
       }
       */
       if (event.session.new) {
           onSessionStarted({ requestId: event.request.requestId }, event.session);
       }
       if (event.request.type === "LaunchRequest") {
           onLaunch(event.request,
               event.session,
               function callback(sessionAttributes, speechletResponse) {
                   context.succeed(buildResponse(sessionAttributes, speechletResponse));
               });
       } else if (event.request.type === "IntentRequest") {
           onIntent(event.request,
               event.session,
               function callback(sessionAttributes, speechletResponse) {
                   context.succeed(buildResponse(sessionAttributes, speechletResponse));
               });
       } else if (event.request.type === "SessionEndedRequest") {
           onSessionEnded(event.request, event.session);
           context.succeed();
       }
   } catch (e) {
       context.fail("Exception: " + e);
   }
};

/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
   console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId + ", sessionId=" + session.sessionId);
}

/**
* Called when the user launches the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
   console.log("onLaunch requestId=" + launchRequest.requestId + ", sessionId=" + session.sessionId);
   // Dispatch to your skill's launch.
   getWelcomeResponse(callback);
}

/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
    console.log("onIntent requestId=" + intentRequest.requestId + ", sessionId=" + session.sessionId);
    var intent = intentRequest.intent,
    intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers
    switch (intentName){
        case "WelcomeIntent":
            getWelcomeResponse(callback);
            break;
        case "ProbeTempIntent":
            GetProbeTemp(intent, session, callback);
            break;
        case "PitProbeTempIntent":
            GetPitProbeTemp(intent, session, callback);
            break;
        case "AllProbesTempIntent":
            GetAllProbeTemp(intent, session, callback);
            break;
        case "SetPointTempIntent":
            GetSetPointTemp(intent, session, callback);
            break;
        case "ChangeSetPointIntent":
            ChangeSetPointTemp(intent, session, callback);
            break;
        case "AMAZON.HelpIntent":
            getHelpResponse(callback);
            break;
        case "AMAZON.StopInten" || "AMAZON.CancelIntent":
            handleSessionEndRequest(callback);
            break;
        default:
            throw "Invalid intent";
    }
}

/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
    console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId + ", sessionId=" + session.sessionId);
    // Add cleanup logic here
}

// --------------- Functions that control the skill's behavior -----------------------
function getWelcomeResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.
    var sessionAttributes = {};
    var cardTitle = "HeaterMeter";
    var speechOutput = "
Welcome to the Heatermeter Alexa skill

Please ask me to give you the current status
";
    var repromptText = "Please ask me to give you the barbeque temp";
    var shouldEndSession = false;
    callback(sessionAttributes, buildSpeechletResponse(cardTitle, speechOutput, repromptText, true));
}

function handleSessionEndRequest(callback) {
    var cardTitle = "Session Ended";
    var speechOutput = "Thank you for using the Heatermeter skill.";
    callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, true));
}

/**s
* Sets the color in the session and prepares the speech to reply to the user.
*/
function GetProbeTemp(intent, session, callback) {
    var cardTitle = "ProbeTemp";
    var probeSlot = intent.slots.probe;

    if (probeSlot && probeSlot.value) {
        var probe = probeSlot.value;
        getStatusRequest(probe, cardTitle, callback);
    } else {
        var speechOutput = 'I was unable to process your request. This is a work in progress please try again';
        callback({}, buildSpeechletResponse(cardTitle, speechOutput, "", false));
    }
}

function GetPitProbeTemp(intent, session, callback) {
    var cardTitle = "PitProbeTemp";
    getStatusRequest(0, cardTitle, callback);
}

function GetAllProbeTemp(intent, session, callback) {
    var cardTitle = "AllProbesTemp";
    getStatusRequest(null, cardTitle, callback);
}

function GetSetPointTemp(intent, session, callback) {
    var cardTitle = "SetPointTemp";
    getStatusRequest(null, cardTitle, callback);
}

function ChangeSetPointTemp(intent, session, callback){
    var cardTitle = "ChangeSetPointTemp";

    var newTempSlot = intent.slots.newTemp;

    if (newTempSlot && newTempSlot.value) {
        var newTemp = newTempSlot.value;

        var form_data = querystring.stringify({ 'value': newTemp});
        var options = {
            host: HeaterMeterHost,
            path: '/cgi-bin/luci/lm/api/config/sp?apikey=' + apiKey,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(form_data)
            }
        };

        var req = http.request(options, function(res){
            var result = '';
            console.log('Status: ' + res.statusCode);
            console.log('Headers: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                result += chunk;
            });
            res.on('end', function() {
                console.log("RESULT: " + result);
                speechOutput = buildSpeechOutput(newTemp, cardTitle, result);
                callback({}, buildSpeechletResponse(cardTitle, speechOutput, "", true));
            });
            res.on('error', function (err) {
                console.log(err);
            });
        });
        req.on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
        req.write(form_data);
        req.end();
    }
    else{
        var speechOutput = 'I was unable to process your request. This is a work in progress please try again';
        var repromptText = "I'm not sure what you wanted. . Please ask me to ...";
        callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, false));
    }
}

function getHelpResponse(callback) {
    return 0;
}

function getStatusRequest(probe, cardTitle, callback){
     var options = {
        host: HeaterMeterHost,
        path: '/cgi-bin/luci/lm/api/status',
        method: 'GET'
    };

    var req = http.request(options, function(res){
        var result = '';
        var speechOutput = '';
        var jsonStatus;
        console.log('Status: ' + res.statusCode);
        console.log('Headers: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            result += chunk;
        });
        res.on('end', function() {
            console.log("RESULT: " + result);
            jsonStatus = JSON.parse('' + result);
            speechOutput = buildSpeechOutput(probe, cardTitle, jsonStatus);
            callback({}, buildSpeechletResponse(cardTitle, speechOutput, "", true));
        });
        res.on('error', function (err) {
            console.log(err);
        });
    });
    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
        speechOutput = 'I was unable to find process your request';
        repromptText = 'Please ask me again';
        callback(sessionAttributes, buildSpeechletResponse(cardTitle, speechOutput, repromptText, true));
    });
    req.end();
}

// --------------- Helpers that build all of the responses -----------------------
function setpointTempMessage(json){
    return "
 Currently set for " + json.set + " degrees
";
}

function probesTempMessage(probe, json){
    if ( !json.temps[probe].c )
        return "
 Probe " + probe + " is not plugged in
";
    return "
 Probe " + probe + "'s temperature is " + json.temps[probe].c + "
";
}

function pitProbesTempMessage(json){
    return "
 The pit probe's temperature is " + json.temps[0].c + " degrees
";
}

function changePitSetPointMessage(newTemp, body){
    return "
 New setpoint is <say-as interpret-as=\"cardinal\">" + newTemp + "</say-as> degrees
";
}

function buildSpeechOutput(arg, cardTitle, response){
    var speechOut="";
    switch (cardTitle){
        case "AllProbesTemp":
            speechOut = setpointTempMessage(response) + pitProbesTempMessage(response) + probesTempMessage(1, response) + probesTempMessage(2, response) + probesTempMessage(3, response);
            break;
        case "SetPointTemp":
            speechOut = setpointTempMessage(response);
            break;
        case "PitProbeTemp":
            speechOut = pitProbesTempMessage(response) + setpointTempMessage(response);
            break;
        case "ChangeSetPointTemp":
            speechOut = changePitSetPointMessage(arg, response);
            break;
        default:
            speechOut = probesTempMessage(arg, response)
            break;
    }

    return speechOut;
}

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
   return {
       outputSpeech: {
           type: "SSML",
           ssml: "<speak>" + output + "</speak>"
       },
       card: {
           type: "Simple",
           title: "Temperature - " + title,
           content: "" + output
       },
       reprompt: {
           outputSpeech: {
               type: "PlainText",
               text: repromptText
           }
       },
       shouldEndSession: shouldEndSession
   };
}

function buildResponse(sessionAttributes, speechletResponse) {
   return {
       version: "1.0",
       sessionAttributes: sessionAttributes,
       response: speechletResponse
   };
} <commit_msg>clean up the code a bit and changed http requests to use promises.  When changing set point temp, this allows me to first make a status http request to get the current set point temp, then call the change sp request.  By doing this, I can have alexa respond with what it changed the set point from and to.<commit_after>'use strict';

var Alexa = require('alexa-sdk');
var http = require('http');
var querystring = require('querystring');

var APP_ID = undefined; // TODO replace with your app ID (OPTIONAL).

var HeaterMeterHost=process.env.heatermeterHost;
var apiKey = process.env.apiKey;

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
   try {
       console.log("event.session.application.applicationId=" + event.session.application.applicationId);
       /**
        * Uncomment this if statement and populate with your skill's application ID to
        * prevent someone else from configuring a skill that sends requests to this function.
        */
       /*
       if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.[unique-value-here]") {
            context.fail("Invalid Application ID");
       }
       */
       if (event.session.new) {
           onSessionStarted({ requestId: event.request.requestId }, event.session);
       }
       if (event.request.type === "LaunchRequest") {
           onLaunch(event.request,
               event.session,
               function callback(sessionAttributes, speechletResponse) {
                   context.succeed(buildResponse(sessionAttributes, speechletResponse));
               });
       } else if (event.request.type === "IntentRequest") {
           onIntent(event.request,
               event.session,
               function callback(sessionAttributes, speechletResponse) {
                   context.succeed(buildResponse(sessionAttributes, speechletResponse));
               });
       } else if (event.request.type === "SessionEndedRequest") {
           onSessionEnded(event.request, event.session);
           context.succeed();
       }
   } catch (e) {
       context.fail("Exception: " + e);
   }
};

/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
   console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId + ", sessionId=" + session.sessionId);
}

/**
* Called when the user launches the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
   console.log("onLaunch requestId=" + launchRequest.requestId + ", sessionId=" + session.sessionId);
   // Dispatch to your skill's launch.
   getWelcomeResponse(callback);
}

/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
    console.log("onIntent requestId=" + intentRequest.requestId + ", sessionId=" + session.sessionId);
    var intent = intentRequest.intent,
    intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers
    switch (intentName){
        case "WelcomeIntent":
            getWelcomeResponse(callback);
            break;
        case "ProbeTempIntent":
            GetProbeTemp(intent, session, callback);
            break;
        case "PitProbeTempIntent":
            GetPitProbeTemp(intent, session, callback);
            break;
        case "AllProbesTempIntent":
            GetAllProbeTemp(intent, session, callback);
            break;
        case "SetPointTempIntent":
            GetSetPointTemp(intent, session, callback);
            break;
        case "ChangeSetPointIntent":
            ChangeSetPointTemp(intent, session, callback);
            break;
        case "AMAZON.HelpIntent":
            getHelpResponse(callback);
            break;
        case "AMAZON.StopInten" || "AMAZON.CancelIntent":
            handleSessionEndRequest(callback);
            break;
        default:
            throw "Invalid intent";
    }
}

/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
    console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId + ", sessionId=" + session.sessionId);
    // Add cleanup logic here
}

// --------------- Functions that control the skill's behavior -----------------------
function getWelcomeResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.
    var sessionAttributes = {};
    var cardTitle = "HeaterMeter";
    var speechOutput = "
Welcome to the Heatermeter Alexa skill

Please ask me to give you the current status
";
    var repromptText = "Please ask me to give you the barbeque temp";
    var shouldEndSession = false;
    callback(sessionAttributes, buildSpeechletResponse(cardTitle, speechOutput, repromptText, true));
}

function handleSessionEndRequest(callback) {
    var cardTitle = "Session Ended";
    var speechOutput = "Thank you for using the Heatermeter skill.";
    callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, true));
}

function GetProbeTemp(intent, session, callback) {
    var cardTitle = "ProbeTemp";
    var probeSlot = intent.slots.probe;

    if (probeSlot && probeSlot.value) {
        var probe = probeSlot.value;
        getStatusRequest(probe, cardTitle, callback);
    } else {
        var speechOutput = 'I was unable to process your request. This is a work in progress please try again';
        callback({}, buildSpeechletResponse(cardTitle, speechOutput, "", false));
    }
}

function GetPitProbeTemp(intent, session, callback) {
    var cardTitle = "PitProbeTemp";
    getStatusRequest(0, cardTitle, callback);
}

function GetAllProbeTemp(intent, session, callback) {
    var cardTitle = "AllProbesTemp";
    getStatusRequest(null, cardTitle, callback);
}

function GetSetPointTemp(intent, session, callback) {
    var cardTitle = "SetPointTemp";
    getStatusRequest(null, cardTitle, callback);
}

function ChangeSetPointTemp(intent, session, callback){
    var cardTitle = "ChangeSetPointTemp";
    var responseOutput;
    var speechOutput;
    var newTempSlot = intent.slots.newTemp;
    if (newTempSlot && newTempSlot.value) {
        var newTemp = newTempSlot.value;
        var oldTemp;

        getStatusPromise(null)
        .then ( (response) => {
            oldTemp=response.set;
            return changeSetpointPromise(newTemp);
        })
        .then( (response) => {
            console.log("Change Setpoint Response: " + response);
            speechOutput = "
 I have changed the setpoint from <say-as interpret-as=\"cardinal\">" +
                oldTemp + "</say-as>  to <say-as interpret-as=\"cardinal\">" + newTemp + "</say-as>degrees
";
            callback({}, buildSpeechletResponse(cardTitle, speechOutput, "", false));
        },
        (reason) => console.log("ERROR: " + reason))
        .catch((err) => console.error(err));
    }
    else {
        console.log ('No new temperature was passed in.');
    }
}

function getHelpResponse(callback) {
    return 0;
}

function getStatusRequest(probe, cardTitle, callback){
    var response;
    var speechOutput;

    getStatusPromise(probe)
        .then( (response) =>  {
            console.log("RESPONSE: " + response );
            speechOutput = buildSpeechOutput(probe, cardTitle, response);
            callback({}, buildSpeechletResponse(cardTitle, speechOutput, "", false));
        },
        (reason) => console.log("ERROR: " + reason))
        .catch( (err) => console.error('Something went wrong', err));
}

function changeSetpointPromise (newTemp) {
    return new Promise( (resolve, reject) => {
        var form_data = querystring.stringify({ 'value': newTemp});
        var options = {
            host: HeaterMeterHost,
            path: '/cgi-bin/luci/lm/api/config/sp?apikey=' + apiKey,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(form_data)
            }
        };

        var req = http.request(options, (res) => {
            var result = '';
            console.log('Status: ' + res.statusCode);
            console.log('Headers: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', (chunk) => result += chunk);
            res.on('end', () => {
                if (result.includes("sp to " + newTemp + " = OK"))
                    resolve (result);
                else
                    reject ("something went wrong." + result);
            });
        });
        req.on('error', (err) => reject (err))
        req.write(form_data);
        req.end();
    })
};

function getStatusPromise(probe) {
    return new Promise( (resolve, reject) => {
        var options = {
                host: HeaterMeterHost,
                path: '/cgi-bin/luci/lm/api/status',
                method: 'GET'
        };

        var req = http.request(options, (res) => {
            var result = '';
            console.log('Status: ' + res.statusCode);
            console.log('Headers: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', (chunk) => result += chunk);
            res.on('end', () => {
                console.log (result);
                resolve( JSON.parse('' + result) )
            });
            res.on('error',  (err) => reject (err));
        });
        req.on('error', (err) => reject (err));
        req.end();
    })
}

function httpRequest(params, postData) {
    return new Promise(function(resolve, reject) {
        var req = http.request(params, function(res) {
            console.log("test");
            // reject on bad status
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            // cumulate data
            var body = [];
            res.on('data', function(chunk) {
                console.log("on data");
                body.push(chunk);
            });
            // resolve on end
            res.on('end', function() {
                console.log ("on end");
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                console.log("BODY: " + body);
                resolve(body);
            });
        });
        // reject on request error
        req.on('error', function(err) {
            // This is not a "Second reject", just a different sort of failure
            reject(err);
        });
        if (postData) {
            req.write(postData);
        }
        // IMPORTANT
        req.end();
    });
}

// --------------- Helpers that build all of the responses -----------------------
function setpointTempMessage(json){
    return "
 Currently set for " + json.set + " degrees
";
}

function probesTempMessage(probe, json){
    if ( !json.temps[probe].c )
        return "
 Probe " + probe + " is not plugged in
";
    return "
 Probe " + probe + "'s temperature is " + json.temps[probe].c + "
";
}

function pitProbesTempMessage(json){
    return "
 The pit probe's temperature is " + json.temps[0].c + " degrees
";
}

function buildSpeechOutput(arg, cardTitle, response){
    var speechOut="";
    switch (cardTitle){
        case "AllProbesTemp":
            speechOut = setpointTempMessage(response) + pitProbesTempMessage(response) + probesTempMessage(1, response) + probesTempMessage(2, response) + probesTempMessage(3, response);
            break;
        case "SetPointTemp":
            speechOut = setpointTempMessage(response);
            break;
        case "PitProbeTemp":
            speechOut = pitProbesTempMessage(response) + setpointTempMessage(response);
            break;
        default:
            speechOut = probesTempMessage(arg, response)
            break;
    }

    return speechOut;
}

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
   return {
       outputSpeech: {
           type: "SSML",
           ssml: "<speak>" + output + "</speak>"
       },
       card: {
           type: "Simple",
           title: "Temperature - " + title,
           content: "" + output
       },
       reprompt: {
           outputSpeech: {
               type: "PlainText",
               text: repromptText
           }
       },
       shouldEndSession: shouldEndSession
   };
}

function buildResponse(sessionAttributes, speechletResponse) {
   return {
       version: "1.0",
       sessionAttributes: sessionAttributes,
       response: speechletResponse
   };
} <|endoftext|>


<commit_before>const fs = require('fs');
const config = require('./config');
const querystring = require('querystring');
const _ = require('lodash');

let helpers = {};

// TODO: Move these to the shared helpers

// Here goes the server-side only helpers

function zeroPad(num) {
  num = String(num);
  if (num.length < 2) {
    num = '0' + num;
  }
  return num;
}

// Replace / add a query parameter to the base url
helpers.urlQuery = function(base, key, val) {
  var params = {};
  var queryPos = base.indexOf('?');
  if (queryPos !== -1) {
    // Add one to also cut `?`
    params = querystring.parse(base.substr(queryPos + 1));
    base = base.substr(0, queryPos);
  }

  if (val !== undefined) {
    params[key] = val;
  } else {
    delete params[key];
  }

  return `${base}?${querystring.stringify(params)}`;
};

helpers.DMYToYDM = function(d) {
  var parts = [];
  if (d.indexOf('/') !== -1) {
    parts = d.split('\/');
  } else if (d.indexOf('-') !== -1) {
    parts = d.split('\-');
  }

  var day = zeroPad(parts[0]);
  var month = zeroPad(parts[1]);
  var year = zeroPad(parts[2]);

  return `${year}-${month}-${day}`;
};

helpers.ensureYMD = function(d) {
  var dmy = helpers.ensureDMY(d);
  if (dmy !== null) {
    return helpers.DMYToYDM(dmy);
  }
  return null;
};

helpers.ensureDMY = function(d) {
  if (!d) {
    return null;
  }

  var parts = [];
  var output = '';
  if (d.indexOf('/') !== -1) {
    parts = d.split('\/');
  } else if (d.indexOf('-') !== -1) {
    parts = d.split('\-');
  }

  console.log(parts);

  if (parts.length === 3) {
    if (parts[2].length === 4) {
      return parts[0] +'-'+ parts[1] +'-'+ parts[2];
    } else {
      return parts[2] +'-'+ parts[1] +'-'+ parts[0];
    }
  }
  return null;
};

helpers.getTwitterAccount = (asset) => {
  if(typeof(config.twitterAccount) == 'string') {
    return config.twitterAccount;
  } else if(typeof(config.twitterAccount) == 'object' && asset) {
    return config.twitterAccount[asset.catalog];
  } else {
    return null;
  }
};

helpers.getFacebookAppId = (asset) => {
  if(typeof(config.facebookAppId) == 'string') {
    return config.facebookAppId;
  } else if(typeof(config.facebookAppId) == 'object' && asset) {
    return config.facebookAppId[asset.catalog];
  } else {
    return null;
  }
};

const MONTHS = [
  'januar', 'februar', 'marts', 'april', 'maj', 'juni',
  'juli', 'august', 'september', 'oktober', 'november', 'december'
];

helpers.formatDate = function(date) {
  var points = [];
  if(typeof(date) === 'number') {
    date = new Date(date);
    console.log('date', date);
    date = {
      day: date.getDate(),
      month: date.getMonth() + 1,
      year: date.getFullYear()
    };
  }
  if(date.day && date.month) {
    points.push(date.day + '.');
  }
  if(date.month) {
    var month = MONTHS[date.month-1];
    if(!date.day) {
      // Capitalize if the month is displayed first
      month = helpers.capitalizeFirstLetter(month);
    }
    points.push(month);
  }
  if(date.year) {
    points.push(date.year);
  }
  return points.join(' ');
};

helpers.filesizeMB = function(filesize) {
  if (filesize && filesize.value) {
    var mb = filesize.value / 1024 / 1024;
    // Formatted
    mb = helpers.decimals(mb, 1);
    return mb + ' MB';
  } else {
    return undefined;
  }
};

/**
 * Get the first of an array of paths
 */
helpers.getFirst = function(metadata, paths) {
  if(typeof(paths) === 'string') {
    paths = [paths];
  }
  return paths.reduce((result, path) => {
    return result || _.get(metadata, path);
  }, undefined);
};

helpers.get = function(metadata, path) {
  return _.get(metadata, path);
};

/**
 * Resolves a path to a date "value" into a simple date object
 *
 * If the path resolves to an object it is checked for the day/
 * month/year properties and is returned as is.
 * If the path resolves to a string it is attempted parsed into an object with
 * the three properties.
 *
 * Example 1:
 *    object = {creationDate: {day: 13, month: 10, year: 1800}}
 *    path = 'creationDate'
 *    returns {day: 13, month: 10, year: 1800}
 *
 * Example 2:
 *    object = {creationDate: {day: 13, year: 1800}}
 *    path = 'creationDate'
 *    Throws Error as the month-property is missing
 *
 * Example 3:
 *    object = {accessionEvents: [{dateFrom: "1946-01-01T00:00:00"]}
 *    path = 'accessionEvents[0].yearFrom'
 *    returns { day: 2, month: 0, year: 1946 }
 *
 * @param {Object} object The object to look for values in.
 * @param {string} path The path used when looking for values.
 */
helpers.getDate = function(metadata, path) {
  // Get the raw value.
  var property = _.get(metadata, path);

  // If we resolve to an object it should have the three properties.
  if(typeof(property) == 'object') {
    if (!(property.day && property.month && property.year)) {
      throw new Error('Expected object with day, month and year defined.');
    }
    return property;
  }

  // If we resolve to a string, parse it and create the "date" object.
  if(typeof(property) == 'string') {
    // Attempt parse.
    var date = new Date(property);
    if (isNaN(date)) throw SyntaxError("Could not parse date " + property);

    return {
      'day': date.getDay(),
      'month': date.getMonth(),
      'year': date.getFullYear(),
    };
  }
};

// Enabling the ability to load helpers that are shared between client and
// server from the appDir instead of the collections-online defaults.
const appDirHelpersPath = config.childPath + '/shared/helpers.js';
if(fs.existsSync(appDirHelpersPath)) {
  helpers = _.merge(helpers, require(appDirHelpersPath));
} else {
  helpers = _.merge(helpers, require('../shared/helpers'));
}

module.exports = helpers;
<commit_msg>Fixing syntax and documentation<commit_after>const fs = require('fs');
const config = require('./config');
const querystring = require('querystring');
const _ = require('lodash');

let helpers = {};

// TODO: Move these to the shared helpers

// Here goes the server-side only helpers

function zeroPad(num) {
  num = String(num);
  if (num.length < 2) {
    num = '0' + num;
  }
  return num;
}

// Replace / add a query parameter to the base url
helpers.urlQuery = function(base, key, val) {
  var params = {};
  var queryPos = base.indexOf('?');
  if (queryPos !== -1) {
    // Add one to also cut `?`
    params = querystring.parse(base.substr(queryPos + 1));
    base = base.substr(0, queryPos);
  }

  if (val !== undefined) {
    params[key] = val;
  } else {
    delete params[key];
  }

  return `${base}?${querystring.stringify(params)}`;
};

helpers.DMYToYDM = function(d) {
  var parts = [];
  if (d.indexOf('/') !== -1) {
    parts = d.split('\/');
  } else if (d.indexOf('-') !== -1) {
    parts = d.split('\-');
  }

  var day = zeroPad(parts[0]);
  var month = zeroPad(parts[1]);
  var year = zeroPad(parts[2]);

  return `${year}-${month}-${day}`;
};

helpers.ensureYMD = function(d) {
  var dmy = helpers.ensureDMY(d);
  if (dmy !== null) {
    return helpers.DMYToYDM(dmy);
  }
  return null;
};

helpers.ensureDMY = function(d) {
  if (!d) {
    return null;
  }

  var parts = [];
  var output = '';
  if (d.indexOf('/') !== -1) {
    parts = d.split('\/');
  } else if (d.indexOf('-') !== -1) {
    parts = d.split('\-');
  }

  console.log(parts);

  if (parts.length === 3) {
    if (parts[2].length === 4) {
      return parts[0] +'-'+ parts[1] +'-'+ parts[2];
    } else {
      return parts[2] +'-'+ parts[1] +'-'+ parts[0];
    }
  }
  return null;
};

helpers.getTwitterAccount = (asset) => {
  if(typeof(config.twitterAccount) == 'string') {
    return config.twitterAccount;
  } else if(typeof(config.twitterAccount) == 'object' && asset) {
    return config.twitterAccount[asset.catalog];
  } else {
    return null;
  }
};

helpers.getFacebookAppId = (asset) => {
  if(typeof(config.facebookAppId) == 'string') {
    return config.facebookAppId;
  } else if(typeof(config.facebookAppId) == 'object' && asset) {
    return config.facebookAppId[asset.catalog];
  } else {
    return null;
  }
};

const MONTHS = [
  'januar', 'februar', 'marts', 'april', 'maj', 'juni',
  'juli', 'august', 'september', 'oktober', 'november', 'december'
];

helpers.formatDate = function(date) {
  var points = [];
  if(typeof(date) === 'number') {
    date = new Date(date);
    console.log('date', date);
    date = {
      day: date.getDate(),
      month: date.getMonth() + 1,
      year: date.getFullYear()
    };
  }
  if(date.day && date.month) {
    points.push(date.day + '.');
  }
  if(date.month) {
    var month = MONTHS[date.month-1];
    if(!date.day) {
      // Capitalize if the month is displayed first
      month = helpers.capitalizeFirstLetter(month);
    }
    points.push(month);
  }
  if(date.year) {
    points.push(date.year);
  }
  return points.join(' ');
};

helpers.filesizeMB = function(filesize) {
  if (filesize && filesize.value) {
    var mb = filesize.value / 1024 / 1024;
    // Formatted
    mb = helpers.decimals(mb, 1);
    return mb + ' MB';
  } else {
    return undefined;
  }
};

/**
 * Get the first of an array of paths
 */
helpers.getFirst = function(metadata, paths) {
  if(typeof(paths) === 'string') {
    paths = [paths];
  }
  return paths.reduce((result, path) => {
    return result || _.get(metadata, path);
  }, undefined);
};

helpers.get = function(metadata, path) {
  return _.get(metadata, path);
};

/**
 * Resolves a path to a date "value" into a simple date object
 *
 * If the path resolves to an object it is checked for the day/
 * month/year properties and is returned as is.
 * If the path resolves to a string it is attempted parsed into an object with
 * the three properties.
 *
 * Example 1:
 *    object = {creationDate: {day: 13, month: 10, year: 1800}}
 *    path = 'creationDate'
 *    returns {day: 13, month: 10, year: 1800}
 *
 * Example 2:
 *    object = {creationDate: {day: 13, year: 1800}}
 *    path = 'creationDate'
 *    Throws Error as the month-property is missing
 *
 * Example 3:
 *    object = {accessionEvents: [{dateFrom: "1946-01-01T00:00:00"]}
 *    path = 'accessionEvents[0].yearFrom'
 *    returns { day: 1, month: 1, year: 1946 }
 *
 * @param {Object} object The object to look for values in.
 * @param {string} path The path used when looking for values.
 */
helpers.getDate = function(metadata, path) {
  // Get the raw value.
  var property = _.get(metadata, path);

  // If we resolve to an object it should have the three properties.
  if(typeof(property) == 'object') {
    if (!(property.day && property.month && property.year)) {
      throw new Error('Expected object with day, month and year defined.');
    }
    return property;
  }

  // If we resolve to a string, parse it and create the "date" object.
  if(typeof(property) == 'string') {
    // Attempt parse.
    var date = new Date(property);
    if (isNaN(date)) {
      throw SyntaxError("Could not parse date " + property);
    }

    return {
      'day': date.getDay(),
      'month': date.getMonth(),
      'year': date.getFullYear(),
    };
  }
};

// Enabling the ability to load helpers that are shared between client and
// server from the appDir instead of the collections-online defaults.
const appDirHelpersPath = config.childPath + '/shared/helpers.js';
if(fs.existsSync(appDirHelpersPath)) {
  helpers = _.merge(helpers, require(appDirHelpersPath));
} else {
  helpers = _.merge(helpers, require('../shared/helpers'));
}

module.exports = helpers;
<|endoftext|>


<commit_before>Function.I = function(x) {return x};

function forEach(fn, ar, thisObject) {
    return ar.forEach(fn, thisObject);
}

function map(fn, ar, thisObject) {
    return ar.map(fn, thisObject);
}

function filter(fn, ar, thisObject) {
    return ar.filter(fn, thisObject);
}

var select = filter;

function pluck(name) {
    return function() {
        return this[name];
    }
}

function invoke(name, args) {
    args = [].slice.call(args, 0);
    return function(object) {
        return object[name].apply(object, args.concat([].slice.call(arguments, 0)));
    }
}
<commit_msg>add Function.K<commit_after>/* Copyright 2007 by Oliver Steele.  All rights reserved. */

Function.I = function(x) {return x};
Function.K = function(x) {return function(){return x}};

function forEach(fn, ar, thisObject) {
    return ar.forEach(fn, thisObject);
}

function map(fn, ar, thisObject) {
    return ar.map(fn, thisObject);
}

function filter(fn, ar, thisObject) {
    return ar.filter(fn, thisObject);
}

var select = filter;

// Returns a projection this -> this[name]
function pluck(name) {
    return function() {
        return this[name];
    }
}

// Returns a projection this -> this[name](args...)
function invoke(name, args) {
    args = [].slice.call(args, 0);
    return function(object) {
        return object[name].apply(object, args.concat([].slice.call(arguments, 0)));
    }
}
<|endoftext|>