<commit_before>/* eslint-disable func-names, space-before-function-paren, wrap-iife, no-underscore-dangle, prefer-arrow-callback, max-len, one-var, one-var-declaration-per-line, no-unused-vars, object-shorthand, comma-dangle, no-else-return, no-self-compare, consistent-return, no-param-reassign, no-shadow */
/* global Issuable */
/* global ListMilestone */
import _ from 'underscore';
import { timeFor } from './lib/utils/datetime_utility';

export default class MilestoneSelect {
  constructor(currentProject, els, options = {}) {
    if (currentProject !== null) {
      this.currentProject = typeof currentProject === 'string' ? JSON.parse(currentProject) : currentProject;
    }

    this.init(els, options);
  }

  init(els, options) {
    let $els = $(els);

    if (!els) {
      $els = $('.js-milestone-select');
    }

    $els.each((i, dropdown) => {
      let collapsedSidebarLabelTemplate, milestoneLinkNoneTemplate, milestoneLinkTemplate, selectedMilestone, selectedMilestoneDefault;
      const $dropdown = $(dropdown);
      const projectId = $dropdown.data('project-id');
      const milestonesUrl = $dropdown.data('milestones');
      const issueUpdateURL = $dropdown.data('issueUpdate');
      const showNo = $dropdown.data('show-no');
      const showAny = $dropdown.data('show-any');
      const showMenuAbove = $dropdown.data('showMenuAbove');
      const showUpcoming = $dropdown.data('show-upcoming');
      const showStarted = $dropdown.data('show-started');
      const useId = $dropdown.data('use-id');
      const defaultLabel = $dropdown.data('default-label');
      const defaultNo = $dropdown.data('default-no');
      const issuableId = $dropdown.data('issuable-id');
      const abilityName = $dropdown.data('ability-name');
      const $selectBox = $dropdown.closest('.selectbox');
      const $block = $selectBox.closest('.block');
      const $sidebarCollapsedValue = $block.find('.sidebar-collapsed-icon');
      const $value = $block.find('.value');
      const $loading = $block.find('.block-loading').fadeOut();
      selectedMilestoneDefault = (showAny ? '' : null);
      selectedMilestoneDefault = (showNo && defaultNo ? 'No Milestone' : selectedMilestoneDefault);
      selectedMilestone = $dropdown.data('selected') || selectedMilestoneDefault;

      if (issueUpdateURL) {
        milestoneLinkTemplate = _.template('<a href="/<%- full_path %>/milestones/<%- iid %>" class="bold has-tooltip" data-container="body" title="<%- remaining %>"><%- title %>');
        milestoneLinkNoneTemplate = 'None';
        collapsedSidebarLabelTemplate = _.template('<span class="has-tooltip" data-container="body" title="<%- name %>
<%- remaining %>" data-placement="left" data-html="true"> <%- title %> ');
      }
      return $dropdown.glDropdown({
        showMenuAbove: showMenuAbove,
        data: (term, callback) => $.ajax({
          url: milestonesUrl
        }).done((data) => {
          const extraOptions = [];
          if (showAny) {
            extraOptions.push({
              id: 0,
              name: '',
              title: 'Any Milestone'
            });
          }
          if (showNo) {
            extraOptions.push({
              id: -1,
              name: 'No Milestone',
              title: 'No Milestone'
            });
          }
          if (showUpcoming) {
            extraOptions.push({
              id: -2,
              name: '#upcoming',
              title: 'Upcoming'
            });
          }
          if (showStarted) {
            extraOptions.push({
              id: -3,
              name: '#started',
              title: 'Started'
            });
          }
          if (extraOptions.length) {
            extraOptions.push('divider');
          }

          callback(extraOptions.concat(data));
          if (showMenuAbove) {
            $dropdown.data('glDropdown').positionMenuAbove();
          }
          $(`[data-milestone-id="${selectedMilestone}"] > a`).addClass('is-active');
        }),
        renderRow: milestone => `

              ${_.escape(milestone.title)}

        `,
        filterable: true,
        search: {
          fields: ['title']
        },
        selectable: true,
        toggleLabel: (selected, el, e) => {
          if (selected && 'id' in selected && $(el).hasClass('is-active')) {
            return selected.title;
          } else {
            return defaultLabel;
          }
        },
        defaultLabel: defaultLabel,
        fieldName: $dropdown.data('field-name'),
        text: milestone => _.escape(milestone.title),
        id: (milestone) => {
          if (!useId && !$dropdown.is('.js-issuable-form-dropdown')) {
            return milestone.name;
          } else {
            return milestone.id;
          }
        },
        isSelected: milestone => milestone.name === selectedMilestone,
        hidden: () => {
          $selectBox.hide();
          // display:block overrides the hide-collapse rule
          return $value.css('display', '');
        },
        opened: (e) => {
          const $el = $(e.currentTarget);
          if ($dropdown.hasClass('js-issue-board-sidebar') || options.handleClick) {
            selectedMilestone = $dropdown[0].dataset.selected || selectedMilestoneDefault;
          }
          $('a.is-active', $el).removeClass('is-active');
          $(`[data-milestone-id="${selectedMilestone}"] > a`, $el).addClass('is-active');
        },
        vue: $dropdown.hasClass('js-issue-board-sidebar'),
        clicked: (clickEvent) => {
          const { $el, e } = clickEvent;
          let selected = clickEvent.selectedObj;

          let data, boardsStore;
          if (!selected) return;

          if (options.handleClick) {
            e.preventDefault();
            options.handleClick(selected);
            return;
          }

          const page = $('body').attr('data-page');
          const isIssueIndex = page === 'projects:issues:index';
          const isMRIndex = (page === page && page === 'projects:merge_requests:index');
          const isSelecting = (selected.name !== selectedMilestone);
          selectedMilestone = isSelecting ? selected.name : selectedMilestoneDefault;
          if ($dropdown.hasClass('js-filter-bulk-update') || $dropdown.hasClass('js-issuable-form-dropdown')) {
            e.preventDefault();
            return;
          }

          if ($dropdown.closest('.add-issues-modal').length) {
            boardsStore = gl.issueBoards.ModalStore.store.filter;
          }

          if (boardsStore) {
            boardsStore[$dropdown.data('field-name')] = selected.name;
            e.preventDefault();
          } else if ($dropdown.hasClass('js-filter-submit') && (isIssueIndex || isMRIndex)) {
            return Issuable.filterResults($dropdown.closest('form'));
          } else if ($dropdown.hasClass('js-filter-submit')) {
            return $dropdown.closest('form').submit();
          } else if ($dropdown.hasClass('js-issue-board-sidebar')) {
            if (selected.id !== -1 && isSelecting) {
              gl.issueBoards.boardStoreIssueSet('milestone', new ListMilestone({
                id: selected.id,
                title: selected.name
              }));
            } else {
              gl.issueBoards.boardStoreIssueDelete('milestone');
            }

            $dropdown.trigger('loading.gl.dropdown');
            $loading.removeClass('hidden').fadeIn();

            gl.issueBoards.BoardsStore.detail.issue.update($dropdown.attr('data-issue-update'))
              .then(() => {
                $dropdown.trigger('loaded.gl.dropdown');
                $loading.fadeOut();
              })
              .catch(() => {
                $loading.fadeOut();
              });
          } else {
            selected = $selectBox.find('input[type="hidden"]').val();
            data = {};
            data[abilityName] = {};
            data[abilityName].milestone_id = selected != null ? selected : null;
            $loading.removeClass('hidden').fadeIn();
            $dropdown.trigger('loading.gl.dropdown');
            return $.ajax({
              type: 'PUT',
              url: issueUpdateURL,
              data: data
            }).done((data) => {
              $dropdown.trigger('loaded.gl.dropdown');
              $loading.fadeOut();
              $selectBox.hide();
              $value.css('display', '');
              if (data.milestone != null) {
                data.milestone.full_path = this.currentProject.full_path;
                data.milestone.remaining = timeFor(data.milestone.due_date);
                data.milestone.name = data.milestone.title;
                $value.html(milestoneLinkTemplate(data.milestone));
                return $sidebarCollapsedValue.find('span').html(collapsedSidebarLabelTemplate(data.milestone));
              } else {
                $value.html(milestoneLinkNoneTemplate);
                return $sidebarCollapsedValue.find('span').text('No');
              }
            });
          }
        }
      });
    });
  }
}
<commit_msg>Converted milestone_select.js to axios<commit_after>/* eslint-disable func-names, space-before-function-paren, wrap-iife, no-underscore-dangle, prefer-arrow-callback, max-len, one-var, one-var-declaration-per-line, no-unused-vars, object-shorthand, comma-dangle, no-else-return, no-self-compare, consistent-return, no-param-reassign, no-shadow */
/* global Issuable */
/* global ListMilestone */
import _ from 'underscore';
import axios from './lib/utils/axios_utils';
import { timeFor } from './lib/utils/datetime_utility';

export default class MilestoneSelect {
  constructor(currentProject, els, options = {}) {
    if (currentProject !== null) {
      this.currentProject = typeof currentProject === 'string' ? JSON.parse(currentProject) : currentProject;
    }

    this.init(els, options);
  }

