<commit_before>'use strict';

angular.module('schwanzen')
  .controller('MainCtrl', function ($scope, $log, $location, $anchorScroll) {

    var gui;
    var Tail;
    var fs;

    // Load node dependencies.  In a try-catch block so that it doesn't break when testing in the browser.
    try {

      gui = require('nw.gui');
      Tail = require('always-tail');
      fs = require('fs');

    }
    catch(err) {

      $log.debug('Unable to load node dependencies, disabling...');

    }

    $scope.tabs = {};

    $scope.tabs['Dynamic Title 1'] = {
      filename:'Dynamic Title 1',
      lines: [
        'Line 1',
        'Line 2'
      ],
      newLines: 0
    };

    $scope.tabs['Dynamic Title 2'] = {
      filename:'Dynamic Title 2',
      lines: [
        'Line 1',
        'Line 2',
        'Line 3',
        'Line 3',
        'Line 4',
        'Line 5',
        'Line 6',
        'Line 7',
        'Line 8',
        'Line 9',
        'Line 10',
        'Line 11'
      ],
      newLines: 5
    };

    $scope.getNewLines = function(tab) {
      if(tab.active) {

        tab.newLines = 0;
        return null;

      }
      else if(tab.newLines == 0) {

          return null;
      }
      else {

        return tab.newLines;

      }
    };

    $scope.addTab = function(file) {

      $scope.tabs[file.filename] = file;

      $scope.$applyAsync();

    };

    $scope.closeTab = function(file) {

      $log.debug('Closing tab %s', file);

      $log.debug($scope.tabs);

      if($scope.tabs[file].tail) {

        $scope.tabs[file].tail.unwatch();
        $scope.tabs[file].tail.closeCurrent(function() {

          $log.debug('Closed file descripter for %s', file.filename);
          delete $scope.tabs[file];

        });

      }
      else {

        delete $scope.tabs[file];

      }

    };

    $scope.status = {

      isopen: false

    };

    $scope.toggled = function(open) {

      $log.log('Dropdown is now: ', open);

    };

    $scope.toggleDropdown = function($event) {

      $event.preventDefault();
      $event.stopPropagation();
      $scope.status.isopen = !$scope.status.isopen;

    };

    $scope.closeApp = function() {

      $log.debug('Closing app...');

      if(gui) {
        gui.App.quit();
      }

    };

    var callDialog = function(dialog, callback) {

      dialog.addEventListener('change', function() {

        var result = dialog.value;
        callback(result);

      }, false);

      dialog.click();

    };

    $scope.scrollToBottom = function(tag) {

      $log.debug('Scrolling to %s', tag);

      //$timeout
      $location.hash(tag);
      //$log.debug(hash);
      $anchorScroll();

    };

    $scope.tailFile = function(fileName) {

      $log.debug('Selected ' + fileName);

      if(Tail) {

        if (!fs.existsSync(fileName)) {

          fs.writeFileSync(fileName, '');

        }

        var tail = new Tail(fileName, '\n', { start: 0, interval: 1000 });

        $log.debug('tail:');
        $log.debug(tail);

        var tailFile = {

          filename: fileName,
          tail: tail,
          lines: [],
          newLines: 0

        };

        tail.on('line', function(data) {

          $log.debug(data);
          tailFile.lines.push(data);
          tailFile.newLines++;
          $scope.scrollToBottom('tabFooter');
          $scope.$apply();

        });

        tail.on('error', function(error) {

          $log.debug('ERROR: ', error);

        });

        tail.watch();

        $log.debug($scope.tabs);

        $log.debug('Pushing tailFile:');
        $log.debug(tailFile);

        $scope.addTab(tailFile);
        //$scope.tabs.push(tailFile);

        $log.debug($scope.tabs);

      }

    };

    $scope.chooseFile = function() {

      $log.debug('Choosing file...');

      /*
       var chooser = $(name);
       chooser.change(function(evt) {
       $log.debug($(this).val());
       });

       chooser.trigger('click');
       */

      //chooseFile('#fileDialog');

      var dialog = document.createElement('input');

      dialog.type = 'file';
      dialog.multiple = 'multiple';

      callDialog(dialog, function(fileName) {

        $scope.tailFile(fileName);

      });

    };

  });
<commit_msg>Added tail file length max.<commit_after>'use strict';

angular.module('schwanzen')
  .controller('MainCtrl', function ($scope, $log, $location, $anchorScroll) {

    var gui;
    var Tail;
    var fs;

    // Load node dependencies.  In a try-catch block so that it doesn't break when testing in the browser.
    try {

      gui = require('nw.gui');
      Tail = require('always-tail');
      fs = require('fs');

    }
    catch(err) {

      $log.debug('Unable to load node dependencies, disabling...');

    }

    $scope.tailLengthMax = 1000;

    $scope.tabs = {};

    $scope.tabs['Dynamic Title 1'] = {
      filename:'Dynamic Title 1',
      lines: [
        'Line 1',
        'Line 2'
      ],
      newLines: 0
    };

    $scope.tabs['Dynamic Title 2'] = {
      filename:'Dynamic Title 2',
      lines: [
        'Line 1',
        'Line 2',
        'Line 3',
        'Line 3',
        'Line 4',
        'Line 5',
        'Line 6',
        'Line 7',
        'Line 8',
        'Line 9',
        'Line 10',
        'Line 11'
      ],
      newLines: 5
    };

    $scope.getNewLines = function(tab) {
      if(tab.active) {

        tab.newLines = 0;
        return null;

      }
      else if(tab.newLines == 0) {

          return null;
      }
      else {

        return tab.newLines;

      }
    };

    $scope.addTab = function(file) {

      $scope.tabs[file.filename] = file;

      $scope.$applyAsync();

    };

    $scope.closeTab = function(file) {

      $log.debug('Closing tab %s', file);

      $log.debug($scope.tabs);

      if($scope.tabs[file].tail) {

        $scope.tabs[file].tail.unwatch();
        $scope.tabs[file].tail.closeCurrent(function() {

          $log.debug('Closed file descripter for %s', file.filename);
          delete $scope.tabs[file];

        });

      }
      else {

        delete $scope.tabs[file];

      }

    };

    $scope.status = {

      isopen: false

    };

    $scope.toggled = function(open) {

      $log.log('Dropdown is now: ', open);

    };

    $scope.toggleDropdown = function($event) {

      $event.preventDefault();
      $event.stopPropagation();
      $scope.status.isopen = !$scope.status.isopen;

    };

    $scope.closeApp = function() {

      $log.debug('Closing app...');

      if(gui) {
        gui.App.quit();
      }

    };

    var callDialog = function(dialog, callback) {

      dialog.addEventListener('change', function() {

        var result = dialog.value;
        callback(result);

      }, false);

      dialog.click();

    };

    $scope.scrollToBottom = function(tag) {

      $log.debug('Scrolling to %s', tag);

      //$timeout
      $location.hash(tag);
      //$log.debug(hash);
      $anchorScroll();

    };

    $scope.tailFile = function(fileName) {

      $log.debug('Selected ' + fileName);

      if(Tail) {

        if (!fs.existsSync(fileName)) {

          fs.writeFileSync(fileName, '');

        }

        var tail = new Tail(fileName, '\n', { start: 0, interval: 1000 });

        $log.debug('tail:');
        $log.debug(tail);

        var tailFile = {

          filename: fileName,
          tail: tail,
          lines: [],
          newLines: 0

        };

        tail.on('line', function(data) {

          $log.debug(data);

          if(tailFile.lines.length > $scope.tailLengthMax) {
            tailFile.lines.shift();
          }
          tailFile.lines.push(data);
          tailFile.newLines++;
          $scope.scrollToBottom('tabFooter');
          $scope.$apply();

        });

        tail.on('error', function(error) {

          $log.debug('ERROR: ', error);

        });

        tail.watch();

        $log.debug($scope.tabs);

        $log.debug('Pushing tailFile:');
        $log.debug(tailFile);

        $scope.addTab(tailFile);
        //$scope.tabs.push(tailFile);

        $log.debug($scope.tabs);

      }

    };

    $scope.chooseFile = function() {

      $log.debug('Choosing file...');

      /*
       var chooser = $(name);
       chooser.change(function(evt) {
       $log.debug($(this).val());
       });

       chooser.trigger('click');
       */

      //chooseFile('#fileDialog');

      var dialog = document.createElement('input');

      dialog.type = 'file';
      dialog.multiple = 'multiple';

      callDialog(dialog, function(fileName) {

        $scope.tailFile(fileName);

      });

    };

  });
<|endoftext|>


<commit_before>const map = {
    //steemit
    ned: 'steemit',
    justinw: 'steemit',
    elipowell: 'steemit',
    vandeberg: 'steemit',
    gerbino: 'steemit',
    andrarchy: 'steemit',
    roadscape: 'steemit',
    steemitblog: 'steemit',
    steemitdev: 'steemit',

    /*
    //steem monsters
    steemmonsters: 'sm',
    'steem.monsters': 'sm',
    aggroed: 'sm',
    yabapmatt: 'sm',
*/
};

export default map;
<commit_msg>add justinsunsteemit as an official account<commit_after>const map = {
    //steemit
    ned: 'steemit',
    justinw: 'steemit',
    elipowell: 'steemit',
    vandeberg: 'steemit',
    gerbino: 'steemit',
    andrarchy: 'steemit',
    roadscape: 'steemit',
    steemitblog: 'steemit',
    steemitdev: 'steemit',
    justinsunsteemit: 'steemit',

    /*
    //steem monsters
    steemmonsters: 'sm',
    'steem.monsters': 'sm',
    aggroed: 'sm',
    yabapmatt: 'sm',
*/
};

export default map;
<|endoftext|>


<commit_before>const { assign } = require('lodash')

const formLabels = require('./labels')
const metaData = require('../../lib/metadata')
const { transformContactToOption, transformObjectToOption } = require('../transformers')

const interactionSortForm = {
  method: 'get',
  class: 'c-collection__sort-form js-AutoSubmit',
  hideFormActions: true,
  hiddenFields: { custom: true },
  children: [
    {
      macroName: 'MultipleChoiceField',
      label: 'Sort by',
      name: 'sortby',
      modifier: ['small', 'inline', 'light'],
      options: [
        { value: 'date:desc', label: 'Newest' },
        { value: 'date:asc', label: 'Oldest' },
        { value: 'company.name:asc', label: 'Company: A-Z' },
        { value: 'company.name:desc', label: 'Company: Z-A' },
        { value: 'contact.name:asc', label: 'Contact: A-Z' },
        { value: 'contact.name:desc', label: 'Contact: Z-A' },
        { value: 'dit_adviser.name:asc', label: 'Adviser: A-Z' },
        { value: 'dit_adviser.name:desc', label: 'Adviser: Z-A' },
        { value: 'subject:asc', label: 'Subject: A-Z' },
        { value: 'subject:desc', label: 'Subject: Z-A' },
      ],
    },
  ],
}

const selectKindFormConfig = function ({
  returnLink,
  errors = [],
}) {
  return {
    buttonText: 'Continue',
    errors,
    children: [
      {
        macroName: 'MultipleChoiceField',
        type: 'radio',
        label: 'What would you like to record?',
        name: 'kind',
        options: [{
          value: 'interaction',
          label: 'A standard interaction',
          hint: 'For example, an email, phone call or meeting',
        }, {
          value: 'service_delivery',
          label: 'A service that you have provided',
          hint: 'For example, account management, a significant assist or an event',
        }],
      },
    ],
  }
}

