<commit_before>/*
 * Formatter for Selenium 2 / WebDriver .NET (C#) client.
 */

var subScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
subScriptLoader.loadSubScript('chrome://selenium-ide/content/formats/webdriver.js', this);

function testClassName(testName) {
  return testName.split(/[^0-9A-Za-z]+/).map(
      function(x) {
        return capitalize(x);
      }).join('');
}

function testMethodName(testName) {
  return "The" + capitalize(testName) + "Test";
}

function nonBreakingSpace() {
  return "\"\\u00a0\"";
}

function array(value) {
  var str = 'new String[] {';
  for (var i = 0; i < value.length; i++) {
    str += string(value[i]);
    if (i < value.length - 1) str += ", ";
  }
  str += '}';
  return str;
}

Equals.prototype.toString = function() {
  return this.e1.toString() + " == " + this.e2.toString();
};

Equals.prototype.assert = function() {
  return "Assert.AreEqual(" + this.e1.toString() + ", " + this.e2.toString() + ");";
};

Equals.prototype.verify = function() {
  return verify(this.assert());
};

NotEquals.prototype.toString = function() {
  return this.e1.toString() + " != " + this.e2.toString();
};

NotEquals.prototype.assert = function() {
  return "Assert.AreNotEqual(" + this.e1.toString() + ", " + this.e2.toString() + ");";
};

NotEquals.prototype.verify = function() {
  return verify(this.assert());
};

function joinExpression(expression) {
  return "String.Join(\",\", " + expression.toString() + ")";
}

function statement(expression) {
  return expression.toString() + ';';
}

function assignToVariable(type, variable, expression) {
  return capitalize(type) + " " + variable + " = " + expression.toString();
}

function ifCondition(expression, callback) {
  return "if (" + expression.toString() + ")\n{\n" + callback() + "}";
}

function assertTrue(expression) {
  return "Assert.IsTrue(" + expression.toString() + ");";
}

function assertFalse(expression) {
  return "Assert.IsFalse(" + expression.toString() + ");";
}

function verify(statement) {
  return "try\n" +
      "{\n" +
      indents(1) + statement + "\n" +
      "}\n" +
      "catch (AssertionException e)\n" +
      "{\n" +
      indents(1) + "verificationErrors.Append(e.Message);\n" +
      "}";
}

function verifyTrue(expression) {
  return verify(assertTrue(expression));
}

function verifyFalse(expression) {
  return verify(assertFalse(expression));
}

