<commit_before>import { createSelector } from 'reselect';
import { List as ImmutableList, Map as ImmutableMap, is } from 'immutable';
import { me } from '../initial_state';

const getAccountBase         = (state, id) => state.getIn(['accounts', id], null);
const getAccountCounters     = (state, id) => state.getIn(['accounts_counters', id], null);
const getAccountRelationship = (state, id) => state.getIn(['relationships', id], null);
const getAccountMoved        = (state, id) => state.getIn(['accounts', state.getIn(['accounts', id, 'moved'])]);

export const makeGetAccount = () => {
  return createSelector([getAccountBase, getAccountCounters, getAccountRelationship, getAccountMoved], (base, counters, relationship, moved) => {
    if (base === null) {
      return null;
    }

    return base.merge(counters).withMutations(map => {
      map.set('relationship', relationship);
      map.set('moved', moved);
    });
  });
};

const toServerSideType = columnType => {
  switch (columnType) {
  case 'home':
  case 'notifications':
  case 'public':
  case 'thread':
  case 'account':
    return columnType;
  default:
    if (columnType.indexOf('list:') > -1) {
      return 'home';
    } else {
      return 'public'; // community, account, hashtag
    }
  }
};

const escapeRegExp = string =>
  string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string

const regexFromKeywords = keywords => {
  if (keywords.size === 0) {
    return null;
  }

  return new RegExp(keywords.map(keyword_filter => {
    let expr = escapeRegExp(keyword_filter.get('keyword'));

    if (keyword_filter.get('whole_word')) {
      if (/^[\w]/.test(expr)) {
        expr = `\\b${expr}`;
      }

      if (/[\w]$/.test(expr)) {
        expr = `${expr}\\b`;
      }
    }

    return expr;
  }).join('|'), 'i');
};

const getFilters = (state, { contextType }) => {
  if (!contextType) return null;

  const serverSideType = toServerSideType(contextType);
  const now = new Date();

  return state.get('filters').filter((filter) => filter.get('context').includes(serverSideType) && (filter.get('expires_at') === null || filter.get('expires_at') > now));
};

export const makeGetStatus = () => {
  return createSelector(
    [
      (state, { id }) => state.getIn(['statuses', id]),
      (state, { id }) => state.getIn(['statuses', state.getIn(['statuses', id, 'reblog'])]),
      (state, { id }) => state.getIn(['accounts', state.getIn(['statuses', id, 'account'])]),
      (state, { id }) => state.getIn(['accounts', state.getIn(['statuses', state.getIn(['statuses', id, 'reblog']), 'account'])]),
      getFilters,
    ],

    (statusBase, statusReblog, accountBase, accountReblog, filters) => {
      if (!statusBase) {
        return null;
      }

      if (statusReblog) {
        statusReblog = statusReblog.set('account', accountReblog);
      } else {
        statusReblog = null;
      }

      let filtered = false;
      if ((accountReblog || accountBase).get('id') !== me && filters) {
        let filterResults = statusReblog?.get('filtered') || statusBase.get('filtered') || ImmutableList();
        if (filterResults.some((result) => filters.getIn([result.get('filter'), 'filter_action']) === 'hide')) {
          return null;
        }
        if (!filterResults.isEmpty()) {
          filtered = filterResults.map(result => filters.getIn([result.get('filter'), 'title']));
        }
      }

      return statusBase.withMutations(map => {
        map.set('reblog', statusReblog);
        map.set('account', accountBase);
        map.set('matched_filters', filtered);
      });
    },
  );
};

export const makeGetPictureInPicture = () => {
  return createSelector([
    (state, { id }) => state.get('picture_in_picture').statusId === id,
    (state) => state.getIn(['meta', 'layout']) !== 'mobile',
  ], (inUse, available) => ImmutableMap({
    inUse: inUse && available,
    available,
  }));
};

const getAlertsBase = state => state.get('alerts');

export const getAlerts = createSelector([getAlertsBase], (base) => {
  let arr = [];

  base.forEach(item => {
    arr.push({
      message: item.get('message'),
      message_values: item.get('message_values'),
      title: item.get('title'),
      key: item.get('key'),
      dismissAfter: 5000,
      barStyle: {
        zIndex: 200,
      },
    });
  });

  return arr;
});

export const makeGetNotification = () => createSelector([
  (_, base)             => base,
  (state, _, accountId) => state.getIn(['accounts', accountId]),
], (base, account) => base.set('account', account));

export const makeGetReport = () => createSelector([
  (_, base) => base,
  (state, _, targetAccountId) => state.getIn(['accounts', targetAccountId]),
], (base, targetAccount) => base.set('target_account', targetAccount));

export const getAccountGallery = createSelector([
  (state, id) => state.getIn(['timelines', `account:${id}:media`, 'items'], ImmutableList()),
  state       => state.get('statuses'),
  (state, id) => state.getIn(['accounts', id]),
], (statusIds, statuses, account) => {
  let medias = ImmutableList();

  statusIds.forEach(statusId => {
    const status = statuses.get(statusId);
    medias = medias.concat(status.get('media_attachments').map(media => media.set('status', status).set('account', account)));
  });

  return medias;
});