const interactionFields = {
  contact (contacts) {
    return {
      macroName: 'MultipleChoiceField',
      name: 'contact',
      initialOption: '-- Select contact --',
      options () {
        return contacts.map(transformContactToOption)
      },
    }
  },
  provider: {
    macroName: 'MultipleChoiceField',
    name: 'dit_team',
    initialOption: '-- Select provider --',
    options () {
      return metaData.teams.map(transformObjectToOption)
    },
  },
  service (services) {
    return {
      macroName: 'MultipleChoiceField',
      name: 'service',
      initialOption: '-- Select service --',
      options () {
        return services.map(transformObjectToOption)
      },
    }
  },
  subject: {
    macroName: 'TextField',
    name: 'subject',
  },
  notes: {
    macroName: 'TextField',
    type: 'textarea',
    name: 'notes',
  },
  date: {
    macroName: 'DateFieldset',
    name: 'date',
  },
  adviser (advisers) {
    return {
      macroName: 'MultipleChoiceField',
      name: 'dit_adviser',
      initialOption: '-- Select adviser --',
      options () {
        return advisers.map(transformContactToOption)
      },
    }
  },
  communicationChannel: {
    macroName: 'MultipleChoiceField',
    name: 'communication_channel',
    initialOption: '-- Select communication channel --',
    options () {
      return metaData.communicationChannelOptions.map(transformObjectToOption)
    },
  },
}

const interactionFormConfig = function ({
  returnLink,
  contacts = [],
  advisers = [],
  services = [],
  hiddenFields,
}) {
  return {
    returnLink,
    buttonText: 'Save',
    returnText: 'Cancel',
    hiddenFields,
    children: [
      interactionFields.contact(contacts),
      interactionFields.provider,
      interactionFields.service(services),
      interactionFields.subject,
      interactionFields.notes,
      interactionFields.date,
      interactionFields.adviser(advisers),
      interactionFields.communicationChannel,
    ].map(field => {
      return assign(field, {
        label: formLabels.interaction[field.name],
      })
    }),
  }
}

const serviceDeliveryFormConfig = function ({
  returnLink,
  contacts = [],
  advisers = [],
  services = [],
  events = [],
  hiddenFields,
}) {
  return {
    returnLink,
    buttonText: 'Save',
    returnText: 'Cancel',
    hiddenFields,
    children: [
      interactionFields.contact(contacts),
      interactionFields.provider,
      interactionFields.adviser(advisers),
      // TODO this will be going once interactions are within events
      {
        macroName: 'MultipleChoiceField',
        type: 'radio',
        name: 'is_event',
        optional: true,
        modifier: 'inline',
        options: [
          {
            label: 'Yes',
            value: 'true',
          },
          {
            label: 'No',
            value: 'false',
          },
        ],
      },
      {
        macroName: 'MultipleChoiceField',
        name: 'event',
        initialOption: '-- Select event --',
        options () {
          return events.map(transformObjectToOption)
        },
        modifier: 'subfield',
        condition: {
          name: 'is_event',
          value: 'true',
        },
      },
      interactionFields.service(services),
      interactionFields.subject,
      interactionFields.notes,
      interactionFields.date,
    ].map(field => {
      return assign(field, {
        label: formLabels.serviceDelivery[field.name],
      })
    }),
  }
}

module.exports = {
  interactionSortForm,
  selectKindFormConfig,
  interactionFormConfig,
  serviceDeliveryFormConfig,
}
<commit_msg>Added a form definition for interaction sorting.<commit_after>const { assign } = require('lodash')

const formLabels = require('./labels')
const metaData = require('../../lib/metadata')
const { transformContactToOption, transformObjectToOption } = require('../transformers')

const currentYear = (new Date()).getFullYear()

const interactionSortForm = {
  method: 'get',
  class: 'c-collection__sort-form js-AutoSubmit',
  hideFormActions: true,
  hiddenFields: { custom: true },
  children: [
    {
      macroName: 'MultipleChoiceField',
      label: 'Sort by',
      name: 'sortby',
      modifier: ['small', 'inline', 'light'],
      options: [
        { value: 'date:desc', label: 'Newest' },
        { value: 'date:asc', label: 'Oldest' },
        { value: 'company.name:asc', label: 'Company: A-Z' },
        { value: 'company.name:desc', label: 'Company: Z-A' },
        { value: 'contact.name:asc', label: 'Contact: A-Z' },
        { value: 'contact.name:desc', label: 'Contact: Z-A' },
        { value: 'dit_adviser.name:asc', label: 'Adviser: A-Z' },
        { value: 'dit_adviser.name:desc', label: 'Adviser: Z-A' },
        { value: 'subject:asc', label: 'Subject: A-Z' },
        { value: 'subject:desc', label: 'Subject: Z-A' },
      ],
    },
  ],
}

const selectKindFormConfig = function ({
  returnLink,
  errors = [],
}) {
  return {
    buttonText: 'Continue',
    errors,
    children: [
      {
        macroName: 'MultipleChoiceField',
        type: 'radio',
        label: 'What would you like to record?',
        name: 'kind',
        options: [{
          value: 'interaction',
          label: 'A standard interaction',
          hint: 'For example, an email, phone call or meeting',
        }, {
          value: 'service_delivery',
          label: 'A service that you have provided',
          hint: 'For example, account management, a significant assist or an event',
        }],
      },
    ],
  }
}

const interactionFields = {
  contact (contacts) {
    return {
      macroName: 'MultipleChoiceField',
      name: 'contact',
      initialOption: '-- Select contact --',
      options () {
        return contacts.map(transformContactToOption)
      },
    }
  },
  provider: {
    macroName: 'MultipleChoiceField',
    name: 'dit_team',
    initialOption: '-- Select provider --',
    options () {
      return metaData.teams.map(transformObjectToOption)
    },
  },
  service (services) {
    return {
      macroName: 'MultipleChoiceField',
      name: 'service',
      initialOption: '-- Select service --',
      options () {
        return services.map(transformObjectToOption)
      },
    }
  },
  subject: {
    macroName: 'TextField',
    name: 'subject',
  },
  notes: {
    macroName: 'TextField',
    type: 'textarea',
    name: 'notes',
  },
  date: {
    macroName: 'DateFieldset',
    name: 'date',
  },
  adviser (advisers) {
    return {
      macroName: 'MultipleChoiceField',
      name: 'dit_adviser',
      initialOption: '-- Select adviser --',
      options () {
        return advisers.map(transformContactToOption)
      },
    }
  },
  communicationChannel: {
    macroName: 'MultipleChoiceField',
    name: 'communication_channel',
    initialOption: '-- Select communication channel --',
    options () {
      return metaData.communicationChannelOptions.map(transformObjectToOption)
    },
  },
}

const interactionFiltersFieldConfig = function (advisers) {
  return [
    {
      macroName: 'MultipleChoiceField',
      name: 'kind',
      type: 'checkbox',
      options: [
        { value: 'interaction', label: 'Interaction' },
        { value: 'service_delivery', label: 'Service delivery' },
      ],
    },
    assign(
      {},
      interactionFields.communicationChannel,
      { initialOption: '-- All channels --' }
    ),
    assign(
      {},
      interactionFields.adviser(advisers),
      { initialOption: '-- All advisers --' }
    ),
    {
      macroName: 'TextField',
      name: 'date_after',
      hint: 'YYYY-MM-DD',
      placeholder: `e.g. ${currentYear}-07-18`,
    },
    {
      macroName: 'TextField',
      name: 'date_before',
      hint: 'YYYY-MM-DD',
      placeholder: `e.g. ${currentYear}-07-21`,
    },
  ].map(filter => {
    return assign(filter, {
      label: formLabels.filters[filter.name],
      modifier: ['smaller', 'light'],
    })
  })
}

const interactionFormConfig = function ({
  returnLink,
  contacts = [],
  advisers = [],
  services = [],
  hiddenFields,
}) {
  return {
    returnLink,
    buttonText: 'Save',
    returnText: 'Cancel',
    hiddenFields,
    children: [
      interactionFields.contact(contacts),
      interactionFields.provider,
      interactionFields.service(services),
      interactionFields.subject,
      interactionFields.notes,
      interactionFields.date,
      interactionFields.adviser(advisers),
      interactionFields.communicationChannel,
    ].map(field => {
      return assign(field, {
        label: formLabels.interaction[field.name],
      })
    }),
  }
}

const serviceDeliveryFormConfig = function ({
  returnLink,
  contacts = [],
  advisers = [],
  services = [],
  events = [],
  hiddenFields,
}) {
  return {
    returnLink,
    buttonText: 'Save',
    returnText: 'Cancel',
    hiddenFields,
    children: [
      interactionFields.contact(contacts),
      interactionFields.provider,
      interactionFields.adviser(advisers),
      // TODO this will be going once interactions are within events
      {
        macroName: 'MultipleChoiceField',
        type: 'radio',
        name: 'is_event',
        optional: true,
        modifier: 'inline',
        options: [
          {
            label: 'Yes',
            value: 'true',
          },
          {
            label: 'No',
            value: 'false',
          },
        ],
      },
      {
        macroName: 'MultipleChoiceField',
        name: 'event',
        initialOption: '-- Select event --',
        options () {
          return events.map(transformObjectToOption)
        },
        modifier: 'subfield',
        condition: {
          name: 'is_event',
          value: 'true',
        },
      },
      interactionFields.service(services),
      interactionFields.subject,
      interactionFields.notes,
      interactionFields.date,
    ].map(field => {
      return assign(field, {
        label: formLabels.serviceDelivery[field.name],
      })
    }),
  }
}

module.exports = {
  interactionFiltersFieldConfig,
  interactionSortForm,
  selectKindFormConfig,
  interactionFormConfig,
  serviceDeliveryFormConfig,
}
<|endoftext|>


<commit_before>angular.module('run.controller', [])

.controller('RunController', function($scope, $timeout, $location, Geo){
  $scope.raceStarted = 0;
  $scope.startTime;
  $scope.userLocation;
  $scope.destination;

  var tick = function() {
    $scope.time = Math.floor((Date.now() - $scope.startTime)/1000);
    $timeout(tick, 100)
  }

  $scope.startRun = function() {
    $scope.startTime = Date.now();
    $scope.raceStarted = true;
    tick();
  }

  // $scope.getCurrentCoords = function() {
  //   console.log('ran');
  //   Geo.getCurrentCoords(function(coordsObj) {
  //     $scope.currentCoords = coordsObj;
  //     console.log('$scope.currentCoords.lat: ', $scope.currentCoords.lat);
  //     console.log('$scope.currentCoords.lng: ', $scope.currentCoords.lng);
  //   });
  // };

  $scope.makeInitialMap = function($scope) {
    Geo.makeInitialMap($scope);
  };

  $scope.makeInitialMap($scope);

  $scope.updateCurrentPosition = function($scope, $location) {
    Geo.updateCurrentPosition($scope);
    $scope.checkIfFinished($location);
  };

  $scope.checkIfFinished = function($location) {
    if ($scope.destination && $scope.userLocation) {
      var currLat = $scope.userLocation.lat;
      var currLng = $scope.userLocation.lng;
      var destLat = $scope.destination.lat;
      var destLng = $scope.destination.lng;
      var distRemaining = Math.sqrt(Math.pow((currLat - destLat), 2) + Math.pow((currLng - destLng) , 2));

      if (distRemaining < 0.0004) {
        $location.path('/finish');
        clearInterval($scope.geoUpdater);
      }
    }
  }

  // Determine user location and update map each second

  $scope.geoUpdater = setInterval(function() {$scope.updateCurrentPosition($scope, $location)}, 1000);

  // Stop geotracker upon canceling run
  $scope.stopGeoUpdater = function() {
    clearInterval($scope.geoUpdater);
  };
})
<commit_msg>Calculate time until medal goals<commit_after>angular.module('run.controller', [])