RegexpMatch.patternToString = function(pattern) {
  if (pattern != null) {
    //value = value.replace(/^\s+/, '');
    //value = value.replace(/\s+$/, '');
    pattern = pattern.replace(/\\/g, '\\\\');
    pattern = pattern.replace(/\"/g, '\\"');
    pattern = pattern.replace(/\r/g, '\\r');
    pattern = pattern.replace(/\n/g, '(\\n|\\r\\n)');
    return '"' + pattern + '"';
  } else {
    return '""';
  }
};

RegexpMatch.prototype.toString = function() {
  return "Regex.IsMatch(" + this.expression + ", " + RegexpMatch.patternToString(this.pattern) + ")";
};

function waitFor(expression) {
  return "for (int second = 0;; second++) {\n" +
      indents(1) + 'if (second >= 60) Assert.Fail("timeout");\n' +
      indents(1) + "try\n" +
      indents(1) + "{\n" +
      (expression.setup ? indents(2) + expression.setup() + "\n" : "") +
      indents(2) + "if (" + expression.toString() + ") break;\n" +
      indents(1) + "}\n" +
      indents(1) + "catch (Exception)\n" +
      indents(1) + "{}\n" +
      indents(1) + "Thread.Sleep(1000);\n" +
      "}";
}

function assertOrVerifyFailure(line, isAssert) {
  var message = '"expected failure"';
  var failStatement = isAssert ? "Assert.Fail(" + message + ");" :
      "verificationErrors.Append(" + message + ");";
  return "try\n" +
      "{\n" +
      line + "\n" +
      failStatement + "\n" +
      "}\n" +
      "catch (Exception) {}\n";
}

function pause(milliseconds) {
  return "Thread.Sleep(" + parseInt(milliseconds, 10) + ");";
}

function echo(message) {
  return "Console.WriteLine(" + xlateArgument(message) + ");";
}

function formatComment(comment) {
  return comment.comment.replace(/.+/mg, function(str) {
    return "// " + str;
  });
}

function getDefaultExtension() {
  return this.options.defaultExtension;
}

this.options = {
  receiver: "driver",
  showSelenese: 'false',
  namespace: "SeleniumTests",
  indent: '4',
  initialIndents:  '3',
  header:
      'using System;\n' +
          'using System.Text;\n' +
          'using System.Text.RegularExpressions;\n' +
          'using System.Threading;\n' +
          'using NUnit.Framework;\n' +
          'using OpenQA.Selenium;\n' +
          'using OpenQA.Selenium.Firefox;\n' +
          'using OpenQA.Selenium.Support.UI;\n' +
          '\n' +
          'namespace ${namespace}\n' +
          '{\n' +
          '    [TestFixture]\n' +
          '    public class ${className}\n' +
          '    {\n' +
          '        private IWebDriver driver;\n' +
          '        private StringBuilder verificationErrors;\n' +
          '        private string baseURL;\n' +
          '        \n' +
          '        [SetUp]\n' +
          '        public void SetupTest()\n' +
          '        {\n' +
          '            ${receiver} = new FirefoxDriver();\n' +
          '            baseURL = "${baseURL}";\n' +
          '            verificationErrors = new StringBuilder();\n' +
          '        }\n' +
          '        \n' +
          '        [TearDown]\n' +
          '        public void TeardownTest()\n' +
          '        {\n' +
          '            try\n' +
          '            {\n' +
          '                ${receiver}.Quit();\n' +
          '            }\n' +
          '            catch (Exception)\n' +
          '            {\n' +
          '                // Ignore errors if unable to close the browser\n' +
          '            }\n' +
          '            Assert.AreEqual("", verificationErrors.ToString());\n' +
          '        }\n' +
          '        \n' +
          '        [Test]\n' +
          '        public void ${methodName}()\n' +
          '        {\n',
  footer:
      '        }\n' +
          "        private bool IsElementPresent(By by)\n" +
          "        {\n" +
          "            try\n" +
          "            {\n" +
          "                driver.FindElement(by);\n" +
          "                return true;\n" +
          "            }\n" +
          "            catch (NoSuchElementException)\n" +
          "            {\n" +
          "                return false;\n" +
          "            }\n" +
          "        }\n" +
          '    }\n' +
          '}\n',
  defaultExtension: "cs"
};
this.configForm = '<description>Variable for Selenium instance</description>' +
    '<textbox id="options_receiver" />' +
    '<description>Namespace</description>' +
    '<textbox id="options_namespace" />' +
    '<checkbox id="options_showSelenese" label="Show Selenese"/>';

this.name = "C# (WebDriver)";
this.testcaseExtension = ".cs";
this.suiteExtension = ".cs";
this.webdriver = true;

WDAPI.Driver = function() {
  this.ref = options.receiver;
};

WDAPI.Driver.searchContext = function(locatorType, locator) {
  var locatorString = xlateArgument(locator);
  switch (locatorType) {
    case 'xpath':
      return 'By.XPath(' + locatorString + ')';
    case 'css':
      return 'By.CssSelector(' + locatorString + ')';
    case 'id':
      return 'By.Id(' + locatorString + ')';
    case 'link':
      return 'By.LinkText(' + locatorString + ')';
    case 'name':
      return 'By.Name(' + locatorString + ')';
    case 'tag_name':
      return 'By.TagName(' + locatorString + ')';
  }
  throw 'Error: unknown strategy [' + locatorType + '] for locator [' + locator + ']';
};

WDAPI.Driver.prototype.back = function() {
  return this.ref + ".Navigate().Back()";
};

WDAPI.Driver.prototype.close = function() {
  return this.ref + ".Close()";
};

WDAPI.Driver.prototype.findElement = function(locatorType, locator) {
  return new WDAPI.Element(this.ref + ".FindElement(" + WDAPI.Driver.searchContext(locatorType, locator) + ")");
};

WDAPI.Driver.prototype.findElements = function(locatorType, locator) {
  return new WDAPI.ElementList(this.ref + ".FindElements(" + WDAPI.Driver.searchContext(locatorType, locator) + ")");
};

WDAPI.Driver.prototype.getCurrentUrl = function() {
  return this.ref + ".Url";
};

WDAPI.Driver.prototype.get = function(url) {
  if (url.length > 1 && (url.substring(1,8) == "http://" || url.substring(1,9) == "https://")) { // url is quoted
    return this.ref + ".Navigate().GoToUrl(" + url + ")";
  } else {
    return this.ref + ".Navigate().GoToUrl(baseURL + " + url + ")";
  }
};

WDAPI.Driver.prototype.getTitle = function() {
  return this.ref + ".Title";
};

WDAPI.Driver.prototype.refresh = function() {
  return this.ref + ".Navigate().Refresh()";
};

WDAPI.Element = function(ref) {
  this.ref = ref;
};

WDAPI.Element.prototype.clear = function() {
  return this.ref + ".Clear()";
};

WDAPI.Element.prototype.click = function() {
  return this.ref + ".Click()";
};

WDAPI.Element.prototype.getAttribute = function(attributeName) {
  return this.ref + ".GetAttribute(" + xlateArgument(attributeName) + ")";
};

WDAPI.Element.prototype.getText = function() {
  return this.ref + ".Text";
};

WDAPI.Element.prototype.isDisplayed = function() {
  return this.ref + ".Displayed";
};

WDAPI.Element.prototype.isSelected = function() {
  return this.ref + ".Selected";
};

WDAPI.Element.prototype.sendKeys = function(text) {
  return this.ref + ".SendKeys(" + xlateArgument(text) + ")";
};

WDAPI.Element.prototype.submit = function() {
  return this.ref + ".Submit()";
};

WDAPI.Element.prototype.select = function(label) {
  return "new SelectElement(" + this.ref + ").SelectByVisibleText(" + xlateArgument(label) + ")";
};

WDAPI.ElementList = function(ref) {
  this.ref = ref;
};

WDAPI.ElementList.prototype.getItem = function(index) {
  return this.ref + "[" + index + "]";
};

WDAPI.ElementList.prototype.getSize = function() {
  return this.ref + ".Count";
};

WDAPI.ElementList.prototype.isEmpty = function() {
  return this.ref + ".Count == 0";
};

WDAPI.Utils = function() {
};

WDAPI.Utils.isElementPresent = function(how, what) {
  return "IsElementPresent(" + WDAPI.Driver.searchContext(how, what) + ")";
};
<commit_msg>LukeIS: c# Select by visible text is actually SelectByText, correcting SeIDE exporter<commit_after>/*
 * Formatter for Selenium 2 / WebDriver .NET (C#) client.
 */

var subScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
subScriptLoader.loadSubScript('chrome://selenium-ide/content/formats/webdriver.js', this);

function testClassName(testName) {
  return testName.split(/[^0-9A-Za-z]+/).map(
      function(x) {
        return capitalize(x);
      }).join('');
}

function testMethodName(testName) {
  return "The" + capitalize(testName) + "Test";
}

function nonBreakingSpace() {
  return "\"\\u00a0\"";
}

function array(value) {
  var str = 'new String[] {';
  for (var i = 0; i < value.length; i++) {
    str += string(value[i]);
    if (i < value.length - 1) str += ", ";
  }
  str += '}';
  return str;
}

Equals.prototype.toString = function() {
  return this.e1.toString() + " == " + this.e2.toString();
};

Equals.prototype.assert = function() {
  return "Assert.AreEqual(" + this.e1.toString() + ", " + this.e2.toString() + ");";
};

Equals.prototype.verify = function() {
  return verify(this.assert());
};

NotEquals.prototype.toString = function() {
  return this.e1.toString() + " != " + this.e2.toString();
};

NotEquals.prototype.assert = function() {
  return "Assert.AreNotEqual(" + this.e1.toString() + ", " + this.e2.toString() + ");";
};

NotEquals.prototype.verify = function() {
  return verify(this.assert());
};

function joinExpression(expression) {
  return "String.Join(\",\", " + expression.toString() + ")";
}

function statement(expression) {
  return expression.toString() + ';';
}

function assignToVariable(type, variable, expression) {
  return capitalize(type) + " " + variable + " = " + expression.toString();
}

function ifCondition(expression, callback) {
  return "if (" + expression.toString() + ")\n{\n" + callback() + "}";
}

function assertTrue(expression) {
  return "Assert.IsTrue(" + expression.toString() + ");";
}

function assertFalse(expression) {
  return "Assert.IsFalse(" + expression.toString() + ");";
}

function verify(statement) {
  return "try\n" +
      "{\n" +
      indents(1) + statement + "\n" +
      "}\n" +
      "catch (AssertionException e)\n" +
      "{\n" +
      indents(1) + "verificationErrors.Append(e.Message);\n" +
      "}";
}

function verifyTrue(expression) {
  return verify(assertTrue(expression));
}

function verifyFalse(expression) {
  return verify(assertFalse(expression));
}

RegexpMatch.patternToString = function(pattern) {
  if (pattern != null) {
    //value = value.replace(/^\s+/, '');
    //value = value.replace(/\s+$/, '');
    pattern = pattern.replace(/\\/g, '\\\\');
    pattern = pattern.replace(/\"/g, '\\"');
    pattern = pattern.replace(/\r/g, '\\r');
    pattern = pattern.replace(/\n/g, '(\\n|\\r\\n)');
    return '"' + pattern + '"';
  } else {
    return '""';
  }
};

RegexpMatch.prototype.toString = function() {
  return "Regex.IsMatch(" + this.expression + ", " + RegexpMatch.patternToString(this.pattern) + ")";
};

function waitFor(expression) {
  return "for (int second = 0;; second++) {\n" +
      indents(1) + 'if (second >= 60) Assert.Fail("timeout");\n' +
      indents(1) + "try\n" +
      indents(1) + "{\n" +
      (expression.setup ? indents(2) + expression.setup() + "\n" : "") +
      indents(2) + "if (" + expression.toString() + ") break;\n" +
      indents(1) + "}\n" +
      indents(1) + "catch (Exception)\n" +
      indents(1) + "{}\n" +
      indents(1) + "Thread.Sleep(1000);\n" +
      "}";
}

function assertOrVerifyFailure(line, isAssert) {
  var message = '"expected failure"';
  var failStatement = isAssert ? "Assert.Fail(" + message + ");" :
      "verificationErrors.Append(" + message + ");";
  return "try\n" +
      "{\n" +
      line + "\n" +
      failStatement + "\n" +
      "}\n" +
      "catch (Exception) {}\n";
}

function pause(milliseconds) {
  return "Thread.Sleep(" + parseInt(milliseconds, 10) + ");";
}

function echo(message) {
  return "Console.WriteLine(" + xlateArgument(message) + ");";
}

function formatComment(comment) {
  return comment.comment.replace(/.+/mg, function(str) {
    return "// " + str;
  });
}

function getDefaultExtension() {
  return this.options.defaultExtension;
}

this.options = {
  receiver: "driver",
  showSelenese: 'false',
  namespace: "SeleniumTests",
  indent: '4',
  initialIndents:  '3',
  header:
      'using System;\n' +
          'using System.Text;\n' +
          'using System.Text.RegularExpressions;\n' +
          'using System.Threading;\n' +
          'using NUnit.Framework;\n' +
          'using OpenQA.Selenium;\n' +
          'using OpenQA.Selenium.Firefox;\n' +
          'using OpenQA.Selenium.Support.UI;\n' +
          '\n' +
          'namespace ${namespace}\n' +
          '{\n' +
          '    [TestFixture]\n' +
          '    public class ${className}\n' +
          '    {\n' +
          '        private IWebDriver driver;\n' +
          '        private StringBuilder verificationErrors;\n' +
          '        private string baseURL;\n' +
          '        \n' +
          '        [SetUp]\n' +
          '        public void SetupTest()\n' +
          '        {\n' +
          '            ${receiver} = new FirefoxDriver();\n' +
          '            baseURL = "${baseURL}";\n' +
          '            verificationErrors = new StringBuilder();\n' +
          '        }\n' +
          '        \n' +
          '        [TearDown]\n' +
          '        public void TeardownTest()\n' +
          '        {\n' +
          '            try\n' +
          '            {\n' +
          '                ${receiver}.Quit();\n' +
          '            }\n' +
          '            catch (Exception)\n' +
          '            {\n' +
          '                // Ignore errors if unable to close the browser\n' +
          '            }\n' +
          '            Assert.AreEqual("", verificationErrors.ToString());\n' +
          '        }\n' +
          '        \n' +
          '        [Test]\n' +
          '        public void ${methodName}()\n' +
          '        {\n',
  footer:
      '        }\n' +
          "        private bool IsElementPresent(By by)\n" +
          "        {\n" +
          "            try\n" +
          "            {\n" +
          "                driver.FindElement(by);\n" +
          "                return true;\n" +
          "            }\n" +
          "            catch (NoSuchElementException)\n" +
          "            {\n" +
          "                return false;\n" +
          "            }\n" +
          "        }\n" +
          '    }\n' +
          '}\n',
  defaultExtension: "cs"
};
this.configForm = '<description>Variable for Selenium instance</description>' +
    '<textbox id="options_receiver" />' +
    '<description>Namespace</description>' +
    '<textbox id="options_namespace" />' +
    '<checkbox id="options_showSelenese" label="Show Selenese"/>';

this.name = "C# (WebDriver)";
this.testcaseExtension = ".cs";
this.suiteExtension = ".cs";
this.webdriver = true;

WDAPI.Driver = function() {
  this.ref = options.receiver;
};

WDAPI.Driver.searchContext = function(locatorType, locator) {
  var locatorString = xlateArgument(locator);
  switch (locatorType) {
    case 'xpath':
      return 'By.XPath(' + locatorString + ')';
    case 'css':
      return 'By.CssSelector(' + locatorString + ')';
    case 'id':
      return 'By.Id(' + locatorString + ')';
    case 'link':
      return 'By.LinkText(' + locatorString + ')';
    case 'name':
      return 'By.Name(' + locatorString + ')';
    case 'tag_name':
      return 'By.TagName(' + locatorString + ')';
  }
  throw 'Error: unknown strategy [' + locatorType + '] for locator [' + locator + ']';
};

WDAPI.Driver.prototype.back = function() {
  return this.ref + ".Navigate().Back()";
};

WDAPI.Driver.prototype.close = function() {
  return this.ref + ".Close()";
};

WDAPI.Driver.prototype.findElement = function(locatorType, locator) {
  return new WDAPI.Element(this.ref + ".FindElement(" + WDAPI.Driver.searchContext(locatorType, locator) + ")");
};

WDAPI.Driver.prototype.findElements = function(locatorType, locator) {
  return new WDAPI.ElementList(this.ref + ".FindElements(" + WDAPI.Driver.searchContext(locatorType, locator) + ")");
};

WDAPI.Driver.prototype.getCurrentUrl = function() {
  return this.ref + ".Url";
};

WDAPI.Driver.prototype.get = function(url) {
  if (url.length > 1 && (url.substring(1,8) == "http://" || url.substring(1,9) == "https://")) { // url is quoted
    return this.ref + ".Navigate().GoToUrl(" + url + ")";
  } else {
    return this.ref + ".Navigate().GoToUrl(baseURL + " + url + ")";
  }
};

WDAPI.Driver.prototype.getTitle = function() {
  return this.ref + ".Title";
};

WDAPI.Driver.prototype.refresh = function() {
  return this.ref + ".Navigate().Refresh()";
};

WDAPI.Element = function(ref) {
  this.ref = ref;
};

WDAPI.Element.prototype.clear = function() {
  return this.ref + ".Clear()";
};

WDAPI.Element.prototype.click = function() {
  return this.ref + ".Click()";
};

WDAPI.Element.prototype.getAttribute = function(attributeName) {
  return this.ref + ".GetAttribute(" + xlateArgument(attributeName) + ")";
};

WDAPI.Element.prototype.getText = function() {
  return this.ref + ".Text";
};

WDAPI.Element.prototype.isDisplayed = function() {
  return this.ref + ".Displayed";
};

WDAPI.Element.prototype.isSelected = function() {
  return this.ref + ".Selected";
};

WDAPI.Element.prototype.sendKeys = function(text) {
  return this.ref + ".SendKeys(" + xlateArgument(text) + ")";
};

WDAPI.Element.prototype.submit = function() {
  return this.ref + ".Submit()";
};

WDAPI.Element.prototype.select = function(label) {
  return "new SelectElement(" + this.ref + ").SelectByText(" + xlateArgument(label) + ")";
};

WDAPI.ElementList = function(ref) {
  this.ref = ref;
};

WDAPI.ElementList.prototype.getItem = function(index) {
  return this.ref + "[" + index + "]";
};

WDAPI.ElementList.prototype.getSize = function() {
  return this.ref + ".Count";
};

WDAPI.ElementList.prototype.isEmpty = function() {
  return this.ref + ".Count == 0";
};

WDAPI.Utils = function() {
};

WDAPI.Utils.isElementPresent = function(how, what) {
  return "IsElementPresent(" + WDAPI.Driver.searchContext(how, what) + ")";
};
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name appApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the appApp
 */
angular.module('appApp')
    .controller('AnalyseCtrl', [
        '$scope',
        'dataService',
        '_',
        function ($scope, ds, _) {

            $scope.data = {
                x: [],
                y: [],
                limit: 50,
            }

            if (_.isNull(ds.datasets.languages) || _.isNull(ds.datasets.countries)) {
                ds.init().then(function() {
                    $scope.datasets = ds.datasets;
                    $scope.processData();
                    $scope.dataLoaded = true;
                });
            } else {
                $scope.datasets = ds.datasets;
                $scope.processData();
                $scope.dataLoaded = true;
            }

            $scope.processData = function() {
                $scope.byCount = _.groupBy(ds.datasets.languages, 'count');
                _.each($scope.byCount, function(value, key) {
                    $scope.data.x.push(key);
                    $scope.data.y.push(value.length);
                });

                $scope.data.xTotal = $scope.data.x.length;
            }
        }
    ]);
<commit_msg>layout stuff<commit_after>'use strict';

/**
 * @ngdoc function
 * @name appApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the appApp
 */
angular.module('appApp')
    .controller('AnalyseCtrl', [
        '$scope',
        'dataService',
        '_',
        function ($scope, ds, _) {

            $scope.data = {
                x: [],
                y: [],
                limit: 50,
            }

            $scope.processData = function() {
                $scope.byCount = _.groupBy(ds.datasets.languages, 'count');
                _.each($scope.byCount, function(value, key) {
                    $scope.data.x.push(key);
                    $scope.data.y.push(value.length);
                });

                $scope.data.xTotal = $scope.data.x.length;
            }

            if (_.isNull(ds.datasets.languages) || _.isNull(ds.datasets.countries)) {
                ds.init().then(function() {
                    $scope.datasets = ds.datasets;
                    $scope.processData();
                    $scope.dataLoaded = true;
                });
            } else {
                $scope.datasets = ds.datasets;
                $scope.processData();
                $scope.dataLoaded = true;
            }

        }
    ]);
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require ace/ace
//= require ace/mode-text
//= require ace/mode-html
//= require ace/mode-markdown
//= require ace/mode-textile
//= require_tree .

window.editor = ace.edit("editor");
var extension = $('#editor').data('file-ext');
var mode      = require("ace/mode/" + extension).Mode;

editor.getSession().setMode(new mode());
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);

$('form').submit(function() {
  $('#contents').val(editor.getValue());
});
<commit_msg>Twilight theme<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require ace/ace
//= require ace/mode-text
//= require ace/mode-html
//= require ace/mode-markdown
//= require ace/mode-textile
//= require_tree .

window.editor = ace.edit("editor");
var extension = $('#editor').data('file-ext');
var mode      = require("ace/mode/" + extension).Mode;

editor.setTheme("ace/theme/twilight");
editor.getSession().setMode(new mode());
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);

$('form').submit(function() {
  $('#contents').val(editor.getValue());
});
<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap-sprockets

$(document).ready(function(){

	$('.contact-artist').click(function (e) {
		e.preventDefault();
		var at = '@'
		var ending = ".com"
		var dom = "markeinert"
		var user = 'hello';

		var subject = "Contact from website";
		document.location.href = "mailto:"+ user +  at + dom + ending + "?subject="+subject;
	});
})
<commit_msg>Add JQuery to collapse open menu when click off the menu<commit_after>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap-sprockets

$(document).ready(function(){

	$('.contact-artist').click(function (e) {
		console.log(e)
		// debugger
		e.preventDefault();
		var at = '@'
		var ending = ".com"
		var dom = "markeinert"
		var user = 'hello';

		var subject = "Contact from website";
		document.location.href = "mailto:"+ user +  at + dom + ending + "?subject="+subject;
	});

	$(document).on('click',function(e){
    $('.collapse').collapse('hide');
})

})
<|endoftext|>


<commit_before>// typed.js
$(function(){
    $(".job-title").typed({
      stringsElement: $('#typed-strings'),
      contentType: 'type',
      typeSpeed: 50,
      startDelay: 500,
      backDelay: 1000
    });
});

// Default application.js

function ShowHideContent() {
  var self = this;

  self.escapeElementName = function(str) {
    result = str.replace('[', '\\[').replace(']', '\\]')
    return(result);
  };

  self.showHideRadioToggledContent = function () {
    $(".block-label input[type='radio']").each(function () {

      var $radio = $(this);
      var $radioGroupName = $radio.attr('name');
      var $radioLabel = $radio.parent('label');

      var dataTarget = $radioLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (dataTarget) {

        // Set aria-controls
        $radio.attr('aria-controls', dataTarget);

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $radio.closest('form').find(".block-label input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () {
            var $this = $(this);

            var groupDataTarget = $this.parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.addClass('js-hidden');
            // Set aria-expanded and aria-hidden for hidden content
            $this.attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

          var $dataTarget = $('#' + dataTarget);
          $dataTarget.removeClass('js-hidden');
          // Set aria-expanded and aria-hidden for clicked radio
          $radio.attr('aria-expanded', 'true');
          $dataTarget.attr('aria-hidden', 'false');

        });

      } else {
        // If the data-target attribute is undefined for a radio button,
        // hide visible data-target content for radio buttons in the same group

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $(".block-label input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () {

            var groupDataTarget = $(this).parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.addClass('js-hidden');
            // Set aria-expanded and aria-hidden for hidden content
            $(this).attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

        });
      }

    });
  }
  self.showHideCheckboxToggledContent = function () {

    $(".block-label input[type='checkbox']").each(function() {

      var $checkbox = $(this);
      var $checkboxLabel = $(this).parent();

      var $dataTarget = $checkboxLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

        // Set aria-controls
        $checkbox.attr('aria-controls', $dataTarget);

        // Set aria-expanded and aria-hidden
        $checkbox.attr('aria-expanded', 'false');
        $('#'+$dataTarget).attr('aria-hidden', 'true');

        // For checkboxes revealing hidden content
        $checkbox.on('click', function() {

          var state = $(this).attr('aria-expanded') === 'false' ? true : false;

          // Toggle hidden content
          $('#'+$dataTarget).toggleClass('js-hidden');

          // Update aria-expanded and aria-hidden attributes
          $(this).attr('aria-expanded', state);
          $('#'+$dataTarget).attr('aria-hidden', !state);

        });
      }

    });
  }
}

