<commit_before>var subtome = angular.module('subtome', ['i18next']);

subtome.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
    when('/', {templateUrl: 'partials/index.html',   controller: "IndexController"}).
    when('/settings', {templateUrl: 'partials/settings.html', controller: "SettingsController"}).
    when('/publishers', {templateUrl: 'partials/publishers.html', controller: "PublishersController"}).
    when('/developers', {templateUrl: 'partials/developers.html', controller: "DevelopersController"}).
    when('/store', {templateUrl: 'partials/store.html', controller: "StoreController"}).
    when('/register', {templateUrl: 'partials/register.html', controller: "RegisterController"}).
    when('/subscribe', {templateUrl: 'partials/subscribe.html', controller: "SubscribeController"}).
    otherwise({redirectTo: '/'});
  }
]);

subtome.run(['$rootScope', function($rootScope) {
  $rootScope.loadGists = function loadGists() {
    $('.script').each(function(i,div) {
      $.ajax({
        url: $(div).data('src') + 'on',
        dataType: 'jsonp',
        success: function(gist) {
          $('head').append('<link rel="stylesheet" href="' + gist.stylesheet + '" type="text/css" />');
          $(div).append($(gist.div))
        }
      });
    });
  }

  $rootScope.showBrowserSpecifics = function showBrowserSpecifics() {
    $('.browser-specific').each(function(i, b) {
      var browserSpecific = $(b).attr('class');
      if(typeof(browserSpecific) == 'string') {
        browserSpecific.split(' ').forEach(function(c) {
          if(navigator.userAgent.toLowerCase().indexOf(c) >= 0) {
            $(b).show();
          }
          else {
            $(b).hide();
          }
        });
      }
    });
  }

  $rootScope.services = new Services();
  $rootScope.services.listen(function() {
    $rootScope.$apply();
  });

}]);

subtome.filter('fromNow', function() {
  return function(dateString) {
    return moment(new Date(dateString)).fromNow()
  };
});

subtome.filter('linkToHome', function() {
  return function(url) {
    var a = document.createElement('a');
    a.href = decodeURIComponent(url);
    return a.protocol + '//' + a.host + '/';
  };
});

subtome.controller("IndexController", function IndexController($scope) {
  $scope.over = function over() {
    document.getElementById('demo').innerHTML=i18n.t("Follow our Blog");
  }
  $scope.left = function left() {
    document.getElementById('demo').innerHTML=i18n.t("See it in Action");
  }
  $scope.follow = function follow() {
    var z=document.createElement('script');
    z.src='/load.js';
    document.body.appendChild(z);
  }
});

subtome.controller("SettingsController", function SettingsController($scope) {
  $scope.showBrowserSpecifics();
  $scope.remove = function removeService(service) {
    $scope.services.removeService(service.name);
  }
});

subtome.controller("PublishersController", function PublishersController($scope) {
  $scope.loadGists();
  $scope.follow = function follow(url) {
    if(!url) {
      var z=document.createElement('script');
      z.src='/load.js';
      document.body.appendChild(z);
    }
    else {
      var s = document.createElement('iframe');
      var feeds = [url];
      var resource = url;
      s.setAttribute('style','position:fixed;top:0px; left:0px; width:100%; height:100%; border:0px; background: transparent; z-index: 2147483647');
      s.setAttribute('src', 'https://www.subtome.com/subscribe.html?resource=' + encodeURIComponent(resource) + '&feeds=' + feeds.join(','));
      var loaded = false;
      s.onload = function() {
        if(loaded) {
          document.getElementsByTagName('body')[0].removeChild(s);
        }
        loaded = true;
      }
      document.getElementsByTagName('body')[0].appendChild(s);
    }
  }
});

subtome.controller("DevelopersController", function DevelopersController($scope) {
  $scope.loadGists();
});

subtome.controller("StoreController", function StoreController($scope) {
  var apps = appStore;
  apps.forEach(function(a) {
    a.installed = $scope.services.uses(a.name);
  });
  $scope.apps = apps;

  $scope.install = function installApp(app) {
    app.installed = true;
    $scope.services.register(app.registration.name, app.registration.url)
  };

  $scope.remove = function removeApp(app) {
    app.installed = false;
    $scope.services.removeService(app.registration.name);
  };
});

subtome.controller("RegisterController", function DevelopersController($scope, $routeParams) {
  $scope.services.register($routeParams.name, $routeParams.url);
  $scope.service = {name: $routeParams.name, url: $routeParams.url};
});

subtome.controller("SubscribeController", function SubscribeController($scope, $routeParams) {
  $("body").css("background", "transparent")
  $("hr").hide();
  $(".masthead").hide();
  $(".footer").hide();

  $('#subtomeModal').modal({backdrop: true, keyboard: true, show: true});
  $('#subtomeModal').on('hidden', function() {
    window.location = '/done.html';
  });

  $scope.resource = $routeParams.resource;
  $scope.feeds = [];
  if($routeParams.feeds && $routeParams.feeds.length > 0) {
    $scope.feeds = $routeParams.feeds.split(",");
  }

  $scope.openSettings = function openSettings() {
    window.open('#/settings');
  }

  $scope.openService = function openService(service) {
    var redirect = decodeURIComponent(service.url).replace('{url}', encodeURIComponent($scope.resource));
    if(redirect.match(/\{feed\}/)) {
      if($scope.feeds[0]) {
        redirect = redirect.replace('{feed}', encodeURIComponent($scope.feeds[0]));
      }
      else {
        redirect = redirect.replace('{feed}', encodeURIComponent($scope.resource));
      }
    }
    if(redirect.match(/\{feeds\}/)) {
      redirect = redirect.replace('{feeds}', $scope.feeds.join(','));
    }
    window.open(redirect);
  }
});

<commit_msg>preparing for minification<commit_after>var subtome = angular.module('subtome', ['i18next']);

subtome.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
    when('/', {templateUrl: 'partials/index.html',   controller: "IndexController"}).
    when('/settings', {templateUrl: 'partials/settings.html', controller: "SettingsController"}).
    when('/publishers', {templateUrl: 'partials/publishers.html', controller: "PublishersController"}).
    when('/developers', {templateUrl: 'partials/developers.html', controller: "DevelopersController"}).
    when('/store', {templateUrl: 'partials/store.html', controller: "StoreController"}).
    when('/register', {templateUrl: 'partials/register.html', controller: "RegisterController"}).
    when('/subscribe', {templateUrl: 'partials/subscribe.html', controller: "SubscribeController"}).
    otherwise({redirectTo: '/'});
  }
]);

subtome.run(['$rootScope', function($rootScope) {
  $rootScope.loadGists = function loadGists() {
    $('.script').each(function(i,div) {
      $.ajax({
        url: $(div).data('src') + 'on',
        dataType: 'jsonp',
        success: function(gist) {
          $('head').append('<link rel="stylesheet" href="' + gist.stylesheet + '" type="text/css" />');
          $(div).append($(gist.div))
        }
      });
    });
  }

  $rootScope.showBrowserSpecifics = function showBrowserSpecifics() {
    $('.browser-specific').each(function(i, b) {
      var browserSpecific = $(b).attr('class');
      if(typeof(browserSpecific) == 'string') {
        browserSpecific.split(' ').forEach(function(c) {
          if(navigator.userAgent.toLowerCase().indexOf(c) >= 0) {
            $(b).show();
          }
          else {
            $(b).hide();
          }
        });
      }
    });
  }

  $rootScope.services = new Services();
  $rootScope.services.listen(function() {
    $rootScope.$apply();
  });

}]);

subtome.filter('fromNow', function() {
  return function(dateString) {
    return moment(new Date(dateString)).fromNow()
  };
});

subtome.filter('linkToHome', function() {
  return function(url) {
    var a = document.createElement('a');
    a.href = decodeURIComponent(url);
    return a.protocol + '//' + a.host + '/';
  };
});

subtome.controller("IndexController", ['$scope', function IndexController($scope) {
  $scope.over = function over() {
    document.getElementById('demo').innerHTML=i18n.t("Follow our Blog");
  }
  $scope.left = function left() {
    document.getElementById('demo').innerHTML=i18n.t("See it in Action");
  }
  $scope.follow = function follow() {
    var z=document.createElement('script');
    z.src='/load.js';
    document.body.appendChild(z);
  }
}]);

subtome.controller("SettingsController", ['$scope', function SettingsController($scope) {
  $scope.showBrowserSpecifics();
  $scope.remove = function removeService(service) {
    $scope.services.removeService(service.name);
  }
}]);

subtome.controller("PublishersController", ['$scope', function PublishersController($scope) {
  $scope.loadGists();
  $scope.follow = function follow(url) {
    if(!url) {
      var z=document.createElement('script');
      z.src='/load.js';
      document.body.appendChild(z);
    }
    else {
      var s = document.createElement('iframe');
      var feeds = [url];
      var resource = url;
      s.setAttribute('style','position:fixed;top:0px; left:0px; width:100%; height:100%; border:0px; background: transparent; z-index: 2147483647');
      s.setAttribute('src', 'https://www.subtome.com/subscribe.html?resource=' + encodeURIComponent(resource) + '&feeds=' + feeds.join(','));
      var loaded = false;
      s.onload = function() {
        if(loaded) {
          document.getElementsByTagName('body')[0].removeChild(s);
        }
        loaded = true;
      }
      document.getElementsByTagName('body')[0].appendChild(s);
    }
  }
}]);

subtome.controller("DevelopersController", ['$scope', function DevelopersController($scope) {
  $scope.loadGists();
}]);

subtome.controller("StoreController", ['$scope', function StoreController($scope) {
  var apps = appStore;
  apps.forEach(function(a) {
    a.installed = $scope.services.uses(a.name);
  });
  $scope.apps = apps;

  $scope.install = function installApp(app) {
    app.installed = true;
    $scope.services.register(app.registration.name, app.registration.url)
  };

  $scope.remove = function removeApp(app) {
    app.installed = false;
    $scope.services.removeService(app.registration.name);
  };
}]);

subtome.controller("RegisterController", ['$scope', '$routeParams', function DevelopersController($scope, $routeParams) {
  $scope.services.register($routeParams.name, $routeParams.url);
  $scope.service = {name: $routeParams.name, url: $routeParams.url};
}]);