.controller('RunController', function($scope, $timeout, $location, Geo){
  $scope.raceStarted = 0;
  $scope.startTime;
  $scope.userLocation;
  $scope.destination;
  $scope.goldPointInTime;
  $scope.silverPointInTime;
  $scope.bronzePointInTime;
  $scope.timeUntilGold;
  $scope.timeUntilSilver;
  $scope.timeUntilBronze;

  var tick = function() {
    $scope.time = Math.floor((Date.now() - $scope.startTime)/1000);
    $timeout(tick, 100)
  }

  $scope.startRun = function() {
    $scope.startTime = Date.now();
    $scope.raceStarted = true;
    $scope.geoUpdater = setInterval(function() {$scope.updateCurrentPosition($scope, $location)}, 500);
    $scope.goldPointInTime = moment().add($scope.goldTime.second(), 'seconds').add($scope.goldTime.minute(), 'minutes');
    $scope.silverPointInTime = moment().add($scope.silverTime.second(), 'seconds').add($scope.silverTime.minute(), 'minutes');
    $scope.bronzePointInTime = moment().add($scope.bronzeTime.second(), 'seconds').add($scope.bronzeTime.minute(), 'minutes');
    tick();
  }

  // $scope.getCurrentCoords = function() {
  //   console.log('ran');
  //   Geo.getCurrentCoords(function(coordsObj) {
  //     $scope.currentCoords = coordsObj;
  //     console.log('$scope.currentCoords.lat: ', $scope.currentCoords.lat);
  //     console.log('$scope.currentCoords.lng: ', $scope.currentCoords.lng);
  //   });
  // };

  $scope.makeInitialMap = function($scope) {
    Geo.makeInitialMap($scope);
  };

  $scope.makeInitialMap($scope);

  $scope.updateCurrentPosition = function($scope, $location) {
    Geo.updateCurrentPosition($scope);
    var secondsToGold = $scope.goldPointInTime.diff(moment(), 'seconds');
    var secondsToSilver = $scope.silverPointInTime.diff(moment(), 'seconds');
    var secondsToBronze = $scope.bronzePointInTime.diff(moment(), 'seconds');
    $scope.timeUntilGold = moment().second(secondsToGold).minute(secondsToGold / 60);
    $scope.timeUntilSilver = moment().second(secondsToSilver).minute(secondsToSilver / 60);
    $scope.timeUntilBronze = moment().second(secondsToBronze).minute(secondsToBronze / 60);
    console.log('$scope.timeUntilGold: ', $scope.timeUntilGold.format('mm:ss'));
    $scope.checkIfFinished($location);
    // console.log('$scope.goldPointInTime: ', $scope.goldPointInTime.format('hh:mm'));
    // console.log('$scope.timeUntilGold: ', $scope.timeUntilGold.format('mm:ss'));
  };

  $scope.checkIfFinished = function($location) {
    if ($scope.destination && $scope.userLocation) {
      var currLat = $scope.userLocation.lat;
      var currLng = $scope.userLocation.lng;
      var destLat = $scope.destination.lat;
      var destLng = $scope.destination.lng;
      var distRemaining = Math.sqrt(Math.pow((currLat - destLat), 2) + Math.pow((currLng - destLng) , 2));

      if (distRemaining < 0.0004) {
        $location.path('/finish');
        clearInterval($scope.geoUpdater);
      }
    }
  }

  // Determine user location and update map each second

  // Stop geotracker upon canceling run
  $scope.stopGeoUpdater = function() {
    clearInterval($scope.geoUpdater);
  };
})
<|endoftext|>


<commit_before>// React
import React, {PropTypes} from "react";
import {StyleGuidePage} from "orion/guide/layout";
import {Button, Section, SubSection, Spacer, Icon, Notice, VMenuLink} from 'orion/ui/helpers';

export class HelpersPage extends StyleGuidePage {
    sidebar() {
        return (

                <VMenuLink index={true}>← Home</VMenuLink>
                <VMenuLink hash="#helpers">Helper Classes</VMenuLink>

        )
    }

    main() {
        return (

                .l-float-left
                .l-float-right
                .l-clear

                .l-inline

                .l-hidden
                .l-no-margin
                .l-no-padding

                .l-center-txt
                --- only center text
                .l-hidden

                .l-align--abscenter
                --- centers element exactly in the middle of the page both horizontally/vertically
                .l-align--horizontal
                --- centers div only horizontally

        )
    }

}
<commit_msg>Helper Text<commit_after>// React
import React, {PropTypes} from "react";
import {StyleGuidePage} from "orion/guide/layout";
import {Button, Section, SubSection, Spacer, Icon, Notice, VMenuLink} from 'orion/ui/helpers';

export class HelpersPage extends StyleGuidePage {
    sidebar() {
        return (

                <VMenuLink index={true}>← Home</VMenuLink>
                <VMenuLink hash="#helpers">Helper Classes</VMenuLink>

        )
    }

    main() {
        return (

 This is a quick guide for class names used on the style guide. These helpers will eventually be replaced by actual code snippets.

                .l-float-left
                .l-float-right
                .l-clear

                .l-inline

                .l-hidden
                .l-no-margin
                .l-no-padding

                .l-center-txt
                --- only center text
                .l-hidden

                .l-align--abscenter
                --- centers element exactly in the middle of the page both horizontally/vertically
                .l-align--horizontal
                --- centers div only horizontally

        )
    }

}
<|endoftext|>


<commit_before>let aboutModule = angular.module('about', [
])

.config(($stateProvider, $compileProvider) => {
  "ngInject";
  $stateProvider
    .state('about', {
      url: '/about',
      controllerAs: 'vm',
      controller: function($scope) {
        this.name = "about";
      },
      templateProvider: ['$q', function($q) {
                let deferred = $q.defer();

                require.ensure(['./about.html'], function() {
                    var template = require('./about.html');
                    deferred.resolve(template);
                });

                return deferred.promise;
            }],

      // Lazy load this component
      resolve: {
        loadComponent: ($q, $ocLazyLoad) => {
          var deferred = $q.defer();

          require.ensure([], function(require) {

            let component = require('./about.component');

            $ocLazyLoad.inject([
              component.name
            ])
            .then(() => $compileProvider.directive('about', component))
            .then(deferred.resolve);
          }, 'about');

          return deferred.promise
        }
      }
    });
});

export default aboutModule;
<commit_msg>Remove Sample Lazy Load Template<commit_after><|endoftext|>


<commit_before>/* global $, document, messages, event, textarea */
'use strict';

$(function(){

  /**
  * Markdown editor
  */
  $("#text-editor").markdown({
    autofocus:true,
    savable:false,
    iconlibrary:'fa',
    height:125
  });

  textarea.onkeydown = function(e) {
    e = e || event;
    if(e.keyCode === 13 && !document.getElementById('disable-enter-action').checked) {
      e.preventDefault();
      if(textarea.value.length > 0)
        messages.vm.send();
      else
        textarea.value = null;
    }
    return true;
  }

});
<commit_msg>feat(): saut de ligne avec shift+enter<commit_after>/* global $, document, messages, event, textarea */
'use strict';

$(function(){

  /**
  * Markdown editor
  */
  $("#text-editor").markdown({
    autofocus:true,
    savable:false,
    iconlibrary:'fa',
    height:125
  });

  textarea.onkeydown = function(e) {
    e = e || event;
    if(e.keyCode === 13 && !e.shiftKey) {
      if(!document.getElementById('disable-enter-action').checked) {
        e.preventDefault();
        if(textarea.value.length > 0)
          messages.vm.send();
        else
          textarea.value = null;
      }
    }
    return true;
  }

});
<|endoftext|>


<commit_before>var renderError = require('./error').renderHTMLError
var child_process = require('child_process')
var spawn = child_process.spawn
var path = require('path')
var fs = require('fs')

// Find the elm-make executable
var elmExecutable =
  path.resolve(__dirname, '../../../node_modules/elm/binwrappers/elm-make')

// Try to load pty.js beacause it's an optional dependency.
var pty
try {
  pty = require('pty.js')
} catch (e) {}

// Renders an .elm file.
var render = function(file, callback) {
  var arguments = `${file} --output test.js --yes`.split(' ')
  var result = ''
  var command
  var regexp

  // If there is pty.js we can have colored output
  if (pty) {
    regexp = /[\n\r]{1,2}/g

    command = pty.spawn(elmExecutable, arguments, {
      name: 'xterm-color',
      cols: 1000,
      rows: 1000,
    })

    command.on('data', function(data) {
      result += data
    })
  } else {
    regexp = /\n/g

    command = spawn(elmExecutable, arguments)

    command.stdout.on('data', (data) => {
      result += data
    })

    command.stderr.on('data', (data) => {
      result += data
    })
  }

  command.on('close', function() {
    if (result.match('Successfully generated test.js')) {
      callback(null, '')
    } else {
      callback(result.replace(regexp, "\n"), '')
    }
  })
}

module.exports = function(file, config, shouldFail) {
  return function(callback) {
    render(file, function(error, result) {
      if (error) {
        var prettyError =
          renderError('You have errors in of your Elm file(s):', error)

        if (shouldFail) {
          callback(error, null)
        } else {
          callback(null, prettyError)
        }
      } else {
        var contents = [
          `window.ENV = ${JSON.stringify(config)};`,
          fs.readFileSync('test.js', 'utf-8'),
          'Elm.Main.fullscreen();'
        ].join('\n')
        callback(null, contents)
        fs.unlink('test.js')
      }
    })
  }
}
<commit_msg>Use different filenames for compiled JS to avoid collision.<commit_after>var renderError = require('./error').renderHTMLError
var child_process = require('child_process')
var spawn = child_process.spawn
var path = require('path')
var fs = require('fs')

// Find the elm-make executable
var elmExecutable =
  path.resolve(__dirname, '../../../node_modules/elm/binwrappers/elm-make')

// Try to load pty.js beacause it's an optional dependency.
var pty
try {
  pty = require('pty.js')
} catch (e) {}

// Renders an .elm file.
var render = function(file, callback) {
  var filename = `test-${+Date.now()}.js`
  var arguments = `${file} --output ${filename} --yes`.split(' ')
  var result = ''
  var command
  var regexp

  // If there is pty.js we can have colored output
  if (pty) {
    regexp = /[\n\r]{1,2}/g

    command = pty.spawn(elmExecutable, arguments, {
      name: 'xterm-color',
      cols: 1000,
      rows: 1000,
    })

    command.on('data', function(data) {
      result += data
    })
  } else {
    regexp = /\n/g

    command = spawn(elmExecutable, arguments)

    command.stdout.on('data', (data) => {
      result += data
    })

    command.stderr.on('data', (data) => {
      result += data
    })
  }

  command.on('close', function() {
    if (result.match('Successfully generated test')) {
      callback(null, '', filename)
    } else {
      callback(result.replace(regexp, "\n"), '', filename)
    }
  })
}

module.exports = function(file, config, shouldFail) {
  return function(callback) {
    render(file, function(error, result, filename) {
      if (error) {
        var prettyError =
          renderError('You have errors in of your Elm file(s):', error)

        if (shouldFail) {
          callback(error, null)
        } else {
          callback(null, prettyError)
        }
      } else {
        var contents = [
          `window.ENV = ${JSON.stringify(config)};`,
          fs.readFileSync(filename, 'utf-8'),
          'Elm.Main.fullscreen();'
        ].join('\n')
        callback(null, contents)
        fs.unlink(filename)
      }
    })
  }
}
<|endoftext|>


<commit_before>/**
 * Script for switching contents
 */

var contains = function(bigger, fragment) {
	return bigger.indexOf(fragment) != -1;
};

// historyObj object
historyObj = {
	actualPage: undefined,

	pages: new Array(),

	setActualPage: function(page, ifhistoryObj) {
		if (!ifhistoryObj && historyObj.actualPage !== page) {
			historyObj.addTohistoryObj();
		}
		historyObj.actualPage = page;
	},

	addTohistoryObj: function(page) {
		if (page) {
			historyObj.pages.push(page);
		} else if (historyObj.actualPage && historyObj.actualPage !== "wall" && historyObj.actualPage !== "connecting") {
			historyObj.pages.push(historyObj.actualPage);
		}
	},

	back: function() {
		if (historyObj.pages.length > 0) {
			var route = historyObj.pages.pop();
			if (route) {
				load(route, true, true);
			}
		} else if (historyObj.pages.length === 0 && contains(window.location.href, "wall.html")) {
			load("rooms", true, true);
		} else if (historyObj.pages.length === 0 && contains(window.location.href, "index2.html")) {
			devices.action.exit();
		}
	}
};

