<commit_before>'use strict';

// Modules
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var taskOpts = require('./tasks.js');

// "Constants"
var PLUGIN_NAME = 'kalabox-plugin-drush';

module.exports = function(kbox) {

  var globalConfig = kbox.core.deps.lookup('globalConfig');
  var events = kbox.core.events;
  var engine = kbox.engine;

  kbox.whenApp(function(app) {

    // Helpers
    /**
     * Gets plugin conf from the appconfig or from CLI arg
     **/
    var getOpts = function(options) {
      // Grab our options from config
      var defaults = app.config.pluginConf[PLUGIN_NAME];
      // Override any config coming in on the CLI
      _.each(Object.keys(defaults), function(key) {
        if (_.has(options, key) && options[key]) {
          defaults[key] = options[key];
        }
      });
      return defaults;
    };

    // This only will work if you have plugin conf for kalabox-plugin-dbenv
    var getAppSettings = function() {
      var settings = {};
      var defaultSettings = {
        databases: {
          default: {
            default: {
              driver: 'mysql',
              prefix: '',
              database: 'kalabox',
              username: 'kalabox',
              password: '',
              host: app.domain,
              port: 3306
            }
          }
        },
        conf: {}
      };
      if (app.config.pluginConf[PLUGIN_NAME]) {
        if (app.config.pluginConf[PLUGIN_NAME].settings) {
          settings = app.config.pluginConf[PLUGIN_NAME].settings;
        }
      }
      settings = _.merge({}, defaultSettings, settings);
      return JSON.stringify(settings);
    };

    /**
     * Runs a git command on the app data container
     **/
    var runDrushCMD = function(cmd, opts, done) {
      // Run the git command in the correct directory in the container if the
      // user is somewhere inside the code directory on the host side.
      // @todo: consider if this is better in the actual engine.run command
      // vs here.
      var workingDirExtra = '';
      var cwd = process.cwd();
      var codeRoot = app.config.codeRoot;
      if (_.startsWith(cwd, codeRoot)) {
        workingDirExtra = cwd.replace(codeRoot, '');
      }
      var workingDir = '/data' + workingDirExtra;

      engine.run(
        'drush',
        cmd,
        {
          WorkingDir: workingDir,
          Env: [
            'DRUSH_VERSION=' + opts['drush-version'],
            'APPNAME=' +  app.name,
            'APPDOMAIN=' +  app.domain,
            'PRESSFLOW_SETTINGS=' + getAppSettings(),
            'BACKDROP_SETTINGS=' + getAppSettings()
          ],
          HostConfig: {
            VolumesFrom: [app.dataContainerName]
          }
        },
        {
          Binds: [
            app.config.homeBind + ':/ssh:rw',
            app.rootBind + ':/src:rw'
          ]
        },
        done
      );
    };

    // Events
    // Install the drush container for our things
    events.on('post-install', function(app, done) {
      // If profile is set to dev build from source
      var opts = {
        name: 'drush',
        srcRoot: path.resolve(__dirname)
      };
      engine.build(opts, done);
    });

    // Updates kalabox aliases when app is started.
    // This allows for both kbox drush to be used
    // and local drush to be used via: drush @<appname> status
    events.on('post-start-component', function(component, done) {
      // Only run on the db container
      if (component.name !== 'db') {
        done();
      }
      else {
        engine.inspect(component.containerId, function(err, data) {
          var key = '3306/tcp';
          if (data && data.NetworkSettings.Ports[key]) {
            var port = data.NetworkSettings.Ports[key][0].HostPort;
            var cmd = [
              'sed',
              '-i',
              's/\'host\'.*/\'host\' => \'' + app.domain + '\',/g',
              '/src/config/drush/aliases.drushrc.php'
            ];

            engine.once(
              'debian',
              ['/bin/bash'],
              {
                'Env': ['APPDOMAIN=' + app.domain],
              },
              {
                Binds: [app.rootBind + ':/src:rw']
              },
              function(container, done) {
                engine.queryData(container.id, cmd, function(err, data) {
                  if (err) {
                    done(err);
                  } else {
                    done();
                  }
                });
              },
              function(err) {
                done(err);
              }
            );
          }
        });
      }
    });

    // Tasks
    // drush wrapper: kbox drush COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'drush'];
      task.description = 'Run drush commands.';
      task.kind = 'delegate';
      task.options.push(taskOpts.drushVersion);
      task.func = function(done) {
        var opts = getOpts(this.options);
        var cmd = this.payload;
        cmd.unshift('@dev');
        runDrushCMD(cmd, opts, done);
      };
    });

  });

};
<commit_msg>this is better for inquirer<commit_after>'use strict';

// Modules
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var taskOpts = require('./tasks.js');

// "Constants"
var PLUGIN_NAME = 'kalabox-plugin-drush';

module.exports = function(kbox) {

  var globalConfig = kbox.core.deps.lookup('globalConfig');
  var events = kbox.core.events;
  var engine = kbox.engine;

  kbox.whenApp(function(app) {

    // Helpers
    /**
     * Gets plugin conf from the appconfig or from CLI arg
     **/
    var getOpts = function(options) {
      // Grab our options from config
      var defaults = app.config.pluginConf[PLUGIN_NAME];
      // Override any config coming in on the CLI
      _.each(Object.keys(defaults), function(key) {
        if (_.has(options, key) && options[key]) {
          defaults[key] = options[key];
        }
      });
      return defaults;
    };

    // This only will work if you have plugin conf for kalabox-plugin-dbenv
    var getAppSettings = function() {
      var settings = {};
      var defaultSettings = {
        databases: {
          default: {
            default: {
              driver: 'mysql',
              prefix: '',
              database: 'kalabox',
              username: 'kalabox',
              password: '',
              host: app.domain,
              port: 3306
            }
          }
        },
        conf: {}
      };
      if (app.config.pluginConf[PLUGIN_NAME]) {
        if (app.config.pluginConf[PLUGIN_NAME].settings) {
          settings = app.config.pluginConf[PLUGIN_NAME].settings;
        }
      }
      settings = _.merge({}, defaultSettings, settings);
      return JSON.stringify(settings);
    };

    /**
     * Runs a git command on the app data container
     **/
    var runDrushCMD = function(cmd, opts, done) {
      // Run the git command in the correct directory in the container if the
      // user is somewhere inside the code directory on the host side.
      // @todo: consider if this is better in the actual engine.run command
      // vs here.
      var workingDirExtra = '';
      var cwd = process.cwd();
      var codeRoot = app.config.codeRoot;
      if (_.startsWith(cwd, codeRoot)) {
        workingDirExtra = cwd.replace(codeRoot, '');
      }
      var workingDir = '/data' + workingDirExtra;

      engine.run(
        'drush',
        cmd,
        {
          WorkingDir: workingDir,
          Env: [
            'DRUSH_VERSION=drush' + opts['drush-version'],
            'APPNAME=' +  app.name,
            'APPDOMAIN=' +  app.domain,
            'PRESSFLOW_SETTINGS=' + getAppSettings(),
            'BACKDROP_SETTINGS=' + getAppSettings()
          ],
          HostConfig: {
            VolumesFrom: [app.dataContainerName]
          }
        },
        {
          Binds: [
            app.config.homeBind + ':/ssh:rw',
            app.rootBind + ':/src:rw'
          ]
        },
        done
      );
    };

    // Events
    // Install the drush container for our things
    events.on('post-install', function(app, done) {
      // If profile is set to dev build from source
      var opts = {
        name: 'drush',
        srcRoot: path.resolve(__dirname)
      };
      engine.build(opts, done);
    });

    // Updates kalabox aliases when app is started.
    // This allows for both kbox drush to be used
    // and local drush to be used via: drush @<appname> status
    events.on('post-start-component', function(component, done) {
      // Only run on the db container
      if (component.name !== 'db') {
        done();
      }
      else {
        engine.inspect(component.containerId, function(err, data) {
          var key = '3306/tcp';
          if (data && data.NetworkSettings.Ports[key]) {
            var port = data.NetworkSettings.Ports[key][0].HostPort;
            var cmd = [
              'sed',
              '-i',
              's/\'host\'.*/\'host\' => \'' + app.domain + '\',/g',
              '/src/config/drush/aliases.drushrc.php'
            ];

            engine.once(
              'debian',
              ['/bin/bash'],
              {
                'Env': ['APPDOMAIN=' + app.domain],
              },
              {
                Binds: [app.rootBind + ':/src:rw']
              },
              function(container, done) {
                engine.queryData(container.id, cmd, function(err, data) {
                  if (err) {
                    done(err);
                  } else {
                    done();
                  }
                });
              },
              function(err) {
                done(err);
              }
            );
          }
        });
      }
    });

    // Tasks
    // drush wrapper: kbox drush COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'drush'];
      task.description = 'Run drush commands.';
      task.kind = 'delegate';
      task.options.push(taskOpts.drushVersion);
      task.func = function(done) {
        var opts = getOpts(this.options);
        var cmd = this.payload;
        cmd.unshift('@dev');
        runDrushCMD(cmd, opts, done);
      };
    });

  });

};
<|endoftext|>


<commit_before>/*  __
___( o)>
\ <_. )
 `---'
*/
import Alert from 'react-s-alert'
import { SubmissionError } from 'redux-form'

import { history, MAP, MY_ENTRIES } from '../../AppRouter'
import { requestAllPlaces } from '../Map/duck'
import { client } from '../../index'
import { transformErrorResponse } from '../../common/formUtils'

export const INIT_CREATE_PLACE = 'INIT_CREATE_PLACE'
export const INIT_EDIT_PLACE_SUCCESS = 'INIT_EDIT_PLACE_SUCCESS'
export const FETCH_PRODUCTS_SUCCESS = 'FETCH_PRODUCTS_SUCCESS'
export const FETCH_GOALS_SUCCESS = 'FETCH_GOALS_SUCCESS'
export const FETCH_BADGES_SUCCESS = 'FETCH_BADGES_SUCCESS'
export const CLEAR_EDITOR = 'CLEAR_EDITOR'

const initialState = {
  feature: null,
  products: [],
  goals: [],
}