subtome.controller("SubscribeController", ['$scope', '$routeParams', function SubscribeController($scope, $routeParams) {
  $("body").css("background", "transparent")
  $("hr").hide();
  $(".masthead").hide();
  $(".footer").hide();

  $('#subtomeModal').modal({backdrop: true, keyboard: true, show: true});
  $('#subtomeModal').on('hidden', function() {
    window.location = '/done.html';
  });

  $scope.resource = $routeParams.resource;
  $scope.feeds = [];
  if($routeParams.feeds && $routeParams.feeds.length > 0) {
    $scope.feeds = $routeParams.feeds.split(",");
  }

  $scope.openSettings = function openSettings() {
    window.open('#/settings');
  }

  $scope.openService = function openService(service) {
    var redirect = decodeURIComponent(service.url).replace('{url}', encodeURIComponent($scope.resource));
    if(redirect.match(/\{feed\}/)) {
      if($scope.feeds[0]) {
        redirect = redirect.replace('{feed}', encodeURIComponent($scope.feeds[0]));
      }
      else {
        redirect = redirect.replace('{feed}', encodeURIComponent($scope.resource));
      }
    }
    if(redirect.match(/\{feeds\}/)) {
      redirect = redirect.replace('{feeds}', $scope.feeds.join(','));
    }
    window.open(redirect);
  }
}]);

<|endoftext|>


<commit_before>// Release 4 User Story:
// As a user, I want to get the sum of all the numbers in a list.
function sum(list) {

  return list.reduce(function(previousValue, currentValue, currentIndex, array) {
                return previousValue + currentValue;
              });

}

// Release 4 User Story:
// As a user, I want to get the mean (also known as the average)
// of all the numbers in a list.
function mean(list) {
  return sum(list) / list.length;
}

// Note from Person #5 (Buck): I believe the function below, 'median'
// may be broken?  I can't know for sure since, per the instructions,
// I don't have access to the original spec/tests. But I do know that
// the function doesn't always calculate the median.  According to the
// instructions, I'm not fixing it and how it functions currently will
// be reflected in the User Story.

// Release 4 User Story:
// As a user, I want to supply a list of numbers.  If the number of
// numbers in my list is odd, I want to know the length of the list
// divided by two.  If the number of numbers in my list is even,
// I want to know the median of the list.
function median(list) {
  var ordered_list = list.sort(function(a,b) {return a - b;} );
  var midPoint = ordered_list.length / 2;
  if(ordered_list.length % 2 != 0)
    return midPoint;
  else
    return (ordered_list[midPoint - 1] + ordered_list[midPoint]) / 2;
}

// Person 5's (Buck's) Driver Code
var list1 = [0];
var list2 = [1,1,1,1,1,1];
var list3 = [1,2,3,4,5,6];
var list4 = [1500,2000,2500,3000,3500,4000,4500,5000,5500];
var list5 = [1234567890, 89764537277838, 1000000000000000000000];
var list6 = [1,1,1,1,1];

console.log("The sums are:");
console.log(sum(list1));
console.log(sum(list2));
console.log(sum(list3));
console.log(sum(list4));
console.log(sum(list5));
console.log(sum(list6));
console.log("");
console.log("The means are:");
console.log(mean(list1));
console.log(mean(list2));
console.log(mean(list3));
console.log(mean(list4));
console.log(mean(list5));
console.log(mean(list6));
console.log("");
console.log("The medians are:");
console.log(median(list1));
console.log(median(list2));
console.log(median(list3));
console.log(median(list4));
console.log(median(list5));
console.log(median(list6));
<commit_msg>Clean up some variable names<commit_after>// Release 4 User Story:
// As a user, I want to get the sum of all the numbers in a list.
function sum(list) {

  return list.reduce(function(prevVal, curVal, curIndex, array) {
                return prevVal + curVal;
              });

}

// Release 4 User Story:
// As a user, I want to get the mean (also known as the average)
// of all the numbers in a list.
function mean(list) {
  return sum(list) / list.length;
}

// Note from Person #5 (Buck): I believe the function below, 'median'
// may be broken?  I can't know for sure since, per the instructions,
// I don't have access to the original spec/tests. But I do know that
// the function doesn't always calculate the median.  According to the
// instructions, I'm not fixing it and how it functions currently will
// be reflected in the User Story.

// Release 4 User Story:
// As a user, I want to supply a list of numbers.  If the number of
// numbers in my list is odd, I want to know the length of the list
// divided by two.  If the number of numbers in my list is even,
// I want to know the median of the list.
function median(list) {
  var ordered_list = list.sort(function(a,b) {return a - b;} );
  var midPoint = ordered_list.length / 2;
  if(ordered_list.length % 2 != 0)
    return midPoint;
  else
    return (ordered_list[midPoint - 1] + ordered_list[midPoint]) / 2;
}

// Person 5's (Buck's) Driver Code
var list1 = [0];
var list2 = [1,1,1,1,1,1];
var list3 = [1,2,3,4,5,6];
var list4 = [1500,2000,2500,3000,3500,4000,4500,5000,5500];
var list5 = [1234567890, 89764537277838, 1000000000000000000000];
var list6 = [1,1,1,1,1];

console.log("The sums are:");
console.log(sum(list1));
console.log(sum(list2));
console.log(sum(list3));
console.log(sum(list4));
console.log(sum(list5));
console.log(sum(list6));
console.log("");
console.log("The means are:");
console.log(mean(list1));
console.log(mean(list2));
console.log(mean(list3));
console.log(mean(list4));
console.log(mean(list5));
console.log(mean(list6));
console.log("");
console.log("The medians are:");
console.log(median(list1));
console.log(median(list2));
console.log(median(list3));
console.log(median(list4));
console.log(median(list5));
console.log(median(list6));
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function (aGlobal) {
  const Cc = Components.classes;
  const Ci = Components.interfaces;
  const Pref = Cc['@mozilla.org/preferences;1']
                 .getService(Ci.nsIPrefBranch);
  const kIEPath = "C:\\Program Files\\Internet Explorer\\iexplore.exe";
  const kChromePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
  const kPrefPrefix = "extensions.switch-link-external-handler@clear-code.com.";
  const kIEPatternsPref = kPrefPrefix +  "ie.patterns.";
  const kChromePatternsPref = kPrefPrefix + "chrome.patterns.";
  var SwitchLinkExternalHandler = {
    startIE: function startIE(aURL) {
      this.startExternalProcess(kIEPath, aURL);
    },

    startChrome: function startChrome(aURL) {
      this.startExternalProcess(kChromePath, aURL);
    },

    startExternalProcess: function startExternalProcess(aPath, aURL) {
      var process = Cc["@mozilla.org/process/util;1"]
                      .createInstance(Ci.nsIProcess);
      var file = Cc["@mozilla.org/file/local;1"]
                   .createInstance(Ci.nsILocalFile);
      var args = [aURL];
      file.initWithPath(aPath);
      process.init(file);
      process.run(false, args, args.length);
    },

    onLinkClick: function onLinkClick(aEvent) {
      let href = hRefForClickEvent(aEvent);

      if (href.match(this.ChromeMatcher)) {
        this.startChrome(href);
      }
      else if (href.match(this.IEMatcher)) {
        this.startIE(href);
      }
      else {
        return;
      }
      aEvent.preventDefault();
      aEvent.stopPropagation();
    },

    get IEMatcher() {
      delete this.IEMatcher;
      return this.IEMatcher = this.urlMatcher(kIEPatternsPref);
    },

    get ChromeMatcher() {
      delete this.ChromeMatcher;
      return this.ChromeMatcher = this.urlMatcher(kChromePatternsPref);
    },

    urlMatcher: function urlMatcher(aPatternsPref) {
      var patterns = [];
      Pref.getChildList(aPatternsPref, {}).forEach(function(aPref) {
        try {
          if (Pref.getPrefType(aPref) != Pref.PREF_STRING)
            return;
          let pattern = this.getStringPref(aPref, '');
          pattern = pattern.trim();
          if (!pattern)
            return;

          pattern = pattern.replace(/([$^\|.{}\[\]()+\\])/g, "$1")
                           .replace(/\*/g, ".*")
                           .replace(/\?/g, ".");
          patterns.push(pattern);
        }
        catch(e) {
        }
      }, this);
      if (patterns.length > 0) {
        return new RegExp("^(" + patterns.join("|") + ")", "i");
      }
      else {
        return null;
      }
    },

    getStringPref: function getStringPref(aKey, aDefault) {
      try {
        return Pref.getComplexValue(aKey, Ci.nsISupportsString).data;
      }
      catch(e) {
      }
      return aDefault || '';
    },

    setStringPref: function setStringPref(aKey, aValue) {
      var str = Cc["@mozilla.org/supports-string;1"]
                  .createInstance(Ci.nsISupportsString);
      str.data = aValue;
      try {
        Pref.setComplexValue(aKey, Ci.nsISupportsString, str);
      }
      catch(e) {
      }
    },

    shellSplit: function shellSplit(aString) {
      var splitStrings = [];
      var buff = "";
      var inQuote = false;
      for (var i = 0, strLength = aString.length; i < strLength; ++i) {
        let char = aString.charAt(i);
        switch (char) {
        case '"':
          if (inQuote) {
            splitStrings.push(buff);
            buff = "";
            inQuote = false;
          }
          else {
            inQuote = true;
          }
          break;
        case ' ':
          if (inQuote) {
            buff += char;
          }
          else if (buff != "") {
            splitStrings.push(buff);
            buff = "";
          }
          break;
        default:
          buff += char;
        }
      }
      if (buff != '') {
        splitStrings.push(buff);
      }
      return splitStrings;
    }
  };

  var browser = document.getElementById("messagepane");
  browser.addEventListener("click", function onClick(aEvent) {
    SwitchLinkExternalHandler.onLinkClick(aEvent);
  }, true);
  aGlobal.SwitchLinkExternalHandler = SwitchLinkExternalHandler;
})(this);
<commit_msg>Get IE executable path for registry<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function (aGlobal) {
  const Cc = Components.classes;
  const Ci = Components.interfaces;
  const Cu = Components.utils;
  const Pref = Cc['@mozilla.org/preferences;1']
                 .getService(Ci.nsIPrefBranch);
  const Registry = Cu.import("resource://gre/modules/WindowsRegistry.jsm")
                     .WindowsRegistry;
  const kIEPath = "C:\\Program Files\\Internet Explorer\\iexplore.exe";
  const kChromePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
  const kPrefPrefix = "extensions.switch-link-external-handler@clear-code.com.";
  const kIEPatternsPref = kPrefPrefix +  "ie.patterns.";
  const kChromePatternsPref = kPrefPrefix + "chrome.patterns.";
  var SwitchLinkExternalHandler = {
    startIE: function startIE(aURL) {
      this.startExternalProcess(kIEPath, aURL);
    },

    startChrome: function startChrome(aURL) {
      this.startExternalProcess(kChromePath, aURL);
    },

    startExternalProcess: function startExternalProcess(aPath, aURL) {
      var process = Cc["@mozilla.org/process/util;1"]
                      .createInstance(Ci.nsIProcess);
      var file = Cc["@mozilla.org/file/local;1"]
                   .createInstance(Ci.nsILocalFile);
      var args = [aURL];
      file.initWithPath(aPath);
      process.init(file);
      process.run(false, args, args.length);
    },

    get IECommandline() {
      delete this.IECommandline;
      var commandLine = Registry.readRegKey(
        Ci.nsIWindowsRegKey.ROOT_KEY_CLASSES_ROOT,
        "Applications\\iexplore.exe\\shell\\open\\command",
        ""
      );
      return this.IECommandline = this.shellSplit(commandLine);
    },

    onLinkClick: function onLinkClick(aEvent) {
      let href = hRefForClickEvent(aEvent);

      if (href.match(this.ChromeMatcher)) {
        this.startChrome(href);
      }
      else if (href.match(this.IEMatcher)) {
        this.startIE(href);
      }
      else {
        return;
      }
      aEvent.preventDefault();
      aEvent.stopPropagation();
    },

    get IEMatcher() {
      delete this.IEMatcher;
      return this.IEMatcher = this.urlMatcher(kIEPatternsPref);
    },

    get ChromeMatcher() {
      delete this.ChromeMatcher;
      return this.ChromeMatcher = this.urlMatcher(kChromePatternsPref);
    },

    urlMatcher: function urlMatcher(aPatternsPref) {
      var patterns = [];
      Pref.getChildList(aPatternsPref, {}).forEach(function(aPref) {
        try {
          if (Pref.getPrefType(aPref) != Pref.PREF_STRING)
            return;
          let pattern = this.getStringPref(aPref, '');
          pattern = pattern.trim();
          if (!pattern)
            return;

          pattern = pattern.replace(/([$^\|.{}\[\]()+\\])/g, "$1")
                           .replace(/\*/g, ".*")
                           .replace(/\?/g, ".");
          patterns.push(pattern);
        }
        catch(e) {
        }
      }, this);
      if (patterns.length > 0) {
        return new RegExp("^(" + patterns.join("|") + ")", "i");
      }
      else {
        return null;
      }
    },

    getStringPref: function getStringPref(aKey, aDefault) {
      try {
        return Pref.getComplexValue(aKey, Ci.nsISupportsString).data;
      }
      catch(e) {
      }
      return aDefault || '';
    },

    setStringPref: function setStringPref(aKey, aValue) {
      var str = Cc["@mozilla.org/supports-string;1"]
                  .createInstance(Ci.nsISupportsString);
      str.data = aValue;
      try {
        Pref.setComplexValue(aKey, Ci.nsISupportsString, str);
      }
      catch(e) {
      }
    },

    shellSplit: function shellSplit(aString) {
      var splitStrings = [];
      var buff = "";
      var inQuote = false;
      for (var i = 0, strLength = aString.length; i < strLength; ++i) {
        let char = aString.charAt(i);
        switch (char) {
        case '"':
          if (inQuote) {
            splitStrings.push(buff);
            buff = "";
            inQuote = false;
          }
          else {
            inQuote = true;
          }
          break;
        case ' ':
          if (inQuote) {
            buff += char;
          }
          else if (buff != "") {
            splitStrings.push(buff);
            buff = "";
          }
          break;
        default:
          buff += char;
        }
      }
      if (buff != '') {
        splitStrings.push(buff);
      }
      return splitStrings;
    }
  };

  var browser = document.getElementById("messagepane");
  browser.addEventListener("click", function onClick(aEvent) {
    SwitchLinkExternalHandler.onLinkClick(aEvent);
  }, true);
  aGlobal.SwitchLinkExternalHandler = SwitchLinkExternalHandler;
})(this);
<|endoftext|>


