<commit_before>import { fork, put, select, takeLatest } from 'redux-saga/effects';
import { push } from 'react-router-redux';

import { getForm } from '../selectors/forms';
import { workshopsAll } from '../selectors/workshops';
import { getCheapestAccomodation } from '../selectors/accomodation';
import {
  getParticipantLatestOrder,
  getParticipantUnconfirmedOrder,
} from '../selectors/participant';
import { yearActiveNumber } from '../selectors/years';
import { reverse } from '../routeTable';

import { fetchResource } from './common';
import { sendForm } from './forms';

import * as api from '../api';
import * as constants from '../constants/actions';

export const selectOrderSubmit = action =>
  action.type === constants.FORM_SUBMIT_ALLOWED && action.form === 'order';

export const selectOrderSuccess = action =>
  action.type === constants.FORM_SUBMIT_SUCCESS && action.form === 'order';

export const selectChangeWorkshopSubmit = action =>
  action.type === constants.FORM_SUBMIT_ALLOWED && action.form === 'changeWorkshop';

export const selectChangeWorkshopSuccess = action =>
  action.type === constants.FORM_SUBMIT_SUCCESS && action.form === 'changeWorkshop';

export function* redirectHome() {
  yield put(push(reverse('participant:home')));
}

export function* orderSetDefaults() {
  const year = yield select(yearActiveNumber);
  const accomodation = yield select(getCheapestAccomodation);
  yield put({
    form: 'order',
    type: constants.FORM_VALUES_SET,
    values: {
      accomodation: accomodation ? accomodation.id : null,
      meals: [],
      year,
    },
  });
}

export function* orderCancel() {
  const order = yield select(getParticipantLatestOrder);
  if (order) {
    yield fork(
      fetchResource,
      api.orderCancel,
      {
        onStart: constants.ORDER_CANCEL_FETCH_STARTED,
        onSuccess: constants.ORDER_CANCEL_FETCH_SUCCESS,
        onError: constants.ORDER_CANCEL_FETCH_ERROR,
        order: order.id,
      }
    );
  }
}

export function* orderConfirm() {
  const order = yield select(getParticipantUnconfirmedOrder);
  if (order) {
    yield fork(
      fetchResource,
      api.orderConfirm,
      {
        onStart: constants.ORDER_CONFIRM_FETCH_STARTED,
        onSuccess: constants.ORDER_CONFIRM_FETCH_SUCCESS,
        onError: constants.ORDER_CONFIRM_FETCH_ERROR,
        order: order.id,
      }
    );
  }
}

export function* orderSubmit() {
  const form = yield select(getForm, 'order');
  yield fork(sendForm, api.orderCreate, 'order', form.values);
}

export function* orderConfirmRedirect(action) {
  yield put({
    type: constants.ORDER_CREATED,
    data: action.data,
  });
  yield put(push(reverse('participant:confirm')));
}

export function* orderCancelRedirect() {
  yield put({ type: constants.ORDER_CANCELED });
  yield fork(redirectHome);
}

export function* orderChangeRedirect() {
  yield put({ type: constants.ORDER_CHANGED });
  yield fork(redirectHome);
}

export function* orderChangeSetDefaults() {
  const order = yield select(getParticipantLatestOrder);
  yield put({
    form: 'changeWorkshop',
    type: constants.FORM_VALUES_SET,
    values: {
      workshop: order ? order.workshop.id : null,
    },
  });
}

export function* orderChangeWorkshopSubmit() {
  const form = yield select(getForm, 'changeWorkshop');
  const order = yield select(getParticipantLatestOrder);
  yield fork(sendForm, api.orderChangeWorkshop, 'changeWorkshop', form.values, {
    order: order.id,
  });
}

export function* bindOrderConfirmRedirect() {
  yield takeLatest(
    selectOrderSubmit,
    orderSubmit
  );
}

export function* bindOrderHomeRedirect() {
  yield takeLatest(
    [
      constants.ORDER_CANCEL_FETCH_SUCCESS,
      constants.ORDER_CONFIRM_FETCH_SUCCESS,
    ],
    orderCancelRedirect
  );
}

export function* bindOrderCancel() {
  yield takeLatest(
    constants.ORDER_CANCEL_REQUESTED,
    orderCancel
  );
}

export function* bindOrderConfirm() {
  yield takeLatest(
    constants.ORDER_CONFIRM_REQUESTED,
    orderConfirm
  );
}

export function* bindOrderSubmit() {
  yield takeLatest(
    selectOrderSuccess,
    orderConfirmRedirect
  );
}

export function* bindOrderSetDefaults() {
  yield takeLatest(
    [
      constants.ACCOMODATION_FETCH_SUCCESS,
      constants.ORDER_FORM_MOUNTED,
    ],
    orderSetDefaults
  );
}

export function* interceptInvalidWorkshop() {
  const form = yield select(getForm, 'order');
  const workshops = yield select(workshopsAll);
  const selectedWorkshop = workshops.find(
    workshop => workshop.id === form.values.workshop
  );

  if (
    form.values.workshop &&
    (
      !selectedWorkshop ||
      selectedWorkshop.capacityStatus.freeSpots === 0
    )
  ) {
    yield put({
      type: constants.FORM_FIELD_CHANGE,
      form: 'order',
      field: 'workshop',
      value: null,
    });
  }
}

export function* interceptInvalidWorkshopChange() {
  const order = yield select(getParticipantLatestOrder);
  const form = yield select(getForm, 'changeWorkshop');
  const workshops = yield select(workshopsAll);

  const selectedWorkshop = workshops.find(
    workshop => workshop.id === form.values.workshop
  );

  if (
    !selectedWorkshop ||
    (
      form.values.workshop &&
      order.workshop.id !== form.values.workshop &&
      selectedWorkshop.capacityStatus.freeSpots === 0
    )
  ) {
    yield put({
      type: constants.FORM_FIELD_CHANGE,
      form: 'changeWorkshop',
      field: 'workshop',
      value: order ? order.workshop.id : null,
    });
  }
}

export function* bindInterceptInvalidWorkshop() {
  yield takeLatest(
    constants.YEAR_CAPACITY_FETCH_SUCCESS,
    interceptInvalidWorkshop
  );
}

export function* bindInterceptInvalidWorkshopChange() {
  yield takeLatest(
    constants.YEAR_CAPACITY_FETCH_SUCCESS,
    interceptInvalidWorkshopChange
  );
}

export function* bindChangeWorkshopSubmit() {
  yield takeLatest(selectChangeWorkshopSubmit, orderChangeWorkshopSubmit);
}

export function* bindChangeWorkshopSuccess() {
  yield takeLatest(selectChangeWorkshopSuccess, orderChangeRedirect);
}

export function* bindChangeWorkshopSetDefaults() {
  yield takeLatest(constants.PARTICIPANT_WORKSHOP_CHANGE_MOUNTED, orderChangeSetDefaults);
}

export default [
  bindChangeWorkshopSetDefaults,
  bindChangeWorkshopSubmit,
  bindChangeWorkshopSuccess,
  bindInterceptInvalidWorkshop,
  bindInterceptInvalidWorkshopChange,
  bindOrderCancel,
  bindOrderConfirm,
  bindOrderConfirmRedirect,
  bindOrderHomeRedirect,
  bindOrderSetDefaults,
  bindOrderSubmit,
];
<commit_msg>Handle missing order<commit_after>import { fork, put, select, takeLatest } from 'redux-saga/effects';
import { push } from 'react-router-redux';

import { getForm } from '../selectors/forms';
import { workshopsAll } from '../selectors/workshops';
import { getCheapestAccomodation } from '../selectors/accomodation';
import {
  getParticipantLatestOrder,
  getParticipantUnconfirmedOrder,
} from '../selectors/participant';
import { yearActiveNumber } from '../selectors/years';
import { reverse } from '../routeTable';

import { fetchResource } from './common';
import { sendForm } from './forms';

import * as api from '../api';
import * as constants from '../constants/actions';

export const selectOrderSubmit = action =>
  action.type === constants.FORM_SUBMIT_ALLOWED && action.form === 'order';

export const selectOrderSuccess = action =>
  action.type === constants.FORM_SUBMIT_SUCCESS && action.form === 'order';

export const selectChangeWorkshopSubmit = action =>
  action.type === constants.FORM_SUBMIT_ALLOWED && action.form === 'changeWorkshop';

export const selectChangeWorkshopSuccess = action =>
  action.type === constants.FORM_SUBMIT_SUCCESS && action.form === 'changeWorkshop';

export function* redirectHome() {
  yield put(push(reverse('participant:home')));
}

export function* orderSetDefaults() {
  const year = yield select(yearActiveNumber);
  const accomodation = yield select(getCheapestAccomodation);
  yield put({
    form: 'order',
    type: constants.FORM_VALUES_SET,
    values: {
      accomodation: accomodation ? accomodation.id : null,
      meals: [],
      year,
    },
  });
}

export function* orderCancel() {
  const order = yield select(getParticipantLatestOrder);
  if (order) {
    yield fork(
      fetchResource,
      api.orderCancel,
      {
        onStart: constants.ORDER_CANCEL_FETCH_STARTED,
        onSuccess: constants.ORDER_CANCEL_FETCH_SUCCESS,
        onError: constants.ORDER_CANCEL_FETCH_ERROR,
        order: order.id,
      }
    );
  }
}

export function* orderConfirm() {
  const order = yield select(getParticipantUnconfirmedOrder);
  if (order) {
    yield fork(
      fetchResource,
      api.orderConfirm,
      {
        onStart: constants.ORDER_CONFIRM_FETCH_STARTED,
        onSuccess: constants.ORDER_CONFIRM_FETCH_SUCCESS,
        onError: constants.ORDER_CONFIRM_FETCH_ERROR,
        order: order.id,
      }
    );
  }
}

export function* orderSubmit() {
  const form = yield select(getForm, 'order');
  yield fork(sendForm, api.orderCreate, 'order', form.values);
}

export function* orderConfirmRedirect(action) {
  yield put({
    type: constants.ORDER_CREATED,
    data: action.data,
  });
  yield put(push(reverse('participant:confirm')));
}

export function* orderCancelRedirect() {
  yield put({ type: constants.ORDER_CANCELED });
  yield fork(redirectHome);
}

export function* orderChangeRedirect() {
  yield put({ type: constants.ORDER_CHANGED });
  yield fork(redirectHome);
}

export function* orderChangeSetDefaults() {
  const order = yield select(getParticipantLatestOrder);
  yield put({
    form: 'changeWorkshop',
    type: constants.FORM_VALUES_SET,
    values: {
      workshop: order ? order.workshop.id : null,
    },
  });
}

export function* orderChangeWorkshopSubmit() {
  const form = yield select(getForm, 'changeWorkshop');
  const order = yield select(getParticipantLatestOrder);
  yield fork(sendForm, api.orderChangeWorkshop, 'changeWorkshop', form.values, {
    order: order.id,
  });
}

export function* bindOrderConfirmRedirect() {
  yield takeLatest(
    selectOrderSubmit,
    orderSubmit
  );
}