  init(els, options) {
    let $els = $(els);

    if (!els) {
      $els = $('.js-milestone-select');
    }

    $els.each((i, dropdown) => {
      let collapsedSidebarLabelTemplate, milestoneLinkNoneTemplate, milestoneLinkTemplate, selectedMilestone, selectedMilestoneDefault;
      const $dropdown = $(dropdown);
      const projectId = $dropdown.data('project-id');
      const milestonesUrl = $dropdown.data('milestones');
      const issueUpdateURL = $dropdown.data('issueUpdate');
      const showNo = $dropdown.data('show-no');
      const showAny = $dropdown.data('show-any');
      const showMenuAbove = $dropdown.data('showMenuAbove');
      const showUpcoming = $dropdown.data('show-upcoming');
      const showStarted = $dropdown.data('show-started');
      const useId = $dropdown.data('use-id');
      const defaultLabel = $dropdown.data('default-label');
      const defaultNo = $dropdown.data('default-no');
      const issuableId = $dropdown.data('issuable-id');
      const abilityName = $dropdown.data('ability-name');
      const $selectBox = $dropdown.closest('.selectbox');
      const $block = $selectBox.closest('.block');
      const $sidebarCollapsedValue = $block.find('.sidebar-collapsed-icon');
      const $value = $block.find('.value');
      const $loading = $block.find('.block-loading').fadeOut();
      selectedMilestoneDefault = (showAny ? '' : null);
      selectedMilestoneDefault = (showNo && defaultNo ? 'No Milestone' : selectedMilestoneDefault);
      selectedMilestone = $dropdown.data('selected') || selectedMilestoneDefault;

      if (issueUpdateURL) {
        milestoneLinkTemplate = _.template('<a href="/<%- full_path %>/milestones/<%- iid %>" class="bold has-tooltip" data-container="body" title="<%- remaining %>"><%- title %>');
        milestoneLinkNoneTemplate = 'None';
        collapsedSidebarLabelTemplate = _.template('<span class="has-tooltip" data-container="body" title="<%- name %>
<%- remaining %>" data-placement="left" data-html="true"> <%- title %> ');
      }
      return $dropdown.glDropdown({
        showMenuAbove: showMenuAbove,
        data: (term, callback) => axios.get(milestonesUrl)
          .then(({ data }) => {
            const extraOptions = [];
            if (showAny) {
              extraOptions.push({
                id: 0,
                name: '',
                title: 'Any Milestone'
              });
            }
            if (showNo) {
              extraOptions.push({
                id: -1,
                name: 'No Milestone',
                title: 'No Milestone'
              });
            }
            if (showUpcoming) {
              extraOptions.push({
                id: -2,
                name: '#upcoming',
                title: 'Upcoming'
              });
            }
            if (showStarted) {
              extraOptions.push({
                id: -3,
                name: '#started',
                title: 'Started'
              });
            }
            if (extraOptions.length) {
              extraOptions.push('divider');
            }

            callback(extraOptions.concat(data));
            if (showMenuAbove) {
              $dropdown.data('glDropdown').positionMenuAbove();
            }
            $(`[data-milestone-id="${selectedMilestone}"] > a`).addClass('is-active');
          }),
        renderRow: milestone => `

              ${_.escape(milestone.title)}

        `,
        filterable: true,
        search: {
          fields: ['title']
        },
        selectable: true,
        toggleLabel: (selected, el, e) => {
          if (selected && 'id' in selected && $(el).hasClass('is-active')) {
            return selected.title;
          } else {
            return defaultLabel;
          }
        },
        defaultLabel: defaultLabel,
        fieldName: $dropdown.data('field-name'),
        text: milestone => _.escape(milestone.title),
        id: (milestone) => {
          if (!useId && !$dropdown.is('.js-issuable-form-dropdown')) {
            return milestone.name;
          } else {
            return milestone.id;
          }
        },
        isSelected: milestone => milestone.name === selectedMilestone,
        hidden: () => {
          $selectBox.hide();
          // display:block overrides the hide-collapse rule
          return $value.css('display', '');
        },
        opened: (e) => {
          const $el = $(e.currentTarget);
          if ($dropdown.hasClass('js-issue-board-sidebar') || options.handleClick) {
            selectedMilestone = $dropdown[0].dataset.selected || selectedMilestoneDefault;
          }
          $('a.is-active', $el).removeClass('is-active');
          $(`[data-milestone-id="${selectedMilestone}"] > a`, $el).addClass('is-active');
        },
        vue: $dropdown.hasClass('js-issue-board-sidebar'),
        clicked: (clickEvent) => {
          const { $el, e } = clickEvent;
          let selected = clickEvent.selectedObj;

          let data, boardsStore;
          if (!selected) return;

          if (options.handleClick) {
            e.preventDefault();
            options.handleClick(selected);
            return;
          }

          const page = $('body').attr('data-page');
          const isIssueIndex = page === 'projects:issues:index';
          const isMRIndex = (page === page && page === 'projects:merge_requests:index');
          const isSelecting = (selected.name !== selectedMilestone);
          selectedMilestone = isSelecting ? selected.name : selectedMilestoneDefault;
          if ($dropdown.hasClass('js-filter-bulk-update') || $dropdown.hasClass('js-issuable-form-dropdown')) {
            e.preventDefault();
            return;
          }

          if ($dropdown.closest('.add-issues-modal').length) {
            boardsStore = gl.issueBoards.ModalStore.store.filter;
          }

          if (boardsStore) {
            boardsStore[$dropdown.data('field-name')] = selected.name;
            e.preventDefault();
          } else if ($dropdown.hasClass('js-filter-submit') && (isIssueIndex || isMRIndex)) {
            return Issuable.filterResults($dropdown.closest('form'));
          } else if ($dropdown.hasClass('js-filter-submit')) {
            return $dropdown.closest('form').submit();
          } else if ($dropdown.hasClass('js-issue-board-sidebar')) {
            if (selected.id !== -1 && isSelecting) {
              gl.issueBoards.boardStoreIssueSet('milestone', new ListMilestone({
                id: selected.id,
                title: selected.name
              }));
            } else {
              gl.issueBoards.boardStoreIssueDelete('milestone');
            }

            $dropdown.trigger('loading.gl.dropdown');
            $loading.removeClass('hidden').fadeIn();

            gl.issueBoards.BoardsStore.detail.issue.update($dropdown.attr('data-issue-update'))
              .then(() => {
                $dropdown.trigger('loaded.gl.dropdown');
                $loading.fadeOut();
              })
              .catch(() => {
                $loading.fadeOut();
              });
          } else {
            selected = $selectBox.find('input[type="hidden"]').val();
            data = {};
            data[abilityName] = {};
            data[abilityName].milestone_id = selected != null ? selected : null;
            $loading.removeClass('hidden').fadeIn();
            $dropdown.trigger('loading.gl.dropdown');
            return axios.put(issueUpdateURL, data)
              .then(({ data }) => {
                $dropdown.trigger('loaded.gl.dropdown');
                $loading.fadeOut();
                $selectBox.hide();
                $value.css('display', '');
                if (data.milestone != null) {
                  data.milestone.full_path = this.currentProject.full_path;
                  data.milestone.remaining = timeFor(data.milestone.due_date);
                  data.milestone.name = data.milestone.title;
                  $value.html(milestoneLinkTemplate(data.milestone));
                  return $sidebarCollapsedValue.find('span').html(collapsedSidebarLabelTemplate(data.milestone));
                } else {
                  $value.html(milestoneLinkNoneTemplate);
                  return $sidebarCollapsedValue.find('span').text('No');
                }
              });
          }
        }
      });
    });
  }
}
<|endoftext|>


<commit_before>// var sql = new cartodb.SQL({ user: 'easherma',format: 'geoJSON'});
// sql.execute("SELECT * FROM bikeways")
//   .done(function(data) {
//       console.log(data);
//     L.geoJson(data).addTo(map);
//   })
//   .error(function(errors) {
//     // errors contains a list of errors
//     console.log("errors:" + errors);
//   })
//

$.ajax({
  type: 'GET',
  url: 'https://api.osgisomg.com/api/data/',
  crossDomain: true,
  // data: {"q":sql_statement},
  dataType: 'json',
  contentType: 'application/json; charset=utf-8',
  success: function(responseData, textStatus, jqXHR) {
    console.log("Submissions retrived");
    console.log(JSON.stringify(responseData));
    var submissionsStyle = L.geoJson(responseData, {
        style: function (feature) {
  return {color: get_random_color()};
},
    // pointToLayer: function (feature, latlng) {
    //         return L.circleMarker(latlng, geojsonMarkerOptions);
    // }
    // ,
        onEachFeature: onEachFeatureSubmissions
    });
    layerOrder[layerOrder.length] = submissionsStyle;
    feature_group.addLayer(submissionsStyle).addTo(submissions);

  },
  error: function (responseData, textStatus, errorThrown) {
      console.log(JSON.stringify(responseData));
      console.log("Problem retriving submissions");
      console.log(errorThrown);
  }
});

var sql_statement="select the_geom, description, email, name, org, insert_time from bikeways where name != 'test'";

// old query for carto

//   $.getJSON('https://easherma.carto.com/api/v2/sql/?format=GeoJSON&q='+sql_statement, function(data) {
// // L.geoJson(data).addTo(map);
//   });
//   $.ajax({
//     type: 'GET',
//     url: 'https://'+config.cartoDBusername+'.carto.com/api/v2/sql/?format=GeoJSON',
//     crossDomain: true,
//     data: {"q":sql_statement},
//     dataType: 'json',
//     success: function(responseData, textStatus, jqXHR) {
//       console.log("Data retrived");
//       console.log(responseData);
//       var submissionsStyle = L.geoJson(responseData, {
//           style: function (feature) {
//     return {color: get_random_color()};
// },
//           onEachFeature: onEachFeatureSubmissions
//       });
//       layerOrder[layerOrder.length] = submissionsStyle;
//       feature_group.addLayer(submissionsStyle).addTo(submissions);
//
//     },
//     error: function (responseData, textStatus, errorThrown) {
//         console.log(responseData);
//
//         console.log("Problem getting the data");
//     }
//   });
<commit_msg>renable carto<commit_after>// var sql = new cartodb.SQL({ user: 'easherma',format: 'geoJSON'});
// sql.execute("SELECT * FROM bikeways")
//   .done(function(data) {
//       console.log(data);
//     L.geoJson(data).addTo(map);
//   })
//   .error(function(errors) {
//     // errors contains a list of errors
//     console.log("errors:" + errors);
//   })
//

$.ajax({
  type: 'GET',
  url: 'https://api.osgisomg.com/api/data/',
  crossDomain: true,
  // data: {"q":sql_statement},
  dataType: 'json',
  contentType: 'application/json; charset=utf-8',
  success: function(responseData, textStatus, jqXHR) {
    console.log("Submissions retrived");
    console.log(JSON.stringify(responseData));
    var submissionsStyle = L.geoJson(responseData, {
        style: function (feature) {
  return {color: get_random_color()};
},
    // pointToLayer: function (feature, latlng) {
    //         return L.circleMarker(latlng, geojsonMarkerOptions);
    // }
    // ,
        onEachFeature: onEachFeatureSubmissions
    });
    layerOrder[layerOrder.length] = submissionsStyle;
    feature_group.addLayer(submissionsStyle).addTo(submissions);

  },
  error: function (responseData, textStatus, errorThrown) {
      console.log(JSON.stringify(responseData));
      console.log("Problem retriving submissions");
      console.log(errorThrown);
  }
});

var sql_statement="select the_geom, description, email, name, org, insert_time from bikeways where name != 'test'";

// old query for carto

