<commit_before>import { createElement, PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import intersection from 'lodash/intersection';
import isEqual from 'lodash/isEqual';
import compact from 'lodash/compact';

import reducerRegistry from 'app/registry';

import { setMapSettings as setMapState } from 'components/map/actions';
import { setModalMetaSettings } from 'components/modals/meta/meta-actions';
import { setShareModal } from 'components/modals/share/share-actions';

import { getWidgetDatasets, getPolynameDatasets } from './utils/config';
import * as ownActions from './actions';
import reducers, { initialState } from './reducers';
import Component from './component';
import { getWidgetsProps } from './selectors';

const actions = {
  ...ownActions,
  setMapSettings: setMapState,
  setModalMetaSettings,
  setShareModal
};

const mapSyncKeys = [
  'startYear',
  'endYear',
  'threshold',
  'extentYear',
  'forestType',
  'landCategory'
];

const adminBoundaryLayer = {
  dataset: 'fdc8dc1b-2728-4a79-b23f-b09485052b8d',
  layers: [
    '6f6798e6-39ec-4163-979e-182a74ca65ee',
    'c5d1e010-383a-4713-9aaa-44f728c0571c'
  ],
  opacity: 1,
  visibility: true
};

const makeMapStateToProps = () => {
  const getWidgetPropsObject = getWidgetsProps();
  const mapStateToProps = (state, props) => ({
    ...getWidgetPropsObject(state, props)
  });
  return mapStateToProps;
};

class WidgetsContainer extends PureComponent {
  static propTypes = {
    getWidgetsData: PropTypes.func,
    location: PropTypes.object,
    activeWidget: PropTypes.object,
    setMapSettings: PropTypes.func
  };

  componentDidMount() {
    const { getWidgetsData, location, activeWidget } = this.props;
    if (location.type === 'global') {
      getWidgetsData();
    }

    if (activeWidget && activeWidget.datasets) {
      this.syncWidgetWithMap();
    }
  }

  componentDidUpdate(prevProps) {
    const { getWidgetsData, activeWidget } = this.props;

    if (location.type === 'global' && prevProps.location.type !== 'global') {
      getWidgetsData();
    }

    // if widget is active and layers or params change push to map
    if (activeWidget) {
      const { settings, datasets } = activeWidget || {};
      const mapSettingsChanged =
        settings &&
        intersection(mapSyncKeys, Object.keys(settings)).length &&
        !isEqual(settings, prevProps.settings);
      const activeWidgetChanged = !isEqual(
        activeWidget,
        prevProps.activeWidget
      );
      if (datasets && (mapSettingsChanged || activeWidgetChanged)) {
        this.syncWidgetWithMap();
      } else if (!datasets && activeWidgetChanged) {
        this.clearMap();
      }
    }

    // if widget is no longer activeWidget remove layers from map
    if (!activeWidget && !isEqual(activeWidget, prevProps.activeWidget)) {
      this.clearMap();
    }
  }

  syncWidgetWithMap = () => {
    const { activeWidget, setMapSettings } = this.props;
    const { datasets, settings, optionsSelected } = activeWidget || {};
    const widgetDatasets =
      datasets &&
      datasets.length &&
      getWidgetDatasets({ datasets, ...settings });

    const polynameDatasets = getPolynameDatasets({ optionsSelected, settings });
    const allDatasets = [...compact(polynameDatasets), ...widgetDatasets];

    setMapSettings({
      datasets: allDatasets
    });
  };

  clearMap = () => {
    const { setMapSettings } = this.props;
    setMapSettings({
      datasets: [adminBoundaryLayer]
    });
  };

  render() {
    return createElement(Component, {
      ...this.props
    });
  }
}

reducerRegistry.registerModule('widgets', {
  actions,
  reducers,
  initialState
});

export default connect(makeMapStateToProps, actions)(WidgetsContainer);
<commit_msg>add loading prop for widgets state<commit_after>import { createElement, PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import intersection from 'lodash/intersection';
import isEqual from 'lodash/isEqual';
import compact from 'lodash/compact';

import reducerRegistry from 'app/registry';

import { setMapSettings as setMapState } from 'components/map/actions';
import { setModalMetaSettings } from 'components/modals/meta/meta-actions';
import { setShareModal } from 'components/modals/share/share-actions';

import { getWidgetDatasets, getPolynameDatasets } from './utils/config';
import * as ownActions from './actions';
import reducers, { initialState } from './reducers';
import Component from './component';
import { getWidgetsProps } from './selectors';

const actions = {
  ...ownActions,
  setMapSettings: setMapState,
  setModalMetaSettings,
  setShareModal
};

const mapSyncKeys = [
  'startYear',
  'endYear',
  'threshold',
  'extentYear',
  'forestType',
  'landCategory'
];

const adminBoundaryLayer = {
  dataset: 'fdc8dc1b-2728-4a79-b23f-b09485052b8d',
  layers: [
    '6f6798e6-39ec-4163-979e-182a74ca65ee',
    'c5d1e010-383a-4713-9aaa-44f728c0571c'
  ],
  opacity: 1,
  visibility: true
};

const makeMapStateToProps = () => {
  const getWidgetPropsObject = getWidgetsProps();
  const mapStateToProps = (state, props) => ({
    ...getWidgetPropsObject(state, props)
  });
  return mapStateToProps;
};

class WidgetsContainer extends PureComponent {
  static propTypes = {
    getWidgetsData: PropTypes.func,
    location: PropTypes.object,
    activeWidget: PropTypes.object,
    setMapSettings: PropTypes.func
  };

  state = {
    loading: true
  };

  componentDidMount() {
    const { getWidgetsData, location, activeWidget } = this.props;
    if (location.type === 'global') {
      getWidgetsData();
    }

    if (activeWidget && activeWidget.datasets) {
      this.syncWidgetWithMap();
    }

    setTimeout(() => {
      this.setState({ loading: false });
    }, 500);
  }

  componentDidUpdate(prevProps) {
    const { getWidgetsData, activeWidget } = this.props;

    if (location.type === 'global' && prevProps.location.type !== 'global') {
      getWidgetsData();
    }

    // if widget is active and layers or params change push to map
    if (activeWidget) {
      const { settings, datasets } = activeWidget || {};
      const mapSettingsChanged =
        settings &&
        intersection(mapSyncKeys, Object.keys(settings)).length &&
        !isEqual(settings, prevProps.settings);
      const activeWidgetChanged = !isEqual(
        activeWidget,
        prevProps.activeWidget
      );
      if (datasets && (mapSettingsChanged || activeWidgetChanged)) {
        this.syncWidgetWithMap();
      } else if (!datasets && activeWidgetChanged) {
        this.clearMap();
      }
    }

    // if widget is no longer activeWidget remove layers from map
    if (!activeWidget && !isEqual(activeWidget, prevProps.activeWidget)) {
      this.clearMap();
    }
  }

  syncWidgetWithMap = () => {
    const { activeWidget, setMapSettings } = this.props;
    const { datasets, settings, optionsSelected } = activeWidget || {};
    const widgetDatasets =
      datasets &&
      datasets.length &&
      getWidgetDatasets({ datasets, ...settings });

    const polynameDatasets = getPolynameDatasets({ optionsSelected, settings });
    const allDatasets = [...compact(polynameDatasets), ...widgetDatasets];

    setMapSettings({
      datasets: allDatasets
    });
  };

  clearMap = () => {
    const { setMapSettings } = this.props;
    setMapSettings({
      datasets: [adminBoundaryLayer]
    });
  };

  render() {
    return createElement(Component, {
      ...this.props,
      ...this.state
    });
  }
}

reducerRegistry.registerModule('widgets', {
  actions,
  reducers,
  initialState
});

export default connect(makeMapStateToProps, actions)(WidgetsContainer);
<|endoftext|>


<commit_before>import {
  name as LIB_NAME,
  version as LIB_VERSION
} from '../../package.json';

const {
  hasOwnProperty,
  toString
} = Object.prototype;

function _isNullProtoObject(val) {
  return typeof val === 'object' &&
    val !== null &&
    val.__proto__ === undefined;
}

function _argsStr(count, name = 'arg') {
  let names = [];

  for (let i = 0; i < count; i++) {
    names.push(`${name}${i + 1}`);
  }

  return names.join(', ');
}

function typeStr(val, k = undefined) {
  let t = (_isNullProtoObject(val)) ?
    'Object(proto:Null)' :
    toString.call(val).match(/^\[object ([^\]]*)\]$/)[1];

  if (val instanceof Object) {
    if (val.constructor) {
      if (val.constructor.name) {
        if (val.constructor.name !== t) {
          let name = val.constructor.name;

          if (t === 'Object') {
            t = name;
          } else if (name !== 'Object') {
            if (t.indexOf(name) >= 0) {
              //t = t;
            } else if (name.indexOf(t) >= 0) {
              t = name;
            } else {
              if (!t.endsWith('Prototype')) {
                t = `${t}(ctor:${name})`;
              }
            }
          }
        }
      } else {
        if (!t.endsWith('Prototype')) {
          t = `${t}(ctor:Anonymous)`;
        }
      }
    }
  }

  if (val instanceof Error) {
    // name might be a getter that throws
    try {
      let name = val.name;

      if (name && name !== t) {
        t = name;
      }
    } catch (err) {}
  }

  if (val instanceof Function) {
    if (val.name && val.name !== t && (
      val.name.match(/^[A-Z]/) ||
      (k &&
        ['__apivis__chain_link',
          'constructor',
          'prototype',
          '__proto__'
        ].includes(k)
      )
    )) {
      t = val.name;
    }

    t = `${t}(${_argsStr(val.length)})`;
  }

  if (val && (
    (val.hasOwnProperty && val.hasOwnProperty('constructor'))
  )) {
    if (!t.endsWith('Prototype') && (
      (t !== 'Object' || val === Object.prototype)
    )) {
      t = `${t}.prototype`;
    }
  }

  return t;
}

function valueStr(val) {
  switch (typeof val) {
  case 'boolean':
  case 'number':
    return `${val}`;
  case 'string':
    return JSON.stringify(val);
  case 'object':
    if (Array.isArray(val) && val !== Array.prototype) {
      return `${val.length}`;
    } else if (val instanceof Date) {
      return JSON.stringify(val);
    } else if (val instanceof Error) {
      // message might be a getter that throws
      try {
        let msg = val.message;

        if (msg) {
          return JSON.stringify(msg);
        }
      } catch (err) {
        return '';
      }
    }
  default:
    return '';
  }
}

function descStr(val, k) {
  if (val === undefined || val === null) {
    return 'n/a';
  }

  let desc = Object.getOwnPropertyDescriptor(val, k);
  let d1 = '';
  let d2 = '';

  if (desc === undefined) {
    return 'n/a';
  }

  if (desc.hasOwnProperty('value')) { d1 += 'v'; }
  if (desc.writable) { d1 += 'w'; }
  if (desc.get) { d1 += 'g'; }
  if (desc.set) { d1 += 's'; }
  if (desc.enumerable) { d2 += 'e'; }
  if (desc.configurable) { d2 += 'c'; }

  return (d2) ? `${d1} ${d2}` : d1;
}

const _getterTagDummy = {
  __proto__: {
    get [Symbol.toStringTag]() { return 'Getter'; }
  }
};

const _noop = () => {};
const _swallowPromiseRejection = v => (
  (typeof v === 'object' && v !== null &&
    v !== Promise.prototype && typeof v.catch === 'function' &&
      v.catch(_noop)),
  v
);

function memberStr(val, k, leaf = val) {
  let sk = String(k);
  let sd = descStr(val, k);
  let isGetter = sd.includes('g');
  // Do not attempt to resolve these
  let skip = [
    'arguments',
    'callee',
    'caller'
  ];
  // Only resolve these in the context of leaf
  let leafOnly = [
    '__proto__'
  ];
  let st;
  let v;
  let sv = '';

  // First resolve k in the context of leaf (like it would be normally)
  try {
    if (!skip.includes(k)) {
      v = _swallowPromiseRejection(leaf[k]);
    }
  } catch (err) {
    v = (isGetter) ? _getterTagDummy : err;
  }

  // Then try resolving k in the context of val (reached through
  // following __proto__) to eventually get a shadowed value (some
  // props only make sense when resolved in the context of leaf
  // and an exception will be thrown upon trying to access them through val)
  try {
    if ( !(val === leaf || leafOnly.includes(k) || skip.includes(k)) ) {
      let shadowed = _swallowPromiseRejection(val[k]);

      if (shadowed !== undefined && shadowed !== null) {
        v = shadowed;
      }
    }
  } catch (err) {
    // Leave v as set by trying to resolve k in the context of leaf
  }

  st = typeStr(v, k);
  sv = valueStr(v);

  return `${sk}{${sd}}: ${st}${(sv) ? `:${sv}` : ''}`;
}

function memberInfo(val, k, seen) {
  let sk = String(k);
  let sd = descStr(val, k);
  let isGetter = sd.includes('g');
  // Do not attempt to resolve these
  let skip = [
    'arguments',
    'callee',
    'caller'
  ];
  let iSeen = -1;
  let sSeen;
  let st;
  let v;
  let sv = '';

  try {
    if (!skip.includes(k)) {
      v = _swallowPromiseRejection(val[k]);
    }
  } catch (err) {
    v = (isGetter) ? _getterTagDummy : err;
  }

  iSeen = seen.findIndex(kv => v === kv[1]);
  sSeen = (iSeen >= 0) ? `->${seen[iSeen][0]}` : '';
  st = typeStr(v, k);
  sv = valueStr(v);

  return {
    v,
    s: `${sk}{${sd}}${sSeen}: ${st}${(sv) ? `:${sv}` : ''}`,
    seen: iSeen >= 0
  };
}

const _compare = (a, b) => {
  let sa = String(a);
  let sb = String(b);
  let na;
  let nb;

  if (Number.isNaN(na = Number(sa)) || Number.isNaN(nb = Number(sb))) {
    return (sa < sb) ? -1 : (sa > sb) ? 1 : 0;
  }

  return na - nb;
};

const _keys = (val, kind) =>
  (val === undefined || val === null) ?
    [] :
    Object[`getOwnProperty${kind}`](val).sort(_compare);

const _symbols = val => _keys(val, 'Symbols');
const _names = val => _keys(val, 'Names');

const members = val => _symbols(val).concat(_names(val));

function membersStr(val, indent = '  ', level = 0, leaf = val) {
  return members(val).
    map(k => `${indent.repeat(level)}${memberStr(val, k, leaf)}`).
    join('\n');
}

const _trackedReference = v =>
  (typeof v === 'object' && v !== null &&
    v !== _getterTagDummy) ||
  typeof v === 'function';
const _descendableObject = v =>
  typeof v === 'object' && v !== null &&
    v !== _getterTagDummy;
const _maybeConstructor = v =>
  // Assumes typeof v === 'function'
  hasOwnProperty.call(v, 'prototype') &&
    v.name && v.name.match(/^[A-Z]/);
const _descendableFunctionWhitelist = v =>
  // Assumes typeof v === 'function'
  v === Proxy ||
  (typeof _ === 'function' && v === _) ||
  (typeof $ === 'function' && v === $);
const _descendableFunction = v =>
  typeof v === 'function' &&
    (_maybeConstructor(v) || _descendableFunctionWhitelist(v));

const _shouldDescend = (k, v, level) =>
  (_descendableObject(v) || _descendableFunction(v));

function _inspectStr(val, k,
  indent = '  ', level = 1,
  seen = [['ROOT', val]], path = []
) {
  let mi = memberInfo(val, k, seen);
  let v = mi.v;
  let result = [`${indent.repeat(level)}${mi.s}`];

  if (!mi.seen && _trackedReference(v)) {
    path.push(String(k));
    seen.push([path.join('.'), v]);

    if (_shouldDescend(k, v, level)) {
      members(v).forEach(_k => result.push(
        _inspectStr(v, _k, indent, level + 1, seen, path)
      ));
    }

    path.pop();
  }

  return result.join('\n');
}

function inspectStr(val, indent = '  ') {
  let st = typeStr(val);
  let sv = valueStr(val);
  let result = [`${st}${(sv) ? `:${sv}` : ''}`];
  let seen = [['ROOT', val]];

  members(val).forEach(k => result.push(
    _inspectStr(val, k, indent, 1, seen)
  ));

  return result.join('\n');
}

function chain(val) {
  let links = [val];

  for (let link = Object.getPrototypeOf(val);
    link;
    link = Object.getPrototypeOf(link)
  ) {
    links.push(link);
  }

  return links;
}

function chainStr(val, indent = '  ') {
  return chain(val).
    reverse().
    map((v, i) => `${indent.repeat(i)}[${typeStr(v, '__apivis__chain_link')}]`).
    join('\n');
}

function apiStr(val, indent = '  ') {
  return chain(val).
    reverse().
    map((v, i) => `${indent.repeat(i)}[${typeStr(v, '__apivis__chain_link')}]\n${membersStr(v, indent, i + 1, val)}`).
    join('\n');
}

// peek42 plugin
function peek42(fnOutput, fnComment) {
  return {
    type(val, comment = undefined, opts = undefined) {
      fnOutput(
        typeStr(val),
        fnComment(comment, val, 'type'),
        opts
      );
    },
    desc(val, k, comment = undefined, opts = undefined) {
      fnOutput(
        descStr(val, k),
        fnComment(comment, `${String(k)} in ${typeStr(val)}`, 'desc'),
        opts
      );
    },
    member(val, k, comment = undefined, opts = undefined) {
      fnOutput(
        memberStr(val, k),
        fnComment(comment, `${String(k)} in ${typeStr(val)}`, 'member'),
        opts
      );
    },
    members(val, comment = undefined, opts = undefined) {
      fnOutput(
        membersStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined,
          (opts && typeof opts.indentLevel === 'number') ?
            opts.indentLevel :
            undefined
        ),
        fnComment(comment, typeStr(val), 'members'),
        opts
      );
    },
    inspect(val, comment = undefined, opts = undefined) {
      fnOutput(
        inspectStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined
        ),
        fnComment(comment, typeStr(val), 'inspect'),
        opts
      );
    },
    chain(val, comment = undefined, opts = undefined) {
      fnOutput(
        chainStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined
        ),
        fnComment(comment, typeStr(val), 'chain'),
        opts
      );
    },
    api(val, comment = undefined, opts = undefined) {
      fnOutput(
        apiStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined
        ),
        fnComment(comment, typeStr(val), 'api'),
        opts
      );
    }
  };
}

