<commit_before>'use strict';

// 1. Get first layout pass of grid view so we have a total width and calculate the column width (componentDidMount?).
// 2. Possibly do artwork column layout now, as we can do so based just on the aspect ratio, assuming the text height
//    won't be too different between artworks.
// 3. Get artwork heights by either:
//    - calculating the item size upfront with aspect ratio and a static height for the text labels.
//    - leting the artwork component do a layout pass and calculate its own height based on the column width.
// 4. Update height of grid to encompass all items.

import Relay from 'react-relay';
import React from 'react-native';
const { View, ScrollView, StyleSheet } = React;

import Artwork from './artwork';

/**
 * TODOs:
 * - currently all the code assumes column layout
 * - calculate in which column an artwork should be put so they grow evenly (see ARMasonryCollectionViewLayout)
 */
class Artworks extends React.Component {
  static defaultProps = {
    sectionDirection: 'column',
    sectionCount: 2,
    sectionMargin: 8,
    itemMargin: 8,
  }

  constructor(props) {
    super(props);
    this.state = { sectionDimension: 0, artworks: this.props.artworks };
    this.onLayout = this.onLayout.bind(this);
  }

  onLayout(event: LayoutEvent) {
    const layout = event.nativeEvent.layout;
    if (layout.width > 0) {
      // This is the sum of all margins in between sections, so do not count to the right of last column.
      const sectionMargins = this.props.sectionMargin * (this.props.sectionCount - 1);
      this.setState({ sectionDimension: (layout.width - sectionMargins) / this.props.sectionCount });
    }
  }

  renderSections() {
    const sectionedArtworks = [];
    for (let i = 0; i < this.props.sectionCount; i++) {
      sectionedArtworks.push([]);
    };
    for (let i = 0; i < this.state.artworks.length; i++) {
      const section = sectionedArtworks[i % this.props.sectionCount];
      section.push(this.state.artworks[i]);
    }

    const spacerStyle = {
      height: this.props.itemMargin,
    };

    const sections = [];
    for (let i = 0; i < this.props.sectionCount; i++) {
      const artworkComponents = [];
      const artworks = sectionedArtworks[i];
      for (let j = 0; j < artworks.length; j++) {
        artworkComponents.push(<Artwork artwork={artworks[j]} key={'artwork-'+j} />);
        // Setting a marginBottom on the artwork component didn’t work, so using a spacer view instead.
        if (j < artworks.length-1) {
          artworkComponents.push(<View style={spacerStyle} key={'spacer-'+j} accessibilityLabel='Spacer View' />);
        }
      }

      const sectionSpecificStyle = {
        width: this.state.sectionDimension,
        marginRight: (i == this.props.sectionCount-1 ? 0 : this.props.sectionMargin),
      };
      sections.push(
        <View style={[styles.section, sectionSpecificStyle]} key={i} accessibilityLabel={'Section ' + i}>
          {artworkComponents}
        </View>
      );
    }
    return sections;
  }

  render() {
    const artworks = this.state.sectionDimension ? this.renderSections() : null;
    return (
      <ScrollView onLayout={this.onLayout} accessibilityLabel='Artworks ScrollView'>
        <View style={styles.container} accessibilityLabel='Artworks Content View'>
          {artworks}
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
  },
  section: {
    flex: 1,
    flexDirection: 'column',
  },
});

export default Relay.createContainer(Artworks, {
  fragments: {
    artworks: () => Relay.QL`
      fragment on Artwork @relay(plural: true) {
        ${Artwork.artworkFragment}
      }
    `,
  }
});
<commit_msg>[Artworks] Try to evenly distribute over sections.<commit_after>'use strict';

// 1. Get first layout pass of grid view so we have a total width and calculate the column width (componentDidMount?).
// 2. Possibly do artwork column layout now, as we can do so based just on the aspect ratio, assuming the text height
//    won't be too different between artworks.
// 3. Get artwork heights by either:
//    - calculating the item size upfront with aspect ratio and a static height for the text labels.
//    - leting the artwork component do a layout pass and calculate its own height based on the column width.
// 4. Update height of grid to encompass all items.

import Relay from 'react-relay';
import React from 'react-native';
const { View, ScrollView, StyleSheet } = React;

import { max } from 'lodash';

import Artwork from './artwork';

/**
 * TODOs:
 * - currently all the code assumes column layout
 *   - do no invert aspect ratios in row layout
 * - deal with edge-cases when calculating in which section an artwork should go
 *   - see ARMasonryCollectionViewLayout for details on how to deal with last works sticking out
 *   - the calculation currently only takes into account the size of the image, not if e.g. the sale message is present
 */
class Artworks extends React.Component {
  static defaultProps = {
    sectionDirection: 'column',
    sectionCount: 2,
    sectionMargin: 8,
    itemMargin: 8,
  }

  constructor(props) {
    super(props);
    this.state = { sectionDimension: 0, artworks: this.props.artworks };
    this.onLayout = this.onLayout.bind(this);
  }

  onLayout(event: LayoutEvent) {
    const layout = event.nativeEvent.layout;
    if (layout.width > 0) {
      // This is the sum of all margins in between sections, so do not count to the right of last column.
      const sectionMargins = this.props.sectionMargin * (this.props.sectionCount - 1);
      this.setState({ sectionDimension: (layout.width - sectionMargins) / this.props.sectionCount });
    }
  }

  sectionedArtworks() {
    const sectionedArtworks = [];
    const sectionRatioSums = [];
    for (let i = 0; i < this.props.sectionCount; i++) {
      sectionedArtworks.push([]);
      sectionRatioSums.push(0);
    };

    const artworks = this.state.artworks;
    for (let i = 0; i < artworks.length; i++) {
      const artwork = this.state.artworks[i];

      // Find section with lowest *inverted* aspect ratio sum, which is the shortest column.
      let lowestRatioSum = max(sectionRatioSums) + 1; // Start higher, so we always find a
      let sectionIndex = null;
      for (let j = 0; j < sectionRatioSums.length; j++) {
        const ratioSum = sectionRatioSums[j];
        if (ratioSum < lowestRatioSum) {
          sectionIndex = j;
          lowestRatioSum = ratioSum;
        }
      }

      const section = sectionedArtworks[sectionIndex];
      section.push(artwork);

      // Keep track of total section aspect ratio
      const aspectRatio = artwork.image.aspect_ratio || 1; // Ensure we never divide by null/0
      // Invert the aspect ratio so that a lower value means a shorter section.
      sectionRatioSums[sectionIndex] += (1 / aspectRatio);
    }

    return sectionedArtworks;
  }

  renderSections() {
    const spacerStyle = {
      height: this.props.itemMargin,
    };

    const sectionedArtworks = this.sectionedArtworks();
    const sections = [];
    for (let i = 0; i < this.props.sectionCount; i++) {
      const artworkComponents = [];
      const artworks = sectionedArtworks[i];
      for (let j = 0; j < artworks.length; j++) {
        artworkComponents.push(<Artwork artwork={artworks[j]} key={'artwork-'+j} />);
        // Setting a marginBottom on the artwork component didn’t work, so using a spacer view instead.
        if (j < artworks.length-1) {
          artworkComponents.push(<View style={spacerStyle} key={'spacer-'+j} accessibilityLabel='Spacer View' />);
        }
      }

      const sectionSpecificStyle = {
        width: this.state.sectionDimension,
        marginRight: (i == this.props.sectionCount-1 ? 0 : this.props.sectionMargin),
      };
      sections.push(
        <View style={[styles.section, sectionSpecificStyle]} key={i} accessibilityLabel={'Section ' + i}>
          {artworkComponents}
        </View>
      );
    }
    return sections;
  }

  render() {
    const artworks = this.state.sectionDimension ? this.renderSections() : null;
    return (
      <ScrollView onLayout={this.onLayout} accessibilityLabel='Artworks ScrollView'>
        <View style={styles.container} accessibilityLabel='Artworks Content View'>
          {artworks}
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
  },
  section: {
    flex: 1,
    flexDirection: 'column',
  },
});

export default Relay.createContainer(Artworks, {
  fragments: {
    artworks: () => Relay.QL`
      fragment on Artwork @relay(plural: true) {
        ${Artwork.artworkFragment}
      }
    `,
  }
});
<|endoftext|>


<commit_before>import {
  each,
  find,
  some,
  isEmpty
} from 'lodash';

import HeadGoverness from './governesses/HeadGoverness';
import Purpose from './Purpose';
import BaseObject from './BaseObject';
import AllowedMethodsService from './utils/AllowedMethodsService';
import {
  isGoverness,
  isPerimeter,
  isPurpose
} from './utils';
import {
  ArgumentError,
  NoGovernessError,
  RestrictedMethodError
} from './errors';

/**
 * The definition of Sandbox class.
 * The sandbox is place where children can play governed by a governess.
 */
export default class Sandbox extends BaseObject {
  /**
   * Create a new empty sandbox.
   */
  constructor(child = null, opts = {}) {
    super(); // init publish/subscribe

    this.child = child;

    // Sandbox is governed by a HeadGoverness by default
    this.governess = opts.governess || new HeadGoverness(child);

    this._perimeters = [];
    const perimeters = opts.perimeters || this._perimeters;

    if (!isEmpty(perimeters)) {
      this.loadPerimeter(...perimeters);
    }
  }

  /**
   * The getter of the governess.
   */
  get governess() {
    return this._governess;
  }

  /**
   * The setter of the governess.
   * Make sure new governess learn all the rules when governess is set.
   */
  set governess(value) {
    if (!isGoverness(value)) {
      throw new NoGovernessError();
    }

    // if governess is null perimeter will use the governess of it's sandbox
    this._governess = value;

    // New governess must know all the rules (if any)
    this._learnRules();

    return value;
  }

  /**
   * Load perimeters.
   * Returns the count of addded perimeters.
   */
  loadPerimeter(...perimeters) {
    let counter = 0;

    each(perimeters, (perimeter) => {
      // Sandbox only accepts perimeters
      if (!isPerimeter(perimeter)) {
        throw new ArgumentError(
          'Module must be instance of Kindergarten.Perimeter.'
        );
      }

      // Skip if sandbox already have the perimeter
      if (this.hasPerimeter(perimeter)) return;

      // If perimeter has a governess, then she has to learn the rules as well
      if (isGoverness(perimeter.governess)) {
        perimeter.governess.learnRules(perimeter);
      }

      // The governess of a sandbox must know all the rules
      this.governess.learnRules(perimeter);

      perimeter.sandbox = this;

      this._perimeters.push(perimeter);

      // Make sure the purpose is available on Sandbox
      this._extendPurpose(perimeter);

      ++counter;

      this.trigger('load-perimeter', this, perimeter);
    });

    return counter;
  }

  /**
   * Alias for loadPerimeter
   */
  loadModule(...args) {
    return this.loadPerimeter(...args);
  }