export function* bindOrderHomeRedirect() {
  yield takeLatest(
    [
      constants.ORDER_CANCEL_FETCH_SUCCESS,
      constants.ORDER_CONFIRM_FETCH_SUCCESS,
    ],
    orderCancelRedirect
  );
}

export function* bindOrderCancel() {
  yield takeLatest(
    constants.ORDER_CANCEL_REQUESTED,
    orderCancel
  );
}

export function* bindOrderConfirm() {
  yield takeLatest(
    constants.ORDER_CONFIRM_REQUESTED,
    orderConfirm
  );
}

export function* bindOrderSubmit() {
  yield takeLatest(
    selectOrderSuccess,
    orderConfirmRedirect
  );
}

export function* bindOrderSetDefaults() {
  yield takeLatest(
    [
      constants.ACCOMODATION_FETCH_SUCCESS,
      constants.ORDER_FORM_MOUNTED,
    ],
    orderSetDefaults
  );
}

export function* interceptInvalidWorkshop() {
  const form = yield select(getForm, 'order');
  const workshops = yield select(workshopsAll);
  const selectedWorkshop = workshops.find(
    workshop => workshop.id === form.values.workshop
  );

  if (
    form.values.workshop &&
    (
      !selectedWorkshop ||
      selectedWorkshop.capacityStatus.freeSpots === 0
    )
  ) {
    yield put({
      type: constants.FORM_FIELD_CHANGE,
      form: 'order',
      field: 'workshop',
      value: null,
    });
  }
}

export function* interceptInvalidWorkshopChange() {
  const order = yield select(getParticipantLatestOrder);
  const form = yield select(getForm, 'changeWorkshop');
  const workshops = yield select(workshopsAll);

  const selectedWorkshop = workshops.find(
    workshop => workshop.id === form.values.workshop
  );

  if (
    !selectedWorkshop ||
    (
      form.values.workshop &&
      order &&
      order.workshop &&
      order.workshop.id !== form.values.workshop &&
      selectedWorkshop.capacityStatus.freeSpots === 0
    )
  ) {
    yield put({
      type: constants.FORM_FIELD_CHANGE,
      form: 'changeWorkshop',
      field: 'workshop',
      value: order ? order.workshop.id : null,
    });
  }
}

export function* bindInterceptInvalidWorkshop() {
  yield takeLatest(
    constants.YEAR_CAPACITY_FETCH_SUCCESS,
    interceptInvalidWorkshop
  );
}

export function* bindInterceptInvalidWorkshopChange() {
  yield takeLatest(
    constants.YEAR_CAPACITY_FETCH_SUCCESS,
    interceptInvalidWorkshopChange
  );
}

export function* bindChangeWorkshopSubmit() {
  yield takeLatest(selectChangeWorkshopSubmit, orderChangeWorkshopSubmit);
}

export function* bindChangeWorkshopSuccess() {
  yield takeLatest(selectChangeWorkshopSuccess, orderChangeRedirect);
}

export function* bindChangeWorkshopSetDefaults() {
  yield takeLatest(constants.PARTICIPANT_WORKSHOP_CHANGE_MOUNTED, orderChangeSetDefaults);
}

export default [
  bindChangeWorkshopSetDefaults,
  bindChangeWorkshopSubmit,
  bindChangeWorkshopSuccess,
  bindInterceptInvalidWorkshop,
  bindInterceptInvalidWorkshopChange,
  bindOrderCancel,
  bindOrderConfirm,
  bindOrderConfirmRedirect,
  bindOrderHomeRedirect,
  bindOrderSetDefaults,
  bindOrderSubmit,
];
<|endoftext|>


<commit_before>const expect = require('unexpected');
const pathModule = require('path');
const childProcess = require('child_process');

describe('in afterEach mode', function () {
    const fs = expect.promise.promisifyAll(require('fs'));
    const tmpDir = pathModule.resolve(__dirname, 'tmp');

    before(() => fs.mkdirAsync(tmpDir).catch(() => {}));
    after(() => fs.rmdirAsync(tmpDir).catch(() => {}));

    const preamble =
        "var fetchception = require('../../');\n" +
        "var expect = require('unexpected');\n";

    expect.addAssertion('<function> when run through mocha <assertion>', (expect, subject) => {
        expect.errorMode = 'nested';
        const code = subject.toString().replace(/^[^{]+\{|\}\s*$/g, '');
        expect.subjectOutput = function (output) {
            output.code(code, 'javascript');
        };
        const tmpFileName = pathModule.resolve(tmpDir, 'fetchception' + Math.round(10000000 * Math.random()) + '.js');
        const testCommand =
            process.argv[0] + ' ' + pathModule.resolve(__dirname, '..', 'node_modules', '.bin', 'mocha') +
            ' --require ' + pathModule.resolve(__dirname, 'mocha', 'setupTests.js') + ' ' + tmpFileName;

        return fs.writeFileAsync(tmpFileName, preamble + code, 'utf-8')
        .then(() => expect.promise.fromNode(cb => childProcess.exec(testCommand, cb.bind(null, null))))
        .then(([stdout, stderr]) => expect.shift(stderr))
        .finally(() => fs.unlinkAsync(tmpFileName));
    });

    it('should succeed when the correct HTTP request is made', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /', response: 200 });
                return fetch('/');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain', '✓ should foo\n\n  1 passing');
    });

    it('should fail with a diff when too few requests are made', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /', response: 200 });
            });
            /* eslint-enable */
        }, 'when run through mocha to match', /"after each" hook for "should foo"[\s\S]*\/\/ missing:\n\/\/ GET \/\n/);
    });

    it('should fail with a diff when a request does not match the mocked out traffic', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/bar');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain',
                'GET /bar // should be GET /foo\n' +
                '         //\n' +
                '         // -GET /bar\n' +
                '         // +GET /foo\n' +
                '\n' +
                '\n' +
                'HTTP/1.1 200 OK\n' +
                '\n'
        );
    });

    it('should fail with a diff the first test out of two fails', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/bar');
            });

            it('should bar', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/foo');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain',
                'GET /bar // should be GET /foo\n' +
                '         //\n' +
                '         // -GET /bar\n' +
                '         // +GET /foo\n' +
                '\n' +
                '\n' +
                'HTTP/1.1 200 OK\n' +
                '\n'
        );
    });

    it('should fail with a diff the second test out of two fails', function () {
        return expect(() => {
            /* eslint-disable */
            it('should bar', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/foo');
            });

            it('should foo', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/bar');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain',
                'GET /bar // should be GET /foo\n' +
                '         //\n' +
                '         // -GET /bar\n' +
                '         // +GET /foo\n' +
                '\n' +
                '\n' +
                'HTTP/1.1 200 OK\n' +
                '\n'
        );
    });
});
<commit_msg>afterEach test: Support both jest's and mocha's before/after hooks<commit_after>/*global afterAll, beforeAll*/
const expect = require('unexpected');
const pathModule = require('path');
const childProcess = require('child_process');

describe('in afterEach mode', function () {
    const fs = expect.promise.promisifyAll(require('fs'));
    const tmpDir = pathModule.resolve(__dirname, 'tmp');

    (typeof before === 'function' ? before : beforeAll)(() => fs.mkdirAsync(tmpDir).catch(() => {}));
    (typeof after === 'function' ? after : afterAll)(() => fs.rmdirAsync(tmpDir).catch(() => {}));

    const preamble =
        "var fetchception = require('../../');\n" +
        "var expect = require('unexpected');\n";

    expect.addAssertion('<function> when run through mocha <assertion>', (expect, subject) => {
        expect.errorMode = 'nested';
        const code = subject.toString().replace(/^[^{]+\{|\}\s*$/g, '');
        expect.subjectOutput = function (output) {
            output.code(code, 'javascript');
        };
        const tmpFileName = pathModule.resolve(tmpDir, 'fetchception' + Math.round(10000000 * Math.random()) + '.js');
        const testCommand =
            process.argv[0] + ' ' + pathModule.resolve(__dirname, '..', 'node_modules', '.bin', 'mocha') +
            ' --require ' + pathModule.resolve(__dirname, 'mocha', 'setupTests.js') + ' ' + tmpFileName;

        return fs.writeFileAsync(tmpFileName, preamble + code, 'utf-8')
        .then(() => expect.promise.fromNode(cb => childProcess.exec(testCommand, cb.bind(null, null))))
        .then(([stdout, stderr]) => expect.shift(stderr))
        .finally(() => fs.unlinkAsync(tmpFileName));
    });

    it('should succeed when the correct HTTP request is made', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /', response: 200 });
                return fetch('/');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain', '✓ should foo\n\n  1 passing');
    });

    it('should fail with a diff when too few requests are made', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /', response: 200 });
            });
            /* eslint-enable */
        }, 'when run through mocha to match', /"after each" hook for "should foo"[\s\S]*\/\/ missing:\n\/\/ GET \/\n/);
    });

    it('should fail with a diff when a request does not match the mocked out traffic', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/bar');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain',
                'GET /bar // should be GET /foo\n' +
                '         //\n' +
                '         // -GET /bar\n' +
                '         // +GET /foo\n' +
                '\n' +
                '\n' +
                'HTTP/1.1 200 OK\n' +
                '\n'
        );
    });

    it('should fail with a diff the first test out of two fails', function () {
        return expect(() => {
            /* eslint-disable */
            it('should foo', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/bar');
            });

            it('should bar', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/foo');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain',
                'GET /bar // should be GET /foo\n' +
                '         //\n' +
                '         // -GET /bar\n' +
                '         // +GET /foo\n' +
                '\n' +
                '\n' +
                'HTTP/1.1 200 OK\n' +
                '\n'
        );
    });

    it('should fail with a diff the second test out of two fails', function () {
        return expect(() => {
            /* eslint-disable */
            it('should bar', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/foo');
            });

            it('should foo', function () {
                fetchception({ request: 'GET /foo', response: 200 });
                return fetch('/bar');
            });
            /* eslint-enable */
        }, 'when run through mocha to contain',
                'GET /bar // should be GET /foo\n' +
                '         //\n' +
                '         // -GET /bar\n' +
                '         // +GET /foo\n' +
                '\n' +
                '\n' +
                'HTTP/1.1 200 OK\n' +
                '\n'
        );
    });
});
<|endoftext|>


<commit_before>exports.handlers = {
  404: function (e) {
    logError(this, e);
    return "[404] Oops.. the URL was not found.";
  },

  500: function (e) {
    logError(this, e);
    return "[500] Well, that didn't work. Sorry about that.";
  }
}

function logError(request, e) {
  if (e.stack) {
    request.LOG.error(request.path + "\n" + e.stack + "\n\n");
  } else if (e.message) {
    request.LOG.error(request.path + " -- " + e.message + "\n");
  } else {
    request.LOG.error(request.path + "--" + JSON.stringify(e));
  }
}
<commit_msg>Fixed new lines.<commit_after>exports.handlers = {
  404: function (e) {
    logError(this, e);
    return "[404] Oops.. the URL was not found.";
  },

  500: function (e) {
    logError(this, e);
    return "[500] Well, that didn't work. Sorry about that.";
  }
}