export const editor = (state = initialState, action) => {
  switch (action.type) {
    case INIT_CREATE_PLACE:
    case INIT_EDIT_PLACE_SUCCESS:
      return Object.assign({}, state, {
        feature: action.payload,
      })
    case FETCH_PRODUCTS_SUCCESS:
      return Object.assign({}, state, {
        products: action.payload,
      })
    case FETCH_GOALS_SUCCESS:
      return Object.assign({}, state, {
        goals: action.payload,
      })
    case FETCH_BADGES_SUCCESS:
      return Object.assign({}, state, {
        badges: action.payload,
      })
    case CLEAR_EDITOR:
      return initialState
    default:
      return state
  }
}

export const mapDepotToApiParams = (payload) => ({
  ...payload,
  farms: payload.farms ? payload.farms.map((p) => p.id) : [],
})

export const clearEditor = () => ({
  type: CLEAR_EDITOR,
})

export const closeEditorAndGoto = (nextScreenUrl) => (dispatch) => {
  dispatch(clearEditor())
  dispatch(requestAllPlaces(true))
  history.push(nextScreenUrl)
}

export const savePlaceError =
  ({ status, message }) =>
  () => {
    if (status === 401) {
      Alert.error(
        'Dein Eintrag konnte nicht gespeichert werden. Bitte überprüfe, ob du angemeldet bist.'
      )
    } else if (status === 422) {
      Alert.error('Bitte überprüfe deine Eingaben.')
    } else {
      Alert.error(`Dein Eintrag konnte nicht gespeichert werden / ${message}`)
    }
  }

export const createPlaceSuccess =
  ({ properties: { name } }) =>
  (dispatch) => {
    Alert.success(
      `Dein Eintrag <strong>${name}</strong> wurde erfolgreich gespeichert.`
    )
    dispatch(closeEditorAndGoto(MAP))
  }

export const updatePlaceSuccess = () => (dispatch) => {
  Alert.success('Dein Eintrag wurde erfolgreich aktualisiert.')
  dispatch(closeEditorAndGoto(MAP))
}

export const initCreatePlace = () => ({
  type: INIT_CREATE_PLACE,
  payload: {},
})

export const initCreateFeature = () => (dispatch) => {
  dispatch(clearEditor())
  dispatch(initCreatePlace())
}

