<commit_before>import _ from 'lodash';
import request from 'superagent';
import Transport from './Transport';
import PromiseMaker from '../PromiseMaker';
import {CONNECTION_STATES, CONNECTION_EVENTS} from '../Constants';

/**
 * Th' long pollin' transport protocol.
 */
export default class LongPollingTransport extends Transport {
  static supportsKeepAlive = false;

  /**
   * Uses th' current client, treaty from th' initial negotiation, 'n target URL to construct a new Longpollin' transport.
   * @param client
   * @param treaty
   * @param url
   */
  constructor(client, treaty, url) {
    super('longPolling', client, treaty);
    this._maxReconnectedTimeout = 3600000;
    this._url = url;
  }

  /**
   * Initiates th' long pollin' transport protocol fer th' current connection.
   * @returns {Promise} That resolves once th' long pollin' transport has started successfully 'n has begun pollin'.
   */
  _queryData(current) {
    return current
      .query({clientProtocol: 1.5})
      .query({connectionToken: this._connectionToken})
      .query({transport: 'longPolling'})
      .query({connectionData: this._data || ''});
  }

  /**
   *Initiates th' connection after th' LongPollin'Transport transport type be declared via th' initial negotiation.
   * @returns {Promise.<T>}
   */
  start() {
    if(this._pollTimeoutId) {
      throw new Error('A polling session has already been initialized. Call `stop()` before attempting to `start()` again.');
    }
    this._logger.info(`*${this.constructor.name}* starting...`);
    return this._connect()
      //.then(this._startConnection.bind(this))
      .then(() => {
        this.state = CONNECTION_STATES.connected;
        this.emit(CONNECTION_EVENTS.onConnected);
        this._reconnectTries = 0;
        this._reconnectTimeoutId = null;
      })
      .then(this._poll.bind(this));
  }

  /**
   * Initiates th' long pollin' transport protocol fer th' current connection.
   * @returns {Promise} that resolves once th' long pollin' transport has started successfully 'n has begun pollin'.
   */
  _connect() {
    const url = this._url + '/connect';
    this._logger.info(`Connecting to ${url}`);
    this.state = CONNECTION_STATES.connecting;
    this.emit(CONNECTION_EVENTS.onConnecting);
    this._current = request
      .post(url);
    this._current = this._queryData(this._current);
    return this._current
      .use(PromiseMaker)
      .promise()
      .then(this._processMessages.bind(this));
  }

  _startConnection() {
    this._current = request
      .post(this._url + '/start');
    this._current = this._queryData(this._current);
    return this._current
      .use(PromiseMaker)
      .promise();
  }

  /**
   * Initiates a poll to th' ship 'n hold th' poll open 'til th' ship be able to send new information.
   * @returns {Promise} That resolves if th' client must reconnect due to bad connection.
   * Else, th' method be called recursively after it recieves new information from th' ship.
   */
  _poll() {
    const poll = () => {
      const {messageId, groupsToken, shouldReconnect} = this._lastMessages;
      this._current = request
        .post(this._url + '/poll');
      this._current = this._queryData(this._current);
      if(groupsToken) {
        this._current = this._current
          .send({messageId, groupsToken});
      } else {
        this._current = this._current
          .send({messageId});
      }
      this._current = this._current
        .end((err, res) => {
          if(err && shouldReconnect) {
            return this._reconnectTimeoutId = setTimeout(this._reconnect(), Math.min(1000 * (Math.pow(2, this._reconnectTries) - 1), this._maxReconnectedTimeout))
              .then(this._poll);
          }
          if(res) {
            if(this.state === CONNECTION_STATES.reconnecting) {
              this.state = CONNECTION_STATES.connected;
              this.emit(CONNECTION_EVENTS.onReconnected);
              this._reconnectTries = 0;
            }
            if(!_.isString(res.body)) {
              this._processMessages(res.body);
            }
          }
          if(!this._abortRequest) {
            this._poll();
          }
        });

    };
    this._currentTimeoutId = setTimeout(poll.bind(this), 250);
  }

  /**
   * Initiates th' long pollin' transport protocol fer th' current connection.
   *  @params {data} data contains th' information that th' client wishes to send to th' ship.
   *  @returns {Promise} that resolves once th' message has be sent..
   */
  send(data) {
    return request
      .post(this._url + '/send')
      .query({connectionToken: this._connectionToken})
      .query({transport: 'longPolling'})
      .send(`data=${JSON.stringify(data)}`)
      .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
      .use(PromiseMaker)
      .promise();
  }

  /**
   * Initiates a reconnection to th' ship in th' case that th' connection be too slow or be lost completely.
   *  @returns {Promise} that resolves once th' client has be successfully reconnected.
   */
  _reconnect() {
    const url = this._url + '/connect';
    this.emit(CONNECTION_EVENTS.onReconnecting);
    this.state = CONNECTION_STATES.reconnecting;
    this._logger.info(`Attempting to reconnect to ${url}`);
    this._reconnectTries++;
    this._current = request
      .post(url);
    this._current = this._queryData(this._current);

    if((Math.min(1000 * (Math.pow(2, this._reconnectTries) - 1)) >= this._maxReconnectedTimeout)) {
      this.stop();
    }
    return this._current
      .use(PromiseMaker)
      .promise()
      .then(this._processMessages.bind(this));

  }

  /**
   * Clears th' timeouts 'n stops th' connection to th' ship cleanly.
   */
  stop() {
    clearTimeout(this._currentTimeoutId);
    clearTimeout(this._reconnectTimeoutId);
    this._abortRequest = true;
    if(this._current) {
      this._current.abort();
    }
    this.emit(CONNECTION_EVENTS.onDisconnecting);
    this._logger.info(`Disconnecting from ${this._url}.`);
    this.state = CONNECTION_STATES.disconnected;
    this.emit(CONNECTION_EVENTS.onDisconnected);
    this._logger.info('Successfully disconnected.');
  }
}
<commit_msg>commented out un-used method<commit_after>import _ from 'lodash';
import request from 'superagent';
import Transport from './Transport';
import PromiseMaker from '../PromiseMaker';
import {CONNECTION_STATES, CONNECTION_EVENTS} from '../Constants';

/**
 * Th' long pollin' transport protocol.
 */
export default class LongPollingTransport extends Transport {
  static supportsKeepAlive = false;

  /**
   * Uses th' current client, treaty from th' initial negotiation, 'n target URL to construct a new Longpollin' transport.
   * @param client
   * @param treaty
   * @param url
   */
  constructor(client, treaty, url) {
    super('longPolling', client, treaty);
    this._maxReconnectedTimeout = 3600000;
    this._url = url;
  }

  /**
   * Initiates th' long pollin' transport protocol fer th' current connection.
   * @returns {Promise} That resolves once th' long pollin' transport has started successfully 'n has begun pollin'.
   */
  _queryData(current) {
    return current
      .query({clientProtocol: 1.5})
      .query({connectionToken: this._connectionToken})
      .query({transport: 'longPolling'})
      .query({connectionData: this._data || ''});
  }

  /**
   *Initiates th' connection after th' LongPollin'Transport transport type be declared via th' initial negotiation.
   * @returns {Promise.<T>}
   */
  start() {
    if(this._pollTimeoutId) {
      throw new Error('A polling session has already been initialized. Call `stop()` before attempting to `start()` again.');
    }
    this._logger.info(`*${this.constructor.name}* starting...`);
    return this._connect()
      //.then(this._startConnection.bind(this))
      .then(() => {
        this.state = CONNECTION_STATES.connected;
        this.emit(CONNECTION_EVENTS.onConnected);
        this._reconnectTries = 0;
        this._reconnectTimeoutId = null;
      })
      .then(this._poll.bind(this));
  }

  /**
   * Initiates th' long pollin' transport protocol fer th' current connection.
   * @returns {Promise} that resolves once th' long pollin' transport has started successfully 'n has begun pollin'.
   */
  _connect() {
    const url = this._url + '/connect';
    this._logger.info(`Connecting to ${url}`);
    this.state = CONNECTION_STATES.connecting;
    this.emit(CONNECTION_EVENTS.onConnecting);
    this._current = request
      .post(url);
    this._current = this._queryData(this._current);
    return this._current
      .use(PromiseMaker)
      .promise()
      .then(this._processMessages.bind(this));
  }

  //_startConnection() {
  //  this._current = request
  //    .post(this._url + '/start');
  //  this._current = this._queryData(this._current);
  //  return this._current
  //    .use(PromiseMaker)
  //    .promise();
  //}

  /**
   * Initiates a poll to th' ship 'n hold th' poll open 'til th' ship be able to send new information.
   * @returns {Promise} That resolves if th' client must reconnect due to bad connection.
   * Else, th' method be called recursively after it recieves new information from th' ship.
   */
  _poll() {
    const poll = () => {
      const {messageId, groupsToken, shouldReconnect} = this._lastMessages;
      this._current = request
        .post(this._url + '/poll');
      this._current = this._queryData(this._current);
      if(groupsToken) {
        this._current = this._current
          .send({messageId, groupsToken});
      } else {
        this._current = this._current
          .send({messageId});
      }
      this._current = this._current
        .end((err, res) => {
          if(err && shouldReconnect) {
            return this._reconnectTimeoutId = setTimeout(this._reconnect(), Math.min(1000 * (Math.pow(2, this._reconnectTries) - 1), this._maxReconnectedTimeout))
              .then(this._poll);
          }
          if(res) {
            if(this.state === CONNECTION_STATES.reconnecting) {
              this.state = CONNECTION_STATES.connected;
              this.emit(CONNECTION_EVENTS.onReconnected);
              this._reconnectTries = 0;
            }
            if(!_.isString(res.body)) {
              this._processMessages(res.body);
            }
          }
          if(!this._abortRequest) {
            this._poll();
          }
        });

    };
    this._currentTimeoutId = setTimeout(poll.bind(this), 250);
  }

  /**
   * Initiates th' long pollin' transport protocol fer th' current connection.
   *  @params {data} data contains th' information that th' client wishes to send to th' ship.
   *  @returns {Promise} that resolves once th' message has be sent..
   */
  send(data) {
    return request
      .post(this._url + '/send')
      .query({connectionToken: this._connectionToken})
      .query({transport: 'longPolling'})
      .send(`data=${JSON.stringify(data)}`)
      .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
      .use(PromiseMaker)
      .promise();
  }