$(document).ready(function() {

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Show and hide toggled content
  // Where .block-label uses the data-target attribute
  var toggleContent = new ShowHideContent();
  toggleContent.showHideRadioToggledContent();
  toggleContent.showHideCheckboxToggledContent();

});
<commit_msg>Stop typedjs function on scroll<commit_after>// typed.js
$(function(){
    $(".job-title").typed({
      stringsElement: $('#typed-strings'),
      contentType: 'type',
      typeSpeed: 50,
      startDelay: 500,
      backDelay: 1000
    });
});
// stop typed.js on scroll
function stopTyped() {
  var scrollTop = $(window).scrollTop(),
      $jobTitle = $('.job-title'),
      headerHeight = $('p.font-large').offset().top;

  if (scrollTop >= headerHeight) {
    $jobTitle.replaceWith('part of a team.');
  }
}
$(window).scroll(stopTyped);

// Default application.js

function ShowHideContent() {
  var self = this;

  self.escapeElementName = function(str) {
    result = str.replace('[', '\\[').replace(']', '\\]')
    return(result);
  };

  self.showHideRadioToggledContent = function () {
    $(".block-label input[type='radio']").each(function () {

      var $radio = $(this);
      var $radioGroupName = $radio.attr('name');
      var $radioLabel = $radio.parent('label');

      var dataTarget = $radioLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (dataTarget) {

        // Set aria-controls
        $radio.attr('aria-controls', dataTarget);

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $radio.closest('form').find(".block-label input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () {
            var $this = $(this);

            var groupDataTarget = $this.parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.addClass('js-hidden');
            // Set aria-expanded and aria-hidden for hidden content
            $this.attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

          var $dataTarget = $('#' + dataTarget);
          $dataTarget.removeClass('js-hidden');
          // Set aria-expanded and aria-hidden for clicked radio
          $radio.attr('aria-expanded', 'true');
          $dataTarget.attr('aria-hidden', 'false');

        });

      } else {
        // If the data-target attribute is undefined for a radio button,
        // hide visible data-target content for radio buttons in the same group

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $(".block-label input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () {

            var groupDataTarget = $(this).parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.addClass('js-hidden');
            // Set aria-expanded and aria-hidden for hidden content
            $(this).attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

        });
      }

    });
  }
  self.showHideCheckboxToggledContent = function () {

    $(".block-label input[type='checkbox']").each(function() {

      var $checkbox = $(this);
      var $checkboxLabel = $(this).parent();

      var $dataTarget = $checkboxLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

        // Set aria-controls
        $checkbox.attr('aria-controls', $dataTarget);

        // Set aria-expanded and aria-hidden
        $checkbox.attr('aria-expanded', 'false');
        $('#'+$dataTarget).attr('aria-hidden', 'true');

        // For checkboxes revealing hidden content
        $checkbox.on('click', function() {

          var state = $(this).attr('aria-expanded') === 'false' ? true : false;

          // Toggle hidden content
          $('#'+$dataTarget).toggleClass('js-hidden');

          // Update aria-expanded and aria-hidden attributes
          $(this).attr('aria-expanded', state);
          $('#'+$dataTarget).attr('aria-hidden', !state);

        });
      }

    });
  }
}

$(document).ready(function() {

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Show and hide toggled content
  // Where .block-label uses the data-target attribute
  var toggleContent = new ShowHideContent();
  toggleContent.showHideRadioToggledContent();
  toggleContent.showHideCheckboxToggledContent();

});
<|endoftext|>


<commit_before>$( document ).ready( function() {
  $('.sortable').sortable({
    stop: function() {
      reNumber();
    },
  });

  $('#add-new').click(function() {
    const newField = $('.hidden').find('.row.padded-field').clone(true).removeClass('hidden');
    newField.find('.grabbable-number input').attr('name', newName('number'));
    newField.find('.grabbable-number input').attr('id', newID('number'));
    newField.find('.grabbable-number input').val(newNumber());
    newField.appendTo('.container.sortable');
  });

  $('.remove').click(function() {
    const parentField = $(this).parents('.row.padded-field');
    parentField.remove();
    reNumber();
  });

  $('.data-type select').change(function() {
    toggleFields(this)
  });
}); // END of document.ready

