<commit_before>import { Router } from 'express';
import http from '../core/HttpClient';
import moment from 'moment';
import filter from 'lodash/fp/filter';
import forEach from 'lodash/fp/forEach';
import map from 'lodash/fp/map';
import transform from 'lodash/transform';
import identity from 'lodash/identity';

const router = new Router();

const baseURL = process.env.WF_SERVER;
const baseURL2 = baseURL + 'workflow/';
const baseURLMeta = baseURL + 'metadata/';
const baseURLTask = baseURL + 'tasks/';

router.get('/', async (req, res, next) => {
  try {
    let freeText = [];
    if (req.query.freeText != '') {
      freeText.push(req.query.freeText);
    } else {
      freeText.push('*');
    }

    let h = '-1';
    if (req.query.h != 'undefined' && req.query.h != '') {
      h = req.query.h;
    }
    if (h != '-1') {
      freeText.push('startTime:[now-' + h + 'h TO now]');
    }
    let start = 0;
    if (!isNaN(req.query.start)) {
      start = req.query.start;
    }

    let query = req.query.q;

    const url =
      baseURL2 +
      'search?size=100&sort=startTime:DESC&freeText=' +
      encodeURIComponent(freeText.join(' AND ')) +
      '&start=' +
      start +
      '&query=' +
      encodeURIComponent(query);
    const result = await http.get(url, req.token);
    const hits = result.results;
    res.status(200).send({ result: { hits: hits, totalHits: result.totalHits } });
  } catch (err) {
    next(err);
  }
});

const LOG_DATE_FORMAT = 'MM/DD/YY, HH:mm:ss:SSS';

router.get('/search-by-task/:taskId', async (req, res, next) => {
  try {
    let freeText = [];
    if (req.query.freeText != '') {
      freeText.push(req.params.taskId);
    } else {
      freeText.push('*');
    }

    let h = '-1';
    if (req.query.h !== undefined && req.query.h != 'undefined' && req.query.h != '') {
      h = req.query.h;
    }
    if (h != '-1') {
      freeText.push('startTime:[now-' + h + 'h TO now]');
    }
    let start = 0;
    if (!isNaN(req.query.start)) {
      start = req.query.start;
    }

    let query = req.query.q || '';
    const url =
      baseURL2 + 'search-by-tasks?size=100&sort=startTime:DESC&freeText=' + freeText.join(' AND ') + '&start=' + start;
    const result = await http.get(url, req.token);

    const hits = result.results;
    res.status(200).send({ result: { hits: hits, totalHits: result.totalHits } });
  } catch (err) {
    next(err);
  }
});

router.get('/id/:workflowId', async (req, res, next) => {

  try {
    const result = await http.get(baseURL2 + req.params.workflowId + '?includeTasks=true', req.token);

    let meta = result.workflowDefinition;
    if (!meta) {
      meta = await http.get(
          baseURLMeta + 'workflow/' + result.workflowType + '?version=' + result.version,
          req.token
      );
    }

    const subs = filter(identity)(
      map(task => {
        if (task.taskType === 'SUB_WORKFLOW') {
          const subWorkflowId = task.inputData && task.inputData.subWorkflowId;

          if (subWorkflowId != null) {
            return {
              name: task.inputData.subWorkflowName,
              version: task.inputData.subWorkflowVersion,
              referenceTaskName: task.referenceTaskName,
              subWorkflowId: subWorkflowId
            };
          }
        }
      })(result.tasks || [])
    );

    (result.tasks || []).forEach(task => {
      if (task.taskType === 'SUB_WORKFLOW') {
        const subWorkflowId = task.inputData && task.inputData.subWorkflowId;

        if (subWorkflowId != null) {
          subs.push({
            name: task.inputData.subWorkflowName,
            version: task.inputData.subWorkflowVersion,
            referenceTaskName: task.referenceTaskName,
            subWorkflowId: subWorkflowId
          });
        }
      }
    });

    const logs = map(task => Promise.all([task, http.get(baseURLTask + task.taskId + '/log')]))(result.tasks);

    await Promise.all(logs).then(result => {
      forEach(([task, logs]) => {
        if (logs) {
          task.logs = map(({ createdTime, log }) => `${moment(createdTime).format(LOG_DATE_FORMAT)} : ${log}`)(logs);
        }
      })(result);
    });

    const promises = map(({ name, version, subWorkflowId, referenceTaskName }) =>
      Promise.all([
        referenceTaskName,
        http.get(baseURLMeta + 'workflow/' + name + '?version=' + version),
        http.get(baseURL2 + subWorkflowId + '?includeTasks=true')
      ])
    )(subs);

    const subworkflows = await Promise.all(promises).then(result => {
      return transform(
        result,
        (result, [key, meta, wfe]) => {
          result[key] = { meta, wfe };
        },
        {}
      );
    });

    res.status(200).send({ result, meta, subworkflows: subworkflows });
  } catch (err) {
    next(err);
  }
});

router.put('/bulk/pause', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + "bulk/pause", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
});

router.put('/bulk/resume', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + "bulk/resume", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
})

router.post('/bulk/retry', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + "bulk/retry", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
});

router.post('/bulk/restart', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + "bulk/restart", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
})