  /**
   * Initiates a reconnection to th' ship in th' case that th' connection be too slow or be lost completely.
   *  @returns {Promise} that resolves once th' client has be successfully reconnected.
   */
  _reconnect() {
    const url = this._url + '/connect';
    this.emit(CONNECTION_EVENTS.onReconnecting);
    this.state = CONNECTION_STATES.reconnecting;
    this._logger.info(`Attempting to reconnect to ${url}`);
    this._reconnectTries++;
    this._current = request
      .post(url);
    this._current = this._queryData(this._current);

    if((Math.min(1000 * (Math.pow(2, this._reconnectTries) - 1)) >= this._maxReconnectedTimeout)) {
      this.stop();
    }
    return this._current
      .use(PromiseMaker)
      .promise()
      .then(this._processMessages.bind(this));

  }

  /**
   * Clears th' timeouts 'n stops th' connection to th' ship cleanly.
   */
  stop() {
    clearTimeout(this._currentTimeoutId);
    clearTimeout(this._reconnectTimeoutId);
    this._abortRequest = true;
    if(this._current) {
      this._current.abort();
    }
    this.emit(CONNECTION_EVENTS.onDisconnecting);
    this._logger.info(`Disconnecting from ${this._url}.`);
    this.state = CONNECTION_STATES.disconnected;
    this.emit(CONNECTION_EVENTS.onDisconnected);
    this._logger.info('Successfully disconnected.');
  }
}
<|endoftext|>


<commit_before><commit_msg>BIC-154 # fix `BMP.BIC.hasStorage()` post-refactor<commit_after><|endoftext|>


<commit_before><commit_msg>fix broken tab bar<commit_after><|endoftext|>


<commit_before><commit_msg>Sort alphabetically<commit_after><|endoftext|>


<commit_before>import test from 'ava';

import init from '../initializer';

test('init succeeds given empty defaults and props', (assert) => {
  const ctx = { props: {} };
  const defaults = {};

  const res = init.call(ctx, defaults);
  assert.truthy(res);

  assert.deepEqual(res.initialState, {
    data: [],
    pageProperties: {},
    renderProperties: {
      rowProperties: null,
      columnProperties: {},
    },
    sortProperties: {},
    styleConfig: {},
  });

  assert.is(typeof res.reducers, 'function');
  assert.deepEqual(res.reducers({}, { type: 'REDUCE' }), {});

  assert.deepEqual(res.reduxMiddleware, []);

  assert.deepEqual(ctx.components, {});
  assert.deepEqual(ctx.settingsComponentObjects, {});
  assert.deepEqual(ctx.events, {});
  assert.deepEqual(ctx.selectors, {});
  assert.deepEqual(ctx.listeners, {});
});

test('init returns defaults given minimum props', (assert) => {
  const ctx = { props: { data: [] } };
  const defaults = {
    reducers: { REDUCE: () => ({ reduced: true }) },
    components: { Layout: () => null },
    settingsComponentObjects: { mySettings: { order: 10 } },
    selectors: { aSelector: () => null },
    styleConfig: { classNames: {} },
    pageProperties: { pageSize: 100 },
    initialState: { init: true },
  };

  const res = init.call(ctx, defaults);
  assert.truthy(res);

  assert.deepEqual(res.initialState, {
    init: true,
    data: ctx.props.data,
    pageProperties: defaults.pageProperties,
    renderProperties: {
      rowProperties: null,
      columnProperties: {},
    },
    sortProperties: {},
    styleConfig: defaults.styleConfig,
  });

  assert.is(typeof res.reducers, 'function');
  assert.deepEqual(Object.keys(res.reducers), Object.keys(defaults.reducers));
  assert.deepEqual(res.reducers({}, { type: 'REDUCE' }), { reduced: true });

  assert.deepEqual(res.reduxMiddleware, []);

  assert.deepEqual(ctx.components, defaults.components);
  assert.deepEqual(ctx.settingsComponentObjects, defaults.settingsComponentObjects);
  assert.deepEqual(ctx.events, {});
  assert.deepEqual(ctx.selectors, defaults.selectors);
  assert.deepEqual(ctx.listeners, {});
});

test('init returns expected initialState.data given props.data', (assert) => {
  const ctx = {
    props: {
      data: [{ foo: 'bar' }],
    },
  };
  const defaults = {};

  const res = init.call(ctx, defaults);
  assert.truthy(res);

  assert.deepEqual(res.initialState.data, ctx.props.data);
});
<commit_msg>Test initialState.renderProperties<commit_after>import test from 'ava';

import init from '../initializer';

import { getColumnProperties } from '../columnUtils';
import { getRowProperties } from '../rowUtils';

test('init succeeds given empty defaults and props', (assert) => {
  const ctx = { props: {} };
  const defaults = {};

  const res = init.call(ctx, defaults);
  assert.truthy(res);

  assert.deepEqual(res.initialState, {
    data: [],
    pageProperties: {},
    renderProperties: {
      rowProperties: null,
      columnProperties: {},
    },
    sortProperties: {},
    styleConfig: {},
  });

  assert.is(typeof res.reducers, 'function');
  assert.deepEqual(res.reducers({}, { type: 'REDUCE' }), {});

  assert.deepEqual(res.reduxMiddleware, []);

  assert.deepEqual(ctx.components, {});
  assert.deepEqual(ctx.settingsComponentObjects, {});
  assert.deepEqual(ctx.events, {});
  assert.deepEqual(ctx.selectors, {});
  assert.deepEqual(ctx.listeners, {});
});

test('init returns defaults given minimum props', (assert) => {
  const ctx = { props: { data: [] } };
  const defaults = {
    reducers: { REDUCE: () => ({ reduced: true }) },
    components: { Layout: () => null },
    settingsComponentObjects: { mySettings: { order: 10 } },
    selectors: { aSelector: () => null },
    styleConfig: { classNames: {} },
    pageProperties: { pageSize: 100 },
    initialState: { init: true },
  };

  const res = init.call(ctx, defaults);
  assert.truthy(res);

  assert.deepEqual(res.initialState, {
    init: true,
    data: ctx.props.data,
    pageProperties: defaults.pageProperties,
    renderProperties: {
      rowProperties: null,
      columnProperties: {},
    },
    sortProperties: {},
    styleConfig: defaults.styleConfig,
  });

  assert.is(typeof res.reducers, 'function');
  assert.deepEqual(Object.keys(res.reducers), Object.keys(defaults.reducers));
  assert.deepEqual(res.reducers({}, { type: 'REDUCE' }), { reduced: true });

  assert.deepEqual(res.reduxMiddleware, []);

  assert.deepEqual(ctx.components, defaults.components);
  assert.deepEqual(ctx.settingsComponentObjects, defaults.settingsComponentObjects);
  assert.deepEqual(ctx.events, {});
  assert.deepEqual(ctx.selectors, defaults.selectors);
  assert.deepEqual(ctx.listeners, {});
});

test('init returns expected initialState.data given props.data', (assert) => {
  const ctx = {
    props: {
      data: [{ foo: 'bar' }],
    },
  };
  const defaults = {};

  const res = init.call(ctx, defaults);
  assert.truthy(res);

  assert.deepEqual(res.initialState.data, ctx.props.data);
});

test('init returns expected initialState.renderProperties given props (children, plugins, user)', (assert) => {
  const ctx = {
    props: {
      children: {
        props: {
          children: [{ props: { id: 'foo', order: 1 } }],
        }
      },
      plugins: [
        { renderProperties: { plugin: 0, user: false } },
        { renderProperties: { plugin: 1 } },
      ],
      renderProperties: { user: true },
    },
  };
  const defaults = {};

  const res = init.call(ctx, defaults);
  assert.truthy(res);

  assert.deepEqual(res.initialState.renderProperties, {
    rowProperties: getRowProperties(ctx.props.children),
    columnProperties: getColumnProperties(ctx.props.children),
    plugin: 1,
    user: true,
  });
});
<|endoftext|>


<commit_before>import { retrieveData, insertData, patchData, putData, searchData, deleteData } from '../network'
import { Transaction } from '../../transactions'