function takesPlaceholder(value) {
  return ['date', 'date/time', 'long-text', 'text', 'time'].includes(value);
}
function reNumber() {
  $('.number input:visible').each(function(index) {
    $(this).attr('name', 'form_draft[fields_attributes][' + index + '][number]' );
    $(this).attr('id', 'form_draft_fields_attributes_' + index + '_number');
    $(this).val(index + 1);
  });
}
function newName(fieldType){
  return 'form_draft[fields_attributes][' + newIndex() + '][' + fieldType + ']';
}
function newNumber(){
  // the number of padded fields will the number of visible fields + 1,
  // which is what we want for the number of a new visible field.
  return $('.row.padded-field').length
}
function newID(fieldType){
  return 'form_draft_fields_attributes_' + newIndex() + '_' + fieldType
}
function newIndex(){
  return newNumber() - 1;
}
function toggleFields(dataField) {
  const dataType = dataField.value;
  const container = $(dataField).parents('.padded-field');
  if (takesPlaceholder(dataType) == true) {
    if (container.find('.placeholder').children().length == 0) {
      const newField = $('<input class="form-control" type="text" name="' + newName('placeholder') + '">')
      newField.appendTo(container.find('.placeholder'));
    }
  } else {
    container.find('.placeholder').children().remove();
  }
  if (dataType == 'options') {
    const newField = $('<textarea placeholder="add options separated by a comma" class="form-control" rows="4" name="' + newName('options') + '">');
    newField.appendTo(container.find('.options'));
  } else {
      container.find('.options').children().remove();
  }
  if (dataType == 'heading' || dataType == 'explanation') {
    container.find('.required').children().remove();
  } else {
    if (container.find('.required').children().length == 0) {
      const newField = $('<input type="checkbox" name="' + newName('required') + '">')
      newField.appendTo(container.find('.required'));
    }
  }
}
<commit_msg>give the newly cloned field all the correct attributes<commit_after>$( document ).ready( function() {
  $('.sortable').sortable({
    stop: function() {
      reNumber();
    },
  });

  $('#add-new').click(function() {
    const newField = $('.hidden').find('.row.padded-field').clone(true).removeClass('hidden');
    newField.find('.grabbable-number input').attr('name', newName('number'));
    newField.find('.grabbable-number input').attr('id', newID('number'));
    newField.find('.grabbable-number input').val(newNumber());
    newField.find('.prompt textarea').attr('name', newName('prompt'));
    newField.find('.prompt textarea').attr('id', newID('prompt'));
    newField.find('.required input').attr('name', newName('required'));
    newField.find('.required input').attr('id', newID('required'));
    newField.appendTo('.container.sortable');
  });

  $('.remove').click(function() {
    const parentField = $(this).parents('.row.padded-field');
    parentField.remove();
    reNumber();
  });

  $('.data-type select').change(function() {
    toggleFields(this)
  });
}); // END of document.ready

function takesPlaceholder(value) {
  return ['date', 'date/time', 'long-text', 'text', 'time'].includes(value);
}
function reNumber() {
  $('.number input:visible').each(function(index) {
    $(this).attr('name', 'form_draft[fields_attributes][' + index + '][number]' );
    $(this).attr('id', 'form_draft_fields_attributes_' + index + '_number');
    $(this).val(index + 1);
  });
}
function newName(fieldType){
  return 'form_draft[fields_attributes][' + newIndex() + '][' + fieldType + ']';
}
function newNumber(){
  // the number of padded fields will the number of visible fields + 1,
  // which is what we want for the number of a new visible field.
  return $('.row.padded-field').length
}
function newID(fieldType){
  return 'form_draft_fields_attributes_' + newIndex() + '_' + fieldType
}
function newIndex(){
  return newNumber() - 1;
}
function toggleFields(dataField) {
  const dataType = dataField.value;
  const container = $(dataField).parents('.padded-field');
  if (takesPlaceholder(dataType) == true) {
    if (container.find('.placeholder').children().length == 0) {
      const newField = $('<input class="form-control" type="text" name="' + newName('placeholder') + '">')
      newField.appendTo(container.find('.placeholder'));
    }
  } else {
    container.find('.placeholder').children().remove();
  }
  if (dataType == 'options') {
    const newField = $('<textarea placeholder="add options separated by a comma" class="form-control" rows="4" name="' + newName('options') + '">');
    newField.appendTo(container.find('.options'));
  } else {
      container.find('.options').children().remove();
  }
  if (dataType == 'heading' || dataType == 'explanation') {
    container.find('.required').children().remove();
  } else {
    if (container.find('.required').children().length == 0) {
      const newField = $('<input type="checkbox" name="' + newName('required') + '">')
      newField.appendTo(container.find('.required'));
    }
  }
}
<|endoftext|>


<commit_before>//= require angular
//= require angulardevise
//= require angular-rails-templates
//= require angular-ui-router
//= require angular-messages
//= require_tree .
<commit_msg>Update angulardevise to AngularDevise in application.js<commit_after>//= require angular
//= require AngularDevise
//= require angular-rails-templates
//= require angular-ui-router
//= require angular-messages
//= require_tree .
<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require bootstrap

<commit_msg>require turbolink<commit_after>//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks

<|endoftext|>


<commit_before>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(function() {
	$('#dialog_form').hide();
	$('#add_authorization_view').click(function() {
		$('#dialog_form').dialog( {
			width: 800,
			height: 200,
			modal: true,
			closeOnEscape: true,
			draggable: true,
			resizable: false,
			title: "Grant New Role",
			show: {
				effect: "blind",
				duration: 1000
			},
			hide: {
				effect: "toggle",
				duration: 1000
			},
			open: function()
			{
				$("#dialog_form").dialog("open");
			},
      close: function() {
        $('#dialog-form').dialog("close");
        $(this).find('form')[0].reset();
      }
		}).prev ().find (".ui-dialog-titlebar-close").show();
		return false
	});
});

$(function() {
	$("#cancel_action").bind("click",function() {
		$("#flash_notice").remove();
	});
});

$(function() {
	$(".tip").tooltip();
});

// //automatically checks Institutional reviewer role when Institutional Administrator role gets checked
$(function() {
	$('#5').change(function(){
		if ($('#5').is(':checked')) {
			$('#4').prop('checked', true);
		}
	});
});

// alert message if Institutional Admin remove his own Inst admin role
$(function() {
	$('#current_admin_with_alert').click(function(){
		if (!$('#5').is(':checked')) {
			if (confirm( "Do you really want to remove yourself from the Institutional Administrator role? You will lose all administrative permissions.")){
				return true;
 			} else {
				return false;
			};
		};
	});
});

$.extend({ alert: function (message, title) {
  $("

").dialog( {
    buttons: { "Ok": function () { $(this).dialog("close"); } },
    close: function (event, ui) { $(this).remove(); },
    resizable: false,
    title: title,
    modal: true
  }).text(message);
}
});

function validateFiles(inputFile) {
  var extErrorMessage = "Only image file with extension: .jpg, .jpeg, .gif or .png is allowed";
  var allowedExtension = ["jpg", "jpeg", "gif", "png"];
  var extName;
  var extError = false;

  $.each(inputFile.files, function() {
    extName = this.name.split('.').pop();
    if ($.inArray(extName, allowedExtension) == -1) {extError=true;};
  });

  if (extError) {
    // window.alert(extErrorMessage);
    $.alert(extErrorMessage, "Wrong File Extension");
    $(inputFile).val('');
  };
}

$(function(){
	$("#run_date").on('change', function(e){
		var run_date = $("#run_date option:selected")[0];

	console.log('run_date selected: ' + run_date.val());

		$.ajax({
			method: "GET",
			url: "institutions/usage_statistics?run_date=" + run_date.val()
		}).done(function(data){

	console.log(data);

			//$("#tab1").html(data);
		});
	});
});<commit_msg>fixed issue with usage stat run_date jquery<commit_after>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(function() {
	$('#dialog_form').hide();
	$('#add_authorization_view').click(function() {
		$('#dialog_form').dialog( {
			width: 800,
			height: 200,
			modal: true,
			closeOnEscape: true,
			draggable: true,
			resizable: false,
			title: "Grant New Role",
			show: {
				effect: "blind",
				duration: 1000
			},
			hide: {
				effect: "toggle",
				duration: 1000
			},
			open: function()
			{
				$("#dialog_form").dialog("open");
			},
      close: function() {
        $('#dialog-form').dialog("close");
        $(this).find('form')[0].reset();
      }
		}).prev ().find (".ui-dialog-titlebar-close").show();
		return false
	});
});

$(function() {
	$("#cancel_action").bind("click",function() {
		$("#flash_notice").remove();
	});
});

$(function() {
	$(".tip").tooltip();
});

// //automatically checks Institutional reviewer role when Institutional Administrator role gets checked
$(function() {
	$('#5').change(function(){
		if ($('#5').is(':checked')) {
			$('#4').prop('checked', true);
		}
	});
});

// alert message if Institutional Admin remove his own Inst admin role
$(function() {
	$('#current_admin_with_alert').click(function(){
		if (!$('#5').is(':checked')) {
			if (confirm( "Do you really want to remove yourself from the Institutional Administrator role? You will lose all administrative permissions.")){
				return true;
 			} else {
				return false;
			};
		};
	});
});

$.extend({ alert: function (message, title) {
  $("

").dialog( {
    buttons: { "Ok": function () { $(this).dialog("close"); } },
    close: function (event, ui) { $(this).remove(); },
    resizable: false,
    title: title,
    modal: true
  }).text(message);
}
});

function validateFiles(inputFile) {
  var extErrorMessage = "Only image file with extension: .jpg, .jpeg, .gif or .png is allowed";
  var allowedExtension = ["jpg", "jpeg", "gif", "png"];
  var extName;
  var extError = false;

  $.each(inputFile.files, function() {
    extName = this.name.split('.').pop();
    if ($.inArray(extName, allowedExtension) == -1) {extError=true;};
  });

  if (extError) {
    // window.alert(extErrorMessage);
    $.alert(extErrorMessage, "Wrong File Extension");
    $(inputFile).val('');
  };
}

$(function(){
	$("#run_date").on('change', function(e){
		var run_date = $("#run_date option:selected")[0];

	console.log('run_date selected: ' + run_date.text());

		$.ajax({
			method: "GET",
			url: "institutions/usage_statistics?run_date=" + run_date.text()
		}).done(function(data){

	console.log(data);

			//$("#tab1").html(data);
		});
	});
});<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery-fileupload/basicplus
//= require underscore
//= require scrollToFixed
//= require jQuery.dotdotdot/src/js/jquery.dotdotdot
//= require jquery-timeago/jquery.timeago
//= require typeahead.js/dist/typeahead.bundle
//= require spin.js/spin
//
//= require bootstrap-sass/dist/js/bootstrap
//= require bootstrap-datepicker/js/bootstrap-datepicker
//= require chosen-jquery
//
//= require handlebars
//= require ember
//= require ember-data
//= require utils
//= require_self
//= require e_tahi
//= require_tree .
//= require standard_tasks/application

(function(context) {
  context.ETahi = Ember.Application.create({
    rootElement: '#ember-app',

    // Ember
    LOG_STACKTRACE_ON_DEPRECATION  : true,
    LOG_BINDINGS                   : true,
    LOG_TRANSITIONS                : true,
    LOG_TRANSITIONS_INTERNAL       : false,
    LOG_VIEW_LOOKUPS               : false,
    LOG_ACTIVE_GENERATION          : false,
    // Tahi
    LOG_RSVP_ERRORS                : true,
    LOG_VIEW_RENDERING_PERFORMANCE : true
  });

  ETahi.ApplicationAdapter = DS.ActiveModelAdapter.extend({
    ajaxError: function(jqXHR) {
      var error = this._super(jqXHR);
      if (jqXHR && jqXHR.status === 401) {
        window.location.href = '/users/sign_in'
      }
      return error;
    }
  });

  ETahi.computed = {};
  ETahi.computed.all = function(hasMany, key, value){
    return Em.computed(hasMany+'.@each.'+key, function(){
      return this.get(hasMany).everyProperty(key, value);
    });
  };

  $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    if (jqXHR.status === 401) {
      document.location.href = '/users/sign_in';
    }
  });
})(window);

