<commit_before>/**
 * This is the History in Black and White JS file
 * @author Matthias Steinbauer <matthias.steinbauer@jku.at>
 */
var HISTBW = HISTBW || {};

/**
 * This is called by the framework after widget was successfully loaded
 */
function histbw_startup() {
	console.log('History in Black and White started');
	HISTBW.dragElement = null;
	$('#toneDrag').on('mousedown', HISTBW.startDragElement);
	$('#monoDrag').on('mousedown', HISTBW.startDragElement);
	$(document).on('mouseup', HISTBW.stopDragElement);
	$(document).on('mousemove', HISTBW.handleMouseMove);
};

/**
 * This is called by the framework right before the widget will be unloaded from DOM
 */
function histbw_teardown() {
	console.log('History in Black and White teardown');
};

/**
 * Reacts to the mouse down
 */
HISTBW.startDragElement = function(evt) {
	console.log('started to drag');
	var dragTarget = $(evt.target);
	HISTBW.dragElement = dragTarget;
	HISTBW.deLeft = HISTBW.dragElement.offset().left;
	HISTBW.deTop = HISTBW.dragElement.offset().top;
	console.log(dragTarget);
};

/**
 * Handle the mouse move events
 */
HISTBW.handleMouseMove = function(evt) {
	if(HISTBW.dragElement != null) {
		if(HISTBW.dragElement.attr('id') === 'monoDrag') {
			$('#mono').width(1024 - evt.pageX);
			$('#mono').height(730 - evt.pageY);
		}else if(HISTBW.dragElement.attr('id') === 'toneDrag') {
			$('#tone').width(evt.pageX);
			$('#tone').height(evt.pageY);
		}
	}
};

/**
 * Reacts to the mouse down
 */
HISTBW.stopDragElement = function(evt) {
	console.log('stopped to drag');
	var dragTarget = $(evt.target);
	console.log(dragTarget);
	HISTBW.dragElement = null;
};

/**
 * The following will run the startup code in cases where we are not
 * embedded in the framework
 */
$(document).ready(function() {
	histbw_startup();
});
<commit_msg>Fixed overlapping Div<commit_after>/**
 * This is the History in Black and White JS file
 * @author Matthias Steinbauer <matthias.steinbauer@jku.at>
 */
var HISTBW = HISTBW || {};

/**
 * This is called by the framework after widget was successfully loaded
 */
function histbw_startup() {
	console.log('History in Black and White started');
	HISTBW.dragElement = null;
	$('#toneDrag').on('mousedown', HISTBW.startDragElement);
	$('#monoDrag').on('mousedown', HISTBW.startDragElement);
	$(document).on('mouseup', HISTBW.stopDragElement);
	$(document).on('mousemove', HISTBW.handleMouseMove);
};

/**
 * This is called by the framework right before the widget will be unloaded from DOM
 */
function histbw_teardown() {
	console.log('History in Black and White teardown');
};

/**
 * Reacts to the mouse down
 */
HISTBW.startDragElement = function(evt) {
	var dragTarget = $(evt.target);
	HISTBW.dragElement = dragTarget;
	HISTBW.deLeft = HISTBW.dragElement.offset().left;
	HISTBW.deTop = HISTBW.dragElement.offset().top;
};

/**
 * Handle the mouse move events
 */
HISTBW.handleMouseMove = function(evt) {
	if(HISTBW.dragElement != null) {
		if(HISTBW.dragElement.attr('id') === 'monoDrag') {
			$('#mono').width(1024 - evt.pageX);
			$('#mono').height(730 - evt.pageY);
		}else if(HISTBW.dragElement.attr('id') === 'toneDrag') {
			$('#tone').width(evt.pageX);
			$('#tone').height(evt.pageY);
		}
		HISTBW.computeOverlap();
	}
};

/**
 * Computes whether tone and mono overlap and from where to where
 */
HISTBW.computeOverlap = function() {
	var mx = 1024 - $('#mono').width();
	var my = 730 - $('#mono').height();
	var tx = $('#tone').width();
	var ty = $('#tone').height();
	if(mx < tx && my < ty) {
		console.log('overlap!');
		$('#monotone').show();
		var w = tx - mx;
		var h = ty - my;
		console.log('mx ' + mx + ' my ' + my + ' tx ' + tx + ' ty ' + ty);

		console.log('displaying monotone w ' + w + ' h ' + h);
		$('#monotone').width(w);
		$('#monotone').height(h);
		$('#monotone').offset({ left: mx, top: my });
		$('#monotone').css('background-position', '-' + mx + 'px -' + my + 'px');
	}else{
		console.log('exit overlap');
		$('#monotone').hide();
	}
	// console.log('mx ' + mx + ' my ' + my + ' tx ' + tx + ' ty ' + ty);
};

/**
 * Reacts to the mouse down
 */
HISTBW.stopDragElement = function(evt) {
	var dragTarget = $(evt.target);
	HISTBW.dragElement = null;
};

/**
 * The following will run the startup code in cases where we are not
 * embedded in the framework
 */
$(document).ready(function() {
	histbw_startup();
});
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import VideoOutput from '../output';

describe('Video output', () => {
  it('should produce valid AMP output', async () => {
    const props = {
      element: {
        id: '123',
        type: 'video',
        mimeType: 'video/mp4',
        scale: 1,
        origRatio: 9 / 16,
        x: 50,
        y: 100,
        height: 1920,
        width: 1080,
        rotationAngle: 0,
        loop: true,
        resource: {
          type: 'video',
          mimeType: 'video/mp4',
          id: 123,
          src: 'https://example.com/image.png',
          poster: 'https://example.com/poster.png',
          height: 1920,
          width: 1080,
        },
      },
      box: { width: 1080, height: 1920, x: 50, y: 100, rotationAngle: 0 },
    };

    await expect(<VideoOutput {...props} />).toBeValidAMPStoryElement();
  });
});
<commit_msg>Update output.js<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
/**
 * External dependencies
 */
import { renderToStaticMarkup } from 'react-dom/server';
import VideoOutput from '../output';