export const createDepot = (depot) => (dispatch) =>
  client
    .service('depots')
    .create(mapDepotToApiParams(depot))
    .then((response) => dispatch(createPlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const createFarm = (farm) => (dispatch) =>
  client
    .service('farms')
    .create(farm)
    .then((response) => dispatch(createPlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const createInitiative = (initiative) => (dispatch) =>
  client
    .service('initiatives')
    .create(initiative)
    .then((response) => dispatch(createPlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const initEditFeatureError = (payload) => () => {
  Alert.error(`Der Eintrag konnte nicht geladen werden / ${payload.message}`)
}

export const initEditFeatureSuccess = (place) => ({
  type: INIT_EDIT_PLACE_SUCCESS,
  payload: place,
})

export const initEditFeature = (id, type) => async (dispatch) => {
  const ownershipCheck = await client
    .service('entries')
    .find({ query: { mine: true, type, id } })
  if (ownershipCheck.features.length !== 1) {
    window.location.assign(MAP)
    dispatch(initEditFeatureError({ message: 'Unauthorized' }))
  }
  dispatch(clearEditor())
  client
    .service(`${type}s`)
    .get(id)
    .then((response) => dispatch(initEditFeatureSuccess(response)))
    .catch((response) => {
      dispatch(initEditFeatureError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })
}

export const updateDepot = (depot) => (dispatch) =>
  client
    .service('depots')
    .patch(depot.id, mapDepotToApiParams(depot))
    .then((response) => dispatch(updatePlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const updateFarm = (farm) => (dispatch) =>
  client
    .service('farms')
    .patch(farm.id, farm)
    .then((response) => dispatch(updatePlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const updateInitiative = (initiative) => (dispatch) =>
  client
    .service('initiatives')
    .patch(initiative.id, initiative)
    .then((response) => dispatch(updatePlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const initDeleteFeature =
  ({ id, service }) =>
  (dispatch) => {
    dispatch(clearEditor())
    client
      .service(service)
      .get(id)
      .then((response) => dispatch(initEditFeatureSuccess(response)))
      .catch((response) => {
        dispatch(initEditFeatureError(response))
      })
  }

export const deleteFeatureError =
  ({ message }) =>
  () => {
    Alert.error(`Dein Eintrag konnte nicht gelöscht werden / ${message}`)
  }

export const deleteFeatureSuccess = () => (dispatch) => {
  Alert.success('Dein Eintrag wurde erfolgreich gelöscht.')
  dispatch(closeEditorAndGoto(MY_ENTRIES))
}

export const deleteFeature =
  ({ properties: { id, type } }) =>
  (dispatch) => {
    client
      .service(`${type}s`)
      .remove(id)
      .then((response) => dispatch(deleteFeatureSuccess(response)))
      .catch((response) => {
        dispatch(deleteFeatureError(response))
      })
  }

export const fetchProductsError = (payload) => () => {
  Alert.error(`Die Produkte konnten nicht geladen werden./ ${payload.message}`)
}
export const fetchProductsSuccess = (payload) => ({
  type: FETCH_PRODUCTS_SUCCESS,
  payload,
})

export const fetchProducts = () => (dispatch) => {
  client
    .service('products')
    .find()
    .then((response) => dispatch(fetchProductsSuccess(response)))
    .catch((response) => {
      dispatch(fetchProductsError(response))
    })
}

export const fetchGoalsError = (payload) => () => {
  Alert.error(`Die Ziele konnten nicht geladen werden./ ${payload.message}`)
}
export const fetchGoalsSuccess = (payload) => ({
  type: FETCH_GOALS_SUCCESS,
  payload,
})

export const fetchGoals = () => (dispatch) => {
  client
    .service('goals')
    .find()
    .then((response) => dispatch(fetchGoalsSuccess(response)))
    .catch((response) => {
      dispatch(fetchGoalsError(response))
    })
}

export const fetchBadgesError = (payload) => () => {
  Alert.error(
    `Die Mitgliedschaften und Zertifizierungen konnten nicht geladen werden./ ${payload.message}`
  )
}
export const fetchBadgesSuccess = (payload) => ({
  type: FETCH_BADGES_SUCCESS,
  payload,
})

export const fetchBadges = () => (dispatch) => {
  client
    .service('badges')
    .find()
    .then((response) => dispatch(fetchBadgesSuccess(response)))
    .catch((response) => {
      dispatch(fetchBadgesError(response))
    })
}
<commit_msg>Remove clear editor, standing data does not need to be cleared from state.<commit_after>/*  __
___( o)>
\ <_. )
 `---'
*/
import Alert from 'react-s-alert'
import { SubmissionError } from 'redux-form'

import { history, MAP, MY_ENTRIES } from '../../AppRouter'
import { requestAllPlaces } from '../Map/duck'
import { client } from '../../index'
import { transformErrorResponse } from '../../common/formUtils'

export const INIT_CREATE_PLACE = 'INIT_CREATE_PLACE'
export const INIT_EDIT_PLACE_SUCCESS = 'INIT_EDIT_PLACE_SUCCESS'
export const FETCH_PRODUCTS_SUCCESS = 'FETCH_PRODUCTS_SUCCESS'
export const FETCH_GOALS_SUCCESS = 'FETCH_GOALS_SUCCESS'
export const FETCH_BADGES_SUCCESS = 'FETCH_BADGES_SUCCESS'
export const CLEAR_EDITOR = 'CLEAR_EDITOR'

const initialState = {
  feature: null,
  products: [],
  goals: [],
}

export const editor = (state = initialState, action) => {
  switch (action.type) {
    case INIT_CREATE_PLACE:
    case INIT_EDIT_PLACE_SUCCESS:
      return Object.assign({}, state, {
        feature: action.payload,
      })
    case FETCH_PRODUCTS_SUCCESS:
      return Object.assign({}, state, {
        products: action.payload,
      })
    case FETCH_GOALS_SUCCESS:
      return Object.assign({}, state, {
        goals: action.payload,
      })
    case FETCH_BADGES_SUCCESS:
      return Object.assign({}, state, {
        badges: action.payload,
      })
    default:
      return state
  }
}

export const mapDepotToApiParams = (payload) => ({
  ...payload,
  farms: payload.farms ? payload.farms.map((p) => p.id) : [],
})

export const closeEditorAndGoto = (nextScreenUrl) => (dispatch) => {
  dispatch(requestAllPlaces(true))
  history.push(nextScreenUrl)
}

export const savePlaceError =
  ({ status, message }) =>
  () => {
    if (status === 401) {
      Alert.error(
        'Dein Eintrag konnte nicht gespeichert werden. Bitte überprüfe, ob du angemeldet bist.'
      )
    } else if (status === 422) {
      Alert.error('Bitte überprüfe deine Eingaben.')
    } else {
      Alert.error(`Dein Eintrag konnte nicht gespeichert werden / ${message}`)
    }
  }

export const createPlaceSuccess =
  ({ properties: { name } }) =>
  (dispatch) => {
    Alert.success(
      `Dein Eintrag <strong>${name}</strong> wurde erfolgreich gespeichert.`
    )
    dispatch(closeEditorAndGoto(MAP))
  }

export const updatePlaceSuccess = () => (dispatch) => {
  Alert.success('Dein Eintrag wurde erfolgreich aktualisiert.')
  dispatch(closeEditorAndGoto(MAP))
}

export const initCreatePlace = () => ({
  type: INIT_CREATE_PLACE,
  payload: {},
})

export const initCreateFeature = () => (dispatch) => {
  dispatch(initCreatePlace())
}

export const createDepot = (depot) => (dispatch) =>
  client
    .service('depots')
    .create(mapDepotToApiParams(depot))
    .then((response) => dispatch(createPlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const createFarm = (farm) => (dispatch) =>
  client
    .service('farms')
    .create(farm)
    .then((response) => dispatch(createPlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const createInitiative = (initiative) => (dispatch) =>
  client
    .service('initiatives')
    .create(initiative)
    .then((response) => dispatch(createPlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const initEditFeatureError = (payload) => () => {
  Alert.error(`Der Eintrag konnte nicht geladen werden / ${payload.message}`)
}

export const initEditFeatureSuccess = (place) => ({
  type: INIT_EDIT_PLACE_SUCCESS,
  payload: place,
})

export const initEditFeature = (id, type) => async (dispatch) => {
  const ownershipCheck = await client
    .service('entries')
    .find({ query: { mine: true, type, id } })
  if (ownershipCheck.features.length !== 1) {
    window.location.assign(MAP)
    dispatch(initEditFeatureError({ message: 'Unauthorized' }))
  }
  client
    .service(`${type}s`)
    .get(id)
    .then((response) => dispatch(initEditFeatureSuccess(response)))
    .catch((response) => {
      dispatch(initEditFeatureError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })
}

export const updateDepot = (depot) => (dispatch) =>
  client
    .service('depots')
    .patch(depot.id, mapDepotToApiParams(depot))
    .then((response) => dispatch(updatePlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const updateFarm = (farm) => (dispatch) =>
  client
    .service('farms')
    .patch(farm.id, farm)
    .then((response) => dispatch(updatePlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const updateInitiative = (initiative) => (dispatch) =>
  client
    .service('initiatives')
    .patch(initiative.id, initiative)
    .then((response) => dispatch(updatePlaceSuccess(response)))
    .catch((response) => {
      dispatch(savePlaceError(response))
      throw new SubmissionError(transformErrorResponse(response))
    })

export const initDeleteFeature =
  ({ id, service }) =>
  (dispatch) => {
    client
      .service(service)
      .get(id)
      .then((response) => dispatch(initEditFeatureSuccess(response)))
      .catch((response) => {
        dispatch(initEditFeatureError(response))
      })
  }

export const deleteFeatureError =
  ({ message }) =>
  () => {
    Alert.error(`Dein Eintrag konnte nicht gelöscht werden / ${message}`)
  }

export const deleteFeatureSuccess = () => (dispatch) => {
  Alert.success('Dein Eintrag wurde erfolgreich gelöscht.')
  dispatch(closeEditorAndGoto(MY_ENTRIES))
}

export const deleteFeature =
  ({ properties: { id, type } }) =>
  (dispatch) => {
    client
      .service(`${type}s`)
      .remove(id)
      .then((response) => dispatch(deleteFeatureSuccess(response)))
      .catch((response) => {
        dispatch(deleteFeatureError(response))
      })
  }

export const fetchProductsError = (payload) => () => {
  Alert.error(`Die Produkte konnten nicht geladen werden./ ${payload.message}`)
}
export const fetchProductsSuccess = (payload) => ({
  type: FETCH_PRODUCTS_SUCCESS,
  payload,
})

export const fetchProducts = () => (dispatch) => {
  client
    .service('products')
    .find()
    .then((response) => dispatch(fetchProductsSuccess(response)))
    .catch((response) => {
      dispatch(fetchProductsError(response))
    })
}

export const fetchGoalsError = (payload) => () => {
  Alert.error(`Die Ziele konnten nicht geladen werden./ ${payload.message}`)
}
export const fetchGoalsSuccess = (payload) => ({
  type: FETCH_GOALS_SUCCESS,
  payload,
})

export const fetchGoals = () => (dispatch) => {
  client
    .service('goals')
    .find()
    .then((response) => dispatch(fetchGoalsSuccess(response)))
    .catch((response) => {
      dispatch(fetchGoalsError(response))
    })
}

export const fetchBadgesError = (payload) => () => {
  Alert.error(
    `Die Mitgliedschaften und Zertifizierungen konnten nicht geladen werden./ ${payload.message}`
  )
}
export const fetchBadgesSuccess = (payload) => ({
  type: FETCH_BADGES_SUCCESS,
  payload,
})

export const fetchBadges = () => (dispatch) => {
  client
    .service('badges')
    .find()
    .then((response) => dispatch(fetchBadgesSuccess(response)))
    .catch((response) => {
      dispatch(fetchBadgesError(response))
    })
}
<|endoftext|>


<commit_before>"use strict";

var request = require('request');
var Q = require('q');
var moment = require('moment-timezone');
var co = require('co');

module.exports = class CMP {

  constructor( options = {} ) {
    this.user = options.user;
    this.pass = options.pass;
    this.host = options.host;
    this.port = options.port;

    if (options.rejectUnauthorized === undefined) {
      this.rejectUnauthorized = true;
    } else this.rejectUnauthorized = Boolean(options.rejectUnauthorized);

  }

  auth() {
    return "Basic " + Buffer(this.user + ":" + this.pass).toString("base64");
  }

  url( resource = '', params = {} ) {

    var url = this.host;
    if (this.port) url += ':' + this.port;

    switch (resource) {
      case 'departments':
        url += '/userAction.php?action=GetDepartments';
      break;
      case 'catalog':
        url += '/userAction.php?action=GetPreApprovedChanges&status_ids=2';
      break;
      case 'environments':
        url += '/userAction.php?action=GetEnvironments';
      break;
      case 'types':
        url += '/userAction.php?action=GetRequestTypes';
      break;
      case 'statuses':
        url += '/userAction.php?action=GetRequestStatuses';
      break;
      case 'users':
        url += '/userAction.php?action=GetUsers';
      break;
      case 'user':
        url += '/userAction.php?action=GetUser';
      break;
      case 'hosts':
        url += '/userAction.php?action=GetHosts&type=paginated&rows=999';
      break;
      case 'requests':
        url += '/requests.json';
      break;

      default:
        url += resource;
        break;
    }

    return url;

  }

  normalizer( resource = '' ) {

    try {
      return require('./normalizers/' + resource + 'Normalizer');
    }
    catch(err) {
      return false;
    }

  }

  get( resource = '', params = {} ) {

    var promise, normalizer = this.normalizer(resource);

    promise = new Promise( (resolve, reject) => {

      var options = {
        url: this.url(resource),
        method: 'get',
        json: true,
        qs: params,
        rejectUnauthorized: this.rejectUnauthorized,
        headers: {
          "Authorization" : this.auth()
        }
      };

      request(options, function(error, response, body) {

        if(error) reject(error);
        if(body && body.error) reject(body);

        // exceptions
        if (resource === 'hosts' && body) body = body.rows;

        // normalize
        if (normalizer) {
          if ( Array.isArray(body) ) body = body.map( (el) => { return normalizer(el) });
          else if ( typeof body === 'object' ) body = normalizer(body);
        }

        resolve(body);

      });

    } );

    return promise;

  }

  post( resource = '', params = {} ) {

    var promise, normalizer = this.normalizer(resource);

    promise = new Promise( (resolve, reject) => {

      var options = {
        url: this.url(resource),
        method: 'post',
        json: true,
        formData: params,
        rejectUnauthorized: false,
        headers: {
          "Authorization" : this.auth()
        }
      };

      request(options, function(error, response, body) {
        if(error) reject(error);
        if(body && body.error) reject(body);
        resolve(body);

      });

    } );

    return promise;

  }

  put( resource = '', params = {} ) {

    var promise, normalizer = this.normalizer(resource);

    promise = new Promise( (resolve, reject) => {

      var options = {
        url: this.url(resource),
        method: 'put',
        json: true,
        form: params,
        rejectUnauthorized: false,
        headers: {
          "Authorization" : this.auth()
        }
      };

      request(options, function(error, response, body) {
        if(error) reject(error);

        if(body && body.error) reject(body);

        resolve(body);

      });

    } );

    return promise;

  }

  generateCMR( data ) {

    var deferred = Q.defer(); // Q is used because it has progress callback
    var self = this;

    if (!data['environment_id']) deferred.reject('missing environment_id');
    if (!data['requesttype_id']) deferred.reject('missing requesttype_id');
    if (!data['department_id']) deferred.reject('missing department_id');
    if (!data['preapprovedchange_id']) deferred.reject('missing preapprovedchange_id');
    var cmr_id;

    co(function* () {

      yield [];

      var hostgroups = data.hostgroups;
      data.hostgroups = 0; // number of CMR hostgroups to be created by default

      // convert usernames to user IDs
      var usersSet = new Set( data['internal-resources-users-id'].split(',') );
      var usersMap = {};
      usersSet.add( data['owner-id'] );
      usersSet.add( data['sponsor-id'] );
      usersSet.add( data['executor-id'] );
      for (var user of usersSet.values() ) {
        if (!user) continue;
        if (parseInt(user)) continue;
        user = user.trim();
        deferred.notify('Searching CMP user id for: ' + user);
        var foo = yield self.get('users', {q: user})
        if (!foo[0]) continue;
        if (!foo[0].id) continue;
        deferred.notify('Searching CMP user id SUCCESS: ' + foo[0].id);
        usersMap[ user ] = foo[0].id;
      }

      if ( data['owner-id'] && !parseInt( data['owner-id'] ) ) data['owner-id'] = usersMap[ data['owner-id'] ];
      if ( data['executor-id'] && !parseInt( data['executor-id'] ) ) data['executor-id'] = usersMap[ data['executor-id'] ];
      if ( data['sponsor-id'] && !parseInt( data['sponsor-id'] ) ) data['sponsor-id'] = usersMap[ data['sponsor-id'] ];

      if ( data['internal-resources-users-id'] ) {
        data['internal-resources-users-id'] = data['internal-resources-users-id'].split(',')
        .map( el => {
          if (parseInt(el)) return parseInt(el);
          if (typeof el === 'string' && usersMap[el.trim()]) return usersMap[el.trim()];
          return '';
        } ).join(',');
      }

      // create CMR
      deferred.notify('Creating CMR: ' + data['summary']);
      cmr_id = yield self.post('requests', data);
      cmr_id = cmr_id.requestID[0];
      deferred.notify('SUCCESS: ' + cmr_id);

      // create hostgroups
      var units_cache = {}; // { unit_name: unit_state } - cache of updated units
      for ( var hostgroup of hostgroups ) {

        deferred.notify('Creating hostgroup: ' + hostgroup['target-value']);
        var hostgroup_id = yield self.post('/requests/' + cmr_id + '/hostgroups', hostgroup);
        hostgroup_id = hostgroup_id.hostgroupID[0];
        deferred.notify('Creating hostgroup: ' + hostgroup['target-value'] + ' SUCCESS');

        if (hostgroup['target-value']) {
          deferred.notify('Getting hosts');
          var hosts = yield self.get('hosts', {
            filters: '{"groupOp":"AND","rules":[{"field":"hostname","op":"bw","data":"' + hostgroup['target-value'] + '"}]}'
          });

          hosts = hosts.map( (el) => { return el.id} ).join(',');
          deferred.notify('Getting hosts SUCCESS: ' + hosts);

          deferred.notify('Applying hosts to hostgroup');
          var units = yield self.put('/requests/' + cmr_id + '/hostgroups/' + hostgroup_id, { 'affected-hosts': hosts });
          units = units.hostSummary.units;
          deferred.notify('Applying hosts to hostgroup SUCCESS. Units are: ' + Object.keys(units) );

        }

        if (hostgroup['unit-state-id'] && units) {

          for (var unit in units){

            if ( !units_cache[unit] || units_cache[unit] != hostgroup['unit-state-id'] ) {
              deferred.notify('Updating unit state: ' + unit + ' -> ' + hostgroup['unit-state-id']);
              var updateUnits = yield self.put('/requests/' + cmr_id + '/unit/' + units[unit].id + '.json', {
                'unit-state-id': hostgroup['unit-state-id']
              });
              deferred.notify('Updating unit state : ' + unit + ' -> ' + hostgroup['unit-state-id'] + 'SUCCESS');
              units_cache[unit] = hostgroup['unit-state-id'];
            }

          }

        }

      }

    })
    .then( () => {deferred.resolve(cmr_id)})
    .catch( (err) => {deferred.reject(err)})

    return deferred.promise;

  }

}<commit_msg>fixed generateCMR target-value field<commit_after>"use strict";

var request = require('request');
var Q = require('q');
var moment = require('moment-timezone');
var co = require('co');

module.exports = class CMP {

  constructor( options = {} ) {
    this.user = options.user;
    this.pass = options.pass;
    this.host = options.host;
    this.port = options.port;

    if (options.rejectUnauthorized === undefined) {
      this.rejectUnauthorized = true;
    } else this.rejectUnauthorized = Boolean(options.rejectUnauthorized);

  }

  auth() {
    return "Basic " + Buffer(this.user + ":" + this.pass).toString("base64");
  }

  url( resource = '', params = {} ) {

    var url = this.host;
    if (this.port) url += ':' + this.port;

    switch (resource) {
      case 'departments':
        url += '/userAction.php?action=GetDepartments';
      break;
      case 'catalog':
        url += '/userAction.php?action=GetPreApprovedChanges&status_ids=2';
      break;
      case 'environments':
        url += '/userAction.php?action=GetEnvironments';
      break;
      case 'types':
        url += '/userAction.php?action=GetRequestTypes';
      break;
      case 'statuses':
        url += '/userAction.php?action=GetRequestStatuses';
      break;
      case 'users':
        url += '/userAction.php?action=GetUsers';
      break;
      case 'user':
        url += '/userAction.php?action=GetUser';
      break;
      case 'hosts':
        url += '/userAction.php?action=GetHosts&type=paginated&rows=999';
      break;
      case 'requests':
        url += '/requests.json';
      break;

      default:
        url += resource;
        break;
    }

    return url;

  }

  normalizer( resource = '' ) {

    try {
      return require('./normalizers/' + resource + 'Normalizer');
    }
    catch(err) {
      return false;
    }

  }

  get( resource = '', params = {} ) {

    var promise, normalizer = this.normalizer(resource);

    promise = new Promise( (resolve, reject) => {

      var options = {
        url: this.url(resource),
        method: 'get',
        json: true,
        qs: params,
        rejectUnauthorized: this.rejectUnauthorized,
        headers: {
          "Authorization" : this.auth()
        }
      };

      request(options, function(error, response, body) {

        if(error) reject(error);
        if(body && body.error) reject(body);

        // exceptions
        if (resource === 'hosts' && body) body = body.rows;

        // normalize
        if (normalizer) {
          if ( Array.isArray(body) ) body = body.map( (el) => { return normalizer(el) });
          else if ( typeof body === 'object' ) body = normalizer(body);
        }

        resolve(body);

      });

    } );

    return promise;

  }

  post( resource = '', params = {} ) {

    var promise, normalizer = this.normalizer(resource);

    promise = new Promise( (resolve, reject) => {

      var options = {
        url: this.url(resource),
        method: 'post',
        json: true,
        formData: params,
        rejectUnauthorized: false,
        headers: {
          "Authorization" : this.auth()
        }
      };

      request(options, function(error, response, body) {
        if(error) reject(error);
        if(body && body.error) reject(body);
        resolve(body);

      });

    } );

    return promise;

  }

  put( resource = '', params = {} ) {

    var promise, normalizer = this.normalizer(resource);

    promise = new Promise( (resolve, reject) => {

      var options = {
        url: this.url(resource),
        method: 'put',
        json: true,
        form: params,
        rejectUnauthorized: false,
        headers: {
          "Authorization" : this.auth()
        }
      };

      request(options, function(error, response, body) {
        if(error) reject(error);

        if(body && body.error) reject(body);

        resolve(body);

      });

    } );

    return promise;

  }

  generateCMR( data ) {

    var deferred = Q.defer(); // Q is used because it has progress callback
    var self = this;

    if (!data['environment_id']) deferred.reject('missing environment_id');
    if (!data['requesttype_id']) deferred.reject('missing requesttype_id');
    if (!data['department_id']) deferred.reject('missing department_id');
    if (!data['preapprovedchange_id']) deferred.reject('missing preapprovedchange_id');
    var cmr_id;

    co(function* () {

      yield [];

      var hostgroups = data.hostgroups;
      data.hostgroups = 0; // number of CMR hostgroups to be created by default

      // convert usernames to user IDs
      var usersSet = new Set( data['internal-resources-users-id'].split(',') );
      var usersMap = {};
      usersSet.add( data['owner-id'] );
      usersSet.add( data['sponsor-id'] );
      usersSet.add( data['executor-id'] );
      for (var user of usersSet.values() ) {
        if (!user) continue;
        if (parseInt(user)) continue;
        user = user.trim();
        deferred.notify('Searching CMP user id for: ' + user);
        var foo = yield self.get('users', {q: user})
        if (!foo[0]) continue;
        if (!foo[0].id) continue;
        deferred.notify('Searching CMP user id SUCCESS: ' + foo[0].id);
        usersMap[ user ] = foo[0].id;
      }

      if ( data['owner-id'] && !parseInt( data['owner-id'] ) ) data['owner-id'] = usersMap[ data['owner-id'] ];
      if ( data['executor-id'] && !parseInt( data['executor-id'] ) ) data['executor-id'] = usersMap[ data['executor-id'] ];
      if ( data['sponsor-id'] && !parseInt( data['sponsor-id'] ) ) data['sponsor-id'] = usersMap[ data['sponsor-id'] ];

      if ( data['internal-resources-users-id'] ) {
        data['internal-resources-users-id'] = data['internal-resources-users-id'].split(',')
        .map( el => {
          if (parseInt(el)) return parseInt(el);
          if (typeof el === 'string' && usersMap[el.trim()]) return usersMap[el.trim()];
          return '';
        } ).join(',');
      }

      // create CMR
      deferred.notify('Creating CMR: ' + data['summary']);
      cmr_id = yield self.post('requests', data);
      if (!cmr_id.requestID) deferred.reject('something went wrong');
      cmr_id = cmr_id.requestID[0];
      deferred.notify('SUCCESS: ' + cmr_id);

      // create hostgroups
      var units_cache = {}; // { unit_name: unit_state } - cache of updated units
      for ( var hostgroup of hostgroups ) {

        deferred.notify('Creating hostgroup: ' + hostgroup['target-value']);
        var hostgroup_id = yield self.post('/requests/' + cmr_id + '/hostgroups', hostgroup);
        hostgroup_id = hostgroup_id.hostgroupID[0];
        deferred.notify('Creating hostgroup: ' + hostgroup['target-value'] + ' SUCCESS');

        deferred.notify('Updating hostgroup target-value');
        yield self.put(`/requests/${cmr_id}/hostgroups/${hostgroup_id}`, {"target-value": hostgroup['target-value']});
        deferred.notify('Updating hostgroup target-value SUCCESS');

        if (hostgroup['target-value']) {
          deferred.notify('Getting hosts');
          var hosts = yield self.get('hosts', {
            filters: '{"groupOp":"AND","rules":[{"field":"hostname","op":"bw","data":"' + hostgroup['target-value'] + '"}]}'
          });

          hosts = hosts.map( (el) => { return el.id} ).join(',');
          deferred.notify('Getting hosts SUCCESS: ' + hosts);

          deferred.notify('Applying hosts to hostgroup');
          var units = yield self.put('/requests/' + cmr_id + '/hostgroups/' + hostgroup_id, { 'affected-hosts': hosts });
          units = units.hostSummary.units;
          deferred.notify('Applying hosts to hostgroup SUCCESS. Units are: ' + Object.keys(units) );

        }

        if (hostgroup['unit-state-id'] && units) {

          for (var unit in units){

            if ( !units_cache[unit] || units_cache[unit] != hostgroup['unit-state-id'] ) {
              deferred.notify('Updating unit state: ' + unit + ' -> ' + hostgroup['unit-state-id']);
              var updateUnits = yield self.put('/requests/' + cmr_id + '/unit/' + units[unit].id + '.json', {
                'unit-state-id': hostgroup['unit-state-id']
              });
              deferred.notify('Updating unit state : ' + unit + ' -> ' + hostgroup['unit-state-id'] + 'SUCCESS');
              units_cache[unit] = hostgroup['unit-state-id'];
            }

          }

        }

      }

    })
    .then( () => {deferred.resolve(cmr_id)})
    .catch( (err) => {deferred.reject(err)})

    return deferred.promise;

  }

}<|endoftext|>


<commit_before>/* global window, define */
(function(factory) {
  if (typeof exports !== 'undefined') {
    module.exports = factory();
    module.exports.ObjectAdapter = require('./lib/object-adapter');
  }
  else if (typeof define === 'function' && define.amd) {
    define(['factory-girl-object-adapter'], function(ObjectAdapter) {
      var _factory = factory();
      _factory.ObjectAdapter = ObjectAdapter;
      return _factory;
    });
  }
  else {
    window.Factory = factory();
  }
}(function() {
  var Factory = function() {
    var factory = this,
        factories = {},
        defaultAdapter = new Adapter(),
        adapters = {},
        created = [];

    factory.define = function(name, model, attributes, options) {
      options = options || {};

      factories[name] = {
        model: model,
        attributes: attributes,
        options: options
      };
    };

    var builderProxy = function(fnName) {
      return function() {
        var builder = new Builder();
        return builder[fnName].apply(builder, arguments);
      };
    };

    factory.withOptions = builderProxy('withOptions');
    factory.build = builderProxy('build');
    factory.buildSync = builderProxy('buildSync');
    factory.buildMany = builderProxy('buildMany');
    factory.create = builderProxy('create');
    factory.createMany = builderProxy('createMany');

    factory.assoc = function(name, key, attrs) {
      attrs = attrs || {};
      return function(callback) {
        factory.create(name, attrs, function(err, doc) {
          if (err) return callback(err);
          callback(null, key ? doc[key] : doc);
        });
      };
    };

    factory.assocMany = function(name, key, num, attrsArray) {
      if (arguments.length < 4) {
        if (typeof key === 'number') {
          attrsArray = num;
          num = key;
          key = null;
        }
      }
      return function(callback) {
        factory.createMany(name, attrsArray, num, function(err, docs) {
          if (err) return callback(err);
          if (key) {
            for (var i = 0; i < docs.length; ++i) {
              docs[i] = docs[i][key];
            }
          }
          callback(null, docs);
        });
      };
    };

    factory.sequence = function(fn) {
      var result;
      var sequenceNum = 1;

      if (!fn || fn.length < 2) {
        result = function() {
          if (fn) {
            return fn(sequenceNum++);
          }
          else {
            return sequenceNum++;
          }
        };
      }
      else {
        result = function(cb) {
          return fn(sequenceNum++, cb);
        };
      }
      return result;
    };

    factory.seq = factory.sequence;

    factory.adapterFor = function(name) {
      return adapters[name] || defaultAdapter;
    };

    factory.setAdapter = function(adapter, name) {
      if (name) {
        adapters[name] = adapter;
      }
      else {
        defaultAdapter = adapter;
      }
    };

    factory.promisify = function(promiseLibrary) {
      var promisify = promiseLibrary.promisify || promiseLibrary.denodeify;
      if (!promisify) throw new Error("No 'promisify' or 'denodeify' method found in supplied promise library");
      var promisified = {};
      for (var i in factory) {
        if (factory.hasOwnProperty(i)) {
          promisified[i] = factory[i];
        }
      }

      var promisifiedBuilderProxy = function(fnName) {
        return function() {
          var builder = new Builder();
          builder.promisify(promisify);
          return builder[fnName].apply(builder, arguments);
        };
      };

      promisified.withOptions = promisifiedBuilderProxy('withOptions');
      promisified.build = promisifiedBuilderProxy('build');
      promisified.buildMany = promisifiedBuilderProxy('buildMany');
      promisified.create = promisifiedBuilderProxy('create');
      promisified.createMany = promisifiedBuilderProxy('createMany');

      promisified.cleanup = promisify(factory.cleanup);

      return promisified;
    };

    factory.cleanup = function(callback) {
      asyncForEach(created.reverse(), function(tuple, cb) {
        var name = tuple[0],
            doc = tuple[1],
            adapter = factory.adapterFor(name),
            model = factories[name].model;
        adapter.destroy(doc, model, cb);
      }, callback);
      created = [];
    };

    var Builder = function() {
      var builder = this;
      builder.options = {};

      builder.promisify = function(promisify) {
        builder.build = promisify(builder.build);
        builder.create = promisify(builder.create);
        builder.buildMany = promisify(builder.buildMany);
        builder.createMany = promisify(builder.createMany);
      };

      builder.withOptions = function(options) {
        merge(builder.options, options);
        return builder;
      };

      builder.create = function(name, attrs, callback) {
        if (typeof attrs === 'function') {
          callback = attrs;
          attrs = {};
        }
        if (!factories[name]) {
          return callback(new Error("No factory defined for model '" + name + "'"));
        }

        builder.build(name, attrs, function(err, doc) {
          if (err) return callback(err);
          save(name, doc, callback);
        });
      };

      builder.build = function(name, attrs, callback) {
        if (typeof attrs === 'function') {
          callback = attrs;
          attrs = {};
        }

        if (!factories[name]) {
          return callback(new Error("No factory defined for model '" + name + "'"));
        }
        var model = factories[name].model;
        attrs = merge(copy(factories[name].attributes), attrs);

        asyncForEach(keys(attrs), function(key, cb) {
          var fn = attrs[key];
          if (typeof fn === 'function') {
            if (!fn.length) {
              attrs[key] = fn.call(attrs);
              cb();
            }
            else {
              fn.call(attrs, function(err, value) {
                if (err) return cb(err);
                attrs[key] = value;
                cb();
              });
            }
          }
          else {
            cb();
          }
        }, function(err) {
          if (err) return callback(err);
          var adapter = factory.adapterFor(name),
              doc = adapter.build(model, attrs);
          callback(null, doc);
        });
      };

      builder.buildSync = function(name, attrs) {
        if (!factories[name]) {
          throw new Error("No factory defined for model '" + name + "'");
        }
        var model = factories[name].model;
        attrs = merge(copy(factories[name].attributes), attrs);
        var names = keys(attrs);
        for (var i = 0; i < names.length; i++) {
          var key = names[i], fn = attrs[key];
          if (typeof fn == 'function') {
            if (fn.length) {
              throw new Error("buildSync only supports synchronous property functions (with no arguments): the function for '" + name + "." + key + "' expects " + fn.length + " arguments");
            }
            attrs[key] = fn.call(attrs);
          }
        }
        var adapter = factory.adapterFor(name);
        return adapter.build(model, attrs);
      };

      builder.buildMany = function(name, attrsArray, num, callback) {
        var args = parseBuildManyArgs.apply(null, arguments);
        buildMany(args);
      };

      builder.createMany = function(name, attrsArray, num, callback) {
        var args = parseBuildManyArgs.apply(null, arguments),
            results = [];
        callback = args.callback;
        args.callback = function(err, docs) {
          if (err) return callback(err);
          asyncForEach(docs, function(doc, cb, index) {
            save(name, doc, function(err) {
              if (!err) results[index] = doc;
              cb(err);
            });
          }, function(err) {
            callback(err, results);
          });
        };
        buildMany(args);
      };

      function buildMany(args) {
        var results = [];
        asyncForEach(args.attrsArray, function(attrs, cb, index) {
          builder.build(args.name, attrs, function(err, doc) {
            if (!err) results[index] = doc;
            cb(err);
          });
        }, function(err) {
          args.callback(err, results);
        });
      }

      function parseBuildManyArgs(name, attrsArray, num, callback) {
        if (typeof num == 'function') { // name, Array, callback
          callback = num;
          num = attrsArray.length;
        }
        if (typeof attrsArray == 'number') { // name, num, callback
          num = attrsArray;
          attrsArray = null;
        }
        if (!(attrsArray instanceof Array)) { // name, Object, num, callback
          if (typeof num != 'number') throw new Error("num must be specified when attrsArray is not an array");
          var attrs = attrsArray;
          attrsArray = new Array(num);
          for (var i = 0; i < num; i++) {
            attrsArray[i] = attrs;
          }
        }
        if (!attrsArray) {
          attrsArray = new Array(num);
        }
        else if( attrsArray.length !== num ) {
          attrsArray.length = num;
        }
        return {
          name: name,
          attrsArray: attrsArray,
          num: num,
          callback: callback
        };
      }

      function save(name, doc, callback) {
        var model = factories[name].model;
        factory.adapterFor(name).save(doc, model, function (err) {
          if (err) return callback(err);
          created.push([name, doc]);
          if (factories[name].options.afterCreate) {
            factories[name].options.afterCreate.call(this, doc, builder.options, callback);
          }
          else {
            callback(err, doc);
          }
        });
      }
    };
  };

  var Adapter = function() {};

  Adapter.prototype.build = function(Model, props) {
    var doc = new Model();
    this.set(props, doc, Model);
    return doc;
  };
  Adapter.prototype.get = function(doc, attr, Model) {
    return doc[attr];
  };
  Adapter.prototype.set = function(props, doc, Model) {
    var key;
    for (key in props) {
      if (props.hasOwnProperty(key)) {
        doc[key] = props[key];
      }
    }
  };
  Adapter.prototype.save = function(doc, Model, cb) {
    doc.save(cb);
  };
  /**
    Be aware that the model may have already been destroyed
   */
  Adapter.prototype.destroy = function(doc, Model, cb) {
    doc.destroy(cb);
  };

  var merge = require('lodash.merge');

  function copy(obj) {
    var newObj = {};
    if (obj) {
      merge(newObj, obj);
    }
    return newObj;
  }
  function keys(obj) {
    var rv = [], key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
       rv.push(key);
      }
    }
    return rv;
  }
  function asyncForEach(array, handler, callback) {
    var length = array.length,
        index = -1;
    function processNext(err) {
      if (err) return callback(err);
      index++;
      if (index < length) {
        handler(array[index], processNext, index);
      }
      else if (callback) {
        setImmediate ? setImmediate(callback) : setTimeout(callback, 0);
      }
    }
    processNext();
  }

  var factory = new Factory();
  factory.Adapter = Adapter;
  factory.Factory = Factory;

  return factory;

}));
<commit_msg>Fix issue with setImmediate being undefined<commit_after>/* global window, define */
(function(factory) {
  if (typeof exports !== 'undefined') {
    module.exports = factory();
    module.exports.ObjectAdapter = require('./lib/object-adapter');
  }
  else if (typeof define === 'function' && define.amd) {
    define(['factory-girl-object-adapter'], function(ObjectAdapter) {
      var _factory = factory();
      _factory.ObjectAdapter = ObjectAdapter;
      return _factory;
    });
  }
  else {
    window.Factory = factory();
  }
}(function() {
  var Factory = function() {
    var factory = this,
        factories = {},
        defaultAdapter = new Adapter(),
        adapters = {},
        created = [];

    factory.define = function(name, model, attributes, options) {
      options = options || {};

      factories[name] = {
        model: model,
        attributes: attributes,
        options: options
      };
    };

    var builderProxy = function(fnName) {
      return function() {
        var builder = new Builder();
        return builder[fnName].apply(builder, arguments);
      };
    };

    factory.withOptions = builderProxy('withOptions');
    factory.build = builderProxy('build');
    factory.buildSync = builderProxy('buildSync');
    factory.buildMany = builderProxy('buildMany');
    factory.create = builderProxy('create');
    factory.createMany = builderProxy('createMany');

    factory.assoc = function(name, key, attrs) {
      attrs = attrs || {};
      return function(callback) {
        factory.create(name, attrs, function(err, doc) {
          if (err) return callback(err);
          callback(null, key ? doc[key] : doc);
        });
      };
    };

    factory.assocMany = function(name, key, num, attrsArray) {
      if (arguments.length < 4) {
        if (typeof key === 'number') {
          attrsArray = num;
          num = key;
          key = null;
        }
      }
      return function(callback) {
        factory.createMany(name, attrsArray, num, function(err, docs) {
          if (err) return callback(err);
          if (key) {
            for (var i = 0; i < docs.length; ++i) {
              docs[i] = docs[i][key];
            }
          }
          callback(null, docs);
        });
      };
    };

    factory.sequence = function(fn) {
      var result;
      var sequenceNum = 1;

      if (!fn || fn.length < 2) {
        result = function() {
          if (fn) {
            return fn(sequenceNum++);
          }
          else {
            return sequenceNum++;
          }
        };
      }
      else {
        result = function(cb) {
          return fn(sequenceNum++, cb);
        };
      }
      return result;
    };

    factory.seq = factory.sequence;

    factory.adapterFor = function(name) {
      return adapters[name] || defaultAdapter;
    };

    factory.setAdapter = function(adapter, name) {
      if (name) {
        adapters[name] = adapter;
      }
      else {
        defaultAdapter = adapter;
      }
    };

    factory.promisify = function(promiseLibrary) {
      var promisify = promiseLibrary.promisify || promiseLibrary.denodeify;
      if (!promisify) throw new Error("No 'promisify' or 'denodeify' method found in supplied promise library");
      var promisified = {};
      for (var i in factory) {
        if (factory.hasOwnProperty(i)) {
          promisified[i] = factory[i];
        }
      }

      var promisifiedBuilderProxy = function(fnName) {
        return function() {
          var builder = new Builder();
          builder.promisify(promisify);
          return builder[fnName].apply(builder, arguments);
        };
      };

      promisified.withOptions = promisifiedBuilderProxy('withOptions');
      promisified.build = promisifiedBuilderProxy('build');
      promisified.buildMany = promisifiedBuilderProxy('buildMany');
      promisified.create = promisifiedBuilderProxy('create');
      promisified.createMany = promisifiedBuilderProxy('createMany');

      promisified.cleanup = promisify(factory.cleanup);

      return promisified;
    };

    factory.cleanup = function(callback) {
      asyncForEach(created.reverse(), function(tuple, cb) {
        var name = tuple[0],
            doc = tuple[1],
            adapter = factory.adapterFor(name),
            model = factories[name].model;
        adapter.destroy(doc, model, cb);
      }, callback);
      created = [];
    };

    var Builder = function() {
      var builder = this;
      builder.options = {};

      builder.promisify = function(promisify) {
        builder.build = promisify(builder.build);
        builder.create = promisify(builder.create);
        builder.buildMany = promisify(builder.buildMany);
        builder.createMany = promisify(builder.createMany);
      };

      builder.withOptions = function(options) {
        merge(builder.options, options);
        return builder;
      };

      builder.create = function(name, attrs, callback) {
        if (typeof attrs === 'function') {
          callback = attrs;
          attrs = {};
        }
        if (!factories[name]) {
          return callback(new Error("No factory defined for model '" + name + "'"));
        }

        builder.build(name, attrs, function(err, doc) {
          if (err) return callback(err);
          save(name, doc, callback);
        });
      };

      builder.build = function(name, attrs, callback) {
        if (typeof attrs === 'function') {
          callback = attrs;
          attrs = {};
        }

        if (!factories[name]) {
          return callback(new Error("No factory defined for model '" + name + "'"));
        }
        var model = factories[name].model;
        attrs = merge(copy(factories[name].attributes), attrs);

        asyncForEach(keys(attrs), function(key, cb) {
          var fn = attrs[key];
          if (typeof fn === 'function') {
            if (!fn.length) {
              attrs[key] = fn.call(attrs);
              cb();
            }
            else {
              fn.call(attrs, function(err, value) {
                if (err) return cb(err);
                attrs[key] = value;
                cb();
              });
            }
          }
          else {
            cb();
          }
        }, function(err) {
          if (err) return callback(err);
          var adapter = factory.adapterFor(name),
              doc = adapter.build(model, attrs);
          callback(null, doc);
        });
      };

      builder.buildSync = function(name, attrs) {
        if (!factories[name]) {
          throw new Error("No factory defined for model '" + name + "'");
        }
        var model = factories[name].model;
        attrs = merge(copy(factories[name].attributes), attrs);
        var names = keys(attrs);
        for (var i = 0; i < names.length; i++) {
          var key = names[i], fn = attrs[key];
          if (typeof fn == 'function') {
            if (fn.length) {
              throw new Error("buildSync only supports synchronous property functions (with no arguments): the function for '" + name + "." + key + "' expects " + fn.length + " arguments");
            }
            attrs[key] = fn.call(attrs);
          }
        }
        var adapter = factory.adapterFor(name);
        return adapter.build(model, attrs);
      };

      builder.buildMany = function(name, attrsArray, num, callback) {
        var args = parseBuildManyArgs.apply(null, arguments);
        buildMany(args);
      };

      builder.createMany = function(name, attrsArray, num, callback) {
        var args = parseBuildManyArgs.apply(null, arguments),
            results = [];
        callback = args.callback;
        args.callback = function(err, docs) {
          if (err) return callback(err);
          asyncForEach(docs, function(doc, cb, index) {
            save(name, doc, function(err) {
              if (!err) results[index] = doc;
              cb(err);
            });
          }, function(err) {
            callback(err, results);
          });
        };
        buildMany(args);
      };

      function buildMany(args) {
        var results = [];
        asyncForEach(args.attrsArray, function(attrs, cb, index) {
          builder.build(args.name, attrs, function(err, doc) {
            if (!err) results[index] = doc;
            cb(err);
          });
        }, function(err) {
          args.callback(err, results);
        });
      }

      function parseBuildManyArgs(name, attrsArray, num, callback) {
        if (typeof num == 'function') { // name, Array, callback
          callback = num;
          num = attrsArray.length;
        }
        if (typeof attrsArray == 'number') { // name, num, callback
          num = attrsArray;
          attrsArray = null;
        }
        if (!(attrsArray instanceof Array)) { // name, Object, num, callback
          if (typeof num != 'number') throw new Error("num must be specified when attrsArray is not an array");
          var attrs = attrsArray;
          attrsArray = new Array(num);
          for (var i = 0; i < num; i++) {
            attrsArray[i] = attrs;
          }
        }
        if (!attrsArray) {
          attrsArray = new Array(num);
        }
        else if( attrsArray.length !== num ) {
          attrsArray.length = num;
        }
        return {
          name: name,
          attrsArray: attrsArray,
          num: num,
          callback: callback
        };
      }

      function save(name, doc, callback) {
        var model = factories[name].model;
        factory.adapterFor(name).save(doc, model, function (err) {
          if (err) return callback(err);
          created.push([name, doc]);
          if (factories[name].options.afterCreate) {
            factories[name].options.afterCreate.call(this, doc, builder.options, callback);
          }
          else {
            callback(err, doc);
          }
        });
      }
    };
  };

  var Adapter = function() {};

  Adapter.prototype.build = function(Model, props) {
    var doc = new Model();
    this.set(props, doc, Model);
    return doc;
  };
  Adapter.prototype.get = function(doc, attr, Model) {
    return doc[attr];
  };
  Adapter.prototype.set = function(props, doc, Model) {
    var key;
    for (key in props) {
      if (props.hasOwnProperty(key)) {
        doc[key] = props[key];
      }
    }
  };
  Adapter.prototype.save = function(doc, Model, cb) {
    doc.save(cb);
  };
  /**
    Be aware that the model may have already been destroyed
   */
  Adapter.prototype.destroy = function(doc, Model, cb) {
    doc.destroy(cb);
  };

  var merge = require('lodash.merge');

  function copy(obj) {
    var newObj = {};
    if (obj) {
      merge(newObj, obj);
    }
    return newObj;
  }
  function keys(obj) {
    var rv = [], key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
       rv.push(key);
      }
    }
    return rv;
  }
  function asyncForEach(array, handler, callback) {
    var length = array.length,
        index = -1;
    function processNext(err) {
      if (err) return callback(err);
      index++;
      if (index < length) {
        handler(array[index], processNext, index);
      }
      else if (callback) {
        typeof setImmediate === 'function' ? setImmediate(callback) : setTimeout(callback, 0);
      }
    }
    processNext();
  }

  var factory = new Factory();
  factory.Adapter = Adapter;
  factory.Factory = Factory;

  return factory;

}));
<|endoftext|>


<commit_before><commit_msg>Update index.js<commit_after><|endoftext|>


<commit_before><commit_msg>[Refactor] use an early return instead of a ternary.<commit_after><|endoftext|>


<commit_before><commit_msg>Try to find out more about what match returns<commit_after><|endoftext|>


<commit_before><commit_msg>message format update<commit_after><|endoftext|>


<commit_before><commit_msg>Use new pressflow defaults<commit_after><|endoftext|>


<commit_before><commit_msg>Call with tickers as args<commit_after><|endoftext|>


<commit_before><commit_msg>no groups for cache.masterRE, early return on set gives the cache.regexp found<commit_after><|endoftext|>


<commit_before><commit_msg>syntax in require for gamecode<commit_after><|endoftext|>


<commit_before><commit_msg>Cosmetic: fix formatting<commit_after><|endoftext|>


<commit_before><commit_msg>修复windows下找不到dart2js命令问题<commit_after><|endoftext|>


<commit_before>d3.mappu = d3.mappu || {};
/*
 * d3.mappu.Map is the central class of the API - it is used to create a map.
 */

/* d3.mappu.Map(element, config)

element = dom object
options:
center: [long,lat]                  default = [0,0]
zoom: zoomlevel                     default = 0.0
layers: [layer]                     default = null
minZoom: zoomlevel                  default = 0.0
maxZoom: zoomlevel                  default = 13.0
maxView: [[long,lat],[long,lat]]    default = [[-180,90],[180,-90]]
projection: projection              default = d3.geo.mercator()
*/

d3.mappu.Map = function(id, config) {
    return d3_mappu_Map(id, config);
};

d3_mappu_Map = function(id, config) {

    var map = {};
	var _layers = [];
	var _mapdiv;

	//check if elem is a dom-element or an identifier
	if (typeof(id) == 'object'){
	    _mapdiv = id;
	}
	else {
	    _mapdiv = document.getElementById(id);
	}

	window.onresize = function(){
		resize();
	};

	//TODO: how to get the size of the map
	var _width = _mapdiv.clientWidth || 2024;
	var _height = _mapdiv.clientHeight || window.innerHeight || 768;
	var _ratio = 1;

	/* Experimental
	var _canvasdiv = d3.select(_mapdiv)
		.style("width", _width + 'px')
		.style("height", _height + 'px')
	  .append("div")
		.style("transform", "scale(" + 1 / _ratio + ")")
		.style("transform-origin", "0 0 0");
	*/

	var _center = config.center || [0,0];
	var _projection = config.projection || d3.geo.mercator();
	var _zoom = config.zoom || 22;
	var _maxZoom = config.maxZoom || 24;
	var _minZoom = config.minZoom || 15;
	var _maxView = config.maxView || [[-180,90],[180,-90]];

    var redraw = function(){
    	//Calculate projection, so we can find out coordinates
    	_projection
           .scale(_zoombehaviour.scale() / 2 / Math.PI)
           .translate(_zoombehaviour.translate());
    	//Set internal zoom
    	var scale = _zoombehaviour.scale();
    	_zoom = (Math.log(scale* 2 * Math.PI)/Math.log(2));

    	//Set internal center
    	var pixcenter = [_width/2,_height/2];
        _center =  _projection.invert(pixcenter);

        //Calculate tile set
        _tiles = _tile.scale(_zoombehaviour.scale())
          .translate(_zoombehaviour.translate())();

        /* EXPERIMENTAL */
        //layer.call(raster);

        _layers.forEach(function(d){
            d.refresh(0);
        });
    };

    var resize = function(){
		_width = _mapdiv.clientWidth;
		_height = _mapdiv.clientHeight;
		d3.select(_mapdiv).select('svg')
			.attr("width", _width)
			.attr("height", _height);
		_tile.size([_width,_height]);
		redraw();
	};

	function zoomcenter(zoomval, centerval){
   	   	var scale = (1 << zoomval) / 2 / Math.PI;
		_zoombehaviour.scale(scale);
		_projection
		   .scale(_zoombehaviour.scale() / 2 / Math.PI)
		   .translate(_zoombehaviour.translate());

		//Adapt projection based on new zoomlevel
		var pixcenter = _projection(centerval);
		var curtranslate = _zoombehaviour.translate();
		var translate = [
			curtranslate[0] + (_width - pixcenter[0]) - (_width/2),
			curtranslate[1] + (_height - pixcenter[1]) - (_height/2)
		];
		_zoombehaviour.translate(translate);
		_zoombehaviour.event(_svg.transition()); //Trigger zoombehaviour
   }

	var _svg = d3.select(_mapdiv).append('svg')
	    .style('position', 'absolute');

    //var p = .5 * _ratio;
	_projection.scale(( _zoom << 12 || 1 << 12) / 2 / Math.PI)
        .translate([_width / 2, _height / 2]);
	    //.center(_center)
        //.clipExtent([[p, p], [_width - p, _height - p]]);

    var _projcenter = _projection(_center);

	var _zoombehaviour = d3.behavior.zoom()
	    .scale(_projection.scale() * 2 * Math.PI)
        .scaleExtent([1 << _minZoom, 1 << _maxZoom])
        .translate([_width - _projcenter[0], _height - _projcenter[1]])
        .on("zoom", redraw);
	d3.select(_mapdiv).call(_zoombehaviour);

    _projection
        .scale(1 / 2 / Math.PI)
        .translate([0, 0]);

    var _tile = d3.geo.tile()
        .size([_width,_height]);

    var _tiles = _tile.scale(_zoombehaviour.scale())
          .translate(_zoombehaviour.translate())();

    resize();

    /*
    var raster = d3.geo.raster(_projection)
        .scaleExtent([0, 10])
        //.url("//{subdomain}.tiles.mapbox.com/v3/mapbox.natural-earth-2/{z}/{x}/{y}.png");
        .url("//{subdomain}.tiles.mapbox.com/v3/examples.map-i86nkdio/{z}/{x}/{y}.png");

    var layer = _canvasdiv
      .append("div")
        .style("transform-origin", "0 0 0")
        .call(raster);
   */
// exposed functions

////getter/setter functions
	 Object.defineProperty(map, 'svg', {
        get: function() {
            return _svg;
        },
        set: function() {
            console.log("do not touch the svg");
        }
    });
    /* TT: Obsolete?
    Object.defineProperty(map, 'size', {
            get: function(){return [_height, _width];},
            set: function(val){
                _height = val[0];
                _width = val[1];
                _tile = d3.geo.tile()
                    .size([_width,_height]);
                d3.select(_mapdiv).select('svg')
                    .attr("width", _width)
                    .attr("height", _height);
                map.redraw();
            }
    });
    */
    Object.defineProperty(map, 'mapdiv', {
        get: function() {
            return _mapdiv;
        },
        set: function() {
            console.log("do not touch the mapdiv");
        }
    });

    Object.defineProperty(map, 'canvasdiv', {
        get: function() {
            return _canvasdiv;
        },
        set: function() {
            console.log("do not touch the canvasdiv");
        }
    });

// .center : ([long,lat])
    Object.defineProperty(map, 'center', {
        get: function() {
            return _center;
        },
        set: function(val) {
        	//zoomcenter will move to and set the center in some steps
			zoomcenter(_zoom, val);
        }
    });
// .zoom : (zoomlevel)
//http://truongtx.me/2014/03/13/working-with-zoom-behavior-in-d3js-and-some-notes/
    Object.defineProperty(map, 'zoom', {
        get: function() {
            return _zoom;
        },
        set: function(val) {
        	if (val <= _maxZoom && val >= _minZoom){
        		//zoomcenter will move to and set the zoomlevel in some steps
				zoomcenter(val, _center);
			}
			else {
				console.log('Zoomlevel exceeded',val , 'Min:',_minZoom ,'Max:', _maxZoom);
			}
        }
    });

// .minZoom : (zoomlevel)
    Object.defineProperty(map, 'minZoom', {
        get: function() {
            return _minZoom;
        },
        set: function(val) {
            _minZoom = val;
            this.zoombehaviour.scaleExtent([1 << _minZoom, 1 << _maxZoom]);
        }
    });
// .maxZoom : (zoomlevel)
    Object.defineProperty(map, 'maxZoom', {
        get: function() {
            return _maxZoom;
        },
        set: function(val) {
            _maxZoom = val;
            this.zoombehaviour.scaleExtent([1 << _minZoom, 1 << _maxZoom]);
        }
    });
// .maxView : ([[long,lat],[long,lat]])
    Object.defineProperty(map, 'maxView', {
        get: function() {
            return _maxView;
        },
        set: function(val) {
            _maxView = val;
        }
    });
// .projection : ({projection})
    Object.defineProperty(map, 'projection', {
        get: function() {
            return _projection;
        },
        set: function(obj) {
          _projection = obj;
          //TODO: redraw
        }
    });

    Object.defineProperty(map, 'tiles', {
            get: function(){return _tiles;},
            set: function(){console.warn('No setting allowed for tile');}
    });

    Object.defineProperty(map, 'zoombehaviour', {
            get: function(){return _zoombehaviour;},
            set: function(){console.warn('No setting allowed for zoombehaviour');}
    });

    Object.defineProperty(map, 'layers', {
            get: function(){return _layers;},
            set: function(){console.warn('No setting allowed for layers');}
    });

////singular functions

	var zoomToFeature = function(d){
		//TODO
		console.warn('Not implemented yet');
	};

    var addLayer = function(layer){
        if (!layer.id){
            console.warn('Not a valid layer. (No ID)');
            return false;
        }
        //Replace existing ID
        _layers.forEach(function(d){
            if (d.id == layer.id){
                d = layer; //TODO: can you replace an array item like this?
                return map;
            }
        });
        _layers.push(layer);
        layer._onAdd(map);
        return map;
    };
    var removeLayer = function(id){
        _layers.forEach(function(d,i){
            if (d.id == id){
                // ?? d.onRemove(self);
                _layers.splice(i,1);
                return map;
            }
        });
        return map;
    };
    var getLayersByName = function(name){
    	var result = [];
    	_layers.forEach(function(d,i){
            if (d.name == name){
                result.push(d);
            }
        });
        return result;
    };

// .removeLayers([{layer}])

// .refresh()

    map.zoomToFeature = zoomToFeature;
    map.addLayer = addLayer;
    map.removeLayer = removeLayer;
    map.getLayersByName = getLayersByName;
    map.redraw = redraw;
    map.resize = resize;

    return map;
};

//                                                                          マップ
<commit_msg>Update d3.mappu.Map.js<commit_after>d3.mappu = d3.mappu || {};
/*
 * d3.mappu.Map is the central class of the API - it is used to create a map.
 */

/* d3.mappu.Map(element, config)

element = dom object
options:
center: [long,lat]                  default = [0,0]
zoom: zoomlevel                     default = 0.0
layers: [layer]                     default = null
minZoom: zoomlevel                  default = 0.0
maxZoom: zoomlevel                  default = 13.0
maxView: [[long,lat],[long,lat]]    default = [[-180,90],[180,-90]]
projection: projection              default = d3.geo.mercator()
*/

d3.mappu.Map = function(id, config) {
    return d3_mappu_Map(id, config);
};

d3_mappu_Map = function(id, config) {

    var map = {};
	var _layers = [];
	var _mapdiv;

	//check if elem is a dom-element or an identifier
	if (typeof(id) == 'object'){
	    _mapdiv = id;
	}
	else {
	    _mapdiv = document.getElementById(id);
	}

	window.onresize = function(){
		resize();
	};

	//TODO: how to get the size of the map
	var _width = _mapdiv.clientWidth || 2024;
	var _height = _mapdiv.clientHeight || window.innerHeight || 768;
	var _ratio = 1;

	/* Experimental
	var _canvasdiv = d3.select(_mapdiv)
		.style("width", _width + 'px')
		.style("height", _height + 'px')
	  .append("div")
		.style("transform", "scale(" + 1 / _ratio + ")")
		.style("transform-origin", "0 0 0");
	*/

	var _center = config.center || [0,0];
	var _projection = config.projection || d3.geo.mercator();
	var _zoom = config.zoom || 22;
	var _maxZoom = config.maxZoom || 24;
	var _minZoom = config.minZoom || 15;
	var _maxView = config.maxView || [[-180,90],[180,-90]];

    var redraw = function(){
    	//Calculate projection, so we can find out coordinates
    	_projection
           .scale(_zoombehaviour.scale() / 2 / Math.PI)
           .translate(_zoombehaviour.translate());
    	//Set internal zoom
    	var scale = _zoombehaviour.scale();
    	_zoom = (Math.log(scale* 2 * Math.PI)/Math.log(2));

    	//Set internal center
    	var pixcenter = [_width/2,_height/2];
        _center =  _projection.invert(pixcenter);

        //Calculate tile set
        _tiles = _tile.scale(_zoombehaviour.scale())
          .translate(_zoombehaviour.translate())();

        /* EXPERIMENTAL */
        //layer.call(raster);

        _layers.forEach(function(d){
            d.refresh(0);
        });
    };

    var resize = function(){
		_width = _mapdiv.clientWidth;
		_height = _mapdiv.clientHeight;
		d3.select(_mapdiv).select('svg')
			.attr("width", _width)
			.attr("height", _height);
		_tile.size([_width,_height]);
		redraw();
	};

	function zoomcenter(zoomval, centerval){
   	   	var scale = (1 << zoomval) / 2 / Math.PI;
		_zoombehaviour.scale(scale);
		_projection
		   .scale(_zoombehaviour.scale() / 2 / Math.PI)
		   .translate(_zoombehaviour.translate());

		//Adapt projection based on new zoomlevel
		var pixcenter = _projection(centerval);
		var curtranslate = _zoombehaviour.translate();
		var translate = [
			curtranslate[0] + (_width - pixcenter[0]) - (_width/2),
			curtranslate[1] + (_height - pixcenter[1]) - (_height/2)
		];
		_zoombehaviour.translate(translate);
		_zoombehaviour.event(_svg.transition()); //Trigger zoombehaviour
   }

	var _svg = d3.select(_mapdiv).append('svg')
	    .style('position', 'absolute');

    //var p = .5 * _ratio;
	_projection.scale(( _zoom << 12 || 1 << 12) / 2 / Math.PI)
        .translate([_width / 2, _height / 2]);
	    //.center(_center)
        //.clipExtent([[p, p], [_width - p, _height - p]]);

    var _projcenter = _projection(_center);

	var _zoombehaviour = d3.behavior.zoom()
	    .scale(_projection.scale() * 2 * Math.PI)
        .scaleExtent([1 << _minZoom, 1 << _maxZoom])
        .translate([_width - _projcenter[0], _height - _projcenter[1]])
        .on("zoom", redraw);
	d3.select(_mapdiv).call(_zoombehaviour);

    _projection
        .scale(1 / 2 / Math.PI)
        .translate([0, 0]);

    var _tile = d3.geo.tile()
        .size([_width,_height]);

    var _tiles = _tile.scale(_zoombehaviour.scale())
          .translate(_zoombehaviour.translate())();

    resize();

    /*
    var raster = d3.geo.raster(_projection)
        .scaleExtent([0, 10])
        //.url("//{subdomain}.tiles.mapbox.com/v3/mapbox.natural-earth-2/{z}/{x}/{y}.png");
        .url("//{subdomain}.tiles.mapbox.com/v3/examples.map-i86nkdio/{z}/{x}/{y}.png");

    var layer = _canvasdiv
      .append("div")
        .style("transform-origin", "0 0 0")
        .call(raster);
   */
// exposed functions

////getter/setter functions
	 Object.defineProperty(map, 'svg', {
        get: function() {
            return _svg;
        },
        set: function() {
            console.log("do not touch the svg");
        }
    });
    /* TT: Obsolete?
    Object.defineProperty(map, 'size', {
            get: function(){return [_height, _width];},
            set: function(val){
                _height = val[0];
                _width = val[1];
                _tile = d3.geo.tile()
                    .size([_width,_height]);
                d3.select(_mapdiv).select('svg')
                    .attr("width", _width)
                    .attr("height", _height);
                map.redraw();
            }
    });
    */
    Object.defineProperty(map, 'mapdiv', {
        get: function() {
            return _mapdiv;
        },
        set: function() {
            console.log("do not touch the mapdiv");
        }
    });

    Object.defineProperty(map, 'canvasdiv', {
        get: function() {
            return _canvasdiv;
        },
        set: function() {
            console.log("do not touch the canvasdiv");
        }
    });

// .center : ([long,lat])
    Object.defineProperty(map, 'center', {
        get: function() {
            return _center;
        },
        set: function(val) {
        	//zoomcenter will move to and set the center in some steps
			zoomcenter(_zoom, val);
        }
    });
// .zoom : (zoomlevel)
//http://truongtx.me/2014/03/13/working-with-zoom-behavior-in-d3js-and-some-notes/
    Object.defineProperty(map, 'zoom', {
        get: function() {
            return _zoom;
        },
        set: function(val) {
        	if (val <= _maxZoom && val >= _minZoom){
        		//zoomcenter will move to and set the zoomlevel in some steps
				zoomcenter(val, _center);
			}
			else {
				console.log('Zoomlevel exceeded',val , 'Min:',_minZoom ,'Max:', _maxZoom);
			}
        }
    });

// .minZoom : (zoomlevel)
    Object.defineProperty(map, 'minZoom', {
        get: function() {
            return _minZoom;
        },
        set: function(val) {
            _minZoom = val;
            this.zoombehaviour.scaleExtent([1 << _minZoom, 1 << _maxZoom]);
        }
    });
// .maxZoom : (zoomlevel)
    Object.defineProperty(map, 'maxZoom', {
        get: function() {
            return _maxZoom;
        },
        set: function(val) {
            _maxZoom = val;
            this.zoombehaviour.scaleExtent([1 << _minZoom, 1 << _maxZoom]);
        }
    });
// .maxView : ([[long,lat],[long,lat]])
    Object.defineProperty(map, 'maxView', {
        get: function() {
            return _maxView;
        },
        set: function(val) {
            _maxView = val;
        }
    });
// .projection : ({projection})
    Object.defineProperty(map, 'projection', {
        get: function() {
            return _projection;
        },
        set: function(obj) {
          _projection = obj;
          //TODO: redraw
        }
    });

    Object.defineProperty(map, 'tiles', {
            get: function(){return _tiles;},
            set: function(){console.warn('No setting allowed for tile');}
    });

    Object.defineProperty(map, 'zoombehaviour', {
            get: function(){return _zoombehaviour;},
            set: function(){console.warn('No setting allowed for zoombehaviour');}
    });

    Object.defineProperty(map, 'layers', {
            get: function(){return _layers;},
            set: function(){console.warn('No setting allowed for layers');}
    });

////singular functions

	var zoomToFeature = function(d){
		//TODO
		console.warn('Not implemented yet');
	};

    var addLayer = function(layer){
        if (!layer.id){
            console.warn('Not a valid layer. (No ID)');
            return false;
        }
        //Replace existing ID
        _layers.forEach(function(d){
            if (d.id == layer.id){
                d = layer; //TODO: can you replace an array item like this?
                return map;
            }
        });
        _layers.push(layer);
        layer._onAdd(map);
        return map;
    };
    var removeLayer = function(id){
        _layers.forEach(function(d,i){
            if (d.id == id){
                // ?? d.onRemove(self);
                _layers.splice(i,1);
                return map;
            }
        });
        return map;
    };
    //SMO: getLayersBy* function are generally a sign of lazyness ;)
    /*var getLayersByName = function(name){
    	var result = [];
    	_layers.forEach(function(d,i){
            if (d.name == name){
                result.push(d);
            }
        });
        return result;
    };*/

// .removeLayers([{layer}])

// .refresh()

    map.zoomToFeature = zoomToFeature;
    map.addLayer = addLayer;
    map.removeLayer = removeLayer;
    //map.getLayersByName = getLayersByName;
    map.redraw = redraw;
    map.resize = resize;

    return map;
};

//                                                                          マップ
<|endoftext|>


<commit_before><commit_msg>updated deprecated method call<commit_after><|endoftext|>


<commit_before><commit_msg>Add 'useAll' method<commit_after><|endoftext|>


<commit_before><commit_msg>Update to new express-dom API<commit_after><|endoftext|>


<commit_before><commit_msg>Added support for multiple connection pools. Also added ability to leave connections open with simpleExecute.<commit_after><|endoftext|>


<commit_before><commit_msg>maybe<commit_after><|endoftext|>


<commit_before><commit_msg>Added code for supplying paramters to event handlers<commit_after><|endoftext|>


<commit_before><commit_msg>forgot to add info<commit_after><|endoftext|>


<commit_before><commit_msg>Resolve conflicts<commit_after><|endoftext|>


<commit_before><commit_msg>change port<commit_after><|endoftext|>