$.extend($.easing, {
  easeInCubic: function (x, t, b, c, d) {
    return c*(t/=d)*t*t + b;
  }
});
<commit_msg>Hopefully semaphore can find it now<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery-fileupload/basicplus
//= require underscore
//= require ScrollToFixed
//= require jQuery.dotdotdot/src/js/jquery.dotdotdot
//= require jquery-timeago/jquery.timeago
//= require typeahead.js/dist/typeahead.bundle
//= require spin.js/spin
//
//= require bootstrap-sass/dist/js/bootstrap
//= require bootstrap-datepicker/js/bootstrap-datepicker
//= require chosen-jquery
//
//= require handlebars
//= require ember
//= require ember-data
//= require utils
//= require_self
//= require e_tahi
//= require_tree .
//= require standard_tasks/application

(function(context) {
  context.ETahi = Ember.Application.create({
    rootElement: '#ember-app',

    // Ember
    LOG_STACKTRACE_ON_DEPRECATION  : true,
    LOG_BINDINGS                   : true,
    LOG_TRANSITIONS                : true,
    LOG_TRANSITIONS_INTERNAL       : false,
    LOG_VIEW_LOOKUPS               : false,
    LOG_ACTIVE_GENERATION          : false,
    // Tahi
    LOG_RSVP_ERRORS                : true,
    LOG_VIEW_RENDERING_PERFORMANCE : true
  });

  ETahi.ApplicationAdapter = DS.ActiveModelAdapter.extend({
    ajaxError: function(jqXHR) {
      var error = this._super(jqXHR);
      if (jqXHR && jqXHR.status === 401) {
        window.location.href = '/users/sign_in'
      }
      return error;
    }
  });

  ETahi.computed = {};
  ETahi.computed.all = function(hasMany, key, value){
    return Em.computed(hasMany+'.@each.'+key, function(){
      return this.get(hasMany).everyProperty(key, value);
    });
  };

  $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    if (jqXHR.status === 401) {
      document.location.href = '/users/sign_in';
    }
  });
})(window);

$.extend($.easing, {
  easeInCubic: function (x, t, b, c, d) {
    return c*(t/=d)*t*t + b;
  }
});
<|endoftext|>


<commit_before>function initiateMap () {
    map = GMaps({
        div: '#map',
        zoom: 15,
        lat: 57.7089,
        lng: 11.9746
    });
    performGeolocation();
};

function performGeolocation() {
    var latitude;
    var longitude;
    var testing_env = document.getElementById('map').dataset.testEnv;
    if (testing_env === 'false') {
        GMaps.geolocate({
            success: function (position) {
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
                map.setCenter(latitude, longitude);
                    map.addMarker({
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                    title: 'You are here',
                    infoWindow: {
                        content: '
You are here!
'
                    }
                });
            },
            error: function (error) {
                alert('Geolocation failed: ' + error.message);
            },
            not_supported: function () {
                alert('Your browser does not support geolocation');
            }
        });
        var restaurants = JSON.parse(document.getElementById('restaurants_addresses').dataset.addresses);
        restaurants.forEach(function(restaurant) {
            console.log(restaurant);
            map.addMarker({
                lat: restaurant.latitude,
                lng: restaurant.longitude,
                title: restaurant.name,
                infoWindow: {
                    content: '
This is a restaurant!
'
                }
            });
        });

    } else {
        latitude = 59.334591;
        longitude = 18.063240;
        map.setCenter(latitude, longitude);
        map.addMarker({
            lat: latitude,
            lng: longitude,
            title: 'You are here',
            infoWindow: {
                content: '
You are here!
'
            }
        });
        var restaurant = $("#restaurants_addresses").data("addresses");
        for (var i = 0; i < restaurant.length; i++){
            GMaps.geocode({
                address: restaurant.address,
                callback: function(results, status) {
                    if (status == 'OK') {
                        var latlng = results[0].geometry.location;
                        map.setCenter(latlng.lat(), latlng.lng());
                        map.addMarker({
                            lat: latlng.lat(),
                            lng: latlng.lng(),
                            title: restaurant.name,
                            infoWindow: {
                                content: '
This is a restaurant!
'
                            }
                        });
                    }
                }
            });
        }
    }

}<commit_msg>refactors test env part of js script<commit_after>function initiateMap() {
    map = GMaps({
        div: '#map',
        zoom: 15,
        lat: 57.7089,
        lng: 11.9746
    });
    performGeolocation();
};

function performGeolocation() {
    var latitude;
    var longitude;
    var testing_env = document.getElementById('map').dataset.testEnv;
    if (testing_env === 'false') {
        GMaps.geolocate({
            success: function (position) {
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
                map.setCenter(latitude, longitude);
                map.addMarker({
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                    title: 'You are here',
                    infoWindow: {
                        content: '
You are here!
'
                    }
                });
                displayRestaurantMarkers(map);
            },
            error: function (error) {
                alert('Geolocation failed: ' + error.message);
            },
            not_supported: function () {
                alert('Your browser does not support geolocation');
            }
        });

    } else {
        latitude = 59.334591;
        longitude = 18.063240;
        map.setCenter(latitude, longitude);
        map.addMarker({
            lat: latitude,
            lng: longitude,
            title: 'You are here',
            infoWindow: {
                content: '
You are here!
'
            }
        });
        displayRestaurantMarkers(map);
    }

}

function displayRestaurantMarkers(map) {
    var restaurants = JSON.parse(document.getElementById('restaurants_addresses').dataset.addresses);
    restaurants.forEach(function (restaurant) {
        console.log(restaurant);
        map.addMarker({
            lat: restaurant.latitude,
            lng: restaurant.longitude,
            title: restaurant.name,
            infoWindow: {
                content: '
This is a restaurant!
'
            }
        });
    });
}<|endoftext|>


<commit_before>

//= require jquery
//= require jquery_ujs
//= require app-js
//= require TweenMax-min
//= require MorphSVGPlugin-js
//= require sweetalert.min
//= require TextPlugin.min
//= require turbolinks

<commit_msg>testdot<commit_after>

//= require jquery
//= require jquery_ujs
//= require app.js
//= require TweenMax-min
//= require MorphSVGPlugin-js
//= require sweetalert.min
//= require TextPlugin.min
//= require turbolinks

<|endoftext|>


<commit_before>$(document).on('ready', function() {
  // on document load, add listener for click of any
  // child element in #text-overlay
  $("#text-overlay").children().on("click", function(el) {
    console.log(el.target);
  });

  var colorRange = ["#c3c3c3", "#8d8d8d",
  "#848484", "#6f6f6f", "#646464", "#545454"]

  var generateRandomNumber = function(min, max) {
    return Math.random() * (max - min) + min;
  };

  var rgb2hex = function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
  };

  var updateWordColors = function() {
    try {
      var idToTarget = "word-number-" + Math.round( generateRandomNumber(0, 900) );
      var currentTarget = document.getElementById( idToTarget );
      var currentTargetRgbColor = getComputedStyle( currentTarget, "").getPropertyValue('color');
      var currentColor = rgb2hex( currentTargetRgbColor );
      var currentColorIndex = colorRange.indexOf(currentColor);

      if (currentColorIndex == colorRange[colorRange.length] - 1) {
        currentTarget.style.color = colorRange[colorRange.length - 2];
      }

      else if (currentColorIndex == 0) {
        currentTarget.style.color = colorRange[1];
      }

      else {
        var randomVariable = generateRandomNumber(0, 1);
        // specify the probability the word will increase in color
        if (randomVariable > .0000001 ) {
          currentTarget.style.color = colorRange[currentColorIndex + 1];
        }
        else {
          currentTarget.style.color = colorRange[currentColorIndex - 1];
        }
      };

    } catch (TypeError) {}

    };

  // additionally, update the colors of words dynamically
  window.setInterval(function(){
    updateWordColors();
  }, 20);

});<commit_msg>update static_pages.js weights<commit_after>$(document).on('ready', function() {
  // on document load, add listener for click of any
  // child element in #text-overlay
  $("#text-overlay").children().on("click", function(el) {
    console.log(el.target);
  });

  var colorRange = ["#c3c3c3", "#8d8d8d",
  "#848484", "#6f6f6f", "#646464", "#545454"]

  var generateRandomNumber = function(min, max) {
    return Math.random() * (max - min) + min;
  };

  var rgb2hex = function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
  };

  var updateWordColors = function() {
    try {
      var idToTarget = "word-number-" + Math.round( generateRandomNumber(0, 900) );
      var currentTarget = document.getElementById( idToTarget );
      var currentTargetRgbColor = getComputedStyle( currentTarget, "").getPropertyValue('color');
      var currentColor = rgb2hex( currentTargetRgbColor );
      var currentColorIndex = colorRange.indexOf(currentColor);

      if (currentColorIndex == colorRange[colorRange.length] - 1) {
        currentTarget.style.color = colorRange[colorRange.length - 2];
      }

      else if (currentColorIndex == 0) {
        currentTarget.style.color = colorRange[1];
      }

      else {
        var randomVariable = generateRandomNumber(0, 1);
        // specify the probability the word will increase in color
        if (randomVariable > .01 ) {
          currentTarget.style.color = colorRange[currentColorIndex + 1];
        }
        else {
          currentTarget.style.color = colorRange[currentColorIndex - 1];
        }
      };

    } catch (TypeError) {}

    };

  // additionally, update the colors of words dynamically
  window.setInterval(function(){
    updateWordColors();
  }, 20);

});<|endoftext|>


<commit_before>const schema = require('./schema/index');

/**
 * Convert an array into a map
 * @param  {array[object]} object The array to convert.
 * @param  {string} keyField      The name of the field is stored in within each
 *                                object in the array.
 * @return {object}               The map converted from the array.
 */
function arrayToMap (object, keyField) {
  const newObject = {};
  if (object === undefined || object === null) {
    return newObject;
  }
  object.forEach((objFuncParam) => {
    const obj = objFuncParam;
    const key = obj[keyField];
    if (key === undefined) {
      return;
    }
    delete obj[keyField];
    newObject[key] = obj;
  });
  return newObject;
}

function isEmpty (object) {
  if (object === undefined || object === null) {
    return true;
  } else if (Array.isArray(object)) {
    if (object.length === 0) {
      return true;
    }
    let empty = true;
    object.forEach((child) => {
      if (!isEmpty(child)) {
        empty = false;
        return true;
      }
      return false;
    });
    return empty;
  } else if (typeof object === 'object') {
    let empty = true;
    Object.keys(object).forEach((key) => {
      if (!isEmpty(object[key])) {
        empty = false;
        return true;
      }
      return false;
    });
    return empty;
  } else if (typeof object === 'string') {
    return object.length === 0;
  }
  return false;
}