  $.getJSON('https://easherma.carto.com/api/v2/sql/?format=GeoJSON&q='+sql_statement, function(data) {
// L.geoJson(data).addTo(map);
  });
  $.ajax({
    type: 'GET',
    url: 'https://'+config.cartoDBusername+'.carto.com/api/v2/sql/?format=GeoJSON',
    crossDomain: true,
    data: {"q":sql_statement},
    dataType: 'json',
    success: function(responseData, textStatus, jqXHR) {
      console.log("Data retrived");
      console.log(responseData);
      var submissionsStyle = L.geoJson(responseData, {
          style: function (feature) {
    return {color: get_random_color()};
},
          onEachFeature: onEachFeatureSubmissions
      });
      layerOrder[layerOrder.length] = submissionsStyle;
      feature_group.addLayer(submissionsStyle).addTo(submissions);

    },
    error: function (responseData, textStatus, errorThrown) {
        console.log(responseData);

        console.log("Problem getting the data");
    }
  });
<|endoftext|>


<commit_before>import chai from 'chai';
import '@babel/polyfill';
import __toString from 'lodash/toString';

const __utils = (() => {
  const MAX_LOGS_SIZE = 64 * 1024;

  let logs = [];
  function flushLogs() {
    if (logs.length) {
      self.postMessage({
        type: 'LOG',
        data: logs.join('\n')
      });
      logs = [];
    }
  }

  const oldLog = self.console.log.bind(self.console);
  self.console.log = function proxyConsole(...args) {
    logs.push(args.map(arg => JSON.stringify(arg)).join(' '));
    if (logs.join('\n').length > MAX_LOGS_SIZE) {
      flushLogs();
    }
    return oldLog(...args);
  };

  function postResult(data) {
    flushLogs();
    self.postMessage(data);
  }

  return {
    postResult
  };
})();

self.onmessage = async e => {
  /* eslint-disable no-unused-vars */
  const { code = '' } = e.data;
  const assert = chai.assert;
  // Fake Deep Equal dependency
  const DeepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
  /* eslint-enable no-unused-vars */
  try {
    let testResult;
    let __userCodeWasExecuted = false;
    /* eslint-disable no-eval */
    try {
      testResult = eval(`
        ${e.data.build}
        __userCodeWasExecuted = true;
        ${e.data.testString}
      `);
    } catch (err) {
      if (__userCodeWasExecuted) {
        throw err;
      }
      testResult = eval(e.data.testString);
    }
    /* eslint-enable no-eval */
    if (typeof testResult === 'function') {
      await testResult(fileName => __toString(e.data.sources[fileName]));
    }
    __utils.postResult({
      pass: true
    });
  } catch (err) {
    __utils.postResult({
      err: {
        message: err.message,
        stack: err.stack
      }
    });
    if (!(err instanceof chai.AssertionError)) {
      console.error(err);
    }
  }
};

self.postMessage({ type: 'contentLoaded' });
<commit_msg>fix: Report build errors to dev console (#36540)<commit_after>import chai from 'chai';
import '@babel/polyfill';
import __toString from 'lodash/toString';

const __utils = (() => {
  const MAX_LOGS_SIZE = 64 * 1024;

  let logs = [];
  function flushLogs() {
    if (logs.length) {
      self.postMessage({
        type: 'LOG',
        data: logs.join('\n')
      });
      logs = [];
    }
  }

  const oldLog = self.console.log.bind(self.console);
  self.console.log = function proxyConsole(...args) {
    logs.push(args.map(arg => JSON.stringify(arg)).join(' '));
    if (logs.join('\n').length > MAX_LOGS_SIZE) {
      flushLogs();
    }
    return oldLog(...args);
  };

  function postResult(data) {
    flushLogs();
    self.postMessage(data);
  }

  return {
    postResult,
    oldLog
  };
})();

self.onmessage = async e => {
  /* eslint-disable no-unused-vars */
  const { code = '' } = e.data;
  const assert = chai.assert;
  // Fake Deep Equal dependency
  const DeepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
  /* eslint-enable no-unused-vars */
  try {
    let testResult;
    let __userCodeWasExecuted = false;
    /* eslint-disable no-eval */
    try {
      testResult = eval(`
        ${e.data.build}
        __userCodeWasExecuted = true;
        ${e.data.testString}
      `);
    } catch (err) {
      if (__userCodeWasExecuted) {
        // rethrow error, since test failed.
        throw err;
      } else {
        // report errors to dev console (not the editor console, since the test
        // may still pass)
        __utils.oldLog(err);
      }
      testResult = eval(e.data.testString);
    }
    /* eslint-enable no-eval */
    if (typeof testResult === 'function') {
      await testResult(fileName => __toString(e.data.sources[fileName]));
    }
    __utils.postResult({
      pass: true
    });
  } catch (err) {
    __utils.postResult({
      err: {
        message: err.message,
        stack: err.stack
      }
    });
    if (!(err instanceof chai.AssertionError)) {
      console.error(err);
    }
  }
};

self.postMessage({ type: 'contentLoaded' });
<|endoftext|>


<commit_before>function updateFirstPage(){
    //temporary put this function here, need to find better place or rename the updateFirstPage
    renameHFMissingField();
    var items = Exhibit.jQuery('div[itemid]');
    var item_type = getItemType(items);
    var item_ids = getItemIds(items);

    Exhibit.jQuery.ajax({
        url: faceted_items_url,
        data: {item_ids: item_ids, item_type: item_type}
    })
    .done(function( data ) {
            updateContent(data.resource_list_items);

            Exhibit.jQuery('.exhibit-viewPanel').removeClass('exhibit-ui-protection');
            Exhibit.jQuery('.exhibit-collectionView-header-groupControl').hide();
            decodeValueTooltip();

            Exhibit.jQuery('.exhibit-viewPanel-viewContainer').show();

    });
}

function getItemIds(items){
    var item_ids = items.map(function(){
        var exhibit_item_id = Exhibit.jQuery(this).attr("itemid");
        return database.getObject(exhibit_item_id, 'item_id');
    }).get();

    return item_ids;
}

function getItemType(items){
    return database.getObject(items.attr("itemid"), 'type');
}

function updateContent(resource_list_items){
    var collection_view_body = Exhibit.jQuery('.exhibit-collectionView-body');
    collection_view_body.html(resource_list_items);
}

function decodeValueTooltip(){
    Exhibit.jQuery('.exhibit-facet-value').map(function(){
        var title = Exhibit.jQuery(this).attr("title");
        Exhibit.jQuery(this).attr("title", decodeHTML(title));
    })
}

//rename Hierachical Facet Missing Field of the root level: from others to missing this field
function renameHFMissingField(){
    var missing_field_elements = Exhibit.jQuery('.exhibit-flowingFacet-body').children("[title='(others)']");
    var replaced_term = "(missing this field)";
    missing_field_elements.map(function(){
        Exhibit.jQuery(this).attr("title", replaced_term);
        var value_link = Exhibit.jQuery(this).children('.exhibit-flowingFacet-value-link');
        value_link.html("(missing this field)");
    })
}

<commit_msg>remove the toolbox for now, might add it back later<commit_after>function updateFirstPage(){
    //temporary put this function here, need to find better place or rename the updateFirstPage
    renameHFMissingField();
    var items = Exhibit.jQuery('div[itemid]');
    var item_type = getItemType(items);
    var item_ids = getItemIds(items);

    Exhibit.jQuery.ajax({
        url: faceted_items_url,
        data: {item_ids: item_ids, item_type: item_type}
    })
    .done(function( data ) {
            updateContent(data.resource_list_items);

            Exhibit.jQuery('.exhibit-viewPanel').removeClass('exhibit-ui-protection');
            Exhibit.jQuery('.exhibit-collectionView-header-groupControl').hide();
            Exhibit.jQuery('.exhibit-toolboxWidget-button').hide();
            decodeValueTooltip();

            Exhibit.jQuery('.exhibit-viewPanel-viewContainer').show();

    });
}

function getItemIds(items){
    var item_ids = items.map(function(){
        var exhibit_item_id = Exhibit.jQuery(this).attr("itemid");
        return database.getObject(exhibit_item_id, 'item_id');
    }).get();

    return item_ids;
}

function getItemType(items){
    return database.getObject(items.attr("itemid"), 'type');
}

function updateContent(resource_list_items){
    var collection_view_body = Exhibit.jQuery('.exhibit-collectionView-body');
    collection_view_body.html(resource_list_items);
}

function decodeValueTooltip(){
    Exhibit.jQuery('.exhibit-facet-value').map(function(){
        var title = Exhibit.jQuery(this).attr("title");
        Exhibit.jQuery(this).attr("title", decodeHTML(title));
    })
}

//rename Hierachical Facet Missing Field of the root level: from others to missing this field
function renameHFMissingField(){
    var missing_field_elements = Exhibit.jQuery('.exhibit-flowingFacet-body').children("[title='(others)']");
    var replaced_term = "(missing this field)";
    missing_field_elements.map(function(){
        Exhibit.jQuery(this).attr("title", replaced_term);
        var value_link = Exhibit.jQuery(this).children('.exhibit-flowingFacet-value-link');
        value_link.html("(missing this field)");
    })
}

<|endoftext|>


<commit_before>/** @fileOverview Boostrap functionality */

var WebSocketServer = require('websocket').server;
var http = require('http');
var fs = require('fs');

/**
 * @constructor
 * @param port {Number} Port this server shall listen on
 */
BootstrapServer = function(hostname, port) {
    if(!(this instanceof BootstrapServer)) {
        return new BootstrapServer();
    }
    this._port = port;
    this._hostname = hostname;
    this._users = {};
    this._httpServer = null;
    this._websocketServer = null;
    return this;
};

BootstrapServer.prototype = {
    /**
     * Start listening
     *
     * @param successCallback {Function} Gets called when the http server is listening
     */
    listen: function(successCallback) {
        this._httpServer = http.createServer(this._onHttpRequest.bind(this));
        this._httpServer.listen(this._port, this._hostname, successCallback);
        this._websocketServer = new WebSocketServer({
            httpServer: this._httpServer,
            autoAcceptConnections: false
        });
        this._websocketServer.on('request', this._onWebSocketRequest.bind(this));
        console.log((new Date()) + ' BootstrapServer listening on ' + this._hostname + ':' + this._port);
    },

    /**
     * Gets called on a HTTP Request to this server (serving static files)
     *
     * @param request {http.IncomingMessage}
     * @param response {http.ServerResponse}
     */
    _onHttpRequest: function(request, response) {
        console.log((new Date()) + ' Received HTTP request for ' + request.url);

        try {
            response.writeHead(200);
            response.write(fs.readFileSync(__dirname + request.url));
        } catch (e) {
            response.writeHead(404);
            response.write('404 - Not Found');
        }
        response.end();
    },

    /**
     * Gets called when a client initiates a WebSocket connection
     * to the server. Associates the initiated connection with a peerId
     * given in the initial connection URI (as 12345 in ws://localhost/ws/12345)
     *
     * @param request {WebSocketRequest}
     */
    _onWebSocketRequest: function(request) {
        var conn;
        var url = request.httpRequest.url;
        var peerId = url.substr(4);
        if (!peerId || url.substr(0,4) !== '/ws/') {
            request.reject('404', 'malformed request');
            console.log((new Date()) + ' Discarding Request because of malformed uri ' + request.httpRequest.url);
            return;
        }
        console.log((new Date()) + ' Received WS request from PeerId ' + peerId);
        conn = request.accept(null, request.origin);
        conn.on('close', this._onWebSocketClose.bind(this, peerId));
        conn.on('message', this._onWebSocketMessage.bind(this));
        this._users[peerId] = conn;
    },

    /**
     * Gets called whenever a peer sends a message over its websocket connection
     *
     * @param rawMsg {String} incoming UTF8-String containing the message
     */
    _onWebSocketMessage: function(rawMsg) {
        var msg;
        try {
            msg = JSON.parse(rawMsg.utf8Data);
        } catch (e) {
            console.log((new Date()) + ' Could not parse incoming message: ' + rawMsg.utf8Data + ' ' + e);
            return;
        }
        switch (msg.payload.type) {
            case 'offer':
                this._handleOffer(msg);
                break;
            case 'answer':
                this._handleAnswer(msg);
                break;
            default:
                console.log((new Date()) + ' Discarding message: ' + JSON.stringify(msg) + ' because the type is unknown');
        }
    },

    /**
     * Forwards an offer to a connected peer via its WebSocket
     * connection. The peer is chosen at random if not explicitly
     * set in the message's `to` field
     *
     * @param msg {Object} The message containing the offer
     */
    _handleOffer: function(msg) {
        var receiver, user, count = 0;
        if (Object.keys(this._users).length <= 1 || (msg.to && !this._users[msg.to])) {
            // denied
            this._users[msg.from].send(JSON.stringify({
                type: 'roap-protocol',
                to: msg.from,
                from: 'signaling-server',
                payload: {type: 'denied'}
            }));
            return;
        }
        if (msg.to && this._users[msg.to]) {
            // receiver known
            receiver = this._users[msg.to];
        } else {
            // random receiver (inital offer)
            for (user in this._users) {
                if (Math.random() < 1/++count && user !== msg.from) {
                    console.log((new Date()) + ' Sending offer from: ' + msg.from + ' to: ' + user);
                    msg.to = user;
                    receiver = this._users[user];
                    break;
                }
            }
        }
        try {
            receiver.send(JSON.stringify(msg));
        } catch (e) {
            console.log((new Date()) + ' Could not send offer to ' + msg.to + ' because the WebSocket connection failed: ' + e);
        }
    },

    /**
     * Forwards an answer to the corresponding peer (set in the `msg.to` field
     * from the client).
     *
     * @param msg {Object} The message containing the answer
     */
    _handleAnswer: function(msg) {
        var receiver = this._users[msg.to];
        try {
            console.log((new Date()) + ' Sending answer from: ' + msg.from + ' to: ' + msg.to);
            this._users[msg.to].send(JSON.stringify(msg));
        } catch(e) {
            console.log((new Date()) + ' Could not send offer to ' + msg.to + ' because the WebSocket connection failed: ' + e);
        }
    },

    /**
     * Removes a peer from the user table when the WebSocket closes
     *
     * @param peerId {String} The ID of the disconnected peer
     * @param reasonCode {Object} (unused) Reason code for disconnect
     * @param description {Object} (unused) Description for disconnect
     */
    _onWebSocketClose: function(peerId, reasonCode, description) {
        console.log((new Date()) + ' Removing user: ' + peerId);
        delete this._users[peerId];
    },

    /**
     *
     *
     */
    close: function() {
        this._websocketServer.shutDown();
        this._httpServer.close();
    }
};

if(typeof(module) !== 'undefined') {
    module.exports = BootstrapServer;
}
<commit_msg>Added null/undefined check for empty signaling messages<commit_after>/** @fileOverview Boostrap functionality */

var WebSocketServer = require('websocket').server;
var http = require('http');
var fs = require('fs');

/**
 * @constructor
 * @param port {Number} Port this server shall listen on
 */
BootstrapServer = function(hostname, port) {
    if(!(this instanceof BootstrapServer)) {
        return new BootstrapServer();
    }
    this._port = port;
    this._hostname = hostname;
    this._users = {};
    this._httpServer = null;
    this._websocketServer = null;
    return this;
};

BootstrapServer.prototype = {
    /**
     * Start listening
     *
     * @param successCallback {Function} Gets called when the http server is listening
     */
    listen: function(successCallback) {
        this._httpServer = http.createServer(this._onHttpRequest.bind(this));
        this._httpServer.listen(this._port, this._hostname, successCallback);
        this._websocketServer = new WebSocketServer({
            httpServer: this._httpServer,
            autoAcceptConnections: false
        });
        this._websocketServer.on('request', this._onWebSocketRequest.bind(this));
        console.log((new Date()) + ' BootstrapServer listening on ' + this._hostname + ':' + this._port);
    },

    /**
     * Gets called on a HTTP Request to this server (serving static files)
     *
     * @param request {http.IncomingMessage}
     * @param response {http.ServerResponse}
     */
    _onHttpRequest: function(request, response) {
        console.log((new Date()) + ' Received HTTP request for ' + request.url);

        try {
            response.writeHead(200);
            response.write(fs.readFileSync(__dirname + request.url));
        } catch (e) {
            response.writeHead(404);
            response.write('404 - Not Found');
        }
        response.end();
    },

    /**
     * Gets called when a client initiates a WebSocket connection
     * to the server. Associates the initiated connection with a peerId
     * given in the initial connection URI (as 12345 in ws://localhost/ws/12345)
     *
     * @param request {WebSocketRequest}
     */
    _onWebSocketRequest: function(request) {
        var conn;
        var url = request.httpRequest.url;
        var peerId = url.substr(4);
        if (!peerId || url.substr(0,4) !== '/ws/') {
            request.reject('404', 'malformed request');
            console.log((new Date()) + ' Discarding Request because of malformed uri ' + request.httpRequest.url);
            return;
        }
        console.log((new Date()) + ' Received WS request from PeerId ' + peerId);
        conn = request.accept(null, request.origin);
        conn.on('close', this._onWebSocketClose.bind(this, peerId));
        conn.on('message', this._onWebSocketMessage.bind(this));
        this._users[peerId] = conn;
    },

    /**
     * Gets called whenever a peer sends a message over its websocket connection
     *
     * @param rawMsg {String} incoming UTF8-String containing the message
     */
    _onWebSocketMessage: function(rawMsg) {
        var msg;
        try {
            msg = JSON.parse(rawMsg.utf8Data);
        } catch (e) {
            console.log((new Date()) + ' Could not parse incoming message: ' + rawMsg.utf8Data + ' ' + e);
            return;
        }
        if (typeof(msg.payload) === 'undefined' || msg.payload === null) {
            console.log((new Date()) + ' Discarding message: ' + JSON.stringify(msg) + ' because it does not carry any payload');
            return;
        }
        switch (msg.payload.type) {
            case 'offer':
                this._handleOffer(msg);
                break;
            case 'answer':
                this._handleAnswer(msg);
                break;
            default:
                console.log((new Date()) + ' Discarding message: ' + JSON.stringify(msg) + ' because the type is unknown');
        }
    },

    /**
     * Forwards an offer to a connected peer via its WebSocket
     * connection. The peer is chosen at random if not explicitly
     * set in the message's `to` field
     *
     * @param msg {Object} The message containing the offer
     */
    _handleOffer: function(msg) {
        var receiver, user, count = 0;
        if (Object.keys(this._users).length <= 1 || (msg.to && !this._users[msg.to])) {
            // denied
            this._users[msg.from].send(JSON.stringify({
                type: 'roap-protocol',
                to: msg.from,
                from: 'signaling-server',
                payload: {type: 'denied'}
            }));
            return;
        }
        if (msg.to && this._users[msg.to]) {
            // receiver known
            receiver = this._users[msg.to];
        } else {
            // random receiver (inital offer)
            for (user in this._users) {
                if (Math.random() < 1/++count && user !== msg.from) {
                    console.log((new Date()) + ' Sending offer from: ' + msg.from + ' to: ' + user);
                    msg.to = user;
                    receiver = this._users[user];
                    break;
                }
            }
        }
        try {
            receiver.send(JSON.stringify(msg));
        } catch (e) {
            console.log((new Date()) + ' Could not send offer to ' + msg.to + ' because the WebSocket connection failed: ' + e);
        }
    },

    /**
     * Forwards an answer to the corresponding peer (set in the `msg.to` field
     * from the client).
     *
     * @param msg {Object} The message containing the answer
     */
    _handleAnswer: function(msg) {
        var receiver = this._users[msg.to];
        try {
            console.log((new Date()) + ' Sending answer from: ' + msg.from + ' to: ' + msg.to);
            this._users[msg.to].send(JSON.stringify(msg));
        } catch(e) {
            console.log((new Date()) + ' Could not send offer to ' + msg.to + ' because the WebSocket connection failed: ' + e);
        }
    },

    /**
     * Removes a peer from the user table when the WebSocket closes
     *
     * @param peerId {String} The ID of the disconnected peer
     * @param reasonCode {Object} (unused) Reason code for disconnect
     * @param description {Object} (unused) Description for disconnect
     */
    _onWebSocketClose: function(peerId, reasonCode, description) {
        console.log((new Date()) + ' Removing user: ' + peerId);
        delete this._users[peerId];
    },

    /**
     *
     *
     */
    close: function() {
        this._websocketServer.shutDown();
        this._httpServer.close();
    }
};

if(typeof(module) !== 'undefined') {
    module.exports = BootstrapServer;
}
<|endoftext|>


<commit_before>var _exec = require('child_process').exec;
var _execSync = require('child_process').execSync;
var path = require('path');
var fs = require('fs');
var webpack = require('webpack');

var tests = [
  'basic',
  'cache-externals-absolute',
  'paths-generate-inside',
  'paths-generate-outside',
];

var originalCWD = process.cwd();
var fixturesPath = path.join(__dirname, 'fixtures');
var tests = fs.readdirSync(fixturesPath).filter(function(file) {
  if (fs.statSync(path.join(fixturesPath, file)).isDirectory()) {
    return true;
  }

  return false;
});

global.__CONFIG__ = require('./config');

tests.reduce(function(last, testName) {
  /*return exec(path.join(__dirname, '../../node_modules/.bin/webpack'), {
    cwd: path.join(__dirname, testName),
    stdio: 'inherit'
  });*/

  return last.then(() => {
    console.log(testName);

    return new Promise((resolve) => {
      var testDir = path.join(fixturesPath, testName);
      // var config = fs.readFileSync(path.join(testDir, 'webpack.config.js'), 'utf-8');
      process.chdir(testDir);
      var config = require(path.join(testDir, 'webpack.config.js'));

      console.log(process.cwd());
      webpack(config, function(err, stats) {
        console.log(err);
        // console.log(stats);
        resolve();
      });
    });
  });
}, Promise.resolve()).then(() => {
  process.chdir(originalCWD);
}).catch(function(data) {
  /*if (!_execSync) {
    process.stdout.write(data.stdout);
    process.stderr.write(data.stderr);
  }*/

  console.log('catch', data);

  // process.exit(data.error ? data.error.code : 1);
});

function exec(cmd, options) {
  return function() {
    return new Promise(function(resolve, reject) {
      options || (options = {});

      if (_execSync) {
        _execSync(cmd, options);
        resolve();
        return;
      }

      _exec(cmd, options, function(error, stdout, stderr) {
        var data = {
          error: error,
          stderr: stderr
        };

        if (error) {
          reject(data);
          return;
        }

        process.stdout.write(stdout);
        resolve();
      });
    })
  };
}

function runAll(all) {
  return all.reduce(function(result, run) {
    return result.then(run);
  }, Promise.resolve());
}

<commit_msg>ES6 all the things! Oh.. wait<commit_after>var _exec = require('child_process').exec;
var _execSync = require('child_process').execSync;
var path = require('path');
var fs = require('fs');
var webpack = require('webpack');

var tests = [
  'basic',
  'cache-externals-absolute',
  'paths-generate-inside',
  'paths-generate-outside',
];

var originalCWD = process.cwd();
var fixturesPath = path.join(__dirname, 'fixtures');
var tests = fs.readdirSync(fixturesPath).filter(function(file) {
  if (fs.statSync(path.join(fixturesPath, file)).isDirectory()) {
    return true;
  }

  return false;
});

global.__CONFIG__ = require('./config');

tests.reduce(function(last, testName) {
  /*return exec(path.join(__dirname, '../../node_modules/.bin/webpack'), {
    cwd: path.join(__dirname, testName),
    stdio: 'inherit'
  });*/

  return last.then(function() {
    console.log(testName);

    return new Promise(function(resolve) {
      var testDir = path.join(fixturesPath, testName);
      // var config = fs.readFileSync(path.join(testDir, 'webpack.config.js'), 'utf-8');
      process.chdir(testDir);
      var config = require(path.join(testDir, 'webpack.config.js'));

      console.log(process.cwd());
      webpack(config, function(err, stats) {
        console.log(err);
        // console.log(stats);
        resolve();
      });
    });
  });
}, Promise.resolve()).then(function() {
  process.chdir(originalCWD);
}).catch(function(data) {
  /*if (!_execSync) {
    process.stdout.write(data.stdout);
    process.stderr.write(data.stderr);
  }*/

  console.log('catch', data);

  // process.exit(data.error ? data.error.code : 1);
});

function exec(cmd, options) {
  return function() {
    return new Promise(function(resolve, reject) {
      options || (options = {});

      if (_execSync) {
        _execSync(cmd, options);
        resolve();
        return;
      }

      _exec(cmd, options, function(error, stdout, stderr) {
        var data = {
          error: error,
          stderr: stderr
        };

        if (error) {
          reject(data);
          return;
        }

        process.stdout.write(stdout);
        resolve();
      });
    })
  };
}

function runAll(all) {
  return all.reduce(function(result, run) {
    return result.then(run);
  }, Promise.resolve());
}

<|endoftext|>


<commit_before>/*
 *jWaitIndicator 1.0 - WaitIndicator for Lazy loading
 *
 * http://hackme.co.vu
 *
 * Copyright (c) 2014 Rajeev Ranjan
 *
 * licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 */

(function ($, window, document, undefined) {
    // Initialize waitindicatorcounter
    var waitindicatorcounter = 0;
    $.fn.jWaitIndicatorStart = function (options) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            display: "none",
            position: "absolute",
            zindex: "99999999",
            top: "0",
            left: "0",
            height: "100%",
            width: "100%",
            backgroundColor: "rgba( 255, 255, 255, .8 )",
            waitIndicatorImage: "url('../Images/pg.gif')",
            backgroundRepeat: "no-repeat",
            backgroundPosX: "50%",
            backgroundPosY: "50%"
        }, options);

        // Initialize and start WaitIndicator

        this.each(function (e) {
            var eID = $(this);
            //If ID is undefined generate new one
            if (eID.attr("id") == undefined)
                eID.attr("id", "_WaitIndicator" + waitindicatorcounter);
            //Dont create if already present
            if ($('._WaitIndicator[WaitIndicatorAssociatedWith="' + $(this).attr("id") + '"]').length == 0)
                $("body").append("

");
            SetWaitIndicatorPos(eID);
            //Resdesign WaitIndicator
            $(window).resize(function () {
                SetWaitIndicatorPos(eID);
            });
            waitindicatorcounter++;
        });

        function SetWaitIndicatorPos(eID) {
            $('._WaitIndicator[WaitIndicatorAssociatedWith="' + eID.attr("id") + '"]').css({
                display: settings.display,
                position: eID.is("body") ? "fixed" : settings.position,
                "z-index": settings.zindex,
                top: eID.is("body") ? 0 : eID.offset().top + 15,
                left: eID.is("body") ? 0 : eID.offset().left + 7,
                height: eID.is("body") ? "100%" : eID.height() - 10,
                width: eID.is("body") ? "100%" : eID.width() - 10,
                "background-image": settings.waitIndicatorImage,
                "background-color": settings.backgroundColor,
                "background-position-x": settings.backgroundPosX,
                "background-position-y": settings.backgroundPosY,
                "background-repeat": settings.backgroundRepeat
            }).show();
        }
    };
    //hide waitindicator
    $.fn.jWaitIndicatorEnd = function () {
        this.each(function (e) {
            $('._WaitIndicator[WaitIndicatorAssociatedWith="' + $(this).attr("id") + '"]').hide();
        });
    };
    //destroy waitindicator
    $.fn.jWaitIndicatorDestroy = function () {
        this.each(function (e) {
            $('._WaitIndicator[WaitIndicatorAssociatedWith="' + $(this).attr("id") + '"]').remove();
        });
    };
    //destroy all waitindicator
    $.fn.jWaitIndicatorDestroyAll = function () {
        $('._WaitIndicator').remove();
    };
}(jQuery, window, document));

<commit_msg>Update jWaitIndicator.js<commit_after>/*
 *jWaitIndicator 1.0 - WaitIndicator for Lazy loading
 *
 * http://hackme.co.vu
 *
 * Copyright (c) 2014 Rajeev Ranjan
 *
 * licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 */
(function ($, window, document, undefined) {
    // Initialize waitindicatorcounter
    var waitindicatorcounter = 0;
    $.fn.jWaitIndicatorStart = function (options) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            display: "none",
            position: "absolute",
            zindex: "99999999",
            top: "0",
            left: "0",
            height: "100%",
            width: "100%",
            backgroundColor: "rgba( 255, 255, 255, .8 )",
            waitIndicatorImage: "url('../Images/pg.gif')",
            backgroundRepeat: "no-repeat",
            backgroundPosX: "50%",
            backgroundPosY: "50%"
        }, options);