function logError(request, e) {
  if (e.stack) {
    request.LOG.error(request.path + "\n" + e.stack + "\n");
  } else if (e.message) {
    request.LOG.error(request.path + " -- " + e.message);
  } else {
    request.LOG.error(request.path + "--" + JSON.stringify(e));
  }
}
<|endoftext|>


<commit_before>/**
 * maryamyriameliamurphies.js
 * A library of Haskell-style morphisms ported to ES2015 JavaScript.
 *
 * test/base/bool-test.js
 *
 * @file Tests for boolean functions.
 * @license ISC
 */

/* global describe, it */

import {
  and,
  or,
  not
} from '../../source';

describe(`Boolean functions`, function() {
  describe(`and()`, function() {
   it(`should return true if both of two values are true`, function() {
     and(true, true).should.be.true;
   });
   it(`should return false if either of two values is false`, function() {
     and(true, false).should.be.false;
     and(false, true).should.be.false;
   });
  });
  describe(`or()`, function() {
   it(`should return true if either of two values are true`, function() {
     or(true, false).should.be.true;
     or(false, true).should.be.true;
     or(true, true).should.be.true;
   });
   it(`should return false if both of two values are false`, function() {
     or(false, false).should.be.false;
   });
  });
  describe(`not()`, function() {
   it(`should return false if a value is true`, function() {
     not(true);
   });
   it(`should return true if a value is false`, function() {
     not(false);
   });
  });
});
<commit_msg>Add tests to bool-test to cover untested code<commit_after>/**
 * maryamyriameliamurphies.js
 * A library of Haskell-style morphisms ported to ES2015 JavaScript.
 *
 * test/base/bool-test.js
 *
 * @file Tests for boolean functions.
 * @license ISC
 */

/* global describe, it */

import {
  and,
  or,
  not
} from '../../source';

describe(`Boolean functions`, function() {
  describe(`and()`, function() {
   it(`should return true if both of two values are true`, function() {
     and(true, true).should.be.true;
   });
   it(`should return false if either of two values is false`, function() {
     and(true, false).should.be.false;
     and(false, true).should.be.false;
   });
   it(`should throw an error if either argument is not a boolean value`, function() {
     and.bind(null, true, 0);
     and.bind(null, 0, false);
   });
  });
  describe(`or()`, function() {
   it(`should return true if either of two values are true`, function() {
     or(true, false).should.be.true;
     or(false, true).should.be.true;
     or(true, true).should.be.true;
   });
   it(`should return false if both of two values are false`, function() {
     or(false, false).should.be.false;
   });
   it(`should throw an error if either argument is not a boolean value`, function() {
     or.bind(null, true, 0);
     or.bind(null, 0, false);
   });
  });
  describe(`not()`, function() {
   it(`should return false if a value is true`, function() {
     not(true);
   });
   it(`should return true if a value is false`, function() {
     not(false);
   });
   it(`should throw an error if the argument is not a boolean value`, function() {
     and.bind(null, 0);
   });
  });
});
<|endoftext|>


<commit_before>"use strict";

// Expressões regulares semi-prontas para cada palavrão.

module.exports = {

  // Deve ser organizado por ordem alfabética (exceto "foder").
  "bilau": "bilau((s|z)(ao|inho))?",
  "boceta": "b(o|u)cet(a(o|(s|z)(inha|ona))?|inha|ona|ud(a|o))",
  "caralho": "(c|k)aralh(a(o|da|zinha)?|inh(a|o)|o(z(ao|inh(a|o)|ona)|na)?|u(d(a|o)))",
  "cu": "(c|k)u(h|(s|z)(ao|inho|ona))?",
  "pepeca": "pepe((c|k)(a((s|z)inha)?|inha|ona|ud(a|o))|quinha)",
  "pinto": "pint(ao|inho|o((s|z)inho)?|udo)",
  "piroca": "piro((c|k)(a(ada|o|(s|z)(inha|ona))?|inha|ona|ud(a|o))|quinha)",
  "porra": "po(h|rr)(a(o|(s|z)(inha|ona))?|inha|ona)",
  "punheta": "p(o|u)nhet(a((s|z)(inha|ona)|o)?|inha|ona)",
  "puta": "put(a(ria|da|(s|z)(inha|ona)|o)?|inha|ona)",

  // Conjugações do verbo foder.
  // Feito com base nas informações obtidas em <https://www.conjugacao.com.br/verbo-foder/>.
  // Corresponde também ao verbo "fuder" (escrita errada), com exceção do presente do indicativo e subjuntivo.
  "foder": "(f(o|u)d(ido|endo|(e(mos|r(a(m(os)?|(o|s)?)?|des|ei(s)?|em(os)?|es|ia(m(os)?|s)?|ieis|mos)?|s(se(is|s|m(os)?)?|te(s)?)|u)|i((a(m(os)?|s)?)?|eis)?))|fod(a(is|m(os)?|s)?|e(is|m(os)?|s)?|o))"
};
<commit_msg>adiciona "merda" na lista<commit_after>"use strict";

// Expressões regulares semi-prontas para cada palavrão.

module.exports = {

  // Deve estar organizado por ordem alfabética (exceto "foder").
  "bilau": "bilau((s|z)(ao|inho))?",
  "boceta": "b(o|u)cet(a(o|(s|z)(inha|ona))?|inha|ona|ud(a|o))",
  "caralho": "(c|k)aralh(a(o|da|zinha)?|inh(a|o)|o(z(ao|inh(a|o)|ona)|na)?|u(d(a|o)))",
  "cu": "(c|k)u(h|(s|z)(ao|inho|ona))?",
  "merda": "merd(a((s|z)(inha|ona)|o)?|inha|ona)",
  "pepeca": "pepe((c|k)(a((s|z)inha)?|inha|ona|ud(a|o))|quinha)",
  "pinto": "pint(ao|inho|o((s|z)inho)?|udo)",
  "piroca": "piro((c|k)(a(ada|o|(s|z)(inha|ona))?|inha|ona|ud(a|o))|quinha)",
  "porra": "po(h|rr)(a(o|(s|z)(inha|ona))?|inha|ona)",
  "punheta": "p(o|u)nhet(a((s|z)(inha|ona)|o)?|inha|ona)",
  "puta": "put(a(ria|da|(s|z)(inha|ona)|o)?|inha|ona)",

  // Conjugações do verbo foder.
  // Feito com base nas informações obtidas em <https://www.conjugacao.com.br/verbo-foder/>.
  // Corresponde também ao verbo "fuder" (escrita errada), com exceção do presente do indicativo e subjuntivo.
  "foder": "(f(o|u)d(ido|endo|(e(mos|r(a(m(os)?|(o|s)?)?|des|ei(s)?|em(os)?|es|ia(m(os)?|s)?|ieis|mos)?|s(se(is|s|m(os)?)?|te(s)?)|u)|i((a(m(os)?|s)?)?|eis)?))|fod(a(is|m(os)?|s)?|e(is|m(os)?|s)?|o))"
};
<|endoftext|>


<commit_before>/**
 * @author Pedro Sanders
 * @since v1
 */
const CoreUtils = require('@routr/core/utils')
const UsersAPI = require('@routr/data_api/users_api')
const AgentsAPI = require('@routr/data_api/agents_api')
const DomainsAPI = require('@routr/data_api/domains_api')
const PeersAPI = require('@routr/data_api/peers_api')
const GatewaysAPI = require('@routr/data_api/gateways_api')
const NumbersAPI = require('@routr/data_api/numbers_api')
const DSSelector = require('@routr/data_api/ds_selector')
const SDSelector = require('@routr/data_api/store_driver_selector')
const StoreAPI = require('@routr/data_api/store_api')
const ConfigAPI = require('@routr/data_api/config_api')
const DSUtils = require('@routr/data_api/utils')
const System = Java.type('java.lang.System')
const isEmpty = require('@routr/utils/obj_util')
const config = require('@routr/core/config_util')()
const { reloadConfig } = require('@routr/core/config_util')
const { Status } = require('@routr/core/status')
const getJWTToken = require('@routr/rest/jwt_token_generator')
const resourcesService = require('@routr/rest/resources_service')
const locationService = require('@routr/rest/location_service')
const parameterAuthFilter = require('@routr/rest/parameter_auth_filter')
const basicAuthFilter = require('@routr/rest/basic_auth_filter')
const moment = require('moment')

const GRPCClient = Java.type('io.routr.core.GRPCClient')
const Spark = Java.type('spark.Spark')
const options = Java.type('spark.Spark').options
const get = Java.type('spark.Spark').get
const post = Java.type('spark.Spark').post
const put = Java.type('spark.Spark').put
const before = Java.type('spark.Spark').before
const path = Java.type('spark.Spark').path

const LogManager = Java.type('org.apache.logging.log4j.LogManager')
const LOG = LogManager.getLogger()

class Rest {
  constructor () {
    this.store = new StoreAPI(SDSelector.getDriver())
    this.grpc = new GRPCClient('localhost', config.spec.grpcService.port)

    LOG.info(
      `Starting Restful service (port: ${
        config.spec.restService.port
      }, apiPath: ${config.system.apiPath})`
    )

    Spark.ipAddress(config.spec.restService.bindAddr)
    Spark.threadPool(
      config.spec.restService.maxThreads,
      config.spec.restService.minThreads,
      config.spec.restService.timeOutMillis
    )

    if (!config.spec.restService.unsecured) {
      Spark.secure(
        config.spec.restService.keyStore,
        config.spec.restService.keyStorePassword,
        config.spec.restService.trustStore,
        config.spec.restService.trustStorePassword
      )
    }

    Spark.port(config.spec.restService.port)

    Spark.initExceptionHandler(e => {
      LOG.fatal('Unable to start restService: ' + e.message)
      System.exit(1)
    })

    Spark.exception(Java.type('java.lang.Exception'), (e, req, res) => {
      res.type('application/json')
      if (e.getMessage().equals('UNAUTHORIZED REQUEST')) {
        res.status(401)
        res.body('{"status": "401", "message":"Unauthorized"}')
      } else {
        res.status(500)
        res.body('{"status": "500", "message":"Internal server error"}')
      }
    })
    Spark.notFound((req, res) => {
      res.type('application/json')
      return '{"status": "404", "message":"Not found"}'
    })
  }

  sendCmd (req, res, grpc) {
    const status = req.params(':status')
    if (status !== 'down' && status !== 'restarting') {
      res.status(400)
      return '{"status": "400", "message":"Bad Request"}'
    }

    const c = status === 'down' ? 'stop-server' : 'restart-server'
    const cmd = req.queryParams('now') === 'true' ? `${c}-now` : c
    grpc.run(cmd)
    res.status(200)
    return '{"status": "200", "message":"Request sent to server."}'
  }