var routing = {
	memory: {},
	registerAction: function(type, action) {
		routing.memory[type] = action;
	},
	runAction: function(type) {
		if (routing.memory[type]) {
			routing.memory[type]();
		}
	}
};

function load(what, ifAction, ifhistoryObj) {
	if (what === "rooms" && contains(window.location.href, "wall.html")) {
		// when we were on wall and want to load rooms page
		window.location = 'index2.html';
	} else if (what === "wall" && !contains(window.location.href, "wall.html")) {
		// when we weren't on wall and want to load wall
		window.location = 'wall.html';
	}
	switch(what) {
		case "connection":
			$( "#content" ).load( "loadConnect.html" );
			break;
		case "login":
			$( "#content" ).load( "loadLogin.html" );
			break;
		case "rooms":
			$( "#content" ).load( "loadRooms.html" );
			break;
		case "registration":
			$( "#content" ).load( "loadRegistration.html" );
			break;
		case "wall":
			$( "#content" ).load( "loadWall.html" );
			break;
		case "wallContent":
			$( "#content" ).load( "loadWallContent.html" );
			break;
		case "connecting":
			$( "#content" ).load( "loadWall.html" );
			break;
		case "users":
			$( "#content" ).load( "loadUsers.html" );
			break;
	}
	historyObj.setActualPage(what, ifhistoryObj);

	if (ifAction) {
		routing.runAction(what);
	}
}<commit_msg>client: dokumentacja routing.js<commit_after>/**
 * Script for switching contents
 */
	/**
	 * @function routing.contains
	 * checks if current URL is the same
	 * @param {function} bigger
	 * current URL
	 * @param {function} fragment
	 * defines page to check if is the same
	 */
var contains = function(bigger, fragment) {
	return bigger.indexOf(fragment) != -1;
};

	 /**
	* Defines current navigation between sites
	*/
historyObj = {
	actualPage: undefined,

	pages: new Array(),

	/**
	 * @function setActualPage
	 * sets actual page if different than current
	 * @param {function} page
	 * page to be set as current
	 * @param {function} ifhistoryObj
	 * checks if page was used before
	 */
	setActualPage: function(page, ifhistoryObj) {
		if (!ifhistoryObj && historyObj.actualPage !== page) {
			historyObj.addTohistoryObj();
		}
		historyObj.actualPage = page;
	},
	/**
	 * @function addTohistoryObj
	 * adds page to historyObj
	 * @param {function} page
	 * page to be added to historyObj
	 */
	addTohistoryObj: function(page) {
		if (page) {
			historyObj.pages.push(page);
		} else if (historyObj.actualPage && historyObj.actualPage !== "wall" && historyObj.actualPage !== "connecting") {
			historyObj.pages.push(historyObj.actualPage);
		}
	},
	/**
	 * @function back
	 * navigates user to earlier page, if window contains index2.html then exits
	 */
	back: function() {
		if (historyObj.pages.length > 0) {
			var route = historyObj.pages.pop();
			if (route) {
				load(route, true, true);
			}
		} else if (historyObj.pages.length === 0 && contains(window.location.href, "wall.html")) {
			load("rooms", true, true);
		} else if (historyObj.pages.length === 0 && contains(window.location.href, "index2.html")) {
			devices.action.exit();
		}
	}
};
	/**
	* Reacts when action is made by user
	*/
var routing = {
	memory: {},
	/**
	 * @function registerAction
	 * registers actions made by user
	 * @param {function} action
	 * action made by user
	 */
	registerAction: function(type, action) {
		routing.memory[type] = action;
	},
	/**
	 * @function runAction
	 * runs action made by user
	 * @param {function} type
	 * type - current action
	 */
	runAction: function(type) {
		if (routing.memory[type]) {
			routing.memory[type]();
		}
	}
};
	/**
	 * @function load
	 * loads content that is set to current user action
	 * @param {function} what
	 * defines current user case
	 * @param {function} ifAction
	 * checks if user had made an action
	 * @param {function} ifhistoryObj
	 * checks if page was used before
	 */
function load(what, ifAction, ifhistoryObj) {
	if (what === "rooms" && contains(window.location.href, "wall.html")) {
		// when we were on wall and want to load rooms page
		window.location = 'index2.html';
	} else if (what === "wall" && !contains(window.location.href, "wall.html")) {
		// when we weren't on wall and want to load wall
		window.location = 'wall.html';
	}
	switch(what) {
		case "connection":
			$( "#content" ).load( "loadConnect.html" );
			break;
		case "login":
			$( "#content" ).load( "loadLogin.html" );
			break;
		case "rooms":
			$( "#content" ).load( "loadRooms.html" );
			break;
		case "registration":
			$( "#content" ).load( "loadRegistration.html" );
			break;
		case "wall":
			$( "#content" ).load( "loadWall.html" );
			break;
		case "wallContent":
			$( "#content" ).load( "loadWallContent.html" );
			break;
		case "connecting":
			$( "#content" ).load( "loadWall.html" );
			break;
		case "users":
			$( "#content" ).load( "loadUsers.html" );
			break;
	}
	historyObj.setActualPage(what, ifhistoryObj);

	if (ifAction) {
		routing.runAction(what);
	}
}<|endoftext|>


<commit_before>/**
 * Created by Wayuki on 25-Mar-17.
 */
/* eslint-disable react/jsx-filename-extension, react/no-array-index-key */

import React from 'react';
import getEmoji from 'emoji-from-word';
import { SEARCH_PAGE_ACTIONS } from './actionTypes';
import { search } from '../../../youtube';
import { getWordAt, getWordSuggestion, dissembleSentence } from '../../../helpers';

import app from '../feathers';

const registerQueryResults = results => ({
  type: SEARCH_PAGE_ACTIONS.REGISTER_QUERY_RESULTS,
  results,
});

export const handleQueryChange = value => (
  (dispatch) => {
    let words = dissembleSentence(value);
    words = words.map((word, key) => {
      if (word.search(/[,. ]/) > -1) {
        return { word };
      }
      return <span key={key} className={`word-${key}`}>{ word };
    });
    dispatch({
      type: SEARCH_PAGE_ACTIONS.HANDLE_QUERY_CHANGE,
      value,
      words,
    });
  }
);

export const handleQuerySubmit = () => (
  (dispatch, getState) => new Promise((resolve, reject) => {
    const { query } = getState().searchPage;
    if (query.length > 0) {
      search(query).then((results) => {
        app.service('searchHistories').create({
          query,
        }).catch();
        dispatch(registerQueryResults(results));
        resolve();
      }).catch((err) => {
        reject(err);
      });
    }
  })
);

export const registerSpellingSuggestions = spelling => ({
  type: SEARCH_PAGE_ACTIONS.REGISTER_SPELLING_SUGGESTIONS,
  spelling,
});

export const registerCaretPosition = caretPosition => ({
  type: SEARCH_PAGE_ACTIONS.REGISTER_CARET_POSITION,
  caretPosition,
});

export const handleInputBoxFocus = caretPosition => (
  (dispatch, getState) => {
    const {
      query,
      inputbox: {
        caretPosition: oldCaretPosition,
      },
    } = getState().searchPage;
    if (oldCaretPosition !== caretPosition) {
      const { wordClass, wordPos, word } = getWordAt(query, caretPosition);
      if (word.search(/[,. ]/) < 0 && word.length > 0) {
        const spelling = getWordSuggestion(word);
        if (!spelling.found && spelling.suggestions.length > 0) {
          const suggestions = spelling.suggestions.map((suggestion) => {
            let emojiChar = null;
            const { score, emoji } = getEmoji(suggestion.word);
            if (score >= 1) {
              emojiChar = emoji.char;
            }
            return {
              ...suggestion,
              emoji: emojiChar,
            };
          });
          dispatch(registerSpellingSuggestions({
            show: true,
            wordPos,
            pos: window.$(`.${wordClass}`).position().left,
            suggestions,
          }));
        } else {
          dispatch(registerSpellingSuggestions({
            show: false,
          }));
        }
      } else {
        dispatch(registerSpellingSuggestions({
          show: false,
        }));
      }
      dispatch(registerCaretPosition(caretPosition));
    }
  }
);

export const handleApplyingSuggestion = (wordPos, word) => (
  (dispatch, getState) => new Promise((resolve) => {
    const {
      query,
    } = getState().searchPage;
    const words = dissembleSentence(query);
    words[wordPos] = word;
    const left = words.slice(0, wordPos + 1).join('');
    const newCaretPosition = left.length;
    const right = words.slice(wordPos + 1).join('');
    const newWord = left + right;
    dispatch(handleQueryChange(newWord));
    dispatch(registerSpellingSuggestions({
      show: false,
    }));
    resolve(newCaretPosition);
  })
);

export default () => {};
<commit_msg>Query now includes "How to" at the beginning<commit_after>/**
 * Created by Wayuki on 25-Mar-17.
 */
/* eslint-disable react/jsx-filename-extension, react/no-array-index-key */

import React from 'react';
import getEmoji from 'emoji-from-word';
import { SEARCH_PAGE_ACTIONS } from './actionTypes';
import { search } from '../../../youtube';
import { getWordAt, getWordSuggestion, dissembleSentence } from '../../../helpers';

import app from '../feathers';

const registerQueryResults = results => ({
  type: SEARCH_PAGE_ACTIONS.REGISTER_QUERY_RESULTS,
  results,
});

export const handleQueryChange = value => (
  (dispatch) => {
    let words = dissembleSentence(value);
    words = words.map((word, key) => {
      if (word.search(/[,. ]/) > -1) {
        return { word };
      }
      return <span key={key} className={`word-${key}`}>{ word };
    });
    dispatch({
      type: SEARCH_PAGE_ACTIONS.HANDLE_QUERY_CHANGE,
      value,
      words,
    });
  }
);

export const handleQuerySubmit = () => (
  (dispatch, getState) => new Promise((resolve, reject) => {
    let { query } = getState().searchPage;
    if (query.length > 0) {
      query = `How to ${query}`;
      search(query).then((results) => {
        app.service('searchHistories').create({
          query,
        }).catch();
        dispatch(registerQueryResults(results));
        resolve();
      }).catch((err) => {
        reject(err);
      });
    }
  })
);

export const registerSpellingSuggestions = spelling => ({
  type: SEARCH_PAGE_ACTIONS.REGISTER_SPELLING_SUGGESTIONS,
  spelling,
});

export const registerCaretPosition = caretPosition => ({
  type: SEARCH_PAGE_ACTIONS.REGISTER_CARET_POSITION,
  caretPosition,
});

export const handleInputBoxFocus = caretPosition => (
  (dispatch, getState) => {
    const {
      query,
      inputbox: {
        caretPosition: oldCaretPosition,
      },
    } = getState().searchPage;
    if (oldCaretPosition !== caretPosition) {
      const { wordClass, wordPos, word } = getWordAt(query, caretPosition);
      if (word.search(/[,. ]/) < 0 && word.length > 0) {
        const spelling = getWordSuggestion(word);
        if (!spelling.found && spelling.suggestions.length > 0) {
          const suggestions = spelling.suggestions.map((suggestion) => {
            let emojiChar = null;
            const { score, emoji } = getEmoji(suggestion.word);
            if (score >= 1) {
              emojiChar = emoji.char;
            }
            return {
              ...suggestion,
              emoji: emojiChar,
            };
          });
          dispatch(registerSpellingSuggestions({
            show: true,
            wordPos,
            pos: window.$(`.${wordClass}`).position().left,
            suggestions,
          }));
        } else {
          dispatch(registerSpellingSuggestions({
            show: false,
          }));
        }
      } else {
        dispatch(registerSpellingSuggestions({
          show: false,
        }));
      }
      dispatch(registerCaretPosition(caretPosition));
    }
  }
);