        // Initialize and start WaitIndicator

        this.each(function (e) {
            var eID = $(this);
            //If ID is undefined generate new one
            if (eID.attr("id") == undefined)
                eID.attr("id", "_WaitIndicator" + waitindicatorcounter);
            //Dont create if already present
            if ($('._WaitIndicator[WaitIndicatorAssociatedWith="' + $(this).attr("id") + '"]').length == 0)
                $("body").append("

");
            SetWaitIndicatorPos(eID);
            //Resdesign WaitIndicator
            $(window).resize(function () {
                SetWaitIndicatorPos(eID);
            });
            waitindicatorcounter++;
        });

        function SetWaitIndicatorPos(eID) {
            $('._WaitIndicator[WaitIndicatorAssociatedWith="' + eID.attr("id") + '"]').css({
                display: settings.display,
                position: eID.is("body") ? "fixed" : settings.position,
                "z-index": settings.zindex,
                top: eID.is("body") ? 0 : eID.offset().top + 15,
                left: eID.is("body") ? 0 : eID.offset().left + 7,
                height: eID.is("body") ? "100%" : eID.height() - 10,
                width: eID.is("body") ? "100%" : eID.width() - 10,
                "background-image": settings.waitIndicatorImage,
                "background-color": settings.backgroundColor,
                "background-position-x": settings.backgroundPosX,
                "background-position-y": settings.backgroundPosY,
                "background-repeat": settings.backgroundRepeat
            }).show();
        }
    };
    //hide waitindicator
    $.fn.jWaitIndicatorEnd = function () {
        this.each(function (e) {
            $('._WaitIndicator[WaitIndicatorAssociatedWith="' + $(this).attr("id") + '"]').hide();
        });
    };
    //destroy waitindicator
    $.fn.jWaitIndicatorDestroy = function () {
        this.each(function (e) {
            $('._WaitIndicator[WaitIndicatorAssociatedWith="' + $(this).attr("id") + '"]').remove();
        });
    };
    //destroy all waitindicator
    $.fn.jWaitIndicatorDestroyAll = function () {
        $('._WaitIndicator').remove();
    };
}(jQuery, window, document));