router.delete('/bulk/terminate', async (req, res, next) => {
  try {
    const result = await http.delete(baseURL2 + "bulk/terminate", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
});

router.delete('/terminate/:workflowId', async (req, res, next) => {
  try {
    const result = await http.delete(baseURL2 + req.params.workflowId, {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {

    next(err);
  }
});

router.post('/restart/:workflowId', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + req.params.workflowId + '/restart', {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

router.post('/retry/:workflowId', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + req.params.workflowId + '/retry', {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

router.post('/pause/:workflowId', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + req.params.workflowId + '/pause');
    res.status(200).send({result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

router.post('/resume/:workflowId', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + req.params.workflowId + '/resume', {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

//metadata
router.get('/metadata/workflow/:name/:version', async (req, res, next) => {
  try {
    const result = await http.get(
      baseURLMeta + 'workflow/' + req.params.name + '?version=' + req.params.version,
      req.token
    );
    res.status(200).send({ result });
  } catch (err) {
    next(err);
  }
});

router.get('/metadata/workflow', async (req, res, next) => {
  try {
    const result = await http.get(baseURLMeta + 'workflow', req.token);
    res.status(200).send({ result });
  } catch (err) {
    next(err);
  }
});

router.get('/metadata/taskdef', async (req, res, next) => {
  try {
    const result = await http.get(baseURLMeta + 'taskdefs', req.token);
    res.status(200).send({ result });
  } catch (err) {
    next(err);
  }
});

router.get('/task/log/:taskId', async (req, res, next) => {
  try {
    const logs = await http.get(baseURLTask + req.params.taskId + '/log', req.token);
    res.status(200).send({ logs });
  } catch (err) {
    next(err);
  }
});

router.get('/queue/data', async (req, res, next) => {
  try {
    const sizes = await http.get(baseURLTask + 'queue/all', req.token);
    const polldata = await http.get(baseURLTask + 'queue/polldata/all', req.token);
    polldata.forEach(pd => {
      var qname = pd.queueName;

      if (pd.domain != null) {
        qname = pd.domain + ':' + qname;
      }
      pd.qsize = sizes[qname];
    });
    res.status(200).send({ polldata });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
<commit_msg>Added encoding to fallback search<commit_after>import { Router } from 'express';
import http from '../core/HttpClient';
import moment from 'moment';
import filter from 'lodash/fp/filter';
import forEach from 'lodash/fp/forEach';
import map from 'lodash/fp/map';
import transform from 'lodash/transform';
import identity from 'lodash/identity';

const router = new Router();

const baseURL = process.env.WF_SERVER;
const baseURL2 = baseURL + 'workflow/';
const baseURLMeta = baseURL + 'metadata/';
const baseURLTask = baseURL + 'tasks/';

router.get('/', async (req, res, next) => {
  try {
    let freeText = [];
    if (req.query.freeText != '') {
      freeText.push(req.query.freeText);
    } else {
      freeText.push('*');
    }

    let h = '-1';
    if (req.query.h != 'undefined' && req.query.h != '') {
      h = req.query.h;
    }
    if (h != '-1') {
      freeText.push('startTime:[now-' + h + 'h TO now]');
    }
    let start = 0;
    if (!isNaN(req.query.start)) {
      start = req.query.start;
    }

    let query = req.query.q;

    const url =
      baseURL2 +
      'search?size=100&sort=startTime:DESC&freeText=' +
      encodeURIComponent(freeText.join(' AND ')) +
      '&start=' +
      start +
      '&query=' +
      encodeURIComponent(query);
    const result = await http.get(url, req.token);
    const hits = result.results;
    res.status(200).send({ result: { hits: hits, totalHits: result.totalHits } });
  } catch (err) {
    next(err);
  }
});

const LOG_DATE_FORMAT = 'MM/DD/YY, HH:mm:ss:SSS';

router.get('/search-by-task/:taskId', async (req, res, next) => {
  try {
    let freeText = [];
    if (req.query.freeText != '') {
      freeText.push(req.params.taskId);
    } else {
      freeText.push('*');
    }

    let h = '-1';
    if (req.query.h !== undefined && req.query.h != 'undefined' && req.query.h != '') {
      h = req.query.h;
    }
    if (h != '-1') {
      freeText.push('startTime:[now-' + h + 'h TO now]');
    }
    let start = 0;
    if (!isNaN(req.query.start)) {
      start = req.query.start;
    }

    let query = req.query.q || '';
    const url =
      baseURL2 + 'search-by-tasks?size=100&sort=startTime:DESC&freeText=' + encodeURIComponent(freeText.join(' AND ')) + '&start=' + start;
    const result = await http.get(url, req.token);

    const hits = result.results;
    res.status(200).send({ result: { hits: hits, totalHits: result.totalHits } });
  } catch (err) {
    next(err);
  }
});

router.get('/id/:workflowId', async (req, res, next) => {

  try {
    const result = await http.get(baseURL2 + req.params.workflowId + '?includeTasks=true', req.token);

    let meta = result.workflowDefinition;
    if (!meta) {
      meta = await http.get(
          baseURLMeta + 'workflow/' + result.workflowType + '?version=' + result.version,
          req.token
      );
    }

    const subs = filter(identity)(
      map(task => {
        if (task.taskType === 'SUB_WORKFLOW') {
          const subWorkflowId = task.inputData && task.inputData.subWorkflowId;

          if (subWorkflowId != null) {
            return {
              name: task.inputData.subWorkflowName,
              version: task.inputData.subWorkflowVersion,
              referenceTaskName: task.referenceTaskName,
              subWorkflowId: subWorkflowId
            };
          }
        }
      })(result.tasks || [])
    );

    (result.tasks || []).forEach(task => {
      if (task.taskType === 'SUB_WORKFLOW') {
        const subWorkflowId = task.inputData && task.inputData.subWorkflowId;

        if (subWorkflowId != null) {
          subs.push({
            name: task.inputData.subWorkflowName,
            version: task.inputData.subWorkflowVersion,
            referenceTaskName: task.referenceTaskName,
            subWorkflowId: subWorkflowId
          });
        }
      }
    });

    const logs = map(task => Promise.all([task, http.get(baseURLTask + task.taskId + '/log')]))(result.tasks);

    await Promise.all(logs).then(result => {
      forEach(([task, logs]) => {
        if (logs) {
          task.logs = map(({ createdTime, log }) => `${moment(createdTime).format(LOG_DATE_FORMAT)} : ${log}`)(logs);
        }
      })(result);
    });

    const promises = map(({ name, version, subWorkflowId, referenceTaskName }) =>
      Promise.all([
        referenceTaskName,
        http.get(baseURLMeta + 'workflow/' + name + '?version=' + version),
        http.get(baseURL2 + subWorkflowId + '?includeTasks=true')
      ])
    )(subs);

    const subworkflows = await Promise.all(promises).then(result => {
      return transform(
        result,
        (result, [key, meta, wfe]) => {
          result[key] = { meta, wfe };
        },
        {}
      );
    });

    res.status(200).send({ result, meta, subworkflows: subworkflows });
  } catch (err) {
    next(err);
  }
});

router.put('/bulk/pause', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + "bulk/pause", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
});

router.put('/bulk/resume', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + "bulk/resume", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
})

router.post('/bulk/retry', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + "bulk/retry", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
});

router.post('/bulk/restart', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + "bulk/restart", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
})

router.delete('/bulk/terminate', async (req, res, next) => {
  try {
    const result = await http.delete(baseURL2 + "bulk/terminate", req.body, req.token);
    res.status(200).send(result);
  } catch (err) {
    next(err);
  }
});

router.delete('/terminate/:workflowId', async (req, res, next) => {
  try {
    const result = await http.delete(baseURL2 + req.params.workflowId, {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {

    next(err);
  }
});

router.post('/restart/:workflowId', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + req.params.workflowId + '/restart', {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

router.post('/retry/:workflowId', async (req, res, next) => {
  try {
    const result = await http.post(baseURL2 + req.params.workflowId + '/retry', {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

router.post('/pause/:workflowId', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + req.params.workflowId + '/pause');
    res.status(200).send({result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

router.post('/resume/:workflowId', async (req, res, next) => {
  try {
    const result = await http.put(baseURL2 + req.params.workflowId + '/resume', {}, req.token);
    res.status(200).send({ result: req.params.workflowId });
  } catch (err) {
    next(err);
  }
});

//metadata
router.get('/metadata/workflow/:name/:version', async (req, res, next) => {
  try {
    const result = await http.get(
      baseURLMeta + 'workflow/' + req.params.name + '?version=' + req.params.version,
      req.token
    );
    res.status(200).send({ result });
  } catch (err) {
    next(err);
  }
});

router.get('/metadata/workflow', async (req, res, next) => {
  try {
    const result = await http.get(baseURLMeta + 'workflow', req.token);
    res.status(200).send({ result });
  } catch (err) {
    next(err);
  }
});

router.get('/metadata/taskdef', async (req, res, next) => {
  try {
    const result = await http.get(baseURLMeta + 'taskdefs', req.token);
    res.status(200).send({ result });
  } catch (err) {
    next(err);
  }
});

router.get('/task/log/:taskId', async (req, res, next) => {
  try {
    const logs = await http.get(baseURLTask + req.params.taskId + '/log', req.token);
    res.status(200).send({ logs });
  } catch (err) {
    next(err);
  }
});

router.get('/queue/data', async (req, res, next) => {
  try {
    const sizes = await http.get(baseURLTask + 'queue/all', req.token);
    const polldata = await http.get(baseURLTask + 'queue/polldata/all', req.token);
    polldata.forEach(pd => {
      var qname = pd.queueName;

      if (pd.domain != null) {
        qname = pd.domain + ':' + qname;
      }
      pd.qsize = sizes[qname];
    });
    res.status(200).send({ polldata });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
<|endoftext|>


<commit_before>var path = require('path');
var compiler = require('jsdoc-api');

var explanation = compiler.explainSync({
    files: [
      path.resolve(__dirname, '../src/two.js'),
      // path.resolve(__dirname, '../src/registry.js'),
      // path.resolve(__dirname, '../src/vector.js'),
      // path.resolve(__dirname, '../src/anchor.js'),
      // path.resolve(__dirname, '../src/matrix.js'),
      // path.resolve(__dirname, '../src/renderer/svg.js'),
      // path.resolve(__dirname, '../src/renderer/canvas.js'),
      // path.resolve(__dirname, '../src/renderer/webgl.js'),
      // path.resolve(__dirname, '../src/shape.js'),
      // path.resolve(__dirname, '../src/path.js'),
      // path.resolve(__dirname, '../src/shapes/line.js'),
      // path.resolve(__dirname, '../src/shapes/rectangle.js'),
      // path.resolve(__dirname, '../src/shapes/ellipse.js'),
      // path.resolve(__dirname, '../src/shapes/circle.js'),
      // path.resolve(__dirname, '../src/shapes/polygon.js'),
      // path.resolve(__dirname, '../src/shapes/arc-segment.js'),
      // path.resolve(__dirname, '../src/shapes/star.js'),
      // path.resolve(__dirname, '../src/shapes/rounded-rectangle.js'),
      // path.resolve(__dirname, '../src/text.js'),
      // path.resolve(__dirname, '../src/effects/gradient.js'),
      // path.resolve(__dirname, '../src/effects/linear-gradient.js'),
      // path.resolve(__dirname, '../src/effects/radial-gradient.js'),
      // path.resolve(__dirname, '../src/effects/texture.js'),
      // path.resolve(__dirname, '../src/effects/sprite.js'),
      // path.resolve(__dirname, '../src/effects/image-sequence.js'),
      // path.resolve(__dirname, '../src/group.js')
    ],
    cache: false,
    configure: path.resolve(__dirname, '../jsdoc-conf.json')
});

explanation.slice(0).forEach(function(object) {
  var a = object.undocumented;
  var b = /package\:undefined/i.test(object.longname);
  if (a || b) {
    explanation.splice(explanation.indexOf(object), 1);
  }
});

// var example = explanation[0];
// ID = example.longname
// example.description
// example.augments
// example.params

// use the meta information in conjunction with the folder structure to
// create the right navigation environment.

// example.meta.path // Replace with github URL based on tagged version
// example.meta.filename
// example.meta.lineno
// example.meta.columnno
// example.memberof

console.log(explanation);
<commit_msg>more comments<commit_after>var path = require('path');
var compiler = require('jsdoc-api');

var explanation = compiler.explainSync({
    files: [
      path.resolve(__dirname, '../src/two.js'),
      // path.resolve(__dirname, '../src/registry.js'),
      // path.resolve(__dirname, '../src/vector.js'),
      // path.resolve(__dirname, '../src/anchor.js'),
      // path.resolve(__dirname, '../src/matrix.js'),
      // path.resolve(__dirname, '../src/renderer/svg.js'),
      // path.resolve(__dirname, '../src/renderer/canvas.js'),
      // path.resolve(__dirname, '../src/renderer/webgl.js'),
      // path.resolve(__dirname, '../src/shape.js'),
      // path.resolve(__dirname, '../src/path.js'),
      // path.resolve(__dirname, '../src/shapes/line.js'),
      // path.resolve(__dirname, '../src/shapes/rectangle.js'),
      // path.resolve(__dirname, '../src/shapes/ellipse.js'),
      // path.resolve(__dirname, '../src/shapes/circle.js'),
      // path.resolve(__dirname, '../src/shapes/polygon.js'),
      // path.resolve(__dirname, '../src/shapes/arc-segment.js'),
      // path.resolve(__dirname, '../src/shapes/star.js'),
      // path.resolve(__dirname, '../src/shapes/rounded-rectangle.js'),
      // path.resolve(__dirname, '../src/text.js'),
      // path.resolve(__dirname, '../src/effects/gradient.js'),
      // path.resolve(__dirname, '../src/effects/linear-gradient.js'),
      // path.resolve(__dirname, '../src/effects/radial-gradient.js'),
      // path.resolve(__dirname, '../src/effects/texture.js'),
      // path.resolve(__dirname, '../src/effects/sprite.js'),
      // path.resolve(__dirname, '../src/effects/image-sequence.js'),
      // path.resolve(__dirname, '../src/group.js')
    ],
    cache: false,
    configure: path.resolve(__dirname, '../jsdoc-conf.json')
});

explanation.slice(0).forEach(function(object) {
  var a = object.undocumented;
  var b = /package\:undefined/i.test(object.longname);
  if (a || b) {
    explanation.splice(explanation.indexOf(object), 1);
  }
});

// For all @kinds
// ID = example.longname
// example.description
// example.augments
// example.params

// use the meta information in conjunction with the folder structure to
// create the right navigation environment.

// example.meta.path // Replace with github URL based on tagged version
// example.meta.filename
// example.meta.lineno
// example.meta.columnno
// example.memberof // Use to map and identify what goes to what

console.log(explanation);
<|endoftext|>


<commit_before>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*eslint max-len: 0*/
// jscs:disable maximumLineLength

var valid = [
    // Current pattern
    'Copyright (c) 2016 Uber Technologies, Inc.\n' +
    '\n' +
    'Permission is hereby granted, free of charge, to any person obtaining a copy\n' +
    'of this software and associated documentation files (the "Software"), to deal\n' +
    'in the Software without restriction, including without limitation the rights\n' +
    'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n' +
    'copies of the Software, and to permit persons to whom the Software is\n' +
    'furnished to do so, subject to the following conditions:\n' +
    '\n' +
    'The above copyright notice and this permission notice shall be included in\n' +
    'all copies or substantial portions of the Software.\n' +
    '\n' +
    'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n' +
    'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n' +
    'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n' +
    'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n' +
    'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n' +
    'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n' +
    'THE SOFTWARE.',

    // Just Uber variant
    'Copyright (c) 2015 Uber\n' +
    '\n' +
    'Permission is hereby granted, free of charge, to any person obtaining a copy\n' +
    'of this software and associated documentation files (the "Software"), to deal\n' +
    'in the Software without restriction, including without limitation the rights\n' +
    'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n' +
    'copies of the Software, and to permit persons to whom the Software is\n' +
    'furnished to do so, subject to the following conditions:\n' +
    '\n' +
    'The above copyright notice and this permission notice shall be included in\n' +
    'all copies or substantial portions of the Software.\n' +
    '\n' +
    'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n' +
    'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n' +
    'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n' +
    'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n' +
    'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n' +
    'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n' +
    'THE SOFTWARE.'
];

module.exports = valid;
<commit_msg>Update copyright year in valid license variant<commit_after>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*eslint max-len: 0*/
// jscs:disable maximumLineLength

var valid = [
    // Current pattern
    'Copyright (c) 2016 Uber Technologies, Inc.\n' +
    '\n' +
    'Permission is hereby granted, free of charge, to any person obtaining a copy\n' +
    'of this software and associated documentation files (the "Software"), to deal\n' +
    'in the Software without restriction, including without limitation the rights\n' +
    'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n' +
    'copies of the Software, and to permit persons to whom the Software is\n' +
    'furnished to do so, subject to the following conditions:\n' +
    '\n' +
    'The above copyright notice and this permission notice shall be included in\n' +
    'all copies or substantial portions of the Software.\n' +
    '\n' +
    'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n' +
    'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n' +
    'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n' +
    'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n' +
    'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n' +
    'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n' +
    'THE SOFTWARE.',

    // Just Uber variant
    'Copyright (c) 2016 Uber\n' +
    '\n' +
    'Permission is hereby granted, free of charge, to any person obtaining a copy\n' +
    'of this software and associated documentation files (the "Software"), to deal\n' +
    'in the Software without restriction, including without limitation the rights\n' +
    'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n' +
    'copies of the Software, and to permit persons to whom the Software is\n' +
    'furnished to do so, subject to the following conditions:\n' +
    '\n' +
    'The above copyright notice and this permission notice shall be included in\n' +
    'all copies or substantial portions of the Software.\n' +
    '\n' +
    'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n' +
    'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n' +
    'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n' +
    'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n' +
    'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n' +
    'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n' +
    'THE SOFTWARE.'
];

module.exports = valid;
<|endoftext|>


<commit_before>var request = require('request'),
	url = require('url'),
	parseXml = require('xml2js').parseString;
	async = require('async');

var uriSource = url.parse('http://www.stolpersteine-berlin.de/st_interface/xml/geo/linked');
//var urlApi = 'http://127.0.0.1:3000/api';
var urlApi = 'https://stolpersteine-optionu.rhcloud.com/api';
var userAgent = 'Stolpersteine/1.0 (http://option-u.com; admin@option-u.com)';

var source = {
	url: uriSource.href,
	name: "Koordinierungsstelle Stolpersteine Berlin"
}

console.log('Loading source data...');
request({ uri:uriSource, headers: {'user-agent' : userAgent } }, function(error, response, body) {
	console.log('Loading source data done');
  if (error) {
    console.log('Error when loading source data');
		return;
  }

	console.log('Parsing source data...');
	parseXml(body, function (err, result) {
		console.log('Parsing source data done');
	  if (error) {
	    console.log('Error when parsing source data');
			return;
	  }

		console.log('Found ' + result.markers.$.cnt + ' stolpersteine in ' + result.markers.marker.length + ' markers');
		var stolpersteine = [];
		source.retrievedAt = 	new Date(response.headers["date"]);
		var markers = result.markers.marker;
		markers = markers.slice(0, 10);	// restrict test data
		async.forEachLimit(markers, 1, function(marker, callback) {
			var location = {
				street : marker.$.adresse,
				city : "Berlin",
				coordinates : {
					longitude: marker.$.lng,
					latitude: marker.$.lat
				}
			};

			var stolperstein = {};
			stolperstein.location = location;
			stolperstein.source = source;
			console.log(stolperstein);
			callback();
		});
	});
});

function convertStolperstein($, tableRow, callback) {
	var stolperstein = {};
	var itemRows = $(tableRow).find('td');

	// Person
	var nameSpan = $(itemRows[1]).find('span');
	if (nameSpan.find('span').length) {
		nameSpan = nameSpan.find('span');
	}
	var names = nameSpan.text().split(',');
	stolperstein.person = {
		lastName: names[0].trim(),
		firstName: names[1].trim()
	};
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (converting...)');

	// Image
	var imageTag = $(itemRows[0]).find('img');
	stolperstein.imageUrl = uriSource.protocol + imageTag.attr('src');
	stolperstein.imageUrl = stolperstein.imageUrl.replace('/100px-', '/1024px-'); // width

	// Location
	stolperstein.location = {
		street: $(itemRows[2]).text().trim(),
		city: "Berlin"
	};

	// Laid at date
	stolperstein.laidAt = {};
	var laidAtSpan = $(itemRows[3]).find('span');
	if ($(laidAtSpan).find('span').length) {
		laidAtSpan = laidAtSpan.find('span');
	}
	var laidAtDates = laidAtSpan.text().split('-');
	if (laidAtDates[0]) {
		var number = new Number(laidAtDates[0]);
		if (number != 0) {
			stolperstein.laidAt.year = number;
		}
	}
	if (laidAtDates[1]) {
		var number = new Number(laidAtDates[1]);
		if (number != 0) {
			stolperstein.laidAt.month = number;
		}
	}
	if (laidAtDates[2]) {
		var number = new Number(laidAtDates[2]);
		if (number != 0) {
			stolperstein.laidAt.date = number;
		}
	}

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (converting done)');
	callback(null, stolperstein);
}

function patchStolperstein(stolperstein, callback) {
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching...)');

	stolperstein.location.street = stolperstein.location.street.replace("(heute Eingang U-Bahnhof Turmstraße)", "");
	stolperstein.location.street = stolperstein.location.street.replace("Spenerstraße Ecke Melanchtonstraße", "Spenerstr. 14");
	stolperstein.location.street = stolperstein.location.street.replace("Bundesratufer 1", "Bundesratufer 2");

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching done)');
	callback(null, stolperstein);
}

function addSourceToStolperstein(source, stolperstein, callback) {
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (adding source...)');

	stolperstein.source = source;

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (adding source done)');
	callback(null, stolperstein);
}<commit_msg>Parse sublocality data<commit_after>var request = require('request'),
	url = require('url'),
	parseXml = require('xml2js').parseString;
	async = require('async');

var uriSource = url.parse('http://www.stolpersteine-berlin.de/st_interface/xml/geo/linked');
//var urlApi = 'http://127.0.0.1:3000/api';
var urlApi = 'https://stolpersteine-optionu.rhcloud.com/api';
var userAgent = 'Stolpersteine/1.0 (http://option-u.com; admin@option-u.com)';

var source = {
	url: uriSource.href,
	name: "Koordinierungsstelle Stolpersteine Berlin"
}

console.log('Loading source data...');
request({ uri:uriSource, headers: {'user-agent' : userAgent } }, function(error, response, body) {
	console.log('Loading source data done');
  if (error) {
    console.log('Error when loading source data');
		return;
  }

	console.log('Parsing source data...');
	parseXml(body, function (err, result) {
		console.log('Parsing source data done');
	  if (error) {
	    console.log('Error when parsing source data');
			return;
	  }

		console.log('Found ' + result.markers.$.cnt + ' stolpersteine in ' + result.markers.marker.length + ' markers');
		var stolpersteine = [];
		source.retrievedAt = 	new Date(response.headers["date"]);
		var markers = result.markers.marker;
		markers = markers.slice(0, 10);	// restrict test data
		async.forEachLimit(markers, 1, function(marker, callback) {
			var location = {
				street : marker.$.adresse,
				city : "Berlin",
				sublocality1 : marker.$.bezirk,
				sublocality2 : marker.$.ortsteil,
				coordinates : {
					longitude: marker.$.lng,
					latitude: marker.$.lat
				}
			};

			var stolperstein = {};
			stolperstein.location = location;
			stolperstein.source = source;
			console.log(stolperstein);
			callback();
		});
	});
});

function convertStolperstein($, tableRow, callback) {
	var stolperstein = {};
	var itemRows = $(tableRow).find('td');

	// Person
	var nameSpan = $(itemRows[1]).find('span');
	if (nameSpan.find('span').length) {
		nameSpan = nameSpan.find('span');
	}
	var names = nameSpan.text().split(',');
	stolperstein.person = {
		lastName: names[0].trim(),
		firstName: names[1].trim()
	};
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (converting...)');

	// Image
	var imageTag = $(itemRows[0]).find('img');
	stolperstein.imageUrl = uriSource.protocol + imageTag.attr('src');
	stolperstein.imageUrl = stolperstein.imageUrl.replace('/100px-', '/1024px-'); // width

	// Location
	stolperstein.location = {
		street: $(itemRows[2]).text().trim(),
		city: "Berlin"
	};

	// Laid at date
	stolperstein.laidAt = {};
	var laidAtSpan = $(itemRows[3]).find('span');
	if ($(laidAtSpan).find('span').length) {
		laidAtSpan = laidAtSpan.find('span');
	}
	var laidAtDates = laidAtSpan.text().split('-');
	if (laidAtDates[0]) {
		var number = new Number(laidAtDates[0]);
		if (number != 0) {
			stolperstein.laidAt.year = number;
		}
	}
	if (laidAtDates[1]) {
		var number = new Number(laidAtDates[1]);
		if (number != 0) {
			stolperstein.laidAt.month = number;
		}
	}
	if (laidAtDates[2]) {
		var number = new Number(laidAtDates[2]);
		if (number != 0) {
			stolperstein.laidAt.date = number;
		}
	}

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (converting done)');
	callback(null, stolperstein);
}

function patchStolperstein(stolperstein, callback) {
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching...)');

	stolperstein.location.street = stolperstein.location.street.replace("(heute Eingang U-Bahnhof Turmstraße)", "");
	stolperstein.location.street = stolperstein.location.street.replace("Spenerstraße Ecke Melanchtonstraße", "Spenerstr. 14");
	stolperstein.location.street = stolperstein.location.street.replace("Bundesratufer 1", "Bundesratufer 2");

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching done)');
	callback(null, stolperstein);
}

function addSourceToStolperstein(source, stolperstein, callback) {
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (adding source...)');

	stolperstein.source = source;

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (adding source done)');
	callback(null, stolperstein);
}<|endoftext|>


<commit_before>var fs = require('fs');
fs.readdir('../index/', function(err, files) {
  for(var i=0; i<files.length; i++) {
    if(files[i]!='README.md') {
      console.log('echo "starting '+files[i]+'"; cat ../index/'+files[i]+' | python -mjson.tool > index/'+files[i]+'; echo "finishing '+files[i]+'"');
    }
  }
});
<commit_msg>prettifier for all json folders<commit_after>var fs = require('fs');
fs.readdir('../points/', function(err, files) {
  for(var i=0; i<files.length; i++) {
    if(files[i]!='README.md') {
      console.log('echo "starting '+files[i]+'"; cat ../points/'+files[i]+' | python -mjson.tool > points/'+files[i]+'; echo "finishing '+files[i]+'"');
    }
  }
});
fs.readdir('../topics/', function(err, files) {
  for(var i=0; i<files.length; i++) {
    if(files[i]!='README.md') {
      console.log('echo "starting '+files[i]+'"; cat ../topics/'+files[i]+' | python -mjson.tool > topics/'+files[i]+'; echo "finishing '+files[i]+'"');
    }
  }
});
fs.readdir('../services/', function(err, files) {
  for(var i=0; i<files.length; i++) {
    if(files[i]!='README.md') {
      console.log('echo "starting '+files[i]+'"; cat ../services/'+files[i]+' | python -mjson.tool > services/'+files[i]+'; echo "finishing '+files[i]+'"');
    }
  }
});
fs.readdir('../index/', function(err, files) {
  for(var i=0; i<files.length; i++) {
    if(files[i]!='README.md') {
      console.log('echo "starting '+files[i]+'"; cat ../index/'+files[i]+' | python -mjson.tool > index/'+files[i]+'; echo "finishing '+files[i]+'"');
    }
  }
});
<|endoftext|>


<commit_before>import {Mongo} from 'meteor/mongo';

export const Debts = new Mongo.Collection('debts');<commit_msg>debts.checkMyDebt, debts.numberOfDebtors, debts.settle<commit_after>import {Meteor} from 'meteor/meteor';
import {Mongo} from 'meteor/mongo';
import {check} from 'meteor/check';

export const Debts = new Mongo.Collection('debts');

Meteor.methods({
	'debts.checkMyDebt'(itemId) {
		check(itemId, String);

		if(!this.userId) {
			throw new Meteor.Error('non-authorized');
		}

		return Debts.findOne(
			{
				debtor: Meteor.userId(),
				item: itemId,
			});
	},

	'debts.numberOfDebtors'(itemId) {
		check(itemId, String);

		if(!this.userId) {
			throw new Meteor.Error('non-authorized');
		}

		return Debts.find({item: itemId,}).count();
	},

	'debts.settle'(itemId) {
		check(itemId, String);

		if(!this.userId) {
			throw new Meteor.Error('non-authorized');
		}

		Debts.update(
			{item: itemId, debtor: this.userId},
			{$set: {cost: 0}},
		);
	}
});

<|endoftext|>


<commit_before>
import {
  OutlinedLeaf,
  SolidLeaf,
  StripedLeaf,
  Logo,
} from "../components/leaves";

import {
  Stats,
  Leaves,
  Image,
  Body,
} from "../components/layout";

import FitText from "../components/fit-text";
import List from "../components/list";

const fuseNumbers = [
  { count: "4,286", label: "Average Weekely Attendance" },
  { count: "3,982", label: "Salvations" },
  { count: "13,427", label: "First Timers" },
];

const Fuse = () => (

      <Stats>
        <FitText compressor={1.5}>

            Each week in 2015, an average of

        </FitText>

        <FitText compressor={0.3}>

            4,286

        </FitText>

        <FitText compressor={0.55}>

            Students

        </FitText>

        <FitText compressor={1.5}>

          got to belong at Fuse

        </FitText>
      </Stats>

      <Leaves>
        <SolidLeaf
          className="locked-bottom locked-right"
          size="200px"
          color="text-secondary"
          style={{
            transform: "rotate(-225deg)",
            marginBottom: "-50px",
            marginRight: "-150px",
          }}
        />
        <SolidLeaf
          className="locked-bottom locked-right"
          size="130px"
          color="text-tertiary"
          style={{
            transform: "rotate(-270deg)",
            marginBottom: "-100px",
            marginRight: "-10px",
          }}
        />
        <StripedLeaf
          className="locked-bottom locked-right"
          size="90px"
          color="text-tertiary"
          style={{
            transform: "rotate(180deg)",
            marginBottom: "60px",
            marginRight: "-20px",
          }}
        />

        <SolidLeaf
          className="locked-bottom locked-left"
          size="250px"
          color="text-secondary"
          style={{
            transform: "rotate(-135deg)",
            marginBottom: "-90px",
            marginLeft: "-150px",
          }}
        />

        <StripedLeaf
          className="locked-bottom locked-left"
          size="120px"
          color="text-tertiary"
          style={{
            transform: "rotate(-90deg)",
            marginBottom: "-20px",
            marginLeft: "0px",
          }}
        />

      </Leaves>

        <Image url="//s3.amazonaws.com/ns.assets/apollos/annual+report/BrooklinKuipers.jpg" />

            "My parents were in the middle of a huge divorce in 2015.  Fuse was the best environment for me, my sister, and my brother. Fuse held us together, and stopped us from falling apart. Everybody was so fun and loving all the time. I felt like I actually belonged. Meeting Jesus helped me see that God actually loves me at a time when I was questioning what real love looked like."

            Brooklin Kuipers, Aiken Campus

Fuse:

The Next Generation

    <List items={fuseNumbers} />

);

export default Fuse;
<commit_msg>lint celebrate fuse<commit_after>
import {
  SolidLeaf,
  StripedLeaf,
} from "../components/leaves";

import {
  Stats,
  Leaves,
  Image,
  Body,
} from "../components/layout";

import FitText from "../components/fit-text";
import List from "../components/list";

const fuseNumbers = [
  { count: "4,286", label: "Average Weekely Attendance" },
  { count: "3,982", label: "Salvations" },
  { count: "13,427", label: "First Timers" },
];

/* eslint-disable max-len */
const Fuse = () => (

      <Stats>
        <FitText compressor={1.5}>

            Each week in 2015, an average of

        </FitText>

        <FitText compressor={0.3}>

              4,286

        </FitText>

        <FitText compressor={0.55}>

              Students

        </FitText>

        <FitText compressor={1.5}>

            got to belong at Fuse

        </FitText>
      </Stats>

      <Leaves>
        <SolidLeaf
          className="locked-bottom locked-right"
          size="200px"
          color="text-secondary"
          style={{
            transform: "rotate(-225deg)",
            marginBottom: "-50px",
            marginRight: "-150px",
          }}
        />
        <SolidLeaf
          className="locked-bottom locked-right"
          size="130px"
          color="text-tertiary"
          style={{
            transform: "rotate(-270deg)",
            marginBottom: "-100px",
            marginRight: "-10px",
          }}
        />
        <StripedLeaf
          className="locked-bottom locked-right"
          size="90px"
          color="text-tertiary"
          style={{
            transform: "rotate(180deg)",
            marginBottom: "60px",
            marginRight: "-20px",
          }}
        />

        <SolidLeaf
          className="locked-bottom locked-left"
          size="250px"
          color="text-secondary"
          style={{
            transform: "rotate(-135deg)",
            marginBottom: "-90px",
            marginLeft: "-150px",
          }}
        />

        <StripedLeaf
          className="locked-bottom locked-left"
          size="120px"
          color="text-tertiary"
          style={{
            transform: "rotate(-90deg)",
            marginBottom: "-20px",
            marginLeft: "0px",
          }}
        />

      </Leaves>

        <Image url="//s3.amazonaws.com/ns.assets/apollos/annual+report/BrooklinKuipers.jpg" />

            "My parents were in the middle of a huge divorce in 2015.  Fuse was the best environment for me, my sister, and my brother. Fuse held us together, and stopped us from falling apart. Everybody was so fun and loving all the time. I felt like I actually belonged. Meeting Jesus helped me see that God actually loves me at a time when I was questioning what real love looked like."

            Brooklin Kuipers, Aiken Campus

Fuse:

The Next Generation

      <List items={fuseNumbers} />

);
/* eslint-enable max-len */

export default Fuse;
<|endoftext|>


<commit_before>/* eslint-disable react/no-danger */
import { Component, PropTypes } from "react";
import ReactMixin from "react-mixin";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import Meta from "../../components/meta";

// loading state
import Loading from "../../components/loading";
import { nav as navActions } from "../../store";
import headerActions from "../../store/header";

import Headerable from "../../mixins/mixins.Header";
import Likeable from "../../mixins/mixins.Likeable";
import Shareable from "../../mixins/mixins.Shareable";

import RelatedContent from "../../blocks/content/RelatedContent";

import collections from "../../util/collections";
import styles from "../../util/styles";
import react from "../../util/react";

import SeriesHero from "./series.Hero";
import SeriesVideoList from "./series.VideoList";

const SERIES_SINGLE_QUERY = gql`
  query getSeriesSingle($id: ID!) {
    content: node(id: $id) {
      id
      ... on Content {
        entryId: id
        title
        status
        channelName
        meta {
          urlTitle
          siteId
          date
          channelId
        }
        content {
          description
          tags
          isLight
          images(sizes: ["large"]) {
            fileName
            fileType
            fileLabel
            url
          }
          ooyalaId
          colors {
            id
            value
            description
          }
        }
      }
    }
  }
`;

const withSingleSeries = graphql(SERIES_SINGLE_QUERY, {
  name: "series",
  options: ownProps => ({
    variables: { id: ownProps.params.id },
  }),
});

@connect()
@withSingleSeries
@ReactMixin.decorate(Likeable)
@ReactMixin.decorate(Shareable)
@ReactMixin.decorate(Headerable)
export default class SeriesSingle extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    series: PropTypes.object.isRequired,
    params: PropTypes.object.isRequired,
  }

  componentWillMount() {
    if (process.env.WEB) return;

    // needed for cached data
    this.handleHeaderStyle(this.props);

    this.props.dispatch(navActions.setLevel("CONTENT"));
    this.props.dispatch(navActions.setAction("CONTENT", {
      id: 2,
      action: this.likeableAction,
    }));
  }

  componentWillUpdate(nextProps) {
    this.handleHeaderStyle(nextProps);
  }

  handleHeaderStyle = (nextProps) => {
    const content = nextProps.series.content;
    if (!content) return;
    const { isLight } = nextProps.series.content.content;
    const color = collections.color(content);
    this.props.dispatch(headerActions.set({
      title: "Series",
      color,
      light: !isLight,
    }));
  }

  hackBackgroundStyles() {
    return {
      position: "absolute",
      top: 0,
      left: 0,
      width: "100%",
      height: "100%",
      zIndex: -1,
    };
  }

  render() {
    const { content } = this.props.series;

    if (!content) {
      // loading
      return (

            <Loading />

      );
    }

    const series = content;
    return (

        <Meta
          title={series.title}
          description={series.content.description}
          image={
            series.content.images && series.content.images.length > 0
              ? series.content.images[0].url
              : null
          }
        />
        <div className={`${collections.classes(series)} background--light-primary`}>

          <SeriesHero series={series} />
          <section className={`${series.content.isLight ? "text-dark-primary" : "text-light-primary"} hard-bottom soft-double-sides@palm-wide`}>

          <SeriesVideoList id={this.props.params.id} />

        <RelatedContent excludedIds={[series.id]} tags={series.content.tags} />

    );
  }
}
<commit_msg>added id for series single meta<commit_after>/* eslint-disable react/no-danger */
import { Component, PropTypes } from "react";
import ReactMixin from "react-mixin";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import Meta from "../../components/meta";

// loading state
import Loading from "../../components/loading";
import { nav as navActions } from "../../store";
import headerActions from "../../store/header";

import Headerable from "../../mixins/mixins.Header";
import Likeable from "../../mixins/mixins.Likeable";
import Shareable from "../../mixins/mixins.Shareable";

import RelatedContent from "../../blocks/content/RelatedContent";

import collections from "../../util/collections";
import styles from "../../util/styles";
import react from "../../util/react";

import SeriesHero from "./series.Hero";
import SeriesVideoList from "./series.VideoList";

const SERIES_SINGLE_QUERY = gql`
  query getSeriesSingle($id: ID!) {
    content: node(id: $id) {
      id
      ... on Content {
        entryId: id
        title
        status
        channelName
        meta {
          urlTitle
          siteId
          date
          channelId
        }
        content {
          description
          tags
          isLight
          images(sizes: ["large"]) {
            fileName
            fileType
            fileLabel
            url
          }
          ooyalaId
          colors {
            id
            value
            description
          }
        }
      }
    }
  }
`;

const withSingleSeries = graphql(SERIES_SINGLE_QUERY, {
  name: "series",
  options: ownProps => ({
    variables: { id: ownProps.params.id },
  }),
});

@connect()
@withSingleSeries
@ReactMixin.decorate(Likeable)
@ReactMixin.decorate(Shareable)
@ReactMixin.decorate(Headerable)
export default class SeriesSingle extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    series: PropTypes.object.isRequired,
    params: PropTypes.object.isRequired,
  }

  componentWillMount() {
    if (process.env.WEB) return;

    // needed for cached data
    this.handleHeaderStyle(this.props);

    this.props.dispatch(navActions.setLevel("CONTENT"));
    this.props.dispatch(navActions.setAction("CONTENT", {
      id: 2,
      action: this.likeableAction,
    }));
  }

  componentWillUpdate(nextProps) {
    this.handleHeaderStyle(nextProps);
  }

  handleHeaderStyle = (nextProps) => {
    const content = nextProps.series.content;
    if (!content) return;
    const { isLight } = nextProps.series.content.content;
    const color = collections.color(content);
    this.props.dispatch(headerActions.set({
      title: "Series",
      color,
      light: !isLight,
    }));
  }

  hackBackgroundStyles() {
    return {
      position: "absolute",
      top: 0,
      left: 0,
      width: "100%",
      height: "100%",
      zIndex: -1,
    };
  }

  render() {
    const { content } = this.props.series;

    if (!content) {
      // loading
      return (

            <Loading />

      );
    }

    const series = content;
    return (

        <Meta
          title={series.title}
          description={series.content.description}
          image={
            series.content.images && series.content.images.length > 0
              ? series.content.images[0].url
              : null
          }
          id={series.id}
        />
        <div className={`${collections.classes(series)} background--light-primary`}>

          <SeriesHero series={series} />
          <section className={`${series.content.isLight ? "text-dark-primary" : "text-light-primary"} hard-bottom soft-double-sides@palm-wide`}>

          <SeriesVideoList id={this.props.params.id} />

        <RelatedContent excludedIds={[series.id]} tags={series.content.tags} />

    );
  }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

var EXPORTED_SYMBOLS = ['SocketConn'];

const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, 'Services', 'resource://gre/modules/Services.jsm');

var nsISocketTransportService =
  Cc["@mozilla.org/network/socket-transport-service;1"].
    getService(Ci.nsISocketTransportService);

function _error(str) {
  dump('-*- conn.jsm error -*- ' + str + '\n');
}

function _logMessage(str) {
  dump('-*- conn.jsm -*- ' + str + '\n');
}

/**
 * Options:
 *  host: 127.0.0.1
 *  port: 23
 *  onopen:
 *  onclose:
 *  onMessage:
 */
function SocketConn(options) {
  this.initialize(options);
}

SocketConn.prototype = {
  outputStream: null,
  inputStream: null,

  initialize: function(options) {
    this.options = options;
  },

  stop: function() {
    if (this.outputStream) {
      this.outputStream.close();
      this.outputStream = null;
    }

    if (this.inputStream) {
      this.inputStream.close();
      this.inputStream = null;
    }

    if (this.nsIConverterOutputStream) {
      this.nsIConverterOutputStream.close();
      this.nsIConverterOutputStream = null;
    }

    if (this.nsIConverterInputStream) {
      this.nsIConverterInputStream.close();
      this.nsIConverterInputStream = null;
    }
  },

  sendData: function(obj) {
    this.nsIConverterOutputStream.writeString(JSON.stringify(obj));
  },

  // nsITransportEventSink (Triggered by transport.setEventSink)
  onTransportStatus: function socket_onTransportStatus(transport,
    status, progress, max) {
    if (status == Ci.nsISocketTransport.STATUS_CONNECTED_TO) {
      // Call event listeners
      if (this.options.onopen) {
        this.options.onopen();
      }

      this.nsIInputStreamPump =
        Cc["@mozilla.org/network/input-stream-pump;1"].
          createInstance(Ci.nsIInputStreamPump);

      this.nsIInputStreamPump.init(this.inputStream, -1, -1, 0, 0, false);
      var self = this;
      this.nsIInputStreamPump.asyncRead({
        data: { },
        restStr: "",

        onStartRequest: function(request, context) {
        },

        onStopRequest: function(request, context, status) {
          try {
            self.stop();
          } catch (e) {
            _error(e);
          }
          if (self.options.onclose) {
            self.options.onclose(request, context, status);
          }
        },

        onDataAvailable: function(request, context, inputStream, offset, count) {
          self.nsIConverterInputStream.readString(65536, this.data);
          var str = this.restStr + this.data.value;
          // May receive string composed by serveral JSON, should be split.
          str = str.trim();
          var lbCount = 0;  // left brace count
          var rbCount = 0;  // right brace count
          var start = 0; // start index of json string
          var isLastEscape = false;
          for (var i = 0; i < str.length; i++) {
            var c = str.charAt(i);
            var isEscape = c == "\\";
            if (!isEscape && !isLastEscape) {
              if (c == "{") {
                lbCount += 1;
              } else if (c == "}") {
                rbCount += 1;
                if (rbCount === lbCount) {
                  var jsonStr = str.substring(start, i + 1);
                  _logMessage(jsonStr);
                  if (self.options.onMessage) {
                    try {
                              self.options.onMessage(JSON.parse(jsonStr));
                    } catch (e) {
                      _error(e);
                    }
                  }
                  start = i + 1;
                }
              }
            }
            isLastEscape = isEscape;
          }
        }
      }, null);
    }
  },

  connect: function() {
    this.nsIConverterInputStream =
      Cc["@mozilla.org/intl/converter-input-stream;1"].
      createInstance(Ci.nsIConverterInputStream);

    this.nsIConverterOutputStream =
      Cc["@mozilla.org/intl/converter-output-stream;1"].
        createInstance(Ci.nsIConverterOutputStream);

    var transport = nsISocketTransportService.
          createTransport(null, 0, this.options.host, this.options.port, null);

    transport.setEventSink(this, Services.tm.currentThread);

    this.outputStream = transport.openOutputStream(0, 0, 0);
    this.inputStream = transport.openInputStream(0, 0, 0);

    var REPLACEMENT_CHARACTER = Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
    this.nsIConverterInputStream.init(this.inputStream, "utf8", 65535, REPLACEMENT_CHARACTER);
    this.nsIConverterOutputStream.init(this.outputStream, "utf8", 65535, REPLACEMENT_CHARACTER);
  }
};

<commit_msg>Send data without stringify the data, consist with WebSocket<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

var EXPORTED_SYMBOLS = ['SocketConn'];

const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, 'Services', 'resource://gre/modules/Services.jsm');

var nsISocketTransportService =
  Cc["@mozilla.org/network/socket-transport-service;1"].
    getService(Ci.nsISocketTransportService);

function _error(str) {
  dump('-*- conn.jsm error -*- ' + str + '\n');
}

function _logMessage(str) {
  dump('-*- conn.jsm -*- ' + str + '\n');
}

/**
 * Options:
 *  host: 127.0.0.1
 *  port: 23
 *  onopen:
 *  onclose:
 *  onMessage:
 */
function SocketConn(options) {
  this.initialize(options);
}

SocketConn.prototype = {
  outputStream: null,
  inputStream: null,

  initialize: function(options) {
    this.options = options;
  },

  stop: function() {
    if (this.outputStream) {
      this.outputStream.close();
      this.outputStream = null;
    }

    if (this.inputStream) {
      this.inputStream.close();
      this.inputStream = null;
    }

    if (this.nsIConverterOutputStream) {
      this.nsIConverterOutputStream.close();
      this.nsIConverterOutputStream = null;
    }

    if (this.nsIConverterInputStream) {
      this.nsIConverterInputStream.close();
      this.nsIConverterInputStream = null;
    }
  },

  sendData: function(str) {
    this.nsIConverterOutputStream.writeString(str);
  },

  // nsITransportEventSink (Triggered by transport.setEventSink)
  onTransportStatus: function socket_onTransportStatus(transport,
    status, progress, max) {
    if (status == Ci.nsISocketTransport.STATUS_CONNECTED_TO) {
      // Call event listeners
      if (this.options.onopen) {
        this.options.onopen();
      }

      this.nsIInputStreamPump =
        Cc["@mozilla.org/network/input-stream-pump;1"].
          createInstance(Ci.nsIInputStreamPump);

      this.nsIInputStreamPump.init(this.inputStream, -1, -1, 0, 0, false);
      var self = this;
      this.nsIInputStreamPump.asyncRead({
        data: { },
        restStr: "",

        onStartRequest: function(request, context) {
        },

        onStopRequest: function(request, context, status) {
          try {
            self.stop();
          } catch (e) {
            _error(e);
          }
          if (self.options.onclose) {
            self.options.onclose(request, context, status);
          }
        },

        onDataAvailable: function(request, context, inputStream, offset, count) {
          self.nsIConverterInputStream.readString(65536, this.data);
          var str = this.restStr + this.data.value;
          // May receive string composed by serveral JSON, should be split.
          str = str.trim();
          var lbCount = 0;  // left brace count
          var rbCount = 0;  // right brace count
          var start = 0; // start index of json string
          var isLastEscape = false;
          for (var i = 0; i < str.length; i++) {
            var c = str.charAt(i);
            var isEscape = c == "\\";
            if (!isEscape && !isLastEscape) {
              if (c == "{") {
                lbCount += 1;
              } else if (c == "}") {
                rbCount += 1;
                if (rbCount === lbCount) {
                  var jsonStr = str.substring(start, i + 1);
                  _logMessage(jsonStr);
                  if (self.options.onMessage) {
                    try {
                              self.options.onMessage(JSON.parse(jsonStr));
                    } catch (e) {
                      _error(e);
                    }
                  }
                  start = i + 1;
                }
              }
            }
            isLastEscape = isEscape;
          }
        }
      }, null);
    }
  },

  connect: function() {
    this.nsIConverterInputStream =
      Cc["@mozilla.org/intl/converter-input-stream;1"].
      createInstance(Ci.nsIConverterInputStream);

    this.nsIConverterOutputStream =
      Cc["@mozilla.org/intl/converter-output-stream;1"].
        createInstance(Ci.nsIConverterOutputStream);

    var transport = nsISocketTransportService.
          createTransport(null, 0, this.options.host, this.options.port, null);

    transport.setEventSink(this, Services.tm.currentThread);

    this.outputStream = transport.openOutputStream(0, 0, 0);
    this.inputStream = transport.openInputStream(0, 0, 0);

    var REPLACEMENT_CHARACTER = Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
    this.nsIConverterInputStream.init(this.inputStream, "utf8", 65535, REPLACEMENT_CHARACTER);
    this.nsIConverterOutputStream.init(this.outputStream, "utf8", 65535, REPLACEMENT_CHARACTER);
  }
};

<|endoftext|>


<commit_before>module.exports = {
  Modules: {
    BaseModule: require('./BaseModule'),
    TopRanking: require('./TopRanking'),
    TrackInfoFetcher: require('./TrackInfoFetcher')
  }
};
<commit_msg>remove unused index<commit_after><|endoftext|>


<commit_before>System.config({
  packages: {
    app: {format: 'register', defaultExtension: 'js'},
    'node_modules/d3': {main: 'd3.js', format: 'cjs', defaultExtension: 'js'},
  },
  paths: {'d3': 'node_modules/d3'}
});
System.import('executions.js').then(null, console.error.bind(console));
<commit_msg>Removed systemjs_setup.js since it's now redundant.<commit_after><|endoftext|>


<commit_before>import fs from 'fs';
import Promise from 'bluebird';
import path from 'path';

let readFile = Promise.promisify(fs.readFile);
let writeFile = Promise.promisify(fs.writeFile);
let readdir = Promise.promisify(fs.readdir);
let rename = Promise.promisify(fs.rename);

let config;

let start = (cb => {

	readFile('configuration.JSON', 'utf8')
	.then(data => JSON.parse(data))
	.then(config => {
		if(typeof cb === 'function') {
			if(config) {
				console.log("Calling callback with:");
				console.log(config);
				cb(config);
			} else {
				console.log("Throwing error");
				cb(null, new Error("Could not read file."));
			}
		}
		return config;
	})
	.each(
		directory => {
			console.log(directory);
			console.log("Reading:");
			console.log(path.relative(__dirname +'/..', path.join(directory.folder.path, directory.folder.name)));
			readdir(path.relative(__dirname +'/..', path.join(directory.folder.path, directory.folder.name)))
				.then(files => {
					var fullPath = path.join(directory.folder.path, directory.folder.name);
					console.log(fullPath);
					files.forEach(file => {
						directory.tasks.forEach(task => {
							if(testFile(fullPath, task.matchAll, task.rules,file)) {
								events[task.event.type](task, file);
							};
						});
					})
				})
				.catch(err => {
					throw new Error(err);
				});

		}

		/*directory => {
		//console.log("Getting path from %s to %s", task.path, __dirname);
		//console.log(path.join('..', path.relative(__dirname, task.path)));
		console.log("dirr: %s", __dirname);
		console.log(directory);

		console.log("lol: " + path.join(directory.folder.path, directory.folder.name));
		readdir(path.relative(__dirname +'/..', path.join(directory.folder.path, directory.folder.name))
		.then(files => {console.log("Hej");console.log(files);files.forEach(file =>
			{
				console.log("KOMMER IN HIT");
				var fullPath = path.join(directory.folder.path, directory.folder.name);
				directory.forEach(task => {
					console.log("directory:");
					console.log(directory);
					console.log("task:");
					console.log(task);
					if(testFile(fullPath, task.matchAll, task.rules,file)) {
						events[task.event.type](task, file);
					}
				});

			}))*/
	).each(function(files) {
		//console.log("files:");
		//console.log(files);
	}).catch(err => {
		throw new Error(err);
	});
});

function testFile(dir, matchAll, rules, file) {
	console.log("inside tesfile");
	let nrOfMatches = matchAll ? rules.length : 1,
			matches = 0;

	for(let i = 0; i < rules.length; i++) {
		if(file.indexOf('.') >= 0 && verifiers[rules[i].verifier](file, rules[i].type, rules[i].reference)) {
			console.log("%s passed test '%s' with type: %s, reference: %s", file, rules[i].verifier, rules[i].type, rules[i].reference);
			matches++;
		} else {
			console.log("%s did not pass test '%s' with type: %s, reference: %s", file, rules[i].verifier, rules[i].type, rules[i].reference);
		}
	}

	let pass = (matches === nrOfMatches) ? true : false;

	return pass;
}

const verifiers = {
	match: (file, type, reference) => {
		let parts = file.split('.');
		if(type === 'extension') {
			return parts[1] === reference
		}
		if(type === 'name') {
			return parts[0] === reference
		}
	},
	contains: (file, type, reference) => {
		let parts = file.split('.');
		if(type === 'extension') {
			return (parts[1].indexOf(reference) >= 0)
		}
		if(type === 'name') {
			return (parts[0].indexOf(reference) >= 0)
		}
	}
}

const events = {
	move: (task, file) => {

		let origin = path.relative(__dirname+'/..', task.path)+'/'+file
		let dest = path.relative(__dirname+'/..', task.event.path)+'/'+file

		rename(origin, dest)
		.then(() => {
			log(task);
			console.log('moved file "%s" from %s to %s', file, origin, dest);
		})
		.catch((err) => {
			console.log('Could not move file "%s" from %s to %s', file, pathToOldFolder, pathToNewFolderFromOld);
			throw new Error(err);
		});
	},
	rename: (task, file) => {

		let origin = path.relative(__dirname+'/..', task.path)+'/'+file
		let newName = path.relative(__dirname+'/..', task.path)+'/'+task.event.newName;

		rename(origin, newName)
		.then(() => {
			log(task);
			console.log('renamed file "%s" from %s to %s', file, origin, newName);
		})
		.catch((err) => {
			console.log('Could not rename file "%s" from %s to %s', file, origin, newName);
			throw new Error(err);
		});
	}
};

function log(task) {

	var currentdate = new Date();
	var datetime = "[" + currentdate.getFullYear() + "/"
	                + (currentdate.getMonth()+1)  + "/"
	                + currentdate.getDate() + " "
	                + currentdate.getHours() + ":"
	                + currentdate.getMinutes() + ":"
	                + currentdate.getSeconds() + "]";

	console.log(datetime);

	let message = datetime + ' Task "'+task.name+'" fired event "'+task.event.type+'" inside folder '+task.path;

	var fs = require('fs');
	writeFile('history.log', message)
	.catch(err => {throw err});
}

//Expose start function
module.exports = {
	start,
	config
}
<commit_msg>add a history logger<commit_after>import fs from 'fs';
import Promise from 'bluebird';
import path from 'path';

let readFile = Promise.promisify(fs.readFile),
		writeFile = Promise.promisify(fs.writeFile),
		readdir = Promise.promisify(fs.readdir),
		rename = Promise.promisify(fs.rename),
		appendFile = Promise.promisify(fs.appendFile);

let config;

let start = (cb => {

	readFile('configuration.JSON', 'utf8')
	.then(data => JSON.parse(data))
	.then(config => {
		if(typeof cb === 'function') {
			if(config) {
				console.log("Calling callback with:");
				console.log(config);
				cb(config);
			} else {
				console.log("Throwing error");
				cb(null, new Error("Could not read file."));
			}
		}
		return config;
	})
	.each(
		directory => {
			console.log(directory);
			console.log("Reading:");
			console.log(path.relative(__dirname +'/..', path.join(directory.folder.path, directory.folder.name)));
			readdir(path.relative(__dirname +'/..', path.join(directory.folder.path, directory.folder.name)))
				.then(files => {
					var fullPath = path.join(directory.folder.path, directory.folder.name);
					console.log(fullPath);
					files.forEach(file => {
						directory.tasks.forEach(task => {
							if(testFile(fullPath, task.matchAll, task.rules,file)) {
								events[task.event.type](task, file);
							};
						});
					})
				})
				.catch(err => {
					throw new Error(err);
				});

		}

	).each(function(files) {
		//console.log("files:");
		//console.log(files);
	}).catch(err => {
		throw new Error(err);
	});
});

function testFile(dir, matchAll, rules, file) {
	console.log("inside tesfile");
	let nrOfMatches = matchAll ? rules.length : 1,
			matches = 0;

	for(let i = 0; i < rules.length; i++) {
		if(file.indexOf('.') >= 0 && verifiers[rules[i].verifier](file, rules[i].type, rules[i].reference)) {
			console.log("%s passed test '%s' with type: %s, reference: %s", file, rules[i].verifier, rules[i].type, rules[i].reference);
			matches++;
		} else {
			console.log("%s did not pass test '%s' with type: %s, reference: %s", file, rules[i].verifier, rules[i].type, rules[i].reference);
		}
	}

	let pass = (matches === nrOfMatches) ? true : false;

	return pass;
}

const verifiers = {
	match: (file, type, reference) => {
		let parts = file.split('.');
		if(type === 'extension') {
			return parts[1] === reference
		}
		if(type === 'name') {
			return parts[0] === reference
		}
	},
	contains: (file, type, reference) => {
		let parts = file.split('.');
		if(type === 'extension') {
			return (parts[1].indexOf(reference) >= 0)
		}
		if(type === 'name') {
			return (parts[0].indexOf(reference) >= 0)
		}
	}
}

const events = {
	move: (task, file) => {

		let origin = path.relative(__dirname+'/..', task.path)+'/'+file
		let dest = path.relative(__dirname+'/..', task.event.path)+'/'+file

		rename(origin, dest)
		.then(() => {
			log(task);
			console.log('moved file "%s" from %s to %s', file, origin, dest);
		})
		.catch((err) => {
			console.log('Could not move file "%s" from %s to %s', file, pathToOldFolder, pathToNewFolderFromOld);
			throw new Error(err);
		});
	},
	rename: (task, file) => {

		let origin = path.relative(__dirname+'/..', task.path)+'/'+file
		let newName = path.relative(__dirname+'/..', task.path)+'/'+task.event.newName;

		rename(origin, newName)
		.then(() => {
			log(task);
			console.log('renamed file "%s" from %s to %s', file, origin, newName);
		})
		.catch((err) => {
			console.log('Could not rename file "%s" from %s to %s', file, origin, newName);
			throw new Error(err);
		});
	}
};

function log(task) {

	var currentdate = new Date();
	var datetime = "[" + currentdate.getFullYear() + "/"
	                + (currentdate.getMonth()+1)  + "/"
	                + currentdate.getDate() + " "
	                + currentdate.getHours() + ":"
	                + currentdate.getMinutes() + ":"
	                + currentdate.getSeconds() + "]";

	let message = datetime + ' Task "'+task.name
								+'" fired event "'+task.event.type
								+'" inside folder "'+task.path
								+'"\n';

	appendFile('history.log', message)
	.catch(err => {throw new Error(err)});
}

//Expose
module.exports = {
	start,
	config
}

<|endoftext|>


<commit_before>var crypto = require('crypto');
var util = require('util');

exports.mod = function(context, server)
{
	this.core$cmd = function(prefix, target, cmd, params, $core)
	{
		switch(cmd)
		{
			case 'ping':
				$core._privmsg(target, 'pong' + (params[0] !== undefined ? (' ' + params[0]) : ''));
				break;
			case 'digest':
				if(params.length < 2)
				{
					$core._privmsg(target, 'Syntax: hash <type> <string>');
					break;
				}

				var h = crypto.createHash(params[0]);
				h.update(params[1]);
				$core._privmsg(target, 'Hash: ' + h.digest('hex'));
				break;
			case 'memusage':
				$core._privmsg(target, util.inspect(process.memoryUsage()));
				break;
		}
	}
}
<commit_msg>Fixed incorrect syntax message and added hashtypes cmd to mod utils.<commit_after>var crypto = require('crypto');
var util = require('util');

exports.mod = function(context, server)
{
	this.core$cmd = function(prefix, target, cmd, params, $core)
	{
		switch(cmd)
		{
			case 'ping':
				$core._privmsg(target, 'pong' + (params[0] !== undefined ? (' ' + params[0]) : ''));
				break;
			case 'digest':
				if(params.length < 2)
				{
					$core._privmsg(target, 'Syntax: digest <type> <string>');
					break;
				}

				var h = crypto.createHash(params[0]);
				h.update(params[1]);
				$core._privmsg(target, 'Hash: ' + h.digest('hex'));
				break;
			case 'hashtypes':
				$core._privmsg(target, 'Hash Types: ' + crypto.getHashes());
				break;
			case 'memusage':
				$core._privmsg(target, util.inspect(process.memoryUsage()));
				break;
		}
	}
}
<|endoftext|>