describe('Video output', () => {
  const baseProps = {
    element: {
      id: '123',
      type: 'video',
      mimeType: 'video/mp4',
      scale: 1,
      origRatio: 9 / 16,
      x: 50,
      y: 100,
      height: 1920,
      width: 1080,
      rotationAngle: 0,
      loop: true,
      resource: {
        type: 'video',
        mimeType: 'video/mp4',
        id: 123,
        src: 'https://example.com/image.png',
        poster: 'https://example.com/poster.png',
        alt: 'alt text',
        height: 1920,
        width: 1080,
      },
    },
    box: { width: 1080, height: 1920, x: 50, y: 100, rotationAngle: 0 },
  };

  it('should produce valid AMP output', async () => {
    await expect(<VideoOutput {...baseProps} />).toBeValidAMPStoryElement();
  });

  it('an undefined alt tag in the element should fall back to the resource', async () => {
    const props = {
      ...baseProps,
      element: { ...baseProps.element, alt: undefined },
    };
    const output = <VideoOutput {...props} />;
    await expect(output).toBeValidAMPStoryElement();
    const outputStr = renderToStaticMarkup(output);
    await expect(outputStr).toStrictEqual(expect.stringMatching('alt text'));
  });

  it('an empty string alt tag in the element should not fall back to the resource', async () => {
    const props = { ...baseProps, element: { ...baseProps.element, alt: '' } };
    const output = <VideoOutput {...props} />;
    await expect(output).toBeValidAMPStoryElement();
    const outputStr = renderToStaticMarkup(output);
    await expect(outputStr).not.toStrictEqual(
      expect.stringMatching('alt text')
    );
  });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name projectVApp.controller:MissionCtrl
 * @description
 * # MissionCtrl
 * Controller of the projectVApp
 */

var BOSS_DESCRIPTION = {
  'TPE-4':{name:'祭止兀',img:'images/head-tsai.png'},
  'TPQ-6':{name:'林鴻池',img:'images/head-lin.png'},
  'TPQ-1':{name:'WEGO昇',img:'images/head-wu.png'},
};

angular.module('projectVApp')
  .controller('MissionCtrl',
  function ($scope, $route, $routeParams, voteInfoService, FeedService) {

    var county = $routeParams.county;
    var effectPrefix = 'effect:';
    var areaPrefix = 'area:';
    var typePrefix = 'type:';
    var RE_SPEECHV = /「(.+)」.*by(.*)。/i;

    $scope.miscope = {};

    $scope.miscope.county = county;

    $scope.miscope.vCount = 0;
    $scope.miscope.vTotal = 0;
    $scope.miscope.sCount = 0;
    $scope.miscope.sTotal = 0;
    $scope.miscope.boss = BOSS_DESCRIPTION[county];
    $scope.miscope.newCitizen = [];
    $scope.miscope.mapLoadingComplete = false;

    FeedService.parseFeed('http://appyv.tumblr.com/rss').then(function(res) {
      var entries = res.data.responseData.feed.entries;
      var item = entries[Math.floor(Math.random() * entries.length)];
      var matched = item.content.match(RE_SPEECHV);
      var parser = new DOMParser();
      var doc = parser.parseFromString(item.content, "text/html");
      if (matched) {
        $scope.speech = matched[1];
        $scope.citizen = matched[2];
        var avatar = doc.querySelector('img');
        if (avatar) {
          $scope.citizenAvatar = {
            'background-image': 'url(' + avatar.src + ')'
          };
        }
      }
    });

    FeedService.parseFeed('http://appytw.tumblr.com/rss').then(function(res) {
      var rawFeeds = res.data.responseData.feed.entries;
      var feeds = [];
      var bossFeeds = [];
      var citizenFeeds = [];
      angular.forEach(rawFeeds, function(feed) {
        angular.forEach(feed.categories, function(c) {
          if (c.indexOf(areaPrefix) === 0) {
            feed.area = c.substr(areaPrefix.length);
          } else if (c.indexOf(effectPrefix) === 0) {
            feed.effect = c.substr(effectPrefix.length).replace('-', ' ');
          } else if (c.indexOf(typePrefix) === 0) {
            feed.type = c.substr(typePrefix.length);
          }
        });
        if (!feed.area) {
          feed.area = 'all';
        }
        if (feed.area === 'all' || feed.area === county) {
          feeds.push(feed);
        }
      });

      angular.forEach(feeds, function(f) {
        if (f.type === 'boss') {
          bossFeeds.push(f);
        } else if (f.type && f.type !== 'v') {
          citizenFeeds.push(f);
        }
      });

      console.log(rawFeeds);

      $scope.bossFeeds = angular.copy(bossFeeds);
      $scope.citizenFeeds = angular.copy(citizenFeeds);

    });

    function loadData(){
      voteInfoService.getAllVoteStatInfo(county).then(function(data){
        //console.log('--data--',data);
        var vCount = 0;
        var vTotal = 0;
        var sCount = 0;
        var sTotal = 0;
        for(var key in data){
          var vtempTotal = voteInfoService.volCount * data[key].vweight;
          vTotal += vtempTotal;
          vCount += data[key].vCount >= vtempTotal ?  vtempTotal : data[key].vCount;
          for(var item in voteInfoService.supplementItem ){
            var stempTotal = voteInfoService.supplementItem[item][0] * data[key].vweight;
            sTotal += stempTotal;
            sCount += data[key].sItemCount[item] >= stempTotal ? stempTotal : data[key].sItemCount[item];
          }
        }
        $scope.miscope.vCount = vCount;
        $scope.miscope.vTotal = vTotal;
        $scope.miscope.sCount = sCount;
        $scope.miscope.sTotal = sTotal;
      });
      //voteInfoService.getTopkCitizen(county,4).then(function(data){
      //  $scope.miscope.newCitizen = data;
      //});
    }
    loadData();

    $scope.$on('missionDataReload',function(){
        console.log('mission load data');
        loadData();
    });

    $scope.miscope.missionAdd = function(){
      $('html, body').animate({scrollTop: $('#mission_map_title').offset().top}, 500);
    };

    //$scope.$on('mapLoadingComplete',function(){
    //  $scope.miscope.mapLoadingComplete = true;
    //});

  });
<commit_msg>fixed #50, boss and citizen new count <= 6<commit_after>'use strict';

/**
 * @ngdoc function
 * @name projectVApp.controller:MissionCtrl
 * @description
 * # MissionCtrl
 * Controller of the projectVApp
 */

var BOSS_DESCRIPTION = {
  'TPE-4':{name:'祭止兀',img:'images/head-tsai.png'},
  'TPQ-6':{name:'林鴻池',img:'images/head-lin.png'},
  'TPQ-1':{name:'WEGO昇',img:'images/head-wu.png'},
};

angular.module('projectVApp')
  .controller('MissionCtrl',
  function ($scope, $route, $routeParams, voteInfoService, FeedService) {

    var county = $routeParams.county;
    var effectPrefix = 'effect:';
    var areaPrefix = 'area:';
    var typePrefix = 'type:';
    var RE_SPEECHV = /「(.+)」.*by(.*)。/i;

    $scope.miscope = {};

    $scope.miscope.county = county;

    $scope.miscope.vCount = 0;
    $scope.miscope.vTotal = 0;
    $scope.miscope.sCount = 0;
    $scope.miscope.sTotal = 0;
    $scope.miscope.boss = BOSS_DESCRIPTION[county];
    $scope.miscope.newCitizen = [];
    $scope.miscope.mapLoadingComplete = false;

    FeedService.parseFeed('http://appyv.tumblr.com/rss').then(function(res) {
      var entries = res.data.responseData.feed.entries;
      var item = entries[Math.floor(Math.random() * entries.length)];
      var matched = item.content.match(RE_SPEECHV);
      var parser = new DOMParser();
      var doc = parser.parseFromString(item.content, "text/html");
      if (matched) {
        $scope.speech = matched[1];
        $scope.citizen = matched[2];
        var avatar = doc.querySelector('img');
        if (avatar) {
          $scope.citizenAvatar = {
            'background-image': 'url(' + avatar.src + ')'
          };
        }
      }
    });

    FeedService.parseFeed('http://appytw.tumblr.com/rss').then(function(res) {
      var rawFeeds = res.data.responseData.feed.entries;
      var feeds = [];
      var bossFeeds = [];
      var citizenFeeds = [];
      var maxCount = 6;
      angular.forEach(rawFeeds, function(feed) {
        angular.forEach(feed.categories, function(c) {
          if (c.indexOf(areaPrefix) === 0) {
            feed.area = c.substr(areaPrefix.length);
          } else if (c.indexOf(effectPrefix) === 0) {
            feed.effect = c.substr(effectPrefix.length).replace('-', ' ');
          } else if (c.indexOf(typePrefix) === 0) {
            feed.type = c.substr(typePrefix.length);
          }
        });
        if (!feed.area) {
          feed.area = 'all';
        }
        if (feed.area === 'all' || feed.area === county) {
          feeds.push(feed);
        }
      });

      angular.forEach(feeds, function(f) {
        if (f.type === 'boss') {
          if (bossFeeds.length < maxCount) {
            bossFeeds.push(f);
          }
        } else if (f.type && f.type !== 'v') {
          if (citizenFeeds.length < maxCount) {
            citizenFeeds.push(f);
          }
        }
      });

      console.log(rawFeeds);

      $scope.bossFeeds = angular.copy(bossFeeds);
      $scope.citizenFeeds = angular.copy(citizenFeeds);

    });

    function loadData(){
      voteInfoService.getAllVoteStatInfo(county).then(function(data){
        //console.log('--data--',data);
        var vCount = 0;
        var vTotal = 0;
        var sCount = 0;
        var sTotal = 0;
        for(var key in data){
          var vtempTotal = voteInfoService.volCount * data[key].vweight;
          vTotal += vtempTotal;
          vCount += data[key].vCount >= vtempTotal ?  vtempTotal : data[key].vCount;
          for(var item in voteInfoService.supplementItem ){
            var stempTotal = voteInfoService.supplementItem[item][0] * data[key].vweight;
            sTotal += stempTotal;
            sCount += data[key].sItemCount[item] >= stempTotal ? stempTotal : data[key].sItemCount[item];
          }
        }
        $scope.miscope.vCount = vCount;
        $scope.miscope.vTotal = vTotal;
        $scope.miscope.sCount = sCount;
        $scope.miscope.sTotal = sTotal;
      });
      //voteInfoService.getTopkCitizen(county,4).then(function(data){
      //  $scope.miscope.newCitizen = data;
      //});
    }
    loadData();

    $scope.$on('missionDataReload',function(){
        console.log('mission load data');
        loadData();
    });

    $scope.miscope.missionAdd = function(){
      $('html, body').animate({scrollTop: $('#mission_map_title').offset().top}, 500);
    };

    //$scope.$on('mapLoadingComplete',function(){
    //  $scope.miscope.mapLoadingComplete = true;
    //});

  });
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012-2016 InSeven Limited.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

(function($) {

  App.Settings = function(drive, store, gameBoy, console) {
    this.init(drive, store, gameBoy, console);
  };

  jQuery.extend(
    App.Settings.prototype, {

      init: function(drive, store, gameBoy, console) {
        var self = this;
        self.drive = drive;
        self.store = store;
        self.gameBoy = gameBoy;
        self.console = console;
        self.element = $('#screen-settings');
        self.dialog = $('#dialog-settings');
        self.done = new App.Controls.Button($('#screen-settings-done'), { touchUpInside: function() {
          self.hide();
        }});
        self.scroll = new App.Controls.Scroll($('#dialog-settings-body'));

        self.element.get(0).addEventListener('touchmove', function(e) {
          e.preventDefault();
        }, false);

        $('#application-version').text(window.config.version);

        self.touchListener = new App.TouchListener($('#screen-settings-dismiss'), self);

        self.signOut = new App.Controls.Button($('#screen-settings-sign-out'), { touchUpInside: function() {
          utilities.dispatch(function() {
            if (confirm("Sign out of Google Drive?")) {
              self.drive.signOut().fail(function(e) {
                alert("Unable to sign out of Google Drive.\n" + e);
              });
            }
          });
        }});

        self.sound = new App.Controls.Switch($('#switch'), function(target, selected) {
          target.setSelected(selected);
          self.store.setProperty(App.Controller.Domain.SETTINGS, App.Store.Property.SOUND, selected);
          self.gameBoy.setSoundEnabled(selected !== 0);
        });

        var setSoundEnabled = function(enabled) {
          if (enabled === true) {
            var audio = document.getElementById('silent');
            audio.addEventListener('ended', function() {
              self.gameBoy.setSoundEnabled(true);
            });
            audio.play();
          } else {
            self.gameBoy.setSoundEnabled(false);
          }
        }

        self.store.property(App.Controller.Domain.SETTINGS, App.Store.Property.SOUND, function(sound) {
          if (sound !== undefined) {
            self.sound.setSelected(sound);
            setSoundEnabled(sound !== 0);
          } else {
            self.sound.setSelected(1);
            setSoundEnabled(true);
          }
        });

        self.thanks = new App.Controls.Button($('#screen-settings-say-thanks'), { touchUpInside: function() {
          utilities.open_new_window("https://gameplaycolor.com/thanks/");
        }});

        // Speed

        var indexToSpeed = function(index) {
          if (index == 0) {
            return 1.0;
          } else if (index == 1) {
            return 1.5;
          } else if (index == 2) {
            return 2.0;
          } else if (index == 3) {
            return 3.0;
          }
          return 1.0;
        };

        var speedToIndex = function (speed) {
          if (speed == 1.0) {
            return 0;
          } else if (speed == 1.5) {
            return 1;
          } else if (speed == 2.0) {
            return 2;
          } else if (speed == 3.0) {
            return 3;
          }
          return 0;
        }

        self.speed = new App.Controls.Segmented($('#emulation-speed'), function(index) {
          self.speed.setIndex(index);
          var speed = indexToSpeed(index);
          self.gameBoy.setSpeed(speed);
          self.store.setProperty(App.Controller.Domain.SETTINGS, App.Store.Property.SPEED, speed);
        });

        self.store.property(App.Controller.Domain.SETTINGS, App.Store.Property.SPEED, function(speed) {
          if (speed !== undefined) {
            self.gameBoy.setSpeed(speed);
            self.speed.setIndex(speedToIndex(speed));
          }
        });

        // Color

        var colors = ["grape", "cherry", "teal", "lime", "yellow"];

        self.color = new App.Controls.Segmented($('#console-color'), function(index) {
          self.color.setIndex(index);
          self.console.setColor(colors[index]);
          self.store.setProperty(App.Controller.Domain.SETTINGS, App.Store.Property.COLOR, colors[index]);
        });

        self.store.property(App.Controller.Domain.SETTINGS, App.Store.Property.COLOR, function(color) {
          if (color !== undefined) {
            self.color.setIndex(colors.indexOf(color));
          }
        });

      },

      onTouchEvent: function(state, position, timestamp) {
        var self = this;
        if (state == App.Control.Touch.START) {
          self.hide();
        }
      },

      hide: function() {
        var self = this;
        self.element.addClass('hidden');
        setTimeout(function() {
          self.element.css('display', 'none');
        }, 200);
      },

      show: function() {
        var self = this;
        self.element.css('display', 'block');
        setTimeout(function() {
          self.element.removeClass('hidden');
        }, 0);

      }

  });

})(jQuery);
<commit_msg>Ensure we select a default color in the picker.<commit_after>/*
 * Copyright (C) 2012-2016 InSeven Limited.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

(function($) {

  App.Settings = function(drive, store, gameBoy, console) {
    this.init(drive, store, gameBoy, console);
  };

  jQuery.extend(
    App.Settings.prototype, {

      init: function(drive, store, gameBoy, console) {
        var self = this;
        self.drive = drive;
        self.store = store;
        self.gameBoy = gameBoy;
        self.console = console;
        self.element = $('#screen-settings');
        self.dialog = $('#dialog-settings');
        self.done = new App.Controls.Button($('#screen-settings-done'), { touchUpInside: function() {
          self.hide();
        }});
        self.scroll = new App.Controls.Scroll($('#dialog-settings-body'));

        self.element.get(0).addEventListener('touchmove', function(e) {
          e.preventDefault();
        }, false);

        $('#application-version').text(window.config.version);

        self.touchListener = new App.TouchListener($('#screen-settings-dismiss'), self);

        self.signOut = new App.Controls.Button($('#screen-settings-sign-out'), { touchUpInside: function() {
          utilities.dispatch(function() {
            if (confirm("Sign out of Google Drive?")) {
              self.drive.signOut().fail(function(e) {
                alert("Unable to sign out of Google Drive.\n" + e);
              });
            }
          });
        }});

        self.sound = new App.Controls.Switch($('#switch'), function(target, selected) {
          target.setSelected(selected);
          self.store.setProperty(App.Controller.Domain.SETTINGS, App.Store.Property.SOUND, selected);
          self.gameBoy.setSoundEnabled(selected !== 0);
        });

        var setSoundEnabled = function(enabled) {
          if (enabled === true) {
            var audio = document.getElementById('silent');
            audio.addEventListener('ended', function() {
              self.gameBoy.setSoundEnabled(true);
            });
            audio.play();
          } else {
            self.gameBoy.setSoundEnabled(false);
          }
        }

        self.store.property(App.Controller.Domain.SETTINGS, App.Store.Property.SOUND, function(sound) {
          if (sound !== undefined) {
            self.sound.setSelected(sound);
            setSoundEnabled(sound !== 0);
          } else {
            self.sound.setSelected(1);
            setSoundEnabled(true);
          }
        });

        self.thanks = new App.Controls.Button($('#screen-settings-say-thanks'), { touchUpInside: function() {
          utilities.open_new_window("https://gameplaycolor.com/thanks/");
        }});

        // Speed

        var indexToSpeed = function(index) {
          if (index == 0) {
            return 1.0;
          } else if (index == 1) {
            return 1.5;
          } else if (index == 2) {
            return 2.0;
          } else if (index == 3) {
            return 3.0;
          }
          return 1.0;
        };

        var speedToIndex = function (speed) {
          if (speed == 1.0) {
            return 0;
          } else if (speed == 1.5) {
            return 1;
          } else if (speed == 2.0) {
            return 2;
          } else if (speed == 3.0) {
            return 3;
          }
          return 0;
        }

        self.speed = new App.Controls.Segmented($('#emulation-speed'), function(index) {
          self.speed.setIndex(index);
          var speed = indexToSpeed(index);
          self.gameBoy.setSpeed(speed);
          self.store.setProperty(App.Controller.Domain.SETTINGS, App.Store.Property.SPEED, speed);
        });

        self.store.property(App.Controller.Domain.SETTINGS, App.Store.Property.SPEED, function(speed) {
          if (speed !== undefined) {
            self.gameBoy.setSpeed(speed);
            self.speed.setIndex(speedToIndex(speed));
          }
        });

        // Color

        var colors = ["grape", "cherry", "teal", "lime", "yellow"];

        self.color = new App.Controls.Segmented($('#console-color'), function(index) {
          self.color.setIndex(index);
          self.console.setColor(colors[index]);
          self.store.setProperty(App.Controller.Domain.SETTINGS, App.Store.Property.COLOR, colors[index]);
        });

        self.store.property(App.Controller.Domain.SETTINGS, App.Store.Property.COLOR, function(color) {
          if (color !== undefined) {
            self.color.setIndex(colors.indexOf(color));
          } else {
            self.color.setIndex(0);
          }
        });

      },

      onTouchEvent: function(state, position, timestamp) {
        var self = this;
        if (state == App.Control.Touch.START) {
          self.hide();
        }
      },

      hide: function() {
        var self = this;
        self.element.addClass('hidden');
        setTimeout(function() {
          self.element.css('display', 'none');
        }, 200);
      },

      show: function() {
        var self = this;
        self.element.css('display', 'block');
        setTimeout(function() {
          self.element.removeClass('hidden');
        }, 0);

      }

  });

})(jQuery);
<|endoftext|>


<commit_before>(function() {
     function SongPlayer() {
          var SongPlayer = {};

          var currentSong = null;

          /**
          *@desc Buzz object audio file
          *@type {Object}
          */
          var currentBuzzObject = null;

          /**
          * @function setSong
          * @desc Stops currently playing song and loads new audio file as currentBuzzObject
          * @param {Object} song
          */

          var setSong = function(song) {
             if (currentBuzzObject) {
                 currentBuzzObject.stop();
                 currentSong.playing = null;
             }

             currentBuzzObject = new buzz.sound(song.audioUrl, {
                  formats: ['mp3'],
                  preload: true
             });

             currentSong = song;
          };

          SongPlayer.play = function(song) {
              if (currentSong !== song) {
                setSong(song);
                currentBuzzObject.play();
                song.playing = true;
              } else if (currentSong === song) {
                  if (currentBuzzObject.isPaused()) {
                      currentBuzzObject.play();
                  }
              }
          };

          SongPlayer.pause = function(song) {
            currentBuzzObject.pause();
            song.playing = false;
          };

          return SongPlayer;
     }

     angular
         .module('blocJams')
         .factory('SongPlayer', SongPlayer);
 })();<commit_msg>Services 2:Assignment<commit_after>(function() {
     function SongPlayer() {
          var SongPlayer = {};

          var currentSong = null;

          /**
          *@desc holds current song number
          *@type {number}
          */

          var currentBuzzObject = null;

          /**
          * @function setSong
          * @desc Stops currently playing song and loads new audio file as currentBuzzObject
          * @param {Object} song
          */

          var setSong = function(song) {
             if (currentBuzzObject) {
                 currentBuzzObject.stop();
                 currentSong.playing = null;
             }

             currentBuzzObject = new buzz.sound(song.audioUrl, {
                  formats: ['mp3'],
                  preload: true
             });

             currentSong = song;
          };

          /**
           * @function playSong
           * @desc sets song.playing to true and plays current song
           * @param {Object} song
           */

           var playSong = function(song) {
               currentBuzzObject.play();
               song.playing = true;
           };

           /**
            * @function SongPlayer.play
            * @desc plays the current or chosen song
            * @params {Object} song
            */

          SongPlayer.play = function(song) {
              if (currentSong !== song) {
                setSong(song);
                playSong(song);
              } else if (currentSong === song) {
                  if (currentBuzzObject.isPaused()) {
                      currentBuzzObject.play();
                  }
              }
          };

          /**
           * @function SongPlayer.pause
           * @desc pauses currently playing song and sets play boolean to false
           * @param {Object} song
           */

          SongPlayer.pause = function(song) {
            currentBuzzObject.pause();
            song.playing = false;
          };

          return SongPlayer;
     }

     angular
         .module('blocJams')
         .factory('SongPlayer', SongPlayer);
 })();<|endoftext|>