<commit_before>/*
 * This file is part of TbSync.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

 "use strict";

 var ProviderInfoObject = class {
    constructor(provider) {
        if (!providers.hasOwnProperty(provider)) {
            throw new Error("Provider <" + provider + "> has not been loaded. Failed to create ProviderInfoObject.");
        }
        this.provider = provider;
    }

    getVersion() {
        return providers.loadedProviders[this.provider].version;
    }

    getStringBundle() {
        return providers.loadedProviders[this.provider].bundle;
    }
}

var providers = {

    //list of default providers (available in add menu, even if not installed)
    defaultProviders: {
        "dav" : {
            name: "CalDAV & CardDAV",
            homepageUrl: "https://addons.thunderbird.net/addon/dav-4-tbsync/"},
        "eas" : {
            name: "Exchange ActiveSync",
            homepageUrl: "https://addons.thunderbird.net/addon/eas-4-tbsync/"},
    },

    loadedProviders: null,

    load: async function () {
        this.loadedProviders = {};
    },

    unload: async function () {
        for (let provider in this.loadedProviders) {
            await this.unloadProvider(provider);
        }
    },

    loadProvider:  async function (addonId, provider, js) {
        //only load, if not yet loaded and if the provider name does not shadow a fuction inside provider.js
        if (!this.loadedProviders.hasOwnProperty(provider) && !this.hasOwnProperty(provider) && js.startsWith("chrome://")) {
            try {
                let addon = await tbSync.getAddonByID(addonId);

                this[provider] = {};
                this.loadedProviders[provider] = {};
                this.loadedProviders[provider].addon = addon;
                this.loadedProviders[provider].addonId = addonId;
                this.loadedProviders[provider].version = addon.version.toString();

                //load provider subscripts into tbSync
                Services.scriptloader.loadSubScript(js, this[provider], "UTF-8");
                this.loadedProviders[provider].bundle = Services.strings.createBundle(this[provider].api.getStringBundleUrl());

                //load provider
                await this[provider].api.load(tbSync.lightning.isAvailable());

                await tbSync.messenger.overlayManager.registerOverlay("chrome://tbsync/content/manager/editAccount.xul?provider=" + provider, this[provider].api.getEditAccountOverlayUrl());
                tbSync.dump("Loaded provider", provider + "::" + this[provider].api.getNiceProviderName() + " ("+this.loadedProviders[provider].version+")");
                tbSync.core.resetSync(provider);
                Services.obs.notifyObservers(null, "tbsync.observer.manager.updateAccountsList", provider);

            } catch (e) {
                tbSync.dump("FAILED to load provider", provider);
                Components.utils.reportError(e);
            }

        }
    },

    unloadProvider: async function (provider) {
        if (this.loadedProviders.hasOwnProperty(provider)) {
            tbSync.dump("Unloading provider", provider);
            await this[provider].api.unload(tbSync.lightning.isAvailable());
            delete this.loadedProviders[provider];
            delete this[provider];
            Services.obs.notifyObservers(null, "tbsync.observer.manager.updateAccountsList", provider);
            Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", null);
        }
    },

    getDefaultAccountEntries: function (provider) {
        let defaults = tbSync.providers[provider].api.getDefaultAccountEntries();

        //add system properties
        defaults.provider = provider;
        defaults.account = "";
        defaults.lastsynctime = "0";
        defaults.status = "disabled"; //global status: disabled, OK, syncing, notsyncronized, nolightning, ...
        defaults.autosync = "0";
        defaults.accountname = "";

        return defaults;
    },

    getDefaultFolderEntries: function (accountID) {
        let provider = tbSync.db.getAccountSetting(accountID, "provider");
        let defaults = tbSync.providers[provider].api.getDefaultFolderEntries();

        //add system properties
        defaults.account = accountID;
        defaults.folderID = "";

        return defaults;
    }

}
<commit_msg>add getAccountObjects() to ProviderInfoObject<commit_after>/*
 * This file is part of TbSync.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

 "use strict";

 var ProviderInfoObject = class {
    constructor(provider) {
        if (!providers.hasOwnProperty(provider)) {
            throw new Error("Provider <" + provider + "> has not been loaded. Failed to create ProviderInfoObject.");
        }
        this.provider = provider;
    }

    getVersion() {
        return providers.loadedProviders[this.provider].version;
    }

    getStringBundle() {
        return providers.loadedProviders[this.provider].bundle;
    }

    getAccountObjects() {
        let accounts = tbSync.db.getAccounts();
        let accountObjects = [];
        for (let i=0; i<accounts.IDs.length; i++) {
            let accountID = accounts.IDs[i];
            if (accounts.data[accountID].provider == this.provider) {
                accountObjects.push(new tbSync.AccountObject(accountID));
            }
        }
        return accountObjects;
    }
}

var providers = {

    //list of default providers (available in add menu, even if not installed)
    defaultProviders: {
        "dav" : {
            name: "CalDAV & CardDAV",
            homepageUrl: "https://addons.thunderbird.net/addon/dav-4-tbsync/"},
        "eas" : {
            name: "Exchange ActiveSync",
            homepageUrl: "https://addons.thunderbird.net/addon/eas-4-tbsync/"},
    },

    loadedProviders: null,

    load: async function () {
        this.loadedProviders = {};
    },

    unload: async function () {
        for (let provider in this.loadedProviders) {
            await this.unloadProvider(provider);
        }
    },

    loadProvider:  async function (addonId, provider, js) {
        //only load, if not yet loaded and if the provider name does not shadow a fuction inside provider.js
        if (!this.loadedProviders.hasOwnProperty(provider) && !this.hasOwnProperty(provider) && js.startsWith("chrome://")) {
            try {
                let addon = await tbSync.getAddonByID(addonId);

                this[provider] = {};
                this.loadedProviders[provider] = {};
                this.loadedProviders[provider].addon = addon;
                this.loadedProviders[provider].addonId = addonId;
                this.loadedProviders[provider].version = addon.version.toString();

                //load provider subscripts into tbSync
                Services.scriptloader.loadSubScript(js, this[provider], "UTF-8");
                this.loadedProviders[provider].bundle = Services.strings.createBundle(this[provider].api.getStringBundleUrl());

                //load provider
                await this[provider].api.load(tbSync.lightning.isAvailable());

                await tbSync.messenger.overlayManager.registerOverlay("chrome://tbsync/content/manager/editAccount.xul?provider=" + provider, this[provider].api.getEditAccountOverlayUrl());
                tbSync.dump("Loaded provider", provider + "::" + this[provider].api.getNiceProviderName() + " ("+this.loadedProviders[provider].version+")");
                tbSync.core.resetSync(provider);
                Services.obs.notifyObservers(null, "tbsync.observer.manager.updateAccountsList", provider);

            } catch (e) {
                tbSync.dump("FAILED to load provider", provider);
                Components.utils.reportError(e);
            }

        }
    },

    unloadProvider: async function (provider) {
        if (this.loadedProviders.hasOwnProperty(provider)) {
            tbSync.dump("Unloading provider", provider);
            await this[provider].api.unload(tbSync.lightning.isAvailable());
            delete this.loadedProviders[provider];
            delete this[provider];
            Services.obs.notifyObservers(null, "tbsync.observer.manager.updateAccountsList", provider);
            Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", null);
        }
    },

    getDefaultAccountEntries: function (provider) {
        let defaults = tbSync.providers[provider].api.getDefaultAccountEntries();

        //add system properties
        defaults.provider = provider;
        defaults.account = "";
        defaults.lastsynctime = "0";
        defaults.status = "disabled"; //global status: disabled, OK, syncing, notsyncronized, nolightning, ...
        defaults.autosync = "0";
        defaults.accountname = "";

        return defaults;
    },

    getDefaultFolderEntries: function (accountID) {
        let provider = tbSync.db.getAccountSetting(accountID, "provider");
        let defaults = tbSync.providers[provider].api.getDefaultFolderEntries();

        //add system properties
        defaults.account = accountID;
        defaults.folderID = "";

        return defaults;
    }

}
<|endoftext|>


<commit_before>define(['jquery','underscore','events','mustache','mybackbone','conf', "text!../templates/toolbar.html", "qtip"],
        function ($,_,events,mustache,mybackbone,conf,toolbartpl, qtip) {
    "use strict";

    // handle keyboard shortcuts also

    var keyboardShortcuts = {};
    var widgets = {};
    var buttons = {};
    var editors = {};
    var colors = [];

    function randColor() {
        return "#"+Math.floor(Math.random()*16777215).toString(16);
    }

    function itemSort(a,b) {
        if ( ( a.index === undefined ) && (b.index === undefined) ) return 0;

        if ( ( a.index !== undefined ) && (b.index === undefined) ) return 1;

        if ( ( a.index === undefined ) && (b.index !== undefined) ) return -1;

        return a.index - b.index;
    }

    function registerWidget(data) {
        // widget is a backbone view that renders widget
        // modes is an array of modes in which this widget is active
        // toolbar takes care that widget.el exists when widget.render
        // is called

        var id = data.id;
        if (id in widgets) {
            throw "Trying to reregister widget " + id;
        }
        widgets [id] = data;
    }

    $('body').on('keydown',function(ev) {
        var key = view.mode+'-'+ev.which;
        var event = keyboardShortcuts[key];
        if (event) {
            events.trigger(event);
        }
    });

    function ping(){
        var re = new RegExp("[0-9a-f]{32}");
        var uidarr = re.exec(document.URL);
        var uid = uidarr[0]
        var options = {
            type:'GET',
            url: "/api/id/"+uid+"/ping",
            statusCode: {
                401: function() {events.trigger("saveFailed401", 'pinging the backend')},
                403: function() {events.trigger("saveFailed", 'Forbidden')},
            }
        }
        var readonly = false;
        $.ajax(options)
            .done(function(data){
                console.log(data)
                if(data.code == 13){
                    console.log("ReadOnly");
                    readonly = true;
                }
                editors = data.users;
                for(var editor in editors){
                    if(colors[editor] == null) {
                        colors[editor] = randColor();
                    }
                }
                view.render(readonly);
            })
    }
    var View = mybackbone.View.extend({
        initialize: function() {
            // we must wait for editor before firing initial cbs
            // BUG: race condition if user clicks between toolbar render
            // and editor render
            this._editorRendered = $.Deferred();
            conf.buttons.map(_.bind(this.registerButton,this));
            conf.shortcuts.map(_.bind(this.registerKeyboardShortcut,this));

            ping();
            (function(view){
                window.setInterval(function(){
                    ping();
                }, 30000);
            })(this)
        },
        el : '#toolbar',
        myEvents: {
            'changeMode': 'changeMode',
            'editorRendered': 'editorRendered'
        },
        events: {
            'click button': 'handleClick'
        },
        myModes: ['page','document'],
        setViewActive: function (mode) {
            this.render();
        },
        handleTag: function(event){
            var ch = event.currentTarget.getAttribute('data-character');
            console.log(ch)
            events.trigger("tagWord")
        },
        editorRendered: function () {
            this._editorRendered.resolve();
        },
        registerKeyboardShortcut: function (shortcut) {
            if (shortcut.which in keyboardShortcuts) {
                throw "Trying to reregister shortcut for " + shortcut.code;
            }
            for (var i in shortcut.modes) {
                var mode = shortcut.modes[i];
                var key = mode+'-'+shortcut.code;
                keyboardShortcuts [key] = shortcut.event;
                // console.log(shortcut)
            }
        },

        registerButton: function (data) {
            var id = data.id;
            if (data.index === undefined) {
                throw 'Sort index must be given for buttons.';
            }
            if (id in buttons) {
                throw "Trying to reregister button " + id;
            }
            buttons [id] = data;
            if (data.toggle && (!data.suppressInitialCB)) {
                this._editorRendered.done( function () {
                    events.trigger(data.event,data.active);
                });
            }
        },
        handleClick: function (ev) {
            var id = ev.currentTarget.id;
            var b = buttons[id];
            if (b === undefined) return;
            if (b.modes.indexOf(this.currentMode()) == -1) return;
            if (b.toggle) {
                var toggled = !($(ev.currentTarget).hasClass("active"));
                events.trigger(b.event,toggled);
            } else {
                events.trigger(b.event, ev);
            }

            events.trigger('refocus');

            var myEvent = 'button-'+id+'-clicked';
            events.trigger(myEvent);
        },
        render: function(opt) {
            var that = this;
            var buttonArray = buttons;
            if(opt){
                buttonArray = _.filter(buttons, function(obj){
                    return obj.id == "save";
                });
            }
            var context = {
                widgets: _.map(widgets, function (w) {
                    return w;
                }),
                buttons: _.map(buttonArray, function (b) {
                    return {
                        id: b.id,
                        index: b.index,
                        classes: 'btn' +
                        (b.active ? ' active' : '') +
                        (b.modes.indexOf(that.mode) != -1 ?
                            '' :
                            ' disabled'),
                        extra: b.toggle && 'data-toggle="button"' || '',
                        icon: b.icon,
                        title: b.title,
                        text: b.text
                    };

                }),
                userbox: _.map(editors, function (e, key) {
                    return {
                        user: key,
                        color: colors[key]
                    };
                })
            };
            context.widgets.sort(itemSort);
            context.buttons.sort(itemSort);
            console.log(context);

            this.$el.html(mustache.render(toolbartpl,context));

            for (var i in widgets) {
                //if (widgets[i].modes)
                var view = widgets[i].view;
                view.setElement('#' + i);
                view.render();
            }
            $(".userbox").qtip({
                content:{
                    attr: 'data-tooltip'
                }
            });
            //this.$el.button(); // enable bootstrap button code
        }
    });

    var view = new View();
    return {
        view : view,
        registerWidget : registerWidget
    };

});
<commit_msg>read only mode<commit_after>define(['jquery','underscore','events','mustache','mybackbone','conf', "text!../templates/toolbar.html", "qtip"],
        function ($,_,events,mustache,mybackbone,conf,toolbartpl, qtip) {
    "use strict";

    // handle keyboard shortcuts also

    var keyboardShortcuts = {};
    var widgets = {};
    var buttons = {};
    var editors = {};
    var colors = [];

    function randColor() {
        return "#"+Math.floor(Math.random()*16777215).toString(16);
    }

    function itemSort(a,b) {
        if ( ( a.index === undefined ) && (b.index === undefined) ) return 0;

        if ( ( a.index !== undefined ) && (b.index === undefined) ) return 1;

        if ( ( a.index === undefined ) && (b.index !== undefined) ) return -1;

        return a.index - b.index;
    }

    function registerWidget(data) {
        // widget is a backbone view that renders widget
        // modes is an array of modes in which this widget is active
        // toolbar takes care that widget.el exists when widget.render
        // is called

        var id = data.id;
        if (id in widgets) {
            throw "Trying to reregister widget " + id;
        }
        widgets [id] = data;
    }

    $('body').on('keydown',function(ev) {
        var key = view.mode+'-'+ev.which;
        var event = keyboardShortcuts[key];
        if (event) {
            events.trigger(event);
        }
    });

    function ping(){
        var re = new RegExp("[0-9a-f]{32}");
        var uidarr = re.exec(document.URL);
        var uid = uidarr[0]
        var options = {
            type:'GET',
            url: "/api/id/"+uid+"/ping",
            statusCode: {
                401: function() {events.trigger("saveFailed401", 'pinging the backend')},
                403: function() {events.trigger("saveFailed", 'Forbidden')},
            }
        }
        var readonly = false;
        $.ajax(options)
            .done(function(data){
                console.log(data)
                if(data.code == 13){
                    console.log("ReadOnly");
                    readonly = true;
                }
                editors = data.users;
                for(var editor in editors){
                    if(colors[editor] == null) {
                        colors[editor] = randColor();
                    }
                }
                view.render(readonly);
            })
    }
    var View = mybackbone.View.extend({
        initialize: function() {
            // we must wait for editor before firing initial cbs
            // BUG: race condition if user clicks between toolbar render
            // and editor render
            this._editorRendered = $.Deferred();
            conf.buttons.map(_.bind(this.registerButton,this));
            conf.shortcuts.map(_.bind(this.registerKeyboardShortcut,this));

            ping();
            (function(view){
                window.setInterval(function(){
                    ping();
                }, 30000);
            })(this)
        },
        el : '#toolbar',
        myEvents: {
            'changeMode': 'changeMode',
            'editorRendered': 'editorRendered'
        },
        events: {
            'click button': 'handleClick'
        },
        myModes: ['page','document'],
        setViewActive: function (mode) {
            this.render();
        },
        handleTag: function(event){
            var ch = event.currentTarget.getAttribute('data-character');
            console.log(ch)
            events.trigger("tagWord")
        },
        editorRendered: function () {
            this._editorRendered.resolve();
        },
        registerKeyboardShortcut: function (shortcut) {
            if (shortcut.which in keyboardShortcuts) {
                throw "Trying to reregister shortcut for " + shortcut.code;
            }
            for (var i in shortcut.modes) {
                var mode = shortcut.modes[i];
                var key = mode+'-'+shortcut.code;
                keyboardShortcuts [key] = shortcut.event;
                // console.log(shortcut)
            }
        },

        registerButton: function (data) {
            var id = data.id;
            if (data.index === undefined) {
                throw 'Sort index must be given for buttons.';
            }
            if (id in buttons) {
                throw "Trying to reregister button " + id;
            }
            buttons [id] = data;
            if (data.toggle && (!data.suppressInitialCB)) {
                this._editorRendered.done( function () {
                    events.trigger(data.event,data.active);
                });
            }
        },
        handleClick: function (ev) {
            var id = ev.currentTarget.id;
            var b = buttons[id];
            if (b === undefined) return;
            if (b.modes.indexOf(this.currentMode()) == -1) return;
            if (b.toggle) {
                var toggled = !($(ev.currentTarget).hasClass("active"));
                events.trigger(b.event,toggled);
            } else {
                events.trigger(b.event, ev);
            }

            events.trigger('refocus');

            var myEvent = 'button-'+id+'-clicked';
            events.trigger(myEvent);
        },
        render: function(opt) {
            var that = this;
            var buttonArray = buttons;
            if(opt){
                buttonArray = _.filter(buttons, function(obj){
                    return obj.id != "save";
                });
            }
            var context = {
                widgets: _.map(widgets, function (w) {
                    return w;
                }),
                buttons: _.map(buttonArray, function (b) {
                    return {
                        id: b.id,
                        index: b.index,
                        classes: 'btn' +
                        (b.active ? ' active' : '') +
                        (b.modes.indexOf(that.mode) != -1 ?
                            '' :
                            ' disabled'),
                        extra: b.toggle && 'data-toggle="button"' || '',
                        icon: b.icon,
                        title: b.title,
                        text: b.text
                    };

                }),
                userbox: _.map(editors, function (e, key) {
                    return {
                        user: key,
                        color: colors[key]
                    };
                })
            };
            context.widgets.sort(itemSort);
            context.buttons.sort(itemSort);
            console.log(context);

            this.$el.html(mustache.render(toolbartpl,context));

            for (var i in widgets) {
                //if (widgets[i].modes)
                var view = widgets[i].view;
                view.setElement('#' + i);
                view.render();
            }
            $(".userbox").qtip({
                content:{
                    attr: 'data-tooltip'
                }
            });
            //this.$el.button(); // enable bootstrap button code
        }
    });

    var view = new View();
    return {
        view : view,
        registerWidget : registerWidget
    };

});
<|endoftext|>


<commit_before>$(document).ready(function() {
  // Declaring Global Variables
  var pomodoroDefault = 25 * 60, // minutes by default
  breakDefault = 5 * 60,
  pomodoroText = $(".pomodoro-text"),
  continuousMode = false,
  soundMode = true,
  workOn = false,
  audio = new Audio('files/sound.mp3')
  timerID = null,
  pomodoros = localStorage.getItem("pomodoros") == undefined ? 0 : localStorage.getItem("pomodoros"),
  spentTime = localStorage.getItem("howMuchTime");

  $(".pomodoros").html(pomodoros);
  $(".timespent").html(spentTime + " mins.");

  function renderTime(duration) {
      var minutes, seconds;
      minutes = parseInt(duration/60, 10);
      seconds = parseInt(duration%60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      pomodoroText.html(minutes + ":" + seconds);
  }

  function reset() {
    renderTime(pomodoroDefault);
    clearTimeout(timerID);
  }

  function soundModeCheck() {
    if(soundMode == true) {
      audio.play();
    } else {
      return null;
    }
  }

  function continuousModeCheck() {
    if(continuousMode == false) {
      $("#continuousModeBlock").show();
    } else if(workOn == true) {
      $("#continuousModeBlock").hide();
      breakTimer(breakDefault - 1);
      } else {
      $("#continuousModeBlock").hide();
      pomodoroTimer(pomodoroDefault - 1);
    }
  }

  function breakTimer(duration) {
    var timer = duration;
    workOn = false;
    $("#indicator").text("Break");

    timerID = setInterval(function() {
      renderTime(timer);

      if(--timer < 0) {
        soundModeCheck();
        timer = duration;
        reset();
        continuousModeCheck();
      }

    }, 1000);
  }

  function updatePomodoros(duration) {
      localStorage.setItem("pomodoros", ++pomodoros);
      localStorage.setItem("howMuchTime", parseInt(spentTime) + parseInt((duration + 1)/60));
      $(".pomodoros").html(pomodoros);
      $(".timespent").html(spentTime + " mins.");
  }

  function updateTime() { // in local storage, checking the date
    var currentTime = new Date();
    if(localStorage.getItem("date") == undefined) {
      var currentTime = new Date();
      localStorage.setItem("date", currentTime);
    } else if(currentTime > localStorage.getItem("date")) {
      localStorage.setItem("pomodoros", 0);
      localStorage.setItem("date", currentTime);
      localStorage.setItem("howMuchTime", zero);
    }
  }

  function pomodoroTimer(duration) {

    var timer = duration;
    workOn = true;

    $("#start").text("Reset");
    $("#indicator").text("Work");

    timerID = setInterval(function() {

      renderTime(timer);

      if(--timer < 0) {
        updatePomodoros(duration);
        updateTime();
        soundModeCheck();
        timer = duration;
        reset();
        continuousModeCheck();
      }

    }, 1000);
  }

  // Events

  $("#start").click(function() {
    if(timerID != undefined) {
      reset();
      pomodoroTimer(pomodoroDefault - 1);
    } else {
      pomodoroTimer(pomodoroDefault - 1);
    }
  });

  $("#okButton").click(function() {
    if(workOn == true) {
      $("#continuousModeBlock").hide();
      breakTimer(breakDefault - 1);
    } else {
      $("#continuousModeBlock").hide();
      pomodoroTimer(pomodoroDefault - 1);
    }
  });

  $("#stop").click(function() {
    workOn = false;
    $("#start").text("Start");
    $("#indicator").text("Work");
    reset();
  });

  $("#settings").click(function() {
    $("#workTime").val(pomodoroDefault / 60);
    $("#breakTime").val(breakDefault / 60);
  });

  $("#changeSettings").click(function() {
    if(isNaN($("#workTime").val()) || isNaN($("#breakTime").val())) {
      alert("Please, enter only numbers");
      return 1;
    } else if($("#workTime").val() < 1 || $("#workTime").val() > 120) {
      alert("Work Time bounds are between 1 and 120 minutes");
      return 1;
    } else if($("#breakTime").val() < 1 || $("#breakTime").val() > 30) {
      alert("Break Time bounds are between 1 and 30 minutes");
      return 1;
    } else {
      pomodoroDefault = $("#workTime").val() * 60;
      breakDefault = $("#breakTime").val() * 60;
      continuousMode = $("#continuousMode").is(":checked");
      soundMode = $("#soundMode").is(":checked")
      renderTime(pomodoroDefault);
    }
  });

  renderTime(pomodoroDefault);
});<commit_msg>Fixed: instead of showing null it renders 0 now, if there is nothing in localstorage<commit_after>$(document).ready(function() {
  // Declaring Global Variables
  var pomodoroDefault = 25 * 60, // minutes by default
  breakDefault = 5 * 60,
  pomodoroText = $(".pomodoro-text"),
  continuousMode = false,
  soundMode = true,
  workOn = false,
  audio = new Audio('files/sound.mp3')
  timerID = null,
  pomodoros = localStorage.getItem("pomodoros") == null ? 0 : localStorage.getItem("pomodoros"),
  spentTime = localStorage.getItem("howMuchTime") == null ? 0 : localStorage.getItem("howMuchTime");

  $(".pomodoros").html(pomodoros);
  $(".timespent").html(spentTime + " mins.");

  function renderTime(duration) {
      var minutes, seconds;
      minutes = parseInt(duration/60, 10);
      seconds = parseInt(duration%60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      pomodoroText.html(minutes + ":" + seconds);
  }

  function reset() {
    renderTime(pomodoroDefault);
    clearTimeout(timerID);
  }

  function soundModeCheck() {
    if(soundMode == true) {
      audio.play();
    } else {
      return null;
    }
  }

  function continuousModeCheck() {
    if(continuousMode == false) {
      $("#continuousModeBlock").show();
    } else if(workOn == true) {
      $("#continuousModeBlock").hide();
      breakTimer(breakDefault - 1);
      } else {
      $("#continuousModeBlock").hide();
      pomodoroTimer(pomodoroDefault - 1);
    }
  }

  function breakTimer(duration) {
    var timer = duration;
    workOn = false;
    $("#indicator").text("Break");

    timerID = setInterval(function() {
      renderTime(timer);

      if(--timer < 0) {
        soundModeCheck();
        timer = duration;
        reset();
        continuousModeCheck();
      }

    }, 1000);
  }

  function updatePomodoros(duration) {
      localStorage.setItem("pomodoros", ++pomodoros);
      localStorage.setItem("howMuchTime", parseInt(spentTime) + parseInt((duration + 1)/60));
      $(".pomodoros").html(pomodoros);
      $(".timespent").html(spentTime + " mins.");
  }

  function updateTime() { // in local storage, checking the date
    var currentTime = new Date();
    if(localStorage.getItem("date") == undefined) {
      var currentTime = new Date();
      localStorage.setItem("date", currentTime);
    } else if(currentTime > localStorage.getItem("date")) {
      localStorage.setItem("pomodoros", 0);
      localStorage.setItem("date", currentTime);
      localStorage.setItem("howMuchTime", zero);
    }
  }

  function pomodoroTimer(duration) {

    var timer = duration;
    workOn = true;

    $("#start").text("Reset");
    $("#indicator").text("Work");

    timerID = setInterval(function() {

      renderTime(timer);

      if(--timer < 0) {
        updatePomodoros(duration);
        updateTime();
        soundModeCheck();
        timer = duration;
        reset();
        continuousModeCheck();
      }

    }, 1000);
  }

  // Events

  $("#start").click(function() {
    if(timerID != undefined) {
      reset();
      pomodoroTimer(pomodoroDefault - 1);
    } else {
      pomodoroTimer(pomodoroDefault - 1);
    }
  });

  $("#okButton").click(function() {
    if(workOn == true) {
      $("#continuousModeBlock").hide();
      breakTimer(breakDefault - 1);
    } else {
      $("#continuousModeBlock").hide();
      pomodoroTimer(pomodoroDefault - 1);
    }
  });

  $("#stop").click(function() {
    workOn = false;
    $("#start").text("Start");
    $("#indicator").text("Work");
    reset();
  });

  $("#settings").click(function() {
    $("#workTime").val(pomodoroDefault / 60);
    $("#breakTime").val(breakDefault / 60);
  });

  $("#changeSettings").click(function() {
    if(isNaN($("#workTime").val()) || isNaN($("#breakTime").val())) {
      alert("Please, enter only numbers");
      return 1;
    } else if($("#workTime").val() < 1 || $("#workTime").val() > 120) {
      alert("Work Time bounds are between 1 and 120 minutes");
      return 1;
    } else if($("#breakTime").val() < 1 || $("#breakTime").val() > 30) {
      alert("Break Time bounds are between 1 and 30 minutes");
      return 1;
    } else {
      pomodoroDefault = $("#workTime").val() * 60;
      breakDefault = $("#breakTime").val() * 60;
      continuousMode = $("#continuousMode").is(":checked");
      soundMode = $("#soundMode").is(":checked")
      renderTime(pomodoroDefault);
    }
  });

  renderTime(pomodoroDefault);
});<|endoftext|>


<commit_before>/*global $rdf, SolidAuthClient, SolidUtils*/