<|endoftext|>


<commit_before>import React, { Component } from "react";
import gql from "graphql-tag";
import { Mutation, graphql, withApollo } from "react-apollo";
import { Container, Row, Col, Input } from "reactstrap";
import { InputField, OutputField } from "../../generic/core";

import FontAwesome from "react-fontawesome";

const ROTATION_CHANGE_SUB = gql`
  subscription RotationChanged($simulatorId: ID) {
    rotationChange(simulatorId: $simulatorId) {
      id
      direction {
        x
        y
        z
      }
      rotation {
        yaw
        pitch
        roll
      }
      rotationDelta {
        yaw
        pitch
        roll
      }
      rotationRequired {
        yaw
        pitch
        roll
      }
      manualThrusters
      rotationSpeed
      movementSpeed
      damage {
        damaged
        report
      }
      power {
        power
        powerLevels
      }
    }
  }
`;

class ThrusterCore extends Component {
  rotationSubscription = null;
  componentWillReceiveProps(nextProps) {
    if (!this.rotationSubscription && !nextProps.data.loading) {
      this.rotationSubscription = nextProps.data.subscribeToMore({
        document: ROTATION_CHANGE_SUB,
        variables: { simulatorId: nextProps.simulator.id },
        updateQuery: (previousResult, { subscriptionData }) => {
          return Object.assign({}, previousResult, {
            thrusters: [subscriptionData.data.rotationChange]
          });
        }
      });
    }
  }
  componentWillUnmount() {
    this.rotationSubscription && this.rotationSubscription();
  }
  toggleManualThrusters = () => {};
  setRequiredRotation = (which, value) => {
    const mutation = gql`
      mutation SetRequiredThrusters($id: ID!, $rotation: RotationInput) {
        requiredRotationSet(id: $id, rotation: $rotation)
      }
    `;
    const thrusters = this.props.data.thrusters[0];
    const rotation = Object.assign(
      {},
      {
        yaw: thrusters.rotationRequired.yaw,
        pitch: thrusters.rotationRequired.pitch,
        roll: thrusters.rotationRequired.roll
      }
    );
    rotation[which] = value;
    const variables = {
      id: thrusters.id,
      rotation
    };
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  render() {
    if (this.props.data.loading || !this.props.data.thrusters) return null;
    const thrusters = this.props.data.thrusters[0];
    if (!thrusters) return
No Thrusters
;
    return (
      <Container className="thrustersCore" fluid>
        {/*<input type="checkbox" onClick={this.toggleManualThrusters} /> Manual Thrusters*/}
        <Row>
          <Col sm={4}>Yaw</Col>
          <Col sm={4}>Pitch</Col>
          <Col sm={4}>Roll</Col>
          <Col sm={4}>
            <OutputField>{Math.round(thrusters.rotation.yaw)}</OutputField>
          </Col>
          <Col sm={4}>
            <OutputField>{Math.round(thrusters.rotation.pitch)}</OutputField>
          </Col>
          <Col sm={4}>
            <OutputField>{Math.round(thrusters.rotation.roll)}</OutputField>
          </Col>
          <Col sm={4}>
            <InputField
              alert={
                Math.round(thrusters.rotation.yaw) !==
                Math.round(thrusters.rotationRequired.yaw)
              }
              prompt="What is the required yaw?"
              onClick={value => {
                this.setRequiredRotation("yaw", value);
              }}
            >
              {Math.round(thrusters.rotationRequired.yaw)}
            </InputField>
          </Col>
          <Col sm={4}>
            <InputField
              alert={
                Math.round(thrusters.rotation.pitch) !==
                Math.round(thrusters.rotationRequired.pitch)
              }
              prompt="What is the required pitch?"
              onClick={value => {
                this.setRequiredRotation("pitch", value);
              }}
            >
              {Math.round(thrusters.rotationRequired.pitch)}
            </InputField>
          </Col>
          <Col sm={4}>
            <InputField
              alert={
                Math.round(thrusters.rotation.roll) !==
                Math.round(thrusters.rotationRequired.roll)
              }
              prompt="What is the required roll?"
              onClick={value => {
                this.setRequiredRotation("roll", value);
              }}
            >
              {Math.round(thrusters.rotationRequired.roll)}
            </InputField>
          </Col>
          <ThrusterArrow
            name="arrow-circle-down"
            value={
              thrusters.direction.z < 0 ? Math.abs(thrusters.direction.z) : 0
            }
          />
          <ThrusterArrow
            name="arrow-up"
            value={
              thrusters.direction.y > 0 ? Math.abs(thrusters.direction.y) : 0
            }
          />
          <ThrusterArrow
            name="arrow-circle-up"
            value={
              thrusters.direction.z > 0 ? Math.abs(thrusters.direction.z) : 0
            }
          />
          <ThrusterArrow
            name="arrow-left"
            value={
              thrusters.direction.x < 0 ? Math.abs(thrusters.direction.x) : 0
            }
          />
          <ThrusterArrow
            name="arrow-down"
            value={
              thrusters.direction.y < 0 ? Math.abs(thrusters.direction.y) : 0
            }
          />
          <ThrusterArrow
            name="arrow-right"
            value={
              thrusters.direction.x > 0 ? Math.abs(thrusters.direction.x) : 0
            }
          />
        </Row>
        <Row>
          <Col sm={6}>
            Rotation Speed
            <Mutation
              mutation={gql`
                mutation UpdateThrusterRotation($id: ID!, $speed: Float!) {
                  setThrusterRotationSpeed(id: $id, speed: $speed)
                }
              `}
            >
              {action => (
                <Input
                  type="select"
                  style={{ height: "18px" }}
                  value={thrusters.rotationSpeed}
                  onChange={e => {
                    action({
                      variables: { id: thrusters.id, speed: e.target.value }
                    });
                  }}
                >
                  <option value={0}>0</option>
                  <option value={0.2}>0.2</option>
                  <option value={0.5}>0.5</option>
                  <option value={1}>1</option>
                  <option value={2}>2</option>
                  <option value={3}>3</option>
                  <option value={4}>4</option>
                  <option value={5}>5</option>
                  <option value={6}>6</option>
                  <option value={7}>7</option>
                  <option value={8}>8</option>
                  <option value={9}>9</option>
                  <option value={10}>10 - Fast</option>
                </Input>
              )}
            </Mutation>
          </Col>
          <Col sm={6}>
            Movement Speed (Sensors Auto-thrusters)
            <Mutation
              mutation={gql`
                mutation UpdateThrusterMovement($id: ID!, $speed: Float!) {
                  setThrusterMovementSpeed(id: $id, speed: $speed)
                }
              `}
            >
              {action => (
                <Input
                  type="select"
                  style={{ height: "18px" }}
                  value={thrusters.movementSpeed}
                  onChange={e => {
                    action({
                      variables: { id: thrusters.id, speed: e.target.value }
                    });
                  }}
                >
                  <option value={0}>0</option>
                  <option value={0.2}>0.2</option>
                  <option value={0.5}>0.5</option>
                  <option value={1}>1</option>
                  <option value={2}>2</option>
                  <option value={3}>3</option>
                  <option value={4}>4</option>
                  <option value={5}>5</option>
                  <option value={6}>6</option>
                  <option value={7}>7</option>
                  <option value={8}>8</option>
                  <option value={9}>9</option>
                  <option value={10}>10 - Fast</option>
                </Input>
              )}
            </Mutation>
          </Col>
        </Row>
      </Container>
    );
  }
}

const ThrusterArrow = ({ name, value }) => {
  return (
    <Col sm={4} className="thruster-symbol">
      <FontAwesome
        name={name}
        style={{
          color: `rgb(${Math.round(value * 255)},${Math.round(
            value * 255
          )},${Math.round(value * 255)})`
        }}
      />
    </Col>
  );
};

const THRUSTER_QUERY = gql`
  query Thrusters($simulatorId: ID) {
    thrusters(simulatorId: $simulatorId) {
      id
      direction {
        x
        y
        z
      }
      rotation {
        yaw
        pitch
        roll
      }
      rotationDelta {
        yaw
        pitch
        roll
      }
      rotationRequired {
        yaw
        pitch
        roll
      }
      manualThrusters
      rotationSpeed
      movementSpeed
      damage {
        damaged
        report
      }
      power {
        power
        powerLevels
      }
    }
  }
`;

export default graphql(THRUSTER_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: { simulatorId: ownProps.simulator.id }
  })
})(withApollo(ThrusterCore));
<commit_msg>Make thrusters icons a bit bigger on core<commit_after>import React, { Component } from "react";
import gql from "graphql-tag";
import { Mutation, graphql, withApollo } from "react-apollo";
import { Container, Row, Col, Input } from "reactstrap";
import { InputField, OutputField } from "../../generic/core";
import SubscriptionHelper from "../../../helpers/subscriptionHelper";