export const handleApplyingSuggestion = (wordPos, word) => (
  (dispatch, getState) => new Promise((resolve) => {
    const {
      query,
    } = getState().searchPage;
    const words = dissembleSentence(query);
    words[wordPos] = word;
    const left = words.slice(0, wordPos + 1).join('');
    const newCaretPosition = left.length;
    const right = words.slice(wordPos + 1).join('');
    const newWord = left + right;
    dispatch(handleQueryChange(newWord));
    dispatch(registerSpellingSuggestions({
      show: false,
    }));
    resolve(newCaretPosition);
  })
);

export default () => {};
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import Cookies from 'js-cookie';
import { submitAnonymousVote, submitRegularVote } from '../../actionCreators/voting';
import { getShuffledAlternatives } from '../../selectors/alternatives';
import { activeIssueExists, getIssue, getIssueId, getOwnVote } from '../../selectors/issues';
import Alternatives from '../Alternatives';
import Button from '../Button';

class VotingMenu extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedVote: null,
      displayVote: false,
    };
  }

  handleChange(event) {
    this.setState({
      selectedVote: event.currentTarget.value,
    });
  }

  handleClick() {
    this.props.handleVote(
      this.props.issueId,
      this.state.selectedVote,
      this.props.voterKey,
    );
    this.setState({
      displayVote: false,
    });
  }

  toggleVoteDisplay() {
    this.setState({
      displayVote: !this.state.displayVote,
    });
  }

  render() {
    const { alternatives, issueIsActive, isLoggedIn, ownVote } = this.props;
    const { displayVote, selectedVote } = this.state;
    const hasSelectedVote = !!selectedVote;
    const hasVoted = !!ownVote;
    const canVote = !isLoggedIn || !hasSelectedVote || hasVoted;
    const selected = hasVoted ? (displayVote && ownVote) : selectedVote;

    return (

        <Alternatives
          alternatives={alternatives}
          disabled={hasVoted}
          handleChange={(...a) => this.handleChange(...a)}
          selectedVote={selected}
        />
        <Button
          background
          size="lg"
          onClick={() => this.handleClick()}
          disabled={canVote}
          hidden={!issueIsActive}
        >
          {hasVoted ? 'Du har allerede stemt' : 'Avgi stemme'}
        </Button>
        {hasVoted && (
          <Button
            background
            size="lg"
            onClick={() => this.toggleVoteDisplay()}
          >
            {displayVote ?
              'Skjul min stemme' : 'Vis min stemme'}
          </Button>
        )}

    );
  }
}

VotingMenu.defaultProps = {
  voterKey: undefined,
  alternatives: [],
  issueId: '',
  isLoggedIn: undefined,
  ownVote: null,
};

VotingMenu.propTypes = {
  alternatives: Alternatives.propTypes.alternatives,
  handleVote: React.PropTypes.func.isRequired,
  issueId: React.PropTypes.string,
  issueIsActive: React.PropTypes.bool.isRequired,
  isLoggedIn: React.PropTypes.bool,
  ownVote: React.PropTypes.string,
  voterKey: React.PropTypes.number,
};

const mapStateToProps = state => ({
  // Alternatives are shuffled as an attempt to prevent peeking over shoulders
  // to figure out what another person has voted for. This scramble needs
  // to be syncronized between LiveVoteCount and VoteHandler, so we take
  // advantage of the memoizing provided by reselect. This keeps the
  // scrambles in sync and avoids rescrambling unless the
  // available alternatives are changed.
  alternatives: getShuffledAlternatives(state),

  // The ID, or undefined, if there is no current issue.
  issueId: getIssueId(state),
  issue: getIssue(state),

  ownVote: getOwnVote(state, state.auth.id),

  voterKey: state.voterKey,
  isLoggedIn: state.auth.loggedIn,

  issueIsActive: activeIssueExists(state),
});

const mergeProps = (stateProps, dispatchProps, ownProps) => {
  const { dispatch } = dispatchProps;
  return {
    ...ownProps,
    ...stateProps,
    handleVote: (issue, alternative) => {
      dispatch(stateProps.issue.secret ?
        submitAnonymousVote(issue, alternative, Cookies.get('passwordHash')) : submitRegularVote(issue, alternative));
    },
  };
};

export default VotingMenu;
export const VotingMenuContainer = connect(
  mapStateToProps,
  null,
  mergeProps,
)(VotingMenu);
<commit_msg>Reset selectedVote after voting<commit_after>import React from 'react';
import { connect } from 'react-redux';
import Cookies from 'js-cookie';
import { submitAnonymousVote, submitRegularVote } from '../../actionCreators/voting';
import { getShuffledAlternatives } from '../../selectors/alternatives';
import { activeIssueExists, getIssue, getIssueId, getOwnVote } from '../../selectors/issues';
import Alternatives from '../Alternatives';
import Button from '../Button';

class VotingMenu extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedVote: null,
      displayVote: false,
    };
  }

  handleChange(event) {
    this.setState({
      selectedVote: event.currentTarget.value,
    });
  }

  handleClick() {
    this.props.handleVote(
      this.props.issueId,
      this.state.selectedVote,
      this.props.voterKey,
    );
    this.setState({
      displayVote: false,
      selectedVote: null,
    });
  }

  toggleVoteDisplay() {
    this.setState({
      displayVote: !this.state.displayVote,
    });
  }

  render() {
    const { alternatives, issueIsActive, isLoggedIn, ownVote } = this.props;
    const { displayVote, selectedVote } = this.state;
    const hasSelectedVote = !!selectedVote;
    const hasVoted = !!ownVote;
    const canVote = !isLoggedIn || !hasSelectedVote || hasVoted;
    const selected = hasVoted ? (displayVote && ownVote) : selectedVote;

    return (

        <Alternatives
          alternatives={alternatives}
          disabled={hasVoted}
          handleChange={(...a) => this.handleChange(...a)}
          selectedVote={selected}
        />
        <Button
          background
          size="lg"
          onClick={() => this.handleClick()}
          disabled={canVote}
          hidden={!issueIsActive}
        >
          {hasVoted ? 'Du har allerede stemt' : 'Avgi stemme'}
        </Button>
        {hasVoted && (
          <Button
            background
            size="lg"
            onClick={() => this.toggleVoteDisplay()}
          >
            {displayVote ?
              'Skjul min stemme' : 'Vis min stemme'}
          </Button>
        )}

    );
  }
}

VotingMenu.defaultProps = {
  voterKey: undefined,
  alternatives: [],
  issueId: '',
  isLoggedIn: undefined,
  ownVote: null,
};

VotingMenu.propTypes = {
  alternatives: Alternatives.propTypes.alternatives,
  handleVote: React.PropTypes.func.isRequired,
  issueId: React.PropTypes.string,
  issueIsActive: React.PropTypes.bool.isRequired,
  isLoggedIn: React.PropTypes.bool,
  ownVote: React.PropTypes.string,
  voterKey: React.PropTypes.number,
};

const mapStateToProps = state => ({
  // Alternatives are shuffled as an attempt to prevent peeking over shoulders
  // to figure out what another person has voted for. This scramble needs
  // to be syncronized between LiveVoteCount and VoteHandler, so we take
  // advantage of the memoizing provided by reselect. This keeps the
  // scrambles in sync and avoids rescrambling unless the
  // available alternatives are changed.
  alternatives: getShuffledAlternatives(state),

  // The ID, or undefined, if there is no current issue.
  issueId: getIssueId(state),
  issue: getIssue(state),

  ownVote: getOwnVote(state, state.auth.id),

  voterKey: state.voterKey,
  isLoggedIn: state.auth.loggedIn,

  issueIsActive: activeIssueExists(state),
});

const mergeProps = (stateProps, dispatchProps, ownProps) => {
  const { dispatch } = dispatchProps;
  return {
    ...ownProps,
    ...stateProps,
    handleVote: (issue, alternative) => {
      dispatch(stateProps.issue.secret ?
        submitAnonymousVote(issue, alternative, Cookies.get('passwordHash')) : submitRegularVote(issue, alternative));
    },
  };
};

export default VotingMenu;
export const VotingMenuContainer = connect(
  mapStateToProps,
  null,
  mergeProps,
)(VotingMenu);
<|endoftext|>


<commit_before>// operator if..elseif..else
/*
JavaScript has a similar set of control structures to other languages in the C family.
Conditional statements are supported by if and else; you can chain them together if you like:
*/
console.log("=== If ELSE ===");
var name = "Nick";
if ( name == "Mark"){
    name+= "!";
}else if( name == "Nick"){
    name +="!!";
}else{
    name = "!" + name;
}

console.log(name);

/*
JavaScript has while loops and do-while loops.
The first is good for basic looping; the second for loops where you wish to ensure that
the body of the loop is executed at least once:
*/

console.log("=== WHILE ===");
//While being a true condition will execute the instructions contained in the code block
var x = 10;
var i = 1;
while(i == x){
    // do something;
/*
Key requirement in the use of the while statement is that the instructions
contained in the code block change the condition, otherwise you are likely to run into an infinite loop.
*/
    i += 1;
    return(i);
}

<commit_msg>Do..while loop condition<commit_after>// operator if..elseif..else
/*
JavaScript has a similar set of control structures to other languages in the C family.
Conditional statements are supported by if and else; you can chain them together if you like:
*/
console.log("=== If ELSE ===");
var name = "Nick";
if ( name == "Mark"){
    name+= "!";
}else if( name == "Nick"){
    name +="!!";
}else{
    name = "!" + name;
}

console.log(name);

/*
JavaScript has while loops and do-while loops.
The first is good for basic looping; the second for loops where you wish to ensure that
the body of the loop is executed at least once:
*/

console.log("=== WHILE ===");
//While being a true condition will execute the instructions contained in the code block
var x = 1;
var i = 1;
while(i <= 5 ){
    // do something;
/*
Key requirement in the use of the while statement is that the instructions
contained in the code block change the condition, otherwise you are likely to run into an infinite loop.
*/
    x = x*i;
    i++;
}

console.log("=== DO...WHILE ===");

var x = 1;
var i = 1;
do{
    x = x*i;
    i++;
}
while(i <= 5)

<|endoftext|>


<commit_before>import Vue from 'vue';
import PhotoCard from './PhotoCard';
import VueRouter from 'vue-router';
import VueI18n from 'vue-i18n';
import VueLazyload from 'vue-lazyload';