  /**
   * Return all loaded perimeters
   */
  getPerimeters() {
    return this._perimeters || [];
  }

  /**
   * Return perimeter by a purpose or null.
   */
  getPerimeter(purpose) {
    const perimeter = find(this.getPerimeters(), (p) => (p.purpose === purpose));

    return isPerimeter(perimeter) ? perimeter : null;
  }

  /**
   * Return true if sandbox already contains a perimeter.
   */
  hasPerimeter(perimeter) {
    const purpose = isPerimeter(perimeter) ?
      perimeter.purpose :
      perimeter;

    return some(this.getPerimeters(), (p) => p.purpose === purpose);
  }

  /**
   * Return true if allowed to do action on target.
   */
  isAllowed(...args) {
    return this.governess.isAllowed(...args);
  }

  /**
   * Return true if not allowed to do action on target.
   */
  isNotAllowed(...args) {
    return this.governess.isNotAllowed(...args);
  }

  /**
   * Expose the purpose of a perimeter, make sure the purpose of the perimeter
   * is available on this sandbox.
   * This method is used internally by Sandbox and shouldn't be used
   * externally.
   */
  _extendPurpose(perimeter) {
    const name = perimeter.purpose;
    const allowedMethodsService = new AllowedMethodsService(this);

    if (allowedMethodsService.isRestricted(name)) {
      throw new RestrictedMethodError(
        `Cannot expose purpose ${name} to sandbox. Restricted method name.`
      );
    }

    this[name] = isPurpose(this[name]) ? this[name] : new Purpose(name, this);
    this[name]._loadPerimeter(perimeter);
  }

  /**
   * Make sure governess know all the rules from all loaded perimeters.
   * This method is used internally by Sandbox and shouldn't be used
   * externally.
   */
  _learnRules() {
    each(this.getPerimeters() || [], (perimeter) =>
      this.governess.learnRules(perimeter)
    );
  }
}
<commit_msg>Use object destructuring in costructor<commit_after>import {
  each,
  find,
  some,
  isEmpty
} from 'lodash';

import HeadGoverness from './governesses/HeadGoverness';
import Purpose from './Purpose';
import BaseObject from './BaseObject';
import AllowedMethodsService from './utils/AllowedMethodsService';
import {
  isGoverness,
  isPerimeter,
  isPurpose
} from './utils';
import {
  ArgumentError,
  NoGovernessError,
  RestrictedMethodError
} from './errors';

/**
 * The definition of Sandbox class.
 * The sandbox is place where children can play governed by a governess.
 */
export default class Sandbox extends BaseObject {
  /**
   * Create a new empty sandbox.
   */
  constructor(child = null, { governess = new HeadGoverness(child), perimeters = [] } = {}) {
    super(); // init publish/subscribe

    this.child = child;

    this.governess = governess;

    this._perimeters = [];

    if (!isEmpty(perimeters)) {
      this.loadPerimeter(...perimeters);
    }
  }

  /**
   * The getter of the governess.
   */
  get governess() {
    return this._governess;
  }

  /**
   * The setter of the governess.
   * Make sure new governess learn all the rules when governess is set.
   */
  set governess(value) {
    if (!isGoverness(value)) {
      throw new NoGovernessError();
    }

    // if governess is null perimeter will use the governess of it's sandbox
    this._governess = value;

    // New governess must know all the rules (if any)
    this._learnRules();

    return value;
  }

  /**
   * Load perimeters.
   * Returns the count of addded perimeters.
   */
  loadPerimeter(...perimeters) {
    let counter = 0;

    each(perimeters, (perimeter) => {
      // Sandbox only accepts perimeters
      if (!isPerimeter(perimeter)) {
        throw new ArgumentError(
          'Module must be instance of Kindergarten.Perimeter.'
        );
      }

      // Skip if sandbox already have the perimeter
      if (this.hasPerimeter(perimeter)) return;

      // If perimeter has a governess, then she has to learn the rules as well
      if (isGoverness(perimeter.governess)) {
        perimeter.governess.learnRules(perimeter);
      }

      // The governess of a sandbox must know all the rules
      this.governess.learnRules(perimeter);

      perimeter.sandbox = this;

      this._perimeters.push(perimeter);

      // Make sure the purpose is available on Sandbox
      this._extendPurpose(perimeter);

      ++counter;

      this.trigger('load-perimeter', this, perimeter);
    });

    return counter;
  }

  /**
   * Alias for loadPerimeter
   */
  loadModule(...args) {
    return this.loadPerimeter(...args);
  }

  /**
   * Return all loaded perimeters
   */
  getPerimeters() {
    return this._perimeters || [];
  }

  /**
   * Return perimeter by a purpose or null.
   */
  getPerimeter(purpose) {
    const perimeter = find(this.getPerimeters(), (p) => (p.purpose === purpose));

    return isPerimeter(perimeter) ? perimeter : null;
  }

  /**
   * Return true if sandbox already contains a perimeter.
   */
  hasPerimeter(perimeter) {
    const purpose = isPerimeter(perimeter) ?
      perimeter.purpose :
      perimeter;

    return some(this.getPerimeters(), (p) => p.purpose === purpose);
  }

  /**
   * Return true if allowed to do action on target.
   */
  isAllowed(...args) {
    return this.governess.isAllowed(...args);
  }

  /**
   * Return true if not allowed to do action on target.
   */
  isNotAllowed(...args) {
    return this.governess.isNotAllowed(...args);
  }

  /**
   * Expose the purpose of a perimeter, make sure the purpose of the perimeter
   * is available on this sandbox.
   * This method is used internally by Sandbox and shouldn't be used
   * externally.
   */
  _extendPurpose(perimeter) {
    const name = perimeter.purpose;
    const allowedMethodsService = new AllowedMethodsService(this);

    if (allowedMethodsService.isRestricted(name)) {
      throw new RestrictedMethodError(
        `Cannot expose purpose ${name} to sandbox. Restricted method name.`
      );
    }

    this[name] = isPurpose(this[name]) ? this[name] : new Purpose(name, this);
    this[name]._loadPerimeter(perimeter);
  }

  /**
   * Make sure governess know all the rules from all loaded perimeters.
   * This method is used internally by Sandbox and shouldn't be used
   * externally.
   */
  _learnRules() {
    each(this.getPerimeters() || [], (perimeter) =>
      this.governess.learnRules(perimeter)
    );
  }
}
<|endoftext|>


<commit_before>"use strict";

/**
 * @constructor
 * @param {Object} opts Options for this factory
 * @param {*=} opts.sdk The Matrix JS SDK require() to use.
 * @param {string=} opts.url The Client-Server base HTTP URL. This must be set
 * prior to calling getClientAs(). See configure() to set this after instantiation.
 * @param {string=} opts.token The application service token to use. This must
 * be set prior to calling getClientAs(). See configure() to set this after
 * instantiation.
 * @param {string=} opts.appServiceUserId The application service's user ID. Must
 * be set prior to calling getClientAs(). See configure() to set this after
 * instantiation.
 * @param {function=} opts.clientSchedulerBuilder Optional. A function that
 * returns a new client scheduler to use in place of the default event
 * scheduler that schedules events to be sent to the HS.
 */
function ClientFactory(opts) {
    opts = opts || {};
    this._sdk = opts.sdk || require("matrix-js-sdk");
    this._clients = {
    //  request_id: {
    //      user_id: Client
    //  }
    };
    this._clientSchedulerBuilder = opts.clientSchedulerBuilder || function() {};
    this.configure(opts.url, opts.token, opts.appServiceUserId);
}

/**
 * Set a function to be called when logging requests and responses.
 * @param {Function} func The function to invoke. The first arg is the string to
 * log. The second arg is a boolean which is 'true' if the log is an error.
 */
ClientFactory.prototype.setLogFunction = function(func) {
    if (func) {
        /* It would be nice if could ask the sdk what its current request
         * function is for wrapping purposes. Until such an API is invented for
         * that this hack will do
         */
        var origRequest = this._sdk.createClient({
            baseUrl: "dummy",
        })._http.opts.request;

        this._sdk.request(function(opts, callback) {
            var logPrefix = (
                (opts._matrix_opts && opts._matrix_opts._reqId ?
                    "[" + opts._matrix_opts._reqId + "] " : ""
                ) +
                opts.method + " " + opts.uri + " " +
                (opts.qs.user_id ? "(" + opts.qs.user_id + ")" : "(AS)")
            );
            // Request logging
            func(
                logPrefix + " Body: " +
                (opts.body ? JSON.stringify(opts.body).substring(0, 80) : "")
            );
            // Make the request
            origRequest(opts, function(err, response, body) {
                // Response logging
                var httpCode = response ? response.statusCode : null;
                var responsePrefix = logPrefix + " HTTP " + httpCode;
                if (err) {
                    func(
                        responsePrefix + " Error: " + JSON.stringify(err), true
                    );
                }
                else if (httpCode >= 300 || httpCode < 200) {
                    func(
                        responsePrefix + " Error: " + JSON.stringify(body), true
                    );
                }
                else {
                    func( // body may be large, so do first 80 chars
                        responsePrefix + " " +
                        JSON.stringify(body).substring(0, 80)
                    );
                }
                // Invoke the callback
                callback(err, response, body);
            });
        });
    }
};

/**
 * Construct a new Matrix JS SDK Client. Calling this twice with the same args
 * will return the *same* client instance.
 * @param {?string} userId Required. The user_id to scope the client to. A new
 * client will be created per user ID. If this is null, a client scoped to the
 * application service *itself* will be created.
 * @param {Request=} request Optional. The request ID to additionally scope the
 * client to. If set, this will create a new client per user ID / request combo.
 * This factory will dispose the created client instance when the request is
 * resolved.
 */
ClientFactory.prototype.getClientAs = function(userId, request) {
    var reqId = request ? request.getId() : "-";
    var userIdKey = userId || "bot";
    var self = this;

    // see if there is an existing match
    var client = this._getClient(reqId, userIdKey);
    if (client) {
        return client;
    }

    // create a new client
    var queryParams = {};
    if (userId) {
        queryParams.user_id = userId;
    }
    // force set access_token= so it is used when /register'ing
    queryParams.access_token = this._token;
    var clientOpts = {
        accessToken: this._token,
        baseUrl: this._url,
        userId: userId || this._botUserId, // NB: no clobber so we don't set ?user_id=BOT
        queryParams: queryParams,
        scheduler: this._clientSchedulerBuilder(),
        localTimeoutMs: 1000 * 60 * 2, // Time out CS-API calls after 2mins
    };
    client = this._sdk.createClient(clientOpts);
    client._http.opts._reqId = reqId; // FIXME gut wrenching

    // add a listener for the completion of this request so we can cleanup
    // the clients we've made
    if (request) {
        request.getPromise().finally(function() {
            delete self._clients[reqId];
        });
    }

    // store the new client
    if (!this._clients[reqId]) {
        this._clients[reqId] = {};
    }
    this._clients[reqId][userIdKey] = client;

    return client;
};