function deleteEmptyChildren (objectFuncParam) {
  const object = objectFuncParam;
  if (Array.isArray(object)) {
    object.forEach((child, index) => {
      if (isEmpty(child)) {
        object.pop(index);
      } else {
        object[index] = deleteEmptyChildren(child);
      }
    });
  } else if (typeof object === 'object') {
    Object.keys(object).forEach((key) => {
      if (isEmpty(object[key])) {
        delete object[key];
      } else {
        object[key] = deleteEmptyChildren(object[key]);
      }
    });
  }
  return object;
}

function propertyHardRefParser (object, propKey, props) {
  const properties = props;
  const property = properties[propKey];

  const targetExists = Object.hasOwnProperty.call(object.definitions, property.$ref);
  if (!targetExists) {
    return;
  }

  const target = object.definitions[property.$ref];
  if (property.hardReference || target.hardReferenceOnly) {
    properties[propKey] = target;
  } else {
    delete property.hardReference;
  }
}

/**
 * @param  {object} object The form value
 * @return {object}        A corrected version of the output. This should be a
 *                         valid Swagger spec.
 */
module.exports = function processJSON (objectFuncParam) {
  let object = JSON.parse(JSON.stringify(objectFuncParam));

  object = deleteEmptyChildren(object);

  // Hardcoded Swagger version
  object.swagger = '2.0';

  if (object.info) {
    if (object.info.host) {
      object.host = object.info.host;
      delete object.info.host;
    }
    if (object.info.basePath) {
      object.basePath = object.info.basePath;
      delete object.info.basePath;
    }
  }

  if (object.security && object.security.length > 0) {
    object.security = arrayToMap(object.security, 'key');

    /*
     * Put the `value` field of each security object as the actual value of the
     * object.
     */
    Object.keys(object.security).forEach((key) => {
      if (Object.hasOwnProperty.call(object.security[key], 'value')) {
        object.security[key] = object.security[key].value;
      } else {
        object.security[key] = [];
      }
    });
  } else {
    delete object.security;
  }

  // Definition keys that have set the Only hard refences to true will be stored
  // here and then deleted from the definitions object at the end of processing.
  const definitionsToDelete = [];

  if (object.definitions) {
    object.definitions = arrayToMap(object.definitions, 'key');

    Object.keys(object.definitions).forEach((key) => {
      const definition = object.definitions[key];

      // Push hard reference -only definitions to the definitionsToDelete array.
      if (definition.hardReferenceOnly) {
        definitionsToDelete.push(key);
      }
      delete definition.hardReferenceOnly;

      // schemaSchema is a schema to create and validate schemas, also known as
      // a meta-schema.
      // schema.definitions is the main schema for global object definitions and
      // object definitions are basically meta-schemas.
      const schemaSchema = schema.definitions.items;

      // If the value of a property is the same as the default value, delete the
      // whole field to avoid unnecessary fields in the output.
      Object.keys(schemaSchema.properties).forEach((schemaKey) => {
        const prop = schemaSchema.properties[schemaKey];
        if (Object.hasOwnProperty.call(definition, schemaKey)
            && Object.hasOwnProperty.call(prop, 'default')) {
          if (prop.default === definition[schemaKey]) {
            delete definition[schemaKey];
          }
        }
      });

      // Convert the properties field to a map and process references in the
      // properties.
      if (definition.properties) {
        definition.properties = arrayToMap(definition.properties, 'key');
        Object.keys(definition.properties).forEach(propKey =>
          propertyHardRefParser(object, propKey, definition.properties));
      }

      // Do the same thing as previously, but for patternProperties.
      if (definition.patternProperties) {
        definition.patternProperties = arrayToMap(definition.patternProperties, 'key');
        Object.keys(definition.patternProperties).forEach(propKey =>
          propertyHardRefParser(object, propKey, definition.patternProperties));
      }
    });
  } else {
    delete object.definitions;
  }

  if (object.securityDefinitions && object.securityDefinitions.length > 0) {
    object.securityDefinitions = arrayToMap(object.security, 'key');
  } else {
    delete object.securityDefinitions;
  }

  if (object.paths && object.paths.length > 0) {
    object.paths = arrayToMap(object.paths, 'path');
    /*
     * Take all elements in the methods array and put them in the parent path
     * element with `methodName` as the key and the method object as the value.
     */
    Object.keys(object.paths).forEach((key) => {
      const path = object.paths[key];

      path.methods = arrayToMap(path.methods, 'method');

      Object.keys(path.methods).forEach((methodName) => {
        const method = path.methods[methodName];
        method.responses = arrayToMap(method.responses, 'statusCode');
        Object.keys(method.responses).forEach((propKey) => {
          const response = method.responses[propKey];
          response.headers = arrayToMap(response.headers, 'key');
          propertyHardRefParser(object, propKey, method.responses);
          const examples = {};
          if (response.examples) {
            response.examples.forEach((example) => {
              examples[example.mimeType] = example.value;
            });
          }
          response.examples = examples;
        });
        method.parameters.forEach((parameter, index) => {
          propertyHardRefParser(object, index, method.parameters);
        });
        path[methodName] = method;
      });

      // Delete the old list as it isn't actually a part of the Swagger spec
      delete path.methods;
    });
  } else {
    delete object.paths;
  }

  definitionsToDelete.forEach(key => delete object.definitions[key]);

  return object;
};
<commit_msg>Add full path for soft references<commit_after>const schema = require('./schema/index');

/**
 * Convert an array into a map
 * @param  {array[object]} object The array to convert.
 * @param  {string} keyField      The name of the field is stored in within each
 *                                object in the array.
 * @return {object}               The map converted from the array.
 */
function arrayToMap (object, keyField) {
  const newObject = {};
  if (object === undefined || object === null) {
    return newObject;
  }
  object.forEach((objFuncParam) => {
    const obj = objFuncParam;
    const key = obj[keyField];
    if (key === undefined) {
      return;
    }
    delete obj[keyField];
    newObject[key] = obj;
  });
  return newObject;
}

function isEmpty (object) {
  if (object === undefined || object === null) {
    return true;
  } else if (Array.isArray(object)) {
    if (object.length === 0) {
      return true;
    }
    let empty = true;
    object.forEach((child) => {
      if (!isEmpty(child)) {
        empty = false;
        return true;
      }
      return false;
    });
    return empty;
  } else if (typeof object === 'object') {
    let empty = true;
    Object.keys(object).forEach((key) => {
      if (!isEmpty(object[key])) {
        empty = false;
        return true;
      }
      return false;
    });
    return empty;
  } else if (typeof object === 'string') {
    return object.length === 0;
  }
  return false;
}

function deleteEmptyChildren (objectFuncParam) {
  const object = objectFuncParam;
  if (Array.isArray(object)) {
    object.forEach((child, index) => {
      if (isEmpty(child)) {
        object.pop(index);
      } else {
        object[index] = deleteEmptyChildren(child);
      }
    });
  } else if (typeof object === 'object') {
    Object.keys(object).forEach((key) => {
      if (isEmpty(object[key])) {
        delete object[key];
      } else {
        object[key] = deleteEmptyChildren(object[key]);
      }
    });
  }
  return object;
}

function propertyHardRefParser (object, propKey, props) {
  const properties = props;
  const property = properties[propKey];

  const targetExists = Object.hasOwnProperty.call(object.definitions, property.$ref);
  if (!targetExists) {
    return;
  }

  const target = object.definitions[property.$ref];
  if (property.hardReference || target.hardReferenceOnly) {
    properties[propKey] = target;
  } else {
    property.$ref = `#/definitions/${property.$ref}`;
    delete property.hardReference;
  }
}

/**
 * @param  {object} object The form value
 * @return {object}        A corrected version of the output. This should be a
 *                         valid Swagger spec.
 */
module.exports = function processJSON (objectFuncParam) {
  let object = JSON.parse(JSON.stringify(objectFuncParam));

  object = deleteEmptyChildren(object);

  // Hardcoded Swagger version
  object.swagger = '2.0';

  if (object.info) {
    if (object.info.host) {
      object.host = object.info.host;
      delete object.info.host;
    }
    if (object.info.basePath) {
      object.basePath = object.info.basePath;
      delete object.info.basePath;
    }
  }

  if (object.security && object.security.length > 0) {
    object.security = arrayToMap(object.security, 'key');

    /*
     * Put the `value` field of each security object as the actual value of the
     * object.
     */
    Object.keys(object.security).forEach((key) => {
      if (Object.hasOwnProperty.call(object.security[key], 'value')) {
        object.security[key] = object.security[key].value;
      } else {
        object.security[key] = [];
      }
    });
  } else {
    delete object.security;
  }

  // Definition keys that have set the Only hard refences to true will be stored
  // here and then deleted from the definitions object at the end of processing.
  const definitionsToDelete = [];

  if (object.definitions) {
    object.definitions = arrayToMap(object.definitions, 'key');

    Object.keys(object.definitions).forEach((key) => {
      const definition = object.definitions[key];

      // Push hard reference -only definitions to the definitionsToDelete array.
      if (definition.hardReferenceOnly) {
        definitionsToDelete.push(key);
      }
      delete definition.hardReferenceOnly;

      // schemaSchema is a schema to create and validate schemas, also known as
      // a meta-schema.
      // schema.definitions is the main schema for global object definitions and
      // object definitions are basically meta-schemas.
      const schemaSchema = schema.definitions.items;

      // If the value of a property is the same as the default value, delete the
      // whole field to avoid unnecessary fields in the output.
      Object.keys(schemaSchema.properties).forEach((schemaKey) => {
        const prop = schemaSchema.properties[schemaKey];
        if (Object.hasOwnProperty.call(definition, schemaKey)
            && Object.hasOwnProperty.call(prop, 'default')) {
          if (prop.default === definition[schemaKey]) {
            delete definition[schemaKey];
          }
        }
      });

      // Convert the properties field to a map and process references in the
      // properties.
      if (definition.properties) {
        definition.properties = arrayToMap(definition.properties, 'key');
        Object.keys(definition.properties).forEach(propKey =>
          propertyHardRefParser(object, propKey, definition.properties));
      }

      // Do the same thing as previously, but for patternProperties.
      if (definition.patternProperties) {
        definition.patternProperties = arrayToMap(definition.patternProperties, 'key');
        Object.keys(definition.patternProperties).forEach(propKey =>
          propertyHardRefParser(object, propKey, definition.patternProperties));
      }
    });
  } else {
    delete object.definitions;
  }

  if (object.securityDefinitions && object.securityDefinitions.length > 0) {
    object.securityDefinitions = arrayToMap(object.security, 'key');
  } else {
    delete object.securityDefinitions;
  }

  if (object.paths && object.paths.length > 0) {
    object.paths = arrayToMap(object.paths, 'path');
    /*
     * Take all elements in the methods array and put them in the parent path
     * element with `methodName` as the key and the method object as the value.
     */
    Object.keys(object.paths).forEach((key) => {
      const path = object.paths[key];

      path.methods = arrayToMap(path.methods, 'method');

      Object.keys(path.methods).forEach((methodName) => {
        const method = path.methods[methodName];
        method.responses = arrayToMap(method.responses, 'statusCode');
        Object.keys(method.responses).forEach((propKey) => {
          const response = method.responses[propKey];
          response.headers = arrayToMap(response.headers, 'key');
          propertyHardRefParser(object, propKey, method.responses);
          const examples = {};
          if (response.examples) {
            response.examples.forEach((example) => {
              examples[example.mimeType] = example.value;
            });
          }
          response.examples = examples;
        });
        method.parameters.forEach((parameter, index) => {
          propertyHardRefParser(object, index, method.parameters);
        });
        path[methodName] = method;
      });

      // Delete the old list as it isn't actually a part of the Swagger spec
      delete path.methods;
    });
  } else {
    delete object.paths;
  }

  definitionsToDelete.forEach(key => delete object.definitions[key]);

  return object;
};
<|endoftext|>