var solid = require('solid');

function createTest() {
    SolidUtils.getStorageRootContainer().then(function (root) {
        return SolidUtils.createPath(root.value + "public", "z/aa1/bb1/cc1/dd1");
    }).then(function (result) {
        alert(result);
    });
}

function updateLoginInfo() {
    SolidAuthClient.currentSession().then(function (session) {
        var user = $rdf.sym(session.webId);
        SolidUtils.rdfFetch(session.webId).then(function (response) {
            var name = response.graph.any(user, vocab.foaf('name'));
            $("#loginInfo").html("Logged in as:");
            $("#loginName").html("" + name + "");
        });
    });
}

$(function () {
    SolidAuthClient.currentSession().then(function (session) {
        if (session === null) {
            SolidUtils.login().then(function () {
                updateLoginInfo();
            });
        } else {
            updateLoginInfo();
        }
    });
});

var vocab = {
    schema: function (suffix) {
        return $rdf.sym("http://schema.org/" + suffix);
    },
    rdf: function (suffix) {
        return $rdf.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#" + suffix);
    },
    solid: function (suffix) {
        return $rdf.sym("http://www.w3.org/ns/solid/terms#" + suffix);
    },
    space: function (suffix) {
        return $rdf.sym("http://www.w3.org/ns/pim/space#" + suffix);
    },
    foaf: function (suffix) {
        return $rdf.sym("http://xmlns.com/foaf/0.1/" + suffix);
    }
};