/**
 * Configure the factory for generating clients.
 * @param {string} baseUrl The base URL to create clients with.
 * @param {string} appServiceToken The AS token to use as the access_token
 * @param {string} appServiceUserId The AS's user_id
 */
ClientFactory.prototype.configure = function(baseUrl, appServiceToken, appServiceUserId) {
    this._url = baseUrl;
    this._token = appServiceToken;
    this._botUserId = appServiceUserId;
};

ClientFactory.prototype._getClient = function(reqId, userId) {
    if (this._clients[reqId] && this._clients[reqId][userId]) {
        return this._clients[reqId][userId];
    }
    return null;
};

module.exports = ClientFactory;
<commit_msg>Use wrapRequest from JS SDK 0.7+ rather than hackery<commit_after>"use strict";

/**
 * @constructor
 * @param {Object} opts Options for this factory
 * @param {*=} opts.sdk The Matrix JS SDK require() to use.
 * @param {string=} opts.url The Client-Server base HTTP URL. This must be set
 * prior to calling getClientAs(). See configure() to set this after instantiation.
 * @param {string=} opts.token The application service token to use. This must
 * be set prior to calling getClientAs(). See configure() to set this after
 * instantiation.
 * @param {string=} opts.appServiceUserId The application service's user ID. Must
 * be set prior to calling getClientAs(). See configure() to set this after
 * instantiation.
 * @param {function=} opts.clientSchedulerBuilder Optional. A function that
 * returns a new client scheduler to use in place of the default event
 * scheduler that schedules events to be sent to the HS.
 */
function ClientFactory(opts) {
    opts = opts || {};
    this._sdk = opts.sdk || require("matrix-js-sdk");
    this._clients = {
    //  request_id: {
    //      user_id: Client
    //  }
    };
    this._clientSchedulerBuilder = opts.clientSchedulerBuilder || function() {};
    this.configure(opts.url, opts.token, opts.appServiceUserId);
}

/**
 * Set a function to be called when logging requests and responses.
 * @param {Function} func The function to invoke. The first arg is the string to
 * log. The second arg is a boolean which is 'true' if the log is an error.
 */
ClientFactory.prototype.setLogFunction = function(func) {
    if (!func) {
        return;
    }
    this._sdk.wrapRequest(function(origRequest, opts, callback) {
        var logPrefix = (
            (opts._matrix_opts && opts._matrix_opts._reqId ?
                "[" + opts._matrix_opts._reqId + "] " : ""
            ) +
            opts.method + " " + opts.uri + " " +
            (opts.qs.user_id ? "(" + opts.qs.user_id + ")" : "(AS)")
        );
        // Request logging
        func(
            logPrefix + " Body: " +
            (opts.body ? JSON.stringify(opts.body).substring(0, 80) : "")
        );
        // Make the request
        origRequest(opts, function(err, response, body) {
            // Response logging
            var httpCode = response ? response.statusCode : null;
            var responsePrefix = logPrefix + " HTTP " + httpCode;
            if (err) {
                func(
                    responsePrefix + " Error: " + JSON.stringify(err), true
                );
            }
            else if (httpCode >= 300 || httpCode < 200) {
                func(
                    responsePrefix + " Error: " + JSON.stringify(body), true
                );
            }
            else {
                func( // body may be large, so do first 80 chars
                    responsePrefix + " " +
                    JSON.stringify(body).substring(0, 80)
                );
            }
            // Invoke the callback
            callback(err, response, body);
        });
    });
};

/**
 * Construct a new Matrix JS SDK Client. Calling this twice with the same args
 * will return the *same* client instance.
 * @param {?string} userId Required. The user_id to scope the client to. A new
 * client will be created per user ID. If this is null, a client scoped to the
 * application service *itself* will be created.
 * @param {Request=} request Optional. The request ID to additionally scope the
 * client to. If set, this will create a new client per user ID / request combo.
 * This factory will dispose the created client instance when the request is
 * resolved.
 */
ClientFactory.prototype.getClientAs = function(userId, request) {
    var reqId = request ? request.getId() : "-";
    var userIdKey = userId || "bot";
    var self = this;

    // see if there is an existing match
    var client = this._getClient(reqId, userIdKey);
    if (client) {
        return client;
    }

    // create a new client
    var queryParams = {};
    if (userId) {
        queryParams.user_id = userId;
    }
    // force set access_token= so it is used when /register'ing
    queryParams.access_token = this._token;
    var clientOpts = {
        accessToken: this._token,
        baseUrl: this._url,
        userId: userId || this._botUserId, // NB: no clobber so we don't set ?user_id=BOT
        queryParams: queryParams,
        scheduler: this._clientSchedulerBuilder(),
        localTimeoutMs: 1000 * 60 * 2, // Time out CS-API calls after 2mins
    };
    client = this._sdk.createClient(clientOpts);
    client._http.opts._reqId = reqId; // FIXME gut wrenching

    // add a listener for the completion of this request so we can cleanup
    // the clients we've made
    if (request) {
        request.getPromise().finally(function() {
            delete self._clients[reqId];
        });
    }

    // store the new client
    if (!this._clients[reqId]) {
        this._clients[reqId] = {};
    }
    this._clients[reqId][userIdKey] = client;

    return client;
};

/**
 * Configure the factory for generating clients.
 * @param {string} baseUrl The base URL to create clients with.
 * @param {string} appServiceToken The AS token to use as the access_token
 * @param {string} appServiceUserId The AS's user_id
 */
ClientFactory.prototype.configure = function(baseUrl, appServiceToken, appServiceUserId) {
    this._url = baseUrl;
    this._token = appServiceToken;
    this._botUserId = appServiceUserId;
};

ClientFactory.prototype._getClient = function(reqId, userId) {
    if (this._clients[reqId] && this._clients[reqId][userId]) {
        return this._clients[reqId][userId];
    }
    return null;
};

module.exports = ClientFactory;
<|endoftext|>


<commit_before>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require("module-toolkit").BaseManager;
var moment = require("moment");
const SELECTED_FIELDS = {
    "_id": 1,
    "salesContractNo": 1,
    "uom.unit": 1,
    "orderQuantity": 1,
    "material.name": 1,
    "materialConstruction.name": 1,
    "yarnMaterial.name": 1,
    "materialWidth": 1,
    "orderNo": 1,
    "orderType.name": 1,
    "processType.name": 1,
    "buyer.name": 1,
    "buyer.type": 1,
    "deliveryDate": 1,
    "_createdDate": 1,
    "buyer.code": 1,
    "_deleted": 1
}

// internal deps
require("mongodb-toolkit");

var ProductionOrderManager = require("../../managers/sales/production-order-manager");