const apivis = {
  get [Symbol.toStringTag]() {
    return LIB_NAME;
  },
  version: LIB_VERSION,
  typeStr,
  descStr,
  memberStr,
  members,
  membersStr,
  inspectStr,
  chain,
  chainStr,
  apiStr,
  peek42
};

export {
  typeStr,
  descStr,
  memberStr,
  members,
  membersStr,
  inspectStr,
  chain,
  chainStr,
  apiStr
};
export default apivis;
<commit_msg>Show the entries (max 200) for values sporting Symbol.iterator<commit_after>import {
  name as LIB_NAME,
  version as LIB_VERSION
} from '../../package.json';

const {
  hasOwnProperty,
  toString
} = Object.prototype;

function _isNullProtoObject(val) {
  return typeof val === 'object' &&
    val !== null &&
    val.__proto__ === undefined;
}

function _argsStr(count, name = 'arg') {
  let names = [];

  for (let i = 0; i < count; i++) {
    names.push(`${name}${i + 1}`);
  }

  return names.join(', ');
}

function typeStr(val, k = undefined) {
  let t = (_isNullProtoObject(val)) ?
    'Object(proto:Null)' :
    toString.call(val).match(/^\[object ([^\]]*)\]$/)[1];

  if (val instanceof Object) {
    if (val.constructor) {
      if (val.constructor.name) {
        if (val.constructor.name !== t) {
          let name = val.constructor.name;

          if (t === 'Object') {
            t = name;
          } else if (name !== 'Object') {
            if (t.indexOf(name) >= 0) {
              //t = t;
            } else if (name.indexOf(t) >= 0) {
              t = name;
            } else {
              if (!t.endsWith('Prototype')) {
                t = `${t}(ctor:${name})`;
              }
            }
          }
        }
      } else {
        if (!t.endsWith('Prototype')) {
          t = `${t}(ctor:Anonymous)`;
        }
      }
    }
  }

  if (val instanceof Error) {
    // name might be a getter that throws
    try {
      let name = val.name;

      if (name && name !== t) {
        t = name;
      }
    } catch (err) {}
  }

  if (val instanceof Function) {
    if (val.name && val.name !== t && (
      val.name.match(/^[A-Z]/) ||
      (k &&
        ['__apivis__chain_link',
          'constructor',
          'prototype',
          '__proto__'
        ].includes(k)
      )
    )) {
      t = val.name;
    }

    t = `${t}(${_argsStr(val.length)})`;
  }

  if (val && (
    (val.hasOwnProperty && val.hasOwnProperty('constructor'))
  )) {
    if (!t.endsWith('Prototype') && (
      (t !== 'Object' || val === Object.prototype)
    )) {
      t = `${t}.prototype`;
    }
  }

  return t;
}