  start () {
    const ds = DSSelector.getDS()
    const configApi = new ConfigAPI(ds)

    options('/*', (req, res) => {
      const accessControlRequestHeaders = req.headers(
        'Access-Control-Request-Headers'
      )
      if (accessControlRequestHeaders !== null) {
        res.header('Access-Control-Allow-Headers', accessControlRequestHeaders)
      }

      const accessControlRequestMethod = req.headers(
        'Access-Control-Request-Method'
      )
      if (accessControlRequestMethod !== null) {
        res.header('Access-Control-Allow-Methods', accessControlRequestMethod)
      }
      return 'OK'
    })

    path(config.system.apiPath, r => {
      before('/*', (req, res) => {
        res.header('Access-Control-Allow-Origin', '*')
        if (
          req.pathInfo().endsWith('/credentials') ||
          req.pathInfo().endsWith('/token')
        ) {
          basicAuthFilter(req, res, new UsersAPI(ds))
        } else {
          parameterAuthFilter(req, res, config.salt)
        }
      })

      // Its always running! Use to ping Routr server
      get('/system/status', (req, res) => '{"status": "Up"}')

      post('/system/status/:status', (req, res) =>
        this.sendCmd(req, res, this.grpc)
      )

      get('/system/info', (req, res) => JSON.stringify(config.system))

      get('/system/config', (req, res) => JSON.stringify(configApi.getConfig()))

      put('/system/config', (req, res) => {
        const c = JSON.parse(req.body())
        return JSON.stringify(configApi.setConfig(c))
      })

      // Deprecated
      get('/credentials', (req, res) => getJWTToken(req, res, config.salt))

      get('/token', (req, res) =>
        JSON.stringify(
          CoreUtils.buildResponse(Status.OK, getJWTToken(req, res, config.salt))
        )
      )

      get('/registry', (req, res) => {
        const items = this.store
          .withCollection('registry')
          .values()
          .map(r => {
            const reg = JSON.parse(r)
            reg.regOnFormatted = moment(reg.registeredOn).fromNow()
            return reg
          })

        let page = 1
        let itemsPerPage = 30
        if (!isEmpty(req.queryParams('page'))) page = req.queryParams('page')
        if (!isEmpty(req.queryParams('itemsPerPage')))
          itemsPerPage = req.queryParams('itemsPerPage')

        return JSON.stringify(DSUtils.paginate(items, page, itemsPerPage))
      })

      locationService(this.store, this.grpc)

      resourcesService(new AgentsAPI(ds), 'Agent')
      resourcesService(new PeersAPI(ds), 'Peer')
      resourcesService(new DomainsAPI(ds), 'Domain')
      resourcesService(new GatewaysAPI(ds), 'Gateway')
      resourcesService(new NumbersAPI(ds), 'Number')
    })
  }

  stop () {
    LOG.info('Stopping Restful service')
    Spark.stop()
    this.grpc.shutdown()
  }
}

new Rest().start()
<commit_msg>Added new endpoints logs and logs-ws<commit_after>/**
 * @author Pedro Sanders
 * @since v1
 */
const CoreUtils = require('@routr/core/utils')
const UsersAPI = require('@routr/data_api/users_api')
const AgentsAPI = require('@routr/data_api/agents_api')
const DomainsAPI = require('@routr/data_api/domains_api')
const PeersAPI = require('@routr/data_api/peers_api')
const GatewaysAPI = require('@routr/data_api/gateways_api')
const NumbersAPI = require('@routr/data_api/numbers_api')
const DSSelector = require('@routr/data_api/ds_selector')
const SDSelector = require('@routr/data_api/store_driver_selector')
const StoreAPI = require('@routr/data_api/store_api')
const ConfigAPI = require('@routr/data_api/config_api')
const DSUtils = require('@routr/data_api/utils')
const FilesUtil = require('@routr/utils/files_util')
const System = Java.type('java.lang.System')
const isEmpty = require('@routr/utils/obj_util')
const config = require('@routr/core/config_util')()
const { reloadConfig } = require('@routr/core/config_util')
const { Status } = require('@routr/core/status')
const getJWTToken = require('@routr/rest/jwt_token_generator')
const resourcesService = require('@routr/rest/resources_service')
const locationService = require('@routr/rest/location_service')
const parameterAuthFilter = require('@routr/rest/parameter_auth_filter')
const basicAuthFilter = require('@routr/rest/basic_auth_filter')
const moment = require('moment')

const LogsHandler = Java.type('io.routr.core.LogsHandler')
const GRPCClient = Java.type('io.routr.core.GRPCClient')
const Spark = Java.type('spark.Spark')
const options = Java.type('spark.Spark').options
const get = Java.type('spark.Spark').get
const post = Java.type('spark.Spark').post
const put = Java.type('spark.Spark').put
const before = Java.type('spark.Spark').before
const path = Java.type('spark.Spark').path
const webSocket = Java.type('spark.Spark').webSocket

const LogManager = Java.type('org.apache.logging.log4j.LogManager')
const LOG = LogManager.getLogger()

class Rest {
  constructor () {
    this.store = new StoreAPI(SDSelector.getDriver())
    this.grpc = new GRPCClient('localhost', config.spec.grpcService.port)

    LOG.info(
      `Starting Restful service (port: ${
        config.spec.restService.port
      }, apiPath: ${config.system.apiPath})`
    )

    Spark.ipAddress(config.spec.restService.bindAddr)
    Spark.threadPool(
      config.spec.restService.maxThreads,
      config.spec.restService.minThreads,
      config.spec.restService.timeOutMillis
    )

    if (!config.spec.restService.unsecured) {
      Spark.secure(
        config.spec.restService.keyStore,
        config.spec.restService.keyStorePassword,
        config.spec.restService.trustStore,
        config.spec.restService.trustStorePassword
      )
    }

    Spark.port(config.spec.restService.port)

    Spark.initExceptionHandler(e => {
      LOG.fatal('Unable to start restService: ' + e.message)
      System.exit(1)
    })

    Spark.exception(Java.type('java.lang.Exception'), (e, req, res) => {
      res.type('application/json')
      if (e.getMessage().equals('UNAUTHORIZED REQUEST')) {
        res.status(401)
        res.body('{"status": "401", "message":"Unauthorized"}')
      } else {
        res.status(500)
        res.body('{"status": "500", "message":"Internal server error"}')
      }
    })
    Spark.notFound((req, res) => {
      res.type('application/json')
      return '{"status": "404", "message":"Not found"}'
    })
  }

  sendCmd (req, res, grpc) {
    const status = req.params(':status')
    if (status !== 'down' && status !== 'restarting') {
      res.status(400)
      return '{"status": "400", "message":"Bad Request"}'
    }

    const c = status === 'down' ? 'stop-server' : 'restart-server'
    const cmd = req.queryParams('now') === 'true' ? `${c}-now` : c
    grpc.run(cmd)
    res.status(200)
    return '{"status": "200", "message":"Request sent to server."}'
  }

  start () {
    const ds = DSSelector.getDS()
    const configApi = new ConfigAPI(ds)

    // Warning: Experimental
    webSocket(config.system.apiPath + '/system/logs-ws', LogsHandler)

    options('/*', (req, res) => {
      const accessControlRequestHeaders = req.headers(
        'Access-Control-Request-Headers'
      )
      if (accessControlRequestHeaders !== null) {
        res.header('Access-Control-Allow-Headers', accessControlRequestHeaders)
      }

      const accessControlRequestMethod = req.headers(
        'Access-Control-Request-Method'
      )
      if (accessControlRequestMethod !== null) {
        res.header('Access-Control-Allow-Methods', accessControlRequestMethod)
      }
      return 'OK'
    })

    path(config.system.apiPath, r => {
      before('/*', (req, res) => {
        res.header('Access-Control-Allow-Origin', '*')
        if (
          req.pathInfo().endsWith('/credentials') ||
          req.pathInfo().endsWith('/token')
        ) {
          basicAuthFilter(req, res, new UsersAPI(ds))
        } else {
          parameterAuthFilter(req, res, config.salt)
        }
      })

      // Its always running! Use to ping Routr server
      get('/system/status', (req, res) =>
        JSON.stringify(CoreUtils.buildResponse(Status.OK, 'up'))
      )

      post('/system/status/:status', (req, res) =>
        this.sendCmd(req, res, this.grpc)
      )

      get('/system/logs', (req, res) => {
        const home = System.getenv('ROUTR_DATA') || '.'
        return JSON.stringify(
          CoreUtils.buildResponse(
            Status.OK,
            FilesUtil.readFile(`${home}/logs/routr.log`)
          )
        )
      })

      get('/system/info', (req, res) =>
        JSON.stringify(CoreUtils.buildResponse(Status.OK, config.system))
      )

      get('/system/config', (req, res) => JSON.stringify(configApi.getConfig()))

      put('/system/config', (req, res) => {
        const c = JSON.parse(req.body())
        return JSON.stringify(configApi.setConfig(c))
      })

      // Deprecated
      get('/credentials', (req, res) => getJWTToken(req, res, config.salt))

      get('/token', (req, res) =>
        JSON.stringify(
          CoreUtils.buildResponse(Status.OK, getJWTToken(req, res, config.salt))
        )
      )

      get('/registry', (req, res) => {
        const items = this.store
          .withCollection('registry')
          .values()
          .map(r => {
            const reg = JSON.parse(r)
            reg.regOnFormatted = moment(reg.registeredOn).fromNow()
            return reg
          })

        let page = 1
        let itemsPerPage = 30
        if (!isEmpty(req.queryParams('page'))) page = req.queryParams('page')
        if (!isEmpty(req.queryParams('itemsPerPage')))
          itemsPerPage = req.queryParams('itemsPerPage')

        return JSON.stringify(DSUtils.paginate(items, page, itemsPerPage))
      })

      locationService(this.store, this.grpc)

      resourcesService(new AgentsAPI(ds), 'Agent')
      resourcesService(new PeersAPI(ds), 'Peer')
      resourcesService(new DomainsAPI(ds), 'Domain')
      resourcesService(new GatewaysAPI(ds), 'Gateway')
      resourcesService(new NumbersAPI(ds), 'Number')
    })
  }

  stop () {
    LOG.info('Stopping Restful service')
    Spark.stop()
    this.grpc.shutdown()
  }
}

new Rest().start()
<|endoftext|>


<commit_before>/*jslint node: true, nomen: true, es5: true */
/**
 * Developed By Carlo Bernaschina (GitHub - B3rn475)
 * www.bernaschina.com
 *
 * Copyright (c) 2014 Politecnico di Milano
 * www.polimi.it
 *
 * Distributed under the MIT Licence
 */
"use strict";

var mongoose = require("mongoose"),
    mongooseAI = require("mongoose-auto-increment"),
    ImageTags = require("./imagetags.js").model,
    ImageSegmentations = require("./imagesegmentations.js").model;

exports.regexp = { points: {}, history: {}, params: {}, query: {}};