module.exports = class FactProductionOrderEtlManager extends BaseManager {
    constructor(db, user, sql) {
        super(db, user);
        this.sql = sql;
        this.productionOrderManager = new ProductionOrderManager(db, user);
        this.migrationLog = this.db.collection("migration-log");
    }

    run() {
        var startedDate = new Date()
        this.migrationLog.insert({
            description: "Fact Production Order from MongoDB to Azure DWH",
            start: startedDate,
        })
        return this.timestamp()
            .then((time) => this.extract(time))
            .then((data) => this.transform(data))
            .then((data) => this.load(data))
            .then((results) => {
                console.log("Success!");
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Production Order from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: "Successful"
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            })
            .catch((err) => {
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Production Order from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: err
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            });
    };

    timestamp() {
        return this.migrationLog.find({
            description: "Fact Production Order from MongoDB to Azure DWH",
            status: "Successful"
        }).sort({ finish: -1 }).limit(1).toArray()
    }

    extract(times) {
        var time = times.length > 0 ? times[0].start : "1970-01-01";
        var timestamp = new Date(time);
        return this.productionOrderManager.collection.find({
            _updatedDate: {
                $gt: timestamp
            }
        }).toArray()
    }

    orderQuantityConvertion(uom, quantity) {
        if (uom.toLowerCase() === "met" || uom.toLowerCase() === "mtr" || uom.toLowerCase() === "pcs") {
            return quantity;
        } else if (uom.toLowerCase() === "yard" || uom.toLowerCase() === "yds") {
            return quantity * 0.9144;
        } else {
            return quantity;
        }
    }

    joinConstructionString(material, materialConstruction, yarnMaterialNo, materialWidth) {
        if (material !== null && materialConstruction !== null && yarnMaterialNo !== null && materialWidth !== null) {
            return `'${material.replace(/'/g, '"') + " " + materialConstruction.replace(/'/g, '"') + " " + yarnMaterialNo.replace(/'/g, '"') + " " + materialWidth.replace(/'/g, '"')}'`;
        } else {
            return null;
        }
    }

    transform(data) {
        var result = data.map((items) => {
            var item = items;
            // var kanban = items.kanban;
            var orderUom = item.uom ? item.uom.unit : null;
            var orderQuantity = item.orderQuantity ? item.orderQuantity : null;
            var material = item.material ? item.material.name.replace(/'/g, '"') : null;
            var materialConstruction = item.materialConstruction ? item.materialConstruction.name.replace(/'/g, '"') : null;
            var yarnMaterialNo = item.yarnMaterial ? item.yarnMaterial.name.replace(/'/g, '"') : null;
            var materialWidth = item.materialWidth ? item.materialWidth : null;

            return {
                salesContractNo: item.salesContractNo ? `'${item.salesContractNo.replace(/'/g, '"')}'` : null,
                productionOrderNo: item.orderNo ? `'${item.orderNo.replace(/'/g, '"')}'` : null,
                orderType: item.orderType && item.orderType.name ? `'${item.orderType.name.replace(/'/g, '"')}'` : null,
                processType: item.processType && item.processType.name ? `'${item.processType.name.replace(/'/g, '"')}'` : null,
                material: item.material && item.material.name ? `'${item.material.name.replace(/'/g, '"')}'` : null,
                materialConstruction: item.materialConstruction && item.materialConstruction.name ? `'${item.materialConstruction.name.replace(/'/g, '"')}'` : null,
                yarnMaterialNo: item.yarnMaterial ? `'${item.yarnMaterial.name.replace(/'/g, '"')}'` : null,
                materialWidth: item.materialWidth ? `'${item.materialWidth.replace(/'/g, '"')}'` : null,
                orderQuantity: item.orderQuantity ? `${item.orderQuantity}` : null,
                orderUom: item.uom && item.uom.unit ? `'${item.uom.unit.replace(/'/g, '"')}'` : null,
                buyer: item.buyer ? `'${item.buyer.name.replace(/'/g, '"')}'` : null,
                buyerType: item.buyer ? `'${item.buyer.type.replace(/'/g, '"')}'` : null,
                deliveryDate: item.deliveryDate ? `'${moment(item.deliveryDate).add(7, "hours").format("YYYY-MM-DD")}'` : null,
                createdDate: item._createdDate ? `'${moment(item._createdDate).add(7, "hours").format("YYYY-MM-DD")}'` : null,
                totalOrderConvertion: item.orderQuantity ? `${this.orderQuantityConvertion(orderUom, orderQuantity)}` : null,
                construction: this.joinConstructionString(material.replace(/'/g, '"'), materialConstruction.replace(/'/g, '"'), yarnMaterialNo.replace(/'/g, '"'), materialWidth),
                buyerCode: item.buyer ? `'${item.buyer.code.replace(/'/g, '"')}'` : null,
                cartQuantity: null,
                kanbanCode: null,
                deleted: `'${item._deleted}'`,
                username: item.account && item.account.username ? `'${item.account.username.replace(/'/g, '"')}'` : null,
            }
        });
        return Promise.resolve([].concat.apply([], result));
    };

    insertQuery(sql, query) {
        return new Promise((resolve, reject) => {
            sql.query(query, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                };
            });
        });
    };

    load(data) {
        return new Promise((resolve, reject) => {
            this.sql.startConnection()
                .then(() => {

                    var transaction = this.sql.transaction();

                    transaction.begin((err) => {

                        var request = this.sql.transactionRequest(transaction);

                        var command = [];

                        var sqlQuery = '';

                        var count = 1;

                        for (var item of data) {
                            if (item) {
                                var queryString = `INSERT INTO DL_Fact_Production_Order_Temp([Nomor Sales Contract], [Nomor Order Produksi], [Jenis Order], [Jenis Proses], [Material], [Konstruksi Material], [Nomor Benang Material], [Lebar Material], [Jumlah Order Produksi], [Satuan], [Buyer], [Jenis Buyer], [Tanggal Delivery], [Created Date], [Jumlah Order Konversi], [Konstruksi], [Kode Buyer], [Jumlah Order(Kanban)], [Kode Kanban], [deleted], [Nama Sales]) VALUES(${item.salesContractNo}, ${item.productionOrderNo}, ${item.orderType}, ${item.processType}, ${item.material}, ${item.materialConstruction}, ${item.yarnMaterialNo}, ${item.materialWidth}, ${item.orderQuantity}, ${item.orderUom}, ${item.buyer}, ${item.buyerType}, ${item.deliveryDate}, ${item.createdDate}, ${item.totalOrderConvertion}, ${item.construction}, ${item.buyerCode}, ${item.cartQuantity}, ${item.kanbanCode}, ${item.deleted}, ${item.username});\n`;
                                sqlQuery = sqlQuery.concat(queryString);
                                if (count % 1000 == 0) {
                                    command.push(this.insertQuery(request, sqlQuery));
                                    sqlQuery = "";
                                }
                                console.log(`add data to query  : ${count}`);
                                count++;
                            }
                        }

                        if (sqlQuery != "")
                            command.push(this.insertQuery(request, `${sqlQuery}`));

                        this.sql.multiple = true;

                        // var fs = require("fs");
                        // var path = "C:\\Users\\IttaAndLeslie\\Desktop\\order.txt";

                        // fs.writeFile(path, sqlQuery, function (error) {
                        //     if (error) {
                        //         console.log("write error:  " + error.message);
                        //     } else {
                        //         console.log("Successful Write to " + path);
                        //     }
                        // });

                        return Promise.all(command)
                            .then((results) => {
                                request.execute("DL_UPSERT_FACT_PRODUCTION_ORDER").then((execResult) => {
                                    transaction.commit((err) => {
                                        if (err)
                                            reject(err);
                                        else
                                            resolve(results);
                                    });

                                }).catch((error) => {
                                    transaction.rollback((err) => {
                                        console.log("rollback")
                                        if (err)
                                            reject(err)
                                        else
                                            reject(error);
                                    });
                                })
                            })
                            .catch((error) => {
                                transaction.rollback((err) => {
                                    console.log("rollback");
                                    if (err)
                                        reject(err)
                                    else
                                        reject(error);
                                });
                            });
                    })
                })
                .catch((err) => {
                    reject(err);
                })
        })
            .catch((err) => {
                reject(err);
            })
    }
}<commit_msg>update fact-production-order-etl-manager.js<commit_after>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require("module-toolkit").BaseManager;
var moment = require("moment");
const SELECTED_FIELDS = {
    "_id": 1,
    "salesContractNo": 1,
    "uom.unit": 1,
    "orderQuantity": 1,
    "material.name": 1,
    "materialConstruction.name": 1,
    "yarnMaterial.name": 1,
    "materialWidth": 1,
    "orderNo": 1,
    "orderType.name": 1,
    "processType.name": 1,
    "buyer.name": 1,
    "buyer.type": 1,
    "deliveryDate": 1,
    "_createdDate": 1,
    "buyer.code": 1,
    "_deleted": 1,
    "isClosed": 1
}

// internal deps
require("mongodb-toolkit");

var ProductionOrderManager = require("../../managers/sales/production-order-manager");

module.exports = class FactProductionOrderEtlManager extends BaseManager {
    constructor(db, user, sql) {
        super(db, user);
        this.sql = sql;
        this.productionOrderManager = new ProductionOrderManager(db, user);
        this.migrationLog = this.db.collection("migration-log");
    }

    run() {
        var startedDate = new Date()
        this.migrationLog.insert({
            description: "Fact Production Order from MongoDB to Azure DWH",
            start: startedDate,
        })
        return this.timestamp()
            .then((time) => this.extract(time))
            .then((data) => this.transform(data))
            .then((data) => this.load(data))
            .then((results) => {
                console.log("Success!");
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Production Order from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: "Successful"
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            })
            .catch((err) => {
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Production Order from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: err
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            });
    };

    timestamp() {
        return this.migrationLog.find({
            description: "Fact Production Order from MongoDB to Azure DWH",
            status: "Successful"
        }).sort({ finish: -1 }).limit(1).toArray()
    }

    extract(times) {
        var time = times.length > 0 ? times[0].start : "1970-01-01";
        var timestamp = new Date(time);
        return this.productionOrderManager.collection.find({
            _updatedDate: {
                $gt: timestamp
            }
        }).toArray()
    }

    orderQuantityConvertion(uom, quantity) {
        if (uom.toLowerCase() === "met" || uom.toLowerCase() === "mtr" || uom.toLowerCase() === "pcs") {
            return quantity;
        } else if (uom.toLowerCase() === "yard" || uom.toLowerCase() === "yds") {
            return quantity * 0.9144;
        } else {
            return quantity;
        }
    }

    joinConstructionString(material, materialConstruction, yarnMaterialNo, materialWidth) {
        if (material !== null && materialConstruction !== null && yarnMaterialNo !== null && materialWidth !== null) {
            return `'${material.replace(/'/g, '"') + " " + materialConstruction.replace(/'/g, '"') + " " + yarnMaterialNo.replace(/'/g, '"') + " " + materialWidth.replace(/'/g, '"')}'`;
        } else {
            return null;
        }
    }

    transform(data) {
        var result = data.map((items) => {
            var item = items;
            // var kanban = items.kanban;
            var orderUom = item.uom ? item.uom.unit : null;
            var orderQuantity = item.orderQuantity ? item.orderQuantity : null;
            var material = item.material ? item.material.name.replace(/'/g, '"') : null;
            var materialConstruction = item.materialConstruction ? item.materialConstruction.name.replace(/'/g, '"') : null;
            var yarnMaterialNo = item.yarnMaterial ? item.yarnMaterial.name.replace(/'/g, '"') : null;
            var materialWidth = item.materialWidth ? item.materialWidth : null;

            return {
                salesContractNo: item.salesContractNo ? `'${item.salesContractNo.replace(/'/g, '"')}'` : null,
                productionOrderNo: item.orderNo ? `'${item.orderNo.replace(/'/g, '"')}'` : null,
                orderType: item.orderType && item.orderType.name ? `'${item.orderType.name.replace(/'/g, '"')}'` : null,
                processType: item.processType && item.processType.name ? `'${item.processType.name.replace(/'/g, '"')}'` : null,
                material: item.material && item.material.name ? `'${item.material.name.replace(/'/g, '"')}'` : null,
                materialConstruction: item.materialConstruction && item.materialConstruction.name ? `'${item.materialConstruction.name.replace(/'/g, '"')}'` : null,
                yarnMaterialNo: item.yarnMaterial ? `'${item.yarnMaterial.name.replace(/'/g, '"')}'` : null,
                materialWidth: item.materialWidth ? `'${item.materialWidth.replace(/'/g, '"')}'` : null,
                orderQuantity: item.orderQuantity ? `${item.orderQuantity}` : null,
                orderUom: item.uom && item.uom.unit ? `'${item.uom.unit.replace(/'/g, '"')}'` : null,
                buyer: item.buyer ? `'${item.buyer.name.replace(/'/g, '"')}'` : null,
                buyerType: item.buyer ? `'${item.buyer.type.replace(/'/g, '"')}'` : null,
                deliveryDate: item.deliveryDate ? `'${moment(item.deliveryDate).add(7, "hours").format("YYYY-MM-DD")}'` : null,
                createdDate: item._createdDate ? `'${moment(item._createdDate).add(7, "hours").format("YYYY-MM-DD")}'` : null,
                totalOrderConvertion: item.orderQuantity ? `${this.orderQuantityConvertion(orderUom, orderQuantity)}` : null,
                construction: this.joinConstructionString(material.replace(/'/g, '"'), materialConstruction.replace(/'/g, '"'), yarnMaterialNo.replace(/'/g, '"'), materialWidth),
                buyerCode: item.buyer ? `'${item.buyer.code.replace(/'/g, '"')}'` : null,
                cartQuantity: null,
                kanbanCode: null,
                deleted: `'${item._deleted}'`,
                username: item.account && item.account.username ? `'${item.account.username.replace(/'/g, '"')}'` : null,
                isClosed: `'${item.isClosed}'`,
            }
        });
        return Promise.resolve([].concat.apply([], result));
    };

    insertQuery(sql, query) {
        return new Promise((resolve, reject) => {
            sql.query(query, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                };
            });
        });
    };

    load(data) {
        return new Promise((resolve, reject) => {
            this.sql.startConnection()
                .then(() => {

                    var transaction = this.sql.transaction();

                    transaction.begin((err) => {

                        var request = this.sql.transactionRequest(transaction);

                        var command = [];

                        var sqlQuery = '';

                        var count = 1;

                        for (var item of data) {
                            if (item) {
                                var queryString = `INSERT INTO DL_Fact_Production_Order_Temp([Nomor Sales Contract], [Nomor Order Produksi], [Jenis Order], [Jenis Proses], [Material], [Konstruksi Material], [Nomor Benang Material], [Lebar Material], [Jumlah Order Produksi], [Satuan], [Buyer], [Jenis Buyer], [Tanggal Delivery], [Created Date], [Jumlah Order Konversi], [Konstruksi], [Kode Buyer], [Jumlah Order(Kanban)], [Kode Kanban], [deleted], [Nama Sales], [isClosed]) VALUES(${item.salesContractNo}, ${item.productionOrderNo}, ${item.orderType}, ${item.processType}, ${item.material}, ${item.materialConstruction}, ${item.yarnMaterialNo}, ${item.materialWidth}, ${item.orderQuantity}, ${item.orderUom}, ${item.buyer}, ${item.buyerType}, ${item.deliveryDate}, ${item.createdDate}, ${item.totalOrderConvertion}, ${item.construction}, ${item.buyerCode}, ${item.cartQuantity}, ${item.kanbanCode}, ${item.deleted}, ${item.username}, ${item.isClosed});\n`;
                                sqlQuery = sqlQuery.concat(queryString);
                                if (count % 1000 == 0) {
                                    command.push(this.insertQuery(request, sqlQuery));
                                    sqlQuery = "";
                                }
                                console.log(`add data to query  : ${count}`);
                                count++;
                            }
                        }

                        if (sqlQuery != "")
                            command.push(this.insertQuery(request, `${sqlQuery}`));

                        this.sql.multiple = true;

                        // var fs = require("fs");
                        // var path = "C:\\Users\\IttaAndLeslie\\Desktop\\order.txt";

                        // fs.writeFile(path, sqlQuery, function (error) {
                        //     if (error) {
                        //         console.log("write error:  " + error.message);
                        //     } else {
                        //         console.log("Successful Write to " + path);
                        //     }
                        // });

                        return Promise.all(command)
                            .then((results) => {
                                request.execute("DL_UPSERT_FACT_PRODUCTION_ORDER").then((execResult) => {
                                    transaction.commit((err) => {
                                        if (err)
                                            reject(err);
                                        else
                                            resolve(results);
                                    });

                                }).catch((error) => {
                                    transaction.rollback((err) => {
                                        console.log("rollback")
                                        if (err)
                                            reject(err)
                                        else
                                            reject(error);
                                    });
                                })
                            })
                            .catch((error) => {
                                transaction.rollback((err) => {
                                    console.log("rollback");
                                    if (err)
                                        reject(err)
                                    else
                                        reject(error);
                                });
                            });
                    })
                })
                .catch((err) => {
                    reject(err);
                })
        })
            .catch((err) => {
                reject(err);
            })
    }
}<|endoftext|>


<commit_before>/**
 * lifesized: Get the physical size of displays and their ppi
 */

var screen = require('screen'),
    remote = require('remote'),
    execSync = require('child_process').execSync,
    path = require('path'),
    os = require('os');

var lifesized = {

    /**
     * Get the pixels per inch of a screen
     *
     * @param [screen] (Electron Screen Instance) If not provided the display
              this process' BrowserWindow' is over will be used
     */
    ppi: function(screen){
        screen = screen || getBrowserWindowDisplay();
        return getPPI(screen);
    }
};

/**
 * Get the display that the window is mostly over
 */
function getBrowserWindowDisplay(){
    return screen.getDisplayMatching(remote.getCurrentWindow().getBounds());
}

/**
 * Get a screens PPI
 */
function getPPI(screen){
    // If on a mac use our native binary to do the work, otherwise fall back
    // to a default
    if(os.platform() === "darwin"){
        return  parseFloat(
                    execSync(
                        path.resolve(__dirname, "../bin/lifesized-cli") + " " + screen.id
                    )
                );
    } else {
        return 72.0;
    }
}

module.exports = lifesized;
<commit_msg>Fix for working in the main process<commit_after>/**
 * lifesized: Get the physical size of displays and their ppi
 */

var screen = require('screen'),
    execSync = require('child_process').execSync,
    path = require('path'),
    os = require('os');

var lifesized = {

    /**
     * Get the pixels per inch of a screen
     *
     * @param [screen] (Electron Screen Instance) If not provided the display
              this process' BrowserWindow' is over will be used
     */
    ppi: function(display){
        display = display || getBrowserWindowDisplay();
        return getPPI(display);
    }
};

/**
 * Get the display that the window is mostly over
 */
function getBrowserWindowDisplay(){
    // Don't require remote unless we hit here as it can't be required in the
    // main process. Main processes need to provide
    var remote = require('remote');
    return screen.getDisplayMatching(remote.getCurrentWindow().getBounds());
}

/**
 * Get a screens PPI
 */
function getPPI(display){
    // If on a mac use our native binary to do the work, otherwise fall back
    // to a default
    if(os.platform() === "darwin"){
        return  parseFloat(
                    execSync(
                        path.resolve(__dirname, "../bin/lifesized-cli") + " " + display.id
                    )
                );
    } else {
        return 72.0;
    }
}

module.exports = lifesized;
<|endoftext|>


<commit_before><commit_msg>Removed unused fixture<commit_after><|endoftext|>


<commit_before>export default {
  name: 'path',

  lookup (req, res, options) {
    let found;

    if (req === undefined) {
      return found;
    }

    if (options.lookupPath !== undefined) {
      found = req.params[options.lookupPath];
    }

    if (!found && options.lookupFromPathIndex !== undefined) {
      let path = req.originalUrl.split('?')[0];
      let parts = path.split('/');
      if (parts[0] === '') { // Handle paths that start with a slash, i.e., '/foo' -> ['', 'foo']
        parts.shift();
      }

      if (parts.length > options.lookupFromPathIndex) {
        found = parts[options.lookupFromPathIndex];
      }
    }

    return found;
  }
};
<commit_msg>add checks for req properties<commit_after>export default {
  name: 'path',

  lookup (req, res, options) {
    let found;

    if (req === undefined) {
      return found;
    }

    if (options.lookupPath !== undefined && req.params) {
      found = req.params[options.lookupPath];
    }

    if (!found && typeof options.lookupFromPathIndex === 'number' && req.originalUrl) {
      let path = req.originalUrl.split('?')[0];
      let parts = path.split('/');
      if (parts[0] === '') { // Handle paths that start with a slash, i.e., '/foo' -> ['', 'foo']
        parts.shift();
      }

      if (parts.length > options.lookupFromPathIndex) {
        found = parts[options.lookupFromPathIndex];
      }
    }

    return found;
  }
};
<|endoftext|>


<commit_before>/** @jsx React.DOM */
var React = require('react');
window.React = React;
var pkg = require('../package.json');
var d3 = require('d3');
var Chart = require('./common').Chart;

var Line = React.createClass({

  propTypes: {
    strokeWidth: React.PropTypes.number,
    path: React.PropTypes.string,
    fill: React.PropTypes.string,
    stroke: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      stroke: '#1f77b4',
      fill: 'none'
    }
  },

  render: function() {
    return (
      <path
        d={this.props.path}
        stroke={this.props.stroke}
        fill={this.props.fill}
        strokeWidth={this.props.strokeWidth}
      />
    );
  }

});

var Circle = React.createClass({

  propTypes: {
    cx: React.PropTypes.number,
    cy: React.PropTypes.number,
    r: React.PropTypes.number,
    fill: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      fill: '#1f77b4'
    }
  },

  render: function() {
    return (
      <circle
        cx={this.props.cx}
        cy={this.props.cy}
        r={this.props.r}
        fill={this.props.fill}
      />
    );
  }

});