<commit_before>(function($, UI) {

    "use strict";

    UI.component('switcher', {

        defaults: {
            connect : false,
            toggle  : ">*",
            active  : 0
        },

        init: function() {

            var $this = this;

            this.on("click", this.options.toggle, function(e) {
                if ($(this).is('a[href="#"]')) e.preventDefault();
                $this.show(this);
            });

            if (this.options.connect) {

                this.connect = $(this.options.connect).find(".uk-active").removeClass(".uk-active").end();

                var toggles = this.find(this.options.toggle),
                    active   = toggles.filter(".uk-active");

                if (active.length) {
                    this.show(active);
                } else {
                    active = toggles.eq(this.options.active);
                    this.show(active.length ? active : toggles.eq(0));
                }
            }

        },

        show: function(tab) {

            tab = isNaN(tab) ? $(tab) : this.find(this.options.toggle).eq(tab);

            var active = tab;

            if (active.hasClass("uk-disabled")) return;

            this.find(this.options.toggle).filter(".uk-active").removeClass("uk-active");
            active.addClass("uk-active");

            if (this.options.connect && this.connect.length) {

                var index = this.find(this.options.toggle).index(active);

                this.connect.children().removeClass("uk-active").eq(index).addClass("uk-active");
            }

            this.trigger("uk.switcher.show", [active]);
            $(document).trigger("uk-check-display");
        }
    });

    // init code
    $(document).on("uk-domready", function(e) {
        $("[data-uk-switcher]").each(function() {
            var switcher = $(this);

            if (!switcher.data("switcher")) {
                var obj = UI.switcher(switcher, UI.Utils.options(switcher.attr("data-uk-switcher")));
            }
        });
    });

})(jQuery, jQuery.UIkit);<commit_msg>Fixes #434<commit_after>(function($, UI) {

    "use strict";

    UI.component('switcher', {

        defaults: {
            connect : false,
            toggle  : ">*",
            active  : 0
        },

        init: function() {

            var $this = this;

            this.on("click", this.options.toggle, function(e) {
                e.preventDefault();
                $this.show(this);
            });

            if (this.options.connect) {

                this.connect = $(this.options.connect).find(".uk-active").removeClass(".uk-active").end();

                var toggles = this.find(this.options.toggle),
                    active   = toggles.filter(".uk-active");

                if (active.length) {
                    this.show(active);
                } else {
                    active = toggles.eq(this.options.active);
                    this.show(active.length ? active : toggles.eq(0));
                }
            }

        },

        show: function(tab) {

            tab = isNaN(tab) ? $(tab) : this.find(this.options.toggle).eq(tab);

            var active = tab;

            if (active.hasClass("uk-disabled")) return;

            this.find(this.options.toggle).filter(".uk-active").removeClass("uk-active");
            active.addClass("uk-active");

            if (this.options.connect && this.connect.length) {

                var index = this.find(this.options.toggle).index(active);

                this.connect.children().removeClass("uk-active").eq(index).addClass("uk-active");
            }

            this.trigger("uk.switcher.show", [active]);
            $(document).trigger("uk-check-display");
        }
    });

    // init code
    $(document).on("uk-domready", function(e) {
        $("[data-uk-switcher]").each(function() {
            var switcher = $(this);

            if (!switcher.data("switcher")) {
                var obj = UI.switcher(switcher, UI.Utils.options(switcher.attr("data-uk-switcher")));
            }
        });
    });

})(jQuery, jQuery.UIkit);<|endoftext|>


<commit_before>/* ========================================================================
 * Phonon: forms.js v0.0.1
 * http://phonon.quarkdev.com
 * ========================================================================
 * Licensed under MIT (http://phonon.quarkdev.com)
 * ======================================================================== */