exports.regexp.color = /(rgb\(([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9])\))|(rgba\(([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*(1|0|1\.0|0\.[0-9]+)\))/;

exports.regexp.params.type = /tagging|segmentation$/;
exports.regexp.query.type = /tagging|segmentation|upload$/;

var schema = mongoose.Schema({ _id: { type: Number, min: 0, index: { unique: true }, select: false},
                                    session: {type: Number, min: 0, index: true, ref: "Session"},
                                    image: {type: Number, min: 0, index: true, ref: "Image"},
                                    tag: {type: Number, min: 0, index: true, ref: "Tag"},
                                    user: {type: Number, min: 0, index: true, ref: "User"},
                                    type: {type: String, index: true, enum: ["tagging", "segmentation", "upload"]},
                                    segmentation: { type: mongoose.Schema.Types.Mixed},
                                    created_at: {type: Date, index: true},
                                    completed_at: {type: Date, index: true},
                                    validity: {type: Boolean, default: true}
                                }, { id: false});

schema.virtual('id').get(function () { return this._id; });

schema.post('init', function (doc) {
    if (doc.segmentation !== undefined && doc.segmentation.points !== undefined && doc.segmentation.quality === undefined) {
        doc.segmentation = undefined;
    }
});

schema.pre('save', function (next) {
    this.wasNew = this.isNew;
    if (this.created_at === undefined) {
        this.created_at = new Date();
    }
    if (this.completed_at === undefined) {
        if (this.type === "tagging" && this.tag !== undefined) {
            this.completed_at = new Date();
        }
        if (this.type === "segmentation" && this.segmentation !== undefined) {
            this.completed_at = new Date();
        }
    }
    if (this.validity === undefined) {
        this.validity = true;
    }
    this.wasCompletedAtModified = this.isModified("completed_at");
    this.wasValidityModified = this.isModified("validity");
    this.wasSegmentationModified = this.isModified("segmentation");
    next();
});

schema.post('save', function () {
    var addAndUpdate = false,
        me = this;
    if (this.type === "tagging") {
        if (this.wasNew) {
            if (this.tag === undefined) {
                if (this.completed_at === undefined) {
                    ImageTags.update({image: this.image}, {$inc: {count: 1}}, function (err) { if (err) { console.log(err); } });
                }
            } else {
                addAndUpdate = true;
            }
        } else {
            if (this.wasCompletedAtModified) {
                ImageTags.update({image: this.image}, {$inc: {count: -1}}, function (err) { if (err) { console.log(err); } });
                if (this.tag !== undefined) {
                    addAndUpdate = true;
                }
            } else {
                if (this.wasValidityModified) {
                    if (this.validity) {
                        addAndUpdate = true;
                    } else {
                        exports.model.count({type: "tagging", image: this.image, tag: this.tag, validity: true}, function (err, count) {
                            if (err) {
                                console.log(err);
                            } else {
                                if (count === 0) {
                                    ImageSegmentations.update({image: me.image, tags: me.tag}, {$set: {validity: false}}, function (err) { if (err) { console.log(err); } });
                                    ImageTags.update({image: me.image, tags: {$in: [me.tag]}}, {$inc: {count: -1}, $pull: {tags: me.tag}}, function (err) { if (err) { console.log(err); } });
                                }
                            }
                        });
                    }
                }
            }
        }
        if (addAndUpdate) {
            ImageTags.findOneAndUpdate({image: this.image, tag: {$nin: [this.tag]}}, {$addToSet: {tags: this.tag}, $inc: {count: 1}}, function (err) { if (err) { console.log(err); } });
            ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: 0}, $set: {validity: true}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
        }
    } else if (this.type === "segmentation") {
        if (this.wasNew) {
            if (this.completed_at === undefined || this.segmentation !== undefined) {
                ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: 1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
            }
        } else {
            if (this.wasCompletedAtModified) {
                if (this.segmentation === undefined) {
                    ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: -1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
                }
            } else {
                if (this.segmentation !== undefined) {
                    if (this.wasValidityModified) {
                        if (this.validity) {
                            ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: 1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
                        } else {
                            ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: -1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
                        }
                    }
                }
            }
        }
    }
});

schema.options.toJSON = {
    transform: function (doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};

schema.statics.json_list_property = "actions";
schema.statics.pname = "action";

exports.schema = schema;

schema.plugin(mongooseAI.plugin, { model: 'Action', field: '_id' });

var model = mongoose.model('Action',
                           schema,
                           'Action');

exports.model = model;
<commit_msg>Update action.js<commit_after>/*jslint node: true, nomen: true, es5: true */
/**
 * Developed By Carlo Bernaschina (GitHub - B3rn475)
 * www.bernaschina.com
 *
 * Copyright (c) 2014 Politecnico di Milano
 * www.polimi.it
 *
 * Distributed under the MIT Licence
 */
"use strict";

var mongoose = require("mongoose"),
    mongooseAI = require("mongoose-auto-increment"),
    ImageTags = require("./imagetags.js").model,
    ImageSegmentations = require("./imagesegmentations.js").model;

exports.regexp = { points: {}, history: {}, params: {}, query: {}};

exports.regexp.color = /(rgb\(([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9])\))|(rgba\(([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*([0-1][0-9]{2}|2[0-4][0-9]|25[0-5]|[0-9]{2}|[0-9]),[ ]*(1|0|1\.0|0\.[0-9]+)\))/;

exports.regexp.params.type = /tagging|segmentation$/;
exports.regexp.query.type = /tagging|segmentation|upload$/;

var schema = mongoose.Schema({ _id: { type: Number, min: 0, index: { unique: true }, select: false},
                                    session: {type: Number, min: 0, index: true, ref: "Session"},
                                    image: {type: Number, min: 0, index: true, ref: "Image"},
                                    tag: {type: Number, min: 0, index: true, ref: "Tag"},
                                    user: {type: Number, min: 0, index: true, ref: "User"},
                                    type: {type: String, index: true, enum: ["tagging", "segmentation", "upload"]},
                                    segmentation: { type: mongoose.Schema.Types.Mixed},
                                    created_at: {type: Date, index: true},
                                    completed_at: {type: Date, index: true},
                                    validity: {type: Boolean, default: true}
                                }, { id: false});

schema.virtual('id').get(function () { return this._id; });

schema.post('init', function (doc) {
    if (doc.segmentation !== undefined && doc.segmentation.points !== undefined && doc.segmentation.quality === undefined) {
        doc.segmentation = undefined;
    }
});

schema.pre('save', function (next) {
    this.wasNew = this.isNew;
    if (this.created_at === undefined) {
        this.created_at = new Date();
    }
    if (this.completed_at === undefined) {
        if (this.type === "tagging" && this.tag !== undefined) {
            this.completed_at = new Date();
        }
        if (this.type === "segmentation" && this.segmentation !== undefined) {
            this.completed_at = new Date();
        }
    }
    if (this.validity === undefined) {
        this.validity = true;
    }
    this.wasCompletedAtModified = this.isModified("completed_at");
    this.wasValidityModified = this.isModified("validity");
    this.wasSegmentationModified = this.isModified("segmentation");
    next();
});

schema.post('save', function () {
    var addAndUpdate = false,
        me = this;
    if (this.type === "tagging") {
        if (this.wasNew) {
            if (this.tag === undefined) {
                if (this.completed_at === undefined) {
                    ImageTags.update({image: this.image}, {$inc: {count: 1}}, function (err) { if (err) { console.log(err); } });
                }
            } else {
                addAndUpdate = true;
            }
        } else {
            if (this.wasCompletedAtModified) {
                ImageTags.update({image: this.image}, {$inc: {count: -1}}, function (err) { if (err) { console.log(err); } });
                if (this.tag !== undefined) {
                    addAndUpdate = true;
                }
            } else {
                if (this.wasValidityModified) {
                    if (this.validity) {
                        addAndUpdate = true;
                    } else {
                        exports.model.count({type: "tagging", image: this.image, tag: this.tag, validity: true}, function (err, count) {
                            if (err) {
                                console.log(err);
                            } else {
                                if (count === 0) {
                                    ImageSegmentations.update({image: me.image, tag: me.tag}, {$set: {validity: false}}, function (err) { if (err) { console.log(err); } });
                                    ImageTags.update({image: me.image, tags: {$in: [me.tag]}}, {$inc: {count: -1}, $pull: {tags: me.tag}}, function (err) { if (err) { console.log(err); } });
                                }
                            }
                        });
                    }
                }
            }
        }
        if (addAndUpdate) {
            ImageTags.findOneAndUpdate({image: this.image, tags: {$nin: [this.tag]}}, {$addToSet: {tags: this.tag}, $inc: {count: 1}}, function (err) { if (err) { console.log(err); } });
            ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: 0}, $set: {validity: true}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
        }
    } else if (this.type === "segmentation") {
        if (this.wasNew) {
            if (this.completed_at === undefined || this.segmentation !== undefined) {
                ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: 1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
            }
        } else {
            if (this.wasCompletedAtModified) {
                if (this.segmentation === undefined) {
                    ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: -1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
                }
            } else {
                if (this.segmentation !== undefined) {
                    if (this.wasValidityModified) {
                        if (this.validity) {
                            ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: 1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
                        } else {
                            ImageSegmentations.update({image: this.image, tag: this.tag}, {$inc: {count: -1}}, {upsert: true}, function (err) { if (err) { console.log(err); } });
                        }
                    }
                }
            }
        }
    }
});

schema.options.toJSON = {
    transform: function (doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};

schema.statics.json_list_property = "actions";
schema.statics.pname = "action";

exports.schema = schema;

schema.plugin(mongooseAI.plugin, { model: 'Action', field: '_id' });

var model = mongoose.model('Action',
                           schema,
                           'Action');

exports.model = model;
<|endoftext|>


<commit_before>var Player = (function() {

    var module = {};

    var x;
    var y;
    var direction;
    var health;
    var canMove;
    var canPerformAction;

    module.name = 'p';

    module.constructor = function(x, y, direction, health) {
        this.x = x;
        this.y = y;
        this.direction = direction;
        this.health = health;
        this.canMove = true;
        this.canPerformAction = true;
    };

    module.getX = function() {
        return this.x;
    };

    module.setDir = function(dir) {
        this.direction = dir;
    };

    module.setHealth = function(health) {
        this.health = health;
    };

    module.walk = function() {
        if(!this.canPerformAction){
            console.log("Egy korben csak egy akciot tudsz vegrehajtani!");
            return;
        }
        this.canPerformAction = false;
        if(!this.canMove && this.direction == "RIGHT") {
            console.log('Nem tudsz tovább menni');
            return;
        }

        switch (this.direction) {
            case "UP":
                this.y++;
                break;
            case "DOWN":
                this.y--;
                break;
            case "LEFT":
                this.x--;
                break;
            case "RIGHT":
                this.x++;
                break;
            default:
                break;
        }

    };

    module.checkNextField = function(map) {
        var returnValue = 'empty field';
        map.forEach(function(element) {
            if (element.x === Player.getX() + 1) {
                returnValue = element;
            }
        });

        return returnValue;
    };

    module.feel = function() {
        var offset = 0;
        switch (this.direction) {
            case "LEFT":
                offset--;
                break;
            case "RIGHT":
                offset++;
                break;
            default:
                break;
        }

        var returnValue = false;
        Map.map.forEach(function(element) {
            if (element.name === 'e' && element.x === Player.getX() + offset) {
                returnValue = true;
            }
        });
        return returnValue;
    };

   // if(Player.feel()){Player.attack()}
    // else{Player.walk()}

    module.attack = function() {

        if(!this.canPerformAction){
            console.log("Egy korben csak egy akciot tudsz vegrehajtani!");
            return;
        }
        this.canPerformAction = false;
        var audio = new Audio('assets/sounds/sword.mp3');
        audio.play();
        var coord = this.x;
        switch (this.direction) {
            case "LEFT":
                coord--;
                break;
            case "RIGHT":
                coord++;
                break;
            default:
                break;
        }
        Map.attack(coord, 25);

    };

    return module;
})();<commit_msg>Renamed feel to isEnemy<commit_after>var Player = (function() {

    var module = {};

    var x;
    var y;
    var direction;
    var health;
    var canMove;
    var canPerformAction;

    module.name = 'p';

    module.constructor = function(x, y, direction, health) {
        this.x = x;
        this.y = y;
        this.direction = direction;
        this.health = health;
        this.canMove = true;
        this.canPerformAction = true;
    };

    module.getX = function() {
        return this.x;
    };

    module.setDir = function(dir) {
        this.direction = dir;
    };

    module.setHealth = function(health) {
        this.health = health;
    };

    module.walk = function() {
        if(!this.canPerformAction){
            console.log("Egy korben csak egy akciot tudsz vegrehajtani!");
            return;
        }
        this.canPerformAction = false;
        if(!this.canMove && this.direction == "RIGHT") {
            console.log('Nem tudsz tovább menni');
            return;
        }

        switch (this.direction) {
            case "UP":
                this.y++;
                break;
            case "DOWN":
                this.y--;
                break;
            case "LEFT":
                this.x--;
                break;
            case "RIGHT":
                this.x++;
                break;
            default:
                break;
        }

    };

    module.checkNextField = function(map) {
        var returnValue = 'empty field';
        map.forEach(function(element) {
            if (element.x === Player.getX() + 1) {
                returnValue = element;
            }
        });

        return returnValue;
    };

    module.isEnemy = function() {
        var offset = 0;
        switch (this.direction) {
            case "LEFT":
                offset--;
                break;
            case "RIGHT":
                offset++;
                break;
            default:
                break;
        }

        var returnValue = false;
        Map.map.forEach(function(element) {
            if (element.name === 'e' && element.x === Player.getX() + offset) {
                returnValue = true;
            }
        });
        return returnValue;
    };

   // if(Player.feel()){Player.attack()}
    // else{Player.walk()}

    module.attack = function() {

        if(!this.canPerformAction){
            console.log("Egy korben csak egy akciot tudsz vegrehajtani!");
            return;
        }
        this.canPerformAction = false;
        var audio = new Audio('assets/sounds/sword.mp3');
        audio.play();
        var coord = this.x;
        switch (this.direction) {
            case "LEFT":
                coord--;
                break;
            case "RIGHT":
                coord++;
                break;
            default:
                break;
        }
        Map.attack(coord, 25);

    };

    return module;
})();<|endoftext|>


<commit_before>// A report is a single post/comment/article or other chunk of data from a source.
// This class is responsible for executing ReportQuerys.

var database = require('../lib/database');
var mongoose = database.mongoose;
var textSearch = require('mongoose-text-search');
var Source = require('./source');
var Query = require('./query');
var _ = require('underscore');

var schema = new mongoose.Schema({
  authoredAt: Date,
  fetchedAt: Date,
  storedAt: Date,
  content: String,
  author: String,
  url: String,
  read: {type: Boolean, default: false, required: true},
  flagged: {type: Boolean, default: false, required: true},
  _source: {type: String, ref: 'Source'},
  _media: String,
  _sourceNickname: String,
  _incident: {type: String, ref: 'Incident'}
});

// Give the report schema text search capabilities
schema.plugin(textSearch);
// Add a text index to the `content` field
schema.index({content: 'text'});

schema.pre('save', function(next) {
  if (this.isNew) {
    this._wasNew = true;

    // Set default storedAt.
    if (!this.storedAt) this.storedAt = new Date();

  } else {
    // Capture updates before saving report
    if (this.isModified('_incident')) this._incidentWasModified = true;
  }
  next();
});

// Emit information about updates after saving report
schema.post('save', function() {
  if (this._wasNew) schema.emit('report:save', {_id: this._id.toString()});
  if (this._incidentWasModified) schema.emit('report:incident', {_id: this._id.toString(), _incident: this._incident ? this._incident.toString() : null});
});

var Report = mongoose.model('Report', schema);

// Query reports based on passed query data
Report.queryReports = function(query, page, callback) {
  if (typeof query === 'function') return Report.findPage(query);
  if (typeof page === 'function') {
    callback = page;
    page = 0;
  }
  if (page < 0) page = 0;

  query.limit = 100;
  query.filter = {};

  // Determine inclusive date filters
  if (query.after || query.before) {
    query.filter.storedAt = {};
    if (query.after) query.filter.storedAt.$gte = query.after;
    if (query.before) query.filter.storedAt.$lte = query.before;
  }

  // Convert reference fields for Report compatibility
  if (query.sourceId) query.filter._source = query.sourceId;
  if (query.sourceType) query.filter._media = query.sourceType;
  if (query.incidentId) query.filter._incident = query.incidentId;

  // Determine author filter
  if (query.author) {
    query.filter.author = {};
    query.filter.author.$in = query.author.replace(/(,|\s)+/g, ' ').split(' ').sort();
  }

  // Return only newer results
  if (query.since) {
    query.filter.storedAt = query.filter.storedAt || {};
    query.filter.storedAt.$gte = query.since;
  }

  // Re-set search timestamp
  query.since = new Date();

  if (!query.keywords) {
    // Just use filters when no keywords are provided
    Report.findSortedPage(query.filter, page, callback);
  } else {
    Report.textSearch(query.keywords, _.pick(query, ['filter', 'limit']), function(err, reports) {
      if (err) return callback(err);
      var result = {
        total: reports.stats.n ? reports.stats.nscannedObjects : 0,
        results: _.chain(reports.results).pluck('obj').sortBy('storedAt').value().reverse()
      };
      callback(null, result);
    });
  }
};

Report.findSortedPage = function(filter, page, callback) {
  Report.findPage(filter, page, {sort: '-storedAt'}, function(err, reports) {
    if (err) return callback(err);
    callback(null, reports);
  });
};

module.exports = Report;
<commit_msg>Made author match case insensitive<commit_after>// A report is a single post/comment/article or other chunk of data from a source.
// This class is responsible for executing ReportQuerys.

var database = require('../lib/database');
var mongoose = database.mongoose;
var textSearch = require('mongoose-text-search');
var Source = require('./source');
var Query = require('./query');
var _ = require('underscore');

var schema = new mongoose.Schema({
  authoredAt: Date,
  fetchedAt: Date,
  storedAt: Date,
  content: String,
  author: String,
  url: String,
  read: {type: Boolean, default: false, required: true},
  flagged: {type: Boolean, default: false, required: true},
  _source: {type: String, ref: 'Source'},
  _media: String,
  _sourceNickname: String,
  _incident: {type: String, ref: 'Incident'}
});

// Give the report schema text search capabilities
schema.plugin(textSearch);
// Add a text index to the `content` field
schema.index({content: 'text'});

schema.pre('save', function(next) {
  if (this.isNew) {
    this._wasNew = true;

    // Set default storedAt.
    if (!this.storedAt) this.storedAt = new Date();

  } else {
    // Capture updates before saving report
    if (this.isModified('_incident')) this._incidentWasModified = true;
  }
  next();
});

// Emit information about updates after saving report
schema.post('save', function() {
  if (this._wasNew) schema.emit('report:save', {_id: this._id.toString()});
  if (this._incidentWasModified) schema.emit('report:incident', {_id: this._id.toString(), _incident: this._incident ? this._incident.toString() : null});
});

var Report = mongoose.model('Report', schema);

// Query reports based on passed query data
Report.queryReports = function(query, page, callback) {
  if (typeof query === 'function') return Report.findPage(query);
  if (typeof page === 'function') {
    callback = page;
    page = 0;
  }
  if (page < 0) page = 0;

  query.limit = 100;
  query.filter = {};

  // Determine inclusive date filters
  if (query.after || query.before) {
    query.filter.storedAt = {};
    if (query.after) query.filter.storedAt.$gte = query.after;
    if (query.before) query.filter.storedAt.$lte = query.before;
  }

  // Convert reference fields for Report compatibility
  if (query.sourceId) query.filter._source = query.sourceId;
  if (query.sourceType) query.filter._media = query.sourceType;
  if (query.incidentId) query.filter._incident = query.incidentId;

  // Determine author filter
  if (query.author) {
    query.filter.author = {};
    query.filter.author.$in = query.author.replace(/(,|\s)+/g, ' ').split(' ').sort().map(function(author){
      // Use case-insensitive matching with anchors so mongo index is still used.
      return new RegExp('^' + author + '$', 'i');
    });
  }

  // Return only newer results
  if (query.since) {
    query.filter.storedAt = query.filter.storedAt || {};
    query.filter.storedAt.$gte = query.since;
  }

  // Re-set search timestamp
  query.since = new Date();

  if (!query.keywords) {
    // Just use filters when no keywords are provided
    Report.findSortedPage(query.filter, page, callback);
  } else {
    Report.textSearch(query.keywords, _.pick(query, ['filter', 'limit']), function(err, reports) {
      if (err) return callback(err);
      var result = {
        total: reports.stats.n ? reports.stats.nscannedObjects : 0,
        results: _.chain(reports.results).pluck('obj').sortBy('storedAt').value().reverse()
      };
      callback(null, result);
    });
  }
};

Report.findSortedPage = function(filter, page, callback) {
  Report.findPage(filter, page, {sort: '-storedAt'}, function(err, reports) {
    if (err) return callback(err);
    callback(null, reports);
  });
};

module.exports = Report;
<|endoftext|>


<commit_before>

L.UtfGrid = L.Class.extend({
	includes: L.Mixin.Events,
	options: {
		minZoom: 0,
		maxZoom: 18,
		tileSize: 256,

		resolution: 2,
		preload: true,

		useJsonP: true
	},

	//The thing the mouse is currently on
	_mouseOn: null,

	initialize: function (url, options) {
		options = L.setOptions(this, options);

		this._url = url;

		this._cache = {};

		if (options.clickCallback) {
			//TODO
		}
	},

	onAdd: function (map) {
		this._map = map;

		this._update();

		//TODO: on moveend update
		var zoom = this._map.getZoom();

		if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
			return;
		}

		map.on('click', this._click, this);
		map.on('mousemove', this._move, this);
		//TODO: Touch needs special support?
	},

	_click: function (e) {
		this.fire('click', this._objectForEvent(e));
	},
	_move: function (e) {
		var on = this._objectForEvent(e);

		if (on.data != this._mouseOn) {
			if (this._mouseOn) {
				this.fire('mouseout', { latlng: e.latlng, data: this._mouseOn });
			}
			this.fire('mouseover', on);

			this._mouseOn = on.data;
		}
	},

	_objectForEvent: function(e) {
		var x = Math.floor(e.layerPoint.x / this.options.tileSize), //FIXME: This can be -1 sometimes (or > than the size of the thing)
		    y = Math.round(e.layerPoint.y / this.options.tileSize),
		    gridX = Math.floor((e.layerPoint.x - (x * this.options.tileSize)) / this.options.resolution),
		    gridY = Math.floor((e.layerPoint.y - (y * this.options.tileSize) + (this.options.tileSize / 2)) / this.options.resolution);

		var data = this._cache[map.getZoom() + '_' + x + '_' + y];
		if (!data) {
			console.log('not cached ' + map.getZoom() + '_' + x + '_' + y);
			return { latlng: e.latlng, data: null };
		}

		var idx = this._utfDecode(data.grid[gridY][gridX]),
		    key = data.keys[idx],
		    result = data.data[key];

		if (!data.data.hasOwnProperty(key))
			result = null;

		return { latlng: e.latlng, data: result};
	},

	//Load up all required json grid files
	//TODO: Load from center etc
	_update: function () {

		//TODO: on moveend update
		var bounds = this._map.getPixelBounds(),
		    zoom = this._map.getZoom(),
		    tileSize = this.options.tileSize;

		if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
			return;
		}

		var nwTilePoint = new L.Point(
				Math.floor(bounds.min.x / tileSize),
				Math.floor(bounds.min.y / tileSize)),
			seTilePoint = new L.Point(
				Math.floor(bounds.max.x / tileSize),
				Math.floor(bounds.max.y / tileSize));

		//Load all required ones
		for (var x = nwTilePoint.x; x < seTilePoint.x; x++) {
			for (var y = nwTilePoint.y; y <= seTilePoint.y; y++) {
				if (this.options.useJsonP) {
					this._loadTileP(zoom, x, y);
				} else {
					this._loadTile(zoom, x, y);
				}
			}
		}
	},

	_loadTileP: function (zoom, x, y) {
		var head = document.getElementsByTagName('head')[0];
		var key = zoom + '_' + x + '_' + y;
		var functionName = 'lu_' + key;

		var url = L.Util.template(this._url, L.extend({
			//s: this._getSubdomain(tilePoint),
			z: zoom,
			x: x,
			y: y
		}, this.options));

		var script = document.createElement('script');
		script.setAttribute("type", "text/javascript");
		script.setAttribute("src", url + "?callback=" + functionName);

		var self = this;
		window[functionName] = function (data) {
			console.log('loaded ' + key);
			self._cache[key] = data;
			delete window[functionName];
			head.removeChild(script);
		};

		head.appendChild(script);
		//TODO: Create script tag
	},

	_loadTile: function (zoom, x, y) {
		var url = L.Util.template(this._url, L.extend({
			//s: this._getSubdomain(tilePoint),
			z: zoom,
			x: x,
			y: y
		}, this.options));

		var key = zoom + '_' + x + '_' + y;

		//FIXME: JQUERYING IN THE HJIZZLE
		//FIXME: NEED JSONP SUPPORT TOO
		$.ajax({
			url: url,
			context: this,
			type: 'GET'
		})
		.done(function (data) {
			console.log("loaded " + url);
			this._cache[key] = data;
		})
		.fail(function () {
			console.log("Failed to load " + url);
		});
	},
	_utfDecode: function (c) {
		c = c.charCodeAt(0);
		if (c >= 93)
			c--;
		if (c >= 35)
			c--;
		return c - 32;
	}
});<commit_msg>Listen to map moving around and get newly required tiles. Fix stopping working after map zooming.<commit_after>

L.UtfGrid = L.Class.extend({
	includes: L.Mixin.Events,
	options: {
		subdomains: 'abc',

		minZoom: 0,
		maxZoom: 18,
		tileSize: 256,

		resolution: 2,
		preload: true,

		useJsonP: true
	},

	//The thing the mouse is currently on
	_mouseOn: null,

	initialize: function (url, options) {
		options = L.setOptions(this, options);

		this._url = url;

		this._cache = {};

		if (options.clickCallback) {
			//TODO
		}
	},

	onAdd: function (map) {
		this._map = map;

		this._update();

		//TODO: on moveend update
		var zoom = this._map.getZoom();

		if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
			return;
		}

		map.on('click', this._click, this);
		map.on('mousemove', this._move, this);
		map.on('moveend', this._update, this);
		//TODO: Touch needs special support?
	},

	_click: function (e) {
		this.fire('click', this._objectForEvent(e));
	},
	_move: function (e) {
		var on = this._objectForEvent(e);

		if (on.data != this._mouseOn) {
			if (this._mouseOn) {
				this.fire('mouseout', { latlng: e.latlng, data: this._mouseOn });
			}
			this.fire('mouseover', on);

			this._mouseOn = on.data;
		}
	},

	_objectForEvent: function (e) {
		var point = this._map.project(e.latlng);
		point.y -= 128; //i dunno

		var x = Math.floor(point.x / this.options.tileSize), //FIXME: This can be -1 sometimes (or > than the size of the thing)
		    y = Math.round(point.y / this.options.tileSize),
		    gridX = Math.floor((point.x - (x * this.options.tileSize)) / this.options.resolution),
		    gridY = Math.floor((point.y - (y * this.options.tileSize) + (this.options.tileSize / 2)) / this.options.resolution);

		var data = this._cache[map.getZoom() + '_' + x + '_' + y];
		if (!data) {
			console.log('not cached ' + map.getZoom() + '_' + x + '_' + y);
			return { latlng: e.latlng, data: null };
		}

		var idx = this._utfDecode(data.grid[gridY][gridX]),
		    key = data.keys[idx],
		    result = data.data[key];

		if (!data.data.hasOwnProperty(key))
			result = null;

		return { latlng: e.latlng, data: result};
	},

	//Load up all required json grid files
	//TODO: Load from center etc
	_update: function () {

		//TODO: on moveend update
		var bounds = this._map.getPixelBounds(),
		    zoom = this._map.getZoom(),
		    tileSize = this.options.tileSize;

		if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
			return;
		}

		var nwTilePoint = new L.Point(
				Math.floor(bounds.min.x / tileSize),
				Math.floor(bounds.min.y / tileSize)),
			seTilePoint = new L.Point(
				Math.floor(bounds.max.x / tileSize),
				Math.floor(bounds.max.y / tileSize)),
				max = this._map.options.crs.scale(zoom) / tileSize;

		//Load all required ones
		for (var x = nwTilePoint.x; x <= seTilePoint.x; x++) {
			for (var y = nwTilePoint.y; y <= seTilePoint.y; y++) {

				var xw = (x + max) % max, yw = (y + max) % max;
				var key = zoom + '_' + xw + '_' + yw;

				if (!this._cache.hasOwnProperty(key)) {
					this._cache[key] = null;

					if (this.options.useJsonP) {
						this._loadTileP(zoom, xw, yw);
					} else {
						this._loadTile(zoom, xw, yw);
					}
				}
			}
		}
	},

	_loadTileP: function (zoom, x, y) {
		var head = document.getElementsByTagName('head')[0];
		var key = zoom + '_' + x + '_' + y;
		var functionName = 'lu_' + key;

		var url = L.Util.template(this._url, L.extend({
			s: L.TileLayer.prototype._getSubdomain.call(this, { x: x, y: y }),
			z: zoom,
			x: x,
			y: y
		}, this.options));

		var script = document.createElement('script');
		script.setAttribute("type", "text/javascript");
		script.setAttribute("src", url + "?callback=" + functionName);

		var self = this;
		window[functionName] = function (data) {
			console.log('loaded ' + key);
			self._cache[key] = data;
			delete window[functionName];
			head.removeChild(script);
		};

		head.appendChild(script);
		//TODO: Create script tag
	},

	_loadTile: function (zoom, x, y) {
		var url = L.Util.template(this._url, L.extend({
			//s: this._getSubdomain(tilePoint),
			z: zoom,
			x: x,
			y: y
		}, this.options));

		var key = zoom + '_' + x + '_' + y;

		//FIXME: JQUERYING IN THE HJIZZLE
		//FIXME: NEED JSONP SUPPORT TOO
		$.ajax({
			url: url,
			context: this,
			type: 'GET'
		})
		.done(function (data) {
			console.log("loaded " + url);
			this._cache[key] = data;
		})
		.fail(function () {
			console.log("Failed to load " + url);
		});
	},
	_utfDecode: function (c) {
		c = c.charCodeAt(0);
		if (c >= 93)
			c--;
		if (c >= 35)
			c--;
		return c - 32;
	}
});<|endoftext|>