var DataSeries = React.createClass({

  propTypes: {
    data: React.PropTypes.array,
    interpolate: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      data: [],
      interpolate: 'linear'
    }
  },

  render: function() {
    var self = this;
    var interpolatePath = d3.svg.line()
        .x(function(d) { return self.props.xScale(d.x); })
        .y(function(d) { return self.props.yScale(d.y); })
        .interpolate(this.props.interpolate);

    return (
      <Line path={interpolatePath(this.props.data)} />
    )
  }

});

var LineChart = React.createClass({

  propTypes: {
    pointRadius: React.PropTypes.number,
    width: React.PropTypes.number,
    height: React.PropTypes.number
  },

  getDefaultProps: function() {
    return {
      pointRadius: 2,
      width: 400,
      height: 200
    }
  },

  render: function() {

    var data = this.props.data;

    var size = { width: this.props.width, height: this.props.height };

    var maxY = d3.max(data, function(d) {
      return d.y;
    });

    var maxX = d3.max(data, function(d) {
      return d.x;
    });

    var xScale = d3.scale.linear()
      .domain([0, maxX])
      .range([0, this.props.width]);

    var yScale = d3.scale.linear()
      .domain([0, maxY])
      .range([this.props.height, 0]);

    var circles = [];
    this.props.data.forEach(function(point) {
      circles.push(<Circle cx={xScale(point.x)} cy={yScale(point.y)} r={this.props.pointRadius}  />);
    }.bind(this));

    return (
      <Chart width={this.props.width} height={this.props.height}>
        <DataSeries
          xScale={xScale}
          yScale={yScale}
          data={this.props.data}
          width={this.props.width}
          height={this.props.height}
        />
        {circles}
      </Chart>
    );
  }

});

exports.LineChart = LineChart;
<commit_msg>Fixed missing linechart keys<commit_after>/** @jsx React.DOM */
var React = require('react');
window.React = React;
var pkg = require('../package.json');
var d3 = require('d3');
var Chart = require('./common').Chart;

var Line = React.createClass({

  propTypes: {
    strokeWidth: React.PropTypes.number,
    path: React.PropTypes.string,
    fill: React.PropTypes.string,
    stroke: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      stroke: '#1f77b4',
      fill: 'none'
    }
  },

  render: function() {
    return (
      <path
        d={this.props.path}
        stroke={this.props.stroke}
        fill={this.props.fill}
        strokeWidth={this.props.strokeWidth}
      />
    );
  }

});

var Circle = React.createClass({

  propTypes: {
    cx: React.PropTypes.number,
    cy: React.PropTypes.number,
    r: React.PropTypes.number,
    fill: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      fill: '#1f77b4'
    }
  },

  render: function() {
    return (
      <circle
        cx={this.props.cx}
        cy={this.props.cy}
        r={this.props.r}
        fill={this.props.fill}
      />
    );
  }

});

var DataSeries = React.createClass({

  propTypes: {
    data: React.PropTypes.array,
    interpolate: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      data: [],
      interpolate: 'linear'
    }
  },

  render: function() {
    var self = this;
    var interpolatePath = d3.svg.line()
        .x(function(d) { return self.props.xScale(d.x); })
        .y(function(d) { return self.props.yScale(d.y); })
        .interpolate(this.props.interpolate);

    return (
      <Line path={interpolatePath(this.props.data)} />
    )
  }

});