;(function (window) {

	'use strict';

	function addListener(inputEl) {
		inputEl.on('focus', onInputFocus);
		inputEl.on('blur', onInputBlur);
	}

	function onInputFocus(evt) {
		evt.target.parentNode.classList.add('input-filled');
	}

	function onInputBlur(evt) {
		if(evt.target.value.trim() === '') {
			evt.target.parentNode.classList.remove('input-filled');
		}
	}

	document.on('pagecreated', function(evt) {
		var page = document.querySelector(evt.detail.page);
		var inputs = page.querySelectorAll('input.with-label'), i = inputs.length - 1;
		for (; i >= 0; i--) {
			addListener(inputs[i]);
		}
	});

}(typeof window !== 'undefined' ? window : this));<commit_msg>fix issue: floating label is not cleared #7<commit_after>/* ========================================================================
 * Phonon: forms.js v0.0.1
 * http://phonon.quarkdev.com
 * ========================================================================
 * Licensed under MIT (http://phonon.quarkdev.com)
 * ======================================================================== */
;(function (window) {

	'use strict';

	function addListener(inputEl) {
		inputEl.on('focus', onInputFocus);
		inputEl.on('blur', onInputBlur);
	}

	function onInputFocus(evt) {
		evt.target.parentNode.classList.add('input-filled');
	}

	function onInputBlur(evt) {
		if(evt.target.value.trim() === '') {
			evt.target.parentNode.classList.remove('input-filled');
		}
	}

	function isInputFilled(input) {
		if(input.value.trim() !== '' && !input.parentNode.classList.contains('input-filled')) {
			input.parentNode.classList.add('input-filled');
		}
	}

	/*
	 * Attachs events once
	 */
	document.on('pagecreated', function(evt) {
		var page = document.querySelector(evt.detail.page);
		var inputs = page.querySelectorAll('input.with-label'), i = inputs.length - 1;
		for (; i >= 0; i--) {
			addListener(inputs[i]);
		}
	});

	/*
	 * Checks if inputs are filled
	 */
	document.on('pageopened', function(evt) {
		var page = document.querySelector(evt.detail.page);
		var inputs = page.querySelectorAll('input.with-label'), i = inputs.length - 1;
		for (; i >= 0; i--) {
			isInputFilled(inputs[i]);
		}
	});

}(typeof window !== 'undefined' ? window : this));<|endoftext|>


<commit_before> (function() {
    function SongPlayer() {
        var SongPlayer = {};

        var currentSong = null;
 /**
 * @desc Buzz object audio file
 * @type {Object}
 */
        var currentBuzzObject = null;
    /**
 * @function setSong
 * @desc Stops currently playing song and loads new audio file as currentBuzzObject
 * @param {Object} song
 */
    var setSong = function(song) {
        if (currentBuzzObject) {
            currentBuzzObject.stop();
            currentSong.playing = null;
        }

        currentBuzzObject = new buzz.sound(song.audioUrl, {
            formats: ['mp3'],
            preload: true
        });

        currentSong = song;
    };
     SongPlayer.play = function(song) {
         if (currentSong !== song) {
             setSong(song);
             currentBuzzObject.play();
             song.playing = true;
              } else if (currentSong === song) {
                    if (currentBuzzObject.isPaused()) {
                        currentBuzzObject.play();
            }
        }
     };

     SongPlayer.pause = function(song) {
        currentBuzzObject.pause();
        song.playing = false;
     };

     return SongPlayer;
 }

     angular
         .module('blocJams')
         .factory('SongPlayer', SongPlayer);
 })();<commit_msg>completed assignment 23<commit_after> (function() {
    function SongPlayer() {
        var SongPlayer = {};
/**
 * @desc current song
 * @type {Object}
 */
        var currentSong = null;
 /**
 * @desc Buzz object audio file
 * @type {Object}
 */
        var currentBuzzObject = null;
    /**
 * @function setSong
 * @desc Stops currently playing song and loads new audio file as currentBuzzObject
 * @param {Object} song
 */
    var setSong = function(song) {
        if (currentBuzzObject) {
            currentBuzzObject.stop();
            currentSong.playing = null;
        }

        currentBuzzObject = new buzz.sound(song.audioUrl, {
            formats: ['mp3'],
            preload: true
        });

        currentSong = song;
    };
    /**
 * @function playSong
 * @desc Plays the current buzz object
 * @param {Object} song
 */
    var playSong = function(song){
        currentBuzzObject.play();
        song.playing = true;

    };

     SongPlayer.play = function(song) {
         if (currentSong !== song) {
             setSong(song);
             playSong(song);
              } else if (currentSong === song) {
                    if (currentBuzzObject.isPaused()) {
                        currentBuzzObject.play();
            }
        }
     };

     SongPlayer.pause = function(song) {
        currentBuzzObject.pause();
        song.playing = false;
     };

     return SongPlayer;
 }

     angular
         .module('blocJams')
         .factory('SongPlayer', SongPlayer);
 })();<|endoftext|>


<commit_before>(function() {
	function SongPlayer($rootScope,Fixtures){

 		// @desc Service Song Player
		var SongPlayer = {};

		//desc album contains list of songs
		var currentAlbum = Fixtures.getAlbum();

		// @desc Buzz object audio file
		var currentBuzzObject = null;

		/**
 			* @desc Stops currently playing song and loads new audio file as currentBuzzObject
 			* @param {Object} song
		*/
		var setSong = function(song) {
    		if (currentBuzzObject) {
        		stopSong();
    		}

    		currentBuzzObject = new buzz.sound(song.audioUrl, {
        		formats: ['mp3'],
        		preload: true
    		});

			currentBuzzObject.bind('timeupdate', function(){
				$rootScope.$apply(function(){
					SongPlayer.currentTime = currentBuzzObject.getTime();
					SongPlayer.volume = currentBuzzObject.getVolume();
				});
			});

    		SongPlayer.currentSong = song;
 		};

		/**
 			* @desc uses play method on currentBuzzObject
 			* @param {Object} song
		*/
		var playSong = function(song, currentBuzzObject){
			currentBuzzObject.play();
			song.playing = true;
			song.muting = false;
		};

		/**
 			* @desc gets an index of given sobg from the currentAlbum
 			* @param {Object} song index
		*/
		var getSongIndex = function(song){
			return currentAlbum.songs.indexOf(song);
		};

		/**
 			* @desc stops playing song
		*/
		var stopSong = function(){
			currentBuzzObject.stop();
			SongPlayer.currentSong.playing = null;
			SongPlayer.currentSong.muting = false;
		};

		//This sets first song of the album as default
		setSong(currentAlbum.songs[0]);

		/**
			 * @desc Current playback time (in seconds) of currently playing song
			 * @type {Number}
		*/
			 SongPlayer.currentTime = 0;

		/**
			 * @desc voulume of the currently playing song
			 * @type {Number}
		*/

		SongPlayer.volume  = 80;
		SongPlayer.maxVolume  = 100;

		/**
 			* @desc Plays a song whether it is paused or not.
 			* @param {Object} currentSong
		*/
		SongPlayer.play = function(song) {
			song = song || SongPlayer.currentSong;
			if(SongPlayer.currentSong !== song){
				setSong(song);
       			playSong(song, currentBuzzObject);
			}
			else if(SongPlayer.currentSong === song) {
				if(currentBuzzObject !== null && currentBuzzObject.isPaused()){
					playSong(song, currentBuzzObject);
				}

			}
     	};

		/**
 			* @desc Pauses a song when it is playing and updates song.playing parameter
		*/
		SongPlayer.pause = function(song){
			song = song || SongPlayer.currentSong;
			currentBuzzObject.pause();
			song.playing = false;
		};

		/**
 			* @desc gets the previous song in the album by decrementing the index
		*/

		SongPlayer.previous = function(){
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex--;

			if(currentSongIndex < 0){
				stopSong();
			} else{
				var song = currentAlbum.songs[currentSongIndex];
				setSong(song);
				playSong(song, currentBuzzObject);
			}
		};

		/**
 			* @desc gets the next song in the album by incrementing the index
		*/
		SongPlayer.next = function(){
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex++;

			if(currentSongIndex >= currentAlbum.songs.length){
				stopSong();
			} else {
				var song = currentAlbum.songs[currentSongIndex];
				setSong(song);
				playSong(song, currentBuzzObject);
			}
		};

		SongPlayer.setCurrentTime = function(time){
			if(currentBuzzObject){
				currentBuzzObject.setTime(time);
			}
		};

		SongPlayer.setVolume = function(volume){
			if(currentBuzzObject){
				currentBuzzObject.setVolume(volume);
			}
		};

		SongPlayer.muteVolume = function(song){
			song = song || SongPlayer.currentSong;
			if(currentBuzzObject){
				currentBuzzObject.mute();
				 song.muting = true;
				console.log("Mute is called")
			}
		};

		SongPlayer.unmuteVolume = function(song){
			song = song || SongPlayer.currentSong;
			if(currentBuzzObject){
				currentBuzzObject.unmute();
				song.muting = false;
				console.log("UnMute is called")
		     }
		}

		return SongPlayer;
	}

	angular
		.module('blocJams')
		.factory('SongPlayer', ['$rootScope', 'Fixtures', SongPlayer])
	 })();

<commit_msg>method documentation added<commit_after>(function() {
	function SongPlayer($rootScope,Fixtures){

 		// @desc Service Song Player
		var SongPlayer = {};

		//desc album contains list of songs
		var currentAlbum = Fixtures.getAlbum();

		// @desc Buzz object audio file
		var currentBuzzObject = null;

		/**
 			* @desc Stops currently playing song and loads new audio file as currentBuzzObject
 			* @param {Object} song
		*/
		var setSong = function(song) {
    		if (currentBuzzObject) {
        		stopSong();
    		}

    		currentBuzzObject = new buzz.sound(song.audioUrl, {
        		formats: ['mp3'],
        		preload: true
    		});

			currentBuzzObject.bind('timeupdate', function(){
				$rootScope.$apply(function(){
					SongPlayer.currentTime = currentBuzzObject.getTime();
					SongPlayer.volume = currentBuzzObject.getVolume();
				});
			});

    		SongPlayer.currentSong = song;
 		};

		/**
 			* @desc uses play method on currentBuzzObject
 			* @param {Object} song
		*/
		var playSong = function(song, currentBuzzObject){
			currentBuzzObject.play();
			song.playing = true;
			song.muting = false;
//			if ( currentBuzzObject.isEnded() ) {
//				this.next();
//				console.log("calling next once ended")
//			}
		};

		/**
 			* @desc gets an index of given sobg from the currentAlbum
 			* @param {Object} song index
		*/
		var getSongIndex = function(song){
			return currentAlbum.songs.indexOf(song);
		};

		/**
 			* @desc stops playing song
		*/
		var stopSong = function(){
			currentBuzzObject.stop();
			SongPlayer.currentSong.playing = null;
			SongPlayer.currentSong.muting = false;
		};

		//This sets first song of the album as default
		setSong(currentAlbum.songs[0]);

		/**
			 * @desc Current playback time (in seconds) of currently playing song
			 * @type {Number}
		*/
			 SongPlayer.currentTime = 0;

		/**
			 * @desc voulume of the currently playing song
			 * @type {Number}
		*/

		SongPlayer.volume  = 80;
		SongPlayer.maxVolume  = 100;

		/**
 			* @desc Plays a song whether it is paused or not.
 			* @param {Object} currentSong
		*/
		SongPlayer.play = function(song) {
			song = song || SongPlayer.currentSong;
			if(SongPlayer.currentSong !== song){
				setSong(song);
       			playSong(song, currentBuzzObject);
			}
			else if(SongPlayer.currentSong === song) {
				if(currentBuzzObject !== null && currentBuzzObject.isPaused()){
					playSong(song, currentBuzzObject);
				}

			}
     	};

		/**
 			* @desc Pauses a song when it is playing and updates song.playing parameter
		*/
		SongPlayer.pause = function(song){
			song = song || SongPlayer.currentSong;
			currentBuzzObject.pause();
			song.playing = false;
		};

		/**
 			* @desc gets the previous song in the album by decrementing the index
		*/

		SongPlayer.previous = function(){
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex--;

			if(currentSongIndex < 0){
				stopSong();
			} else{
				var song = currentAlbum.songs[currentSongIndex];
				setSong(song);
				playSong(song, currentBuzzObject);
			}
		};

		/**
 			* @desc gets the next song in the album by incrementing the index
		*/
		SongPlayer.next = function(){
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex++;

			if(currentSongIndex >= currentAlbum.songs.length){
				stopSong();
			} else {
				var song = currentAlbum.songs[currentSongIndex];
				setSong(song);
				playSong(song, currentBuzzObject);
			}
		};

		/**
 			* @desc updates the current time  while song is playing

		*/
		SongPlayer.setCurrentTime = function(time){
			if(currentBuzzObject){
				currentBuzzObject.setTime(time);
			}
		};

		/**
 			* @desc sets volume the playing song

		*/
		SongPlayer.setVolume = function(volume){
			if(currentBuzzObject){
				currentBuzzObject.setVolume(volume);
			}
		};

		/**
 			* @desc mutes song

		*/
		SongPlayer.muteVolume = function(song){
			song = song || SongPlayer.currentSong;
			if(currentBuzzObject){
				currentBuzzObject.mute();
				 song.muting = true;
			}
		};

		/**
 			* @desc unmutes song

		*/
		SongPlayer.unmuteVolume = function(song){
			song = song || SongPlayer.currentSong;
			if(currentBuzzObject){
				currentBuzzObject.unmute();
				song.muting = false;
		     }
		}

		return SongPlayer;
	}

	angular
		.module('blocJams')
		.factory('SongPlayer', ['$rootScope', 'Fixtures', SongPlayer])
	 })();

<|endoftext|>


<commit_before>(function() {
	function SongPlayer(Fixtures) {

/**
* @desc (Public) Public name for SongPlayer object
* @type {Object}
*/
		var SongPlayer = {};
/**
* @desc (Private) Information for current album
* @type {Object}
*/
		var currentAlbum = Fixtures.getAlbum();
/**
* @desc (Private) Buzz object audio file
* @type {Object}
*/
		var currentBuzzObject = null;
/**
* @function (Private) setSong
* @desc Stops currently playing song and loads new audio file as currentBuzzObject
* @param {Object} song
*/
		var setSong = function(song) {
			if (currentBuzzObject) {
				stopSong(SongPlayer.currentSong);
			}
			currentBuzzObject = new buzz.sound(song.audioUrl,{
				formats: ['mp3'],
				preload: true
			});
			SongPlayer.currentSong = song;
		};
/**
* @function (Private) playSong
* @desc Plays the current Buzz object and sets playing property of the song object to true
* @param {Object} song
*/
		var playSong = function(song){
			currentBuzzObject.play();
			song.playing = true;
		};
/**
* @function (Private) getSongIndex
* @desc Get index of song in the songs array
* @param {Object} song
* @returns {Number}
*/
		var getSongIndex = function(song) {
			return currentAlbum.songs.indexOf(song);
		};
/**
* @function (Private) stopSong
* @desc Stop a song
* @param {Object} song
*/
		var stopSong = function(song) {
			currentBuzzObject.stop();
			song.playing = null;
		};
/**
* @desc (Public) Public name for 'current song' designated object
* @type {Object}
*/
		SongPlayer.currentSong = null;
/**
* @desc (Public) Current playback time (in seconds) of currently playing song
* @type {Number}
*/
		SongPlayer.currentTime = null;
/**
* @function (Public) play
* @desc Plays a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.play = function(song) {
			song = song || SongPlayer.currentSong;
			if (SongPlayer.currentSong !== song) {
				setSong(song);
				playSong(song);
			}
			else if (SongPlayer.currentSong === song) {
				if (currentBuzzObject.isPaused()) {
					playSong(song);
				}
			}
		};
/**
* @function (Public) pause
* @desc Pauses a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.pause = function(song) {
			song = song || SongPlayer.currentSong;
			currentBuzzObject.pause();
			song.playing = false;
		};
/**
* @function (Public) previous
* @desc Set 'song' to previous 'song' in album
*/
		SongPlayer.previous = function() {
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex--;
			if (currentSongIndex < 0) {
				stopSong(SongPlayer.currentSong);
			}
			else {
				var song = currentAlbum.songs[currentSongIndex];
				setSong(song);
				playSong(song);
			}
		};
/**
* @function (Public) next
* @desc Set 'song' to next 'song' in album
*/
		SongPlayer.next = function() {
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex++;
		};
		return SongPlayer;
	}

	angular
		.module('blocJams')
		.factory('SongPlayer', ['Fixtures', SongPlayer]);
})();<commit_msg>Adding (Public) 'setCurrentTime' method to 'SongPlayer.js' service...<commit_after>(function() {
	function SongPlayer(Fixtures) {

/**
* @desc (Public) Public name for SongPlayer object
* @type {Object}
*/
		var SongPlayer = {};
/**
* @desc (Private) Information for current album
* @type {Object}
*/
		var currentAlbum = Fixtures.getAlbum();
/**
* @desc (Private) Buzz object audio file
* @type {Object}
*/
		var currentBuzzObject = null;
/**
* @function (Private) setSong
* @desc Stops currently playing song and loads new audio file as currentBuzzObject
* @param {Object} song
*/
		var setSong = function(song) {
			if (currentBuzzObject) {
				stopSong(SongPlayer.currentSong);
			}
			currentBuzzObject = new buzz.sound(song.audioUrl,{
				formats: ['mp3'],
				preload: true
			});
			SongPlayer.currentSong = song;
		};
/**
* @function (Private) playSong
* @desc Plays the current Buzz object and sets playing property of the song object to true
* @param {Object} song
*/
		var playSong = function(song){
			currentBuzzObject.play();
			song.playing = true;
		};
/**
* @function (Private) getSongIndex
* @desc Get index of song in the songs array
* @param {Object} song
* @returns {Number}
*/
		var getSongIndex = function(song) {
			return currentAlbum.songs.indexOf(song);
		};
/**
* @function (Private) stopSong
* @desc Stop a song
* @param {Object} song
*/
		var stopSong = function(song) {
			currentBuzzObject.stop();
			song.playing = null;
		};
/**
* @desc (Public) Public name for 'current song' designated object
* @type {Object}
*/
		SongPlayer.currentSong = null;
/**
* @desc (Public) Current playback time (in seconds) of currently playing song
* @type {Number}
*/
		SongPlayer.currentTime = null;
/**
* @function (Public) play
* @desc Plays a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.play = function(song) {
			song = song || SongPlayer.currentSong;
			if (SongPlayer.currentSong !== song) {
				setSong(song);
				playSong(song);
			}
			else if (SongPlayer.currentSong === song) {
				if (currentBuzzObject.isPaused()) {
					playSong(song);
				}
			}
		};
/**
* @function (Public) pause
* @desc Pauses a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.pause = function(song) {
			song = song || SongPlayer.currentSong;
			currentBuzzObject.pause();
			song.playing = false;
		};
/**
* @function (Public) previous
* @desc Set 'song' to previous 'song' in album
*/
		SongPlayer.previous = function() {
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex--;
			if (currentSongIndex < 0) {
				stopSong(SongPlayer.currentSong);
			}
			else {
				var song = currentAlbum.songs[currentSongIndex];
				setSong(song);
				playSong(song);
			}
		};
/**
* @function (Public) next
* @desc Set 'song' to next 'song' in album
*/
		SongPlayer.next = function() {
			var currentSongIndex = getSongIndex(SongPlayer.currentSong);
			currentSongIndex++;
		};
		return SongPlayer;
	}

/**
* @function (Public) setCurrentTime
* @desc Set current time (in seconds) of currently playing song
* @param {Number} time
*/
		SongPlayer.setCurrentTime = function(time) {
			if (currentBuzzObject) {
			currentBuzzObject.setTime(time);
			}
		};

	angular
		.module('blocJams')
		.factory('SongPlayer', ['Fixtures', SongPlayer]);
})();<|endoftext|>


<commit_before>/* istanbul ignore next */
import './sandbox';

// require all modules ending in "_test" from the
// current directory and all subdirectories
/* istanbul ignore next */
let testsContext = require.context('project/test/karma/', true);
/* istanbul ignore next */
testsContext.keys().forEach(testsContext);
<commit_msg>Fix karma compile fail when installed<commit_after>// Using es5 in this module as it won't be transpiled in child projects
// due to the node_modules babel loader exclude.
/* istanbul ignore next */
require('./sandbox');

// require all modules ending in "_test" from the
// current directory and all subdirectories
/* istanbul ignore next */
let testsContext = require.context('project/test/karma/', true);
/* istanbul ignore next */
testsContext.keys().forEach(testsContext);
<|endoftext|>


<commit_before>var Client = require(__dirname + '/../lib/client').Client;
var EventEmitter = require('events').EventEmitter;

var statusCodeTable = {
  500: 'Inetnal Server Error',
  404: 'Not Found',
  409: 'Conflict',
  400: 'Bad Request',
  200: 'OK'
};

function Runner(options) {
  this.client = new Client(options);
  this.options = options;
  if (options.documentEndpoint)
    this.client.docEndpoint = options.documentEndpoint;
}

Runner.prototype = new EventEmitter();

Runner.prototype.run = function(scenario) {
  if (!Array.isArray(scenario))
    this._processScenario(scenario);
  else
    this._processScenarios({ scenarios: scenario });
};

Runner.prototype._processScenarios = function(params) {
  if (!params.start) params.start = Date.now();
  var scenario = params.scenarios.shift();
  var self = this;
  this._processScenario(
    scenario,
    function(error, event) {
      if (params.scenarios.length) {
        self._processScenarios(params);
      } else {
        var elapsedTime = Date.now() - params.start;
        self.emit('all:finish', {elapsedTime: elapsedTime});
      }
    }
  );
};

Runner.prototype._processScenario = function(scenario, callback) {
  if (!scenario.toBeProcessedRequests) {
    scenario.toBeProcessedRequests = scenario.requests.slice(0);
    scenario.start = Date.now();
    scenario.processed = {};
    this.emit('scenario:start', {scenario: scenario});
  }

  var request = scenario.toBeProcessedRequests.shift();
  var self = this;
  function processNext() {
    if (scenario.toBeProcessedRequests.length) {
      self._processScenario(scenario, callback);
    } else {
      var elapsedTime = Date.now() - scenario.start;
      var event = { type: 'scenario:finish',
                    elapsedTime: elapsedTime,
                    scenario: scenario };
      self.emit('scenario:finish', {
        elapsedTime: elapsedTime,
        scenario: scenario
      });
      if (callback)
        callback(null, event);
    }
  }

  if (request.onlyGCS && this.options.acs)
    return processNext();

  var name = request.name;
  var count = 1;
  while (name in scenario.processed) {
    name = request.name + count++;
  }

  this.emit('request:start', {
    scenario: scenario,
    request: request
  });

  this.client.rawConfigurationRequest(request.params.Action, request.params, function(error, result) {
    var response = error || result;

    var statusCode = response.StatusCode;
    if (!statusCodeTable[statusCode]) {
      self.emit('error:status_unknown', {statusCode: statusCode});
      if (callback)
        callback(statusCode, null);
      return;
    }

    var output = '';
    output += 'HTTP/1.1 ' + statusCode + ' ' + statusCodeTable[statusCode] + '\r\n';
    for (var key in response.Headers) {
      output += key + ': ' + response.Headers[key] + '\r\n';
    };
    output += '\r\n';
    output += response.Body.toString();

    request.result = output;
    self.emit('request:finish', {scenario: scenario, request: request});
    processNext();
  });
};

Runner.toSafeName = function(name) {
  return name
           .replace(/[^a-zA-Z0-9]+/g, '-')
           .replace(/-$/, '');
};

exports.Runner = Runner;
<commit_msg>Remove an unused variable<commit_after>var Client = require(__dirname + '/../lib/client').Client;
var EventEmitter = require('events').EventEmitter;

var statusCodeTable = {
  500: 'Inetnal Server Error',
  404: 'Not Found',
  409: 'Conflict',
  400: 'Bad Request',
  200: 'OK'
};

function Runner(options) {
  this.client = new Client(options);
  this.options = options;
  if (options.documentEndpoint)
    this.client.docEndpoint = options.documentEndpoint;
}

Runner.prototype = new EventEmitter();

Runner.prototype.run = function(scenario) {
  if (!Array.isArray(scenario))
    this._processScenario(scenario);
  else
    this._processScenarios({ scenarios: scenario });
};

Runner.prototype._processScenarios = function(params) {
  if (!params.start) params.start = Date.now();
  var scenario = params.scenarios.shift();
  var self = this;
  this._processScenario(
    scenario,
    function(error, event) {
      if (params.scenarios.length) {
        self._processScenarios(params);
      } else {
        var elapsedTime = Date.now() - params.start;
        self.emit('all:finish', {elapsedTime: elapsedTime});
      }
    }
  );
};

Runner.prototype._processScenario = function(scenario, callback) {
  if (!scenario.toBeProcessedRequests) {
    scenario.toBeProcessedRequests = scenario.requests.slice(0);
    scenario.start = Date.now();
    scenario.processed = {};
    this.emit('scenario:start', {scenario: scenario});
  }

  var request = scenario.toBeProcessedRequests.shift();
  var self = this;
  function processNext() {
    if (scenario.toBeProcessedRequests.length) {
      self._processScenario(scenario, callback);
    } else {
      var elapsedTime = Date.now() - scenario.start;
      self.emit('scenario:finish', {
        elapsedTime: elapsedTime,
        scenario: scenario
      });
      if (callback)
        callback(null, event);
    }
  }

  if (request.onlyGCS && this.options.acs)
    return processNext();

  var name = request.name;
  var count = 1;
  while (name in scenario.processed) {
    name = request.name + count++;
  }

  this.emit('request:start', {
    scenario: scenario,
    request: request
  });

  this.client.rawConfigurationRequest(request.params.Action, request.params, function(error, result) {
    var response = error || result;

    var statusCode = response.StatusCode;
    if (!statusCodeTable[statusCode]) {
      self.emit('error:status_unknown', {statusCode: statusCode});
      if (callback)
        callback(statusCode, null);
      return;
    }

    var output = '';
    output += 'HTTP/1.1 ' + statusCode + ' ' + statusCodeTable[statusCode] + '\r\n';
    for (var key in response.Headers) {
      output += key + ': ' + response.Headers[key] + '\r\n';
    };
    output += '\r\n';
    output += response.Body.toString();

    request.result = output;
    self.emit('request:finish', {scenario: scenario, request: request});
    processNext();
  });
};

Runner.toSafeName = function(name) {
  return name
           .replace(/[^a-zA-Z0-9]+/g, '-')
           .replace(/-$/, '');
};

exports.Runner = Runner;
<|endoftext|>


<commit_before>$(document).ready(function() {

	// Set up hover cursor for the two tables
	$('.stat_row').hover(function() {
			stat_num = $(this).attr('stat_num');
			$(this).css('cursor','pointer');
			plotAccordingToChoices(stat_num);
		}, function() {
			$(this).css('cursor','auto');
			plotAccordingToChoices(null);
	});

	// Session clicks
	$('.stat_row').click(function() {
		stat_info = $(this).attr('stat_info');
		window.location = "/admin/sessions/" + stat_info + "/";
		return false;
	});

    TableToolsInit.oFeatures.bXls = false;
    TableToolsInit.oFeatures.bCopy = false;
    TableToolsInit.oFeatures.bPrint = false;
    TableToolsInit.oBom.bXls = false;
    TableToolsInit.iButtonHeight = 24;
    TableToolsInit.iButtonWidth = 24;
    TableToolsInit.sSwfPath = "/media/js/tabletools/swf/ZeroClipboard.swf";
    TableToolsInit.sTitle = "Grades";

    var grades_table = $('#stats_table').dataTable( {
        "bAutoWidth": false,
        "bJQueryUI": true,
        "bStateSave": true,
        // "sScrollY": "325px",
        "bPaginate": false,
        "bLengthChange": false,
        // "bScrollCollapse": true,
        "sDom": '<"H"Tf>t',
    });

	var datasets = [
		{% for session in sessions %}
	        {
	            label: "{{ session.name }}",
	            data: eval('{{ session.grade_distribution }}'),
	            lines: {
	                show: true,
	                fill: true,
	                lineWidth: 3,
	                align: "center",
	            },
	            color: "rgb(91,144,151)",
	        },
		{% endfor %}
        ];

	// hard-code color indices to prevent them from shifting as
    // countries are turned on/off
    var i = 0;
    $.each(datasets, function(key, val) {
        val.color = i;
        i++;
    });

	var max_y_value = -1;

	for (var i = 0; i < datasets.length; i++) {
		var set = datasets[i];
		d = set['data'];
		for (var j = 0; j < d.length; j++) {
			var el = d[j];
			var val = el[1];
			if (max_y_value < val) {
				max_y_value = val;
			}
		}
	}

	function plotAccordingToChoices(plot_choice) {
        var data = [];

		if (plot_choice == null) {
			data = datasets;
		}
		else {
			data.push(datasets[plot_choice])
		}

        if (data.length > 0) {
            $.plot($("#grades_graph"), data, {
				xaxis: {
	                ticks: {{ problem_count }},
	                tickSize: 1,
	                tickDecimals: 0,
	                min: -.5,
	                max: {{ problem_count }} + 0.5,
	            },
	            yaxis: {
	                min: 0,
					max: max_y_value + 0.5,
	                tickSize: 1,
	                tickDecimals: 0,
	            },
	            grid: {
	                backgroundColor: { colors: ["#fff", "#eee"] },
	                hoverable: true,
	                clickable: true,
	                borderWidth: 1,
	                borderColor: "#C1DAD7",
	                verticalLinesX1: false,
	            }
            });
		}
    }

	plotAccordingToChoices(null);

	// TODO: consolidate all this js into one file and share it w/ admin_session
});<commit_msg>Removed a todo<commit_after>$(document).ready(function() {

	// Set up hover cursor for the two tables
	$('.stat_row').hover(function() {
			stat_num = $(this).attr('stat_num');
			$(this).css('cursor','pointer');
			plotAccordingToChoices(stat_num);
		}, function() {
			$(this).css('cursor','auto');
			plotAccordingToChoices(null);
	});

	// Session clicks
	$('.stat_row').click(function() {
		stat_info = $(this).attr('stat_info');
		window.location = "/admin/sessions/" + stat_info + "/";
		return false;
	});

    TableToolsInit.oFeatures.bXls = false;
    TableToolsInit.oFeatures.bCopy = false;
    TableToolsInit.oFeatures.bPrint = false;
    TableToolsInit.oBom.bXls = false;
    TableToolsInit.iButtonHeight = 24;
    TableToolsInit.iButtonWidth = 24;
    TableToolsInit.sSwfPath = "/media/js/tabletools/swf/ZeroClipboard.swf";
    TableToolsInit.sTitle = "Grades";

    var grades_table = $('#stats_table').dataTable( {
        "bAutoWidth": false,
        "bJQueryUI": true,
        "bStateSave": true,
        // "sScrollY": "325px",
        "bPaginate": false,
        "bLengthChange": false,
        // "bScrollCollapse": true,
        "sDom": '<"H"Tf>t',
    });

	var datasets = [
		{% for session in sessions %}
	        {
	            label: "{{ session.name }}",
	            data: eval('{{ session.grade_distribution }}'),
	            lines: {
	                show: true,
	                fill: true,
	                lineWidth: 3,
	                align: "center",
	            },
	            color: "rgb(91,144,151)",
	        },
		{% endfor %}
        ];

	// hard-code color indices to prevent them from shifting as
    // countries are turned on/off
    var i = 0;
    $.each(datasets, function(key, val) {
        val.color = i;
        i++;
    });

	var max_y_value = -1;

	for (var i = 0; i < datasets.length; i++) {
		var set = datasets[i];
		d = set['data'];
		for (var j = 0; j < d.length; j++) {
			var el = d[j];
			var val = el[1];
			if (max_y_value < val) {
				max_y_value = val;
			}
		}
	}

	function plotAccordingToChoices(plot_choice) {
        var data = [];

		if (plot_choice == null) {
			data = datasets;
		}
		else {
			data.push(datasets[plot_choice])
		}

        if (data.length > 0) {
            $.plot($("#grades_graph"), data, {
				xaxis: {
	                ticks: {{ problem_count }},
	                tickSize: 1,
	                tickDecimals: 0,
	                min: -.5,
	                max: {{ problem_count }} + 0.5,
	            },
	            yaxis: {
	                min: 0,
					max: max_y_value + 0.5,
	                tickSize: 1,
	                tickDecimals: 0,
	            },
	            grid: {
	                backgroundColor: { colors: ["#fff", "#eee"] },
	                hoverable: true,
	                clickable: true,
	                borderWidth: 1,
	                borderColor: "#C1DAD7",
	                verticalLinesX1: false,
	            }
            });
		}
    }

	plotAccordingToChoices(null);
});<|endoftext|>


<commit_before>// app.shoppingListDirective.js

(function() {
  "use strict";

  angular.module("ShoppingListDirectiveApp")
    .directive("shoppingList", ShoppingList);

  function ShoppingList() {
    const templateUrl = "../templates/shoppingList.view.html";
    const ddo = {
      restrict: "E",
      templateUrl,
      scope: {
        list: "<",
        title: "@"
      },
      //controller: "ShoppingListDirectiveController as ShoppingListDirectiveCtrl",
      controller: "ShoppingListDirectiveController",
      controllerAs: "ShoppingListDirectiveCtrl",
      bindToController: true
    };

    return ddo;
  }
})();
<commit_msg>Edit scope object<commit_after>// app.shoppingListDirective.js

(function() {
  "use strict";

  angular.module("ShoppingListDirectiveApp")
    .directive("shoppingList", ShoppingList);

  function ShoppingList() {
    const templateUrl = "../templates/shoppingList.view.html";
    const ddo = {
      restrict: "E",
      templateUrl,
      scope: {
        items: "<",
        title: "@",
        badRemove: "=",
        onRemove: "&"
      },
      //controller: "ShoppingListDirectiveController as ShoppingListDirectiveCtrl",
      controller: "ShoppingListDirectiveController",
      controllerAs: "ShoppingListDirectiveCtrl",
      bindToController: true
    };

    return ddo;
  }
})();
<|endoftext|>


<commit_before>/*
Copyright (C) 2017  Cloudbase Solutions SRL

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Table from '../Table';
import s from './MigrationNetworks.scss';

const title = 'Migration Networks';

class MigrationNetworks extends Component {
  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired,
  };

  static propTypes = {
    migration: PropTypes.object
  }

  constructor(props) {
    super(props)
    this.headers = [
      { label: "Source Network", key: 'source_network' },
      { label: "Connected VMs", key: 'connected_vms' },
      { label: "Destination Network", key: 'destination_network' },
      { label: "Destination Type", key: 'destination_type' }
    ]

    this.listItems = []
    this.processProps(props)
  }

  componentWillMount() {
    this.context.onSetTitle(title);
  }

  getConnectedVms(networkId) {
    let vms = []
    this.props.migration.instances.forEach((item) => {
      if (item.networks.indexOf(networkId) != -1) {
        vms.push(item.name)
      }
    })
    return vms
  }

  processProps(props) {
    if (props.migration && props.migration.destination_environment) {
      for (let i in props.migration.destination_environment.network_map) {
        let newItem = {
          source_network: i,
          connected_vms: "-",
          destination_network: props.migration.destination_environment.network_map[i],
          destination_type: "Existing network"
        }
        this.listItems.push(newItem)
      }
      /*
       props.migration.destination_environment.network_map.forEach((item) => {
       //let connectedVms = this.getConnectedVms(item.id).join(", ")
       let connectedVms = "-"
       let newItem = {
       source_network: item.name,
       connected_vms: connectedVms,
       destination_network: item.migrateNetwork,
       destination_type: item.migrateNetwork == "Create new" ? "New network" : "Existing network"
       }
       this.listItems.push(newItem)
       }*/
    }
  }

  render() {
    if (this.listItems.length) {
      return (

      );
    } else {
      return (
No networks mapped
)
    }
  }
}