$(function () {

    function default_timestamp() {
        var momentNow = moment();
        return "FactsMission--" + momentNow.format('YYYY-MM-DD') + '-'
                + momentNow.format('dddd').substring(0, 3).toUpperCase() + "-" + momentNow.format('Ahhmmss');
    }

    $('#default_timestamp').html(default_timestamp());
    $('[data-toggle="tooltip"]').tooltip();
    $('#tweet_url').on('change keyup paste', function () {
        $("#tweet-valid").removeClass("show").addClass("hide");
        $("#tweet-invalid").removeClass("show").addClass("hide");
        CheckData();
    });
    $('#claim_reviewed, #ldp-uri, #review_body').on('change keyup paste', function () {
        CheckData();
    });
    $('#rating-in-stars').on('change', function () {
        CheckData();
    });

    function check_tweet(value) {
        // Regex-pattern to check URLs against:
        // https://twitter.com/<twitteruser>/status/<long number>
        var urlRegex = /^https:\/\/twitter.com\/[a-zA-Z _.,!"'/$]+\/status\/[0-9]*$/;
        if (urlRegex.test(value)) {
            return true;
        } else {
            return false;
        }
    }

    $('#check_tweet').on('click', function () {
        // Regex-pattern to check URLs against:
        // https://twitter.com/<twitteruser>/status/<long number>
        var urlRegex = /^https:\/\/twitter.com\/[a-zA-Z _.,!"'/$]+\/status\/[0-9]*$/;
        var tweet_url = $('#tweet_url').val();
        if (check_tweet(tweet_url)) {
            $("#tweet-valid").removeClass("hide").addClass("show");
        } else {
            $("#tweet-invalid").removeClass("hide").addClass("show");
        }
    });

    function CheckData() {
        const LDP_neg_msg = "Missing LDP-URI.";
        const Tweet_url_neg_msg = "Missing Valid Tweet URL.";
        const Claim_neg_msg = "Missing Claim made in Tweet.";
        const Review_body_neg_msg = "Missing the body of your Review.";
        const Rating_neg_msg = "Missing Rating.";
        const LDP_msg = "LDP-URI appears valid";
        const Tweet_url_msg = "Tweet URL appears valid";
        const Claim_msg = "Claim in Tweet described.";
        const Rating_msg = "Claim Rated.";
        const Review_body_msg = "Review of Tweet described.";
        if ($('#ldp-uri').val() == false) {
            $('#valcheck_1_msg').text(LDP_neg_msg);
            $('#valcheck_1_ck').prop('checked', false);
        } else {
            $('#valcheck_1_msg').text(LDP_msg);
            $('#valcheck_1_ck').prop('checked', true);
        }
        if (check_tweet($('#tweet_url').val()) == false) {
            $('#valcheck_2_msg').text(Tweet_url_neg_msg);
            $('#valcheck_2_ck').prop('checked', false);
        } else {
            $('#valcheck_2_msg').text(Tweet_url_msg);
            $('#valcheck_2_ck').prop('checked', true);
        }
        if ($('#claim_reviewed').val() == false) {
            $('#valcheck_3_msg').text(Review_body_neg_msg);
            $('#valcheck_3_ck').prop('checked', false);
        } else {
            $('#valcheck_3_msg').text(Review_body_msg);
            $('#valcheck_3_ck').prop('checked', true);
        }
        if ($('#review_body').val() == false) {
            $('#valcheck_4_msg').text(Claim_neg_msg);
            $('#valcheck_4_ck').prop('checked', false);
        } else {
            $('#valcheck_4_msg').text(Claim_msg);
            $('#valcheck_4_ck').prop('checked', true);
        }
        if ($('#rating-in-stars').val() == 0) {
            $('#valcheck_5_msg').text(Rating_neg_msg);
            $('#valcheck_5_ck').prop('checked', false);
        } else {
            $('#valcheck_5_msg').text(Rating_msg);
            $('#valcheck_5_ck').prop('checked', true);
        }
    }
    ;

    $('#pop_claim').on('click', function (event) {
        event.preventDefault();
        event.stopPropagation();
        $('#ldp-uri').val("https://farewellutopia.com:8443/");
        $('#tweet_url').val("https://twitter.com/wesbos/status/912736261630251008");
        $('#claim_reviewed').val("That Facebook has decided to relicense React & Friends to MIT.");
        $('#review_body').val("Wes Bos is a reliable developer and has no reason to lie.");
        $('#rating-in-stars').val(5);
        $('#create-claim-review').trigger('click');
    });

    $('#submit_claim').on('click', function (event) {
        // setup for this submit.
        event.preventDefault();
        event.stopPropagation();
        $('#claimreview_text').val("");
        $('#claimreview_text').addClass('hide').removeClass('show');
        $("#cr-valid").removeClass("show").addClass("hide");
        $("#cr-invalid").removeClass("show").addClass("hide");
        var thetweet = $('#tweet_url').val();
        var today = new Date();
        var today_iso = today.toISOString().slice(0, 10);
        var rating_int = $('#rating-in-stars').val();
        var rating_alt = "";
        var claim_reviewed = $('#claim_reviewed').val();
        var review_body = $('#review_body').val();
        var form = document.getElementById("needs-validation");
        if (rating_int == 0) {
            $('#invalid').html("Please rate the truthfulness of the Tweet");
            form.classList.add("was-validated");
        } else {
            if (!form.checkValidity()) {
                //event.preventDefault();
                //event.stopPropagation();
                form.classList.add("was-validated");
            } else {
                form.classList.add("was-validated");
                switch (rating_int) {
                    case '1':
                        rating_alt = "Flat out lie";
                        break;
                    case '2':
                        rating_alt = "Quicksand";
                        break;
                    case '3':
                        rating_alt = "Somewhat true";
                        break;
                    case '4':
                        rating_alt = "Mostly true";
                        break;
                    case '5':
                        rating_alt = "Rock solid truth";
                        break;
                    default:
                        rating_alt = "May or may not be true";
                }

                // if all is good: create claimreview and save.
                function schema(suffix) {
                    return $rdf.sym("http://schema.org/" + suffix);
                }
                function rdf(suffix) {
                    return $rdf.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#" + suffix);
                }
                var graph = $rdf.graph();

                var claimReview = $rdf.sym("http://review.local/");
                graph.add(claimReview, rdf("type"), schema("ClaimReview"));
                graph.add(claimReview, schema("claimedReviewed"), claim_reviewed);
                graph.add(claimReview, schema("reviewBody"), review_body);
                var itemReviewed = $rdf.sym(thetweet);
                graph.add(claimReview, schema("itemReviewed"), itemReviewed);
                graph.add(claimReview, schema("datePublished"), $rdf.literal(today_iso, schema("Date")));
                var reviewRating = $rdf.blankNode();
                graph.add(reviewRating, rdf("type"), schema("Rating"));
                graph.add(reviewRating, schema("ratingValue"), rating_int);
                graph.add(reviewRating, schema("alternateName"), rating_alt);
                graph.add(claimReview, schema("reviewRating"), reviewRating);
                graph.add(claimReview, schema("url"), claimReview);
                var data = new $rdf.Serializer(graph, $rdf.sym("https://twitter.com/")).setBase("http://review.local/").toN3(graph);
                $('#claimreview_text').val(data);
                $('#claimreview_text').addClass('show').removeClass('hide');
                if (($('#claimreview_filename').length > 0) && ($('#claimreview_filename').val().length > 0)) {
                    var slug = $('#claimreview_filename').val();
                } else {
                    var slug = default_timestamp();
                }
                SolidUtils.getStorageRootContainer().then(function (root) {
                    return SolidUtils.createPath(root.value + "public", "twee-fi").then(
                            function (defaultContainer) {
                                return SolidAuthClient.fetch(defaultContainer, {
                                    'method': 'POST',
                                    'data': data,
                                    'headers': {
                                        'slug': slug
                                    }
                                }).then(function (meta) {
                                    console.log("Success! Sent payload to designated LDP-URI!");
                                    $("#cr-valid").removeClass("hide").addClass("show");
                                    $("#cr-invalid").removeClass("show").addClass("hide");
                                }).catch(function (err) {
                                    // do something with the error
                                    console.log(err);
                                    $('#cr_error_msg').text(err);
                                    $("#cr-invalid").addClass("show").removeClass("hide");
                                    $("#cr-valid").removeClass("show").addClass("hide");
                                });
                            });
                });
            }
        }
    });

    // Display a particular ClaimReview

    // list contents of the LDP
    $('#list-ldp').on('click', function (event) {
        var defaultContainer = $('#ldp-uri').val();
        if (defaultContainer.length == 0) {
            alert("You need to set the value of LDP-URI on the Select LDP-URI tab first.");
            return;
        }
        $('#spinner').addClass('show').removeClass('hide');
        $('#content_listing').empty();
        var start_row = "
";
        var end_row = "	<button class='btn-listing-show btn btn-sm btn-info mr-2'>show</button><button class='btn-listing-delete btn btn-sm btn-danger mr-2'>delete</button>"
        var container = solid.web.get(defaultContainer)
                .then(function (container) {
                    for (i = 0; i < container.contentsUris.length; i++) {
                        var new_row = start_row + container.contentsUris[i] + end_row;
                        $('#content_listing').append(new_row);
                    }
                    $('#spinner').addClass('hide').removeClass('show');

                    $('.btn-listing-show').on('click', function (event) {
                        // prep
                        $('#claim_review_listing_heading').text("");
                        $('#claim_review_listing').text("");
                        var targ = $(this).parent().parent().children('td:eq(0)');
                        var targ_text = targ.text();
                        solid.web.get(targ_text)
                                .then(function (response) {
                                    if (response.isContainer()) {
                                        // ignore...
                                    } else {
                                        // Regular resource
                                        // console.log('Raw resource: %s', response.raw())
                                        the_response = response.raw()
                                        // You can access the parsed graph (parsed by RDFLib.js):
                                        // var parsedGraph = response.parsedGraph()
                                        $('#claim_review_listing_heading').text(targ_text);
                                        $('#claim_review_listing').text(the_response);
                                        $('#show_claim_review').modal('show');
                                    }
                                })
                                .catch(function (err) {
                                    console.log(err) // error object
                                })
                    });
                    $('.btn-listing-delete').on('click', function (event) {
                        var targ = $(this).parent().parent().children('td:eq(0)');
                        var targ_text = targ.text();
                        console.log(targ_text);
                        if (window.confirm("Delete ClaimReview?")) {
                            solid.web.del(targ_text)
                                    .then(function (response) {
                                        console.log(response);
                                        targ.parent().remove();
                                    }).catch(function (err) {
                                console.log(err); // error object
                            });
                        }
                        ;
                    });
                });
    });

});<commit_msg>file reviews in tweet specific LDPC<commit_after>/*global $rdf, SolidAuthClient, SolidUtils*/

var solid = require('solid');

function createTest() {
    SolidUtils.getStorageRootContainer().then(function (root) {
        return SolidUtils.createPath(root.value + "public", "z/aa1/bb1/cc1/dd1");
    }).then(function (result) {
        alert(result);
    });
}

function updateLoginInfo() {
    SolidAuthClient.currentSession().then(function (session) {
        var user = $rdf.sym(session.webId);
        SolidUtils.rdfFetch(session.webId).then(function (response) {
            var name = response.graph.any(user, vocab.foaf('name'));
            $("#loginInfo").html("Logged in as:");
            $("#loginName").html("" + name + "");
        });
    });
}

$(function () {
    SolidAuthClient.currentSession().then(function (session) {
        if (session === null) {
            SolidUtils.login().then(function () {
                updateLoginInfo();
            });
        } else {
            updateLoginInfo();
        }
    });
});

var vocab = {
    schema: function (suffix) {
        return $rdf.sym("http://schema.org/" + suffix);
    },
    rdf: function (suffix) {
        return $rdf.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#" + suffix);
    },
    solid: function (suffix) {
        return $rdf.sym("http://www.w3.org/ns/solid/terms#" + suffix);
    },
    space: function (suffix) {
        return $rdf.sym("http://www.w3.org/ns/pim/space#" + suffix);
    },
    foaf: function (suffix) {
        return $rdf.sym("http://xmlns.com/foaf/0.1/" + suffix);
    }
};

$(function () {

    function default_timestamp() {
        var momentNow = moment();
        return "FactsMission--" + momentNow.format('YYYY-MM-DD') + '-'
                + momentNow.format('dddd').substring(0, 3).toUpperCase() + "-" + momentNow.format('Ahhmmss');
    }

    $('#default_timestamp').html(default_timestamp());
    $('[data-toggle="tooltip"]').tooltip();
    $('#tweet_url').on('change keyup paste', function () {
        $("#tweet-valid").removeClass("show").addClass("hide");
        $("#tweet-invalid").removeClass("show").addClass("hide");
        CheckData();
    });
    $('#claim_reviewed, #ldp-uri, #review_body').on('change keyup paste', function () {
        CheckData();
    });
    $('#rating-in-stars').on('change', function () {
        CheckData();
    });

    class TweetUri {
        constructor(value) {
            // Regex-pattern to check URLs against:
            // https://twitter.com/<twitteruser>/status/<long number>
            var urlRegex = /^https:\/\/twitter.com\/([a-zA-Z _.,!"'/$]+)\/status\/([0-9]*$)/;
            this.match = urlRegex.exec(value);
        }

        isValid() {
            return this.match != null;
        }

        getUser() {
            return this.match[1];
        }

        getStatus() {
            return this.match[2];
        }
    }

    $('#check_tweet').on('click', function () {
        // Regex-pattern to check URLs against:
        // https://twitter.com/<twitteruser>/status/<long number>
        var urlRegex = /^https:\/\/twitter.com\/[a-zA-Z _.,!"'/$]+\/status\/[0-9]*$/;
        var tweet_url = $('#tweet_url').val();
        if (check_tweet(tweet_url)) {
            $("#tweet-valid").removeClass("hide").addClass("show");
        } else {
            $("#tweet-invalid").removeClass("hide").addClass("show");
        }
    });

    function CheckData() {
        const LDP_neg_msg = "Missing LDP-URI.";
        const Tweet_url_neg_msg = "Missing Valid Tweet URL.";
        const Claim_neg_msg = "Missing Claim made in Tweet.";
        const Review_body_neg_msg = "Missing the body of your Review.";
        const Rating_neg_msg = "Missing Rating.";
        const LDP_msg = "LDP-URI appears valid";
        const Tweet_url_msg = "Tweet URL appears valid";
        const Claim_msg = "Claim in Tweet described.";
        const Rating_msg = "Claim Rated.";
        const Review_body_msg = "Review of Tweet described.";
        if ($('#ldp-uri').val() == false) {
            $('#valcheck_1_msg').text(LDP_neg_msg);
            $('#valcheck_1_ck').prop('checked', false);
        } else {
            $('#valcheck_1_msg').text(LDP_msg);
            $('#valcheck_1_ck').prop('checked', true);
        }
        if (!(new TweetUri($('#tweet_url').val())).isValid()) {
            $('#valcheck_2_msg').text(Tweet_url_neg_msg);
            $('#valcheck_2_ck').prop('checked', false);
        } else {
            $('#valcheck_2_msg').text(Tweet_url_msg);
            $('#valcheck_2_ck').prop('checked', true);
        }
        if ($('#claim_reviewed').val() == false) {
            $('#valcheck_3_msg').text(Review_body_neg_msg);
            $('#valcheck_3_ck').prop('checked', false);
        } else {
            $('#valcheck_3_msg').text(Review_body_msg);
            $('#valcheck_3_ck').prop('checked', true);
        }
        if ($('#review_body').val() == false) {
            $('#valcheck_4_msg').text(Claim_neg_msg);
            $('#valcheck_4_ck').prop('checked', false);
        } else {
            $('#valcheck_4_msg').text(Claim_msg);
            $('#valcheck_4_ck').prop('checked', true);
        }
        if ($('#rating-in-stars').val() == 0) {
            $('#valcheck_5_msg').text(Rating_neg_msg);
            $('#valcheck_5_ck').prop('checked', false);
        } else {
            $('#valcheck_5_msg').text(Rating_msg);
            $('#valcheck_5_ck').prop('checked', true);
        }
    }
    ;

    $('#pop_claim').on('click', function (event) {
        event.preventDefault();
        event.stopPropagation();
        $('#ldp-uri').val("https://farewellutopia.com:8443/");
        $('#tweet_url').val("https://twitter.com/wesbos/status/912736261630251008");
        $('#claim_reviewed').val("That Facebook has decided to relicense React & Friends to MIT.");
        $('#review_body').val("Wes Bos is a reliable developer and has no reason to lie.");
        $('#rating-in-stars').val(5);
        $('#create-claim-review').trigger('click');
    });

    $('#submit_claim').on('click', function (event) {
        // setup for this submit.
        event.preventDefault();
        event.stopPropagation();
        $('#claimreview_text').val("");
        $('#claimreview_text').addClass('hide').removeClass('show');
        $("#cr-valid").removeClass("show").addClass("hide");
        $("#cr-invalid").removeClass("show").addClass("hide");
        var tweetURI = $('#tweet_url').val();
        var today = new Date();
        var today_iso = today.toISOString().slice(0, 10);
        var rating_int = $('#rating-in-stars').val();
        var rating_alt = "";
        var claim_reviewed = $('#claim_reviewed').val();
        var review_body = $('#review_body').val();
        var form = document.getElementById("needs-validation");
        if (rating_int == 0) {
            $('#invalid').html("Please rate the truthfulness of the Tweet");
            form.classList.add("was-validated");
        } else {
            if (!form.checkValidity()) {
                //event.preventDefault();
                //event.stopPropagation();
                form.classList.add("was-validated");
            } else {
                form.classList.add("was-validated");
                switch (rating_int) {
                    case '1':
                        rating_alt = "Flat out lie";
                        break;
                    case '2':
                        rating_alt = "Quicksand";
                        break;
                    case '3':
                        rating_alt = "Somewhat true";
                        break;
                    case '4':
                        rating_alt = "Mostly true";
                        break;
                    case '5':
                        rating_alt = "Rock solid truth";
                        break;
                    default:
                        rating_alt = "May or may not be true";
                }

                // if all is good: create claimreview and save.
                function schema(suffix) {
                    return $rdf.sym("http://schema.org/" + suffix);
                }
                function rdf(suffix) {
                    return $rdf.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#" + suffix);
                }
                var graph = $rdf.graph();

                var claimReview = $rdf.sym("http://review.local/");
                graph.add(claimReview, rdf("type"), schema("ClaimReview"));
                graph.add(claimReview, schema("claimedReviewed"), claim_reviewed);
                graph.add(claimReview, schema("reviewBody"), review_body);
                var itemReviewed = $rdf.sym(tweetURI);
                graph.add(claimReview, schema("itemReviewed"), itemReviewed);
                graph.add(claimReview, schema("datePublished"), $rdf.literal(today_iso, schema("Date")));
                var reviewRating = $rdf.blankNode();
                graph.add(reviewRating, rdf("type"), schema("Rating"));
                graph.add(reviewRating, schema("ratingValue"), rating_int);
                graph.add(reviewRating, schema("alternateName"), rating_alt);
                graph.add(claimReview, schema("reviewRating"), reviewRating);
                graph.add(claimReview, schema("url"), claimReview);
                var data = new $rdf.Serializer(graph, $rdf.sym("https://twitter.com/")).setBase("http://review.local/").toN3(graph);
                $('#claimreview_text').val(data);
                $('#claimreview_text').addClass('show').removeClass('hide');
                if (($('#claimreview_filename').length > 0) && ($('#claimreview_filename').val().length > 0)) {
                    var slug = $('#claimreview_filename').val();
                } else {
                    var slug = default_timestamp();
                }
                var tweetUri = new TweetUri(tweetURI);
                SolidUtils.getStorageRootContainer().then(function (root) {
                    return SolidUtils.createPath(root.value + "public", "twee-fi/"+tweetUri.getUser()+"/"+tweetUri.getStatus()).then(
                            function (defaultContainer) {
                                return SolidAuthClient.fetch(defaultContainer, {
                                    'method': 'POST',
                                    'body': data,
                                    'headers': {
                                        'Content-Type': 'text/turtle',
                                        'slug': slug
                                    }
                                }).then(function (meta) {
                                    console.log("Success! Sent payload to designated LDP-URI!");
                                    $("#cr-valid").removeClass("hide").addClass("show");
                                    $("#cr-invalid").removeClass("show").addClass("hide");
                                }).catch(function (err) {
                                    // do something with the error
                                    console.log(err);
                                    $('#cr_error_msg').text(err);
                                    $("#cr-invalid").addClass("show").removeClass("hide");
                                    $("#cr-valid").removeClass("show").addClass("hide");
                                });
                            });
                });
            }
        }
    });

    // Display a particular ClaimReview

    // list contents of the LDP
    $('#list-ldp').on('click', function (event) {
        var defaultContainer = $('#ldp-uri').val();
        if (defaultContainer.length == 0) {
            alert("You need to set the value of LDP-URI on the Select LDP-URI tab first.");
            return;
        }
        $('#spinner').addClass('show').removeClass('hide');
        $('#content_listing').empty();
        var start_row = "
";
        var end_row = "	<button class='btn-listing-show btn btn-sm btn-info mr-2'>show</button><button class='btn-listing-delete btn btn-sm btn-danger mr-2'>delete</button>"
        var container = solid.web.get(defaultContainer)
                .then(function (container) {
                    for (i = 0; i < container.contentsUris.length; i++) {
                        var new_row = start_row + container.contentsUris[i] + end_row;
                        $('#content_listing').append(new_row);
                    }
                    $('#spinner').addClass('hide').removeClass('show');

                    $('.btn-listing-show').on('click', function (event) {
                        // prep
                        $('#claim_review_listing_heading').text("");
                        $('#claim_review_listing').text("");
                        var targ = $(this).parent().parent().children('td:eq(0)');
                        var targ_text = targ.text();
                        solid.web.get(targ_text)
                                .then(function (response) {
                                    if (response.isContainer()) {
                                        // ignore...
                                    } else {
                                        // Regular resource
                                        // console.log('Raw resource: %s', response.raw())
                                        the_response = response.raw()
                                        // You can access the parsed graph (parsed by RDFLib.js):
                                        // var parsedGraph = response.parsedGraph()
                                        $('#claim_review_listing_heading').text(targ_text);
                                        $('#claim_review_listing').text(the_response);
                                        $('#show_claim_review').modal('show');
                                    }
                                })
                                .catch(function (err) {
                                    console.log(err) // error object
                                })
                    });
                    $('.btn-listing-delete').on('click', function (event) {
                        var targ = $(this).parent().parent().children('td:eq(0)');
                        var targ_text = targ.text();
                        console.log(targ_text);
                        if (window.confirm("Delete ClaimReview?")) {
                            solid.web.del(targ_text)
                                    .then(function (response) {
                                        console.log(response);
                                        targ.parent().remove();
                                    }).catch(function (err) {
                                console.log(err); // error object
                            });
                        }
                        ;
                    });
                });
    });

});<|endoftext|>


<commit_before>var profilerGrid = {

	init: function(args) {

		//INIT GLOBALS
		this.initGlobals();

		this.$detail.hide();
		this.$prevbtn.hide();

		this.loadData(1, args.googleKey);
	},

	initGlobals: function() {

		//GLOBALS
		this.current = 0;
		this.totalEntries = [];
		this.allData = [];
		this.ds = [];

		//JQUERY CACHING
		this.$detail = $("#detail");
		this.$prevbtn = $("#prevbtn");
		this.$nextbtn = $("#nextbtn");

	},

	loadData: function(which, key) {
		var that = this;

		//LOAD DATA WITH MISO
		//SAMPLE SPREADSHEET
		//https://docs.google.com/spreadsheet/pub?key=0AurS2EUbrPERdE9Nc1dMSGdfenFCN0FCTk9jZF9TVWc&output=html
		that.ds = new Miso.Dataset({
	  		importer : Miso.Dataset.Importers.GoogleSpreadsheet,
	  		parser : Miso.Dataset.Parsers.GoogleSpreadsheet,
	  		key : key,
	  		worksheet : which
		});

		that.ds.fetch({
		  success : function() {
		    that.populateGrid();
		  },
		  error : function() {
		  	console.error("ERROR: Failed to load Google Spreadsheet");
		  }
		});

	},

	showDetail: function(which) {

		this.current = which;

		this.$detail.show();
		this.$detail.animate({ opacity: '1' }, 500);

		var context = {
			name: this.allData[which][0].name,
			photo: this.allData[which][0].photourl,
			blurb: this.allData[which][0].blurb,
			url: this.allData[which][0].url,
			data1: this.allData[which][0].data1,
			data2: this.allData[which][0].data2,
			data3: this.allData[which][0].data3
		}

		this.$detail.html(Handlebars.templates['display-template'](context));

		this.checkNav();

		//CLOSE BUTTON
		$("#closebtn").click(function() {
			this.$detail.hide();
			this.$detail.animate({ opacity: '0' }, 500);
			$("#detail #vid").empty();
		});

	},

	nextPerson: function() {
		this.current ++;
		this.showDetail(this.current);
	},

	prevPerson: function() {
		this.current --;
		this.showDetail(this.current);
	},

	checkNav: function() {

		if (this.current == 0) {
			//this.$prevbtn.hide();
			$("#prevbtn").hide();
		} else {
			//this.$prevbtn.show();
			$("#prevbtn").show();
		}

		if (this.current == this.totalEntries - 1) {
			//this.$nextbtn.hide();
			$("#nextbtn").hide();
		} else {
			//this.$nextbtn.show();
			$("#nextbtn").show();
		}
	},

	populateGrid: function() {

		var $len = this.ds.column("name").data.length;
		this.totalEntries = $len;

		//LOOP THRU GOOGLE DATA AND PUT INTO OBJECT
		for (var j=0; j<$len; j++) {
			var counter = this.ds.column("id").data[j];
			this.allData[counter] = [ {
				myid: this.ds.column("id").data[j],
				name: this.ds.column("name").data[j],
				url: this.ds.column("url").data[j],
				data1: this.ds.column("data1").data[j],
				data2: this.ds.column("data2").data[j],
				data3: this.ds.column("data3").data[j],
				blurb: this.ds.column("blurb").data[j],
				photourl: this.ds.column("image").data[j]
		    }];
		}

		for (var i = 0; i<this.totalEntries; i++) {

			var context = {
				id: i,
				name: this.allData[i][0].name,
				photo: this.allData[i][0].photourl
			}

			$("#container").append(Handlebars.templates['th-template'](context));
		}

	}

}
<commit_msg>close button reference to this has been fixed<commit_after>var profilerGrid = {

	init: function(args) {

		//INIT GLOBALS
		this.initGlobals();

		this.$detail.hide();
		this.$prevbtn.hide();

		this.loadData(1, args.googleKey);
	},

	initGlobals: function() {

		//GLOBALS
		this.current = 0;
		this.totalEntries = [];
		this.allData = [];
		this.ds = [];

		//JQUERY CACHING
		this.$detail = $("#detail");
		this.$prevbtn = $("#prevbtn");
		this.$nextbtn = $("#nextbtn");

	},

	loadData: function(which, key) {
		var that = this;

		//LOAD DATA WITH MISO
		//SAMPLE SPREADSHEET
		//https://docs.google.com/spreadsheet/pub?key=0AurS2EUbrPERdE9Nc1dMSGdfenFCN0FCTk9jZF9TVWc&output=html
		that.ds = new Miso.Dataset({
	  		importer : Miso.Dataset.Importers.GoogleSpreadsheet,
	  		parser : Miso.Dataset.Parsers.GoogleSpreadsheet,
	  		key : key,
	  		worksheet : which
		});

		that.ds.fetch({
		  success : function() {
		    that.populateGrid();
		  },
		  error : function() {
		  	console.error("ERROR: Failed to load Google Spreadsheet");
		  }
		});

	},

	showDetail: function(which) {
		var that = this;
		this.current = which;

		this.$detail.show();
		this.$detail.animate({ opacity: '1' }, 500);

		var context = {
			name: this.allData[which][0].name,
			photo: this.allData[which][0].photourl,
			blurb: this.allData[which][0].blurb,
			url: this.allData[which][0].url,
			data1: this.allData[which][0].data1,
			data2: this.allData[which][0].data2,
			data3: this.allData[which][0].data3
		}

		this.$detail.html(Handlebars.templates['display-template'](context));

		this.checkNav();

		//CLOSE BUTTON
		$("#closebtn").click(function() {
			that.$detail.hide();
			that.$detail.animate({ opacity: '0' }, 500);
			$("#detail #vid").empty();
		});

	},

	nextPerson: function() {
		this.current ++;
		this.showDetail(this.current);
	},

	prevPerson: function() {
		this.current --;
		this.showDetail(this.current);
	},

	checkNav: function() {

		if (this.current == 0) {
			//this.$prevbtn.hide();
			$("#prevbtn").hide();
		} else {
			//this.$prevbtn.show();
			$("#prevbtn").show();
		}

		if (this.current == this.totalEntries - 1) {
			//this.$nextbtn.hide();
			$("#nextbtn").hide();
		} else {
			//this.$nextbtn.show();
			$("#nextbtn").show();
		}
	},

	populateGrid: function() {

		var $len = this.ds.column("name").data.length;
		this.totalEntries = $len;

		//LOOP THRU GOOGLE DATA AND PUT INTO OBJECT
		for (var j=0; j<$len; j++) {
			var counter = this.ds.column("id").data[j];
			this.allData[counter] = [ {
				myid: this.ds.column("id").data[j],
				name: this.ds.column("name").data[j],
				url: this.ds.column("url").data[j],
				data1: this.ds.column("data1").data[j],
				data2: this.ds.column("data2").data[j],
				data3: this.ds.column("data3").data[j],
				blurb: this.ds.column("blurb").data[j],
				photourl: this.ds.column("image").data[j]
		    }];
		}

		for (var i = 0; i<this.totalEntries; i++) {

			var context = {
				id: i,
				name: this.allData[i][0].name,
				photo: this.allData[i][0].photourl
			}

			$("#container").append(Handlebars.templates['th-template'](context));
		}

	}

}
<|endoftext|>


<commit_before>window.onload=updateTime;

function updateTime() {
    var hours_div = document.getElementById("hours");
    var minutes_div = document.getElementById("minutes");
    var now = new Date();
    hours_div.innerText = now.getHours();
    minutes_div.innerText = now.getMinutes();
}
window.setInterval(updateTime, 1000);
<commit_msg>time displaying as 01, 02, ... instead of 1,2,...<commit_after>window.onload=updateTime;

function updateTime() {
    var hours_div = document.getElementById("hours");
    var minutes_div = document.getElementById("minutes");

    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();

    if(hours < 10) {
      hours_div.innerText = '0' + hours;
    } else {
    }

    if(minutes < 10) {
      minutes_div.innerText = '0' + minutes;
    } else {
    }

}
window.setInterval(updateTime, 1000);
<|endoftext|>