var LineChart = React.createClass({

  propTypes: {
    pointRadius: React.PropTypes.number,
    width: React.PropTypes.number,
    height: React.PropTypes.number
  },

  getDefaultProps: function() {
    return {
      pointRadius: 2,
      width: 400,
      height: 200
    }
  },

  render: function() {

    var data = this.props.data;

    var size = { width: this.props.width, height: this.props.height };

    var maxY = d3.max(data, function(d) {
      return d.y;
    });

    var maxX = d3.max(data, function(d) {
      return d.x;
    });

    var xScale = d3.scale.linear()
      .domain([0, maxX])
      .range([0, this.props.width]);

    var yScale = d3.scale.linear()
      .domain([0, maxY])
      .range([this.props.height, 0]);

    var circles = [];
    this.props.data.forEach(function(point, i) {
      circles.push(<Circle cx={xScale(point.x)} cy={yScale(point.y)} r={this.props.pointRadius} key={i} />);
    }.bind(this));

    return (
      <Chart width={this.props.width} height={this.props.height}>
        <DataSeries
          xScale={xScale}
          yScale={yScale}
          data={this.props.data}
          width={this.props.width}
          height={this.props.height}
        />
        {circles}
      </Chart>
    );
  }

});

exports.LineChart = LineChart;
<|endoftext|>


<commit_before>/*
Language: JavaScript
Category: common, scripting
*/

function(hljs) {
  return {
    aliases: ['js'],
    keywords: {
      keyword:
        'in of if for while finally var new function do return void else break catch ' +
        'instanceof with throw case default try this switch continue typeof delete ' +
        'let yield const export super debugger as',
      literal:
        'true false null undefined NaN Infinity',
      built_in:
        'eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent ' +
        'encodeURI encodeURIComponent escape unescape Object Function Boolean Error ' +
        'EvalError InternalError RangeError ReferenceError StopIteration SyntaxError ' +
        'TypeError URIError Number Math Date String RegExp Array Float32Array ' +
        'Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array ' +
        'Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require ' +
        'module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect ' +
        'Promise'
    },
    contains: [
      {
        className: 'pi',
        relevance: 10,
        variants: [
          {begin: /^\s*('|")use strict('|")/},
          {begin: /^\s*('|")use asm('|")/}
        ]
      },
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      { // template string
        className: 'string',
        begin: '`', end: '`',
        contains: [
          hljs.BACKSLASH_ESCAPE,
          {
            className: 'subst',
            begin: '\\$\\{', end: '\\}'
          }
        ]
      },
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'number',
        begin: '\\b(0[xXbBoO][a-fA-F0-9]+|(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)', // 0x..., 0..., 0b..., 0o..., decimal, float
        relevance: 0
      },
      { // "value" container
        begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
        keywords: 'return throw case',
        contains: [
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          hljs.REGEXP_MODE,
          { // E4X / JSX
            begin: /</, end: />\s*[);\]]/,
            relevance: 0,
            subLanguage: 'xml'
          }
        ],
        relevance: 0
      },
      {
        className: 'function',
        beginKeywords: 'function', end: /\{/, excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/}),
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            contains: [
              hljs.C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE
            ],
            illegal: /["'\(]/
          }
        ],
        illegal: /\[|%/
      },
      {
        begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      },
      {
        begin: '\\.' + hljs.IDENT_RE, relevance: 0 // hack: prevents detection of keywords after dots
      },
      // ECMAScript 6 modules import
      {
        beginKeywords: 'import', end: '[;$]',
        keywords: 'import from as',
        contains: [
          hljs.APOS_STRING_MODE,
          hljs.QUOTE_STRING_MODE
        ]
      },
      { // ES6 class
        className: 'class',
        beginKeywords: 'class', end: /[{;=]/, excludeEnd: true,
        illegal: /[:"\[\]]/,
        contains: [
          {beginKeywords: 'extends'},
          hljs.UNDERSCORE_TITLE_MODE
        ]
      }
    ]
  };
}
<commit_msg>Add `await` to ES6 keywords<commit_after>/*
Language: JavaScript
Category: common, scripting
*/

function(hljs) {
  return {
    aliases: ['js'],
    keywords: {
      keyword:
        'in of if for while finally var new function do return void else break catch ' +
        'instanceof with throw case default try this switch continue typeof delete ' +
        'let yield const export super debugger as await',
      literal:
        'true false null undefined NaN Infinity',
      built_in:
        'eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent ' +
        'encodeURI encodeURIComponent escape unescape Object Function Boolean Error ' +
        'EvalError InternalError RangeError ReferenceError StopIteration SyntaxError ' +
        'TypeError URIError Number Math Date String RegExp Array Float32Array ' +
        'Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array ' +
        'Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require ' +
        'module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect ' +
        'Promise'
    },
    contains: [
      {
        className: 'pi',
        relevance: 10,
        variants: [
          {begin: /^\s*('|")use strict('|")/},
          {begin: /^\s*('|")use asm('|")/}
        ]
      },
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      { // template string
        className: 'string',
        begin: '`', end: '`',
        contains: [
          hljs.BACKSLASH_ESCAPE,
          {
            className: 'subst',
            begin: '\\$\\{', end: '\\}'
          }
        ]
      },
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'number',
        begin: '\\b(0[xXbBoO][a-fA-F0-9]+|(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)', // 0x..., 0..., 0b..., 0o..., decimal, float
        relevance: 0
      },
      { // "value" container
        begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
        keywords: 'return throw case',
        contains: [
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          hljs.REGEXP_MODE,
          { // E4X / JSX
            begin: /</, end: />\s*[);\]]/,
            relevance: 0,
            subLanguage: 'xml'
          }
        ],
        relevance: 0
      },
      {
        className: 'function',
        beginKeywords: 'function', end: /\{/, excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/}),
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            contains: [
              hljs.C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE
            ],
            illegal: /["'\(]/
          }
        ],
        illegal: /\[|%/
      },
      {
        begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      },
      {
        begin: '\\.' + hljs.IDENT_RE, relevance: 0 // hack: prevents detection of keywords after dots
      },
      // ECMAScript 6 modules import
      {
        beginKeywords: 'import', end: '[;$]',
        keywords: 'import from as',
        contains: [
          hljs.APOS_STRING_MODE,
          hljs.QUOTE_STRING_MODE
        ]
      },
      { // ES6 class
        className: 'class',
        beginKeywords: 'class', end: /[{;=]/, excludeEnd: true,
        illegal: /[:"\[\]]/,
        contains: [
          {beginKeywords: 'extends'},
          hljs.UNDERSCORE_TITLE_MODE
        ]
      }
    ]
  };
}
<|endoftext|>


<commit_before>'use strict';

const Set = require('../../utils/objects/set'),
    _ = require('lodash'),
    _v = require('./validations'),
    JDLEnum = require('../jdl_enum'),
    VALIDATIONS = _v.VALIDATIONS,
    buildException = require('../../exceptions/exception_factory').buildException,
    exceptions = require('../../exceptions/exception_factory').exceptions;

const SQL_TYPES = {
  STRING: 'String',
  INTEGER: 'Integer',
  LONG: 'Long',
  BIG_DECIMAL: 'BigDecimal',
  FLOAT: 'Float',
  DOUBLE: 'Float',
  ENUM: 'Enum',
  BOOLEAN: 'Boolean',
  LOCAL_DATE: 'LocalDate',
  ZONED_DATE_TIME: 'ZonedDateTime',
  BLOB: 'Blob',
  ANY_BLOB: 'AnyBlob',
  IMAGE_BLOB: 'ImageBlob'
};

const SQL_VALIDATIONS = {
  String: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINLENGTH, VALIDATIONS.MAXLENGTH, VALIDATIONS.PATTERN]),
  Integer: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Long: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  BigDecimal: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Float: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Double: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Enum: new Set([VALIDATIONS.REQUIRED]),
  Boolean: new Set([VALIDATIONS.REQUIRED]),
  LocalDate: new Set([VALIDATIONS.REQUIRED]),
  ZonedDateTime: new Set([VALIDATIONS.REQUIRED]),
  Blob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  AnyBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  ImageBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES])
};

const MONGODB_TYPES = {
  STRING: 'String',
  INTEGER: 'Integer',
  LONG: 'Long',
  BIG_DECIMAL: 'BigDecimal',
  FLOAT: 'Float',
  DOUBLE: 'Float',
  ENUM: 'Enum',
  BOOLEAN: 'Boolean',
  LOCAL_DATE: 'LocalDate',
  ZONED_DATE_TIME: 'ZonedDateTime',
  BLOB: 'Blob',
  ANY_BLOB: 'AnyBlob',
  IMAGE_BLOB: 'ImageBlob'
};

const MONGODB_VALIDATIONS = {
  String: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINLENGTH, VALIDATIONS.MAXLENGTH, VALIDATIONS.PATTERN]),
  Integer: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Long: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  BigDecimal: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Float: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Double: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Enum: new Set([VALIDATIONS.REQUIRED]),
  Boolean: new Set([VALIDATIONS.REQUIRED]),
  LocalDate: new Set([VALIDATIONS.REQUIRED]),
  ZonedDateTime: new Set([VALIDATIONS.REQUIRED]),
  Blob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  AnyBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  ImageBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES])
};

const CASSANDRA_TYPES = {
  STRING: 'String',
  INTEGER: 'Integer',
  LONG: 'Long',
  BIG_DECIMAL: 'BigDecimal',
  FLOAT: 'Float',
  DOUBLE: 'Float',
  BOOLEAN: 'Boolean',
  DATE: 'Date',
  UUID: 'UUID'
};

const CASSANDRA_VALIDATIONS = {
  String: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINLENGTH, VALIDATIONS.MAXLENGTH, VALIDATIONS.PATTERN]),
  Integer: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Long: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  BigDecimal: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Float: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Double: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Boolean: new Set([VALIDATIONS.REQUIRED]),
  Date: new Set([VALIDATIONS.REQUIRED]),
  UUID: new Set([VALIDATIONS.REQUIRED])
};

function isSQLType(type) {
  if (!type) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  return (_.snakeCase(type).toUpperCase() in SQL_TYPES) || type instanceof JDLEnum;
}

function isMongoDBType(type) {
  if (!type) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  return (_.snakeCase(type).toUpperCase() in MONGODB_TYPES) || type instanceof JDLEnum;
}

function isCassandraType(type) {
  if (!type) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  return (_.snakeCase(type).toUpperCase() in CASSANDRA_TYPES) && !(type instanceof JDLEnum);
}

function hasValidation(type, validation, isAnEnum) {
  if (!type || !validation) {
    throw new buildException(exceptions.NullPointer, 'The passed type and value must not be nil.');
  }
  var concreteType = type;
  if (isAnEnum) {
    concreteType = 'Enum'
  }
  return (isSQLType(concreteType) && SQL_VALIDATIONS[concreteType].has(validation))
      || (isMongoDBType(concreteType) && MONGODB_VALIDATIONS[concreteType].has(validation))
      || (isCassandraType(concreteType) && CASSANDRA_VALIDATIONS[concreteType].has(validation));
}