import FontAwesome from "react-fontawesome";

const ROTATION_CHANGE_SUB = gql`
  subscription RotationChanged($simulatorId: ID) {
    rotationChange(simulatorId: $simulatorId) {
      id
      direction {
        x
        y
        z
      }
      rotation {
        yaw
        pitch
        roll
      }
      rotationDelta {
        yaw
        pitch
        roll
      }
      rotationRequired {
        yaw
        pitch
        roll
      }
      manualThrusters
      rotationSpeed
      movementSpeed
      damage {
        damaged
        report
      }
      power {
        power
        powerLevels
      }
    }
  }
`;

class ThrusterCore extends Component {
  toggleManualThrusters = () => {};
  setRequiredRotation = (which, value) => {
    const mutation = gql`
      mutation SetRequiredThrusters($id: ID!, $rotation: RotationInput) {
        requiredRotationSet(id: $id, rotation: $rotation)
      }
    `;
    const thrusters = this.props.data.thrusters[0];
    const rotation = Object.assign(
      {},
      {
        yaw: thrusters.rotationRequired.yaw,
        pitch: thrusters.rotationRequired.pitch,
        roll: thrusters.rotationRequired.roll
      }
    );
    rotation[which] = value;
    const variables = {
      id: thrusters.id,
      rotation
    };
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  render() {
    if (this.props.data.loading || !this.props.data.thrusters) return null;
    const thrusters = this.props.data.thrusters[0];
    if (!thrusters) return
No Thrusters
;
    return (
      <Container className="thrustersCore" fluid>
        <SubscriptionHelper
          subscribe={() =>
            this.props.data.subscribeToMore({
              document: ROTATION_CHANGE_SUB,
              variables: { simulatorId: this.props.simulator.id },
              updateQuery: (previousResult, { subscriptionData }) => {
                return Object.assign({}, previousResult, {
                  thrusters: [subscriptionData.data.rotationChange]
                });
              }
            })
          }
        />
        {/*<input type="checkbox" onClick={this.toggleManualThrusters} /> Manual Thrusters*/}
        <Row>
          <Col sm={4}>Yaw</Col>
          <Col sm={4}>Pitch</Col>
          <Col sm={4}>Roll</Col>
          <Col sm={4}>
            <OutputField>{Math.round(thrusters.rotation.yaw)}</OutputField>
          </Col>
          <Col sm={4}>
            <OutputField>{Math.round(thrusters.rotation.pitch)}</OutputField>
          </Col>
          <Col sm={4}>
            <OutputField>{Math.round(thrusters.rotation.roll)}</OutputField>
          </Col>
          <Col sm={4}>
            <InputField
              alert={
                Math.round(thrusters.rotation.yaw) !==
                Math.round(thrusters.rotationRequired.yaw)
              }
              prompt="What is the required yaw?"
              onClick={value => {
                this.setRequiredRotation("yaw", value);
              }}
            >
              {Math.round(thrusters.rotationRequired.yaw)}
            </InputField>
          </Col>
          <Col sm={4}>
            <InputField
              alert={
                Math.round(thrusters.rotation.pitch) !==
                Math.round(thrusters.rotationRequired.pitch)
              }
              prompt="What is the required pitch?"
              onClick={value => {
                this.setRequiredRotation("pitch", value);
              }}
            >
              {Math.round(thrusters.rotationRequired.pitch)}
            </InputField>
          </Col>
          <Col sm={4}>
            <InputField
              alert={
                Math.round(thrusters.rotation.roll) !==
                Math.round(thrusters.rotationRequired.roll)
              }
              prompt="What is the required roll?"
              onClick={value => {
                this.setRequiredRotation("roll", value);
              }}
            >
              {Math.round(thrusters.rotationRequired.roll)}
            </InputField>
          </Col>
          <ThrusterArrow
            name="arrow-circle-down"
            value={
              thrusters.direction.z < 0 ? Math.abs(thrusters.direction.z) : 0
            }
          />
          <ThrusterArrow
            name="arrow-up"
            value={
              thrusters.direction.y > 0 ? Math.abs(thrusters.direction.y) : 0
            }
          />
          <ThrusterArrow
            name="arrow-circle-up"
            value={
              thrusters.direction.z > 0 ? Math.abs(thrusters.direction.z) : 0
            }
          />
          <ThrusterArrow
            name="arrow-left"
            value={
              thrusters.direction.x < 0 ? Math.abs(thrusters.direction.x) : 0
            }
          />
          <ThrusterArrow
            name="arrow-down"
            value={
              thrusters.direction.y < 0 ? Math.abs(thrusters.direction.y) : 0
            }
          />
          <ThrusterArrow
            name="arrow-right"
            value={
              thrusters.direction.x > 0 ? Math.abs(thrusters.direction.x) : 0
            }
          />
        </Row>
        <Row>
          <Col sm={6}>
            Rotation Speed
            <Mutation
              mutation={gql`
                mutation UpdateThrusterRotation($id: ID!, $speed: Float!) {
                  setThrusterRotationSpeed(id: $id, speed: $speed)
                }
              `}
            >
              {action => (
                <Input
                  type="select"
                  style={{ height: "18px" }}
                  value={thrusters.rotationSpeed}
                  onChange={e => {
                    action({
                      variables: { id: thrusters.id, speed: e.target.value }
                    });
                  }}
                >
                  <option value={0}>0</option>
                  <option value={0.2}>0.2</option>
                  <option value={0.5}>0.5</option>
                  <option value={1}>1</option>
                  <option value={2}>2</option>
                  <option value={3}>3</option>
                  <option value={4}>4</option>
                  <option value={5}>5</option>
                  <option value={6}>6</option>
                  <option value={7}>7</option>
                  <option value={8}>8</option>
                  <option value={9}>9</option>
                  <option value={10}>10 - Fast</option>
                </Input>
              )}
            </Mutation>
          </Col>
          <Col sm={6}>
            Movement Speed (Sensors Auto-thrusters)
            <Mutation
              mutation={gql`
                mutation UpdateThrusterMovement($id: ID!, $speed: Float!) {
                  setThrusterMovementSpeed(id: $id, speed: $speed)
                }
              `}
            >
              {action => (
                <Input
                  type="select"
                  style={{ height: "18px" }}
                  value={thrusters.movementSpeed}
                  onChange={e => {
                    action({
                      variables: { id: thrusters.id, speed: e.target.value }
                    });
                  }}
                >
                  <option value={0}>0</option>
                  <option value={0.2}>0.2</option>
                  <option value={0.5}>0.5</option>
                  <option value={1}>1</option>
                  <option value={2}>2</option>
                  <option value={3}>3</option>
                  <option value={4}>4</option>
                  <option value={5}>5</option>
                  <option value={6}>6</option>
                  <option value={7}>7</option>
                  <option value={8}>8</option>
                  <option value={9}>9</option>
                  <option value={10}>10 - Fast</option>
                </Input>
              )}
            </Mutation>
          </Col>
        </Row>
      </Container>
    );
  }
}

const ThrusterArrow = ({ name, value }) => {
  return (
    <Col sm={4} className="thruster-symbol">
      <FontAwesome
        name={name}
        size="lg"
        style={{
          margin: "2px",
          color: `rgb(${Math.round(value * 255)},${Math.round(
            value * 255
          )},${Math.round(value * 255)})`
        }}
      />
    </Col>
  );
};

const THRUSTER_QUERY = gql`
  query Thrusters($simulatorId: ID) {
    thrusters(simulatorId: $simulatorId) {
      id
      direction {
        x
        y
        z
      }
      rotation {
        yaw
        pitch
        roll
      }
      rotationDelta {
        yaw
        pitch
        roll
      }
      rotationRequired {
        yaw
        pitch
        roll
      }
      manualThrusters
      rotationSpeed
      movementSpeed
      damage {
        damaged
        report
      }
      power {
        power
        powerLevels
      }
    }
  }
`;

export default graphql(THRUSTER_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: { simulatorId: ownProps.simulator.id }
  })
})(withApollo(ThrusterCore));
<|endoftext|>