function valueStr(val) {
  switch (typeof val) {
  case 'boolean':
  case 'number':
    return `${val}`;
  case 'string':
    return JSON.stringify(val);
  case 'object':
    if (Array.isArray(val) && val !== Array.prototype) {
      return `${val.length}`;
    } else if (val instanceof Date) {
      return JSON.stringify(val);
    } else if (val instanceof Error) {
      // message might be a getter that throws
      try {
        let msg = val.message;

        if (msg) {
          return JSON.stringify(msg);
        }
      } catch (err) {
        return '';
      }
    }
  default:
    return '';
  }
}

function descStr(val, k) {
  if (val === undefined || val === null) {
    return 'n/a';
  }

  let desc = Object.getOwnPropertyDescriptor(val, k);
  let d1 = '';
  let d2 = '';

  if (desc === undefined) {
    return 'n/a';
  }

  if (desc.hasOwnProperty('value')) { d1 += 'v'; }
  if (desc.writable) { d1 += 'w'; }
  if (desc.get) { d1 += 'g'; }
  if (desc.set) { d1 += 's'; }
  if (desc.enumerable) { d2 += 'e'; }
  if (desc.configurable) { d2 += 'c'; }

  return (d2) ? `${d1} ${d2}` : d1;
}

const _getterTagDummy = {
  __proto__: {
    get [Symbol.toStringTag]() { return 'Getter'; }
  }
};

const _noop = () => {};
const _swallowPromiseRejection = v => (
  (typeof v === 'object' && v !== null &&
    v !== Promise.prototype && typeof v.catch === 'function' &&
      v.catch(_noop)),
  v
);

function memberStr(val, k, leaf = val) {
  let sk = String(k);
  let sd = descStr(val, k);
  let isGetter = sd.includes('g');
  // Do not attempt to resolve these
  let skip = [
    'arguments',
    'callee',
    'caller'
  ];
  // Only resolve these in the context of leaf
  let leafOnly = [
    '__proto__'
  ];
  let st;
  let v;
  let sv = '';

  // First resolve k in the context of leaf (like it would be normally)
  try {
    if (!skip.includes(k)) {
      if (k === SymbolVpropEntries) {
        v = _vpropEntries(leaf);
      } else {
        v = _swallowPromiseRejection(leaf[k]);
      }
    }
  } catch (err) {
    v = (isGetter) ? _getterTagDummy : err;
  }

  // Then try resolving k in the context of val (reached through
  // following __proto__) to eventually get a shadowed value (some
  // props only make sense when resolved in the context of leaf
  // and an exception will be thrown upon trying to access them through val)
  try {
    if ( !(val === leaf || leafOnly.includes(k) || skip.includes(k)) ) {
      let shadowed = _swallowPromiseRejection(val[k]);

      if (shadowed !== undefined && shadowed !== null) {
        v = shadowed;
      }
    }
  } catch (err) {
    // Leave v as set by trying to resolve k in the context of leaf
  }

  st = typeStr(v, k);
  sv = valueStr(v);

  return `${sk}{${sd}}: ${st}${(sv) ? `:${sv}` : ''}`;
}

function memberInfo(val, k, seen) {
  let sk = String(k);
  let sd = descStr(val, k);
  let isGetter = sd.includes('g');
  // Do not attempt to resolve these
  let skip = [
    'arguments',
    'callee',
    'caller'
  ];
  let iSeen = -1;
  let sSeen;
  let st;
  let v;
  let sv = '';

  try {
    if (!skip.includes(k)) {
      if (k === SymbolVpropEntries) {
        v = _vpropEntries(val);
      } else {
        v = _swallowPromiseRejection(val[k]);
      }
    }
  } catch (err) {
    v = (isGetter) ? _getterTagDummy : err;
  }

  iSeen = seen.findIndex(kv => v === kv[1]);
  sSeen = (iSeen >= 0) ? `->${seen[iSeen][0]}` : '';
  st = typeStr(v, k);
  sv = valueStr(v);

  return {
    v,
    s: `${sk}{${sd}}${sSeen}: ${st}${(sv) ? `:${sv}` : ''}`,
    seen: iSeen >= 0
  };
}

const _compare = (a, b) => {
  let sa = String(a);
  let sb = String(b);
  let na;
  let nb;

  if (Number.isNaN(na = Number(sa)) || Number.isNaN(nb = Number(sb))) {
    return (sa < sb) ? -1 : (sa > sb) ? 1 : 0;
  }

  return na - nb;
};

const _keys = (val, kind) =>
  (val === undefined || val === null) ?
    [] :
    Object[`getOwnProperty${kind}`](val).sort(_compare);

const _symbols = val => _keys(val, 'Symbols');
const _names = val => _keys(val, 'Names');

const MaxVpropEntries = 200;
const DescVpropEntries = `vprop_entries(max:${MaxVpropEntries})`;
const SymbolVpropEntries = Symbol(DescVpropEntries);

const _isVpropEntriesType = val => val[Symbol.iterator] && (
  !(typeof val === 'string' ||
    Array.isArray(val) ||
    (typeof NodeList !== 'undefined' && val instanceof NodeList) ||
    (typeof HTMLCollection !== 'undefined' && val instanceof HTMLCollection) ||
    (typeof NamedNodeMap !== 'undefined' && val instanceof NamedNodeMap)
  ) && !hasOwnProperty.call(val, 'constructor')
);

const _take = (iterator, max = Infinity) => {
  let result = [];

  for (let iter = iterator.next(), i = 0;
    !iter.done && i < max;
    iter = iterator.next(), i++
  ) {
    let entry = iter.value;

    result.push(
      (Array.isArray(entry) && entry.length === 2) ?
        {key: entry[0], value: entry[1]} :
        entry
    );
  }

  return result;
};

const _vpropEntries = val => _take(
  val[Symbol.iterator](),
  MaxVpropEntries
);

const members = val => (
  ( !(val === undefined || val === null) && _isVpropEntriesType(val) ) ?
    [SymbolVpropEntries] :
    []
).
  concat(_symbols(val), _names(val));

function membersStr(val, indent = '  ', level = 0, leaf = val) {
  return members(val).
    map(k => `${indent.repeat(level)}${memberStr(val, k, leaf)}`).
    join('\n');
}

const _trackedReference = v =>
  (typeof v === 'object' && v !== null &&
    v !== _getterTagDummy) ||
  typeof v === 'function';
const _descendableObject = v =>
  typeof v === 'object' && v !== null &&
    v !== _getterTagDummy;
const _maybeConstructor = v =>
  // Assumes typeof v === 'function'
  hasOwnProperty.call(v, 'prototype') &&
    v.name && v.name.match(/^[A-Z]/);
const _descendableFunctionWhitelist = v =>
  // Assumes typeof v === 'function'
  v === Proxy ||
  (typeof _ === 'function' && v === _) ||
  (typeof $ === 'function' && v === $);
const _descendableFunction = v =>
  typeof v === 'function' &&
    (_maybeConstructor(v) || _descendableFunctionWhitelist(v));

const _shouldDescend = (k, v, level) =>
  (_descendableObject(v) || _descendableFunction(v));