function getIsType(databaseType, cb) {
  if (!databaseType) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  let isType;
  switch (databaseType) {
    case 'sql':
    case 'mysql':
    case 'postgresql':
    case 'oracle':
      isType = isSQLType;
      break;
    case 'mongodb':
      isType = isMongoDBType;
      break;
    case 'cassandra':
      isType = isCassandraType;
      break;
    default:
      cb && cb();
      throw new buildException(
          exceptions.IllegalArgument,
          "The passed database type must either be 'sql', 'mysql', 'postgresql', 'oracle', 'mongodb', or 'cassandra'");
  }
  return isType;
}

module.exports = {
  SQL_TYPES: SQL_TYPES,
  MONGODB_TYPES: MONGODB_TYPES,
  CASSANDRA_TYPES: CASSANDRA_TYPES,
  isSQLType: isSQLType,
  isMongoDBType: isMongoDBType,
  isCassandraType: isCassandraType,
  hasValidation: hasValidation,
  getIsType: getIsType
};
<commit_msg>polish<commit_after>'use strict';

const Set = require('../../utils/objects/set'),
    _ = require('lodash'),
    _v = require('./validations'),
    JDLEnum = require('../jdl_enum'),
    VALIDATIONS = _v.VALIDATIONS,
    DatabaseTypes = require('./database_types').Types,
    buildException = require('../../exceptions/exception_factory').buildException,
    exceptions = require('../../exceptions/exception_factory').exceptions;

const SQL_TYPES = {
  STRING: 'String',
  INTEGER: 'Integer',
  LONG: 'Long',
  BIG_DECIMAL: 'BigDecimal',
  FLOAT: 'Float',
  DOUBLE: 'Float',
  ENUM: 'Enum',
  BOOLEAN: 'Boolean',
  LOCAL_DATE: 'LocalDate',
  ZONED_DATE_TIME: 'ZonedDateTime',
  BLOB: 'Blob',
  ANY_BLOB: 'AnyBlob',
  IMAGE_BLOB: 'ImageBlob'
};

const SQL_VALIDATIONS = {
  String: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINLENGTH, VALIDATIONS.MAXLENGTH, VALIDATIONS.PATTERN]),
  Integer: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Long: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  BigDecimal: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Float: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Double: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Enum: new Set([VALIDATIONS.REQUIRED]),
  Boolean: new Set([VALIDATIONS.REQUIRED]),
  LocalDate: new Set([VALIDATIONS.REQUIRED]),
  ZonedDateTime: new Set([VALIDATIONS.REQUIRED]),
  Blob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  AnyBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  ImageBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES])
};

const MONGODB_TYPES = {
  STRING: 'String',
  INTEGER: 'Integer',
  LONG: 'Long',
  BIG_DECIMAL: 'BigDecimal',
  FLOAT: 'Float',
  DOUBLE: 'Float',
  ENUM: 'Enum',
  BOOLEAN: 'Boolean',
  LOCAL_DATE: 'LocalDate',
  ZONED_DATE_TIME: 'ZonedDateTime',
  BLOB: 'Blob',
  ANY_BLOB: 'AnyBlob',
  IMAGE_BLOB: 'ImageBlob'
};

const MONGODB_VALIDATIONS = {
  String: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINLENGTH, VALIDATIONS.MAXLENGTH, VALIDATIONS.PATTERN]),
  Integer: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Long: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  BigDecimal: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Float: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Double: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Enum: new Set([VALIDATIONS.REQUIRED]),
  Boolean: new Set([VALIDATIONS.REQUIRED]),
  LocalDate: new Set([VALIDATIONS.REQUIRED]),
  ZonedDateTime: new Set([VALIDATIONS.REQUIRED]),
  Blob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  AnyBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES]),
  ImageBlob: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINBYTES, VALIDATIONS.MAXBYTES])
};

const CASSANDRA_TYPES = {
  STRING: 'String',
  INTEGER: 'Integer',
  LONG: 'Long',
  BIG_DECIMAL: 'BigDecimal',
  FLOAT: 'Float',
  DOUBLE: 'Float',
  BOOLEAN: 'Boolean',
  DATE: 'Date',
  UUID: 'UUID'
};

const CASSANDRA_VALIDATIONS = {
  String: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MINLENGTH, VALIDATIONS.MAXLENGTH, VALIDATIONS.PATTERN]),
  Integer: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Long: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  BigDecimal: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Float: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Double: new Set([VALIDATIONS.REQUIRED, VALIDATIONS.MIN, VALIDATIONS.MAX]),
  Boolean: new Set([VALIDATIONS.REQUIRED]),
  Date: new Set([VALIDATIONS.REQUIRED]),
  UUID: new Set([VALIDATIONS.REQUIRED])
};

function isSQLType(type) {
  if (!type) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  return (_.snakeCase(type).toUpperCase() in SQL_TYPES) || type instanceof JDLEnum;
}

function isMongoDBType(type) {
  if (!type) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  return (_.snakeCase(type).toUpperCase() in MONGODB_TYPES) || type instanceof JDLEnum;
}

function isCassandraType(type) {
  if (!type) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  return (_.snakeCase(type).toUpperCase() in CASSANDRA_TYPES) && !(type instanceof JDLEnum);
}

function hasValidation(type, validation, isAnEnum) {
  if (!type || !validation) {
    throw new buildException(exceptions.NullPointer, 'The passed type and value must not be nil.');
  }
  var concreteType = type;
  if (isAnEnum) {
    concreteType = 'Enum'
  }
  return (isSQLType(concreteType) && SQL_VALIDATIONS[concreteType].has(validation))
      || (isMongoDBType(concreteType) && MONGODB_VALIDATIONS[concreteType].has(validation))
      || (isCassandraType(concreteType) && CASSANDRA_VALIDATIONS[concreteType].has(validation));
}

function getIsType(databaseType, cb) {
  if (!databaseType) {
    throw new buildException(exceptions.NullPointer, 'The passed type must not be nil.');
  }
  let isType;
  switch (databaseType) {
    case DatabaseTypes.sql:
    case DatabaseTypes.mysql:
    case DatabaseTypes.postgresql:
    case DatabaseTypes.oracle:
      isType = isSQLType;
      break;
    case DatabaseTypes.mongodb:
      isType = isMongoDBType;
      break;
    case DatabaseTypes.cassandra:
      isType = isCassandraType;
      break;
    default:
      cb && cb();
      throw new buildException(
          exceptions.IllegalArgument,
          "The passed database type must either be 'sql', 'mysql', 'postgresql', 'oracle', 'mongodb', or 'cassandra'");
  }
  return isType;
}

module.exports = {
  SQL_TYPES: SQL_TYPES,
  MONGODB_TYPES: MONGODB_TYPES,
  CASSANDRA_TYPES: CASSANDRA_TYPES,
  isSQLType: isSQLType,
  isMongoDBType: isMongoDBType,
  isCassandraType: isCassandraType,
  hasValidation: hasValidation,
  getIsType: getIsType
};
<|endoftext|>


<commit_before>/*
 * L.TileLayer is used for standard xyz-numbered tile layers.
 */

L.TileLayer = L.GridLayer.extend({

	options: {
		maxZoom: 18,

		subdomains: 'abc',
		errorTileUrl: '',
		zoomOffset: 0,

		maxNativeZoom: null, // Number
		tms: false,
		zoomReverse: false,
		detectRetina: false,
		crossOrigin: false
	},

	initialize: function (url, options) {

		this._url = url;

		options = L.setOptions(this, options);

		// detecting retina displays, adjusting tileSize and zoom levels
		if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {

			options.tileSize = Math.floor(options.tileSize / 2);
			options.zoomOffset++;

			options.minZoom = Math.max(0, options.minZoom);
			options.maxZoom--;
		}

		if (typeof options.subdomains === 'string') {
			options.subdomains = options.subdomains.split('');
		}

		// for https://github.com/Leaflet/Leaflet/issues/137
		if (!L.Browser.android) {
			this.on('tileunload', this._onTileRemove);
		}
	},

	setUrl: function (url, noRedraw) {
		this._url = url;

		if (!noRedraw) {
			this.redraw();
		}
		return this;
	},

	createTile: function (coords, done) {
		var tile = document.createElement('img');

		L.DomEvent.on(tile, 'load', L.bind(this._tileOnLoad, this, done, tile));
		L.DomEvent.on(tile, 'error', L.bind(this._tileOnError, this, done, tile));

		if (this.options.crossOrigin) {
			tile.crossOrigin = '';
		}

		/*
		 Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
		 http://www.w3.org/TR/WCAG20-TECHS/H67
		*/
		tile.alt = '';

		tile.src = this.getTileUrl(coords);

		return tile;
	},

	getTileUrl: function (coords) {
		return L.Util.template(this._url, L.extend({
			r: this.options.detectRetina && L.Browser.retina && this.options.maxZoom > 0 ? '@2x' : '',
			s: this._getSubdomain(coords),
			x: coords.x,
			y: this.options.tms ? this._globalTileRange.max.y - coords.y : coords.y,
			z: this._getZoomForUrl()
		}, this.options));
	},

	_tileOnLoad: function (done, tile) {
		// For https://github.com/Leaflet/Leaflet/issues/3332
		if (L.Browser.ielt9) {
			setTimeout(L.bind(done, this, null, tile), 0);
		} else {
			done(null, tile);
		}
	},

	_tileOnError: function (done, tile, e) {
		var errorUrl = this.options.errorTileUrl;
		if (errorUrl) {
			tile.src = errorUrl;
		}
		done(e, tile);
	},

	getTileSize: function () {
		var map = this._map,
		    tileSize = L.GridLayer.prototype.getTileSize.call(this),
		    zoom = this._tileZoom + this.options.zoomOffset,
		    zoomN = this.options.maxNativeZoom;

		// increase tile size when overscaling
		return zoomN !== null && zoom > zoomN ?
				tileSize.divideBy(map.getZoomScale(zoomN, zoom)).round() :
				tileSize;
	},

	_onTileRemove: function (e) {
		e.tile.onload = null;
	},

	_getZoomForUrl: function () {

		var options = this.options,
		    zoom = this._tileZoom;

		if (options.zoomReverse) {
			zoom = options.maxZoom - zoom;
		}

		zoom += options.zoomOffset;

		return options.maxNativeZoom !== null ? Math.min(zoom, options.maxNativeZoom) : zoom;
	},

	_getSubdomain: function (tilePoint) {
		var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
		return this.options.subdomains[index];
	},

	// stops loading all tiles in the background layer
	_abortLoading: function () {
		var i, tile;
		for (i in this._tiles) {
			if (this._tiles[i].coords.z !== this._tileZoom) {
				tile = this._tiles[i].el;

				tile.onload = L.Util.falseFn;
				tile.onerror = L.Util.falseFn;

				if (!tile.complete) {
					tile.src = L.Util.emptyImageUrl;
					L.DomUtil.remove(tile);
				}
			}
		}
	}
});

L.tileLayer = function (url, options) {
	return new L.TileLayer(url, options);
};
<commit_msg>retina url fix<commit_after>/*
 * L.TileLayer is used for standard xyz-numbered tile layers.
 */