<commit_before>/*
 Copyright 2017 New Vector Ltd.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClient} from 'matrix-js-sdk';
import FlairStore from '../../../stores/FlairStore';
import dis from '../../../dispatcher';

class FlairAvatar extends React.Component {
    constructor() {
        super();
        this.onClick = this.onClick.bind(this);
    }

    onClick(ev) {
        ev.preventDefault();
        // Don't trigger onClick of parent element
        ev.stopPropagation();
        dis.dispatch({
            action: 'view_group',
            group_id: this.props.groupProfile.groupId,
        });
    }

    render() {
        const httpUrl = this.context.matrixClient.mxcUrlToHttp(
            this.props.groupProfile.avatarUrl, 16, 16, 'scale', false);
        const tooltip = this.props.groupProfile.name ?
            `${this.props.groupProfile.name} (${this.props.groupProfile.groupId})`:
            this.props.groupProfile.groupId;
        return ;
    }
}

FlairAvatar.propTypes = {
    groupProfile: PropTypes.shape({
        groupId: PropTypes.string.isRequired,
        name: PropTypes.string,
        avatarUrl: PropTypes.string.isRequired,
    }),
};

FlairAvatar.contextTypes = {
    matrixClient: PropTypes.instanceOf(MatrixClient).isRequired,
};

export default class Flair extends React.Component {
    constructor() {
        super();
        this.state = {
            profiles: [],
        };
    }

    componentWillUnmount() {
        this._unmounted = true;
    }

    componentWillMount() {
        this._unmounted = false;
        this._generateAvatars(this.props.groups);
    }

    componentWillReceiveProps(newProps) {
        this._generateAvatars(newProps.groups);
    }

    async _getGroupProfiles(groups) {
        const profiles = [];
        for (const groupId of groups) {
            let groupProfile = null;
            try {
                groupProfile = await FlairStore.getGroupProfileCached(this.context.matrixClient, groupId);
            } catch (err) {
                console.error('Could not get profile for group', groupId, err);
            }
            profiles.push(groupProfile);
        }
        return profiles.filter((p) => p !== null);
    }

    async _generateAvatars(groups) {
        if (!groups || groups.length === 0) {
            return;
        }
        const profiles = await this._getGroupProfiles(groups);
        if (!this.unmounted) {
            this.setState({
                profiles: profiles.filter((profile) => {
                    return profile ? profile.avatarUrl : false;
                }),
            });
        }
    }

    render() {
        if (this.state.profiles.length === 0) {
            return
;
        }
        const avatars = this.state.profiles.map((profile, index) => {
            return <FlairAvatar key={index} groupProfile={profile} />;
        });
        return (

                { avatars }

        );
    }
}

Flair.propTypes = {
    groups: PropTypes.arrayOf(PropTypes.string),
};

// TODO: We've decided that all components should follow this pattern, which means removing withMatrixClient and using
// this.context.matrixClient everywhere instead of this.props.matrixClient.
// See https://github.com/vector-im/riot-web/issues/4951.
Flair.contextTypes = {
    matrixClient: PropTypes.instanceOf(MatrixClient).isRequired,
};
<commit_msg>show flair container when no profiles loaded to ensure same height<commit_after>/*
 Copyright 2017 New Vector Ltd.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClient} from 'matrix-js-sdk';
import FlairStore from '../../../stores/FlairStore';
import dis from '../../../dispatcher';

class FlairAvatar extends React.Component {
    constructor() {
        super();
        this.onClick = this.onClick.bind(this);
    }

    onClick(ev) {
        ev.preventDefault();
        // Don't trigger onClick of parent element
        ev.stopPropagation();
        dis.dispatch({
            action: 'view_group',
            group_id: this.props.groupProfile.groupId,
        });
    }

    render() {
        const httpUrl = this.context.matrixClient.mxcUrlToHttp(
            this.props.groupProfile.avatarUrl, 16, 16, 'scale', false);
        const tooltip = this.props.groupProfile.name ?
            `${this.props.groupProfile.name} (${this.props.groupProfile.groupId})`:
            this.props.groupProfile.groupId;
        return ;
    }
}

FlairAvatar.propTypes = {
    groupProfile: PropTypes.shape({
        groupId: PropTypes.string.isRequired,
        name: PropTypes.string,
        avatarUrl: PropTypes.string.isRequired,
    }),
};

FlairAvatar.contextTypes = {
    matrixClient: PropTypes.instanceOf(MatrixClient).isRequired,
};

export default class Flair extends React.Component {
    constructor() {
        super();
        this.state = {
            profiles: [],
        };
    }

    componentWillUnmount() {
        this._unmounted = true;
    }

    componentWillMount() {
        this._unmounted = false;
        this._generateAvatars(this.props.groups);
    }

    componentWillReceiveProps(newProps) {
        this._generateAvatars(newProps.groups);
    }

    async _getGroupProfiles(groups) {
        const profiles = [];
        for (const groupId of groups) {
            let groupProfile = null;
            try {
                groupProfile = await FlairStore.getGroupProfileCached(this.context.matrixClient, groupId);
            } catch (err) {
                console.error('Could not get profile for group', groupId, err);
            }
            profiles.push(groupProfile);
        }
        return profiles.filter((p) => p !== null);
    }

    async _generateAvatars(groups) {
        if (!groups || groups.length === 0) {
            return;
        }
        const profiles = await this._getGroupProfiles(groups);
        if (!this.unmounted) {
            this.setState({
                profiles: profiles.filter((profile) => {
                    return profile ? profile.avatarUrl : false;
                }),
            });
        }
    }

    render() {
        if (this.state.profiles.length === 0) {
            return ;
        }
        const avatars = this.state.profiles.map((profile, index) => {
            return <FlairAvatar key={index} groupProfile={profile} />;
        });
        return (

                { avatars }

        );
    }
}

Flair.propTypes = {
    groups: PropTypes.arrayOf(PropTypes.string),
};

// TODO: We've decided that all components should follow this pattern, which means removing withMatrixClient and using
// this.context.matrixClient everywhere instead of this.props.matrixClient.
// See https://github.com/vector-im/riot-web/issues/4951.
Flair.contextTypes = {
    matrixClient: PropTypes.instanceOf(MatrixClient).isRequired,
};
<|endoftext|>


<commit_before>import React, {Component} from 'react';

import MaterialDropdown from 'src/MaterialDropdown';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import Theme from 'src/Theme';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Dropdown.json';

import 'sass/containers/app/modules/layout/MaterialDropdownExamples.scss';

export default class MaterialDropdownExamples extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (

MaterialDropdown

                    A MaterialDropdown.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                <MaterialDropdown theme={Theme.HIGHLIGHT}
                                                  triggerValue="Material Dropdown">

MaterialDropdown content

                                </MaterialDropdown>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};<commit_msg>update MaterialDropdown examples<commit_after>import React, {Component} from 'react';

import MaterialDropdown from 'src/MaterialDropdown';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import Theme from 'src/Theme';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Dropdown.json';

import 'sass/containers/app/modules/layout/MaterialDropdownExamples.scss';

export default class MaterialDropdownExamples extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (

MaterialDropdown

                    A MaterialDropdown.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                <MaterialDropdown theme={Theme.HIGHLIGHT}
                                                  label="Label"
                                                  triggerValue="Material Dropdown">

MaterialDropdown content

                                </MaterialDropdown>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};<|endoftext|>


<commit_before>/**
 * Converts an element or fragment into a string of HTML with no extra whitespaces.
 *
 * e.g. stringify(dom.create(`<div> <strong> Hello hello </strong> </div>`))
 * returns '
Hello hello
'
 *
 * @param {Element|DocumentFragment} el
 * @returns {string}
 */
function stringify(el) {
  var isDocumentFragment = el.nodeType === 11,
    // Clone for in-place white-space removal.
    clone = isDocumentFragment ? el.firstElementChild.cloneNode(true) : el.cloneNode(true),
    walker = document.createTreeWalker(clone, NodeFilter.SHOW_ALL);

  while (walker.nextNode()) {
    // remove white spaces
    walker.currentNode.textContent.replace(/[^\S+]+\s[^\S+]+/g, '');
  }
  // remove line breaks
  return clone.outerHTML.replace(/(\r|\n)\s*/g, '');
}

module.exports = stringify;
<commit_msg>Remove stringify.<commit_after><|endoftext|>


<commit_before>import path from './path.js';

/**
 * Draw a line between `start` and `end`.
 *
 * @public
 * @method drawLine
 * @memberof CornerstoneTools.Drawing
 *
 * @param {CanvasRenderingContext2D} context
 * @param {HTMLElement} element - The DOM Element to draw on
 * @param {Object} start - `{ x, y } in either pixel or canvas coordinates.
 * @param {Object} end - `{ x, y }` in either pixel or canvas coordinates.
 * @param {Object} options - See {@link path}
 * @param {String} [coordSystem='pixel'] - Can be "pixel" (default) or "canvas". The coordinate
 *     system of the points passed in to the function. If "pixel" then cornerstone.pixelToCanvas
 *     is used to transform the points from pixel to canvas coordinates.
 */
export function drawLine(
  context,
  element,
  start,
  end,
  options,
  coordSystem = 'pixel'
) {
  path(context, options, context => {
    if (coordSystem === 'pixel') {
      const cornerstone = external.cornerstone;

      start = cornerstone.pixelToCanvas(element, start);
      end = cornerstone.pixelToCanvas(element, end);
    }

    context.moveTo(start.x, start.y);
    context.lineTo(end.x, end.y);
  });
}
<commit_msg>default function :point:<commit_after>import path from './path.js';

/**
 * Draw a line between `start` and `end`.
 *
 * @public
 * @method drawLine
 * @memberof CornerstoneTools.Drawing
 *
 * @param {CanvasRenderingContext2D} context
 * @param {HTMLElement} element - The DOM Element to draw on
 * @param {Object} start - `{ x, y } in either pixel or canvas coordinates.
 * @param {Object} end - `{ x, y }` in either pixel or canvas coordinates.
 * @param {Object} options - See {@link path}
 * @param {String} [coordSystem='pixel'] - Can be "pixel" (default) or "canvas". The coordinate
 *     system of the points passed in to the function. If "pixel" then cornerstone.pixelToCanvas
 *     is used to transform the points from pixel to canvas coordinates.
 */
export default function drawLine(
  context,
  element,
  start,
  end,
  options,
  coordSystem = 'pixel'
) {
  path(context, options, context => {
    if (coordSystem === 'pixel') {
      const cornerstone = external.cornerstone;

      start = cornerstone.pixelToCanvas(element, start);
      end = cornerstone.pixelToCanvas(element, end);
    }

    context.moveTo(start.x, start.y);
    context.lineTo(end.x, end.y);
  });
}
<|endoftext|>