export default withStyles(MigrationNetworks, s);
<commit_msg>Adds connected VMs to migration/replica networks detail view<commit_after>/*
Copyright (C) 2017  Cloudbase Solutions SRL

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Table from '../Table';
import s from './MigrationNetworks.scss';

const title = 'Migration Networks';

class MigrationNetworks extends Component {
  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired,
  };

  static propTypes = {
    migration: PropTypes.object
  }

  constructor(props) {
    super(props)
    this.headers = [
      { label: "Source Network", key: 'source_network' },
      { label: "Connected VMs", key: 'connected_vms' },
      { label: "Destination Network", key: 'destination_network' },
      { label: "Destination Type", key: 'destination_type' }
    ]

    this.listItems = []
    this.processProps(props)
  }

  componentWillMount() {
    this.context.onSetTitle(title);
  }

  getConnectedVms(networkId) {
    let vms = []
    for (let instanceName in this.props.migration.info) {
      let instance = this.props.migration.info[instanceName]
      if (instance.export_info.devices.nics.length) {
        instance.export_info.devices.nics.forEach(nic => {
          if (nic.network_name == networkId) {
            vms.push(instanceName)
          }
        })
      }
    }
    return vms
  }

  processProps(props) {
    if (props.migration && props.migration.destination_environment) {
      for (let i in props.migration.destination_environment.network_map) {
        let newItem = {
          source_network: i,
          connected_vms: this.getConnectedVms(i),
          destination_network: props.migration.destination_environment.network_map[i],
          destination_type: "Existing network"
        }
        this.listItems.push(newItem)
      }
    }
  }

  render() {
    if (this.listItems.length) {
      return (

      );
    } else {
      return (
No networks mapped
)
    }
  }
}

export default withStyles(MigrationNetworks, s);
<|endoftext|>


<commit_before>import React from 'react';
import Autocomplete from 'react-autocomplete';
import TicketLink from '../TicketLink';

const TicketForm = (props) => {
  return (
    <form>
      <button
        type="button"
        className="close-btn btn"
        aria-label="close"
        onClick={() => props.toggleTicketModal()}
      >
        ✕
      </button>

        Project
        <input
          id="projects"
          className="form-control"
          disabled="disabled"
          value={`${props.selectedProject['company.name']} — ${props.selectedProject['project.name']}`}
        />

        Phase
        <Autocomplete
          id="phases"
          items={props.phases}
          getItemValue={item => item.path}
          shouldItemRender={(item, value) => item.path.toLowerCase().indexOf(value.toLowerCase()) > -1}
          renderItem={item => (
            <div key={`${item.phaseId}-${item.ticketId}`}>
              {item.path}

          )}
          value={props.phaseValue}
          inputProps={{ className: "autocomplete-input form-control" }}
          onChange={e => props.setPhaseValue(e.target.value)}
          onSelect={value => props.setPhaseValue(value)}
        />

        Summary
        <input
          className="form-control"
          type="text"
          id="summary"
          onChange={(e) => props.setSummary(e.target.value)}
          required
          value={props.summary}
          autoComplete="off"
        ></input>

        Budget Hours
        <input
          type="number"
          id="budget-hours"
          className="form-control"
          onChange={(e) => props.setBudget(e.target.value)}
          required
          min="0"
          step="0.25"
          placeholder="1"
          autoComplete="off"
          value={props.budget}
        ></input>
        {props.budget > 10 && (

Warning: This is a higher than normal budget

        )}

        Description
        <textarea
          id="description"
          rows="4"
          cols="50"
          className="form-control"
          placeholder="This is optional"
          value={props.description}
          onChange={(e) => props.setDescription(e.target.value)}
        ></textarea>

      <button
        type="button"
        className="btn btn-submit btn-primary"
        disabled={!props.budget || !props.summary || !props.phaseValue || props.hasCompletedTicket}
        onClick={() => {
          props.setTicketCompleted(true);
          props.createNewTicket();
        }}
      >
        Create Ticket
      </button>
      {(props.hasCompletedTicket && (
        <>

You created a new ticket:
              {props.newTicketId && (
                <TicketLink ticketNumber={props.newTicketId}/>
              )}

          <button
            type="button"
            className="btn btn-default btn-md btn-create-ticket"
            onClick={() => props.resetTicketDetails()}
          >
            Create another ticket
          </button>
        </>
      ))}
    </form>
  );
};

export default TicketForm;
<commit_msg>Prevent annoying autocomplete<commit_after>import React from 'react';
import Autocomplete from 'react-autocomplete';
import TicketLink from '../TicketLink';

const TicketForm = (props) => {
  return (
    <form>
      <button
        type="button"
        className="close-btn btn"
        aria-label="close"
        onClick={() => props.toggleTicketModal()}
      >
        ✕
      </button>

        Project
        <input
          id="projects"
          className="form-control"
          disabled="disabled"
          value={`${props.selectedProject['company.name']} — ${props.selectedProject['project.name']}`}
        />

        Phase
        <Autocomplete
          id="phases"
          items={props.phases}
          getItemValue={item => item.path}
          shouldItemRender={(item, value) => item.path.toLowerCase().indexOf(value.toLowerCase()) > -1}
          renderItem={item => (
            <div key={`${item.phaseId}-${item.ticketId}`}>
              {item.path}

          )}
          value={props.phaseValue}
          inputProps={{ className: "autocomplete-input form-control" }}
          onChange={e => props.setPhaseValue(e.target.value)}
          onSelect={value => props.setPhaseValue(value)}
        />

        Summary
        <input
          className="form-control"
          type="text"
          id="summary"
          onChange={(e) => props.setSummary(e.target.value)}
          required
          value={props.summary}
          autoComplete="off"
        ></input>

        Budget Hours
        <input
          type="number"
          id="budget-hours"
          className="form-control"
          onChange={(e) => props.setBudget(e.target.value)}
          required
          min="0"
          step="0.25"
          placeholder="1"
          autoComplete="off"
          value={props.budget}
        ></input>
        {props.budget > 10 && (

Warning: This is a higher than normal budget

        )}

        Description
        <textarea
          id="description"
          rows="4"
          cols="50"
          className="form-control"
          placeholder="This is optional"
          autoComplete="off"
          value={props.description}
          onChange={(e) => props.setDescription(e.target.value)}
        ></textarea>

      <button
        type="button"
        className="btn btn-submit btn-primary"
        disabled={!props.budget || !props.summary || !props.phaseValue || props.hasCompletedTicket}
        onClick={() => {
          props.setTicketCompleted(true);
          props.createNewTicket();
        }}
      >
        Create Ticket
      </button>
      {(props.hasCompletedTicket && (
        <>

You created a new ticket:
              {props.newTicketId && (
                <TicketLink ticketNumber={props.newTicketId}/>
              )}

          <button
            type="button"
            className="btn btn-default btn-md btn-create-ticket"
            onClick={() => props.resetTicketDetails()}
          >
            Create another ticket
          </button>
        </>
      ))}
    </form>
  );
};

export default TicketForm;
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * Created by Leandro Späth ©2016
 * Sources:
 * - https://www.npmjs.com/package/mqtt
 * - https://mosquitto.org/
 *
 */