<commit_before>var modCommon = {

  getFatigue: function(creep){
    var body = creep.body;
    var nonMoveCount = 0;
    var moveCount = 0;
    var total = 0;
    for(var limb in body){
      if(limb.type === MOVE){
        moveCount++;
        total++;
      }else{
        nonMoveCount++;
        total++;
      }
    }
    return 2*(nonMoveCount * 0.5 - moveCount);

  },

  distTo: function(creep, pos){
    var x = creep.pos.x - pos.x;
    var y = creep.pos.y - pos.y;
    var xSquared = x * x;
    var ySquared = y * y;
    var root = xSquared + ySquared;
    var dist = Math.sqrt(root);
    return dist;
  },

  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){
    var maxTicks = 50;
    //Priority 1 is dropped energy, since it detiorates
    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_ENERGY);
    if(dropped && dropped.resourceType === RESOURCE_ENERGY){
      var dist;
      var fat;
      var worth = 2;
      dist = this.distTo(creep, dropped.pos);
      fat = this.getFatigue(creep);
      worth = (dist * fat) / maxTicks;
      if(dropped && worth<=1){
        if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
          modCommon.move(creep,dropped.pos);
        }else{
          creep.memory.path = null;
        }
      }
    }else{
      //Next priority is the closest container or storage
      var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
      });
      if(storage!==null){
        var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
        if(getEnergy===ERR_NOT_IN_RANGE) {
            modCommon.move(creep, storage);
        }else{
          creep.memory.path = null;
        }
      //Finally, the creep will harvest if it can
      }else if(creep.memory.selfHarvest){
        var sources = creep.room.find(FIND_SOURCES);
        if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
          modCommon.move(creep, sources[0]);
        }else{
          creep.memory.path = null;
        }
      }
    }
  },

  //Function to remove 'dead' creeps from the memory to conserve space
  clearDead: function(){
    for(var i in Memory.creeps) {
      if(!Game.creeps[i]) {
          var job = Memory.creeps[i].role;
          this.decrementNum(job);
          delete Memory.creeps[i];
      }
    }
  },

  decrementNum:function(creepType){
    if(creepType==="harvester"){
      --Memory.roles.numHarvesters;
    }else if(creepType === "upgrader"){
      --Memory.roles.numUpgraders;
    }else if(creepType === "builder"){
      --Memory.roles.numBuilders;
    }else if(creepType === "repair"){
      --Memory.roles.numRepair;
    }else if (creepType === "architect"){
      --Memory.roles.numArchitects;
    }else if(creepType === "miner"){
      --Memory.roles.numMiners;
    }else if(creepType === "hauler"){
      --Memory.roles.numHaulers;
    }else if(creepType === "feeder"){
      --Memory.roles.numFeeders;
    }else if(creepType === "geo"){
      --Memory.roles.numGeo;
    }else if(creepType === "geoH"){
      --Memory.roles.numGeoH;
    }else if(creepType === "merchant"){
      --Memory.roles.numMerchant;
    }
    --Memory.roles.numCreeps;
  },

  //Method to find the next structure to repair, shared by repair creeps and towers
  findToFixArr: function(room){
    var controlLvl = room.controller.level;
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);
    var buffer = 1000;
    var roomBuffer = 300000;

    var fixeArrPriority = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < 3000);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
      var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }});

    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < object.hitsMax/2);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp;
    }});

    var fixeArr2 = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+buffer)) && (object.hitsMax-object.hits>0);
      return brokenWall;
    }});

    if(room.storage.store.energy < roomBuffer || fixeArrPriority.length>0){
      return fixeArrPriority;
    }else if(fixeArr.length>0){
      return fixeArr;
    }else {
      return fixeArr2;
    }
    return NULL;
  },

  findToFortify: function(room){
    // use  '|| object.structureType ===STRUCTURE_RAMPART' ?
    var fortArr = room.find(FIND_STRUCTURES, {filter: function(object){
      return (object.structureType ===STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000) && (object.hitsMax-object.hits>0);
    }});

    return fortArr;
  },

  //Function to run away and hide
  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  //Function to move useing a stored path
  move:function(creep,pos){
    var emptyPath = false;
    var creepPath = creep.memory.path;
    var destX = -1;
    var destY = -1;
    var lastObj = null;
    if(creepPath && creepPath.length>0){
      var index = creepPath.length-1;
      lastObj = creepPath[index];
      destX = lastObj.x + lastObj.dx;
      destY = lastObj.y + lastObj.dy;
    }else{
      emptyPath = true;
    }

    if(emptyPath || (lastObj && (pos.x !== destX || pos.y !== destY))){
      creep.memory.path = creep.pos.findPathTo(pos);
    }
    creep.moveByPath(creep.memory.path);
  },

  playerAttack:function(allCreepList){
    //priority Targets
    var pTargets = _.filter(allCreepList, (creep) => (creep.owner && !( creep.owner.username == "PCarton" || creep.owner.username == 'Invader')));
    return pTargets.length;
  },

  findInjured:function(allCreepList){
    var hTargets = _.filter(allCreepList, (creep) => creep.hits<creep.hitsMax && creep.owner.username === "PCarton");
    //TODO sort by a priority
    return hTargets;
  },

  whatCarry:function(creep){
    var resourceType;

    var creepCarry = creep.carry;
    if(creepCarry.energy>0){
      resourceType = RESOURCE_ENERGY;
    }else if(creepCarry.power>0){
      resourceType = RESOURCE_POWER;
    }else if(creepCarry.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(creepCarry.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(creepCarry.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(creepCarry.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(creepCarry.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(creepCarry.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(creepCarry.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(creepCarry.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  whatStore:function(struct){
    var resourceType;

    var structStore = struct.store;
    if(structStore.power>0){
      resourceType = RESOURCE_POWER;
    }else if(structStore.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(structStore.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(structStore.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(structStore.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(structStore.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(structStore.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(structStore.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(structStore.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  getResourceCount:function(storeObj, resourceType){
    var count;
    switch(resourceType){
      case RESOURCE_ENERGY:
        count = storeObj.energy;
        break;
      case RESOURCE_POWER:
        count = storeObj.power;
        break;
      case RESOURCE_HYDROGEN:
        count = storeObj.H;
        break;
      case RESOURCE_OXYGEN:
        count = storeObj.O;
        break;
      case RESOURCE_UTRIUM:
        count = storeObj.U;
        break;
      case RESOURCE_LEMERGIUM:
        count = storeObj.L;
        break;
      case RESOURCE_KEANIUM:
        count = storeObj.K;
        break;
      case RESOURCE_ZYNTHIUM:
        count = storeObj.Z;
        break;
      case RESOURCE_CATALYST:
        count = storeObj.X;
        break;
      case RESOURCE_GHODIUM:
        count = storeObj.G;
        break;
      default:
        count = 0;
    }
    return count;
  },
  //TODO Emergency upgrade logic

  //TODO link to history page for the room at given tick
  //Formated as https://screeps.com/a/#!/history/E33N43?t=15527000
  linkRoomAtTick:function(room,tick,msg){
    return ""+msg+"";
  }

};

module.exports = modCommon;
<commit_msg>tried to fix linking again<commit_after>var modCommon = {

  getFatigue: function(creep){
    var body = creep.body;
    var nonMoveCount = 0;
    var moveCount = 0;
    var total = 0;
    for(var limb in body){
      if(limb.type === MOVE){
        moveCount++;
        total++;
      }else{
        nonMoveCount++;
        total++;
      }
    }
    return 2*(nonMoveCount * 0.5 - moveCount);

  },

  distTo: function(creep, pos){
    var x = creep.pos.x - pos.x;
    var y = creep.pos.y - pos.y;
    var xSquared = x * x;
    var ySquared = y * y;
    var root = xSquared + ySquared;
    var dist = Math.sqrt(root);
    return dist;
  },

  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){
    var maxTicks = 50;
    //Priority 1 is dropped energy, since it detiorates
    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_ENERGY);
    if(dropped && dropped.resourceType === RESOURCE_ENERGY){
      var dist;
      var fat;
      var worth = 2;
      dist = this.distTo(creep, dropped.pos);
      fat = this.getFatigue(creep);
      worth = (dist * fat) / maxTicks;
      if(dropped && worth<=1){
        if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
          modCommon.move(creep,dropped.pos);
        }else{
          creep.memory.path = null;
        }
      }
    }else{
      //Next priority is the closest container or storage
      var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
      });
      if(storage!==null){
        var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
        if(getEnergy===ERR_NOT_IN_RANGE) {
            modCommon.move(creep, storage);
        }else{
          creep.memory.path = null;
        }
      //Finally, the creep will harvest if it can
      }else if(creep.memory.selfHarvest){
        var sources = creep.room.find(FIND_SOURCES);
        if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
          modCommon.move(creep, sources[0]);
        }else{
          creep.memory.path = null;
        }
      }
    }
  },

  //Function to remove 'dead' creeps from the memory to conserve space
  clearDead: function(){
    for(var i in Memory.creeps) {
      if(!Game.creeps[i]) {
          var job = Memory.creeps[i].role;
          this.decrementNum(job);
          delete Memory.creeps[i];
      }
    }
  },

  decrementNum:function(creepType){
    if(creepType==="harvester"){
      --Memory.roles.numHarvesters;
    }else if(creepType === "upgrader"){
      --Memory.roles.numUpgraders;
    }else if(creepType === "builder"){
      --Memory.roles.numBuilders;
    }else if(creepType === "repair"){
      --Memory.roles.numRepair;
    }else if (creepType === "architect"){
      --Memory.roles.numArchitects;
    }else if(creepType === "miner"){
      --Memory.roles.numMiners;
    }else if(creepType === "hauler"){
      --Memory.roles.numHaulers;
    }else if(creepType === "feeder"){
      --Memory.roles.numFeeders;
    }else if(creepType === "geo"){
      --Memory.roles.numGeo;
    }else if(creepType === "geoH"){
      --Memory.roles.numGeoH;
    }else if(creepType === "merchant"){
      --Memory.roles.numMerchant;
    }
    --Memory.roles.numCreeps;
  },

  //Method to find the next structure to repair, shared by repair creeps and towers
  findToFixArr: function(room){
    var controlLvl = room.controller.level;
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);
    var buffer = 1000;
    var roomBuffer = 300000;

    var fixeArrPriority = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < 3000);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
      var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }});

    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < object.hitsMax/2);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp;
    }});

    var fixeArr2 = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+buffer)) && (object.hitsMax-object.hits>0);
      return brokenWall;
    }});

    if(room.storage.store.energy < roomBuffer || fixeArrPriority.length>0){
      return fixeArrPriority;
    }else if(fixeArr.length>0){
      return fixeArr;
    }else {
      return fixeArr2;
    }
    return NULL;
  },

  findToFortify: function(room){
    // use  '|| object.structureType ===STRUCTURE_RAMPART' ?
    var fortArr = room.find(FIND_STRUCTURES, {filter: function(object){
      return (object.structureType ===STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000) && (object.hitsMax-object.hits>0);
    }});

    return fortArr;
  },

  //Function to run away and hide
  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  //Function to move useing a stored path
  move:function(creep,pos){
    var emptyPath = false;
    var creepPath = creep.memory.path;
    var destX = -1;
    var destY = -1;
    var lastObj = null;
    if(creepPath && creepPath.length>0){
      var index = creepPath.length-1;
      lastObj = creepPath[index];
      destX = lastObj.x + lastObj.dx;
      destY = lastObj.y + lastObj.dy;
    }else{
      emptyPath = true;
    }

    if(emptyPath || (lastObj && (pos.x !== destX || pos.y !== destY))){
      creep.memory.path = creep.pos.findPathTo(pos);
    }
    creep.moveByPath(creep.memory.path);
  },

  playerAttack:function(allCreepList){
    //priority Targets
    var pTargets = _.filter(allCreepList, (creep) => (creep.owner && !( creep.owner.username == "PCarton" || creep.owner.username == 'Invader')));
    return pTargets.length;
  },

  findInjured:function(allCreepList){
    var hTargets = _.filter(allCreepList, (creep) => creep.hits<creep.hitsMax && creep.owner.username === "PCarton");
    //TODO sort by a priority
    return hTargets;
  },

  whatCarry:function(creep){
    var resourceType;

    var creepCarry = creep.carry;
    if(creepCarry.energy>0){
      resourceType = RESOURCE_ENERGY;
    }else if(creepCarry.power>0){
      resourceType = RESOURCE_POWER;
    }else if(creepCarry.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(creepCarry.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(creepCarry.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(creepCarry.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(creepCarry.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(creepCarry.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(creepCarry.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(creepCarry.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  whatStore:function(struct){
    var resourceType;

    var structStore = struct.store;
    if(structStore.power>0){
      resourceType = RESOURCE_POWER;
    }else if(structStore.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(structStore.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(structStore.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(structStore.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(structStore.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(structStore.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(structStore.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(structStore.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  getResourceCount:function(storeObj, resourceType){
    var count;
    switch(resourceType){
      case RESOURCE_ENERGY:
        count = storeObj.energy;
        break;
      case RESOURCE_POWER:
        count = storeObj.power;
        break;
      case RESOURCE_HYDROGEN:
        count = storeObj.H;
        break;
      case RESOURCE_OXYGEN:
        count = storeObj.O;
        break;
      case RESOURCE_UTRIUM:
        count = storeObj.U;
        break;
      case RESOURCE_LEMERGIUM:
        count = storeObj.L;
        break;
      case RESOURCE_KEANIUM:
        count = storeObj.K;
        break;
      case RESOURCE_ZYNTHIUM:
        count = storeObj.Z;
        break;
      case RESOURCE_CATALYST:
        count = storeObj.X;
        break;
      case RESOURCE_GHODIUM:
        count = storeObj.G;
        break;
      default:
        count = 0;
    }
    return count;
  },
  //TODO Emergency upgrade logic

  //TODO link to history page for the room at given tick
  //Formated as https://screeps.com/a/#!/history/E33N43?t=15527000
  linkRoomAtTick:function(room,tick,msg){
    var link = "https://screeps.com/a/#!/history/"+room.name+"?t="+tick;
    console.log(link);
    return ""+msg+"";
  }

};

module.exports = modCommon;
<|endoftext|>