export const getAccountHidden = createSelector([
  (state, id) => state.getIn(['accounts', id, 'hidden']),
  (state, id) => state.getIn(['relationships', id, 'following']) || state.getIn(['relationships', id, 'requested']),
  (state, id) => id === me,
], (hidden, followingOrRequested, isSelf) => {
  return hidden && !(isSelf || followingOrRequested);
});
<commit_msg>Remove dead code in WebUI filtering code (#18745)<commit_after>import { createSelector } from 'reselect';
import { List as ImmutableList, Map as ImmutableMap } from 'immutable';
import { me } from '../initial_state';

const getAccountBase         = (state, id) => state.getIn(['accounts', id], null);
const getAccountCounters     = (state, id) => state.getIn(['accounts_counters', id], null);
const getAccountRelationship = (state, id) => state.getIn(['relationships', id], null);
const getAccountMoved        = (state, id) => state.getIn(['accounts', state.getIn(['accounts', id, 'moved'])]);

export const makeGetAccount = () => {
  return createSelector([getAccountBase, getAccountCounters, getAccountRelationship, getAccountMoved], (base, counters, relationship, moved) => {
    if (base === null) {
      return null;
    }

    return base.merge(counters).withMutations(map => {
      map.set('relationship', relationship);
      map.set('moved', moved);
    });
  });
};

const toServerSideType = columnType => {
  switch (columnType) {
  case 'home':
  case 'notifications':
  case 'public':
  case 'thread':
  case 'account':
    return columnType;
  default:
    if (columnType.indexOf('list:') > -1) {
      return 'home';
    } else {
      return 'public'; // community, account, hashtag
    }
  }
};

const getFilters = (state, { contextType }) => {
  if (!contextType) return null;

  const serverSideType = toServerSideType(contextType);
  const now = new Date();

  return state.get('filters').filter((filter) => filter.get('context').includes(serverSideType) && (filter.get('expires_at') === null || filter.get('expires_at') > now));
};

export const makeGetStatus = () => {
  return createSelector(
    [
      (state, { id }) => state.getIn(['statuses', id]),
      (state, { id }) => state.getIn(['statuses', state.getIn(['statuses', id, 'reblog'])]),
      (state, { id }) => state.getIn(['accounts', state.getIn(['statuses', id, 'account'])]),
      (state, { id }) => state.getIn(['accounts', state.getIn(['statuses', state.getIn(['statuses', id, 'reblog']), 'account'])]),
      getFilters,
    ],

    (statusBase, statusReblog, accountBase, accountReblog, filters) => {
      if (!statusBase) {
        return null;
      }

      if (statusReblog) {
        statusReblog = statusReblog.set('account', accountReblog);
      } else {
        statusReblog = null;
      }

      let filtered = false;
      if ((accountReblog || accountBase).get('id') !== me && filters) {
        let filterResults = statusReblog?.get('filtered') || statusBase.get('filtered') || ImmutableList();
        if (filterResults.some((result) => filters.getIn([result.get('filter'), 'filter_action']) === 'hide')) {
          return null;
        }
        if (!filterResults.isEmpty()) {
          filtered = filterResults.map(result => filters.getIn([result.get('filter'), 'title']));
        }
      }

      return statusBase.withMutations(map => {
        map.set('reblog', statusReblog);
        map.set('account', accountBase);
        map.set('matched_filters', filtered);
      });
    },
  );
};

export const makeGetPictureInPicture = () => {
  return createSelector([
    (state, { id }) => state.get('picture_in_picture').statusId === id,
    (state) => state.getIn(['meta', 'layout']) !== 'mobile',
  ], (inUse, available) => ImmutableMap({
    inUse: inUse && available,
    available,
  }));
};

const getAlertsBase = state => state.get('alerts');

export const getAlerts = createSelector([getAlertsBase], (base) => {
  let arr = [];

  base.forEach(item => {
    arr.push({
      message: item.get('message'),
      message_values: item.get('message_values'),
      title: item.get('title'),
      key: item.get('key'),
      dismissAfter: 5000,
      barStyle: {
        zIndex: 200,
      },
    });
  });

  return arr;
});

export const makeGetNotification = () => createSelector([
  (_, base)             => base,
  (state, _, accountId) => state.getIn(['accounts', accountId]),
], (base, account) => base.set('account', account));

export const makeGetReport = () => createSelector([
  (_, base) => base,
  (state, _, targetAccountId) => state.getIn(['accounts', targetAccountId]),
], (base, targetAccount) => base.set('target_account', targetAccount));

export const getAccountGallery = createSelector([
  (state, id) => state.getIn(['timelines', `account:${id}:media`, 'items'], ImmutableList()),
  state       => state.get('statuses'),
  (state, id) => state.getIn(['accounts', id]),
], (statusIds, statuses, account) => {
  let medias = ImmutableList();

  statusIds.forEach(statusId => {
    const status = statuses.get(statusId);
    medias = medias.concat(status.get('media_attachments').map(media => media.set('status', status).set('account', account)));
  });

  return medias;
});

export const getAccountHidden = createSelector([
  (state, id) => state.getIn(['accounts', id, 'hidden']),
  (state, id) => state.getIn(['relationships', id, 'following']) || state.getIn(['relationships', id, 'requested']),
  (state, id) => id === me,
], (hidden, followingOrRequested, isSelf) => {
  return hidden && !(isSelf || followingOrRequested);
});
<|endoftext|>


<commit_before>const jwt = require('jsonwebtoken')
const userModel = require('../../models/users')
const { buildResponse } = require('../../utils/responseService')
const validator = require('./loginValidation')

module.exports = (req, res) => {
    const {error, value} = validator.validate(req.body)
    if (error) return buildResponse(res, 400, { message: 'bad request', error: error.details[0].message})

    userModel.login(value.username, value.password)
      .then(token => buildResponse(res, 200, { message: 'success', token }))
      .catch(error => {
        if (error && error.status === 401) return buildResponse(res, 401, { message: 'invalid login details' })
        buildResponse(res, 500, { message: 'Internal server error'})
      })
}
<commit_msg>Implement passing code for the headers<commit_after>const jwt = require('jsonwebtoken')
const userModel = require('../../models/users')
const { buildResponse } = require('../../utils/responseService')
const validator = require('./loginValidation')

module.exports = (req, res) => {
    // extra security layer. Client should not cache the request
    // only for the /login route
    res.header('Cache-Control', 'no-store')
      .header('Pragma', 'no-store')

    const {error, value} = validator.validate(req.body)
    if (error) return buildResponse(res, 400, { message: 'bad request', error: error.details[0].message})

    userModel.login(value.username, value.password)
      .then(token => buildResponse(res, 200, { message: 'success', token }))
      .catch(error => {
        if (error && error.status === 401) return buildResponse(res, 401, { message: 'invalid login details' })
        buildResponse(res, 500, { message: 'Internal server error'})
      })
}
<|endoftext|>


<commit_before>iD.ui.Background = function(context) {
    var key = 'b',
        opacities = [1, 0.75, 0.5, 0.25],
        directions = [
            ['left', [1, 0]],
            ['top', [0, -1]],
            ['right', [-1, 0]],
            ['bottom', [0, 1]]],
        opacityDefault = (context.storage('background-opacity') !== null) ?
            (+context.storage('background-opacity')) : 0.5;

    // Can be 0 from <1.3.0 use or due to issue #1923.
    if (opacityDefault === 0) opacityDefault = 0.5;

    function background(selection) {

        function setOpacity(d) {
            var bg = context.container().selectAll('.background-layer')
                .transition()
                .style('opacity', d)
                .attr('data-opacity', d);

            if (!iD.detect().opera) {
                iD.util.setTransform(bg, 0, 0);
            }

            opacityList.selectAll('li')
                .classed('active', function(_) { return _ === d; });

            context.storage('background-opacity', d);
        }

        function selectLayer() {
            function active(d) {
                return context.background().showsLayer(d);
            }

            content.selectAll('.layer, .custom_layer')
                .classed('active', active)
                .selectAll('input')
                .property('checked', active);
        }

        function clickSetSource(d) {
            d3.event.preventDefault();
            context.background().baseLayerSource(d);
            selectLayer();
        }

        function clickCustom() {
            d3.event.preventDefault();
            var template = window.prompt(t('background.custom_prompt'));
            if (!template || template.indexOf('google.com') !== -1 ||
               template.indexOf('googleapis.com') !== -1 ||
               template.indexOf('google.ru') !== -1) {
                selectLayer();
                return;
            }
            context.background().baseLayerSource(iD.BackgroundSource.Custom(template));
            selectLayer();
        }

        function clickSetOverlay(d) {
            d3.event.preventDefault();
            context.background().toggleOverlayLayer(d);
            selectLayer();
        }

        function clickGpx() {
            context.background().toggleGpxLayer();
            update();
        }

        function drawList(layerList, type, change, filter) {
            var sources = context.background()
                .sources(context.map().extent())
                .filter(filter);

            var layerLinks = layerList.selectAll('li.layer')
                .data(sources, function(d) { return d.name(); });

            var enter = layerLinks.enter()
                .insert('li', '.custom_layer')
                .attr('class', 'layer');

            // only set tooltips for layers with tooltips
            enter.filter(function(d) { return d.description; })
                .call(bootstrap.tooltip()
                    .title(function(d) { return d.description; })
                    .placement('top'));

            var label = enter.append('label');

            label.append('input')
                .attr('type', type)
                .attr('name', 'layers')
                .on('change', change);

            label.append('span')
                .text(function(d) { return d.name(); });

            layerLinks.exit()
                .remove();

            layerList.style('display', layerList.selectAll('li.layer').data().length > 0 ? 'block' : 'none');
        }

        function update() {
            backgroundList.call(drawList, 'radio', clickSetSource, function(d) { return !d.overlay; });
            overlayList.call(drawList, 'checkbox', clickSetOverlay, function(d) { return d.overlay; });

            var hasGpx = context.background().hasGpxLayer(),
                showsGpx = context.background().showsGpxLayer();

            gpxLayerItem
                .classed('active', showsGpx)
                .selectAll('input')
                .property('disabled', !hasGpx)
                .property('checked', showsGpx);

            selectLayer();
        }

        function clickNudge(d) {

            var timeout = window.setTimeout(function() {
                    interval = window.setInterval(nudge, 100);
                }, 500),
                interval;

            d3.select(this).on('mouseup', function() {
                window.clearInterval(interval);
                window.clearTimeout(timeout);
                nudge();
            });

            function nudge() {
                var offset = context.background()
                    .nudge(d[1], context.map().zoom())
                    .offset();
                resetButton.classed('disabled', offset[0] === 0 && offset[1] === 0);
            }
        }

        var content = selection.append('div')
                .attr('class', 'fillL map-overlay col3 content hide'),
            tooltip = bootstrap.tooltip()
                .placement('left')
                .html(true)
                .title(iD.ui.tooltipHtml(t('background.description'), key));

        function hide() { setVisible(false); }

        function toggle() {
            if (d3.event) d3.event.preventDefault();
            tooltip.hide(button);
            setVisible(!button.classed('active'));
        }

        function setVisible(show) {
            if (show !== shown) {
                button.classed('active', show);
                shown = show;

                if (show) {
                    selection.on('mousedown.background-inside', function() {
                        return d3.event.stopPropagation();
                    });
                    content.style('display', 'block')
                        .style('right', '-300px')
                        .transition()
                        .duration(200)
                        .style('right', '0px');
                } else {
                    content.style('display', 'block')
                        .style('right', '0px')
                        .transition()
                        .duration(200)
                        .style('right', '-300px')
                        .each('end', function() {
                            d3.select(this).style('display', 'none');
                        });
                    selection.on('mousedown.background-inside', null);
                }
            }
        }

        var button = selection.append('button')
                .attr('tabindex', -1)
                .on('click', toggle)
                .call(tooltip),
            opa = content
                .append('div')
                .attr('class', 'opacity-options-wrapper'),
            shown = false;

        button.append('span')
            .attr('class', 'icon layers light');

        opa.append('h4')
            .text(t('background.title'));

        var opacityList = opa.append('ul')
            .attr('class', 'opacity-options');

        opacityList.selectAll('div.opacity')
            .data(opacities)
            .enter()
            .append('li')
            .attr('data-original-title', function(d) {
                return t('background.percent_brightness', { opacity: (d * 100) });
            })
            .on('click.set-opacity', setOpacity)
            .html('

')
            .call(bootstrap.tooltip()
                .placement('left'))
            .append('div')
            .attr('class', 'opacity')
            .style('opacity', String);

        var backgroundList = content.append('ul')
            .attr('class', 'layer-list');

        var custom = backgroundList.append('li')
            .attr('class', 'custom_layer')
            .datum(iD.BackgroundSource.Custom());

        var label = custom.append('label');

        label.append('input')
            .attr('type', 'radio')
            .attr('name', 'layers')
            .on('change', clickCustom);

        label.append('span')
            .text(t('background.custom'));

        var overlayList = content.append('ul')
            .attr('class', 'layer-list');

        var gpxLayerItem = content.append('ul')
            .style('display', iD.detect().filedrop ? 'block' : 'none')
            .attr('class', 'layer-list')
            .append('li')
            .classed('layer-toggle-gpx', true);

        gpxLayerItem.append('button')
            .attr('class', 'layer-extent')
            .call(bootstrap.tooltip()
                .title(t('gpx.zoom'))
                .placement('left'))
            .on('click', function() {
                d3.event.preventDefault();
                d3.event.stopPropagation();
                context.background().zoomToGpxLayer();
            })
            .append('span')
            .attr('class', 'icon geolocate');

        gpxLayerItem.append('button')
            .attr('class', 'layer-browse')
            .call(bootstrap.tooltip()
                .title(t('gpx.browse'))
                .placement('left'))
            .on('click', function() {
                d3.select(document.createElement('input'))
                    .attr('type', 'file')
                    .on('change', function() {
                        context.background().gpxLayerFiles(d3.event.target.files);
                    })
                    .node().click();
            })
            .append('span')
            .attr('class', 'icon geocode');

        label = gpxLayerItem.append('label')
            .call(bootstrap.tooltip()
                .title(t('gpx.drag_drop'))
                .placement('top'));

        label.append('input')
            .attr('type', 'checkbox')
            .property('disabled', true)
            .on('change', clickGpx);

        label.append('span')
            .text(t('gpx.local_layer'));

        var adjustments = content.append('div')
            .attr('class', 'adjustments');

        adjustments.append('a')
            .text(t('background.fix_misalignment'))
            .attr('href', '#')
            .classed('hide-toggle', true)
            .classed('expanded', false)
            .on('click', function() {
                var exp = d3.select(this).classed('expanded');
                nudgeContainer.style('display', exp ? 'none' : 'block');
                d3.select(this).classed('expanded', !exp);
                d3.event.preventDefault();
            });

        var nudgeContainer = adjustments.append('div')
            .attr('class', 'nudge-container cf')
            .style('display', 'none');

        nudgeContainer.selectAll('button')
            .data(directions).enter()
            .append('button')
            .attr('class', function(d) { return d[0] + ' nudge'; })
            .on('mousedown', clickNudge);

        var resetButton = nudgeContainer.append('button')
            .attr('class', 'reset disabled')
            .on('click', function () {
                context.background().offset([0, 0]);
                resetButton.classed('disabled', true);
            });

        resetButton.append('div')
            .attr('class', 'icon undo');

        context.map()
            .on('move.background-update', _.debounce(update, 1000));
        update();
        setOpacity(opacityDefault);

        var keybinding = d3.keybinding('background');
        keybinding.on(key, toggle);

        d3.select(document)
            .call(keybinding);

        context.surface().on('mousedown.background-outside', hide);
        context.container().on('mousedown.background-outside', hide);
    }

    return background;
};
<commit_msg>Correctly update UI after choosing GPX file (#2144)<commit_after>iD.ui.Background = function(context) {
    var key = 'b',
        opacities = [1, 0.75, 0.5, 0.25],
        directions = [
            ['left', [1, 0]],
            ['top', [0, -1]],
            ['right', [-1, 0]],
            ['bottom', [0, 1]]],
        opacityDefault = (context.storage('background-opacity') !== null) ?
            (+context.storage('background-opacity')) : 0.5;

    // Can be 0 from <1.3.0 use or due to issue #1923.
    if (opacityDefault === 0) opacityDefault = 0.5;

    function background(selection) {

        function setOpacity(d) {
            var bg = context.container().selectAll('.background-layer')
                .transition()
                .style('opacity', d)
                .attr('data-opacity', d);

            if (!iD.detect().opera) {
                iD.util.setTransform(bg, 0, 0);
            }

            opacityList.selectAll('li')
                .classed('active', function(_) { return _ === d; });

            context.storage('background-opacity', d);
        }

        function selectLayer() {
            function active(d) {
                return context.background().showsLayer(d);
            }

            content.selectAll('.layer, .custom_layer')
                .classed('active', active)
                .selectAll('input')
                .property('checked', active);
        }

        function clickSetSource(d) {
            d3.event.preventDefault();
            context.background().baseLayerSource(d);
            selectLayer();
        }

        function clickCustom() {
            d3.event.preventDefault();
            var template = window.prompt(t('background.custom_prompt'));
            if (!template || template.indexOf('google.com') !== -1 ||
               template.indexOf('googleapis.com') !== -1 ||
               template.indexOf('google.ru') !== -1) {
                selectLayer();
                return;
            }
            context.background().baseLayerSource(iD.BackgroundSource.Custom(template));
            selectLayer();
        }

        function clickSetOverlay(d) {
            d3.event.preventDefault();
            context.background().toggleOverlayLayer(d);
            selectLayer();
        }

        function clickGpx() {
            context.background().toggleGpxLayer();
            update();
        }

        function drawList(layerList, type, change, filter) {
            var sources = context.background()
                .sources(context.map().extent())
                .filter(filter);

            var layerLinks = layerList.selectAll('li.layer')
                .data(sources, function(d) { return d.name(); });

            var enter = layerLinks.enter()
                .insert('li', '.custom_layer')
                .attr('class', 'layer');

            // only set tooltips for layers with tooltips
            enter.filter(function(d) { return d.description; })
                .call(bootstrap.tooltip()
                    .title(function(d) { return d.description; })
                    .placement('top'));

            var label = enter.append('label');

            label.append('input')
                .attr('type', type)
                .attr('name', 'layers')
                .on('change', change);

            label.append('span')
                .text(function(d) { return d.name(); });

            layerLinks.exit()
                .remove();

            layerList.style('display', layerList.selectAll('li.layer').data().length > 0 ? 'block' : 'none');
        }

        function update() {
            backgroundList.call(drawList, 'radio', clickSetSource, function(d) { return !d.overlay; });
            overlayList.call(drawList, 'checkbox', clickSetOverlay, function(d) { return d.overlay; });

            var hasGpx = context.background().hasGpxLayer(),
                showsGpx = context.background().showsGpxLayer();

            gpxLayerItem
                .classed('active', showsGpx)
                .selectAll('input')
                .property('disabled', !hasGpx)
                .property('checked', showsGpx);

            selectLayer();
        }

        function clickNudge(d) {

            var timeout = window.setTimeout(function() {
                    interval = window.setInterval(nudge, 100);
                }, 500),
                interval;

            d3.select(this).on('mouseup', function() {
                window.clearInterval(interval);
                window.clearTimeout(timeout);
                nudge();
            });

            function nudge() {
                var offset = context.background()
                    .nudge(d[1], context.map().zoom())
                    .offset();
                resetButton.classed('disabled', offset[0] === 0 && offset[1] === 0);
            }
        }

        var content = selection.append('div')
                .attr('class', 'fillL map-overlay col3 content hide'),
            tooltip = bootstrap.tooltip()
                .placement('left')
                .html(true)
                .title(iD.ui.tooltipHtml(t('background.description'), key));

        function hide() { setVisible(false); }

        function toggle() {
            if (d3.event) d3.event.preventDefault();
            tooltip.hide(button);
            setVisible(!button.classed('active'));
        }

        function setVisible(show) {
            if (show !== shown) {
                button.classed('active', show);
                shown = show;

                if (show) {
                    selection.on('mousedown.background-inside', function() {
                        return d3.event.stopPropagation();
                    });
                    content.style('display', 'block')
                        .style('right', '-300px')
                        .transition()
                        .duration(200)
                        .style('right', '0px');
                } else {
                    content.style('display', 'block')
                        .style('right', '0px')
                        .transition()
                        .duration(200)
                        .style('right', '-300px')
                        .each('end', function() {
                            d3.select(this).style('display', 'none');
                        });
                    selection.on('mousedown.background-inside', null);
                }
            }
        }

        var button = selection.append('button')
                .attr('tabindex', -1)
                .on('click', toggle)
                .call(tooltip),
            opa = content
                .append('div')
                .attr('class', 'opacity-options-wrapper'),
            shown = false;

        button.append('span')
            .attr('class', 'icon layers light');

        opa.append('h4')
            .text(t('background.title'));

        var opacityList = opa.append('ul')
            .attr('class', 'opacity-options');

        opacityList.selectAll('div.opacity')
            .data(opacities)
            .enter()
            .append('li')
            .attr('data-original-title', function(d) {
                return t('background.percent_brightness', { opacity: (d * 100) });
            })
            .on('click.set-opacity', setOpacity)
            .html('

')
            .call(bootstrap.tooltip()
                .placement('left'))
            .append('div')
            .attr('class', 'opacity')
            .style('opacity', String);

        var backgroundList = content.append('ul')
            .attr('class', 'layer-list');

        var custom = backgroundList.append('li')
            .attr('class', 'custom_layer')
            .datum(iD.BackgroundSource.Custom());

        var label = custom.append('label');

        label.append('input')
            .attr('type', 'radio')
            .attr('name', 'layers')
            .on('change', clickCustom);

        label.append('span')
            .text(t('background.custom'));

        var overlayList = content.append('ul')
            .attr('class', 'layer-list');

        var gpxLayerItem = content.append('ul')
            .style('display', iD.detect().filedrop ? 'block' : 'none')
            .attr('class', 'layer-list')
            .append('li')
            .classed('layer-toggle-gpx', true);

        gpxLayerItem.append('button')
            .attr('class', 'layer-extent')
            .call(bootstrap.tooltip()
                .title(t('gpx.zoom'))
                .placement('left'))
            .on('click', function() {
                d3.event.preventDefault();
                d3.event.stopPropagation();
                context.background().zoomToGpxLayer();
            })
            .append('span')
            .attr('class', 'icon geolocate');

        gpxLayerItem.append('button')
            .attr('class', 'layer-browse')
            .call(bootstrap.tooltip()
                .title(t('gpx.browse'))
                .placement('left'))
            .on('click', function() {
                d3.select(document.createElement('input'))
                    .attr('type', 'file')
                    .on('change', function() {
                        context.background().gpxLayerFiles(d3.event.target.files);
                    })
                    .node().click();
            })
            .append('span')
            .attr('class', 'icon geocode');

        label = gpxLayerItem.append('label')
            .call(bootstrap.tooltip()
                .title(t('gpx.drag_drop'))
                .placement('top'));

        label.append('input')
            .attr('type', 'checkbox')
            .property('disabled', true)
            .on('change', clickGpx);

        label.append('span')
            .text(t('gpx.local_layer'));

        var adjustments = content.append('div')
            .attr('class', 'adjustments');

        adjustments.append('a')
            .text(t('background.fix_misalignment'))
            .attr('href', '#')
            .classed('hide-toggle', true)
            .classed('expanded', false)
            .on('click', function() {
                var exp = d3.select(this).classed('expanded');
                nudgeContainer.style('display', exp ? 'none' : 'block');
                d3.select(this).classed('expanded', !exp);
                d3.event.preventDefault();
            });

        var nudgeContainer = adjustments.append('div')
            .attr('class', 'nudge-container cf')
            .style('display', 'none');

        nudgeContainer.selectAll('button')
            .data(directions).enter()
            .append('button')
            .attr('class', function(d) { return d[0] + ' nudge'; })
            .on('mousedown', clickNudge);

        var resetButton = nudgeContainer.append('button')
            .attr('class', 'reset disabled')
            .on('click', function () {
                context.background().offset([0, 0]);
                resetButton.classed('disabled', true);
            });

        resetButton.append('div')
            .attr('class', 'icon undo');

        context.map()
            .on('move.background-update', _.debounce(update, 1000));

        context.background()
            .on('change.background-update', update);

        update();
        setOpacity(opacityDefault);

        var keybinding = d3.keybinding('background');
        keybinding.on(key, toggle);

        d3.select(document)
            .call(keybinding);

        context.surface().on('mousedown.background-outside', hide);
        context.container().on('mousedown.background-outside', hide);
    }

    return background;
};
<|endoftext|>


<commit_before>'use strict';

const EventEmitter = require('events');
const inherits = require('util').inherits;

const Garage = function (config) {
    EventEmitter.call(this);

    var self = this,
        isGarageOpen = undefined,
        isOperating = false,
        operationQueue = 0,
        isPositioning = false,
        positioned = undefined,
        positionHandle = undefined,
        isInitial = true,
        startHandle = undefined,
        garageOpened = undefined,
        reminded = undefined,
        //config settings
        statusPin = config.statusPin,
        statusOpenMatch = config.statusOpenMatch,
        operatePin = config.operatePin,
        operateIdleValue = config.operateIdleValue,
        statusInterval = config.statusInterval || 250,
        reminderInterval = config.reminderInterval || 60000,
        openCloseDuration = config.openCloseDuration,
        operateTimeout = config.operateTimeout || 2000,
        operatePulseDuration = config.operatePulseDuration || 200,
        operatePulseSleep = config.operatePulseSleep || 100;

    if (operateValue === undefined) {
        throw 'Garage operatevalue must be defined';
    }

    function isOpen() {
        return isGarageOpen;
    }

    function opened() {
        return garageOpened;
    }

    function open() {
    }

    function close() {
        if (isPositioning || !isGarageOpen) {
            return false;
        }
        isPositioning = true;
        //door is     : opened,  opening, closing, halted
        //door will be: closing, halted,  halted,  opening/closing
        operate();

        positioned = new Date();
        var isOpening = false,
            isClosing = true;
        positionHandle = setInterval(() => {
            //done yet?
            if (!isGarageOpen || !isPositioning) {
                isPositioning = false;
                clearInterval(positionHandle);
                return;
            }

            if (isClosing) {
                if (new Date() - positioned > openCloseDuration + operateTimeout) {
                    //halted or opened
                    positioned = new Date();
                    operate();
                    self.emit('action', 'Still trying to close the door');
                }
            }
        }, statusInterval);
        return true;
    }

    function operate() {
        operationQueue++;
        if (isOperating) {
            return false;
        }
        isOperating = true;

        operatePin.write(!operateIdleValue);
        setTimeout(() => {
            operatePin.write(operateIdleValue);
            setTimeout(() => {
                if (--operationQueue > 0) {
                    operationQueue--;
                    operate();
                }
                else {
                    isOperating = false;
                }
            }, operatePulseSleep);
        }, operatePulseDuration);
        return true;
    }

    function update(value) {
        //console.log('garage status: ' + value);
        isGarageOpen = value == statusOpenMatch;
        if (isGarageOpen) {
            if (!garageOpened) {
                //opened just now
                garageOpened = reminded = new Date();
                self.emit('open', isInitial);
            }
            else if (new Date() - reminded > reminderInterval) {
                //already open
                self.emit('openReminder', garageOpened);
                reminded = new Date();
            }
        }
        else if (garageOpened) {
            //closed just now
            garageOpened = undefined;
            self.emit('close');
        }
    }

    function start() {
        //reset and perform initial update
        isInitial = true;
        garageOpened = reminded = undefined;
        update(statusPin.read());
        isInitial = false;

        //poll loop
        var isBusy = false;
        startHandle = setInterval(function () {
            if (!isBusy) {
                isBusy = true;
                update(statusPin.read());
                isBusy = false;
            }
        }, statusInterval);
    }

    function stop() {
        clearInterval(startHandle);
    }

    function reset() {
        isOperating = false;
        isPositioning = false;
        operationQueue = 0;
    }

    //constructor
    (function () {
        start();
    })();

    return {
        on: self.on,
        open: open,
        close: close,
        isOpen: isOpen,
        opened: opened,
        stop: stop,
        start: start,
        operate: operate,
        reset: reset
    };
};

inherits(Garage, EventEmitter);

module.exports = Garage;<commit_msg>fixed typo<commit_after>'use strict';

const EventEmitter = require('events');
const inherits = require('util').inherits;

const Garage = function (config) {
    EventEmitter.call(this);

    var self = this,
        isGarageOpen = undefined,
        isOperating = false,
        operationQueue = 0,
        isPositioning = false,
        positioned = undefined,
        positionHandle = undefined,
        isInitial = true,
        startHandle = undefined,
        garageOpened = undefined,
        reminded = undefined,
        //config settings
        statusPin = config.statusPin,
        statusOpenMatch = config.statusOpenMatch,
        operatePin = config.operatePin,
        operateIdleValue = config.operateIdleValue,
        statusInterval = config.statusInterval || 250,
        reminderInterval = config.reminderInterval || 60000,
        openCloseDuration = config.openCloseDuration,
        operateTimeout = config.operateTimeout || 2000,
        operatePulseDuration = config.operatePulseDuration || 200,
        operatePulseSleep = config.operatePulseSleep || 100;

    if (operateIdleValue === undefined) {
        throw 'Garage operateIdleValue must be defined';
    }

    function isOpen() {
        return isGarageOpen;
    }

    function opened() {
        return garageOpened;
    }

    function open() {
    }

    function close() {
        if (isPositioning || !isGarageOpen) {
            return false;
        }
        isPositioning = true;
        //door is     : opened,  opening, closing, halted
        //door will be: closing, halted,  halted,  opening/closing
        operate();

        positioned = new Date();
        var isOpening = false,
            isClosing = true;
        positionHandle = setInterval(() => {
            //done yet?
            if (!isGarageOpen || !isPositioning) {
                isPositioning = false;
                clearInterval(positionHandle);
                return;
            }

            if (isClosing) {
                if (new Date() - positioned > openCloseDuration + operateTimeout) {
                    //halted or opened
                    positioned = new Date();
                    operate();
                    self.emit('action', 'Still trying to close the door');
                }
            }
        }, statusInterval);
        return true;
    }

    function operate() {
        operationQueue++;
        if (isOperating) {
            return false;
        }
        isOperating = true;

        operatePin.write(!operateIdleValue);
        setTimeout(() => {
            operatePin.write(operateIdleValue);
            setTimeout(() => {
                if (--operationQueue > 0) {
                    operationQueue--;
                    operate();
                }
                else {
                    isOperating = false;
                }
            }, operatePulseSleep);
        }, operatePulseDuration);
        return true;
    }

    function update(value) {
        //console.log('garage status: ' + value);
        isGarageOpen = value == statusOpenMatch;
        if (isGarageOpen) {
            if (!garageOpened) {
                //opened just now
                garageOpened = reminded = new Date();
                self.emit('open', isInitial);
            }
            else if (new Date() - reminded > reminderInterval) {
                //already open
                self.emit('openReminder', garageOpened);
                reminded = new Date();
            }
        }
        else if (garageOpened) {
            //closed just now
            garageOpened = undefined;
            self.emit('close');
        }
    }

    function start() {
        //reset and perform initial update
        isInitial = true;
        garageOpened = reminded = undefined;
        update(statusPin.read());
        isInitial = false;

        //poll loop
        var isBusy = false;
        startHandle = setInterval(function () {
            if (!isBusy) {
                isBusy = true;
                update(statusPin.read());
                isBusy = false;
            }
        }, statusInterval);
    }

    function stop() {
        clearInterval(startHandle);
    }

    function reset() {
        isOperating = false;
        isPositioning = false;
        operationQueue = 0;
    }

    //constructor
    (function () {
        start();
    })();

    return {
        on: self.on,
        open: open,
        close: close,
        isOpen: isOpen,
        opened: opened,
        stop: stop,
        start: start,
        operate: operate,
        reset: reset
    };
};

inherits(Garage, EventEmitter);

module.exports = Garage;<|endoftext|>


<commit_before>sap.ui.define([
   'sap/ui/core/mvc/Controller',
   'sap/ui/model/json/JSONModel',
   'sap/ui/commons/CheckBox',
   'sap/ui/commons/Menu',
   'sap/ui/commons/MenuItem',
   'sap/ui/core/Item',
   'sap/ui/table/Column',
   'sap/m/Input',
   'sap/m/Button',
   "sap/ui/core/ResizeHandler",
   "sap/ui/layout/VerticalLayout",
   "sap/ui/layout/HorizontalLayout"
], function (Controller, JSONModel, CheckBox, Menu, MenuItem, coreItem, Column,
             mInput, mButton, ResizeHandler, VerticalLayout, HorizontalLayout) {

   "use strict";

   return Controller.extend("rootui5.eve7.controller.EveTable", {

      onInit : function() {
         var data = this.getView().getViewData();
         // console.log("VIEW DATA", data);

         var id = this.getView().getId();
         console.log("eve.GL.onInit id = ", id );

         this._load_scripts = true;
         this._render_html = false;

         this.mgr = data.mgr;
         this.elementid = data.elementid;
         this.kind = data.kind;

         this.bindTableColumns = true;
         var element = this.mgr.GetElement(this.elementid);
         // loop over scene and add dependency
         for (var k=0;k<element.childs.length;++k) {
            var scene = element.childs[k];
            this.mgr.RegisterSceneReceiver(scene.fSceneId, this);
            this.onSceneCreate();
         }
      },

      locateEveTable: function()
      {
         this.eveTable = 0;
         var element = this.mgr.GetElement(this.elementid);
         var sceneInfo = element.childs[0];
         var scene = this.mgr.GetElement(sceneInfo.fSceneId);
         // console.log(">>>table scene", scene);
         if (scene.childs[0]._typename == "ROOT::Experimental::REveTableViewInfo") {
            // presume table view manger is first child of table scene
            this.viewInfo = scene.childs[0];
         }

         // console.log("table viewinfo", this.viewInfo  );
         this.collection = this.mgr.GetElement(this.viewInfo.fDisplayedCollection);
         // loop over products
         for (var i = 1; i < scene.childs.length; ++i) {
            var product = scene.childs[i];
            if (product.childs && product.childs.length && product.childs[0].fCollectionId == this.viewInfo.fDisplayedCollection) {
               // console.log("table found  ",product.childs[0] );
               this.eveTable =  product.childs[0];
               break;
            }
         }

      },

      buildTableBody: function()
      {
         var oTable = this.getView().byId("table");

         // row definition
         var rowData = this.eveTable.body;

         // parse to float -- AMT in future data should be streamed as floats
         for (var r=0; r < rowData.length; r++) {
            var xr = rowData[r];
            for (var xri = 0; xri < xr.length; xri++) {
               var nv = parseFloat(xr[i]);
               if (nv != NaN) {
                  rowData[r][ri] = nv;
               }
            }
         }

         for (var i = 0; i < this.collection.childs.length; i++)
         {
            rowData[i].Name =  this.collection.childs[i].fName;
            rowData[i].Filtered =  this.collection.childs[i].fFiltered === true ? "--" : "*";
         }

         if (this.bindTableColumns) {
            // column definition
            var columnData = [];

            columnData.push({columnName:"Name"});
            columnData.push({columnName:"Filtered"});

            var eveColumns = this.eveTable.childs;
            for (var i = 0; i < eveColumns.length; i++)
            {
               var cname = eveColumns[i].fName;
               columnData.push({columnName : cname});
            }

            // table model
            var oModel = new JSONModel();
            oModel.setData({
               rows: rowData,
               columns: columnData
            });
            oTable.setModel(oModel);

            oTable.bindAggregation("columns", "/columns", function(sId, oContext) {
               return new sap.ui.table.Column(sId, {
	          label: "{columnName}",
	          sortProperty: "{columnName}",
	          template: new sap.m.Text().bindText(oContext.getProperty("columnName")),
                  showFilterMenuEntry: true,
                  width: "100px"
               });
            });
            oTable.bindRows("/rows");
            this.bindTableColumns = false;
         }
         else
         {
            var model = oTable.getModel();
            var data = model.getData();
            model.setData({"rows":rowData, "columns":data.columns});
         }
      },

      buildTableHeader: function()
      {
         var oModel = new JSONModel();
         var collection = this.mgr.GetElement(this.eveTable.fCollectionId);
         var clist = this.mgr.GetElement(collection.fMotherId);
         // console.log("collection list ", clist);

	 var mData = {
	    "itemx": [
	    ]};

         for (var i = 0; i < clist.childs.length; i++)
         {
            mData.itemx.push({"text" :clist.childs[i].fName, "key": clist.childs[i].fName, "elementId":clist.childs[i].fElementId });
         }
         oModel.setData(mData);
         this.getView().setModel(oModel, "collections");

         var combo = this.getView().byId("ccombo");
         combo.setSelectedKey(collection.fName);
         combo.data("controller", this);
      },

      onLoadScripts: function() {
         this._load_scripts = true;
         this.checkScenes();
      },

      // function called from GuiPanelController
      onExit : function() {
         if (this.mgr) this.mgr.Unregister(this);
      },

      onSceneCreate: function(element, id) {
         console.log("EveTable onSceneChanged", id);
         this.locateEveTable();
         this.buildTableHeader();
         this.buildTableBody(true);
      },

      UpdateMgr : function(mgr) {
         var elem = mgr.map[this.elementid];
         var scene = mgr.map[ elem.fMotherId];
         this.mgr = mgr;
      },

      onAfterRendering: function() {
         this._render_html = true;

         // this.getView().$().css("overflow", "hidden");

         // this.getView().$().parent().css("overflow", "hidden");

         // only when rendering completed - register for modify events
         var element = this.mgr.GetElement(this.elementid);

         this.checkScenes();
      },

      checkScenes: function() {
      },

      toggleTableEdit: function() {

         var header = this.getView().byId("header");
         if (!this.editor) {
            this.editor = new VerticalLayout("tableEdit", {"width":"100%"});

            header.addContent(this.editor);

            // expression row
            {
               var collection = this.mgr.GetElement(this.eveTable.fCollectionId);
               var oModel = new JSONModel();
               oModel.setData(collection.publicFunction);
               // oModel.setData(aData);
               this.getView().setModel(oModel);

               var exprIn = new mInput("expression", {
                                         width:"98%",
                                         type : sap.m.InputType.Text,
                                         placeholder: "Expression",
                                         showSuggestion: true
                                       });
               exprIn.setModel(oModel);
               exprIn.bindAggregation("suggestionItems", "/", new coreItem({text: "{name}"}));
               exprIn.setFilterFunction(function(sTerm, oItem) {
                  // A case-insensitive 'string contains' style filter
                  // console.log("filter sterm", sTerm);
                  var base = sTerm;
                  var n = base.lastIndexOf("i.");
                  // console.log("last index ", n);
                  if (n>=0) n+=2;
                  var txt = base.substring(n,this.getFocusInfo().cursorPos );
                  // console.log("suggest filter ", txt);
                  // console.log("focus 1", this.getFocusInfo());

                  return oItem.getText().match(new RegExp(txt, "i"));
               });
               this.editor.addContent(exprIn);
            }

            // title & prec
            {
               var hl = new HorizontalLayout();
               var titleIn = new mInput("title", {placeholder:"Title", tooltip:"title"});
               titleIn.setWidth("98%");
               hl.addContent(titleIn);
               //this.editor.addContent(titleIn);

               var precIn = new mInput("precision", {placeholder:"Precision", type: sap.m.InputType.Number, constraints: {minimum:"0", maximum:"9"}});
               // precIn.bindProperty("value", "abc>precision");
               precIn.setWidth("100px");

               hl.addContent(precIn);

               this.editor.addContent(hl);

            }

            //  button actions
            {
               var ll = new HorizontalLayout();
               var addBut = new mButton("AddCol", {text:"Add", press: this.addColumn});
               addBut.data("controller", this);
               ll.addContent(addBut);
               this.editor.visible = true;
               this.editor.addContent(ll);
            }
            return;
         }

         if (this.editor.visible) {
            var x = header.getContent().pop();
            header.removeContent(x);
            this.editor.visible = false;
         }
         else {
            header.addContent(this.editor);
            this.editor.visible = true;
         }
      },

      addColumn: function(event) {
         // console.log("add column s", event.getSource(), this);
         // console.log("add column p", this.data("controller"));
         var pthis = this.data("controller");
         var ws = pthis.editor.getContent();

         var expr = ws[0].getProperty("value");
         if (!expr) {
            alert("need a new column expression");
         }
         var hl =  ws[1].getContent();
         var title = hl[0].getProperty("value");
         if (!title) {
            title = expr;
         }

         var mir = "AddNewColumnToCurrentCollection( \"" + expr + "\", \"" + title + "\" )";

         // console.log("table element id ", pthis.eveTable.fElementId);

         var obj = {"mir" : mir, "fElementId" :pthis.viewInfo.fElementId, "class" : pthis.viewInfo._typename};
         // console.log("MIR obj ", obj);
         //pthis.mgr.handle.Send(JSON.stringify(obj));
         pthis.mgr.SendMIR(obj);
      },

      collectionChanged: function(oEvent) {
         // console.log("collectionChanged ", oEvent.getSource());
         var model = oEvent.oSource.getSelectedItem().getBindingContext("collections");
         var path = model.getPath();
         var entry = model.getProperty(path);
         var coll = entry.elementId;
         var mng =  this.viewInfo;

         var mir = "SetDisplayedCollection(" + coll + ")";
         var obj = {"mir" : mir, "fElementId" : mng.fElementId, "class":mng._typename };
         this.mgr.SendMIR(obj);
      },

      sceneElementChange : function(el)
      {
         // console.log("table sceneElementChange", el);
         if (el._typename == "ROOT::Experimental::REveTableViewInfo") {
            this.bindTableColumns = true;
         }
      },

      endChanges : function(oEvent) {
         // console.log("table controller endChanges ",this.eveTable );
         this.locateEveTable();
         this.buildTableBody();
      },

      elementRemoved: function(elId) {
         var el = this.mgr.GetElement(elId);
         // console.log("EveTable element removed ", el);
      }
   });
});
<commit_msg>Implement tabular suggestions for new expression<commit_after>sap.ui.define([
   'sap/ui/core/mvc/Controller',
   'sap/ui/model/json/JSONModel',
   'sap/ui/commons/CheckBox',
   'sap/ui/commons/Menu',
   'sap/ui/commons/MenuItem',
   'sap/ui/core/Item',
   'sap/ui/table/Column',
   'sap/m/Input',
   'sap/m/Button',
   "sap/ui/core/ResizeHandler",
   "sap/ui/layout/VerticalLayout",
   "sap/ui/layout/HorizontalLayout"
], function (Controller, JSONModel, CheckBox, Menu, MenuItem, coreItem, Column,
             mInput, mButton, ResizeHandler, VerticalLayout, HorizontalLayout) {

   "use strict";

   return Controller.extend("rootui5.eve7.controller.EveTable", {

      onInit : function() {
         var data = this.getView().getViewData();
         // console.log("VIEW DATA", data);

         var id = this.getView().getId();
         console.log("eve.GL.onInit id = ", id );

         this._load_scripts = true;
         this._render_html = false;

         this.mgr = data.mgr;
         this.elementid = data.elementid;
         this.kind = data.kind;

         this.bindTableColumns = true;
         var element = this.mgr.GetElement(this.elementid);
         // loop over scene and add dependency
         for (var k=0;k<element.childs.length;++k) {
            var scene = element.childs[k];
            this.mgr.RegisterSceneReceiver(scene.fSceneId, this);
            this.onSceneCreate();
         }
      },

      locateEveTable: function()
      {
         this.eveTable = 0;
         var element = this.mgr.GetElement(this.elementid);
         var sceneInfo = element.childs[0];
         var scene = this.mgr.GetElement(sceneInfo.fSceneId);
         // console.log(">>>table scene", scene);
         if (scene.childs[0]._typename == "ROOT::Experimental::REveTableViewInfo") {
            // presume table view manger is first child of table scene
            this.viewInfo = scene.childs[0];
         }

         // console.log("table viewinfo", this.viewInfo  );
         this.collection = this.mgr.GetElement(this.viewInfo.fDisplayedCollection);
         // loop over products
         for (var i = 1; i < scene.childs.length; ++i) {
            var product = scene.childs[i];
            if (product.childs && product.childs.length && product.childs[0].fCollectionId == this.viewInfo.fDisplayedCollection) {
               // console.log("table found  ",product.childs[0] );
               this.eveTable =  product.childs[0];
               break;
            }
         }

      },

      buildTableBody: function()
      {
         var oTable = this.getView().byId("table");

         // row definition
         var rowData = this.eveTable.body;

         // parse to float -- AMT in future data should be streamed as floats
         for (var r=0; r < rowData.length; r++) {
            var xr = rowData[r];
            for (var xri = 0; xri < xr.length; xri++) {
               var nv = parseFloat(xr[i]);
               if (nv != NaN) {
                  rowData[r][ri] = nv;
               }
            }
         }

         for (var i = 0; i < this.collection.childs.length; i++)
         {
            rowData[i].Name =  this.collection.childs[i].fName;
            rowData[i].Filtered =  this.collection.childs[i].fFiltered === true ? "--" : "*";
         }

         if (this.bindTableColumns) {
            // column definition
            var columnData = [];

            columnData.push({columnName:"Name"});
            columnData.push({columnName:"Filtered"});

            var eveColumns = this.eveTable.childs;
            for (var i = 0; i < eveColumns.length; i++)
            {
               var cname = eveColumns[i].fName;
               columnData.push({columnName : cname});
            }

            // table model
            var oModel = new JSONModel();
            oModel.setData({
               rows: rowData,
               columns: columnData
            });
            oTable.setModel(oModel);

            oTable.bindAggregation("columns", "/columns", function(sId, oContext) {
               return new sap.ui.table.Column(sId, {
	          label: "{columnName}",
	          sortProperty: "{columnName}",
	          template: new sap.m.Text().bindText(oContext.getProperty("columnName")),
                  showFilterMenuEntry: true,
                  width: "100px"
               });
            });
            oTable.bindRows("/rows");
            this.bindTableColumns = false;
         }
         else
         {
            var model = oTable.getModel();
            var data = model.getData();
            model.setData({"rows":rowData, "columns":data.columns});
         }
      },

      buildTableHeader: function()
      {
         var oModel = new JSONModel();
         var collection = this.mgr.GetElement(this.eveTable.fCollectionId);
         var clist = this.mgr.GetElement(collection.fMotherId);
         // console.log("collection list ", clist);

	 var mData = {
	    "itemx": [
	    ]};

         for (var i = 0; i < clist.childs.length; i++)
         {
            mData.itemx.push({"text" :clist.childs[i].fName, "key": clist.childs[i].fName, "elementId":clist.childs[i].fElementId });
         }
         oModel.setData(mData);
         this.getView().setModel(oModel, "collections");

         var combo = this.getView().byId("ccombo");
         combo.setSelectedKey(collection.fName);
         combo.data("controller", this);
      },

      onLoadScripts: function() {
         this._load_scripts = true;
         this.checkScenes();
      },

      // function called from GuiPanelController
      onExit : function() {
         if (this.mgr) this.mgr.Unregister(this);
      },

      onSceneCreate: function(element, id) {
         console.log("EveTable onSceneChanged", id);
         this.locateEveTable();
         this.buildTableHeader();
         this.buildTableBody(true);
      },

      UpdateMgr : function(mgr) {
         var elem = mgr.map[this.elementid];
         var scene = mgr.map[ elem.fMotherId];
         this.mgr = mgr;
      },

      onAfterRendering: function() {
         this._render_html = true;

         // this.getView().$().css("overflow", "hidden");

         // this.getView().$().parent().css("overflow", "hidden");

         // only when rendering completed - register for modify events
         var element = this.mgr.GetElement(this.elementid);

         this.checkScenes();
      },

      checkScenes: function() {
      },

      toggleTableEdit: function() {
         var header = this.getView().byId("header");
         if (!this.editor) {
            this.editor = new VerticalLayout("tableEdit", {"width":"100%"});

            header.addContent(this.editor);

            // expression row
            {
               var collection = this.mgr.GetElement(this.eveTable.fCollectionId);
               var exprIn = new sap.m.Input("inputExp", {
    		  placeholder: "Start expression with \"i.\" to access object",
    		  showValueHelp: true,
    		  showTableSuggestionValueHelp: false,
    		  width: "50%",
    		  maxSuggestionWidth: "500px",
    		  showSuggestion: true,
    		  valueHelpRequest: function (oEvent) {
    		     sap.m.MessageBox.alert("Value help requested");
    		  },
    		  suggestionItemSelected: function(oEvent){
    		     var oItem = oEvent.getParameter("selectedRow");
    		     console.log("sap.m.Input id with suggestion: selected item text is ------ " , oItem.getCells());
                     // fill in title if empty
                     var it = sap.ui.getCore().byId("titleEx");
                     if ((it.getValue() && it.getValue().length) == false) {
                        var v =  oItem.getCells()[0].getText().substring(2);
                        var t = v.split("(");
                        it.setValue(t[0]);
                     }
                     //fill in precision if empty
                     var ip = sap.ui.getCore().byId("precisionEx");
                     if ((ip.getValue() && ip.getValue().length) == false) {
                        var p = oItem.getCells()[1].getText();
                        if (p.startsWith("Int") || p.startsWith("int"))
                           ip.setValue("0");
                        else
                           ip.setValue("3");
                     }
    		  },
    		  suggestionColumns : [
    		     new sap.m.Column({
    			styleClass : "f",
    			hAlign : "Begin",
    			header : new sap.m.Label({
                           text : "Funcname"
    			})
    		     }),
    		     new sap.m.Column({
    			hAlign : "Center",
    			styleClass : "r",
    			popinDisplay : "Inline",
    			header : new sap.m.Label({
    			   text : "Return"
    			}),
    			minScreenWidth : "Tablet",
    			demandPopin : true
    		     }),

    		     new sap.m.Column({
    			hAlign : "End",
    			styleClass : "c",
    			width : "30%",
    			popinDisplay : "Inline",
    			header : new sap.m.Label({
                           text : "Class"
    			}),
    			minScreenWidth : "400px",
    			demandPopin : true
    		     })
    		  ]
    	       }).addStyleClass("inputRight");

               exprIn.setModel(oModel);

    	       var oTableItemTemplate = new sap.m.ColumnListItem({
    		  type : "Active",
    		  vAlign : "Middle",
    		  cells : [
    		     new sap.m.Label({
    			text : "{f}"
    		     }),
                     new sap.m.Label({
    			text: "{r}"
    		     }),
                     new sap.m.Label({
    			text : "{c}"
    		     })
    		  ]
    	       });
    	       var oModel = new sap.ui.model.json.JSONModel();
               var oSuggestionData = collection.fPublicFunctions;
               console.log("suggested data ",oSuggestionData );
    	       oModel.setData(oSuggestionData);
    	       exprIn.setModel(oModel);
    	       exprIn.bindAggregation("suggestionRows", "/", oTableItemTemplate);

               this.editor.addContent(exprIn);
            }

            // title & prec
            {
               var hl = new HorizontalLayout();
               var titleIn = new mInput("titleEx", {placeholder:"Title", tooltip:"column title"});
               titleIn.setWidth("98%");
               hl.addContent(titleIn);

               var precIn = new mInput("precisionEx", {placeholder:"Precision", type: sap.m.InputType.Number, constraints: {minimum:"0", maximum:"9"}});
               precIn.setWidth("100px");
               hl.addContent(precIn);

               this.editor.addContent(hl);
            }

            //  button actions
            {
               var ll = new HorizontalLayout();
               var addBut = new mButton("AddCol", {text:"Add", press: this.addColumn});
               addBut.data("controller", this);
               ll.addContent(addBut);
               this.editor.visible = true;
               this.editor.addContent(ll);
            }
            return;
         }

         if (this.editor.visible) {
            var x = header.getContent().pop();
            header.removeContent(x);
            this.editor.visible = false;
         }
         else {
            header.addContent(this.editor);
            this.editor.visible = true;
         }
      },

      addColumn: function(event) {
         // console.log("add column s", event.getSource(), this);
         // console.log("add column p", this.data("controller"));
         var pthis = this.data("controller");
         var ws = pthis.editor.getContent();

         var expr = ws[0].getProperty("value");
         if (!expr) {
            alert("need a new column expression");
         }
         var hl =  ws[1].getContent();
         var title = hl[0].getProperty("value");
         if (!title) {
            title = expr;
         }

         var mir = "AddNewColumnToCurrentCollection( \"" + expr + "\", \"" + title + "\" )";

         // console.log("table element id ", pthis.eveTable.fElementId);

         var obj = {"mir" : mir, "fElementId" :pthis.viewInfo.fElementId, "class" : pthis.viewInfo._typename};
         // console.log("MIR obj ", obj);
         //pthis.mgr.handle.Send(JSON.stringify(obj));
         pthis.mgr.SendMIR(obj);

         // reset values
         sap.ui.getCore().byId("titleEx").setValue("");
         sap.ui.getCore().byId("precisionEx").setValue("");
      },

      collectionChanged: function(oEvent) {
         // console.log("collectionChanged ", oEvent.getSource());
         var model = oEvent.oSource.getSelectedItem().getBindingContext("collections");
         var path = model.getPath();
         var entry = model.getProperty(path);
         var coll = entry.elementId;
         var mng =  this.viewInfo;

         var mir = "SetDisplayedCollection(" + coll + ")";
         var obj = {"mir" : mir, "fElementId" : mng.fElementId, "class":mng._typename };
         this.mgr.SendMIR(obj);
      },

      sceneElementChange : function(el)
      {
         // console.log("table sceneElementChange", el);
         if (el._typename == "ROOT::Experimental::REveTableViewInfo") {
            this.bindTableColumns = true;
         }
      },

      endChanges : function(oEvent) {
         // console.log("table controller endChanges ",this.eveTable );
         this.locateEveTable();
         this.buildTableBody();
      },

      elementRemoved: function(elId) {
         var el = this.mgr.GetElement(elId);
         // console.log("EveTable element removed ", el);
      }
   });
});
<|endoftext|>


<commit_before>import fs from 'fs';
import glob from 'glob';

export default function({

  // delimiters
  opening = '/***',
  closing = '***/',
  valueOpening = '{',
  valueClosing = '}',

} = {}) {

  // Helpers
  const snippetStart    = (str) => str.indexOf(opening) + opening.length
      , snippetEnd      = (str) => str.indexOf(closing)
      , delimiterEnd    = (str) => str.indexOf(closing) + closing.length;

  // Regex escape function - allows variables with special characters in expression
  const esc = (s) => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

  // Patterns
  const pattern = {
    snippet: new RegExp(esc(opening) + '(.|\n)*' + esc(closing), 'g'),
    keyValue: new RegExp('(.|\n)*' + esc(valueOpening) + '(.|\n)*', 'g')
  };

  // Utility Functions (read/write)
  const read = (file) => {

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

      fs.readFile(file, 'utf-8', (err, fileContent) => {
        if(err) reject(err);
        resolve(fileContent);
      });
    });
  };

  // write json file, return promise
  const writeJSON = (filename, obj) => {

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

      if(!Object.is(obj)) resolve(new Error('writeJSON requires the second argument to be an object'));

      fs.writeFile(filename, JSON.stringify(obj, null, 2) + '\n', err => {
        if(err) reject(err);
        resolve(obj);
      });
    });
  };

  // Module
  return {

    pluckable(str) {
      // Returns true if both opening and closing delimiters are found
      return str.match(pattern.snippet);
    },

    pluckSingle(str) {
      if(!this.pluckable(str)) return new Error(`Unpluckable input: ${str}`);

      // Returns the first pluckable snippet
      return str.substring(snippetStart(str), snippetEnd(str)).trim();
    },

    pluck(str, limit) {
      let snippets = [];

      if(limit) {
        while(this.pluckable(str) && limit--) {
          snippets.push(this.pluckSingle(str));
          str = str.slice(delimiterEnd(str), str.length);
        }
      } else {
        while(this.pluckable(str)) {
          snippets.push(this.pluckSingle(str));
          str = str.slice(delimiterEnd(str), str.length);
        }
      }
      return snippets;
    },

    pluckSingleFile(file, limit) {
      return read(file)
      .then(fileContent => this.pluck(fileContent, limit) );
    },

    pluckFile(files) {

      // Make sure files exist
      if(!files) return new Error('pluckFile - first argument should be a file or an array of files');

      let allFiles;

      // Check if files is array. If not, force it.
      if(!Array.isArray(files)) files = [files];

      // Reduce files to flat array
      // This will handle globs and allow mapping
      // Otherwise, with globs, we would have 2D array
      allFiles = files.reduce( (prev, cur) => {
        return prev.concat( glob.sync(cur, {}) );
      }, [])

      // Map files to an array of promises
      .map( file => this.pluckSingleFile(file) );

      // return promise
      return Promise.all(allFiles)
      .then(allFileContents => {

        // reduce all files to flat array of plucked content
        return allFileContents.reduce((prev, cur) => {
          return prev.concat(cur);
        }, []);

      });
    },

    hasKeyValue(str) {
      // Returns true if all key/value delimiters are found
      return str.match(pattern.keyValue);
    },

    pairUp(str) {

      let pair;

      return str.split(valueClosing).reduce((prev, cur) => {

        // Skip this item if its blank or if it doesn't have qualifying delimiters
        if(!cur || !this.hasKeyValue(cur)) return prev;

        pair = cur.trim()     // Trim the string
        .split(valueOpening); // Split into pair

        // trim and add the pair to the reduction object
        prev[pair[0].trim()] = pair[1].trim()
        return prev;

      }, {});
    },

    objectify(snippets) {
      return snippets.map(snippet => this.pairUp(snippet) );
    },

    writeJSON: writeJSON
  };

}<commit_msg>cleanup<commit_after>import fs from 'fs';
import glob from 'glob';