var fs = require('fs');
var util = require('util');
var mqtt = require('mqtt');
//var express = require('express');
var hsl2rgb = require('hsv-rgb');

//additionally write console.log to log file
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags: 'w'});
var log_stdout = process.stdout;
console.log = function (d) { //
    log_file.write(util.format(d) + '\n');
    log_stdout.write(util.format(d) + '\n');
};

//SOCKET
const server = require('./server');
const io = server.io;

//MQTT stuff
var client = mqtt.connect('mqtt://192.168.178.168');
var domain = "RGB-LED-control";
var topicRegistration = domain + "/registration";
var topicACK = domain + "/ack/+";
var topicControl = domain + "/data/RGB/";
var topicFade = domain + "/data/fade/";

var masterOverride = 1;

var devices = {
    "18:FE:34:CC:FC:EA": {room: 1},
    "18:FE:34:D4:2E:BD": {room: 2},
    "5C:CF:7F:88:1B:5D": {room: 3},
    "18:FE:34:D3:F5:7F": {room: 4},
    "5C:CF:7F:8B:F0:70": {room: 5}, //Leandros nodeMCU
    "5C:CF:7F:1B:6F:85": {room: 6},
    "5C:CF:7F:8B:C5:03": {room: 7},
    "5C:CF:7F:88:1A:13": {room: 8},
    "5C:CF:7F:8B:EF:42": {room: 9},
    "18:FE:34:D3:F0:B2": {room: 10},
    "5C:CF:7F:8B:C6:AA": {room: 11},
    "5C:CF:7F:88:1D:A0": {room: 12},
    "18:FE:34:E1:AF:AD": {room: 13},
    "5C:CF:7F:88:1E:04": {room: 14},
};