/**
* Retrieve a Transaction from the database
* @function retrieve
* @memberof module:api.Transactions
* @static
* @param {object} params - object of parameters:
* @param {number} params.AMId - Asset Manager ID of the Transaction's owner
* @param {string} [params.resourceId] - Transaction ID. Omit to return all Transactions for the supplied AMId
* @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is an Array of Transactions or a single Transaction instance. Omit to return Promise
* @returns {Promise|null} If no callback supplied, returns Promise that resolves with an Array of Transactions or a single Transaction instance
*/
export function retrieve({ AMId, resourceId }, callback) {
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    resourceId
  }
  let promise = retrieveData(params).then(result => {
    if (Array.isArray(result)) {
      result = result.map(tran => _parseTransaction(tran))
    } else {
      result = _parseTransaction(result)
    }
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Insert a new Transaction into the database
 * @function insert
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters:
 * @param {Transaction} params.transaction - Transaction instance or object to insert
 * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the inserted Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the inserted Transaction instance
 */
export function insert({ AMId, transaction }, callback) {
 let data
 if (transaction) {
   data = JSON.parse(JSON.stringify(transaction))
 }
 const params = {
   AMaaSClass: 'transactions',
   AMId,
   data
 }
 let promise = insertData(params).then(result => {
   result = _parseTransaction(result)
   if (typeof callback === 'function') {
     callback(null, result)
   }
   return result
 })
 if (typeof callback !== 'function') {
   // return promise if callback is not provided
   return promise
 }
 promise.catch(error => callback(error))
}

 /**
  * Amend a Transaction
  * @function amend
  * @memberof module:api.Transactions
  * @static
  * @param {object} params - object of parameters:
  * @param {Transaction} params.transaction - The amended Transaction instance
  * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
  * @param {string} params.resourceId - Transaction ID
  * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the amended Transaction instance. Omit to return Promise
  * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the amended Transaction instance
  */
export function amend({ transaction, AMId, resourceId }, callback) {
  let data
  if (transaction) {
    data = JSON.parse(JSON.stringify(transaction))
  }
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    resourceId,
    data
  }
  let promise = putData(params).then(result => {
    result = _parseTransaction(result)
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Partially amend a Transaction
 * @function partialAmend
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters:
 * @param {Transaction} params.changes - object of changes to apply to the Transaction
 * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
 * @param {string} params.resourceId - Transaction ID
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the amended Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the amended Transaction instance
 */
export function partialAmend({ changes, AMId, resourceId }, callback) {
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    resourceId,
    data: changes
  }
  let promise = patchData(params).then(result => {
    result = _parseTransaction(result)
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Search Transactions
 * @function search
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters
 * @param {number} [params.AMId] - Asset Manager ID of the Transactions to search over. If omitted you must pass assetManagerIds in the query
 * @param {object} params.query - Search parameters of the form: { `key`: `[values]` }

 * Available keys are:
 *
clientIds

 *
transactionStatuses

 *
transactionIds

 *
assetBookIds

 *
counterpartyBookIds

 *
assetIds

 *
transactionDateStart

 *
transactionDateEnd

 *
codeTypes

 *
codeValues

 *
linkTypes

 *
linkedTransactionIds

 *
partyTypes

 *
partyIds

 *
referenceTypes

 *
referenceValues

 * e.g. `{ assetManagerIds: [1], bookIds: [1, 2, 3] }`
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is an array of Transactions or a single Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns a Promise that resolves with an array of Transactions or a single Transaction instance
 */
export function search({ AMId, query }, callback) {
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    query
  }
  let promise = searchData(params).then(result => {
    if (Array.isArray(result)) {
      result = result.map(tran => _parseTransaction(tran))
    } else {
      result = _parseTransaction(result)
    }
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Cancel a Transaction
 * @function cancel
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters:
 * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
 * @param {string} params.resourceId - Transaction ID
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the cancelled Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the cancelled Transaction instance. Note that this is the only time the API returns a Transaction instance where transactionStatus === 'Cancelled'
 */
 export function cancel({ AMId, resourceId }, callback) {
   const params = {
     AMaaSClass: 'transactions',
     AMId,
     resourceId
   }
   let promise = deleteData(params).then(result => {
     result = _parseTransaction(result)
     if (typeof callback === 'function') {
       callback(null, result)
     }
     return result
   })
   if (typeof callback !== 'function') {
     return promise
   }
   promise.catch(error => callback(error))
 }

function _parseTransaction(t) {
  return new Transaction(t)
}

<commit_msg>Add fieldsSearch to transaction<commit_after>import { retrieveData, insertData, patchData, putData, searchData, deleteData } from '../network'
import { Transaction } from '../../transactions'

/**
* Retrieve a Transaction from the database
* @function retrieve
* @memberof module:api.Transactions
* @static
* @param {object} params - object of parameters:
* @param {number} params.AMId - Asset Manager ID of the Transaction's owner
* @param {string} [params.resourceId] - Transaction ID. Omit to return all Transactions for the supplied AMId
* @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is an Array of Transactions or a single Transaction instance. Omit to return Promise
* @returns {Promise|null} If no callback supplied, returns Promise that resolves with an Array of Transactions or a single Transaction instance
*/
export function retrieve({ AMId, resourceId }, callback) {
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    resourceId
  }
  let promise = retrieveData(params).then(result => {
    if (Array.isArray(result)) {
      result = result.map(tran => _parseTransaction(tran))
    } else {
      result = _parseTransaction(result)
    }
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Insert a new Transaction into the database
 * @function insert
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters:
 * @param {Transaction} params.transaction - Transaction instance or object to insert
 * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the inserted Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the inserted Transaction instance
 */
export function insert({ AMId, transaction }, callback) {
 let data
 if (transaction) {
   data = JSON.parse(JSON.stringify(transaction))
 }
 const params = {
   AMaaSClass: 'transactions',
   AMId,
   data
 }
 let promise = insertData(params).then(result => {
   result = _parseTransaction(result)
   if (typeof callback === 'function') {
     callback(null, result)
   }
   return result
 })
 if (typeof callback !== 'function') {
   // return promise if callback is not provided
   return promise
 }
 promise.catch(error => callback(error))
}

 /**
  * Amend a Transaction
  * @function amend
  * @memberof module:api.Transactions
  * @static
  * @param {object} params - object of parameters:
  * @param {Transaction} params.transaction - The amended Transaction instance
  * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
  * @param {string} params.resourceId - Transaction ID
  * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the amended Transaction instance. Omit to return Promise
  * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the amended Transaction instance
  */
export function amend({ transaction, AMId, resourceId }, callback) {
  let data
  if (transaction) {
    data = JSON.parse(JSON.stringify(transaction))
  }
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    resourceId,
    data
  }
  let promise = putData(params).then(result => {
    result = _parseTransaction(result)
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Partially amend a Transaction
 * @function partialAmend
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters:
 * @param {Transaction} params.changes - object of changes to apply to the Transaction
 * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
 * @param {string} params.resourceId - Transaction ID
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the amended Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the amended Transaction instance
 */
export function partialAmend({ changes, AMId, resourceId }, callback) {
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    resourceId,
    data: changes
  }
  let promise = patchData(params).then(result => {
    result = _parseTransaction(result)
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Search Transactions
 * @function search
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters
 * @param {number} [params.AMId] - Asset Manager ID of the Transactions to search over. If omitted you must pass assetManagerIds in the query
 * @param {object} params.query - Search parameters of the form: { `key`: `[values]` }

 * Available keys are:
 *
clientIds

 *
transactionStatuses

 *
transactionIds

 *
assetBookIds

 *
counterpartyBookIds

 *
assetIds

 *
transactionDateStart

 *
transactionDateEnd

 *
codeTypes

 *
codeValues

 *
linkTypes

 *
linkedTransactionIds

 *
partyTypes

 *
partyIds

 *
referenceTypes

 *
referenceValues

 * e.g. `{ assetManagerIds: [1], bookIds: [1, 2, 3] }`
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is an array of Transactions or a single Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns a Promise that resolves with an array of Transactions or a single Transaction instance
 */
export function search({ AMId, query }, callback) {
  const params = {
    AMaaSClass: 'transactions',
    AMId,
    query
  }
  let promise = searchData(params).then(result => {
    if (Array.isArray(result)) {
      result = result.map(tran => _parseTransaction(tran))
    } else {
      result = _parseTransaction(result)
    }
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Search for Transaction with specified fields
 * @function fieldsSearch
 * @memberof module:api.Positions
 * @static
 * @param {object} params - object of parameters:
 * @param {number} [params.AMId] - Asset Manager ID of the Assets to search over. If omitted, you must send assetManagerIds in the search query with at least one value
 * @param {number} [params.assetId] -Asset ID of the asset
 * @param {string} [params.field] -Fields should be returned
 * Available keys are:
 *
assetManagerIds (Required if AMId param is omitted)

 *
bookIds

 *
counterpartyBookId

 *
transactionAction

 *
assetIds

 *
quantity

 *
transactionDate

 *
settlementDate

 *
price

 *
transactionCurrency

 *
settlementCurrency

 *
asset

 *
executionTime

 *
transactionType

 *
transactionId

 *
transactionStatus

 *
charges

 *
codes

 *
comments

 *
links

 *
parties

 *
rates

 *
references

 *
postings

 * e.g. `{ AMIds: [1], assetIds: [1, 2], fields: [assetManagerIds, assetIds, transactionType] }`
 * @param {function} callback - Called with two arguments (error, result) on completion. `result` is an array of Assets or a single Asset instance
 * @returns {Promise|null} If no callback supplied, returns a Promise that resolves with an array of Assets or a single Asset instance
 */
export function fieldsSearch({ AMIds, assetIds, fields }, callback) {
  const params = {
    AMaaSClass: 'transactions',
    AMIds,
    assetIds,
    fields
  }

  let promise = searchData (params).then(result => {
    if (Array.isArray(result)) {
      result = result.map(tran => _parseTransaction(tran))
    } else {
      result = _parseTransaction(result)
    }
    if(typeof callback === 'function'){
       callback(null, result)
    }
    return result
  })
  if (typeof callback !== 'function') {
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Cancel a Transaction
 * @function cancel
 * @memberof module:api.Transactions
 * @static
 * @param {object} params - object of parameters:
 * @param {number} params.AMId - Asset Manager ID of the Transaction's owner
 * @param {string} params.resourceId - Transaction ID
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is the cancelled Transaction instance. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns Promise that resolves with the cancelled Transaction instance. Note that this is the only time the API returns a Transaction instance where transactionStatus === 'Cancelled'
 */
 export function cancel({ AMId, resourceId }, callback) {
   const params = {
     AMaaSClass: 'transactions',
     AMId,
     resourceId
   }
   let promise = deleteData(params).then(result => {
     result = _parseTransaction(result)
     if (typeof callback === 'function') {
       callback(null, result)
     }
     return result
   })
   if (typeof callback !== 'function') {
     return promise
   }
   promise.catch(error => callback(error))
 }

function _parseTransaction(t) {
  return new Transaction(t)
}

<|endoftext|>


<commit_before>import React from "react";
import { Log } from "../victory-util/index";

export default class RenderInPortal extends React.Component {
  static propTypes = {
    children: React.PropTypes.node
  };

  static contextTypes = {
    portalUpdate: React.PropTypes.func,
    portalRegister: React.PropTypes.func,
    portalDeregister: React.PropTypes.func
  }

  componentDidUpdate() {
    if (!this.portalKey) {
      this.portalKey = this.context.portalRegister();
    }
    if (!this.checkedContext) {
      if (typeof this.context.portalUpdate !== "function") {
        const msg = "`renderInPortal` is not supported outside of `VictoryContainer`. " +
          "Component will be rendered in place";
        Log.warn(msg);
        this.renderInPlace = true;
      }
      this.checkedContext = true;
    }
    this.context.portalUpdate(this.portalKey, this.element);
  }

  componentWillUnmount() {
    this.context.portalDeregister(this.portalKey);
  }

  render() {
    const child = React.cloneElement(this.props.children, {renderInPortal: false});
    if (this.renderInPlace) {
      return child;
    }
    this.element = child;
    return null;
  }
}

<commit_msg>fix logic order<commit_after>import React from "react";
import { Log } from "../victory-util/index";

export default class RenderInPortal extends React.Component {
  static propTypes = {
    children: React.PropTypes.node
  };

  static contextTypes = {
    portalUpdate: React.PropTypes.func,
    portalRegister: React.PropTypes.func,
    portalDeregister: React.PropTypes.func
  }

  componentDidUpdate() {
    if (!this.checkedContext) {
      if (typeof this.context.portalUpdate !== "function") {
        const msg = "`renderInPortal` is not supported outside of `VictoryContainer`. " +
          "Component will be rendered in place";
        Log.warn(msg);
        this.renderInPlace = true;
      }
      this.checkedContext = true;
    }
    if (!this.renderInPlace) {
      this.portalKey = this.portalKey || this.context.portalRegister();
      this.context.portalUpdate(this.portalKey, this.element);
    }
  }

  componentWillUnmount() {
    this.context.portalDeregister(this.portalKey);
  }

  render() {
    const child = React.cloneElement(this.props.children, {renderInPortal: false});
    if (this.renderInPlace) {
      return child;
    }
    this.element = child;
    return null;
  }
}

<|endoftext|>


<commit_before><commit_msg>Update core module<commit_after><|endoftext|>


<commit_before>import * as types from './mutation-types'
import Promise from 'bluebird'
import { mergeMetaAttributes } from '../../../services/collectionHelper'
import Vue from 'vue'

export default {
  [types.CREATE_COLLECTION]({ state }, { index }) {
    return Vue.prototype.$kuzzle.query(
      {
        controller: 'collection',
        action: 'create'
      },
      {
        collection: state.name,
        index,
        body: mergeMetaAttributes({
          mapping: state.mapping,
          schema: state.schema,
          allowForm: state.allowForm
        })
      }
    )
  },
  [types.UPDATE_COLLECTION]({ state }, { index }) {
    if (state.isRealtimeOnly) {
      return Promise.resolve()
    }

    return Vue.prototype.$kuzzle.query(
      {
        controller: 'collection',
        action: 'updateMapping',
        collection: state.name,
        index,
        body: mergeMetaAttributes({
          mapping: state.mapping,
          schema: state.schema,
          allowForm: state.allowForm
        })
      }
    )
  },
  async [types.FETCH_COLLECTION_DETAIL](
    { commit, getters, dispatch },
    { index, collection }
  ) {
    if (!collection) {
      commit(types.RESET_COLLECTION_DETAIL)
      return
    }

    if (getters.indexCollections(index).stored.indexOf(collection) !== -1) {
      const response = await Vue.prototype.$kuzzle.collection.getMapping(index, collection)
      let result = response[index].mappings[collection]
      let schema = {}
      let allowForm = false

      if (result._meta) {
        schema = result._meta.schema || {}
        allowForm = result._meta.allowForm || false
      }

      dispatch(types.GET_COLLECTION_DEFAULT_VIEW_JSON, {
        index,
        collection
      })

      commit(types.RECEIVE_COLLECTION_DETAIL, {
        name: collection,
        mapping: result.properties || {},
        schema,
        allowForm,
        isRealtimeOnly: false
      })
    }

    if (getters.indexCollections(index).realtime.indexOf(collection) !== -1) {
      commit(types.RECEIVE_COLLECTION_DETAIL, {
        name: collection,
        mapping: {},
        isRealtimeOnly: true,
        schema: {},
        allowForm: false
      })
    }
  },
  [types.GET_COLLECTION_DEFAULT_VIEW_JSON](
    { dispatch },
    { index, collection }
  ) {
    let indexes = JSON.parse(localStorage.getItem('defaultJsonView') || '{}')
    if (!indexes[index]) {
      return dispatch(types.SET_COLLECTION_DEFAULT_VIEW_JSON, {
        index,
        collection,
        jsonView: false
      })
    }

    return dispatch(types.SET_COLLECTION_DEFAULT_VIEW_JSON, {
      index,
      collection,
      jsonView: indexes[index][collection] || false
    })
  },
  [types.SET_COLLECTION_DEFAULT_VIEW_JSON](
    { commit },
    { index, collection, jsonView }
  ) {
    let indexes = JSON.parse(localStorage.getItem('defaultJsonView') || '{}')
    if (!indexes[index]) {
      indexes[index] = {}
    }

    indexes[index][collection] = jsonView

    localStorage.setItem('defaultJsonView', JSON.stringify(indexes))
    return commit(types.SET_COLLECTION_DEFAULT_VIEW_JSON, { jsonView })
  },
  async [types.CLEAR_COLLECTION]({ state }, { index }) {
    await Vue.prototype.$kuzzle
      .query(
        {
          controller: 'collection',
          action: 'truncate',
          index,
          collection: state.name,
          refresh: 'wait_for'
        }
      )
  }
}
<commit_msg>call createCollection from collection controller<commit_after>import * as types from './mutation-types'
import Promise from 'bluebird'
import { mergeMetaAttributes } from '../../../services/collectionHelper'
import Vue from 'vue'

export default {
  [types.CREATE_COLLECTION]({ state }, { index }) {
    return Vue.prototype.$kuzzle
      .collection
      .create(index, state.name, mergeMetaAttributes({
        mapping: state.mapping,
        schema: state.schema,
        allowForm: state.allowForm
      }))
  },
  [types.UPDATE_COLLECTION]({ state }, { index }) {
    if (state.isRealtimeOnly) {
      return Promise.resolve()
    }

    return Vue.prototype.$kuzzle.query(
      {
        controller: 'collection',
        action: 'updateMapping',
        collection: state.name,
        index,
        body: mergeMetaAttributes({
          mapping: state.mapping,
          schema: state.schema,
          allowForm: state.allowForm
        })
      }
    )
  },
  async [types.FETCH_COLLECTION_DETAIL](
    { commit, getters, dispatch },
    { index, collection }
  ) {
    if (!collection) {
      commit(types.RESET_COLLECTION_DETAIL)
      return
    }

    if (getters.indexCollections(index).stored.indexOf(collection) !== -1) {
      const response = await Vue.prototype.$kuzzle.collection.getMapping(index, collection)
      let result = response[index].mappings[collection]
      let schema = {}
      let allowForm = false

      if (result._meta) {
        schema = result._meta.schema || {}
        allowForm = result._meta.allowForm || false
      }

      dispatch(types.GET_COLLECTION_DEFAULT_VIEW_JSON, {
        index,
        collection
      })

      commit(types.RECEIVE_COLLECTION_DETAIL, {
        name: collection,
        mapping: result.properties || {},
        schema,
        allowForm,
        isRealtimeOnly: false
      })
    }

    if (getters.indexCollections(index).realtime.indexOf(collection) !== -1) {
      commit(types.RECEIVE_COLLECTION_DETAIL, {
        name: collection,
        mapping: {},
        isRealtimeOnly: true,
        schema: {},
        allowForm: false
      })
    }
  },
  [types.GET_COLLECTION_DEFAULT_VIEW_JSON](
    { dispatch },
    { index, collection }
  ) {
    let indexes = JSON.parse(localStorage.getItem('defaultJsonView') || '{}')
    if (!indexes[index]) {
      return dispatch(types.SET_COLLECTION_DEFAULT_VIEW_JSON, {
        index,
        collection,
        jsonView: false
      })
    }

    return dispatch(types.SET_COLLECTION_DEFAULT_VIEW_JSON, {
      index,
      collection,
      jsonView: indexes[index][collection] || false
    })
  },
  [types.SET_COLLECTION_DEFAULT_VIEW_JSON](
    { commit },
    { index, collection, jsonView }
  ) {
    let indexes = JSON.parse(localStorage.getItem('defaultJsonView') || '{}')
    if (!indexes[index]) {
      indexes[index] = {}
    }

    indexes[index][collection] = jsonView

    localStorage.setItem('defaultJsonView', JSON.stringify(indexes))
    return commit(types.SET_COLLECTION_DEFAULT_VIEW_JSON, { jsonView })
  },
  async [types.CLEAR_COLLECTION]({ state }, { index }) {
    await Vue.prototype.$kuzzle
      .query(
        {
          controller: 'collection',
          action: 'truncate',
          index,
          collection: state.name,
          refresh: 'wait_for'
        }
      )
  }
}
<|endoftext|>


<commit_before>const moment = require('moment');
const Discord = require("discord.js");
const bot = new Discord.Client();

bot.set = require(__dirname+'/bot.json');

global.bot = bot;
global.ys = require(__dirname+'util.js');

bot.on('ready', function() {
  bot.user.setPresence({status: 'online', game:{ name:`${bot.set.prefix}help - ${bot.guilds.size} Servers`}});
  console.log(`${bot.users.size} users, in ${bot.channels.size} channels of ${bot.guilds.size} servers`);
  bot.start = moment().valueOf();
});

bot.login(bot.set.token);
<commit_msg>Update yasashii.js<commit_after>const moment = require('moment');
const Discord = require("discord.js");
const bot = new Discord.Client();

bot.set = require(__dirname+'/bot.json');
bot.commands = fs.readdirSync(__dirname+'/commands/');

global.bot = bot;
global.ys = require(__dirname+'util.js');

bot.on('ready', function() {
  bot.user.setPresence({status: 'online', game:{ name:`${bot.set.prefix}help - ${bot.guilds.size} Servers`}});
  console.log(`${bot.users.size} users, in ${bot.channels.size} channels of ${bot.guilds.size} servers`);
  bot.start = moment().valueOf();
});

bot.on('message', function() {
  if (m.author.bot === true) return;
	if (m.channel.type === "dm") return;

  if(m.content.startsWith(bot.set.prefix)) {
    var command = m.content.split(" ")[0].replace(bot.set.prefix, "");
    if (bot.commands.indexOf(command+'.js') > -1) {
      var cmd = reload(__dirname+'/commands/'+command+'.js');
      var args = m.content.substring((bot.set.prefix).length+command.length+1);
    }
  }
});

bot.login(bot.set.token);
<|endoftext|>


<commit_before>import Inferno   from 'inferno'
import Component from 'inferno-component'
import styled    from 'styled-components'
import { bind } from 'decko'

import { lightTheme } from '@slup/theming'

const Drawer = styled.div`
  z-index: 1000;
  transition: max-width 150ms linear, transform 320ms cubic-bezier(0.4, 0.0, 0.2, 1);
  height: 100%;
  width: calc(100% - 64px);
  max-width: 320px;
  background: ${props => props.theme.background || lightTheme.background};
  box-shadow: 0px 8px 10px -5px rgba(0, 0, 0, 0.2),
    0px 16px 24px 2px rgba(0, 0, 0, 0.14),
    0px 6px 30px 5px rgba(0, 0, 0, 0.12);
  position: fixed;
  top: 0;
  left: ${props => props.right ? 'auto' : '0'};
  right: ${props => props.right ? '0' : 'auto'};
  transform: ${props => props.responsive || props.permanent
    ? 'translateX(0)'
    : props.right && !props.opened
      ? 'translateX(105%)'
      : props.opened
        ? 'translateX(0)'
        : 'translateX(-105%)'
  };

  @media only screen and (max-width: 960px) {
    width: calc(100% - 56px);
    max-width: 280px;
    transform: ${props => props.right && !props.opened
      ? 'translateX(105%)'
      : props.opened
        ? 'translateX(0)'
        : 'translateX(-105%)'
    };
  }
`

const Overlay = styled.div`
  display: ${props => props.responsive || props.permanent ? 'none' : 'block'};
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0; left: 0;
  right: 0; bottom: 0;
  z-index: 999;
  opacity: .48;
  transition: background 320ms linear;
  pointer-events: ${props => props.opened  ? 'auto' : 'none'};
  background: ${props => props.opened  ? 'rgb(33, 33, 33)' : 'transparent'};

  @media only screen and (max-width: 960px) {
    display: block;
  }
`

export class Sidenav extends Component {

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyDown)
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyDown)
  }

  @bind
  handleKeyDown({ keyCode }) {
    if (this.props.opened && keyCode == 27) {
      this.props.onClose()
    }
  }

  @bind
  handleClick(e) {
    if(this.props.onClose) {
      this.props.onClose(e)
    }
  }

  render(props) {
    return (

        <Drawer {...props} />
        {props.overlay == false
          ? null
          : <Overlay
            opened={props.opened}
            permanent={props.permanent}
            responsive={props.responsive}
            onClick={this.handleClick} />
        }

    )
  }
}
<commit_msg>:bug: Fixed bug with the 'permanent' prop in the sidenav<commit_after>import Inferno   from 'inferno'
import Component from 'inferno-component'
import styled    from 'styled-components'
import { bind } from 'decko'

import { lightTheme } from '@slup/theming'

const Drawer = styled.div`
  z-index: 1000;
  transition: max-width 150ms linear, transform 320ms cubic-bezier(0.4, 0.0, 0.2, 1);
  height: 100%;
  width: calc(100% - 64px);
  max-width: 320px;
  background: ${props => props.theme.background || lightTheme.background};
  box-shadow: 0px 8px 10px -5px rgba(0, 0, 0, 0.2),
    0px 16px 24px 2px rgba(0, 0, 0, 0.14),
    0px 6px 30px 5px rgba(0, 0, 0, 0.12);
  position: fixed;
  top: 0;
  left: ${props => props.right ? 'auto' : '0'};
  right: ${props => props.right ? '0' : 'auto'};
  transform: ${props => props.responsive || props.permanent
    ? 'translateX(0)'
    : props.right && !props.opened
      ? 'translateX(105%)'
      : props.opened
        ? 'translateX(0)'
        : 'translateX(-105%)'
  };

  @media only screen and (max-width: 960px) {
    width: calc(100% - 56px);
    max-width: 280px;
    transform: ${props => props.right && !props.opened
      ? 'translateX(105%)'
      : props.opened || props.permanent
        ? 'translateX(0)'
        : 'translateX(-105%)'
    };
  }
`

const Overlay = styled.div`
  display: ${props => props.responsive || props.permanent ? 'none' : 'block'};
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0; left: 0;
  right: 0; bottom: 0;
  z-index: 999;
  opacity: .48;
  transition: background 320ms linear;
  pointer-events: ${props => props.opened  ? 'auto' : 'none'};
  background: ${props => props.opened  ? 'rgb(33, 33, 33)' : 'transparent'};

  @media only screen and (max-width: 960px) {
    display: block;
  }
`

export class Sidenav extends Component {

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyDown)
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyDown)
  }

  @bind
  handleKeyDown({ keyCode }) {
    if (this.props.opened && keyCode == 27) {
      this.props.onClose()
    }
  }

  @bind
  handleClick(e) {
    if(this.props.onClose) {
      this.props.onClose(e)
    }
  }

  render(props) {
    return (

        <Drawer {...props} />
        {props.overlay == false
          ? null
          : <Overlay
            opened={props.opened}
            permanent={props.permanent}
            responsive={props.responsive}
            onClick={this.handleClick} />
        }

    )
  }
}
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, Text, StyleSheet, TouchableOpacityPropTypes } from 'react-native';
import { getAdjustedStyle } from './utilities';

/**
 * Renders a cell with value (or renderChildren) that is touchable
 *
 * @param {string|number} value The value to render in cell
 * @param {string|number} rowKey Unique key associated to row cell is in
 * @param {string|number} columnKey Unique key associated to column cell is in
 * @param {func} onPressAction Action creator for handling focusing of this cell.
 *                          `(rowKey, columnKey) => {...}`
 * @param {func} dispatch Reducer dispatch callback for handling actions
 * @param {func} renderChildren Reducer dispatch callback for handling actions
 * @param {func} TouchableComponent Override containing element of TouchableCell
 * Additional props spread into TouchableComponent
 * @param {object} containerStyle Style object for the containing Touchable component
 * @param {object} textStyle Style object for the inner Text component
 */
const TouchableCell = React.memo(
  ({
    value,
    rowKey,
    columnKey,
    onPressAction,
    dispatch,
    renderChildren,
    TouchableComponent,
    containerStyle,
    width,
    textStyle,
    isLastCell,
    ...otherProps
  }) => {
    console.log(`- TouchableCell: ${rowKey},${columnKey}`);

    const onPress = () => {
      dispatch(onPressAction(rowKey, columnKey));
    };

    const internalContainerStyle = getAdjustedStyle(containerStyle, width, isLastCell);
    const Container = TouchableComponent || TouchableOpacity;
    const content = renderChildren ? renderChildren(value) : <Text style={textStyle}>{value}</Text>;

    return (
      <Container style={internalContainerStyle} onPress={onPress} {...otherProps}>
        {content}
      </Container>
    );
  }
);

const defaultStyles = StyleSheet.create({
  containerStyle: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  textStyle: {},
});

TouchableCell.propTypes = {
  ...TouchableOpacityPropTypes,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  rowKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
  columnKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
  onPressAction: PropTypes.func.isRequired,
  dispatch: PropTypes.func.isRequired,
  renderChildren: PropTypes.func.isRequired,
  TouchableComponent: PropTypes.func.isRequired,
  containerStyle: PropTypes.object,
  textStyle: PropTypes.object,
  isLastCell: PropTypes.bool,
};

TouchableCell.defaultProps = {
  value: '',
  containerStyle: defaultStyles.containerStyle,
  textStyle: defaultStyles.textStyle,
  isLastCell: false,
};

export default TouchableCell;
<commit_msg>Add fix for TouchableCell propType<commit_after>/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, Text, StyleSheet, TouchableOpacityPropTypes } from 'react-native';
import { getAdjustedStyle } from './utilities';

/**
 * Renders a cell with value (or renderChildren) that is touchable
 *
 * @param {string|number} value The value to render in cell
 * @param {string|number} rowKey Unique key associated to row cell is in
 * @param {string|number} columnKey Unique key associated to column cell is in
 * @param {func} onPressAction Action creator for handling focusing of this cell.
 *                          `(rowKey, columnKey) => {...}`
 * @param {func} dispatch Reducer dispatch callback for handling actions
 * @param {func} renderChildren Reducer dispatch callback for handling actions
 * @param {func} TouchableComponent Override containing element of TouchableCell
 * Additional props spread into TouchableComponent
 * @param {object} containerStyle Style object for the containing Touchable component
 * @param {object} textStyle Style object for the inner Text component
 */
const TouchableCell = React.memo(
  ({
    value,
    rowKey,
    columnKey,
    onPressAction,
    dispatch,
    renderChildren,
    TouchableComponent,
    containerStyle,
    width,
    textStyle,
    isLastCell,
    ...otherProps
  }) => {
    console.log(`- TouchableCell: ${rowKey},${columnKey}`);

    const onPress = () => {
      dispatch(onPressAction(rowKey, columnKey));
    };

    const internalContainerStyle = getAdjustedStyle(containerStyle, width, isLastCell);
    const Container = TouchableComponent || TouchableOpacity;
    const content = renderChildren ? renderChildren(value) : <Text style={textStyle}>{value}</Text>;

    return (
      <Container style={internalContainerStyle} onPress={onPress} {...otherProps}>
        {content}
      </Container>
    );
  }
);

const defaultStyles = StyleSheet.create({
  containerStyle: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  textStyle: {},
});

TouchableCell.propTypes = {
  ...TouchableOpacityPropTypes,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  rowKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
  columnKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
  onPressAction: PropTypes.func.isRequired,
  dispatch: PropTypes.func.isRequired,
  renderChildren: PropTypes.func.isRequired,
  TouchableComponent: PropTypes.node,
  containerStyle: PropTypes.object,
  textStyle: PropTypes.object,
  isLastCell: PropTypes.bool,
};

TouchableCell.defaultProps = {
  value: '',
  containerStyle: defaultStyles.containerStyle,
  textStyle: defaultStyles.textStyle,
  isLastCell: false,
  TouchableComponent: null,
};

export default TouchableCell;
<|endoftext|>


<commit_before>var _ = require('underscore');

var mapping = [
		'ad',
		'ga',
		'pop'
	],
	replaceList = '1234567890';

module.exports = function(str) {
	if (!str) {
		return str;
	}

	_.each(mapping, function(value) {
		str = str.replace(value, replaceList.slice(0, value.length));
	});

	return str;
}<commit_msg>Code refactoring<commit_after>var replaceList = '1234567890';

module.exports = function(str) {
	if (!str) {
		return str;
	}

	return ('' + str).replace(/ad|ga|pop/gi, function(match) {
		return replaceList.slice(0, match.length);
	});
}<|endoftext|>


<commit_before><commit_msg>bug fix in how git owner and repo name are constructed.<commit_after><|endoftext|>


<commit_before><commit_msg>change third test file from must to should<commit_after><|endoftext|>


<commit_before><commit_msg>Added achievement test<commit_after><|endoftext|>


<commit_before><commit_msg>parse sound and picture<commit_after><|endoftext|>


<commit_before>import _ from 'underscore';

describe('Browse Views', function () {

    context('Test /browse/ page redirection from homepage', function(){
        /*
        before(function(){
            cy.visit('/');
        });
        */

        it('If start from home page, clicking on Browse nav menu item gets us to Browse page.', function(){

            cy.visit('/');

            cy.get('#sBrowse').click().then(()=>{
                cy.get('#page-title-container .page-title span.title').should('have.text', 'Data Browser');
            });

        });

        it('Only shows award.project=4DN results.', function(){

            cy.location('search').should('include', 'award.project=4DN');

        });

        it('If point browser to /browse/ page (no URL params), we also get redirected to award.project=4DN correctly.', function(){

            cy.visit('/');
            cy.visit('/browse/', { "failOnStatusCode" : false });

            cy.location('search').should('include', 'award.project=4DN');

        });

    });

    context('QuickInfoBar', function(){

        it('Test that QuickInfoBar counts change re: logging in', function(){

            cy.visit('/browse/', { "failOnStatusCode" : false });
            cy.getQuickInfoBarCounts().then((counts)=>{

                const loggedOutCounts = _.clone(counts);

                cy.login4DN().then(()=>{
                    cy.getQuickInfoBarCounts().its('experiment_sets').should('be.greaterThan', loggedOutCounts.experiment_sets);
                });

            });

        });

    });

});
<commit_msg>Ongoing<commit_after>import _ from 'underscore';

describe('Browse Views', function () {

    context.skip('Test /browse/ page redirection from homepage', function(){
        /*
        before(function(){
            cy.visit('/');
        });
        */

        it('If start from home page, clicking on Browse nav menu item gets us to Browse page.', function(){

            cy.visit('/');

            cy.get('#sBrowse').click().then(()=>{
                cy.get('#page-title-container .page-title span.title').should('have.text', 'Data Browser');
            });

        });

        it('Only shows award.project=4DN results & "Include External Data" is off', function(){

            cy.location('search').should('include', 'award.project=4DN');
            cy.get('#stats .browse-base-state-toggle-container input[type="checkbox"]').should('not.be.checked');

        });

        it('If point browser to /browse/ page (no URL params), we also get redirected to award.project=4DN correctly.', function(){

            cy.visit('/');
            cy.visit('/browse/', { "failOnStatusCode" : false });

            cy.location('search').should('include', 'award.project=4DN');

        });

    });

    context('QuickInfoBar & BarPlotChart', function(){

        before(function(){
            cy.clearCookies();
        });

        beforeEach(function(){
            Cypress.Cookies.preserveOnce(); // @see https://docs.cypress.io/api/cypress-api/cookies.html#Preserve-Once
            Cypress.Cookies.defaults({
                whitelist: [ "jwtToken", "searchSessionID" ]
            });
        });

        afterEach(function(){
            Cypress.Cookies.preserveOnce(); // @see https://docs.cypress.io/api/cypress-api/cookies.html#Preserve-Once
        });

        it('Login & test that QuickInfoBar counts changed, that we have BarPlot bars', function(){

            cy.visit('/browse/', { "failOnStatusCode" : false });
            cy.getQuickInfoBarCounts().then((counts)=>{

                const loggedOutCounts = _.clone(counts);

                cy.login4DN().then(()=>{
                    cy.getQuickInfoBarCounts().its('experiment_sets').should('be.greaterThan', loggedOutCounts.experiment_sets);
                });

            });

        });

        it('Ensure we have some BarPlot bars', function(){

            cy.get('.bar-plot-chart .chart-bar').should('have.length.above', 0);
            cy.wait(1000).visit('/browse/', { "failOnStatusCode" : false });

        });

    });

});
<|endoftext|>


<commit_before><commit_msg>converts content of imported files to matrix<commit_after><|endoftext|>


<commit_before>/**
 * doodle.js - for drawing with the mouse
 *
 * @author Nicolas CARPi <nicolas.carpi@curie.fr>
 * @copyright 2012 Nicolas CARPi
 * @see https://www.elabftw.net Official website
 * @license AGPL-3.0
 * @package elabftw
 */
(function() {
    'use strict';

    $(document).ready(function() {
        $('.canvasDiv').hide();
        $(document).on('click', '.toggleCanvas', function() {
            $('.canvasDiv').toggle();
        });
        $(document).on('click', '.clearCanvas', function() {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height);
            clickX = [];
            clickY = [];
            clickDrag = [];
        });

        $(document).on('click', '.saveCanvas', function() {
            var image = ($('#doodleCanvas')[0]).toDataURL();
            var type = $(this).data('type');
            var id = $(this).data('id');
            $.post('app/controllers/EntityAjaxController.php', {
                addFromString: true,
                type: type,
                id: id,
                fileType: 'png',
                string: image
            }).done(function() {
                if (type === 'items') {
                    type = 'database';
                }
                $('#filesdiv').load(type + '.php?mode=edit&id=' + id + ' #filesdiv');
                notif('Saved', 'ok');
            });
        });

        // code from http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
        var clickX = [];
        var clickY = [];
        var clickDrag = [];
        var paint;
        var context = document.getElementById('doodleCanvas').getContext('2d');

        $('#doodleCanvas').mousedown(function(e){
            paint = true;
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
            redraw();
        });
        $('#doodleCanvas').mousemove(function(e){
            if (paint) {
                addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                redraw();
            }
        });
        $('#doodleCanvas').mouseup(function(){
            paint = false;
        });
        $('#doodleCanvas').mouseleave(function(){
            paint = false;
        });

        function addClick(x, y, dragging)
        {
            clickX.push(x);
            clickY.push(y);
            clickDrag.push(dragging);
        }
        function redraw() {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height);

            context.strokeStyle = '#29AEB9';
            context.lineJoin = 'round';
            context.lineWidth = 5;

            for (var i=0; i < clickX.length; i++) {
                context.beginPath();
                if (clickDrag[i] && i){
                    context.moveTo(clickX[i-1], clickY[i-1]);
                } else {
                    context.moveTo(clickX[i]-1, clickY[i]);
                }
                context.lineTo(clickX[i], clickY[i]);
                context.closePath();
                context.stroke();
            }
        }
    });
}());
<commit_msg>fix notif call on doodle<commit_after>/**
 * doodle.js - for drawing with the mouse
 *
 * @author Nicolas CARPi <nicolas.carpi@curie.fr>
 * @copyright 2012 Nicolas CARPi
 * @see https://www.elabftw.net Official website
 * @license AGPL-3.0
 * @package elabftw
 */
(function() {
    'use strict';

    $(document).ready(function() {
        $('.canvasDiv').hide();
        $(document).on('click', '.toggleCanvas', function() {
            $('.canvasDiv').toggle();
        });
        $(document).on('click', '.clearCanvas', function() {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height);
            clickX = [];
            clickY = [];
            clickDrag = [];
        });

        $(document).on('click', '.saveCanvas', function() {
            var image = ($('#doodleCanvas')[0]).toDataURL();
            var type = $(this).data('type');
            var id = $(this).data('id');
            $.post('app/controllers/EntityAjaxController.php', {
                addFromString: true,
                type: type,
                id: id,
                fileType: 'png',
                string: image
            }).done(function(json) {
                if (type === 'items') {
                    type = 'database';
                }
                $('#filesdiv').load(type + '.php?mode=edit&id=' + id + ' #filesdiv');
                notif(json);
            });
        });

        // code from http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
        var clickX = [];
        var clickY = [];
        var clickDrag = [];
        var paint;
        var context = document.getElementById('doodleCanvas').getContext('2d');

        $('#doodleCanvas').mousedown(function(e){
            paint = true;
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
            redraw();
        });
        $('#doodleCanvas').mousemove(function(e){
            if (paint) {
                addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                redraw();
            }
        });
        $('#doodleCanvas').mouseup(function(){
            paint = false;
        });
        $('#doodleCanvas').mouseleave(function(){
            paint = false;
        });

        function addClick(x, y, dragging)
        {
            clickX.push(x);
            clickY.push(y);
            clickDrag.push(dragging);
        }
        function redraw() {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height);

            context.strokeStyle = '#29AEB9';
            context.lineJoin = 'round';
            context.lineWidth = 5;

            for (var i=0; i < clickX.length; i++) {
                context.beginPath();
                if (clickDrag[i] && i){
                    context.moveTo(clickX[i-1], clickY[i-1]);
                } else {
                    context.moveTo(clickX[i]-1, clickY[i]);
                }
                context.lineTo(clickX[i], clickY[i]);
                context.closePath();
                context.stroke();
            }
        }
    });
}());
<|endoftext|>


<commit_before>odoo.define('web_kanban.Column', function (require) {
"use strict";

var core = require('web.core');
var Dialog = require('web.Dialog');
var form_common = require('web.form_common');
var Widget = require('web.Widget');
var quick_create = require('web_kanban.quick_create');
var KanbanRecord = require('web_kanban.Record');

var _t = core._t;
var QWeb = core.qweb;
var RecordQuickCreate = quick_create.RecordQuickCreate;

var KanbanColumn = Widget.extend({
    template: "KanbanView.Group",

    events: {
        'click .o_kanban_toggle_fold': function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.folded = true;
            this.update_column();
        },
        'click .o_column_edit': 'edit_column',
        'click .o_column_delete': 'delete_column',
        'click .o_column_archive': 'archive_records',
        'click .o_column_unarchive': 'unarchive_records',
        'click .o_kanban_quick_add': 'add_quick_create',
        'click .o_kanban_load_more': 'load_more',
    },

    custom_events: {
        'kanban_record_delete': 'delete_record',
        'cancel_quick_create': 'cancel_quick_create',
        'quick_create_add_record': 'quick_create_add_record',
    },

    init: function(parent, group_data, options, record_options) {
        this._super(parent);
        this.data_records = group_data.records;
        this.dataset = group_data.dataset;
        this.records = [];
        this.title = group_data.title;
        this.id = group_data.id;
        this.folded = group_data.attributes.folded;
        this.fields = options.fields;
        this.values = group_data.values;

        this.quick_create = options.quick_create;
        this.grouped_by_m2o = options.grouped_by_m2o;
        this.editable = options.editable;
        this.deletable = options.deletable;
        this.has_active_field = options.has_active_field;
        this.records_editable = options.records_editable;
        this.records_deletable = options.records_deletable;
        this.relation = options.relation;
        this.offset = 0;
        this.remaining = this.dataset.size() - this.data_records.length;

        this.record_options = _.extend(_.clone(record_options), {
            group_info: this.values,
        });

        var self = this;
        if (group_data.options && group_data.options.group_by_tooltip) {
            this.tooltip_info = _.map(group_data.options.group_by_tooltip, function (key, value, list) {
                return (self.values && self.values[value] && "
" +key + "
" + self.values[value] + "
") || '';
            }).join('');
        } else {
            this.tooltip_info = "";
        }
    },

    start: function() {
        var self = this;
        this.$header = this.$('.o_kanban_header');

        for (var i = 0; i < this.data_records.length; i++) {
            this.add_record(this.data_records[i], {no_update: true});
        }
        this.$header.tooltip();

        this.$el.sortable({
            connectWith: '.o_kanban_group',
            revert: 0,
            delay: 0,
            items: '> .o_kanban_record',
            helper: 'clone',
            cursor: 'move',
            over: function () {
                self.$el.addClass('o_kanban_hover');
                self.update_column();
            },
            out: function () {
                self.$el.removeClass('o_kanban_hover');
            },
            update: function (event, ui) {
                var record = ui.item.data('record');
                var index = self.records.indexOf(record);
                var test2 = $.contains(self.$el[0], record.$el[0]);
                record.$el.removeAttr('style');  // jqueryui sortable add display:block inline
                if (index >= 0 && test2) {
                    // resequencing records
                    self.trigger_up('kanban_column_resequence');
                } else if (index >= 0 && !test2) {
                    // removing record from this column
                    self.records.splice(self.records.indexOf(record), 1);
                    self.dataset.remove_ids([record.id]);
                } else {
                    // adding record to this column
                    self.records.push(record);
                    record.setParent(self);
                    self.trigger_up('kanban_column_add_record', {record: record});
                }
                self.update_column();
            }
        });
        this.update_column();
        this.$el.click(function (event) {
            if (self.$el.hasClass('o_column_folded')) {
                event.preventDefault();
                self.folded = false;
                self.update_column();
            }
        });
    },

    is_empty: function () {
        return !this.records.length;
    },

    add_record: function (data, options) {
        var record = new KanbanRecord(this, data, this.record_options);
        this.records.push(record);
        this.dataset.ids = _.uniq(this.dataset.ids.concat(record.id));
        if (options.position === 'before') {
            record.insertAfter(this.quick_create_widget ? this.quick_create_widget.$el : this.$header);
        } else {
            var $load_more = this.$('.o_kanban_load_more');
            if ($load_more.length) {
                record.insertBefore($load_more);
            } else {
                record.appendTo(this.$el);
            }
        }
        if (!options.no_update) {
            this.update_column();
        }
    },

    get_ids: function () {
        var ids = [];
        this.$('.o_kanban_record').each(function (index, r) {
            ids.push($(r).data('record').id);
        });
        return ids;
    },

    update_column: function () {
        var title = this.folded ? this.title + ' (' + this.records.length + ')' : this.title;
        this.$header.find('.o_column_title').text(title);
        this.$header.find('.o-kanban-count').text(this.records.length);

        this.$el.toggleClass('o_column_folded', this.folded);
        var tooltip;
        if (this.remaining) {
            tooltip = this.records.length + '/' + this.dataset.size() + _t(' records');
        } else {
            tooltip = this.records.length + _t(' records');
        }
        tooltip = '
' + tooltip + '
' + this.tooltip_info;
        this.$header.tooltip({html: true}).attr('data-original-title', tooltip);
        if (!this.remaining) {
            this.$('.o_kanban_load_more').remove();
        } else {
            this.$('.o_kanban_load_more').html(QWeb.render('KanbanView.LoadMore', {widget:this}))
        }
    },

    archive_records: function(event) {
        event.preventDefault();
        this.trigger_up('kanban_column_archive_records', {archive: true});
    },

    unarchive_records: function(event) {
        event.preventDefault();
        this.trigger_up('kanban_column_archive_records', {archive: false});
    },

    delete_column: function (event) {
        event.preventDefault();
        var buttons = [
            {
                text: _t("Ok"),
                classes: 'btn-primary',
                close: true,
                click: this.trigger_up.bind(this, 'kanban_column_delete')
            },
            {text: _t("Cancel"), close: true}
        ];
        new Dialog(this, {
            size: 'medium',
            buttons: buttons,
            $content: $('
', {
                text: _t("Are you sure that you want to remove this column ?")
            }),
        }).open();
    },

    edit_column: function (event) {
        event.preventDefault();
        var dialog = new form_common.FormViewDialog(this, {
            res_model: this.relation,
            res_id: this.id,
            title: _t("Edit Column"),
        }).open();

        dialog.on('record_saved', this, function () {
            this.trigger_up('kanban_reload');
        });
    },

    delete_record: function (event) {
        event.stopped = false;
        var self = this;
        event.data.after = function cleanup () {
            var index = self.records.indexOf(event.data.record);
            self.records.splice(index, 1);
            self.update_column();
        };
    },

    add_quick_create: function () {
        if (this.quick_create_widget) {
            return;
        }
        var self = this;
        var width = this.records.length ? this.records[0].$el.innerWidth() : this.$el.width() - 8;
        this.quick_create_widget = new RecordQuickCreate(this, width);
        this.quick_create_widget.insertAfter(this.$header);
        this.quick_create_widget.$el.focusout(function () {
            var hasFocus = (self.quick_create_widget.$(':focus').length > 0);
            if (! hasFocus && self.quick_create_widget) {
                self.cancel_quick_create();
            }
        });

    },

    cancel_quick_create: function () {
        this.quick_create_widget.destroy();
        this.quick_create_widget = undefined;
    },

    quick_create_add_record: function (event) {
        this.trigger_up('column_add_record', event.data);
    },

    load_more: function (event) {
        event.preventDefault();
        this.trigger_up('kanban_load_more');
    },

});

return KanbanColumn;

});
<commit_msg>[FIX] web_kanban: disable jquery sortable in mobile mode<commit_after>odoo.define('web_kanban.Column', function (require) {
"use strict";

var config = require('web.config');
var core = require('web.core');
var Dialog = require('web.Dialog');
var form_common = require('web.form_common');
var Widget = require('web.Widget');
var quick_create = require('web_kanban.quick_create');
var KanbanRecord = require('web_kanban.Record');

var _t = core._t;
var QWeb = core.qweb;
var RecordQuickCreate = quick_create.RecordQuickCreate;

var KanbanColumn = Widget.extend({
    template: "KanbanView.Group",

    events: {
        'click .o_kanban_toggle_fold': function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.folded = true;
            this.update_column();
        },
        'click .o_column_edit': 'edit_column',
        'click .o_column_delete': 'delete_column',
        'click .o_column_archive': 'archive_records',
        'click .o_column_unarchive': 'unarchive_records',
        'click .o_kanban_quick_add': 'add_quick_create',
        'click .o_kanban_load_more': 'load_more',
    },

    custom_events: {
        'kanban_record_delete': 'delete_record',
        'cancel_quick_create': 'cancel_quick_create',
        'quick_create_add_record': 'quick_create_add_record',
    },

    init: function(parent, group_data, options, record_options) {
        this._super(parent);
        this.data_records = group_data.records;
        this.dataset = group_data.dataset;
        this.records = [];
        this.title = group_data.title;
        this.id = group_data.id;
        this.folded = group_data.attributes.folded;
        this.fields = options.fields;
        this.values = group_data.values;

        this.quick_create = options.quick_create;
        this.grouped_by_m2o = options.grouped_by_m2o;
        this.editable = options.editable;
        this.deletable = options.deletable;
        this.has_active_field = options.has_active_field;
        this.records_editable = options.records_editable;
        this.records_deletable = options.records_deletable;
        this.relation = options.relation;
        this.offset = 0;
        this.remaining = this.dataset.size() - this.data_records.length;

        this.record_options = _.extend(_.clone(record_options), {
            group_info: this.values,
        });

        var self = this;
        if (group_data.options && group_data.options.group_by_tooltip) {
            this.tooltip_info = _.map(group_data.options.group_by_tooltip, function (key, value, list) {
                return (self.values && self.values[value] && "
" +key + "
" + self.values[value] + "
") || '';
            }).join('');
        } else {
            this.tooltip_info = "";
        }
    },

    start: function() {
        var self = this;
        this.$header = this.$('.o_kanban_header');

        for (var i = 0; i < this.data_records.length; i++) {
            this.add_record(this.data_records[i], {no_update: true});
        }
        this.$header.tooltip();

        if (config.device.size_class > config.device.SIZES.XS) {
            // deactivate sortable in mobile mode.  It does not work anyway,
            // and it breaks horizontal scrolling in kanban views.  Someday, we
            // should find a way to use the touch events to make sortable work.
            this.$el.sortable({
                connectWith: '.o_kanban_group',
                revert: 0,
                delay: 0,
                items: '> .o_kanban_record',
                helper: 'clone',
                cursor: 'move',
                over: function () {
                    self.$el.addClass('o_kanban_hover');
                    self.update_column();
                },
                out: function () {
                    self.$el.removeClass('o_kanban_hover');
                },
                update: function (event, ui) {
                    var record = ui.item.data('record');
                    var index = self.records.indexOf(record);
                    var test2 = $.contains(self.$el[0], record.$el[0]);
                    record.$el.removeAttr('style');  // jqueryui sortable add display:block inline
                    if (index >= 0 && test2) {
                        // resequencing records
                        self.trigger_up('kanban_column_resequence');
                    } else if (index >= 0 && !test2) {
                        // removing record from this column
                        self.records.splice(self.records.indexOf(record), 1);
                        self.dataset.remove_ids([record.id]);
                    } else {
                        // adding record to this column
                        self.records.push(record);
                        record.setParent(self);
                        self.trigger_up('kanban_column_add_record', {record: record});
                    }
                    self.update_column();
                }
            });
        }
        this.update_column();
        this.$el.click(function (event) {
            if (self.$el.hasClass('o_column_folded')) {
                event.preventDefault();
                self.folded = false;
                self.update_column();
            }
        });
    },

    is_empty: function () {
        return !this.records.length;
    },

    add_record: function (data, options) {
        var record = new KanbanRecord(this, data, this.record_options);
        this.records.push(record);
        this.dataset.ids = _.uniq(this.dataset.ids.concat(record.id));
        if (options.position === 'before') {
            record.insertAfter(this.quick_create_widget ? this.quick_create_widget.$el : this.$header);
        } else {
            var $load_more = this.$('.o_kanban_load_more');
            if ($load_more.length) {
                record.insertBefore($load_more);
            } else {
                record.appendTo(this.$el);
            }
        }
        if (!options.no_update) {
            this.update_column();
        }
    },

    get_ids: function () {
        var ids = [];
        this.$('.o_kanban_record').each(function (index, r) {
            ids.push($(r).data('record').id);
        });
        return ids;
    },

    update_column: function () {
        var title = this.folded ? this.title + ' (' + this.records.length + ')' : this.title;
        this.$header.find('.o_column_title').text(title);
        this.$header.find('.o-kanban-count').text(this.records.length);

        this.$el.toggleClass('o_column_folded', this.folded);
        var tooltip;
        if (this.remaining) {
            tooltip = this.records.length + '/' + this.dataset.size() + _t(' records');
        } else {
            tooltip = this.records.length + _t(' records');
        }
        tooltip = '
' + tooltip + '
' + this.tooltip_info;
        this.$header.tooltip({html: true}).attr('data-original-title', tooltip);
        if (!this.remaining) {
            this.$('.o_kanban_load_more').remove();
        } else {
            this.$('.o_kanban_load_more').html(QWeb.render('KanbanView.LoadMore', {widget:this}))
        }
    },

    archive_records: function(event) {
        event.preventDefault();
        this.trigger_up('kanban_column_archive_records', {archive: true});
    },

    unarchive_records: function(event) {
        event.preventDefault();
        this.trigger_up('kanban_column_archive_records', {archive: false});
    },

    delete_column: function (event) {
        event.preventDefault();
        var buttons = [
            {
                text: _t("Ok"),
                classes: 'btn-primary',
                close: true,
                click: this.trigger_up.bind(this, 'kanban_column_delete')
            },
            {text: _t("Cancel"), close: true}
        ];
        new Dialog(this, {
            size: 'medium',
            buttons: buttons,
            $content: $('
', {
                text: _t("Are you sure that you want to remove this column ?")
            }),
        }).open();
    },

    edit_column: function (event) {
        event.preventDefault();
        var dialog = new form_common.FormViewDialog(this, {
            res_model: this.relation,
            res_id: this.id,
            title: _t("Edit Column"),
        }).open();

        dialog.on('record_saved', this, function () {
            this.trigger_up('kanban_reload');
        });
    },

    delete_record: function (event) {
        event.stopped = false;
        var self = this;
        event.data.after = function cleanup () {
            var index = self.records.indexOf(event.data.record);
            self.records.splice(index, 1);
            self.update_column();
        };
    },

    add_quick_create: function () {
        if (this.quick_create_widget) {
            return;
        }
        var self = this;
        var width = this.records.length ? this.records[0].$el.innerWidth() : this.$el.width() - 8;
        this.quick_create_widget = new RecordQuickCreate(this, width);
        this.quick_create_widget.insertAfter(this.$header);
        this.quick_create_widget.$el.focusout(function () {
            var hasFocus = (self.quick_create_widget.$(':focus').length > 0);
            if (! hasFocus && self.quick_create_widget) {
                self.cancel_quick_create();
            }
        });

    },

    cancel_quick_create: function () {
        this.quick_create_widget.destroy();
        this.quick_create_widget = undefined;
    },

    quick_create_add_record: function (event) {
        this.trigger_up('column_add_record', event.data);
    },

    load_more: function (event) {
        event.preventDefault();
        this.trigger_up('kanban_load_more');
    },

});

return KanbanColumn;

});
<|endoftext|>


<commit_before>if ('Accelerometer' in window && 'Gyroscope' in window) {
  //document.getElementById('moApi').innerHTML = 'Generic Sensor API';

  let accelerometer = new Accelerometer();
  accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel'));
  accelerometer.start();

  let accelerometerWithGravity = new Accelerometer({includeGravity: true});
  accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav'));
  accelerometerWithGravity.start();

  let gyroscope = new Gyroscope();
  gyroscope.addEventListener('reading', e => rotationHandler({
    alpha: gyroscope.x,
    beta: gyroscope.y,
    gamma: gyroscope.z
  }));
  gyroscope.start();

  intervalHandler('Not available in Generic Sensor API');

} else if ('DeviceMotionEvent' in window) {
  //document.getElementById('alert').style.display = 'none';
  //document.getElementById('moApi').innerHTML = 'Device Motion API';

  window.addEventListener('devicemotion', function (eventData) {
    accelerationHandler(eventData.acceleration, 'moAccel');
    MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
    rotationHandler(eventData.rotationRate);
    intervalHandler(eventData.interval);
  }, false);
} else {
  //document.getElementById('alert').style.display = 'none';
  //document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}

function accelerationHandler(acceleration, targetId) {
  var info, xyz = "[X, Y, Z]";

  info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
  info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
  info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
  //document.getElementById(targetId).innerHTML = info;
}

function MaccelerationHandler(acceleration, targetId) {
  var info, xyz = "[X, Y, Z]";

  var zz = (acceleration.z && acceleration.z.toFixed(3));

  if (zz>10) {
                x = 1;
            var timer = setInterval(function change() {
              if (x === 1) {
                  color = "#ffffff";
                x = 2;
              } else {
                  color = "#000000";
                  x = 1;
              }

              document.body.style.background = color;
            }, 50);

          setTimeout(function() {
            clearInterval(timer);
          }, 1000);
  }
}

function rotationHandler(rotation) {
  var info, xyz = "[X, Y, Z]";

  //info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
  //info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
  //info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));

  var xx = (rotation.alpha && rotation.alpha.toFixed(3));
  var yy = (rotation.beta && rotation.beta.toFixed(3));
  var zz = (rotation.gamma && rotation.gamma.toFixed(3));

  var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2);
  //document.getElementById("mean").innerHTML = mean;
  //document.getElementById("moRotation").innerHTML = info;

}

function intervalHandler(interval) {
  //document.getElementById("moInterval").innerHTML = interval;
}

if (location.href.indexOf('debug') !== -1) {
  //document.getElementById('alert').style.display = 'none';
}
<commit_msg>Update index.js<commit_after>if ('Accelerometer' in window && 'Gyroscope' in window) {
  //document.getElementById('moApi').innerHTML = 'Generic Sensor API';

  let accelerometer = new Accelerometer();
  accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel'));
  accelerometer.start();

  let accelerometerWithGravity = new Accelerometer({includeGravity: true});
  accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav'));
  accelerometerWithGravity.start();

  let gyroscope = new Gyroscope();
  gyroscope.addEventListener('reading', e => rotationHandler({
    alpha: gyroscope.x,
    beta: gyroscope.y,
    gamma: gyroscope.z
  }));
  gyroscope.start();

  intervalHandler('Not available in Generic Sensor API');

} else if ('DeviceMotionEvent' in window) {
  //document.getElementById('alert').style.display = 'none';
  //document.getElementById('moApi').innerHTML = 'Device Motion API';

  window.addEventListener('devicemotion', function (eventData) {
    accelerationHandler(eventData.acceleration, 'moAccel');
    MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
    rotationHandler(eventData.rotationRate);
    intervalHandler(eventData.interval);
  }, false);
} else {
  //document.getElementById('alert').style.display = 'none';
  //document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}

function accelerationHandler(acceleration, targetId) {
  var info, xyz = "[X, Y, Z]";

  info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
  info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
  info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
  //document.getElementById(targetId).innerHTML = info;
}

function MaccelerationHandler(acceleration, targetId) {
  var info, xyz = "[X, Y, Z]";

  var zz = (acceleration.z && acceleration.z.toFixed(3));

  if (zz>10) {
                x = 1;
            var timer = setInterval(function change() {
              if (x === 1) {
                  color = "#ffffff";
                x = 2;
              } else {
                  color = "#000000";
                  x = 1;
              }

              document.body.style.background = "url('1.png') no-repeat center cover";
            }, 50);

          setTimeout(function() {
            clearInterval(timer);
          }, 1000);
  }
}

function rotationHandler(rotation) {
  var info, xyz = "[X, Y, Z]";

  //info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
  //info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
  //info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));

  var xx = (rotation.alpha && rotation.alpha.toFixed(3));
  var yy = (rotation.beta && rotation.beta.toFixed(3));
  var zz = (rotation.gamma && rotation.gamma.toFixed(3));

  var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2);
  //document.getElementById("mean").innerHTML = mean;
  //document.getElementById("moRotation").innerHTML = info;

}

function intervalHandler(interval) {
  //document.getElementById("moInterval").innerHTML = interval;
}

if (location.href.indexOf('debug') !== -1) {
  //document.getElementById('alert').style.display = 'none';
}
<|endoftext|>


<commit_before>Mailpile.render = function() {

  // Dynamic CSS Reiszing
  var dynamic_sizing = function() {

    // Is Tablet or Mobile
    if ($('#sidebar').length === 0 || $(window).width() < 1024) {
      var sidebar_width  = 0;
    }
    else {
      var sidebar_width  = 225;
    }

    var content_width  = $(window).width() - sidebar_width;
    var content_height = $(window).height() - 62;
    var content_tools_height    = $('#content-tools').height();
    var new_content_width       = $(window).width() - sidebar_width;
    var new_content_view_height = content_height - content_tools_height;

    $('#content-tools').css('position', 'fixed');
    $('.sub-navigation').width(content_width);
    $('#thread-title').width(content_width);

    // Set Content View
    $('#content, #content-wide').css({'height': content_height});
    $('#content-tools, .sub-navigation, .bulk-actions').width(new_content_width);
    $('#content-view').css({'height': new_content_view_height, 'top': content_tools_height});
  };

  // Resize Elements Start + On Drag
  dynamic_sizing();
  window.onresize = function(event) {
    dynamic_sizing();
  };

  // Show Mailboxes
  if ($('#sidebar-tag-outbox').find('span.sidebar-notification').html() !== undefined) {
    $('#sidebar-tag-outbox').show();
  }

  // Mousetrap Keybindings
	for (item in Mailpile.keybindings) {
	  var keybinding = Mailpile.keybindings[item];
		if (keybinding[0] == "global") {
			Mousetrap.bindGlobal(keybinding[1], keybinding[2]);
		} else {
      Mousetrap.bind(keybinding[1], keybinding[2]);
		}
	}
};<commit_msg>Added nice_fingerprint JS<commit_after>Mailpile.render = function() {

  // Dynamic CSS Reiszing
  var dynamic_sizing = function() {

    // Is Tablet or Mobile
    if ($('#sidebar').length === 0 || $(window).width() < 1024) {
      var sidebar_width  = 0;
    }
    else {
      var sidebar_width  = 225;
    }

    var content_width  = $(window).width() - sidebar_width;
    var content_height = $(window).height() - 62;
    var content_tools_height    = $('#content-tools').height();
    var new_content_width       = $(window).width() - sidebar_width;
    var new_content_view_height = content_height - content_tools_height;

    $('#content-tools').css('position', 'fixed');
    $('.sub-navigation').width(content_width);
    $('#thread-title').width(content_width);

    // Set Content View
    $('#content, #content-wide').css({'height': content_height});
    $('#content-tools, .sub-navigation, .bulk-actions').width(new_content_width);
    $('#content-view').css({'height': new_content_view_height, 'top': content_tools_height});
  };

  // Resize Elements Start + On Drag
  dynamic_sizing();
  window.onresize = function(event) {
    dynamic_sizing();
  };

  // Show Mailboxes
  if ($('#sidebar-tag-outbox').find('span.sidebar-notification').html() !== undefined) {
    $('#sidebar-tag-outbox').show();
  }

  // Mousetrap Keybindings
	for (item in Mailpile.keybindings) {
	  var keybinding = Mailpile.keybindings[item];
		if (keybinding[0] == "global") {
			Mousetrap.bindGlobal(keybinding[1], keybinding[2]);
		} else {
      Mousetrap.bind(keybinding[1], keybinding[2]);
		}
	}
};

Mailpile.nice_fingerprint = function(fingerprint) {
  // FIXME: I'd really love to make these individual pieces color coded
  // Pertaining to the hex value pairings & even perhaps toggle-able icons
  return fingerprint.split(/(....)/).join(' ');
};<|endoftext|>