L.TileLayer = L.GridLayer.extend({

	options: {
		maxZoom: 18,

		subdomains: 'abc',
		errorTileUrl: '',
		zoomOffset: 0,

		maxNativeZoom: null, // Number
		tms: false,
		zoomReverse: false,
		detectRetina: false,
		crossOrigin: false
	},

	initialize: function (url, options) {

		this._url = url;

		options = L.setOptions(this, options);

		// detecting retina displays, adjusting tileSize and zoom levels
		if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {

			options.tileSize = Math.floor(options.tileSize / 2);
			options.zoomOffset++;

			options.minZoom = Math.max(0, options.minZoom);
			options.maxZoom--;
		}

		if (typeof options.subdomains === 'string') {
			options.subdomains = options.subdomains.split('');
		}

		// for https://github.com/Leaflet/Leaflet/issues/137
		if (!L.Browser.android) {
			this.on('tileunload', this._onTileRemove);
		}
	},

	setUrl: function (url, noRedraw) {
		this._url = url;

		if (!noRedraw) {
			this.redraw();
		}
		return this;
	},

	createTile: function (coords, done) {
		var tile = document.createElement('img');

		L.DomEvent.on(tile, 'load', L.bind(this._tileOnLoad, this, done, tile));
		L.DomEvent.on(tile, 'error', L.bind(this._tileOnError, this, done, tile));

		if (this.options.crossOrigin) {
			tile.crossOrigin = '';
		}

		/*
		 Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
		 http://www.w3.org/TR/WCAG20-TECHS/H67
		*/
		tile.alt = '';

		tile.src = this.getTileUrl(coords);

		return tile;
	},

	getTileUrl: function (coords) {
		return L.Util.template(this._url, L.extend({
			r: L.Browser.retina ? '@2x' : '',
			s: this._getSubdomain(coords),
			x: coords.x,
			y: this.options.tms ? this._globalTileRange.max.y - coords.y : coords.y,
			z: this._getZoomForUrl()
		}, this.options));
	},

	_tileOnLoad: function (done, tile) {
		// For https://github.com/Leaflet/Leaflet/issues/3332
		if (L.Browser.ielt9) {
			setTimeout(L.bind(done, this, null, tile), 0);
		} else {
			done(null, tile);
		}
	},

	_tileOnError: function (done, tile, e) {
		var errorUrl = this.options.errorTileUrl;
		if (errorUrl) {
			tile.src = errorUrl;
		}
		done(e, tile);
	},

	getTileSize: function () {
		var map = this._map,
		    tileSize = L.GridLayer.prototype.getTileSize.call(this),
		    zoom = this._tileZoom + this.options.zoomOffset,
		    zoomN = this.options.maxNativeZoom;

		// increase tile size when overscaling
		return zoomN !== null && zoom > zoomN ?
				tileSize.divideBy(map.getZoomScale(zoomN, zoom)).round() :
				tileSize;
	},

	_onTileRemove: function (e) {
		e.tile.onload = null;
	},

	_getZoomForUrl: function () {

		var options = this.options,
		    zoom = this._tileZoom;

		if (options.zoomReverse) {
			zoom = options.maxZoom - zoom;
		}

		zoom += options.zoomOffset;

		return options.maxNativeZoom !== null ? Math.min(zoom, options.maxNativeZoom) : zoom;
	},

	_getSubdomain: function (tilePoint) {
		var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
		return this.options.subdomains[index];
	},

	// stops loading all tiles in the background layer
	_abortLoading: function () {
		var i, tile;
		for (i in this._tiles) {
			if (this._tiles[i].coords.z !== this._tileZoom) {
				tile = this._tiles[i].el;

				tile.onload = L.Util.falseFn;
				tile.onerror = L.Util.falseFn;

				if (!tile.complete) {
					tile.src = L.Util.emptyImageUrl;
					L.DomUtil.remove(tile);
				}
			}
		}
	}
});

L.tileLayer = function (url, options) {
	return new L.TileLayer(url, options);
};
<|endoftext|>


<commit_before>$(document).ready(function() {
	var shareButtons = $('.js-share');
	var urls = {
		initial: window.location.href,
		short: ''
	};
	var buttonClass = {
		active: 'share-button--active',
		generate: 'share-button--generate'
	};
	shareButtons.data('copied', false);

	var copyTextToClipboard = function(button, text) {
		var _textArea = document.createElement("textarea");

		_textArea.style.position = 'fixed';
		_textArea.style.top = 0;
		_textArea.style.left = 0;
		_textArea.style.width = '2em';
		_textArea.style.height = '2em';
		_textArea.style.padding = 0;
		_textArea.style.border = 'none';
		_textArea.style.outline = 'none';
		_textArea.style.boxShadow = 'none';
		_textArea.style.background = 'transparent';
		_textArea.value = text;

		document.body.appendChild(_textArea);

		_textArea.select();

		try {
			var _successful = document.execCommand('copy');
			if (_successful) {
				button.addClass(buttonClass.active);
				button.data('copied', true);
			}
		} catch (err) {
			console.error('Oops, unable to copy');
		}

		document.body.removeChild(_textArea);
	}

	function prepareShareButtons(url) {
		var _username = window.ICEKIT_SHARE_USERNAME;
		var _key = window.ICEKIT_SHARE_KEY;
        if (!_username || !_key) {
            return;
        }
		$.ajax({
			url: "http://api.bit.ly/v3/shorten",
			data: {
				'longUrl': url,
				'apiKey': _key,
				'login': _username
			},
			dataType: 'JSON',
			success: function (data) {
				var _requestUrl = urls.short = data.data.url;
				var _truncateUrl = _requestUrl.replace(/http[s]*:\/\//, '');
				shareButtons.find('.js-short-url')
					.text(_truncateUrl)
					.prop('href', urls.short);
				shareButtons.addClass(buttonClass.generate);
			}
		});
	}

	prepareShareButtons(urls.initial);

	shareButtons.on('click', function () {
		var button = $(this);
		if (button.data('copied')) {
			button.removeClass(buttonClass.active);
			button.data('copied', false);
		} else {
			copyTextToClipboard(button, urls.short);
		}
	});
});
<commit_msg>Fix Bitly API URL to the HTTPS version to work on secure sites, re #1151<commit_after>$(document).ready(function() {
	var shareButtons = $('.js-share');
	var urls = {
		initial: window.location.href,
		short: ''
	};
	var buttonClass = {
		active: 'share-button--active',
		generate: 'share-button--generate'
	};
	shareButtons.data('copied', false);

	var copyTextToClipboard = function(button, text) {
		var _textArea = document.createElement("textarea");

		_textArea.style.position = 'fixed';
		_textArea.style.top = 0;
		_textArea.style.left = 0;
		_textArea.style.width = '2em';
		_textArea.style.height = '2em';
		_textArea.style.padding = 0;
		_textArea.style.border = 'none';
		_textArea.style.outline = 'none';
		_textArea.style.boxShadow = 'none';
		_textArea.style.background = 'transparent';
		_textArea.value = text;

		document.body.appendChild(_textArea);

		_textArea.select();

		try {
			var _successful = document.execCommand('copy');
			if (_successful) {
				button.addClass(buttonClass.active);
				button.data('copied', true);
			}
		} catch (err) {
			console.error('Oops, unable to copy');
		}

		document.body.removeChild(_textArea);
	}

	function prepareShareButtons(url) {
		var _username = window.ICEKIT_SHARE_USERNAME;
		var _key = window.ICEKIT_SHARE_KEY;
        if (!_username || !_key) {
            return;
        }
		$.ajax({
			url: "https://api-ssl.bit.ly/v3/shorten",
			data: {
				'longUrl': url,
				'apiKey': _key,
				'login': _username
			},
			dataType: 'JSON',
			success: function (data) {
				var _requestUrl = urls.short = data.data.url;
				var _truncateUrl = _requestUrl.replace(/http[s]*:\/\//, '');
				shareButtons.find('.js-short-url')
					.text(_truncateUrl)
					.prop('href', urls.short);
				shareButtons.addClass(buttonClass.generate);
			}
		});
	}

	prepareShareButtons(urls.initial);

	shareButtons.on('click', function () {
		var button = $(this);
		if (button.data('copied')) {
			button.removeClass(buttonClass.active);
			button.data('copied', false);
		} else {
			copyTextToClipboard(button, urls.short);
		}
	});
});
<|endoftext|>


<commit_before>/*eslint-disable*/
var os = require('os');

var MAX_BUFFER = 400 * 1024;

module.exports = function(grunt) {
  grunt.config('shell', {
    bundle: {
      command: function(version) {
        if (os.platform() !== 'win32') {
          throw new Error('The bundle command is not available on non-windows platforms.');
        }

        var cmd = 'build\\bundle';
        if (version) {
          return [cmd, ' ', version].join('');
        }

        return cmd;
      },
      options: {
        stderr: true,
        stdout: true,
        stdin: true,
        execOptions: {
          cwd: '.',
          maxBuffer: MAX_BUFFER
        }
      }
    },
    release: {
      command: os.platform() === 'win32' ? 'build\\release.cmd' : 'build/release.sh',
      options: {
        execOptions: {
          cwd: '',
          maxBuffer: MAX_BUFFER
        }
      }
    },
    'lang-bundle': {
      command: function(bundleName, configFileName) {
        var cmd = 'build\\langBundle';
        return [cmd, ' ', bundleName, ' ', configFileName].join('');

        return cmd;
      },
      options: {
        stderr: true,
        stdout: true,
        stdin: true,
        execOptions: {
          cwd: '.',
          maxBuffer: MAX_BUFFER
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-shell');
};
<commit_msg>Increasing buffer size on grunt-shell.<commit_after>/*eslint-disable*/
var os = require('os');

var MAX_BUFFER = 800 * 1024;

module.exports = function(grunt) {
  grunt.config('shell', {
    bundle: {
      command: function(version) {
        if (os.platform() !== 'win32') {
          throw new Error('The bundle command is not available on non-windows platforms.');
        }

        var cmd = 'build\\bundle';
        if (version) {
          return [cmd, ' ', version].join('');
        }

        return cmd;
      },
      options: {
        stderr: true,
        stdout: true,
        stdin: true,
        execOptions: {
          cwd: '.',
          maxBuffer: MAX_BUFFER
        }
      }
    },
    release: {
      command: os.platform() === 'win32' ? 'build\\release.cmd' : 'build/release.sh',
      options: {
        execOptions: {
          cwd: '',
          maxBuffer: MAX_BUFFER
        }
      }
    },
    'lang-bundle': {
      command: function(bundleName, configFileName) {
        var cmd = 'build\\langBundle';
        return [cmd, ' ', bundleName, ' ', configFileName].join('');

        return cmd;
      },
      options: {
        stderr: true,
        stdout: true,
        stdin: true,
        execOptions: {
          cwd: '.',
          maxBuffer: MAX_BUFFER
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-shell');
};
<|endoftext|>