function _inspectStr(val, k,
  indent = '  ', level = 1,
  seen = [['ROOT', val]], path = []
) {
  let mi = memberInfo(val, k, seen);
  let v = mi.v;
  let result = [`${indent.repeat(level)}${mi.s}`];

  if (!mi.seen && _trackedReference(v)) {
    path.push(String(k));
    seen.push([path.join('.'), v]);

    if (_shouldDescend(k, v, level)) {
      members(v).forEach(_k => result.push(
        _inspectStr(v, _k, indent, level + 1, seen, path)
      ));
    }

    path.pop();
  }

  return result.join('\n');
}

function inspectStr(val, indent = '  ') {
  let st = typeStr(val);
  let sv = valueStr(val);
  let result = [`${st}${(sv) ? `:${sv}` : ''}`];
  let seen = [['ROOT', val]];

  members(val).forEach(k => result.push(
    _inspectStr(val, k, indent, 1, seen)
  ));

  return result.join('\n');
}

function chain(val) {
  let links = [val];

  for (let link = Object.getPrototypeOf(val);
    link;
    link = Object.getPrototypeOf(link)
  ) {
    links.push(link);
  }

  return links;
}

function chainStr(val, indent = '  ') {
  return chain(val).
    reverse().
    map((v, i) => `${indent.repeat(i)}[${typeStr(v, '__apivis__chain_link')}]`).
    join('\n');
}

function apiStr(val, indent = '  ') {
  return chain(val).
    reverse().
    map((v, i) => `${indent.repeat(i)}[${typeStr(v, '__apivis__chain_link')}]\n${membersStr(v, indent, i + 1, val)}`).
    join('\n');
}

// peek42 plugin
function peek42(fnOutput, fnComment) {
  return {
    type(val, comment = undefined, opts = undefined) {
      fnOutput(
        typeStr(val),
        fnComment(comment, val, 'type'),
        opts
      );
    },
    desc(val, k, comment = undefined, opts = undefined) {
      fnOutput(
        descStr(val, k),
        fnComment(comment, `${String(k)} in ${typeStr(val)}`, 'desc'),
        opts
      );
    },
    member(val, k, comment = undefined, opts = undefined) {
      fnOutput(
        memberStr(val, k),
        fnComment(comment, `${String(k)} in ${typeStr(val)}`, 'member'),
        opts
      );
    },
    members(val, comment = undefined, opts = undefined) {
      fnOutput(
        membersStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined,
          (opts && typeof opts.indentLevel === 'number') ?
            opts.indentLevel :
            undefined
        ),
        fnComment(comment, typeStr(val), 'members'),
        opts
      );
    },
    inspect(val, comment = undefined, opts = undefined) {
      fnOutput(
        inspectStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined
        ),
        fnComment(comment, typeStr(val), 'inspect'),
        opts
      );
    },
    chain(val, comment = undefined, opts = undefined) {
      fnOutput(
        chainStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined
        ),
        fnComment(comment, typeStr(val), 'chain'),
        opts
      );
    },
    api(val, comment = undefined, opts = undefined) {
      fnOutput(
        apiStr(val,
          (opts && typeof opts.indent === 'string') ?
            opts.indent :
            undefined
        ),
        fnComment(comment, typeStr(val), 'api'),
        opts
      );
    }
  };
}

const apivis = {
  get [Symbol.toStringTag]() {
    return LIB_NAME;
  },
  version: LIB_VERSION,
  typeStr,
  descStr,
  memberStr,
  members,
  membersStr,
  inspectStr,
  chain,
  chainStr,
  apiStr,
  peek42
};

export {
  typeStr,
  descStr,
  memberStr,
  members,
  membersStr,
  inspectStr,
  chain,
  chainStr,
  apiStr
};
export default apivis;
<|endoftext|>


<commit_before>const router = require('router');
const route = require('../route');
const validations = require('../validations');
const protect = require('../middleware/protect');
const checkFields = require('../middleware/checkFields');
const controller = require('../controllers/authenticate');

function authenticateRoutes(api, options) {
  const { passport } = api.uw;

  const auth = router()
    // GET /auth/ - Show current user information.
    .get(
      '/',
      route(controller.getCurrentUser),
    )
    // GET /auth/strategies - Show available authentication strategies.
    .get(
      '/strategies',
      route(controller.getAuthStrategies),
    )
    // POST /auth/register - Create a new user account.
    .post(
      '/register',
      checkFields(validations.register),
      route(controller.register.bind(null, options)),
    )
    // POST /auth/login - Log in as an existing user.
    .post(
      '/login',
      checkFields(validations.login),
      passport.authenticate('local', { failWithError: true }),
      route(controller.login.bind(null, options)),
    )
    // GET /auth/socket - Obtain an authentication token for the WebSocket server.
    .get(
      '/socket',
      protect(),
      route(controller.getSocketToken),
    )
    // DELETE /auth/ - Log out (delete the session).
    .delete(
      '/',
      protect(),
      route(controller.logout.bind(null, options)),
    )
    // POST /auth/password/reset - Request a password reset.
    .post(
      '/password/reset',
      checkFields(validations.requestPasswordReset),
      route(controller.reset.bind(null, options)),
    )
    // POST /auth/password/reset/:reset - Change the password using a reset token.
    .post(
      '/password/reset/:reset',
      checkFields(validations.passwordReset),
      route(controller.changePassword),
    )
    // DELETE /auth/session/:id - Unused? Forcibly quit a user's session.
    .delete(
      '/session/:id',
      route(controller.removeSession),
    );

  if (passport.supports('google')) {
    auth
      // GET /auth/service/google - Initiate a social login using Google.
      .get(
        '/service/google',
        passport.authenticate('google'),
        route(controller.login.bind(null, options)),
      )
      // GET /auth/service/google/callback - Finish a social login using Google.
      .get(
        '/service/google/callback',
        passport.authenticate('google'),
        route(controller.socialLoginCallback.bind(null, options)),
      );
  }

  return auth;
}