export default function({

  // delimiters
  opening = '/***',
  closing = '***/',
  valueOpening = '{',
  valueClosing = '}',

} = {}) {

  // Helpers
  const snippetStart    = (str) => str.indexOf(opening) + opening.length
      , snippetEnd      = (str) => str.indexOf(closing)
      , delimiterEnd    = (str) => str.indexOf(closing) + closing.length;

  // Regex escape function - allows variables with special characters in expression
  const esc = (s) => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

  // Patterns
  const pattern = {
    snippet: new RegExp(esc(opening) + '(.|\n)*' + esc(closing), 'g'),
    keyValue: new RegExp('(.|\n)*' + esc(valueOpening) + '(.|\n)*', 'g')
  };

  // Utility Functions (read/write)
  const read = (file) => {

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

      fs.readFile(file, 'utf-8', (err, fileContent) => {
        if(err) reject(err);
        resolve(fileContent);
      });
    });
  };

  // write json file, return promise
  const writeJSON = (filename, obj) => {

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

      if(!Object.is(obj)) resolve(new Error('writeJSON requires the second argument to be an object'));

      fs.writeFile(filename, JSON.stringify(obj, null, 2) + '\n', err => {
        if(err) reject(err);
        resolve(obj);
      });
    });
  };

  // Module
  return {

    pluckable(str) {
      // Returns true if both opening and closing delimiters are found
      return str.match(pattern.snippet);
    },

    pluckSingle(str) {
      if(!this.pluckable(str)) return new Error(`Unpluckable input: ${str}`);

      // Returns the first pluckable snippet
      return str.substring(snippetStart(str), snippetEnd(str)).trim();
    },

    pluck(str, limit) {
      let snippets = [];

      if(limit) {
        while(this.pluckable(str) && limit--) {
          snippets.push(this.pluckSingle(str));
          str = str.slice(delimiterEnd(str), str.length);
        }
      } else {
        while(this.pluckable(str)) {
          snippets.push(this.pluckSingle(str));
          str = str.slice(delimiterEnd(str), str.length);
        }
      }
      return snippets;
    },

    pluckSingleFile(file, limit) {
      return read(file)
      .then(fileContent => this.pluck(fileContent, limit) );
    },

    pluckFile(files) {

      // Make sure files exist
      if(!files) return new Error('pluckFile - first argument should be a file or an array of files');

      let allFiles;

      // Check if files is array. If not, force it.
      if(!Array.isArray(files)) files = [files];

      // Reduce files to flat array
      // This will handle globs and allow mapping
      // Otherwise, with globs, we would have 2D array
      allFiles = files.reduce( (prev, cur) => {
        return prev.concat( glob.sync(cur, {}) );
      }, [])

      // Map files to an array of promises
      .map( file => this.pluckSingleFile(file) );

      // return promise
      return Promise.all(allFiles)
      .then(allFileContents => {

        // reduce all files to flat array of plucked content
        return allFileContents.reduce((prev, cur) => {
          return prev.concat(cur);
        }, []);

      });
    },

    hasKeyValue(str) {
      // Returns true if all key/value delimiters are found
      return str.match(pattern.keyValue);
    },

    pairUp(str) {

      let pair;

      return str.split(valueClosing).reduce((prev, cur) => {

        // Skip this item if its blank or if it doesn't have qualifying delimiters
        if(!cur || !this.hasKeyValue(cur)) return prev;

        pair = cur.trim()     // Trim the string
        .split(valueOpening); // Split into pair

        // trim and add the pair to the reduction object
        prev[pair[0].trim()] = pair[1].trim()
        return prev;

      }, {});
    },

    objectify(snippets) {
      return snippets.map(snippet => this.pairUp(snippet) );
    },

    writeJSON: writeJSON
  };

}
<|endoftext|>