// deviceObjs is for properties that can't be serialized to json, e.g. intervals
var deviceObjs = {};
Object.keys(devices).forEach(device => deviceObjs[device] = {});

var sets = {
    "all": Object.keys(devices),
    "segment1": Object.keys(devices).slice(0, 4),
    "segment2": Object.keys(devices).slice(4, 8),
    "segment3": Object.keys(devices).slice(8)
};

function sendRGB(mac, rgb) {
    devices[mac].color = rgb;
    client.publish(topicControl + mac, rgb);
    sendDevices();
    console.log(mac + " <set " + rgb);
}

function sendFade(mac, rgb, fadeTime) //
{
    devices[mac].color = rgb;
    var fadeStr = rgb + ";" + fadeTime;
    client.publish(topicFade + mac, fadeStr);
    console.log(mac + " <fade " + rgb + " in " + fadeTime + "ms");
}

function setMasterOverride(state)
{
  masterOverride = state;
  if(masterOverride == 0)
  {
    Object.keys(devices).forEach(function(key){
      sendFade(key, "#000000", 1000);
    });
  }
}

function dec2hex(i) {
    return (i + 0x100).toString(16).substr(-2).toUpperCase();
}

function rgbArrToStr(rgb) {
    var rgbString = "#";
    rgbString += dec2hex(rgb[0]);
    rgbString += dec2hex(rgb[1]);
    rgbString += dec2hex(rgb[2]);
    return rgbString;
}