module.exports = authenticateRoutes;
<commit_msg>Unconditionally add social authentication routes. (#385)<commit_after>const router = require('router');
const route = require('../route');
const validations = require('../validations');
const protect = require('../middleware/protect');
const checkFields = require('../middleware/checkFields');
const controller = require('../controllers/authenticate');

function authenticateRoutes(api, options) {
  const { passport } = api.uw;

  const auth = router()
    // GET /auth/ - Show current user information.
    .get(
      '/',
      route(controller.getCurrentUser),
    )
    // GET /auth/strategies - Show available authentication strategies.
    .get(
      '/strategies',
      route(controller.getAuthStrategies),
    )
    // POST /auth/register - Create a new user account.
    .post(
      '/register',
      checkFields(validations.register),
      route(controller.register.bind(null, options)),
    )
    // POST /auth/login - Log in as an existing user.
    .post(
      '/login',
      checkFields(validations.login),
      passport.authenticate('local', { failWithError: true }),
      route(controller.login.bind(null, options)),
    )
    // GET /auth/socket - Obtain an authentication token for the WebSocket server.
    .get(
      '/socket',
      protect(),
      route(controller.getSocketToken),
    )
    // DELETE /auth/ - Log out (delete the session).
    .delete(
      '/',
      protect(),
      route(controller.logout.bind(null, options)),
    )
    // POST /auth/password/reset - Request a password reset.
    .post(
      '/password/reset',
      checkFields(validations.requestPasswordReset),
      route(controller.reset.bind(null, options)),
    )
    // POST /auth/password/reset/:reset - Change the password using a reset token.
    .post(
      '/password/reset/:reset',
      checkFields(validations.passwordReset),
      route(controller.changePassword),
    )
    // DELETE /auth/session/:id - Unused? Forcibly quit a user's session.
    .delete(
      '/session/:id',
      route(controller.removeSession),
    )
    // GET /auth/service/google - Initiate a social login using Google.
    .get(
      '/service/google',
      passport.authenticate('google'),
      route(controller.login.bind(null, options)),
    )
    // GET /auth/service/google/callback - Finish a social login using Google.
    .get(
      '/service/google/callback',
      passport.authenticate('google'),
      route(controller.socialLoginCallback.bind(null, options)),
    );

  return auth;
}

module.exports = authenticateRoutes;
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import AutoRefresh from 'shared/components/AutoRefresh';
import LineGraph from 'shared/components/LineGraph';
import SingleStat from 'shared/components/SingleStat';
import ReactGridLayout, {WidthProvider} from 'react-grid-layout';
const GridLayout = WidthProvider(ReactGridLayout);
import _ from 'lodash';

const RefreshingLineGraph = AutoRefresh(LineGraph);
const RefreshingSingleStat = AutoRefresh(SingleStat);

export const LayoutRenderer = React.createClass({
  propTypes: {
    timeRange: PropTypes.shape({
      defaultGroupBy: PropTypes.string.isRequired,
      queryValue: PropTypes.string.isRequired,
    }).isRequired,
    cells: PropTypes.arrayOf(
      PropTypes.shape({
        queries: PropTypes.arrayOf(
          PropTypes.shape({
            label: PropTypes.string,
            range: PropTypes.shape({
              upper: PropTypes.number,
              lower: PropTypes.number,
            }),
            rp: PropTypes.string,
            text: PropTypes.string.isRequired,
            database: PropTypes.string.isRequired,
            groupbys: PropTypes.arrayOf(PropTypes.string),
            wheres: PropTypes.arrayOf(PropTypes.string),
          }).isRequired
        ).isRequired,
        x: PropTypes.number.isRequired,
        y: PropTypes.number.isRequired,
        w: PropTypes.number.isRequired,
        h: PropTypes.number.isRequired,
        i: PropTypes.string.isRequired,
        name: PropTypes.string.isRequired,
      }).isRequired
    ),
    autoRefreshMs: PropTypes.number.isRequired,
    host: PropTypes.string,
    source: PropTypes.string,
  },

  getInitialState() {
    return ({
      layout: _.without(this.props.cells, ['queries']),
    });
  },

  buildQuery(q) {
    const {timeRange, host} = this.props;
    const {wheres, groupbys} = q;

    let text = q.text;

    text += ` where time > ${timeRange.queryValue}`;

    if (host) {
      text += ` and \"host\" = '${host}'`;
    }

    if (wheres && wheres.length > 0) {
      text += ` and ${wheres.join(' and ')}`;
    }

    if (groupbys) {
      if (groupbys.find((g) => g.includes("time"))) {
        text += ` group by ${groupbys.join(',')}`;
      } else if (groupbys.length > 0) {
        text += ` group by time(${timeRange.defaultGroupBy}),${groupbys.join(',')}`;
      } else {
        text += ` group by time(${timeRange.defaultGroupBy})`;
      }
    } else {
      text += ` group by time(${timeRange.defaultGroupBy})`;
    }

    return text;
  },

  generateVisualizations() {
    const {autoRefreshMs, source, cells} = this.props;

    return cells.map((cell) => {
      const qs = cell.queries.map((q) => {
        return Object.assign({}, q, {
          host: source,
          text: this.buildQuery(q),
        });
      });

      if (cell.type === 'single-stat') {
        return (

{cell.name}

              <RefreshingSingleStat queries={[qs[0]]} autoRefresh={autoRefreshMs} />

        );
      }

      return (

{cell.name}

            <RefreshingLineGraph queries={qs} autoRefresh={autoRefreshMs} showSingleStat={cell.type === "line-plus-single-stat"} />

      );
    });
  },

  render() {
    const layoutMargin = 4;
    return (
      <GridLayout
        layout={this.state.layout}
        cols={12}
        rowHeight={83.5}
        margin={[layoutMargin, layoutMargin]}
        containerPadding={[0, 0]}
        useCSSTransforms={false}
        onResize={triggerWindowResize}
        onLayoutChange={triggerWindowResize}
      >
        {this.generateVisualizations()}
      </GridLayout>
    );

    function triggerWindowResize() {
      // Hack to get dygraphs to fit properly during and after resize (dispatchEvent is a global method on window).
      const evt = document.createEvent('CustomEvent');  // MUST be 'CustomEvent'
      evt.initCustomEvent('resize', false, false, null);
      dispatchEvent(evt);
    }

  },
});

export default LayoutRenderer;
<commit_msg>Remove padded line<commit_after>import React, {PropTypes} from 'react';
import AutoRefresh from 'shared/components/AutoRefresh';
import LineGraph from 'shared/components/LineGraph';
import SingleStat from 'shared/components/SingleStat';
import ReactGridLayout, {WidthProvider} from 'react-grid-layout';
const GridLayout = WidthProvider(ReactGridLayout);
import _ from 'lodash';

const RefreshingLineGraph = AutoRefresh(LineGraph);
const RefreshingSingleStat = AutoRefresh(SingleStat);

export const LayoutRenderer = React.createClass({
  propTypes: {
    timeRange: PropTypes.shape({
      defaultGroupBy: PropTypes.string.isRequired,
      queryValue: PropTypes.string.isRequired,
    }).isRequired,
    cells: PropTypes.arrayOf(
      PropTypes.shape({
        queries: PropTypes.arrayOf(
          PropTypes.shape({
            label: PropTypes.string,
            range: PropTypes.shape({
              upper: PropTypes.number,
              lower: PropTypes.number,
            }),
            rp: PropTypes.string,
            text: PropTypes.string.isRequired,
            database: PropTypes.string.isRequired,
            groupbys: PropTypes.arrayOf(PropTypes.string),
            wheres: PropTypes.arrayOf(PropTypes.string),
          }).isRequired
        ).isRequired,
        x: PropTypes.number.isRequired,
        y: PropTypes.number.isRequired,
        w: PropTypes.number.isRequired,
        h: PropTypes.number.isRequired,
        i: PropTypes.string.isRequired,
        name: PropTypes.string.isRequired,
      }).isRequired
    ),
    autoRefreshMs: PropTypes.number.isRequired,
    host: PropTypes.string,
    source: PropTypes.string,
  },

  getInitialState() {
    return ({
      layout: _.without(this.props.cells, ['queries']),
    });
  },

  buildQuery(q) {
    const {timeRange, host} = this.props;
    const {wheres, groupbys} = q;

    let text = q.text;

    text += ` where time > ${timeRange.queryValue}`;

    if (host) {
      text += ` and \"host\" = '${host}'`;
    }

    if (wheres && wheres.length > 0) {
      text += ` and ${wheres.join(' and ')}`;
    }

    if (groupbys) {
      if (groupbys.find((g) => g.includes("time"))) {
        text += ` group by ${groupbys.join(',')}`;
      } else if (groupbys.length > 0) {
        text += ` group by time(${timeRange.defaultGroupBy}),${groupbys.join(',')}`;
      } else {
        text += ` group by time(${timeRange.defaultGroupBy})`;
      }
    } else {
      text += ` group by time(${timeRange.defaultGroupBy})`;
    }

    return text;
  },

  generateVisualizations() {
    const {autoRefreshMs, source, cells} = this.props;

    return cells.map((cell) => {
      const qs = cell.queries.map((q) => {
        return Object.assign({}, q, {
          host: source,
          text: this.buildQuery(q),
        });
      });

      if (cell.type === 'single-stat') {
        return (

{cell.name}

              <RefreshingSingleStat queries={[qs[0]]} autoRefresh={autoRefreshMs} />

        );
      }

      return (

{cell.name}

            <RefreshingLineGraph queries={qs} autoRefresh={autoRefreshMs} showSingleStat={cell.type === "line-plus-single-stat"} />

      );
    });
  },

  render() {
    const layoutMargin = 4;
    return (
      <GridLayout
        layout={this.state.layout}
        cols={12}
        rowHeight={83.5}
        margin={[layoutMargin, layoutMargin]}
        containerPadding={[0, 0]}
        useCSSTransforms={false}
        onResize={triggerWindowResize}
        onLayoutChange={triggerWindowResize}
      >
        {this.generateVisualizations()}
      </GridLayout>
    );

    function triggerWindowResize() {
      // Hack to get dygraphs to fit properly during and after resize (dispatchEvent is a global method on window).
      const evt = document.createEvent('CustomEvent');  // MUST be 'CustomEvent'
      evt.initCustomEvent('resize', false, false, null);
      dispatchEvent(evt);
    }
  },
});

export default LayoutRenderer;
<|endoftext|>


<commit_before>import httpStatus from 'http-status';
import sqlClient from 'squel'

import Sequelize from 'sequelize';
import config from '../../../config/config';

const sequelize = new Sequelize(config.dbUriG, {
  define: {
    charset: 'utf8',
    collate: 'utf8_general_ci',
    timestamps: true
  },
  logging: false
});

const selectWithOutOperation = "select {0}";
const fromWithOutJoins = "from {0}";
const groupBy = "group by {0}";

const replaceAll = (search, replacement, target) => {
    return target.split(search).join(replacement);
}

const baseQueryHandler = (baseColumn, operation, column) => {
    let sqlOperation = "";
    if(column.second_table != "dim_fecha" && baseColumn.second_table != "dim_fecha"){
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.name + ") as value"
                break;
            }
            default: {
                break;
            }
        }
        let sqlColumn = column.name;
        let calculateColumn = "q." + baseColumn.name;
        let groupBy =  calculateColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("nit_proveedor").field("nog").field(column.name).field(baseColumn.name).from("consolidated_table");
        }
        else{
            selectFrom = sqlClient.select().distinct().field("nog").field(column.name).field(baseColumn.name).from("consolidated_table");
        }

        let query = sqlClient.select().field(sqlOperation).field(calculateColumn).from(selectFrom, "q").group(groupBy);

        return query.toString();
    }
    else if (column.second_table != "dim_fecha" && baseColumn.second_table == "dim_fecha"){
        let sqlOperation = "";
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.name + ") as value"
                break;
            }
            default: {
                break;
            }
        }

        let joinDateField = "b." + baseColumn.date_column;
        let joinOpFielf = "a." + column.name;
        let joinCondition = "a." + baseColumn.name + "=" + "b.id_fecha";
        let sqlColumn = column.date_column;
        let displayColumn = "q." +  baseColumn.date_column;
        let groupBy = displayColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("a.nit_proveedor").field("a.nog").field(joinOpFielf).field(joinDateField).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }
        else{
            selectFrom = sqlClient.select().distinct().field("a.nog").field(joinOpFielf).field(joinDateField).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }
        let query = sqlClient.select().field(sqlOperation).field(displayColumn).from(selectFrom, "q").group(groupBy);
        return query.toString();
    }
    else if (column.second_table == "dim_fecha" && baseColumn.second_table != "dim_fecha"){
        let sqlOperation = "";
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.date_column + ") as value"
                break;
            }
            default: {
                break;
            }
        }

        let joinDateField = "b." + column.name ;
        let joinOpFielf = "a." + baseColumn.name;
        let joinCondition = "a." + column.name + "=" + "b.id_fecha";
        let realColumn = "b." + column.date_column;
        let sqlColumn = column.name;
        let displayColumn = "q." +  baseColumn.name;
        let groupBy = displayColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("a.nit_proveedor").field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }
        else{
            selectFrom = sqlClient.select().distinct().field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }

        let query = sqlClient.select().field(sqlOperation).field(displayColumn).from(selectFrom, "q").group(groupBy);
        return query.toString();
    }else{
        let sqlOperation = "";
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.date_column + ") as value"
                break;
            }
            default: {
                break;
            }
        }

        let joinDateField = "b." + column.name ;
        let joinOpFielf = "a." + baseColumn.name;
        let joinCondition = "a." + column.name + "=" + "b.id_fecha";
        let realColumn = "b." + column.date_column;
        let sqlColumn = column.name;
        let displayColumn = "q." +  baseColumn.date_column;
        let groupBy = displayColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("a.nit_proveedor").field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }else{
            selectFrom = sqlClient.select().distinct().field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }
        let query = sqlClient.select().field(sqlOperation).field(displayColumn).from(selectFrom, "q").group(groupBy);
        return query.toString();
    }

};