<commit_before>//= require jquery
//= require uikit
//= require moment
//= require handlebars
//= require ember
//= require ember-restless
//= require_self
//= require covered
//= require debug

$.ajaxSetup({
  headers: {
    'Accept': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
  }
});

Covered = Ember.Application.create({
  // LOG_MODULE_RESOLVER: true,
  // LOG_ACTIVE_GENERATION: true,
  // LOG_VIEW_LOOKUPS: true,
  LOG_TRANSITIONS: true,
  // LOG_TRANSITIONS_INTERNAL: true
});
// Ember.run.backburner.DEBUG = true;

Covered.isSignedIn = function(){
  var currentUser = Covered.CurrentUser.get();
  return currentUser && currentUser.get && currentUser.get('isSignedIn');
};

Ember.TextField.reopen({
  attributeBindings: ['autofocus']
});

$(document).on('click', 'a[href=""]', function(e){ e.preventDefault(); });

// This disables all css-transitions while resizing
$(window).on('resize', function(){
  $('body').addClass('disable-all-transitions');
  var timeout = $(this).data('disableAllTransitionsTimeout');
  clearTimeout(timeout);
  timeout = setTimeout(function(){ $('body').removeClass('disable-all-transitions'); }, 100);
  $(this).data('disableAllTransitionsTimeout', timeout);
});
<commit_msg>added an Ember.onerror handler that throws a horribly ugly error on the page<commit_after>//= require jquery
//= require uikit
//= require moment
//= require handlebars
//= require ember
//= require ember-restless
//= require_self
//= require covered
//= require debug

$.ajaxSetup({
  headers: {
    'Accept': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
  }
});

Covered = Ember.Application.create({
  // LOG_MODULE_RESOLVER: true,
  // LOG_ACTIVE_GENERATION: true,
  // LOG_VIEW_LOOKUPS: true,
  LOG_TRANSITIONS: true,
  // LOG_TRANSITIONS_INTERNAL: true
});
// Ember.run.backburner.DEBUG = true;

Covered.isSignedIn = function(){
  var currentUser = Covered.CurrentUser.get();
  return currentUser && currentUser.get && currentUser.get('isSignedIn');
};

Ember.onerror = function(error){
  var notice = $('<div>');
  notice.text('ERROR: '+error.message);
  notice.css({color: 'red'});
  $('body').prepend(notice);
};

Ember.TextField.reopen({
  attributeBindings: ['autofocus']
});

$(document).on('click', 'a[href=""]', function(e){ e.preventDefault(); });

// This disables all css-transitions while resizing
$(window).on('resize', function(){
  $('body').addClass('disable-all-transitions');
  var timeout = $(this).data('disableAllTransitionsTimeout');
  clearTimeout(timeout);
  timeout = setTimeout(function(){ $('body').removeClass('disable-all-transitions'); }, 100);
  $(this).data('disableAllTransitionsTimeout', timeout);
});
<|endoftext|>


<commit_before>// var db = require('../dbfiles/testdb.js');
//
// var User = db.Model.extend({
//   tableName: 'users',
//   games: function () {
//     return this.hasMany(Game, 'users_games', 'game_id', 'user_id');
//   },
//   rounds: function () {
//     return this.hasMany(Round, 'reader_id');
//   },
//   responses: function () {
//     return this.hasMany(Response, 'user_id');
//   },
//   currentGame: function () {
//     return this.belongsTo(Game, 'current_game_id');
//   }
// });
//
// var Game = db.Model.extend({
//   tableName: 'games',
//   users: function () {
//     return this.hasMany(User, 'users_games', 'user_id', 'game_id');
//   },
//   rounds: function () {
//     return this.hasMany(Round, 'game_id');
//   },
//   responses: function () {
//     return this.hasMany(User, 'current_game_id');
//   }
// });
//
// var Round = db.Model.extend({
//   tableName: 'rounds',
//   responses: function () {
//     return this.hasMany(Response, 'round_id');
//   },
//   reader: function () {
//     return this.belongsTo(User, 'reader_id');
//   },
//   game: function () {
//     return this.belongsTo(Game, 'game_id');
//   }
// });
//
// var Response = db.Model.extend({
//   tableName: 'responses',
//   user: function () {
//     return this.belongsTo(User, 'user_id');
//   },
//   round: function () {
//     return this.belongsTo(Round, 'round_id');
//   }
// });
//
//
// module.exports = {
//   User: User,
//   Game: Game,
//   Round: Round,
//   Response: Response
// };
<commit_msg>(chore) Removes testing seed file<commit_after><|endoftext|>


<commit_before>function choose(choice,id) {
  console.log(id);
  var tgt=$('#'+id);
  $.getJSON("/grammar/choose/"+choice, function(json){
    var result=json['answer'];
    console.log(result);
    tgt.addClass("spinner");
    setTimeout(function() {
      if(result)tgt.addClass('bg-green');
      else tgt.addClass('bg-red');
    }, 1800);
    setTimeout(function() {
      tgt.removeClass('spinner');
    }, 2000);
  });
}

function setSiteCookie(cname,cvalue,exdays)
{
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
  var expires = "expires="+d.toGMTString();
  document.cookie = cname + "=" + cvalue + "; " + expires + "; PATH=/";
}

function getCookie(cname)
{
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++)
  {
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

function renderQuestion(json)
{
  var str='
\n';
  str+='
\nPlease click an alphabetically labeled button to see if you are correct. Click "Hit me!" to view another random question. Click "Previous" to view the last question you saw. Click "List" to return to the question list.\n
';
  str+='
'+json['nickname']+'
';
  str+='
';
  str+=json['question_1st'];
  str+='';
  str+=json['choices'][0];
  str+='';
  str+=json['question_2nd'];
  str+='
\n';
  str+='
\n'
  for (var i=0;i<5;i++)
  {
    str+='
\n';
    str+='('+json['labels'][i]+')\n';
    str+=''+json['choices'][i]+'\n';
    str+='
';
  }
  str+='
';
  str+='
';
  for (var i=0;i<5;i++)
  {
    console.log(i);
    str+='("+json['labels'][i]+')';
  }
  str+='\n
\n';//!buttons
  str+='
\n';//!question
  return str;
}
function renderHit(nextId)
{
  var str=' Hit me!';
  return str;
}
function renderList(json)
{
  var str='
\n';
  str+=' Shuffle\n';
  str+="
Here's a list of all grammar questions avaliable:
\n";
  for(var i=0;i<json['count'];i++)
  {
    console.log(i);
    str+="
"+ ' '+json['nicks'][i]+'
\n';
  }
  str+='
\n';
  return str;
}
function rendertoList(nextId)
{
  var str=' List';
  return str;
}
function renderPrevious(thisId)
{
  var lastId;
  if(getCookie("last")=="")lastId=thisId;
  else lastId=getCookie("last");
  var str=' Previous';
  return str;
}
function viewQuestion(id)
{
  var jqxhr = $.getJSON( "/grammar/ajax/"+id, function() {
  console.log( "Successfully registered ajax event. Loading question "+id+"." );
  })
    .done(function(json) {
      var htmldata=renderQuestion(json);
      var pastHeight=$('#main').height();
      $('#main').addClass('switch_in_out');
      setTimeout(function() {
        $('#main').empty();
        $('#main').append(htmldata);
        var currentHeight=$('#main').height();
        //$('#operations').animate({up:"+="+currentHeight-pastHeight},500);
        var state = {type:'Question',pk:id,now:document.URL}
        document.title = json['nickname']+" - Grammar";
        window.history.pushState(state, document.title, "/grammar/view/"+id);
      },350);
      setTimeout(function() {
        $('#main').removeClass('switch_in_out');
      },1000);
      $('#operations').empty();
      $('#operations').append(renderHit(json['next']));
      $('#operations').append(renderPrevious(id));
      $('#operations').append(rendertoList(json['next']));
    });
}
function viewList()
{
  var jqxhr = $.getJSON( "/grammar/listajax/", function() {
  console.log( "Successfully registered ajax event. Loading list." );
  })
    .done(function(json) {
      var htmldata=renderList(json);
      var pastHeight=$('#main').height();
      $('#main').addClass('switch_in_out');
      setTimeout(function() {
        $('#main').empty();
        $('#main').append(htmldata);
        var currentHeight=$('#main').height();
        //$('#operations').animate({up:"+="+currentHeight-pastHeight},500);
        var state = {type:'List'}
        document.title = "List"+" - Grammar";
        window.history.pushState(state, document.title, "/grammar/");
      },350);
      setTimeout(function() {
        $('#main').removeClass('switch_in_out');
      },1000);
      $('#operations').empty();
    });
}
window.onpopstate = function(event) {
  if(event.state['type']=='List')viewList();
  if(event.state['type']=='Question')viewQuestion(event.state['pk']);
};<commit_msg>fix history support<commit_after>function choose(choice,id) {
  console.log(id);
  var tgt=$('#'+id);
  $.getJSON("/grammar/choose/"+choice, function(json){
    var result=json['answer'];
    console.log(result);
    tgt.addClass("spinner");
    setTimeout(function() {
      if(result)tgt.addClass('bg-green');
      else tgt.addClass('bg-red');
    }, 1800);
    setTimeout(function() {
      tgt.removeClass('spinner');
    }, 2000);
  });
}

function setSiteCookie(cname,cvalue,exdays)
{
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
  var expires = "expires="+d.toGMTString();
  document.cookie = cname + "=" + cvalue + "; " + expires + "; PATH=/";
}