describe('Component | PhotoCard.vue', () => {
  let wrapper
  let photo;
  let localVue;

  beforeEach(() => {
    photo = {
      imgLink: 'webf',
      dropboxId: '45',
    };
    localVue = createLocalVue();
    localVue.use(VueI18n)
    localVue.use(VueRouter)
    localVue.use(VueLazyload)
    const propsData = { photo };
    wrapper = shallowMount(PhotoCard, { localVue, propsData })
  });

  it('should be named "PhotoCard"', () => {
    expect(wrapper.name()).toEqual('PhotoCard');
  });

  describe('template', () => {
    it('should match snapshot', () => {
      expect(wrapper.element).toMatchSnapshot()
    })
  })

  xdescribe('render', () => {
    it('should render photo image', () => Vue.nextTick().then(() => {
      const photoLink = wrapper.find('img');
      expect(photoLink.getAttribute('src')).toEqual('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
      expect(photoLink.getAttribute('lazy')).toEqual('loading');
    }));

    // Comment tester le lazy load ?
    it.skip('should render photo image', () => Vue.nextTick().then(() => {
      const photoLink = wrapper.find('img');

      // return Vue.nextTick().then(() => {
      // console.log(photoLink);
      expect(photoLink.getAttribute('lazy')).toEqual('loaded');
      expect(photoLink.getAttribute('src')).toContain('webf');
      // });
    }));
  });

  xdescribe('computed property #imgLink', () => {
    it('should return imgLink when defined', () => {

      photo.imgLink = 'dropbox.com/img0.jpg';

      const { imgLink } = component;

      expect(imgLink).toEqual('dropbox.com/img0.jpg');
    });

    it('should return false when api status is undefined', () => {

      photo.imgLink = '';

      const { imgLink } = component;

      expect(imgLink).toEqual(false);
    });
  });
});
<commit_msg>bsr : photocard is tested<commit_after>import Vue from 'vue';
import PhotoCard from './PhotoCard';
import VueRouter from 'vue-router';
import VueI18n from 'vue-i18n';
import VueLazyload from 'vue-lazyload';

describe('Component | PhotoCard.vue', () => {
  let wrapper
  let photo;
  let localVue;

  beforeEach(() => {
    photo = {
      imgLink: 'webf',
      dropboxId: '45',
    };
    localVue = createLocalVue();
    localVue.use(VueI18n)
    localVue.use(VueRouter)
    localVue.use(VueLazyload)
    const propsData = { photo };
    wrapper = shallowMount(PhotoCard, { localVue, propsData })
  });

  it('should be named "PhotoCard"', () => {
    expect(wrapper.name()).toEqual('PhotoCard');
  });

  describe('template', () => {
    it('should match snapshot', () => {
      expect(wrapper.element).toMatchSnapshot()
    })
  })

  describe('render', () => {
    it('should render photo image', () => Vue.nextTick().then(() => {
      const photoLink = wrapper.find('img');
      expect(photoLink.attributes().src).toEqual('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
      expect(photoLink.attributes().lazy).toEqual('loading');
    }));

    // Comment tester le lazy load ?
    it.skip('should render photo image', () => Vue.nextTick().then(() => {
      const photoLink = wrapper.find('img');

      // return Vue.nextTick().then(() => {
      // console.log(photoLink);
      expect(photoLink.getAttribute('lazy')).toEqual('loaded');
      expect(photoLink.getAttribute('src')).toContain('webf');
      // });
    }));
  });

  describe('computed property #imgLink', () => {
    it('should return imgLink when defined', () => {
      photo.imgLink = 'dropbox.com/img0.jpg';
      const propsData = { photo };

      wrapper = shallowMount(PhotoCard, { localVue, propsData })

      expect(wrapper.vm.imgLink).toEqual('dropbox.com/img0.jpg');
    });

    it('should return false when api status is undefined', () => {
      photo.imgLink = '';
      const propsData = { photo };

      wrapper = shallowMount(PhotoCard, { localVue, propsData })

      expect(wrapper.vm.imgLink).toEqual(false);
    });
  });
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React, {Component} from 'react'
import {Button, Modal} from 'react-bootstrap'
import './ReportWorkflow.css'
import Settings from 'Settings'
import LinkTo from 'components/LinkTo'

import Fieldset from 'components/Fieldset'
import moment from 'moment'

const APPROVE = 'APPROVE'
const REJECT = 'REJECT'
const SUBMIT = 'SUBMIT'
const PUBLISH = 'PUBLISH'

const ACTION_TYPE_DETAILS = {
  APPROVE: {text: 'Approved', cssClass: 'btn-success approved'},
  REJECT: {text: 'Changes requested', cssClass: 'btn-danger rejected'},
  SUBMIT: {text: 'Submitted', cssClass: 'btn-pending submitted'},
  PUBLISH: {text: 'Published', cssClass: 'btn-success published'},
  null: {text: 'Pending', cssClass: 'btn-pending default'}
}

const ApprovalStepModalStatus = ({action}) => {
  if (action.type) {
    const actionType = ACTION_TYPE_DETAILS[action.type]
    const cssClass = 'label ' + actionType.cssClass
    return (
      {actionType.text} by <LinkTo person={action.person} isLink= {false} /> on
         {moment(action.createdAt).format(Settings.dateFormats.forms.withTime)}

    )
  }
  return Pending
}

class ApprovalStepModal extends Component {
  static propTypes = {
    action: PropTypes.object.isRequired,
  }

  constructor(props){
    super(props)
    this.state = {
      showModal: false
    }
  }

  closeModal = () => {
    this.setState({ showModal: false })
  }

  openModal = () => {
    this.setState({ showModal: true })
  }

  render() {
    const { action } = this.props
    const step = action.step
    const actionTypeCss =  ACTION_TYPE_DETAILS[action.type].cssClass
    return (
      step ?
        <React.Fragment>
          <Button className={actionTypeCss + ' btn-sm'} onClick={this.openModal}>
            {step.name}
          </Button>
          <Modal show={this.state.showModal} onHide={this.closeModal}>
            <Modal.Header closeButton>
                <Modal.Title>Approvers for {step.name}</Modal.Title>
            </Modal.Header>
            <Modal.Body>

              {step.approvers.map(position =>

                  <LinkTo position={position} /> - <LinkTo person={position.person} />

              )}

            </Modal.Body>
            <Modal.Footer>
              <ApprovalStepModalStatus action={action} />
            </Modal.Footer>
          </Modal>
        </React.Fragment>
      :
        null
    )
  }
}

const ActionStatus = ({action}) => {
  return
{ACTION_TYPE_DETAILS[action.type].text}

}

const ActionButton = ({action}) => {
  const step = action.step
  const actionType =  ACTION_TYPE_DETAILS[action.type]
  return (
    step ?
      <ApprovalStepModal action={action} />
    :
      <Button className={actionType.cssClass + ' btn-sm'}>
        <LinkTo person={action.person} isLink={false} />
      </Button>
  )
}

const ActionDetails = ({action}) => {
  if (action.type) {
    return(

        By <LinkTo person={action.person} />

          On {moment(action.createdAt).format(Settings.dateFormats.forms.short)}

          At {moment(action.createdAt).format('h:mm a')}

    )
  }
  return null
}

const ReportAction = ({action}) => {
  return (

      <ActionStatus action={action} />
      <ActionButton action={action} />
      <ActionDetails action={action} />

  )
}

const CompactReportAction = ({action}) => {
  return (

      <ActionButton action={action} />

  )
}

export const ReportFullWorkflow = ({report}) => {
  return (
    <Fieldset id="workflow" className="workflow-fieldset" title="Workflow">
      { report.workflow.map(action => {
        const key = action.step ? `${action.createdAt}-${action.step.uuid}` : action.createdAt
        return <ReportAction action={action} key={key} />
      })}
    </Fieldset>
  )
}

export const ReportCompactWorkflow = ({report}) => {
  return (
    <Fieldset className="workflow-fieldset compact" title="Workflow">
      { report.workflow.map(action => {
        const key = action.step ? `${action.createdAt}-${action.step.uuid}` : action.createdAt
        return <CompactReportAction action={action} key={key} />
      })}
    </Fieldset>
  )
}
<commit_msg>NCI-Agency/anet#1252: Fix datetime formatting in report workflow<commit_after>import PropTypes from 'prop-types'
import React, {Component} from 'react'
import {Button, Modal} from 'react-bootstrap'
import './ReportWorkflow.css'
import Settings from 'Settings'
import LinkTo from 'components/LinkTo'

import Fieldset from 'components/Fieldset'
import moment from 'moment'

const APPROVE = 'APPROVE'
const REJECT = 'REJECT'
const SUBMIT = 'SUBMIT'
const PUBLISH = 'PUBLISH'

const ACTION_TYPE_DETAILS = {
  APPROVE: {text: 'Approved', cssClass: 'btn-success approved'},
  REJECT: {text: 'Changes requested', cssClass: 'btn-danger rejected'},
  SUBMIT: {text: 'Submitted', cssClass: 'btn-pending submitted'},
  PUBLISH: {text: 'Published', cssClass: 'btn-success published'},
  null: {text: 'Pending', cssClass: 'btn-pending default'}
}

const ApprovalStepModalStatus = ({action}) => {
  if (action.type) {
    const actionType = ACTION_TYPE_DETAILS[action.type]
    const cssClass = 'label ' + actionType.cssClass
    return (
      {actionType.text} by <LinkTo person={action.person} isLink= {false} /> on
         {moment(action.createdAt).format(Settings.dateFormats.forms.withTime)}

    )
  }
  return Pending
}

class ApprovalStepModal extends Component {
  static propTypes = {
    action: PropTypes.object.isRequired,
  }

  constructor(props){
    super(props)
    this.state = {
      showModal: false
    }
  }

  closeModal = () => {
    this.setState({ showModal: false })
  }

  openModal = () => {
    this.setState({ showModal: true })
  }

  render() {
    const { action } = this.props
    const step = action.step
    const actionTypeCss =  ACTION_TYPE_DETAILS[action.type].cssClass
    return (
      step ?
        <React.Fragment>
          <Button className={actionTypeCss + ' btn-sm'} onClick={this.openModal}>
            {step.name}
          </Button>
          <Modal show={this.state.showModal} onHide={this.closeModal}>
            <Modal.Header closeButton>
                <Modal.Title>Approvers for {step.name}</Modal.Title>
            </Modal.Header>
            <Modal.Body>

              {step.approvers.map(position =>

                  <LinkTo position={position} /> - <LinkTo person={position.person} />

              )}

            </Modal.Body>
            <Modal.Footer>
              <ApprovalStepModalStatus action={action} />
            </Modal.Footer>
          </Modal>
        </React.Fragment>
      :
        null
    )
  }
}

const ActionStatus = ({action}) => {
  return
{ACTION_TYPE_DETAILS[action.type].text}

}

const ActionButton = ({action}) => {
  const step = action.step
  const actionType =  ACTION_TYPE_DETAILS[action.type]
  return (
    step ?
      <ApprovalStepModal action={action} />
    :
      <Button className={actionType.cssClass + ' btn-sm'}>
        <LinkTo person={action.person} isLink={false} />
      </Button>
  )
}

const ActionDetails = ({action}) => {
  if (action.type) {
    return(

        By <LinkTo person={action.person} />

          On {moment(action.createdAt).format(Settings.dateFormats.forms.withTime)}

    )
  }
  return null
}

const ReportAction = ({action}) => {
  return (

      <ActionStatus action={action} />
      <ActionButton action={action} />
      <ActionDetails action={action} />

  )
}

const CompactReportAction = ({action}) => {
  return (

      <ActionButton action={action} />

  )
}

export const ReportFullWorkflow = ({report}) => {
  return (
    <Fieldset id="workflow" className="workflow-fieldset" title="Workflow">
      { report.workflow.map(action => {
        const key = action.step ? `${action.createdAt}-${action.step.uuid}` : action.createdAt
        return <ReportAction action={action} key={key} />
      })}
    </Fieldset>
  )
}

export const ReportCompactWorkflow = ({report}) => {
  return (
    <Fieldset className="workflow-fieldset compact" title="Workflow">
      { report.workflow.map(action => {
        const key = action.step ? `${action.createdAt}-${action.step.uuid}` : action.createdAt
        return <CompactReportAction action={action} key={key} />
      })}
    </Fieldset>
  )
}
<|endoftext|>


<commit_before>Template.addProject.events({
	"click .addLine": function(event){
		event.preventDefault();
		Session.set("featurearrayLength", Session.get("featurearrayLength")+1);
	},

	"click .displayPreview": function(event, template){
		event.preventDefault();
		Session.set("descmarkdown", template.$('#projectdesc').val());
	},

	"submit form": function(event, template){
		event.preventDefault();

		var newProject = {
			_name: event.target.projectname.value,
			_public: event.target.projectpublic.checked,
			_slug: event.target.projectslug.value,
			_tags: event.target.projecttags.value,
			_desc: event.target.projectdesc.value,
			_start: event.target.projectstart.value,
			_createdAt: new Date(),
			_modifiedAt: new Date()
		}

		var found = true;
		var featArr = [];
		var featIdx = 0;
		while(found)
		{
			if(			typeof(event.target["feature"+featIdx]) !== "undefined"
					&&	event.target["feature"+featIdx].value.length > 0)
			{
				featArr[featIdx] =
					{
						_idx: featIdx,
						_feat: event.target["feature"+featIdx].value
					}
			}
			else
			{
				found = false;
			}
			featIdx++;
		}
		newProject._features = featArr;

		Projects.insert(newProject);
		Router.go('/projects');
	}
});

Template.addProject.helpers({
	featurearray: function(){
		var arr = [];
		// TODO: switch to Session.equals()?
		var count = Session.get("featurearrayLength");
		for(var i=0; i<count; i++)
		{
			arr[i] = {
				_idx: i
			};
		}
		return arr;
	},

	getDescriptionMarkdown: function(){
		return Session.get("descmarkdown");
	}
});

Template.addProject.rendered = function() {
	Session.set("featurearrayLength", 3);
	Session.set("descmarkdown","");
  this.$('.datepicker').datepicker();
}<commit_msg>Resolve #9, though it seems to be running into the #21 issue. Will verify later :P<commit_after>Template.addProject.events({
	"click .addLine": function(event){
		event.preventDefault();
		Session.set("featurearrayLength", Session.get("featurearrayLength")+1);
	},

	"click .displayPreview": function(event, template){
		event.preventDefault();
		Session.set("descmarkdown", template.$('#projectdesc').val());
	},

	"submit form": function(event, template){
		event.preventDefault();

		var newProject = {
			_name: event.target.projectname.value,
			_public: event.target.projectpublic.checked,
			_slug: event.target.projectslug.value,
			_tags: event.target.projecttags.value,
			_desc: event.target.projectdesc.value,
			_start: event.target.projectstart.value,
			_createdAt: new Date(),
			_modifiedAt: new Date()
		}

		var found = true;
		var featArr = [];
		var featIdx = 0;
		while(found)
		{
			if(			typeof(event.target["feature"+featIdx]) !== "undefined"
					&&	event.target["feature"+featIdx].value.length > 0)
			{
				featArr[featIdx] =
					{
						_idx: featIdx,
						_feat: event.target["feature"+featIdx].value
					}
			}
			else
			{
				found = false;
			}
			featIdx++;
		}
		newProject._features = featArr;

		var projectid = Projects.insert(newProject);

		// and now, glue in a log entry commemorating the creation of the project
		var newActivity = {
			_project: projectid,
			_date: 		(new Date()).toISOString().slice(0,10), // nice-format date
			_summary: "Website presence established",
			_desc: 		"On this date, this project was created here on this site. How exciting!"
		};

		ActivityLog.insert(newActivity);

		// finally, go somewhere else.
		Router.go('/projects');
	}
});

Template.addProject.helpers({
	featurearray: function(){
		var arr = [];
		// TODO: switch to Session.equals()?
		var count = Session.get("featurearrayLength");
		for(var i=0; i<count; i++)
		{
			arr[i] = {
				_idx: i
			};
		}
		return arr;
	},

	getDescriptionMarkdown: function(){
		return Session.get("descmarkdown");
	}
});

Template.addProject.rendered = function() {
	Session.set("featurearrayLength", 3);
	Session.set("descmarkdown","");
  this.$('.datepicker').datepicker();
}<|endoftext|>


<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/**
 * @fileoverview Test cases for jspb's binary protocol buffer writer. In
 * practice BinaryWriter is used to drive the Decoder and Reader test cases,
 * so only writer-specific tests are here.
 *
 * Test suite is written using Jasmine -- see http://jasmine.github.io/
 *
 * @author aappleby@google.com (Austin Appleby)
 */

goog.require('goog.crypt');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryWriter');

/**
 * @param {function()} func This function should throw an error when run.
 */
function assertFails(func) {
  var e = assertThrows(func);
  console.log(e);
  //assertNotNull(e.toString().match(/Error/));
}

describe('binaryWriterTest', function() {
  /**
   * Verifies that misuse of the writer class triggers assertions.
   */
  it('testWriteErrors', function() {
    // Submessages with invalid field indices should assert.
    var writer = new jspb.BinaryWriter();
    var dummyMessage = /** @type {!jspb.BinaryMessage} */({});

    assertFails(function() {
      writer.writeMessage(-1, dummyMessage, goog.nullFunction);
    });

    // Writing invalid field indices should assert.
    writer = new jspb.BinaryWriter();
    assertFails(function() {writer.writeUint64(-1, 1);});

    // Writing out-of-range field values should assert.
    writer = new jspb.BinaryWriter();

    assertFails(function() {writer.writeInt32(1, -Infinity);});
    assertFails(function() {writer.writeInt32(1, Infinity);});

    assertFails(function() {writer.writeInt64(1, -Infinity);});
    assertFails(function() {writer.writeInt64(1, Infinity);});

    assertFails(function() {writer.writeUint32(1, -1);});
    assertFails(function() {writer.writeUint32(1, Infinity);});

    assertFails(function() {writer.writeUint64(1, -1);});
    assertFails(function() {writer.writeUint64(1, Infinity);});

    assertFails(function() {writer.writeSint32(1, -Infinity);});
    assertFails(function() {writer.writeSint32(1, Infinity);});

    assertFails(function() {writer.writeSint64(1, -Infinity);});
    assertFails(function() {writer.writeSint64(1, Infinity);});

    assertFails(function() {writer.writeFixed32(1, -1);});
    assertFails(function() {writer.writeFixed32(1, Infinity);});

    assertFails(function() {writer.writeFixed64(1, -1);});
    assertFails(function() {writer.writeFixed64(1, Infinity);});

    assertFails(function() {writer.writeSfixed32(1, -Infinity);});
    assertFails(function() {writer.writeSfixed32(1, Infinity);});

    assertFails(function() {writer.writeSfixed64(1, -Infinity);});
    assertFails(function() {writer.writeSfixed64(1, Infinity);});
  });

  /**
   * Basic test of retrieving the result as a Uint8Array buffer
   */
  it('testGetResultBuffer', function() {
    var expected = '0864120b48656c6c6f20776f726c641a0301020320c801';

    var writer = new jspb.BinaryWriter();
    writer.writeUint32(1, 100);
    writer.writeString(2, 'Hello world');
    writer.writeBytes(3, new Uint8Array([1, 2, 3]));
    writer.writeUint32(4, 200);

    var buffer = writer.getResultBuffer();
    assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
  });
});
<commit_msg>Removed log statement from writer_test.js<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/**
 * @fileoverview Test cases for jspb's binary protocol buffer writer. In
 * practice BinaryWriter is used to drive the Decoder and Reader test cases,
 * so only writer-specific tests are here.
 *
 * Test suite is written using Jasmine -- see http://jasmine.github.io/
 *
 * @author aappleby@google.com (Austin Appleby)
 */

goog.require('goog.crypt');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryWriter');

/**
 * @param {function()} func This function should throw an error when run.
 */
function assertFails(func) {
  var e = assertThrows(func);
}

describe('binaryWriterTest', function() {
  /**
   * Verifies that misuse of the writer class triggers assertions.
   */
  it('testWriteErrors', function() {
    // Submessages with invalid field indices should assert.
    var writer = new jspb.BinaryWriter();
    var dummyMessage = /** @type {!jspb.BinaryMessage} */({});

    assertFails(function() {
      writer.writeMessage(-1, dummyMessage, goog.nullFunction);
    });

    // Writing invalid field indices should assert.
    writer = new jspb.BinaryWriter();
    assertFails(function() {writer.writeUint64(-1, 1);});

    // Writing out-of-range field values should assert.
    writer = new jspb.BinaryWriter();

    assertFails(function() {writer.writeInt32(1, -Infinity);});
    assertFails(function() {writer.writeInt32(1, Infinity);});

    assertFails(function() {writer.writeInt64(1, -Infinity);});
    assertFails(function() {writer.writeInt64(1, Infinity);});

    assertFails(function() {writer.writeUint32(1, -1);});
    assertFails(function() {writer.writeUint32(1, Infinity);});

    assertFails(function() {writer.writeUint64(1, -1);});
    assertFails(function() {writer.writeUint64(1, Infinity);});

    assertFails(function() {writer.writeSint32(1, -Infinity);});
    assertFails(function() {writer.writeSint32(1, Infinity);});

    assertFails(function() {writer.writeSint64(1, -Infinity);});
    assertFails(function() {writer.writeSint64(1, Infinity);});

    assertFails(function() {writer.writeFixed32(1, -1);});
    assertFails(function() {writer.writeFixed32(1, Infinity);});

    assertFails(function() {writer.writeFixed64(1, -1);});
    assertFails(function() {writer.writeFixed64(1, Infinity);});

    assertFails(function() {writer.writeSfixed32(1, -Infinity);});
    assertFails(function() {writer.writeSfixed32(1, Infinity);});

    assertFails(function() {writer.writeSfixed64(1, -Infinity);});
    assertFails(function() {writer.writeSfixed64(1, Infinity);});
  });

  /**
   * Basic test of retrieving the result as a Uint8Array buffer
   */
  it('testGetResultBuffer', function() {
    var expected = '0864120b48656c6c6f20776f726c641a0301020320c801';

    var writer = new jspb.BinaryWriter();
    writer.writeUint32(1, 100);
    writer.writeString(2, 'Hello world');
    writer.writeBytes(3, new Uint8Array([1, 2, 3]));
    writer.writeUint32(4, 200);

    var buffer = writer.getResultBuffer();
    assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
  });
});
<|endoftext|>


<commit_before>import '/imports/ui/FilterPreview.js';

Template.filter.onCreated(function() {
	this.stateFilters =
		[
			{ name: 'proposal'
			, cssClass: 'is-proposal'
			, label: mf('filterCaptions.is-proposal', 'Proposal')
			, title: mf('filterCaptions.showProposal', 'Show all proposed courses')
			}
		,
			{ name: 'upcomingEvent'
			, cssClass: 'has-upcoming-events'
			, label: mf('filterCaptions.upcoming.label', 'Upcoming')
			, title: mf('filterCaptions.upcoming.title', 'Show all courses with upcoming events')
			}
		,
			{ name: 'pastEvent'
			, cssClass: 'has-past-events'
			, label: mf('filterCaptions.passed.label', 'Passed')
			, title: mf('filterCaptions.passed.title', 'Show all courses with passed events')
			}
		];

	this.visibleFilters = ['state', 'needsRole', 'categories'];
});

Template.filter.helpers({
	filterClasses() {
		const classes = [];
		const instance = Template.instance();
		const parentInstance = instance.parentInstance();

		// check if one of the filters indicated as filters is active
		let activeVisibleFilter = false;
		instance.visibleFilters.forEach(filter => {
			if (parentInstance.filter.get(filter)) activeVisibleFilter = true;
		});

		if (activeVisibleFilter) classes.push('active');

		if (parentInstance.showingFilters.get()) classes.push('open');

		return classes.join(' ');
	},

	stateFilters() {
		return Template.instance().stateFilters;
	},

	stateFilterClasses(stateFilter) {
		const classes = [];
		const parentInstance = Template.instance().parentInstance();

		classes.push(stateFilter.cssClass);

		if (parentInstance.filter.get('state') == stateFilter.name) {
			classes.push('active');
		}

		return classes.join(' ');
	},

	showingFilters() {
		return Template.instance().parentInstance().showingFilters.get();
	}
});

Template.filter.events({
	'click #toggleFilters'(e, instance) {
		const parentInstance = instance.parentInstance();
		const showingFilters = parentInstance.showingFilters;

		if (showingFilters.get()) {
			instance.visibleFilters.forEach(filter => {
				parentInstance.filter.disable(filter);
			});

			parentInstance.filter.done();
			parentInstance.updateUrl();
			showingFilters.set(false);
		} else {
			showingFilters.set(true);
		}
	},

	'click .js-filter-caption'(e, instance) {
		const parentInstance = instance.parentInstance();
		const filterName = instance.$(e.currentTarget).data('filter-name');

		parentInstance.filter
			.toggle('state', filterName)
			.done();

		parentInstance.updateUrl();
	},

	'mouseover .js-filter-caption, mouseout .js-filter-caption'(e, instance) {
		const name = instance.$(e.currentTarget).data('filter-name');
		const state = _.findWhere(instance.stateFilters, { name });

		if (!instance.parentInstance().filter.get('state')) {
			FilterPreview({
				property: 'state',
				id: state.cssClass,
				activate: e.type == 'mouseover'
			});
		}
	}
});

Template.additionalFilters.onCreated(function() {
	this.findInstance = this.parentInstance(2);

	this.roles =
		[
			{ name: 'team'
			, label: mf('find.needsOrganizer', 'Looking for an organizer')
			}
		,
			{ name: 'mentor'
			, label: mf('find.needsMentor', 'Looking for a mentor')
			}
		,
			{ name: 'host'
			, label: mf('find.needsHost', 'Looking for a host')
			}
		]
		.map(role => {
			// add icon from Roles collection to role object
			role.icon =
				_.findWhere(Roles, { type: role.name } ).icon;

			return role;
		});
});

Template.additionalFilters.onRendered(function() {
	const instance = this;
	const catSelect = instance.$('.filter-categories-select');

	catSelect.on('show.bs.dropdown hide.bs.dropdown', () => {
		instance.$('.dropdown-toggle').fadeToggle(200);
	});

	catSelect.on('shown.bs.dropdown', () => {
		instance.$('.js-search-categories').select();
	});
});

Template.additionalFilters.helpers({
	roles() {
		return Template.instance().roles;
	},

	roleClasses(role) {
		const classes = [];
		const findInstance = Template.instance().findInstance;
		const needsRoleFilter = findInstance.filter.get('needsRole');

		if (needsRoleFilter && needsRoleFilter.indexOf(role.name) >= 0) {
			classes.push('active');
		}

		return classes.join(' ');
	},

	categories() {
		const findInstance = Template.instance().findInstance;
		return findInstance.filter.get('categories');
	},

	availableCategories() {
		const findInstance = Template.instance().findInstance;
		return Object.keys(findInstance.categorySearchResults.get());
	},

	availableSubcategories(mainCategory) {
		const findInstance = Template.instance().findInstance;
		return findInstance.categorySearchResults.get()[mainCategory];
	},

	categoryNameMarked() {
		Session.get('locale'); // Reactive dependency
		const search =
			Template.instance().findInstance.categorySearch.get();

		return markedName(search, mf('category.' + this));
	},

	isMobile() {
		return Session.get('viewportWidth') <= SCSSVars.screenXS;
	}
});

Template.additionalFilters.events({
	'click .js-filter-course-role'(e, instance) {
		const findInstance = instance.findInstance;
		const filterName = instance.$(e.currentTarget).data('filter-name');

		findInstance.filter
			.toggle('needsRole', filterName)
			.done();

		findInstance.updateUrl();
	},

	'mouseover .js-filter-course-role, mouseout .js-filter-course-role'(e, instance) {
		FilterPreview({
			property: 'role',
			id: instance.$(e.currentTarget).data('filter-name'),
			activate: e.type == 'mouseover'
		});
	},

	'mouseout .js-category-selection-label, mouseover .js-category-selection-label'(e) {
		FilterPreview({
			property: 'category',
			id: this,
			activate: e.type == 'mouseover'
		});
	},

	'keyup .js-search-categories'(e, instance) {
		const query = instance.$('.js-search-categories').val();

		instance.findInstance.updateCategorySearchDebounced(query);
	},

	'click .js-search-categories'(e, instance) {
		instance.$('.dropdown-toggle').dropdown('toggle');
	},

	'click .js-toggle-subcategories'(event, instance) {
		event.stopPropagation();
		instance.$(".js-sub-category" + "." + this).toggle();
		instance.$(".js-toggle-subcategories." + this + " span")
			.toggleClass('fa-angle-down fa-angle-up');
	},

	'click .js-category-selection-label'(e, instance) {
		e.preventDefault();
		const findInstance = instance.findInstance;

		// Add to filter
		findInstance.filter.add('categories', "" + this).done();

		// Clear search field
		instance.$('.js-search-categories').val('');

		findInstance.updateCategorySearch('');
		findInstance.updateUrl();

		window.scrollTo(0, 0);
	},

	'click .js-remove-category-btn'(e, instance) {
		const findInstance = instance.findInstance;

		findInstance.filter.remove('categories', '' + this).done();
		findInstance.updateUrl();
	}
});
<commit_msg>change course state label 'passed' to 'resting'<commit_after>import '/imports/ui/FilterPreview.js';

Template.filter.onCreated(function() {
	this.stateFilters =
		[
			{ name: 'proposal'
			, cssClass: 'is-proposal'
			, label: mf('filterCaptions.is-proposal', 'Proposal')
			, title: mf('filterCaptions.showProposal', 'Show all proposed courses')
			}
		,
			{ name: 'upcomingEvent'
			, cssClass: 'has-upcoming-events'
			, label: mf('filterCaptions.upcoming.label', 'Upcoming')
			, title: mf('filterCaptions.upcoming.title', 'Show all courses with upcoming events')
			}
		,
			{ name: 'pastEvent'
			, cssClass: 'has-past-events'
			, label: mf('filterCaptions.resting.label', 'Resting')
			, title: mf('filterCaptions.resting.title', 'Show all courses which already had events')
			}
		];

	this.visibleFilters = ['state', 'needsRole', 'categories'];
});

Template.filter.helpers({
	filterClasses() {
		const classes = [];
		const instance = Template.instance();
		const parentInstance = instance.parentInstance();

		// check if one of the filters indicated as filters is active
		let activeVisibleFilter = false;
		instance.visibleFilters.forEach(filter => {
			if (parentInstance.filter.get(filter)) activeVisibleFilter = true;
		});

		if (activeVisibleFilter) classes.push('active');

		if (parentInstance.showingFilters.get()) classes.push('open');

		return classes.join(' ');
	},

	stateFilters() {
		return Template.instance().stateFilters;
	},

	stateFilterClasses(stateFilter) {
		const classes = [];
		const parentInstance = Template.instance().parentInstance();

		classes.push(stateFilter.cssClass);

		if (parentInstance.filter.get('state') == stateFilter.name) {
			classes.push('active');
		}

		return classes.join(' ');
	},

	showingFilters() {
		return Template.instance().parentInstance().showingFilters.get();
	}
});

Template.filter.events({
	'click #toggleFilters'(e, instance) {
		const parentInstance = instance.parentInstance();
		const showingFilters = parentInstance.showingFilters;

		if (showingFilters.get()) {
			instance.visibleFilters.forEach(filter => {
				parentInstance.filter.disable(filter);
			});

			parentInstance.filter.done();
			parentInstance.updateUrl();
			showingFilters.set(false);
		} else {
			showingFilters.set(true);
		}
	},

	'click .js-filter-caption'(e, instance) {
		const parentInstance = instance.parentInstance();
		const filterName = instance.$(e.currentTarget).data('filter-name');

		parentInstance.filter
			.toggle('state', filterName)
			.done();

		parentInstance.updateUrl();
	},

	'mouseover .js-filter-caption, mouseout .js-filter-caption'(e, instance) {
		const name = instance.$(e.currentTarget).data('filter-name');
		const state = _.findWhere(instance.stateFilters, { name });

		if (!instance.parentInstance().filter.get('state')) {
			FilterPreview({
				property: 'state',
				id: state.cssClass,
				activate: e.type == 'mouseover'
			});
		}
	}
});

Template.additionalFilters.onCreated(function() {
	this.findInstance = this.parentInstance(2);

	this.roles =
		[
			{ name: 'team'
			, label: mf('find.needsOrganizer', 'Looking for an organizer')
			}
		,
			{ name: 'mentor'
			, label: mf('find.needsMentor', 'Looking for a mentor')
			}
		,
			{ name: 'host'
			, label: mf('find.needsHost', 'Looking for a host')
			}
		]
		.map(role => {
			// add icon from Roles collection to role object
			role.icon =
				_.findWhere(Roles, { type: role.name } ).icon;

			return role;
		});
});

Template.additionalFilters.onRendered(function() {
	const instance = this;
	const catSelect = instance.$('.filter-categories-select');

	catSelect.on('show.bs.dropdown hide.bs.dropdown', () => {
		instance.$('.dropdown-toggle').fadeToggle(200);
	});

	catSelect.on('shown.bs.dropdown', () => {
		instance.$('.js-search-categories').select();
	});
});

Template.additionalFilters.helpers({
	roles() {
		return Template.instance().roles;
	},

	roleClasses(role) {
		const classes = [];
		const findInstance = Template.instance().findInstance;
		const needsRoleFilter = findInstance.filter.get('needsRole');

		if (needsRoleFilter && needsRoleFilter.indexOf(role.name) >= 0) {
			classes.push('active');
		}

		return classes.join(' ');
	},

	categories() {
		const findInstance = Template.instance().findInstance;
		return findInstance.filter.get('categories');
	},

	availableCategories() {
		const findInstance = Template.instance().findInstance;
		return Object.keys(findInstance.categorySearchResults.get());
	},

	availableSubcategories(mainCategory) {
		const findInstance = Template.instance().findInstance;
		return findInstance.categorySearchResults.get()[mainCategory];
	},

	categoryNameMarked() {
		Session.get('locale'); // Reactive dependency
		const search =
			Template.instance().findInstance.categorySearch.get();

		return markedName(search, mf('category.' + this));
	},

	isMobile() {
		return Session.get('viewportWidth') <= SCSSVars.screenXS;
	}
});

Template.additionalFilters.events({
	'click .js-filter-course-role'(e, instance) {
		const findInstance = instance.findInstance;
		const filterName = instance.$(e.currentTarget).data('filter-name');

		findInstance.filter
			.toggle('needsRole', filterName)
			.done();

		findInstance.updateUrl();
	},

	'mouseover .js-filter-course-role, mouseout .js-filter-course-role'(e, instance) {
		FilterPreview({
			property: 'role',
			id: instance.$(e.currentTarget).data('filter-name'),
			activate: e.type == 'mouseover'
		});
	},

	'mouseout .js-category-selection-label, mouseover .js-category-selection-label'(e) {
		FilterPreview({
			property: 'category',
			id: this,
			activate: e.type == 'mouseover'
		});
	},

	'keyup .js-search-categories'(e, instance) {
		const query = instance.$('.js-search-categories').val();

		instance.findInstance.updateCategorySearchDebounced(query);
	},

	'click .js-search-categories'(e, instance) {
		instance.$('.dropdown-toggle').dropdown('toggle');
	},

	'click .js-toggle-subcategories'(event, instance) {
		event.stopPropagation();
		instance.$(".js-sub-category" + "." + this).toggle();
		instance.$(".js-toggle-subcategories." + this + " span")
			.toggleClass('fa-angle-down fa-angle-up');
	},

	'click .js-category-selection-label'(e, instance) {
		e.preventDefault();
		const findInstance = instance.findInstance;

		// Add to filter
		findInstance.filter.add('categories', "" + this).done();

		// Clear search field
		instance.$('.js-search-categories').val('');

		findInstance.updateCategorySearch('');
		findInstance.updateUrl();

		window.scrollTo(0, 0);
	},

	'click .js-remove-category-btn'(e, instance) {
		const findInstance = instance.findInstance;

		findInstance.filter.remove('categories', '' + this).done();
		findInstance.updateUrl();
	}
});
<|endoftext|>