const getDataForPreview = async(req, res) => {
    try{

        const filters = req.body.definition.filters;

        const dateFilters = req.body.definition.dateFilters;
        let baseQuery = "";

        //Base Query data
        let baseColumn = req.body.definition.baseColumn;
        let category = req.body.definition.category;
        baseQuery = baseQueryHandler(baseColumn, category.operation, category.column);

        //Filters data
        const filterColumns = []
        const filterOperations = []

        if(filters.length > 0){
            filters.forEach(function(item, index){
                if(item.column =! null && item.operation != null){
                    filterColumns.push(item.column);
                    filterOperations.push(item.operation);
                }
            });
        }

        //Date Filter Data

        //Run query

        let queryString = replaceAll("`","",baseQuery);
        const data = await sequelize.query(queryString);

        return res.json(data);
    }
    catch (e) {
        console.log(e);
        return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(e);
    }

}

export default {
    getDataForPreview
  };

<commit_msg>add support for filters<commit_after>import httpStatus from 'http-status';
import sqlClient from 'squel'

import Sequelize from 'sequelize';
import config from '../../../config/config';

const sequelize = new Sequelize(config.dbUriG, {
  define: {
    charset: 'utf8mb4',
    collate: 'utf8_general_ci',
    timestamps: true
  },
  logging: false
});

const selectWithOutOperation = "select {0}";
const fromWithOutJoins = "from {0}";
const groupBy = "group by {0}";

const replaceAll = (search, replacement, target) => {
    return target.split(search).join(replacement);
}
const buildConstraints = (baseQuery, columns, operations, values, baseColumnDate, operationColumnDate) => {
    for(let x = 0; x < columns.length; x++){
        let column = columns[x];
        let operation = operations[x];
        let value = values[x];
        let condition = ""
        if(!baseColumnDate && !operationColumnDate){
            baseQuery = baseQuery.where(buildOperation(column, value, operation));
        }
    }
    return baseQuery;
}

const buildOperation = (column, value, operation) =>{
    let sentence = ""
    if(operation.value_type == 1){
        switch(operation.name){
            case "Igual a": {
                sentence = "a." + column.name + "=" + "'" + value + "'";;
                return sentence;
            }
            case "Diferente de":{
                sentence ="a."  + column.name + "!=" + "'" + value + "'";
                return sentence;
            }
            case "Contiene":{
                sentence = "a." + column.name + " like " + "'" + "%" + value + "%" + "'";
                return sentence;
            }

            default:{
                break;
            }
        }
    }
    if(operation.value_type == 2 || operation.value_type == 4){
        switch(operation.name){
            case "Mayor que":{
                sentence = "a." + column.name + ">" + value;
                return sentence;
            }
            case "Menor que": {
                sentence = "a." + column.name + "<" + value;
                return sentence;
            }
            case "Igual a": {
                sentence = "a." + column.name + "="  + value ;
                return sentence;
            }
            case "Diferente de":{
                sentence ="a."  + column.name + "!=" + value;
                return sentence;
            }
        }

    }

}

const baseQueryHandler = (baseColumn, operation, column, filterList) => {
    let sqlOperation = "";
    if(column.second_table != "dim_fecha" && baseColumn.second_table != "dim_fecha"){
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.name + ") as value"
                break;
            }
            default: {
                break;
            }
        }
        let sqlColumn = column.name;
        let calculateColumn = "q." + baseColumn.name;
        let groupBy =  calculateColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("a.nit_proveedor").field("a.nog").field(column.name).field("a."+baseColumn.name).from("consolidated_table","a").join("dim_fecha","b","b.id_fecha = a.fecha_adjudicada");
        }
        else{
            selectFrom = sqlClient.select().distinct().field("a.nog").field(column.name).field("a."+baseColumn.name).from("consolidated_table","a").join("dim_fecha","b","b.id_fecha = a.fecha_adjudicada")
        }
        if(filterList[0] != undefined){
            if (filterList[0].length > 0){
                selectFrom = buildConstraints(selectFrom, filterList[0], filterList[1], filterList[2], false, false)
            }
        }

        let query = sqlClient.select().field(sqlOperation).field(calculateColumn).from(selectFrom, "q")

        query = query.group(groupBy);

        return query.toString();
    }
    else if (column.second_table != "dim_fecha" && baseColumn.second_table == "dim_fecha"){
        let sqlOperation = "";
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.name + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.name + ") as value"
                break;
            }
            default: {
                break;
            }
        }

        let joinDateField = "b." + baseColumn.date_column;
        let joinOpFielf = "a." + column.name;
        let joinCondition = "a." + baseColumn.name + "=" + "b.id_fecha";
        let sqlColumn = column.date_column;
        let displayColumn = "q." +  baseColumn.date_column;
        let groupBy = displayColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("a.nit_proveedor").field("a.nog").field(joinOpFielf).field(joinDateField).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }
        else{
            selectFrom = sqlClient.select().distinct().field("a.nog").field(joinOpFielf).field(joinDateField).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }
        if(filterList[0] != undefined){
            if (filterList[0].length > 0){
                selectFrom = buildConstraints(selectFrom, filterList[0], filterList[1], filterList[2], false, false)
            }
        }
        let query = sqlClient.select().field(sqlOperation).field(displayColumn).from(selectFrom, "q").group(groupBy);
        return query.toString();
    }
    else if (column.second_table == "dim_fecha" && baseColumn.second_table != "dim_fecha"){
        let sqlOperation = "";
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.date_column + ") as value"
                break;
            }
            default: {
                break;
            }
        }

        let joinDateField = "b." + column.name ;
        let joinOpFielf = "a." + baseColumn.name;
        let joinCondition = "a." + column.name + "=" + "b.id_fecha";
        let realColumn = "b." + column.date_column;
        let sqlColumn = column.name;
        let displayColumn = "q." +  baseColumn.name;
        let groupBy = displayColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("a.nit_proveedor").field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }
        else{
            selectFrom = sqlClient.select().distinct().field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }

        if(filterList[0] != undefined){
            if (filterList[0].length > 0){
                selectFrom = buildConstraints(selectFrom, filterList[0], filterList[1], filterList[2], false, false)
            }
        }

        let query = sqlClient.select().field(sqlOperation).field(displayColumn).from(selectFrom, "q").group(groupBy);
        return query.toString();
    }else{
        let sqlOperation = "";
        switch(operation.name){
            case "Contar": {
                sqlOperation = "COUNT(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Sumar":{
                sqlOperation = "SUM(" + 'q.' + column.date_column + ") as value"
                break;
            }
            case "Promedio":{
                sqlOperation = "AVG(" + 'q.' + column.date_column + ") as value"
                break;
            }
            default: {
                break;
            }
        }

        let joinDateField = "b." + column.name ;
        let joinOpFielf = "a." + baseColumn.name;
        let joinCondition = "a." + column.name + "=" + "b.id_fecha";
        let realColumn = "b." + column.date_column;
        let sqlColumn = column.name;
        let displayColumn = "q." +  baseColumn.date_column;
        let groupBy = displayColumn;
        let selectFrom = "";
        if( baseColumn.name == "monto" || column.name == "monto"){
            selectFrom = sqlClient.select().distinct().field("a.nit_proveedor").field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }else{
            selectFrom = sqlClient.select().distinct().field("a.nog").field(joinOpFielf).field(realColumn).from("consolidated_table","a").join("dim_fecha","b",joinCondition);
        }

        if(filterList[0] != undefined){
            if (filterList[0].length > 0){
                selectFrom = buildConstraints(selectFrom, filterList[0], filterList[1], filterList[2], false, false)
            }
        }
        let query = sqlClient.select().field(sqlOperation).field(displayColumn).from(selectFrom, "q").group(groupBy);
        return query.toString();
    }

};

const getDataForPreview = async(req, res) => {
    try{

        const filters = req.body.definition.filters;

        const dateFilters = req.body.definition.dateFilters;
        let finalQuery = "";

        //Base Query data
        let baseColumn = req.body.definition.baseColumn;
        let category = req.body.definition.category;

        //Filters data
        let filterColumns = [];
        let filterOperations = [];
        let filterValues = [];
        let filterList = [];

        if(filters!= undefined){
            if(filters.length > 0){
                filters.forEach(function(item, index){

                    filterColumns.push(item.column);
                    filterOperations.push(item.operation);
                    filterValues.push(item.value);

                });
                filterList.push(filterColumns, filterOperations, filterValues)
            }

        }

        //Date Filter Data

        //Run query
        finalQuery = baseQueryHandler(baseColumn, category.operation, category.column, filterList);
        let queryString = replaceAll("`","",finalQuery);
        const data = await sequelize.query(queryString);

        return res.json(data);
    }
    catch (e) {
        console.log(e);
        return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(e);
    }

}

export default {
    getDataForPreview
  };

<|endoftext|>


<commit_before>var slice = Array.prototype.slice;