<commit_before>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict
 * @format
 */

import Platform from '../Utilities/Platform';
const ReactNativeVersion = require('./ReactNativeVersion');

/**
 * Checks that the version of this React Native JS is compatible with the native
 * code, throwing an error if it isn't.
 *
 * The existence of this module is part of the public interface of React Native
 * even though it is used only internally within React Native. React Native
 * implementations for other platforms (ex: Windows) may override this module
 * and rely on its existence as a separate module.
 */
exports.checkVersions = function checkVersions(): void {
  const nativeVersion = Platform.constants.reactNativeVersion;
  if (
    ReactNativeVersion.version.major !== nativeVersion.major ||
    ReactNativeVersion.version.minor !== nativeVersion.minor
  ) {
    console.error(
      `React Native version mismatch.\n\nJavaScript version: ${_formatVersion(
        ReactNativeVersion.version,
      )}\n` +
        `Native version: ${_formatVersion(nativeVersion)}\n\n` +
        'Make sure that you have rebuilt the native code. If the problem ' +
        'persists try clearing the Watchman and packager caches with ' +
        '`watchman watch-del-all && react-native start --reset-cache`.',
    );
  }
};

function _formatVersion(
  version:
    | {major: number, minor: number, patch: number, prerelease: ?number}
    | $TEMPORARY$object<{
        major: number,
        minor: number,
        patch: number,
        prerelease: null,
      }>,
): string {
  return (
    `${version.major}.${version.minor}.${version.patch}` +
    // eslint-disable-next-line eqeqeq
    (version.prerelease != undefined ? `-${version.prerelease}` : '')
  );
}
<commit_msg>Update RN Version Expected Structure (#32892)<commit_after>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict
 * @format
 */

import Platform from '../Utilities/Platform';
const ReactNativeVersion = require('./ReactNativeVersion');

/**
 * Checks that the version of this React Native JS is compatible with the native
 * code, throwing an error if it isn't.
 *
 * The existence of this module is part of the public interface of React Native
 * even though it is used only internally within React Native. React Native
 * implementations for other platforms (ex: Windows) may override this module
 * and rely on its existence as a separate module.
 */
exports.checkVersions = function checkVersions(): void {
  const nativeVersion = Platform.constants.reactNativeVersion;
  if (
    ReactNativeVersion.version.major !== nativeVersion.major ||
    ReactNativeVersion.version.minor !== nativeVersion.minor
  ) {
    console.error(
      `React Native version mismatch.\n\nJavaScript version: ${_formatVersion(
        ReactNativeVersion.version,
      )}\n` +
        `Native version: ${_formatVersion(nativeVersion)}\n\n` +
        'Make sure that you have rebuilt the native code. If the problem ' +
        'persists try clearing the Watchman and packager caches with ' +
        '`watchman watch-del-all && react-native start --reset-cache`.',
    );
  }
};

function _formatVersion(
  version:
    | {major: number, minor: number, patch: number, prerelease: ?number}
    | {major: number, minor: number, patch: number, prerelease: ?string}
    | $TEMPORARY$object<{
        major: number,
        minor: number,
        patch: number,
        prerelease: null,
      }>,
): string {
  return (
    `${version.major}.${version.minor}.${version.patch}` +
    // eslint-disable-next-line eqeqeq
    (version.prerelease != undefined ? `-${version.prerelease}` : '')
  );
}
<|endoftext|>


<commit_before>const config = require("config");
const email = require("helper/email");
const exec = require("child_process").exec;

if (require.main === module) {
  main(function (err) {
    if (err) throw err;
    process.exit();
  });
}

function main(callback) {
  exec(
    `ps -e -o ppid= -o pid= -o command= | grep "node ${config.blot_directory}" | awk '$1 == "1" { print $2 }'`,
    function (err, stdout) {
      if (err) return callback(err);

      const zombie_pids = stdout.split("\n").filter((i) => !!i);

      if (zombie_pids.length) {
        console.log("zombies", zombie_pids);
        console.log("src", stdout);
      } else {
        console.log("no zombies found");
      }

      // if (config.environment === "development") {
      //   // this is annoying in development
      // } else {
      //   console.log(clfdate(), "[STATS]", "top");
      //   console.log(stdout);
      // }

      callback();
    }
  );
}

module.exports = main;
<commit_msg>Updates zombie process monitor<commit_after>const config = require("config");
const exec = require("child_process").exec;
const email = require("helper/email");
const async = require("async");

if (require.main === module) {
  main(function (err) {
    if (err) throw err;
    process.exit();
  });
}

function main(callback) {
  exec(
    `ps -e -o ppid= -o pid= -o command= | grep "node ${config.blot_directory}" | awk '$1 == "1" { print $2 }'`,
    function (err, stdout) {
      if (err) return callback(err);

      const zombie_pids = stdout.split("\n").filter((i) => !!i);

      async.eachSeries(
        zombie_pids,
        (pid, next) => {
          console.log("found pid", pid);
          next();
        },
        callback
      );

      // if (config.environment === "development") {
      //   // this is annoying in development
      // } else {
      //   console.log(clfdate(), "[STATS]", "top");
      //   console.log(stdout);
      // }
    }
  );
}

module.exports = main;
<|endoftext|>