<commit_before>'use strict';
import React from 'react';
import { Dropdown } from 'openaq-design-system';

var ShareBtn = React.createClass({
  displayName: 'ShareBtn',

  propTypes: {
  },

  render: function () {
    return (
      <Dropdown
        triggerElement='button'
        triggerClassName='button-inpage-share'
        triggerTitle='Show/hide share options'
        triggerText='Share' >

<a className='drop__menu-item share-opt-twitter' href={`https://twitter.com/share?url=${window.location.href}`} target='_blank' title='Share on twitter' data-hook='dropdown:close'>Twitter

<a className='drop__menu-item share-opt-facebook' href={`http://facebook.com/sharer.php?u=${window.location.href}`} target='_blank' title='Share on Facebook' data-hook='dropdown:close'>Facebook

      </Dropdown>
    );
  }
});

module.exports = ShareBtn;
<commit_msg>Encodes the current URL for sharing<commit_after>'use strict';
import React from 'react';
import { Dropdown } from 'openaq-design-system';

var ShareBtn = React.createClass({
  displayName: 'ShareBtn',

  propTypes: {
  },

  render: function () {

    var encodedURI = encodeURIComponent(window.location.href);

    return (
      <Dropdown
        triggerElement='button'
        triggerClassName='button-inpage-share'
        triggerTitle='Show/hide share options'
        triggerText='Share' >

<a className='drop__menu-item share-opt-twitter' href={`https://twitter.com/share?url=${encodedURI}`} target='_blank' title='Share on twitter' data-hook='dropdown:close'>Twitter

<a className='drop__menu-item share-opt-facebook' href={`http://facebook.com/sharer.php?u=${encodedURI}`} target='_blank' title='Share on Facebook' data-hook='dropdown:close'>Facebook

      </Dropdown>
    );
  }
});

module.exports = ShareBtn;
<|endoftext|>


<commit_before>/*
 * grunt
 * https://github.com/cowboy/grunt
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 * http://benalman.com/about/license/
 */

var fs = require('fs');
var path = require('path');
var glob = require('glob');

// Return an array of all file paths that match the given wildcard patterns.
exports.expand = function() {
  // Use the first argument if it's an Array, otherwise convert the arguments
  // object to an array and use that.
  var patterns = arguments[0] instanceof Array ? arguments[0] : [].slice.call(arguments);
  // Generate a should-be-unique number.
  var uid = +new Date();
  // Return a flattened, uniqued array of matching file paths.
  return _(patterns).chain().flatten().map(function(pattern) {
    // Just return the pattern if it's an internal directive.
    if (task.getDirectiveParts(pattern)) { return pattern; }
    // Otherwise, expand paths.
    return glob.globSync(pattern, glob.GLOB_DEFAULT | glob.GLOB_NOCHECK);
  }).flatten().uniq(false, function(filepath) {
    // Only unique file paths, but don't unique <something> directives, in case
    // they are repeated intentionally.
    return task.getDirectiveParts(filepath) ? ++uid : filepath;
  }).filter(function(filepath) {
    // Just return the filepath if it's an internal directive.
    if (task.getDirectiveParts(filepath)) { return filepath; }
    try {
      return fs.statSync(filepath).mode !== 16877;
    } catch(e) {
      throw {name: 'TaskError', message: e.message};
    }
  }).value();
};

// Like mkdir -p. Create a directory and any intermediary directories.
exports.mkdir = function(dirpath) {
  var parts = [];
  dirpath.split('/').forEach(function(part) {
    parts.push(part);
    var subpath = parts.join('/');
    if (part && !path.existsSync(subpath)) {
      fs.mkdirSync(subpath, '0755');
    }
  });
};

// Recurse into a directory, executing callback for each file.
exports.recurse = function(rootdir, callback, subdir) {
  var abspath = subdir ? path.join(rootdir, subdir) : rootdir;
  fs.readdirSync(abspath).forEach(function(filename) {
    var filepath = path.join(abspath, filename);
    if (fs.statSync(filepath).mode === 16877) {
      exports.recurse(rootdir, callback, path.join(subdir, filename));
    } else {
      callback(path.join(rootdir, subdir, filename), rootdir, subdir, filename);
    }
  });
};

// Search for a filename in the given directory or all parent directories.
exports.findup = function(rootdir, filename) {
  var filepath = path.join(rootdir, filename);
  if (path.existsSync(filepath)) {
    return filepath;
  } else if (rootdir === '/') {
    return false;
  } else {
    return exports.findup(path.resolve(rootdir, '..'), filename);
  }
};

// Write a file.
exports.write = function(filepath, contents) {
  var nowrite = option('no-write');
  verbose.write((nowrite ? 'Not actually writing ' : 'Writing ') + filepath + '...');
  try {
    if (!nowrite) {
      // Create path, if necessary.
      exports.mkdir(path.dirname(filepath));
      // Actually write file.
      fs.writeFileSync(filepath, contents, 'UTF-8');
    }
    verbose.ok();
    return true;
  } catch(e) {
    verbose.error();
    throw {name: 'TaskError', message: 'Unable to write "' + filepath + '" file (Error code: ' + e.code + ').'};
  }
};

// Read a file, return its contents.
exports.read = function(filepath) {
  var src;
  verbose.write('Reading ' + filepath + '...');
  try {
    src = fs.readFileSync(filepath, 'UTF-8');
    verbose.ok();
    return src;
  } catch(e) {
    verbose.error();
    throw {name: 'TaskError', message: 'Unable to read "' + filepath + '" file (Error code: ' + e.code + ').'};
  }
};

// Read a file, parse its contents, return an object.
exports.readJson = function(filepath) {
  var src = this.read(filepath);
  var result;
  verbose.write('Parsing ' + filepath + '...');
  try {
    result = JSON.parse(src);
    verbose.ok();
    return result;
  } catch(e) {
    verbose.error();
    throw {name: 'TaskError', message: 'Unable to parse "' + filepath + '" file (' + e.message + ').'};
  }
};

// Clear the require cache for all passed filepaths.
exports.clearRequireCache = function() {
  // If a non-string argument is passed, it's an array of filepaths, otherwise
  // each filepath is passed individually.
  var filepaths = typeof arguments[0] !== 'string' ? arguments[0] : [].slice.call(arguments);
  // For each filepath, clear the require cache, if necessary.
  filepaths.forEach(function(filepath) {
    var abspath = path.resolve(filepath);
    if (require.cache[abspath]) {
      verbose.write('Clearing require cache for "' + filepath + '" file...').ok();
      delete require.cache[abspath];
    }
  });
};
<commit_msg>patched grunt file.js<commit_after>/*
 * grunt
 * https://github.com/cowboy/grunt
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 * http://benalman.com/about/license/
 */

var fs = require('fs');
var path = require('path');
var glob = require('glob-sync');

// Return an array of all file paths that match the given wildcard patterns.
exports.expand = function() {
  // Use the first argument if it's an Array, otherwise convert the arguments
  // object to an array and use that.
  var patterns = arguments[0] instanceof Array ? arguments[0] : [].slice.call(arguments);
  // Generate a should-be-unique number.
  var uid = +new Date();
  // Return a flattened, uniqued array of matching file paths.
  return _(patterns).chain().flatten().map(function(pattern) {
    // Just return the pattern if it's an internal directive.
    if (task.getDirectiveParts(pattern)) { return pattern; }
    // Otherwise, expand paths.
    return glob.globSync(pattern);
  }).flatten().uniq(false, function(filepath) {
    // Only unique file paths, but don't unique <something> directives, in case
    // they are repeated intentionally.
    return task.getDirectiveParts(filepath) ? ++uid : filepath;
  }).filter(function(filepath) {
    // Just return the filepath if it's an internal directive.
    if (task.getDirectiveParts(filepath)) { return filepath; }
    try {
      return fs.statSync(filepath).mode !== 16877;
    } catch(e) {
      throw {name: 'TaskError', message: e.message};
    }
  }).value();
};

// Like mkdir -p. Create a directory and any intermediary directories.
exports.mkdir = function(dirpath) {
  var parts = [];
  dirpath.split('/').forEach(function(part) {
    parts.push(part);
    var subpath = parts.join('/');
    if (part && !path.existsSync(subpath)) {
      fs.mkdirSync(subpath, '0755');
    }
  });
};

// Recurse into a directory, executing callback for each file.
exports.recurse = function(rootdir, callback, subdir) {
  var abspath = subdir ? path.join(rootdir, subdir) : rootdir;
  fs.readdirSync(abspath).forEach(function(filename) {
    var filepath = path.join(abspath, filename);
    if (fs.statSync(filepath).mode === 16877) {
      exports.recurse(rootdir, callback, path.join(subdir, filename));
    } else {
      callback(path.join(rootdir, subdir, filename), rootdir, subdir, filename);
    }
  });
};

// Search for a filename in the given directory or all parent directories.
exports.findup = function(rootdir, filename) {
  var filepath = path.join(rootdir, filename);
  if (path.existsSync(filepath)) {
    return filepath;
  } else if (rootdir === '/') {
    return false;
  } else {
    return exports.findup(path.resolve(rootdir, '..'), filename);
  }
};

// Write a file.
exports.write = function(filepath, contents) {
  var nowrite = option('no-write');
  verbose.write((nowrite ? 'Not actually writing ' : 'Writing ') + filepath + '...');
  try {
    if (!nowrite) {
      // Create path, if necessary.
      exports.mkdir(path.dirname(filepath));
      // Actually write file.
      fs.writeFileSync(filepath, contents, 'UTF-8');
    }
    verbose.ok();
    return true;
  } catch(e) {
    verbose.error();
    throw {name: 'TaskError', message: 'Unable to write "' + filepath + '" file (Error code: ' + e.code + ').'};
  }
};

// Read a file, return its contents.
exports.read = function(filepath) {
  var src;
  verbose.write('Reading ' + filepath + '...');
  try {
    src = fs.readFileSync(filepath, 'UTF-8');
    verbose.ok();
    return src;
  } catch(e) {
    verbose.error();
    throw {name: 'TaskError', message: 'Unable to read "' + filepath + '" file (Error code: ' + e.code + ').'};
  }
};

// Read a file, parse its contents, return an object.
exports.readJson = function(filepath) {
  var src = this.read(filepath);
  var result;
  verbose.write('Parsing ' + filepath + '...');
  try {
    result = JSON.parse(src);
    verbose.ok();
    return result;
  } catch(e) {
    verbose.error();
    throw {name: 'TaskError', message: 'Unable to parse "' + filepath + '" file (' + e.message + ').'};
  }
};

// Clear the require cache for all passed filepaths.
exports.clearRequireCache = function() {
  // If a non-string argument is passed, it's an array of filepaths, otherwise
  // each filepath is passed individually.
  var filepaths = typeof arguments[0] !== 'string' ? arguments[0] : [].slice.call(arguments);
  // For each filepath, clear the require cache, if necessary.
  filepaths.forEach(function(filepath) {
    var abspath = path.resolve(filepath);
    if (require.cache[abspath]) {
      verbose.write('Clearing require cache for "' + filepath + '" file...').ok();
      delete require.cache[abspath];
    }
  });
};
<|endoftext|>