function startParty(mac) {
    stopInterval(mac);
    deviceObjs[mac].interval = setInterval(function () {
        party(mac)
    }, 180);
}

function stopInterval(mac) {
    if (deviceObjs[mac].interval) {
        clearInterval(deviceObjs[mac].interval);
        deviceObjs[mac].interval = null;
    }
}

function party(mac) {
    if (!devices[mac].hue) devices[mac].hue = 0;
    var rgb = hsl2rgb(devices[mac].hue, 100, 100);
    var rgbString = rgbArrToStr(rgb);
    sendFade(mac, rgbString, 180);
    devices[mac].hue += 5;
    if (devices[mac].hue >= 360)
        devices[mac].hue = 0;
}

function startLighthouse()
{
  setInterval(lightHouseTick, 500);
}

var lightHouseIdx = 0;
var prevColor;
function lightHouseTick()
{
  var macs = Object.keys(devices);
  var prevMAC = macs[lightHouseIdx%14];
  var curMAC = macs[(lightHouseIdx+1)%14]; //handle overflow
  sendFade(prevMAC, prevColor, 250);
  prevColor = devices[curMAC].color;
  sendFade(curMAC, "#FFFFFF", 250);
  lightHouseIdx++;
}

const sendDevices = () => {
    io.emit('devices', devices);
};

client.on('connect', function () {
    console.log('connect');
    client.subscribe(topicRegistration);
    client.subscribe(topicACK);
});

client.on('message', function (topic, message) {
    //console.log('message received');
    if (topic == topicRegistration) {
        const split = message.toString().split(';');
        if(!devices[split[0]]) {
            console.log('unknown device ' + message.toString());
            return false;
        }
        if (split[1]) devices[split[0]].version = split[1];
        console.log("New registration from MAC " + split[0] + ', Version: ' + split[1]);
    }
    else if (topic.substr(0, topicACK.length - 1) == topicACK.substr(0, topicACK.length - 1)) { //check if topic is ACK
        var mac = topic.split("/").pop();
        if(!devices[mac]) {
            console.log('unknown device ' + mac);
            return false;
        }
        if (devices[mac].isOnline == false) {
            console.log("Node " + mac + " went back online");
            sendDevices();
            io.emit('deviceUpdate', {key, status: 'online'});
        }
        devices[mac].isOnline = true;
        devices[mac].lastSeen = Date.now();
    }
});

function keepalive() {
    client.publish("RGB-LED-control/keepalive", Date.now().toString());
    Object.keys(devices).forEach(function (key) {
        if (devices[key].lastSeen + 15000 < Date.now()) {
            if (devices[key].isOnline == true) {
                console.log("Node " + key + " went offline");
                sendDevices();
                io.emit('deviceUpdate', {key, status: 'offline'});
            }
            devices[key].isOnline = false;
        }
    });
}
setInterval(keepalive, 5000);
setInterval(sendDevices, 10000);

module.exports = {devices, sets, sendRGB, sendFade, startParty, stopInterval, sendDevices, setMasterOverride, startLighthouse};
<commit_msg>added timestamp to log<commit_after>#!/usr/bin/env node
/*
 * Created by Leandro Späth ©2016
 * Sources:
 * - https://www.npmjs.com/package/mqtt
 * - https://mosquitto.org/
 *
 */

var fs = require('fs');
var util = require('util');
var mqtt = require('mqtt');
//var express = require('express');
var hsl2rgb = require('hsv-rgb');

//additionally write console.log to log file
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags: 'a'});
var log_stdout = process.stdout;
console.log = function (d) { //
    log_file.write(new Date().toISOString() + " " + util.format(d) + '\n');
    log_stdout.write(util.format(d) + '\n');
};

//SOCKET
const server = require('./server');
const io = server.io;

//MQTT stuff
var client = mqtt.connect('mqtt://192.168.178.168');
var domain = "RGB-LED-control";
var topicRegistration = domain + "/registration";
var topicACK = domain + "/ack/+";
var topicControl = domain + "/data/RGB/";
var topicFade = domain + "/data/fade/";

var masterOverride = 1;

var devices = {
    "18:FE:34:CC:FC:EA": {room: 1},
    "18:FE:34:D4:2E:BD": {room: 2},
    "5C:CF:7F:88:1B:5D": {room: 3},
    "18:FE:34:D3:F5:7F": {room: 4},
    "5C:CF:7F:8B:F0:70": {room: 5}, //Leandros nodeMCU
    "5C:CF:7F:1B:6F:85": {room: 6},
    "5C:CF:7F:8B:C5:03": {room: 7},
    "5C:CF:7F:88:1A:13": {room: 8},
    "5C:CF:7F:8B:EF:42": {room: 9},
    "18:FE:34:D3:F0:B2": {room: 10},
    "5C:CF:7F:8B:C6:AA": {room: 11},
    "5C:CF:7F:88:1D:A0": {room: 12},
    "18:FE:34:E1:AF:AD": {room: 13},
    "5C:CF:7F:88:1E:04": {room: 14},
};

// deviceObjs is for properties that can't be serialized to json, e.g. intervals
var deviceObjs = {};
Object.keys(devices).forEach(device => deviceObjs[device] = {});

var sets = {
    "all": Object.keys(devices),
    "segment1": Object.keys(devices).slice(0, 4),
    "segment2": Object.keys(devices).slice(4, 8),
    "segment3": Object.keys(devices).slice(8)
};

function sendRGB(mac, rgb) {
    devices[mac].color = rgb;
    client.publish(topicControl + mac, rgb);
    sendDevices();
    console.log(mac + " <set " + rgb);
}

function sendFade(mac, rgb, fadeTime) //
{
    devices[mac].color = rgb;
    var fadeStr = rgb + ";" + fadeTime;
    client.publish(topicFade + mac, fadeStr);
    console.log(mac + " <fade " + rgb + " in " + fadeTime + "ms");
}

function setMasterOverride(state)
{
  masterOverride = state;
  if(masterOverride == 0)
  {
    Object.keys(devices).forEach(function(key){
      sendFade(key, "#000000", 1000);
    });
  }
}

function dec2hex(i) {
    return (i + 0x100).toString(16).substr(-2).toUpperCase();
}

function rgbArrToStr(rgb) {
    var rgbString = "#";
    rgbString += dec2hex(rgb[0]);
    rgbString += dec2hex(rgb[1]);
    rgbString += dec2hex(rgb[2]);
    return rgbString;
}

function startParty(mac) {
    stopInterval(mac);
    deviceObjs[mac].interval = setInterval(function () {
        party(mac)
    }, 180);
}

function stopInterval(mac) {
    if (deviceObjs[mac].interval) {
        clearInterval(deviceObjs[mac].interval);
        deviceObjs[mac].interval = null;
    }
}

function party(mac) {
    if (!devices[mac].hue) devices[mac].hue = 0;
    var rgb = hsl2rgb(devices[mac].hue, 100, 100);
    var rgbString = rgbArrToStr(rgb);
    sendFade(mac, rgbString, 180);
    devices[mac].hue += 5;
    if (devices[mac].hue >= 360)
        devices[mac].hue = 0;
}

function startLighthouse()
{
  setInterval(lightHouseTick, 500);
}

var lightHouseIdx = 0;
var prevColor;
function lightHouseTick()
{
  var macs = Object.keys(devices);
  var prevMAC = macs[lightHouseIdx%14];
  var curMAC = macs[(lightHouseIdx+1)%14]; //handle overflow
  sendFade(prevMAC, prevColor, 250);
  prevColor = devices[curMAC].color;
  sendFade(curMAC, "#FFFFFF", 250);
  lightHouseIdx++;
}

const sendDevices = () => {
    io.emit('devices', devices);
};

client.on('connect', function () {
    console.log('connect');
    client.subscribe(topicRegistration);
    client.subscribe(topicACK);
});

client.on('message', function (topic, message) {
    //console.log('message received');
    if (topic == topicRegistration) {
        const split = message.toString().split(';');
        if(!devices[split[0]]) {
            console.log('unknown device ' + message.toString());
            return false;
        }
        if (split[1]) devices[split[0]].version = split[1];
        console.log("New registration from MAC " + split[0] + ', Version: ' + split[1]);
    }
    else if (topic.substr(0, topicACK.length - 1) == topicACK.substr(0, topicACK.length - 1)) { //check if topic is ACK
        var mac = topic.split("/").pop();
        if(!devices[mac]) {
            console.log('unknown device ' + mac);
            return false;
        }
        if (devices[mac].isOnline == false) {
            console.log("Node " + mac + " went back online");
            sendDevices();
            io.emit('deviceUpdate', {key, status: 'online'});
        }
        devices[mac].isOnline = true;
        devices[mac].lastSeen = Date.now();
    }
});

function keepalive() {
    client.publish("RGB-LED-control/keepalive", Date.now().toString());
    Object.keys(devices).forEach(function (key) {
        if (devices[key].lastSeen + 15000 < Date.now()) {
            if (devices[key].isOnline == true) {
                console.log("Node " + key + " went offline");
                sendDevices();
                io.emit('deviceUpdate', {key, status: 'offline'});
            }
            devices[key].isOnline = false;
        }
    });
}
setInterval(keepalive, 5000);
setInterval(sendDevices, 10000);

module.exports = {devices, sets, sendRGB, sendFade, startParty, stopInterval, sendDevices, setMasterOverride, startLighthouse};
<|endoftext|>