let _curry = (n, fn, curryArgs = []) => {
  return (...args) => {
    var concatArgs = curryArgs.concat(args);

    if (n > concatArgs.length) {
      return _curry(n, fn, concatArgs);
    } else {
      return fn.apply(null, slice.call(concatArgs, 0, n));
    }
  };
};

export function curry(fn) {
  return _curry(fn.length, fn);
}

export function curryN(n, fn) {
  return _curry(n, fn);
}

export var curry1 = curryN(2, curryN)(1);
export var curry2 = curryN(2, curryN)(2);
export var curry3 = curryN(2, curryN)(3);
export var curry4 = curryN(2, curryN)(4);
<commit_msg>factor out fn.apply and add es2015 spread operators<commit_after>let _curry = (fn, curryArgs = []) => {
  return (...args) => {
    var concatArgs = [...concatArgs, ...args];

    // If function arity greater than number of received args
    if (fn.length > concatArgs.length) {
      return _curry(fn, concatArgs);
    } else {
      return fn(...concatArgs);
    }
  };
};

export function curry(fn) {
  return _curry(fn);
}

// curryN now unnecessary
export function curryN(n, fn) {
  return _curry(n, fn);
}

export var curry1 = curryN(2, curryN)(1);
export var curry2 = curryN(2, curryN)(2);
export var curry3 = curryN(2, curryN)(3);
export var curry4 = curryN(2, curryN)(4);
<|endoftext|>


<commit_before>/**
 * Bootstrap Table Spanish (Costa Rica) translation
 * Author: Dennis Hernández (http://djhvscf.github.io/Blog/)
 */
(function ($) {
    'use strict';

    $.extend($.fn.bootstrapTable.defaults, {
        formatLoadingMessage: function () {
            return 'Cargando, por favor espere...';
        },
        formatRecordsPerPage: function (pageNumber) {
            return pageNumber + ' registros por página';
        },
        formatShowingRows: function (pageFrom, pageTo, totalRows) {
            return 'Mostrando de ' + pageFrom + ' a ' + pageTo + ' registros de ' + totalRows + ' registros en total';
        },
        formatSearch: function () {
            return 'Buscar';
        },
        formatNoMatches: function () {
            return 'No se encontraron registros';
        },
        formatRefresh: function () {
            return 'Refrescar';
        },
        formatToggle: function () {
            return 'Alternar';
        },
        formatColumns: function () {
            return 'Columnas';
        }
    });
})(jQuery);
<commit_msg>Delete bootstrap-table-es-CR.js<commit_after><|endoftext|>


<commit_before>angular.module('pcApp.fcm.directives.cytoscapes', [])

    .directive('cytoscape', function ($rootScope) {
        // graph visualisation by - https://github.com/cytoscape/cytoscape.js
        return {
            restrict: 'E',
            template: '

',
            replace: true,
            scope: {
                // data objects to be passed as an attributes - for nodes and edges
                cyData: '=',
                cyEdges: '=', // controller function to be triggered when clicking on a node
                cyClick: '&',
                cyMouseup: '&'
            },
            link: function (scope, element, attrs, fn) {
                // dictionary of colors by types. Just to show some design options
                scope.typeColors = {
                    'ellipse': '#992222',
                    'triangle': '#222299',
                    'rectangle': '#661199',
                    'roundrectangle': '#772244',
                    'pentagon': '#990088',
                    'hexagon': '#229988',
                    'heptagon': '#118844',
                    'octagon': '#335577',
                    'star': '#113355'
                };

                // graph  build
                scope.doCy = function () { // will be triggered on an event broadcast
                    // initialize data object
                    scope.elements = {};
                    scope.elements.nodes = [];
                    scope.elements.edges = [];

                    // parse data and create the Nodes array
                    // object type - is the object's group
                    for (i = 0; i < scope.cyData.length; i++) {
                        // get id, name and type  from the object
                        var dId = "n" + scope.cyData[i].id;
                        var dName = scope.cyData[i].name.substring(0, 24);
                        var dType = 'roundrectangle';
                        var posX = scope.cyData[i].posX;
                        var posY = scope.cyData[i].posY;
                        // get color from the object-color dictionary
                        var typeColor = scope.typeColors[4];
                        // build the object, add or change properties as you need - just have a name and id
                        var elementObj = {
                            data: {
                                id: dId,
                                name: dName,
                                typeColor: typeColor,
                                typeShape: dType,
                                type: dType
                            },
                            position: {
                                x: posX,
                                y: posY
                            }
                        };
                        // add new object to the Nodes array
                        scope.elements.nodes.push(elementObj);
                    }

                    // parse edges
                    // you can build a complete object in the controller and pass it without rebuilding it in the directive.
                    // doing it like that allows you to add options, design or what needed to the objects
                    // doing it like that is also good if your data object/s has a different structure
                    for (i = 0; i < scope.cyEdges.length; i++) {
                        // get edge source
                        var eSource = "n" + scope.cyEdges[i].source;
                        // get edge target
                        var eTarget = "n" + scope.cyEdges[i].target;
                        // get edge id
                        var eId = "e" + scope.cyEdges[i].id;
                        // get edge weight
                        var eLabel = scope.cyEdges[i].weighted;
                        // Change arrows colors against the weight value.
                        var edgecolor = 'grey';
                        if (eLabel > 0)
                            edgecolor = 'green';
                        else if (eLabel < 0)
                            edgecolor = 'red';

                        // build the edge object
                        var edgeObj = {
                            data: {
                                id: eId,
                                source: eSource,
                                target: eTarget,
                                label: eLabel,
                                edgecolor: edgecolor

                            }
                        };
                        // adding the edge object to the edges array
                        console.log(edgeObj);
                        scope.elements.edges.push(edgeObj);
                    }

                    // graph  initialization
                    // use object's properties as properties using: data(propertyName)
                    // check Cytoscapes site for much more data, options, designs etc
                    // http://cytoscape.github.io/cytoscape.js/
                    // here are just some basic options
                    $('#cy').cytoscape({
                        showOverlay: false,
                        zoom: 1,
                        layout: {
                            name: 'preset',
                            positions: undefined,
                            zoom: undefined,
                            pan: undefined,
                            fit: false,
                            padding: 30,
                            animate: false,
                            animationDuration: 500,
                            ready: undefined,
                            stop: undefined,
                        },
                        style: cytoscape.stylesheet().selector('node').css({
                            'shape': 'roundrectangle',
                            'width': '200',
                            'height': '40',
                            'background-color': 'data(typeColor)',
                            'content': 'data(name)',
                            'text-valign': 'center',
                            'color': 'white',
                            'text-outline-color': 'data(typeColor)'
                        }).selector('edge').css({
                            'target-arrow-shape': 'triangle',
                            'content': 'data(label)',
                            'text-outline-color': '#FFFFFF',
                            'text-outline-opacity': '1',
                            'text-outline-width': 2,
                            'text-valign': 'center',
                            'color': '#777777',
                            'width': '2px',
                            'line-color': 'data(edgecolor)',
                            'target-arrow-color': 'data(edgecolor)'
                        }).selector(':selected').css({
                            'background-color': '#C50C44',
                            'line-color': 'black',
                            'target-arrow-color': 'black',
                            'source-arrow-color': 'black'
                        }).selector('.faded').css({
                            'opacity': 0.65,
                            'text-opacity': 0.65
                        }),
                        ready: function () {
                            window.cy = this;

                            // giddy up...
                            cy.elements().unselectify();
                            // ##MOBA## this is to calculate the doubleClick trigger over a node in the Edit mode.
                            var tappedBefore;
                            var tappedTimeout;
                            cy.on('tap', function (event) {

                                var tappedNow = event.cyTarget;
                                if (tappedTimeout && tappedBefore) {
                                    clearTimeout(tappedTimeout);
                                }
                                if (tappedBefore === tappedNow) {
                                    tappedNow.trigger('doubleTap');
                                    tappedBefore = null;
                                } else {
                                    tappedTimeout = setTimeout(function () { tappedBefore = null; }, 300);
                                    tappedBefore = tappedNow;
                                }
                            });

                            // Event listeners
                            // with sample calling to the controller function as passed as an attribute
                            cy.on('unselect', 'node', function (e) {
                                var nodes = cy.elements('node');
                                nodes.css('background-color', 'gray');
                            });

                            cy.on('doubleTap', 'node', function (e) {
                                var nodes = cy.elements('node');
                                nodes.css('background-color', 'gray');
                                var evtTarget = e.cyTarget;
                                var nodeId = evtTarget.id();
                                var edgesFrom = cy.elements('edge[source="' + nodeId + '"]');
                                var edgesTo = cy.elements('edge[target="' + nodeId + '"]');
                                evtTarget.css('background-color', '#C50C44');
                                for (i = 0; i < edgesFrom.length; i++) {
                                    var nodeChild = edgesFrom[i].target();
                                    nodeChild.css('background-color', 'blue');
                                }
                                for (i = 0; i < edgesTo.length; i++) {
                                    var nodeParent = edgesTo[i].source();
                                    nodeParent.css('background-color', 'green');
                                }
                                scope.cyClick({ value: nodeId });
                            });

                            cy.on('mouseup', 'node', function (e) {
                                var evtTarget = e.cyTarget;
                                var nodeId = evtTarget.id();
                                var posX = evtTarget.position("x");
                                var posY = evtTarget.position("y");
                                scope.cyMouseup({
                                    value: nodeId,
                                    x: posX,
                                    y: posY
                                });
                            });

                            cy.on('doubleTap', 'edge', function (e) {
                                var evtTarget = e.cyTarget;
                                var nodeId = evtTarget.id();
                                scope.cyClick({ value: nodeId });
                            });

                            cy.on('mouseover', 'edge', function (e) {
                                $(cy.container()).css('cursor', 'crosshair');
                            });
                            cy.on('mouseout', 'edge', function (e) {
                                $(cy.container()).css('cursor', 'default');
                            });
                            cy.on('mouseover', 'node', function (e) {
                                $(cy.container()).css('cursor', 'crosshair');
                            });
                            cy.on('mouseout', 'node', function (e) {
                                $(cy.container()).css('cursor', 'default');
                            });

                            cy.panzoom({
                                // options go here
                            });
                            // load the objects array
                            // use cy.add() / cy.remove() with passed data to add or remove nodes and edges without rebuilding the graph
                            // sample use can be adding a passed variable which will be broadcast on change
                            cy.load(scope.elements);

                            if (scope.elements.nodes.length > 5) {
                                cy.fit(window.defaults.fitPadding);
                            }
                        }
                    });

                }; // end doCy()

                // When the app object changed = redraw the graph
                // you can use it to pass data to be added or removed from the object without redrawing it
                // using cy.remove() / cy.add()
                $rootScope.$on('appChanged', function (e) {
                    scope.doCy();
                });
            }
        };
    });