function getCookie(cname)
{
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++)
  {
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

function renderQuestion(json)
{
  var str='
\n';
  str+='
\nPlease click an alphabetically labeled button to see if you are correct. Click "Hit me!" to view another random question. Click "Previous" to view the last question you saw. Click "List" to return to the question list.\n
';
  str+='
'+json['nickname']+'
';
  str+='
';
  str+=json['question_1st'];
  str+='';
  str+=json['choices'][0];
  str+='';
  str+=json['question_2nd'];
  str+='
\n';
  str+='
\n'
  for (var i=0;i<5;i++)
  {
    str+='
\n';
    str+='('+json['labels'][i]+')\n';
    str+=''+json['choices'][i]+'\n';
    str+='
';
  }
  str+='
';
  str+='
';
  for (var i=0;i<5;i++)
  {
    console.log(i);
    str+='("+json['labels'][i]+')';
  }
  str+='\n
\n';//!buttons
  str+='
\n';//!question
  return str;
}
function renderHit(nextId)
{
  var str=' Hit me!';
  return str;
}
function renderList(json)
{
  var str='
\n';
  str+=' Shuffle\n';
  str+="
Here's a list of all grammar questions avaliable:
\n";
  for(var i=0;i<json['count'];i++)
  {
    console.log(i);
    str+="
"+ ' '+json['nicks'][i]+'
\n';
  }
  str+='
\n';
  return str;
}
function rendertoList(nextId)
{
  var str=' List';
  return str;
}
function renderPrevious(thisId)
{
  var lastId;
  if(getCookie("last")=="")lastId=thisId;
  else lastId=getCookie("last");
  var str=' Previous';
  return str;
}
function viewQuestion(id,isHistoryAccess)
{
  var jqxhr = $.getJSON( "/grammar/ajax/"+id, function() {
  console.log( "Successfully registered ajax event. Loading question "+id+"." );
  })
    .done(function(json) {
      var htmldata=renderQuestion(json);
      var pastHeight=$('#main').height();
      $('#main').addClass('switch_in_out');
      setTimeout(function() {
        $('#main').empty();
        $('#main').append(htmldata);
        var currentHeight=$('#main').height();
        //$('#operations').animate({up:"+="+currentHeight-pastHeight},500);
        var state = {type:'Question',pk:id,now:document.URL}
        document.title = json['nickname']+" - Grammar";
        if(!isHistoryAccess)window.history.pushState(state, document.title, "/grammar/view/"+id);
      },350);
      setTimeout(function() {
        $('#main').removeClass('switch_in_out');
      },1000);
      $('#operations').empty();
      $('#operations').append(renderHit(json['next']));
      $('#operations').append(renderPrevious(id));
      $('#operations').append(rendertoList(json['next']));
    });
}
function viewList(isHistoryAccess)
{
  var jqxhr = $.getJSON( "/grammar/listajax/", function() {
  console.log( "Successfully registered ajax event. Loading list." );
  })
    .done(function(json) {
      var htmldata=renderList(json);
      var pastHeight=$('#main').height();
      $('#main').addClass('switch_in_out');
      setTimeout(function() {
        $('#main').empty();
        $('#main').append(htmldata);
        var currentHeight=$('#main').height();
        //$('#operations').animate({up:"+="+currentHeight-pastHeight},500);
        var state = {type:'List'}
        document.title = "List"+" - Grammar";
        if(!isHistoryAccess)window.history.pushState(state, document.title, "/grammar/");
      },350);
      setTimeout(function() {
        $('#main').removeClass('switch_in_out');
      },1000);
      $('#operations').empty();
    });
}
window.onpopstate = function(event) {
  if(event.state['type']=='List')viewList(true);
  if(event.state['type']=='Question')viewQuestion(event.state['pk'],true);
};<|endoftext|>


<commit_before>//= require jquery
//= require jquery-ui
//= require jquery.colorbox
//= require jquery_ujs
//= require jquery.highlight
//= require jquery.hotkeys
//= require jquery.cookie
//= require fg.menu
//= require fg.menu.enju
//= require pagination
//= require select_locale
//= require portlets
//= require tab_view
//= require event_calendar
//= require rails.validations
<commit_msg>updated asset file<commit_after>//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require jquery.colorbox
//= require jquery.highlight
//= require jquery.hotkeys
//= require jquery.cookie
//= require fg.menu
//= require fg.menu.enju
//= require pagination
//= require select_locale
//= require portlets
//= require tab_view
//= require event_calendar
//= require rails.validations
<|endoftext|>


<commit_before>import {expect} from 'chai'
import tabular from '../src/scripts/utils/data_extractors/dom-extractor'
import $ from 'jquery'

describe("dom-extractor", function() {
  describe("with vanilla HTML", function() {
    before(function () {
      document.body.innerHTML = `

Col A

Col B

Col C

1A

1B

1C

2A

2B

2C

3A

3B

3C

`
    })

    describe("getClosestCommonAncestor", () => {
      it("should get closest common ancestor", () => {
        let nodeA = $('#td2c')
        let nodeB = $('#td3a')
        let closestCommonAncestor = tabular._getClosestCommonAncestor(nodeA, nodeB)
        expect(closestCommonAncestor.attr('id')).to.equal('container')
      })
      it("should get closest common ancestor on same row", () => {
        let nodeA = $('#td2c')
        let nodeB = $('#td2a')
        let closestCommonAncestor = tabular._getClosestCommonAncestor(nodeA, nodeB)
        expect(closestCommonAncestor.attr('id')).to.equal('tr2')
      })
    })

    describe("getFirstChildThatContains", () => {
      it("should get first child that contains element", () => {
        let parent = $('#container')
        let containedDescendant = $('#span1b')
        let firstChild = tabular._getFirstChildThatContains(parent, containedDescendant)
        expect(firstChild.attr('id')).to.equal('tr1')
      })

      it("should return undefined if not found", () => {
        let parent = $('#tr2')
        let containedDescendant = $('#span1b')
        let firstChild = tabular._getFirstChildThatContains(parent, containedDescendant)
        expect(firstChild.attr('id')).to.be.undefined
      })
    })

    describe("getChildrenTextAsArray", () => {
      it("should get children text as array", () => {
        expect(tabular._getChildrenTextAsArray($('#tr1'))).to.deep.equal(['1A', '1B', '1C'])
      })
    })

    describe("getTabularDataFromSelection", () => {
      it("should get tabular data", () => {
        var domSelectionRange = {
          start: $('#td1a').get(0),
          end: $('#td3c').get(0)
        }
        expect(tabular.getTabularDataFromSelection(domSelectionRange))
          .to.deep.equal({
            'data': [['1A','1B','1C'],['2A','2B','2C'],['3A','3B','3C']]
          })
      })

      it("should get tabular data from inverted selection", () => {
        var domSelectionRange = {
          start: $('#td3c').get(0),
          end: $('#td1a').get(0)
        }
        expect(tabular.getTabularDataFromSelection(domSelectionRange))
          .to.deep.equal({
            'data': [['1A','1B','1C'],['2A','2B','2C'],['3A','3B','3C']]
          })
      })

      it("should get tabular data from a single row", () => {
        var domSelectionRange = {
          start: $('#td1a').get(0),
          end: $('#td1c').get(0)
        }
        expect(tabular.getTabularDataFromSelection(domSelectionRange))
          .to.deep.equal({
            'data': [['1A','1B','1C']]
          })
      })
    })
  })

  describe("with Amex HTML", function() {

    before(function () {
      document.body.innerHTML = `

29 apr

ICA KVANTUM FLEN 020350 FLEN

805,62 kr

`
    })

    describe("getChildrenTextAsArray", () => {
      it("should get children text as array", () => {
        expect(tabular._getChildrenTextAsArray($('#transaction-xxx'))).to.deep.equal([
          '',
          '29 apr',
          'ICA KVANTUM FLEN 020350 FLEN',
          '',
          '805,62 kr',
          ''
        ])
      })
    })
  })
})
<commit_msg>Refactor and add logs to dom-extractor<commit_after>import {expect} from 'chai'
import domExtractor from '../src/scripts/utils/data_extractors/dom-extractor'
import $ from 'jquery'

describe("dom-extractor", function() {
  describe("with vanilla HTML", function() {
    before(function () {
      document.body.innerHTML = `

Col A

Col B

Col C

1A

1B

1C

2A

2B

2C

3A

3B

3C

`
    })

    describe("getClosestCommonAncestor", () => {
      it("should get closest common ancestor", () => {
        let nodeA = $('#td2c')
        let nodeB = $('#td3a')
        let closestCommonAncestor = domExtractor._getClosestCommonAncestor(nodeA, nodeB)
        expect(closestCommonAncestor.attr('id')).to.equal('container')
      })
      it("should get closest common ancestor on same row", () => {
        let nodeA = $('#td2c')
        let nodeB = $('#td2a')
        let closestCommonAncestor = domExtractor._getClosestCommonAncestor(nodeA, nodeB)
        expect(closestCommonAncestor.attr('id')).to.equal('tr2')
      })
    })

    describe("getFirstChildThatContains", () => {
      it("should get first child that contains element", () => {
        let parent = $('#container')
        let containedDescendant = $('#span1b')
        let firstChild = domExtractor._getFirstChildThatContains(parent, containedDescendant)
        expect(firstChild.attr('id')).to.equal('tr1')
      })

      it("should return undefined if not found", () => {
        let parent = $('#tr2')
        let containedDescendant = $('#span1b')
        let firstChild = domExtractor._getFirstChildThatContains(parent, containedDescendant)
        expect(firstChild.attr('id')).to.be.undefined
      })
    })

    describe("getChildrenTextAsArray", () => {
      it("should get children text as array", () => {
        expect(domExtractor._getChildrenTextAsArray($('#tr1'))).to.deep.equal(['1A', '1B', '1C'])
      })
    })

    describe("getTabularDataFromSelection", () => {
      it("should get tabular data", () => {
        var domSelectionRange = {
          start: $('#td1a').get(0),
          end: $('#td3c').get(0)
        }
        expect(domExtractor.getTabularDataFromSelection(domSelectionRange))
          .to.deep.equal({
            'data': [['1A','1B','1C'],['2A','2B','2C'],['3A','3B','3C']]
          })
      })

      it("should get tabular data from inverted selection", () => {
        var domSelectionRange = {
          start: $('#td3c').get(0),
          end: $('#td1a').get(0)
        }
        expect(domExtractor.getTabularDataFromSelection(domSelectionRange))
          .to.deep.equal({
            'data': [['1A','1B','1C'],['2A','2B','2C'],['3A','3B','3C']]
          })
      })

      it("should get tabular data from a single row", () => {
        var domSelectionRange = {
          start: $('#td1a').get(0),
          end: $('#td1c').get(0)
        }
        expect(domExtractor.getTabularDataFromSelection(domSelectionRange))
          .to.deep.equal({
            'data': [['1A','1B','1C']]
          })
      })

      it("should throw on invalid selection", () => {
        expect(() => {
          domExtractor.getTabularDataFromSelection(null)
        }).to.throw('Could not find tabular data')
      })
    })
  })

  describe("with Amex HTML", function() {

    before(function () {
      document.body.innerHTML = `

29 apr

ICA KVANTUM FLEN 020350 FLEN

805,62 kr

`
    })

    describe("getChildrenTextAsArray", () => {
      it("should get children text as array", () => {
        expect(domExtractor._getChildrenTextAsArray($('#transaction-xxx'))).to.deep.equal([
          '',
          '29 apr',
          'ICA KVANTUM FLEN 020350 FLEN',
          '',
          '805,62 kr',
          ''
        ])
      })
    })
  })
})
<|endoftext|>