<commit_msg>Change  mouse corsor changed over a node. policycompass/policycompass#456<commit_after>angular.module('pcApp.fcm.directives.cytoscapes', [])

    .directive('cytoscape', function ($rootScope) {
        // graph visualisation by - https://github.com/cytoscape/cytoscape.js
        return {
            restrict: 'E',
            template: '

',
            replace: true,
            scope: {
                // data objects to be passed as an attributes - for nodes and edges
                cyData: '=',
                cyEdges: '=', // controller function to be triggered when clicking on a node
                cyClick: '&',
                cyMouseup: '&'
            },
            link: function (scope, element, attrs, fn) {
                // dictionary of colors by types. Just to show some design options
                scope.typeColors = {
                    'ellipse': '#992222',
                    'triangle': '#222299',
                    'rectangle': '#661199',
                    'roundrectangle': '#772244',
                    'pentagon': '#990088',
                    'hexagon': '#229988',
                    'heptagon': '#118844',
                    'octagon': '#335577',
                    'star': '#113355'
                };

                // graph  build
                scope.doCy = function () { // will be triggered on an event broadcast
                    // initialize data object
                    scope.elements = {};
                    scope.elements.nodes = [];
                    scope.elements.edges = [];

                    // parse data and create the Nodes array
                    // object type - is the object's group
                    for (i = 0; i < scope.cyData.length; i++) {
                        // get id, name and type  from the object
                        var dId = "n" + scope.cyData[i].id;
                        var dName = scope.cyData[i].name.substring(0, 24);
                        var dType = 'roundrectangle';
                        var posX = scope.cyData[i].posX;
                        var posY = scope.cyData[i].posY;
                        // get color from the object-color dictionary
                        var typeColor = scope.typeColors[4];
                        // build the object, add or change properties as you need - just have a name and id
                        var elementObj = {
                            data: {
                                id: dId,
                                name: dName,
                                typeColor: typeColor,
                                typeShape: dType,
                                type: dType
                            },
                            position: {
                                x: posX,
                                y: posY
                            }
                        };
                        // add new object to the Nodes array
                        scope.elements.nodes.push(elementObj);
                    }

                    // parse edges
                    // you can build a complete object in the controller and pass it without rebuilding it in the directive.
                    // doing it like that allows you to add options, design or what needed to the objects
                    // doing it like that is also good if your data object/s has a different structure
                    for (i = 0; i < scope.cyEdges.length; i++) {
                        // get edge source
                        var eSource = "n" + scope.cyEdges[i].source;
                        // get edge target
                        var eTarget = "n" + scope.cyEdges[i].target;
                        // get edge id
                        var eId = "e" + scope.cyEdges[i].id;
                        // get edge weight
                        var eLabel = scope.cyEdges[i].weighted;
                        // Change arrows colors against the weight value.
                        var edgecolor = 'grey';
                        if (eLabel > 0)
                            edgecolor = 'green';
                        else if (eLabel < 0)
                            edgecolor = 'red';

                        // build the edge object
                        var edgeObj = {
                            data: {
                                id: eId,
                                source: eSource,
                                target: eTarget,
                                label: eLabel,
                                edgecolor: edgecolor

                            }
                        };
                        // adding the edge object to the edges array
                        console.log(edgeObj);
                        scope.elements.edges.push(edgeObj);
                    }

                    // graph  initialization
                    // use object's properties as properties using: data(propertyName)
                    // check Cytoscapes site for much more data, options, designs etc
                    // http://cytoscape.github.io/cytoscape.js/
                    // here are just some basic options
                    $('#cy').cytoscape({
                        showOverlay: false,
                        zoom: 1,
                        layout: {
                            name: 'preset',
                            positions: undefined,
                            zoom: undefined,
                            pan: undefined,
                            fit: false,
                            padding: 30,
                            animate: false,
                            animationDuration: 500,
                            ready: undefined,
                            stop: undefined,
                        },
                        style: cytoscape.stylesheet().selector('node').css({
                            'shape': 'roundrectangle',
                            'width': '200',
                            'height': '40',
                            'background-color': 'data(typeColor)',
                            'content': 'data(name)',
                            'text-valign': 'center',
                            'color': 'white',
                            'text-outline-color': 'data(typeColor)'
                        }).selector('edge').css({
                            'target-arrow-shape': 'triangle',
                            'content': 'data(label)',
                            'text-outline-color': '#FFFFFF',
                            'text-outline-opacity': '1',
                            'text-outline-width': 2,
                            'text-valign': 'center',
                            'color': '#777777',
                            'width': '2px',
                            'line-color': 'data(edgecolor)',
                            'target-arrow-color': 'data(edgecolor)'
                        }).selector(':selected').css({
                            'background-color': '#C50C44',
                            'line-color': 'black',
                            'target-arrow-color': 'black',
                            'source-arrow-color': 'black'
                        }).selector('.faded').css({
                            'opacity': 0.65,
                            'text-opacity': 0.65
                        }),
                        ready: function () {
                            window.cy = this;

                            // giddy up...
                            cy.elements().unselectify();
                            // ##MOBA## this is to calculate the doubleClick trigger over a node in the Edit mode.
                            var tappedBefore;
                            var tappedTimeout;
                            cy.on('tap', function (event) {

                                var tappedNow = event.cyTarget;
                                if (tappedTimeout && tappedBefore) {
                                    clearTimeout(tappedTimeout);
                                }
                                if (tappedBefore === tappedNow) {
                                    tappedNow.trigger('doubleTap');
                                    tappedBefore = null;
                                } else {
                                    tappedTimeout = setTimeout(function () { tappedBefore = null; }, 300);
                                    tappedBefore = tappedNow;
                                }
                            });

                            // Event listeners
                            // with sample calling to the controller function as passed as an attribute
                            cy.on('unselect', 'node', function (e) {
                                var nodes = cy.elements('node');
                                nodes.css('background-color', 'gray');
                            });

                            cy.on('doubleTap', 'node', function (e) {
                                var nodes = cy.elements('node');
                                nodes.css('background-color', 'gray');
                                var evtTarget = e.cyTarget;
                                var nodeId = evtTarget.id();
                                var edgesFrom = cy.elements('edge[source="' + nodeId + '"]');
                                var edgesTo = cy.elements('edge[target="' + nodeId + '"]');
                                evtTarget.css('background-color', '#C50C44');
                                for (i = 0; i < edgesFrom.length; i++) {
                                    var nodeChild = edgesFrom[i].target();
                                    nodeChild.css('background-color', 'blue');
                                }
                                for (i = 0; i < edgesTo.length; i++) {
                                    var nodeParent = edgesTo[i].source();
                                    nodeParent.css('background-color', 'green');
                                }
                                scope.cyClick({ value: nodeId });
                            });

                            cy.on('mouseup', 'node', function (e) {
                                var evtTarget = e.cyTarget;
                                var nodeId = evtTarget.id();
                                var posX = evtTarget.position("x");
                                var posY = evtTarget.position("y");
                                scope.cyMouseup({
                                    value: nodeId,
                                    x: posX,
                                    y: posY
                                });
                            });

                            cy.on('doubleTap', 'edge', function (e) {
                                var evtTarget = e.cyTarget;
                                var nodeId = evtTarget.id();
                                scope.cyClick({ value: nodeId });
                            });
                            //##MOBA## mouse cursor change over a node
                            cy.on('mouseover', 'node', function (e) {
                                $(cy.container()).css('cursor', 'pointer');
                            });
                            cy.on('mousedown', 'node', function (e) {
                                $(cy.container()).css('cursor', 'move');
                            });
                            cy.on('mouseout', 'node', function (e) {
                                $(cy.container()).css('cursor', 'default');
                            });

                            cy.panzoom({
                                // options go here
                            });
                            // load the objects array
                            // use cy.add() / cy.remove() with passed data to add or remove nodes and edges without rebuilding the graph
                            // sample use can be adding a passed variable which will be broadcast on change
                            cy.load(scope.elements);

                            if (scope.elements.nodes.length > 5) {
                                cy.fit(window.defaults.fitPadding);
                            }
                        }
                    });

                }; // end doCy()

                // When the app object changed = redraw the graph
                // you can use it to pass data to be added or removed from the object without redrawing it
                // using cy.remove() / cy.add()
                $rootScope.$on('appChanged', function (e) {
                    scope.doCy();
                });
            }
        };
    });
<|endoftext|>