<commit_before>'use strict';

describe('Unit tests: story-service', function () {

    beforeEach(module('ftuApp.story-service'));

    var storyFactory, httpMock;

    beforeEach(inject(function($httpBackend, storyAPIservice) {

        httpMock = $httpBackend;

        //httpMock.when('GET', 'json/stories.json')
        //    .respond([{
        //        "title": "Story Title",
        //        "id": 1
        //    }]);

        httpMock.when('GET', 'json/topics.json')
            .respond([{
                "id": 1,
                "name": "Avira"
            }]);

        storyFactory = storyAPIservice;

    }));

    var storyList, topicList;

    it('should retrieve the stories list', function(){
        storyFactory.getStories().success(function(data){ storyList = data; });
        httpMock.flush();
        expect(storyList[0].title).toBe("Story Title");
    });

    it('should retrieve the topic list', function(){
        storyFactory.getTopics().success(function(data){ topicList = data; });
        httpMock.flush();
        expect(topicList[1].name).toBe("Avira");
    });

});<commit_msg>modified unit test<commit_after>'use strict';

describe('Unit tests: story-service', function () {

    beforeEach(module('ftuApp.story-service'));

    var storyFactory, httpMock;

    beforeEach(inject(function($httpBackend, storyAPIservice) {

        httpMock = $httpBackend;

        httpMock.when('GET', 'json/topics.json')
            .respond([{
                "id": 1,
                "name": "Avira"
            }]);

        storyFactory = storyAPIservice;

    }));

    var storyList, topicList;

    it('should retrieve the stories list', function(){
        storyFactory.getStories().success(function(data){ storyList = data; });
        httpMock.flush();
        expect(storyList[0].title).toBe("Story Title");
    });

    it('should retrieve the topic list', function(){
        storyFactory.getTopics().success(function(data){ topicList = data; });
        httpMock.flush();
        expect(topicList[1].name).toBe("Avira");
    });

});<|endoftext|>


<commit_before>/*
 Copyright 2010 WebDriver committers
 Copyright 2010 Google Inc.

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

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

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

/**
 * @fileoverview Methods for dealing with modal dialogs
 */

goog.provide('webdriver.modals');

goog.require('ErrorCode');
goog.require('Logger');
goog.require('Timer');
goog.require('webdriver.firefox.utils');

var CI = Components.interfaces;
var CC = Components.classes;

webdriver.modals.isModalPresent = function(callback, timeout) {
  var timer = new Timer();
  timer.runWhenTrue(
    function() { return webdriver.modals.find_() },
    function() { callback(true) },
    timeout,
    function() { callback(false) });
};

webdriver.modals.acceptAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "accept");
  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.dismissAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "cancel");

  if (!button) {
    Logger.dumpn('No cancel button Falling back to the accept button');
    button = webdriver.modals.findButton_(modal, "accept");
  }

  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.getText = function(driver) {
  return driver.modalOpen
};

webdriver.modals.setValue = function(driver, value) {
  var modal = webdriver.modals.find_();
  var textbox = modal.document.getElementById('loginTextbox');
  if (textbox.clientWidth == 0 || textbox.clientHeight == 0) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE, 'Alert did not have a text box');
  }
  textbox.value = value;
};

webdriver.modals.find_ = function() {
  var window = webdriver.firefox.utils.windowMediator().getMostRecentWindow('');
  window = webdriver.firefox.utils.unwrap(window);

  // Get the WebBrowserChrome and check if it's a modal window
  var chrome = window.QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebNavigation).
      QueryInterface(CI.nsIDocShellTreeItem).
      treeOwner.
      QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebBrowserChrome);
  if (!chrome.isWindowModal()) {
    return null;
  }

  return window;
};

webdriver.modals.findButton_ = function(modal, value) {
  var doc = modal.document;
  var dialog = doc.getElementsByTagName("dialog")[0];
  return dialog.getButton(value);
};

webdriver.modals.setFlag = function(driver, flagValue) {
  driver.modalOpen = flagValue;
};

webdriver.modals.clearFlag_ = function(driver) {
  webdriver.modals.setFlag(driver, false);
};

webdriver.modals.findAssociatedDriver_ = function(window) {
  var ww = CC["@mozilla.org/embedcomp/window-watcher;1"].getService(CI["nsIWindowWatcher"]);

  var parent = window ? window : ww.activeWindow;
  if (parent.wrappedJSObject) {
    parent = parent.wrappedJSObject;
  }
  var top = parent.top;

  // Now iterate over all open browsers to find the one we belong to
  var wm = CC["@mozilla.org/appshell/window-mediator;1"].getService(CI["nsIWindowMediator"]);
  var allWindows = wm.getEnumerator("navigator:browser");
  while (allWindows.hasMoreElements()) {
    var chrome = allWindows.getNext().QueryInterface(CI.nsIDOMWindow);
    if (chrome.content == window) {
      return chrome.fxdriver;
    } else if(chrome.content.parent == window.parent) {
      return chrome.fxdriver;
    }
  }

  // There's no meaningful way we can reach this.
  Logger.dumpn('Unable to find the associated driver');
  return undefined;
};

webdriver.modals.signalOpenModal = function(parent, text) {
  Logger.dumpn("signalOpenModal");
  // Try to grab the top level window
  var driver = webdriver.modals.findAssociatedDriver_(parent);
  if (driver && driver.response_) {
    webdriver.modals.setFlag(driver, text);
    var res = driver.response_;
    res.value = {
      text: text
    };
    res.statusCode = ErrorCode.MODAL_DIALOG_OPENED;
    res.send();
  }
};
<commit_msg>DanielWagnerHall: It turns out Firefox 3 doesn't define clientWidth/clientHeight for modal text boxes, and somehow my run of tests didn't find that.  Use a test for existence of a prompt textbox which works on all firefoxes.  For now.<commit_after>/*
 Copyright 2010 WebDriver committers
 Copyright 2010 Google Inc.

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

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

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

/**
 * @fileoverview Methods for dealing with modal dialogs
 */

goog.provide('webdriver.modals');

goog.require('ErrorCode');
goog.require('Logger');
goog.require('Timer');
goog.require('webdriver.firefox.utils');

var CI = Components.interfaces;
var CC = Components.classes;

webdriver.modals.isModalPresent = function(callback, timeout) {
  var timer = new Timer();
  timer.runWhenTrue(
    function() { return webdriver.modals.find_() },
    function() { callback(true) },
    timeout,
    function() { callback(false) });
};

webdriver.modals.acceptAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "accept");
  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.dismissAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "cancel");

  if (!button) {
    Logger.dumpn('No cancel button Falling back to the accept button');
    button = webdriver.modals.findButton_(modal, "accept");
  }

  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.getText = function(driver) {
  return driver.modalOpen
};

webdriver.modals.setValue = function(driver, value) {
  var modal = webdriver.modals.find_();
  var textbox = modal.document.getElementById('loginTextbox');
  try {
    var trueIfTextboxExists = textbox.selectionStart > -1;
    if (trueIfTextboxExists) {
      textbox.value = value;
    }
  } catch (e) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE, 'Alert did not have a text box');
  }
};

webdriver.modals.find_ = function() {
  var window = webdriver.firefox.utils.windowMediator().getMostRecentWindow('');
  window = webdriver.firefox.utils.unwrap(window);

  // Get the WebBrowserChrome and check if it's a modal window
  var chrome = window.QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebNavigation).
      QueryInterface(CI.nsIDocShellTreeItem).
      treeOwner.
      QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebBrowserChrome);
  if (!chrome.isWindowModal()) {
    return null;
  }

  return window;
};

webdriver.modals.findButton_ = function(modal, value) {
  var doc = modal.document;
  var dialog = doc.getElementsByTagName("dialog")[0];
  return dialog.getButton(value);
};

webdriver.modals.setFlag = function(driver, flagValue) {
  driver.modalOpen = flagValue;
};

webdriver.modals.clearFlag_ = function(driver) {
  webdriver.modals.setFlag(driver, false);
};

webdriver.modals.findAssociatedDriver_ = function(window) {
  var ww = CC["@mozilla.org/embedcomp/window-watcher;1"].getService(CI["nsIWindowWatcher"]);

  var parent = window ? window : ww.activeWindow;
  if (parent.wrappedJSObject) {
    parent = parent.wrappedJSObject;
  }
  var top = parent.top;

  // Now iterate over all open browsers to find the one we belong to
  var wm = CC["@mozilla.org/appshell/window-mediator;1"].getService(CI["nsIWindowMediator"]);
  var allWindows = wm.getEnumerator("navigator:browser");
  while (allWindows.hasMoreElements()) {
    var chrome = allWindows.getNext().QueryInterface(CI.nsIDOMWindow);
    if (chrome.content == window) {
      return chrome.fxdriver;
    } else if(chrome.content.parent == window.parent) {
      return chrome.fxdriver;
    }
  }

  // There's no meaningful way we can reach this.
  Logger.dumpn('Unable to find the associated driver');
  return undefined;
};

webdriver.modals.signalOpenModal = function(parent, text) {
  Logger.dumpn("signalOpenModal");
  // Try to grab the top level window
  var driver = webdriver.modals.findAssociatedDriver_(parent);
  if (driver && driver.response_) {
    webdriver.modals.setFlag(driver, text);
    var res = driver.response_;
    res.value = {
      text: text
    };
    res.statusCode = ErrorCode.MODAL_DIALOG_OPENED;
    res.send();
  }
};
<|endoftext|>


<commit_before>import {
  default as React,
  Component,
} from "react";

import {
  default as ReactDOM,
} from "react-dom";

import {
  default as GitHubForkRibbon,
} from "react-github-fork-ribbon";

export function CustomizedTagComponent (props) {
  const trigger = props.currentMentionText.substring(0, 1);

  return (

      <button onClick={() => props.selectMentionCallback(null)}>
        Cancel
      </button>
      <button onClick={() => props.selectMentionCallback(trigger + "mention")}>
        Select `{ trigger }mention`
      </button>
      CustomizedTagComponent!!!

  );
}

export default class ReactRoot extends Component {

  componentDidMount () {
    const MediumEditor = require("medium-editor");
    const TCMention = require("../../../src").TCMention;

    this.editor = new MediumEditor(this.refs.editable, {
      extensions: {
        "mention": new TCMention({
          extraClassName: "abc123",
          tagName: "b",
          renderPanelContent: function (panelEl, currentMentionText, selectMentionCallback) {
            ReactDOM.render((
              <CustomizedTagComponent
                currentMentionText={currentMentionText}
                selectMentionCallback={selectMentionCallback}
              />
            ), panelEl);
          },
          destroyPanelContent: function (panelEl) {
            ReactDOM.unmountComponentAtNode(panelEl);
          },
          activeTriggerList: ["#", "@"]
        })
      }
    });
  }

  render () {
    return (

        <GitHubForkRibbon
          position="right"
          color="black"
          href="https://github.com/tomchentw/medium-editor-tc-mention">
          Fork me on GitHub
        </GitHubForkRibbon>

Medium Editor

My father’s family name being Pirrip, and my Christian name Philip, my infant tongue could make of both names nothing longer or more explicit than Pip. So, I called myself Pip, and came to be called Pip.

I give Pirrip as my father’s family name, on the authority of his tombstone and my sister,—Mrs. Joe Gargery, who married the blacksmith. As I never saw my father or my mother, and never saw any likeness of either of them (for their days were long before the days of photographs), my first fancies regarding what they were like were unreasonably derived from their tombstones. The shape of the letters on my father’s, gave me an odd idea that he was a square, stout, dark man, with curly black hair. From the character and turn of the inscription, “Also Georgiana Wife of the Above,” I drew a childish conclusion that my mother was freckled and sickly. To five little stone lozenges, each about a foot and a half long, which were arranged in a neat row beside their grave, and were sacred to the memory of five little brothers of mine,—who gave up trying to get a living, exceedingly early in that universal struggle,—I am indebted for a belief I religiously entertained that they had all been born on their backs with their hands in their trousers-pockets, and had never taken them out in this state of existence.

Ours was the marsh country, down by the river, within, as the river wound, twenty miles of the sea. My first most vivid and broad impression of the identity of things seems to me to have been gained on a memorable raw afternoon towards evening. At such a time I found out for certain that this bleak place overgrown with nettles was the churchyard; and that Philip Pirrip, late of this parish, and also Georgiana wife of the above, were dead and buried; and that Alexander, Bartholomew, Abraham, Tobias, and Roger, infant children of the aforesaid, were also dead and buried; and that the dark flat wilderness beyond the churchyard, intersected with dikes and mounds and gates, with scattered cattle feeding on it, was the marshes; and that the low leaden line beyond was the river; and that the distant savage lair from which the wind was rushing was the sea; and that the small bundle of shivers growing afraid of it all and beginning to cry, was Pip.

    );
  }
}
<commit_msg>docs(gh-pages): add extraActiveClassName<commit_after>import {
  default as React,
  Component,
} from "react";

import {
  default as ReactDOM,
} from "react-dom";

import {
  default as GitHubForkRibbon,
} from "react-github-fork-ribbon";

export function CustomizedTagComponent (props) {
  const trigger = props.currentMentionText.substring(0, 1);

  return (

      <button onClick={() => props.selectMentionCallback(null)}>
        Cancel
      </button>
      <button onClick={() => props.selectMentionCallback(trigger + "mention")}>
        Select `{ trigger }mention`
      </button>
      CustomizedTagComponent!!!

  );
}

export default class ReactRoot extends Component {

  componentDidMount () {
    const MediumEditor = require("medium-editor");
    const TCMention = require("../../../src").TCMention;

    this.editor = new MediumEditor(this.refs.editable, {
      extensions: {
        "mention": new TCMention({
          extraClassName: "abc123",
          extraActiveClassName: "xyz",
          tagName: "b",
          renderPanelContent: function (panelEl, currentMentionText, selectMentionCallback) {
            ReactDOM.render((
              <CustomizedTagComponent
                currentMentionText={currentMentionText}
                selectMentionCallback={selectMentionCallback}
              />
            ), panelEl);
          },
          destroyPanelContent: function (panelEl) {
            ReactDOM.unmountComponentAtNode(panelEl);
          },
          activeTriggerList: ["#", "@"]
        })
      }
    });
  }

  render () {
    return (

        <GitHubForkRibbon
          position="right"
          color="black"
          href="https://github.com/tomchentw/medium-editor-tc-mention">
          Fork me on GitHub
        </GitHubForkRibbon>

Medium Editor

My father’s family name being Pirrip, and my Christian name Philip, my infant tongue could make of both names nothing longer or more explicit than Pip. So, I called myself Pip, and came to be called Pip.

I give Pirrip as my father’s family name, on the authority of his tombstone and my sister,—Mrs. Joe Gargery, who married the blacksmith. As I never saw my father or my mother, and never saw any likeness of either of them (for their days were long before the days of photographs), my first fancies regarding what they were like were unreasonably derived from their tombstones. The shape of the letters on my father’s, gave me an odd idea that he was a square, stout, dark man, with curly black hair. From the character and turn of the inscription, “Also Georgiana Wife of the Above,” I drew a childish conclusion that my mother was freckled and sickly. To five little stone lozenges, each about a foot and a half long, which were arranged in a neat row beside their grave, and were sacred to the memory of five little brothers of mine,—who gave up trying to get a living, exceedingly early in that universal struggle,—I am indebted for a belief I religiously entertained that they had all been born on their backs with their hands in their trousers-pockets, and had never taken them out in this state of existence.

Ours was the marsh country, down by the river, within, as the river wound, twenty miles of the sea. My first most vivid and broad impression of the identity of things seems to me to have been gained on a memorable raw afternoon towards evening. At such a time I found out for certain that this bleak place overgrown with nettles was the churchyard; and that Philip Pirrip, late of this parish, and also Georgiana wife of the above, were dead and buried; and that Alexander, Bartholomew, Abraham, Tobias, and Roger, infant children of the aforesaid, were also dead and buried; and that the dark flat wilderness beyond the churchyard, intersected with dikes and mounds and gates, with scattered cattle feeding on it, was the marshes; and that the low leaden line beyond was the river; and that the distant savage lair from which the wind was rushing was the sea; and that the small bundle of shivers growing afraid of it all and beginning to cry, was Pip.

    );
  }
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('#li-boot').addClass('active');

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto'
    });

    var table = $('#bootstable').dataTable({
        'dom': '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"<"length-menu"l>>' +
            '<"col-xs-4 col-sm-4 col-md-4 col-lg-4 col-lg-offset-2"f>r' +
            '<"col-xs-12 col-sm-12 col-md-12 col-lg-12"t>>' +
            '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"i>' +
            '<"col-xs-6 col-sm-6 col-md-6 col-lg-6"p>>',
        'language': {
            'lengthMenu': '_MENU_ boot reports per page',
            'zeroRecords': '
No boot reports to display.
',
            'search': '
_INPUT_
'
        },
        'lengthMenu': [25, 50, 75, 100],
        'deferRender': true,
        'ordering': true,
        'processing': true,
        'stateDuration': -1,
        'stateSave': true,
        'order': [4, 'desc'],
        'search': {
            'regex': true
        },
        'ajax': {
            'url': '/_ajax/boot',
            'traditional': true,
            'cache': true,
            'dataType': 'json',
            'dataSrc': 'result',
            'dataFilter': function(data, type) {
                if (type === 'json') {
                    var parsed = JSON.parse(data);
                    parsed.result = JSON.parse(parsed.result);
                    return JSON.stringify(parsed);
                }
                return data;
            },
            'data': {
                'sort': 'created_on',
                'sort_order': -1,
                'date_range': $('#date-range').val(),
                'field': [
                    'job', 'kernel', 'defconfig', 'board', 'created_on',
                    'status'
                ]
            }
        },
        'columns': [
            {
                'data': 'job',
                'title': 'Tree',
                'render': function(data, type, object) {
                    return '' +
                        data + '';
                }
            },
            {
                'data': 'kernel',
                'title': 'Kernel'
            },
            {
                'data': 'defconfig',
                'title': 'Defconfig'
            },
            {
                'data': 'board',
                'title': 'Board Model'
            },
            {
                'data': 'created_on',
                'title': 'Date',
                'type': 'date',
                'render': function(data, type, object) {
                    var created = new Date(data['$date']);
                    return created.getCustomISODate();
                }
            },
            {
                'data': 'status',
                'title': 'Status',
                'type': 'string',
                'render': function(data, type, object) {
                    var displ;
                    switch (data) {
                        case 'PASS':
                            displ = '' +
                                '' +
                                '';
                            break;
                        case 'FAIL':
                            displ = '' +
                                '' +
                                '' +
                                '';
                            break;
                        case 'OFFLINE':
                            displ = '<span rel="tooltip"' +
                                'data-toggle="tooltip"' +
                                'title="Board offline"' +
                                '' +
                                '' +
                                '';
                            break;
                        default:
                            displ = '' +
                                '' +
                                '' +
                                '';
                            break;
                    }
                    return displ;
                }
            },
            {
                'data': 'board',
                'title': '',
                'orderable': false,
                'searchable': false,
                'className': 'pull-center',
                'render': function(data, type, object) {
                    var defconfig = object.defconfig,
                        kernel = object.kernel,
                        job = object.job;

                    return '' +
                        '';
                }
            }
        ]
    });

    $(document).on("click", "#bootstable tbody tr", function() {
        var data = table.fnGetData(this);
        if (data) {
            window.location = '/boot/' + data.board + '/job/' + data.job +
                '/kernel/' + data.kernel + '/defconfig/' + data.defconfig + '/';
        }
    });

    $('#search-area > .input-sm').attr('placeholder', 'Filter the results');
    $('.input-sm').keyup(function(key) {
        // Remove focus from input when Esc is pressed.
        if (key.keyCode === 27) {
            $(this).blur();
        }
    });
});
<commit_msg>Fix lint errors, add CSRF token.<commit_after>var csrftoken = $('meta[name=csrf-token]').attr('content');

$(document).ready(function () {
    "use strict";

    $('#li-boot').addClass('active');

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto'
    });

    var table = $('#bootstable').dataTable({
        'dom': '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"<"length-menu"l>>' +
            '<"col-xs-4 col-sm-4 col-md-4 col-lg-4 col-lg-offset-2"f>r' +
            '<"col-xs-12 col-sm-12 col-md-12 col-lg-12"t>>' +
            '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"i>' +
            '<"col-xs-6 col-sm-6 col-md-6 col-lg-6"p>>',
        'language': {
            'lengthMenu': '_MENU_ boot reports per page',
            'zeroRecords': '
No boot reports to display.
',
            'search': '
_INPUT_
'
        },
        'lengthMenu': [25, 50, 75, 100],
        'deferRender': true,
        'ordering': true,
        'processing': true,
        'stateDuration': -1,
        'stateSave': true,
        'order': [4, 'desc'],
        'search': {
            'regex': true
        },
        'ajax': {
            'url': '/_ajax/boot',
            'traditional': true,
            'cache': true,
            'dataType': 'json',
            'dataSrc': 'result',
            'dataFilter': function (data, type) {
                if (type === 'json') {
                    var parsed = JSON.parse(data);
                    parsed.result = JSON.parse(parsed.result);
                    return JSON.stringify(parsed);
                }
                return data;
            },
            'beforeSend': function (xhr) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            'data': {
                'sort': 'created_on',
                'sort_order': -1,
                'date_range': $('#date-range').val(),
                'field': [
                    'job', 'kernel', 'defconfig', 'board', 'created_on',
                    'status'
                ]
            }
        },
        'columns': [
            {
                'data': 'job',
                'title': 'Tree',
                'render': function (data) {
                    return '' +
                        data + '';
                }
            },
            {
                'data': 'kernel',
                'title': 'Kernel'
            },
            {
                'data': 'defconfig',
                'title': 'Defconfig'
            },
            {
                'data': 'board',
                'title': 'Board Model'
            },
            {
                'data': 'created_on',
                'title': 'Date',
                'type': 'date',
                'render': function (data) {
                    var created = new Date(data['$date']);
                    return created.getCustomISODate();
                }
            },
            {
                'data': 'status',
                'title': 'Status',
                'type': 'string',
                'render': function (data) {
                    var displ;
                    switch (data) {
                        case 'PASS':
                            displ = '' +
                                '' +
                                '';
                            break;
                        case 'FAIL':
                            displ = '' +
                                '' +
                                '' +
                                '';
                            break;
                        case 'OFFLINE':
                            displ = '<span rel="tooltip"' +
                                'data-toggle="tooltip"' +
                                'title="Board offline"' +
                                '' +
                                '' +
                                '';
                            break;
                        default:
                            displ = '' +
                                '' +
                                '' +
                                '';
                            break;
                    }
                    return displ;
                }
            },
            {
                'data': 'board',
                'title': '',
                'orderable': false,
                'searchable': false,
                'className': 'pull-center',
                'render': function (data, object) {
                    var defconfig = object.defconfig,
                        kernel = object.kernel,
                        job = object.job;

                    return '' +
                        '';
                }
            }
        ]
    });

    $(document).on("click", "#bootstable tbody tr", function () {
        var data = table.fnGetData(this);
        if (data) {
            window.location = '/boot/' + data.board + '/job/' + data.job +
                '/kernel/' + data.kernel + '/defconfig/' + data.defconfig + '/';
        }
    });

    $('#search-area > .input-sm').attr('placeholder', 'Filter the results');
    $('.input-sm').keyup(function (key) {
        // Remove focus from input when Esc is pressed.
        if (key.keyCode === 27) {
            $(this).blur();
        }
    });
});
<|endoftext|>


<commit_before>import {
  default as React,
  Component,
} from "react";

import {
  default as ReactDOM,
} from "react-dom";

import {
  default as GitHubForkRibbon,
} from "react-github-fork-ribbon";

export function CustomizedTagComponent (props) {
  const trigger = props.currentMentionText.substring(0, 1);
  const current = props.currentMentionText.substring(1);

  return (

        Current text: {current}

      <button onClick={() => props.selectMentionCallback(null)}>
        Cancel
      </button>
      <button onClick={() => props.selectMentionCallback(trigger + "mention")}>
        Select `{ trigger }mention`
      </button>
      CustomizedTagComponent!!!

  );
}

export default class ReactRoot extends Component {

  componentDidMount () {
    const MediumEditor = require("medium-editor");
    const TCMention = require("../../../src").TCMention;

    this.editor = new MediumEditor(this.refs.editable, {
      extensions: {
        "mention": new TCMention({
          extraPanelClassName: "abc123",
          extraActivePanelClassName: "xyz",
          tagName: "b",
          renderPanelContent: function (panelEl, currentMentionText, selectMentionCallback) {
            ReactDOM.render((
              <CustomizedTagComponent
                currentMentionText={currentMentionText}
                selectMentionCallback={selectMentionCallback}
              />
            ), panelEl);
          },
          destroyPanelContent: function (panelEl) {
            ReactDOM.unmountComponentAtNode(panelEl);
          },
          activeTriggerList: ["#", "@"]
        })
      }
    });
  }

  render () {
    return (

        <GitHubForkRibbon
          position="right"
          color="black"
          href="https://github.com/tomchentw/medium-editor-tc-mention">
          Fork me on GitHub
        </GitHubForkRibbon>

Medium Editor

My father’s family name being Pirrip, and my Christian name Philip, my infant tongue could make of both names nothing longer or more explicit than Pip. So, I called myself Pip, and came to be called Pip.

I give Pirrip as my father’s family name, on the authority of his tombstone and my sister,—Mrs. Joe Gargery, who married the blacksmith. As I never saw my father or my mother, and never saw any likeness of either of them (for their days were long before the days of photographs), my first fancies regarding what they were like were unreasonably derived from their tombstones. The shape of the letters on my father’s, gave me an odd idea that he was a square, stout, dark man, with curly black hair. From the character and turn of the inscription, “Also Georgiana Wife of the Above,” I drew a childish conclusion that my mother was freckled and sickly. To five little stone lozenges, each about a foot and a half long, which were arranged in a neat row beside their grave, and were sacred to the memory of five little brothers of mine,—who gave up trying to get a living, exceedingly early in that universal struggle,—I am indebted for a belief I religiously entertained that they had all been born on their backs with their hands in their trousers-pockets, and had never taken them out in this state of existence.

Ours was the marsh country, down by the river, within, as the river wound, twenty miles of the sea. My first most vivid and broad impression of the identity of things seems to me to have been gained on a memorable raw afternoon towards evening. At such a time I found out for certain that this bleak place overgrown with nettles was the churchyard; and that Philip Pirrip, late of this parish, and also Georgiana wife of the above, were dead and buried; and that Alexander, Bartholomew, Abraham, Tobias, and Roger, infant children of the aforesaid, were also dead and buried; and that the dark flat wilderness beyond the churchyard, intersected with dikes and mounds and gates, with scattered cattle feeding on it, was the marshes; and that the low leaden line beyond was the river; and that the distant savage lair from which the wind was rushing was the sea; and that the small bundle of shivers growing afraid of it all and beginning to cry, was Pip.

    );
  }
}
<commit_msg>docs(gh-pages): update for extraTriggerClassNameMap & extraActiveTriggerClassNameMap<commit_after>import {
  default as React,
  Component,
} from "react";

import {
  default as ReactDOM,
} from "react-dom";

import {
  default as GitHubForkRibbon,
} from "react-github-fork-ribbon";

export function CustomizedTagComponent (props) {
  const trigger = props.currentMentionText.substring(0, 1);
  const current = props.currentMentionText.substring(1);

  return (

        Current text: {current}

      <button onClick={() => props.selectMentionCallback(null)}>
        Cancel
      </button>
      <button onClick={() => props.selectMentionCallback(trigger + "mention")}>
        Select `{ trigger }mention`
      </button>
      CustomizedTagComponent!!!

  );
}

export default class ReactRoot extends Component {

  componentDidMount () {
    const MediumEditor = require("medium-editor");
    const TCMention = require("../../../src").TCMention;

    this.editor = new MediumEditor(this.refs.editable, {
      extensions: {
        "mention": new TCMention({
          extraPanelClassName: "abc123",
          extraActivePanelClassName: "xyz",
          extraTriggerClassNameMap: {
            "#": "IUHGYJH",
          },
          extraActiveTriggerClassNameMap: {
            "@": "gabdsf",
          },
          tagName: "b",
          renderPanelContent: function (panelEl, currentMentionText, selectMentionCallback) {
            ReactDOM.render((
              <CustomizedTagComponent
                currentMentionText={currentMentionText}
                selectMentionCallback={selectMentionCallback}
              />
            ), panelEl);
          },
          destroyPanelContent: function (panelEl) {
            ReactDOM.unmountComponentAtNode(panelEl);
          },
          activeTriggerList: ["#", "@"]
        })
      }
    });
  }

  render () {
    return (

        <GitHubForkRibbon
          position="right"
          color="black"
          href="https://github.com/tomchentw/medium-editor-tc-mention">
          Fork me on GitHub
        </GitHubForkRibbon>

Medium Editor

My father’s family name being Pirrip, and my Christian name Philip, my infant tongue could make of both names nothing longer or more explicit than Pip. So, I called myself Pip, and came to be called Pip.

I give Pirrip as my father’s family name, on the authority of his tombstone and my sister,—Mrs. Joe Gargery, who married the blacksmith. As I never saw my father or my mother, and never saw any likeness of either of them (for their days were long before the days of photographs), my first fancies regarding what they were like were unreasonably derived from their tombstones. The shape of the letters on my father’s, gave me an odd idea that he was a square, stout, dark man, with curly black hair. From the character and turn of the inscription, “Also Georgiana Wife of the Above,” I drew a childish conclusion that my mother was freckled and sickly. To five little stone lozenges, each about a foot and a half long, which were arranged in a neat row beside their grave, and were sacred to the memory of five little brothers of mine,—who gave up trying to get a living, exceedingly early in that universal struggle,—I am indebted for a belief I religiously entertained that they had all been born on their backs with their hands in their trousers-pockets, and had never taken them out in this state of existence.

Ours was the marsh country, down by the river, within, as the river wound, twenty miles of the sea. My first most vivid and broad impression of the identity of things seems to me to have been gained on a memorable raw afternoon towards evening. At such a time I found out for certain that this bleak place overgrown with nettles was the churchyard; and that Philip Pirrip, late of this parish, and also Georgiana wife of the above, were dead and buried; and that Alexander, Bartholomew, Abraham, Tobias, and Roger, infant children of the aforesaid, were also dead and buried; and that the dark flat wilderness beyond the churchyard, intersected with dikes and mounds and gates, with scattered cattle feeding on it, was the marshes; and that the low leaden line beyond was the river; and that the distant savage lair from which the wind was rushing was the sea; and that the small bundle of shivers growing afraid of it all and beginning to cry, was Pip.

    );
  }
}
<|endoftext|>


<commit_before>define(['angular', 'lodash',  'directives/checkbox'], function(angular, _ ) {'use strict';
    var Dropbox;

    return ['$scope', '$http', 'documents','$rootScope', 'allowBack','$window', function ($scope, $http, documents,$rootScope, allowBack,$window) {

    if(!$scope.viewOnly)
      require(['dropbox-dropins'],function(val){
        Dropbox = val;
      })
		var publicComputer    = true; // TODO
		var signedInToDropbox = false;

		$scope.close            = close;
		$scope.documents        = documents;
		$scope.allowBack        = allowBack;
		$scope.languages        = _(documents).map('files').flatten().map('language').uniq().sortBy().value();
		$scope.formats          = _(documents).map('files').flatten().map('type'  ).uniq().sortBy().value();
		$scope.selectedLanguages= {};
		$scope.selectedFormats  = {};
        $scope.canDropbox       = canDropbox;
        $scope.sendToDropbox    = sendToDropbox;
    $scope.download        = download

		if($scope.languages.length==1) $scope.selectedLanguages[$scope.languages[0]] = true;
		if($scope.formats  .length==1) $scope.selectedFormats[$scope.formats[0]] = true;

		$scope.$watch('selectedFormats', initDownloadLink, true);
		$scope.$watch('selectedLanguages', initDownloadLink, true);

    if($scope.viewOnly) {
      $window.addEventListener('message', closeDialogRemote)
      $scope.$on('$destroy', function(){
        $window.removeEventListener('message', closeDialogRemote)
      });
    }

		if(canDropbox && publicComputer)
			signoutDropbox();

		//==============================================
		//
		//
		//==============================================
		function initDownloadLink()	{

			delete $scope.success;
			delete $scope.downloadLink;

			var urls = selectedLinks();

			if(urls.length) {

				$http.post('/api/v2014/printsmart-downloads', urls).then(function(res){
					$scope.downloadLink = '/api/v2014/printsmart-downloads/'+res.data._id;
				}).catch(function(err){
					console.error(err);
				});
			}
		}

    function download(event){

      if($scope.viewOnly ) {
        $scope.success='download'
        event.preventDefault()
        event.stopPropagation()
        console.log(selectedLinks(true))
        $window.parent.postMessage({type:'saveFiles',data:selectedLinks(true)},'*');
      } else if(!$scope.downloadLink){
        event.preventDefault()
        event.stopPropagation()
      }

    }
        //==============================================
        //
        //
        //==============================================
        function logDownloadHit(urls) {

            if(urls && urls.length) {
                $http.post('/api/v2014/printsmart-downloads/hit', urls);
            }
        }

		//==============================================
		//
		//
		//==============================================
		function selectedLinks(allProps) {

            return _(documents).map(function(doc){
                if(allProps) {
                  return _(doc.files||[])
                      .filter(function(f){ return $scope.selectedLanguages[f.language] && $scope.selectedFormats[f.type]; })
                      .value()
                }
                return _(doc.files||[])
                    .filter(function(f){ return $scope.selectedLanguages[f.language] && $scope.selectedFormats[f.type]; })
                    .pluck('url')
                    .value();
            }).flatten()
              .compact()
              .uniq()
              .value();
		}

		//==============================================
		//
		//
		//==============================================
		function canDropbox() {

			return !$scope.viewOnly && Dropbox && Dropbox.isBrowserSupported();
		}

		//==============================================
		//
		//
		//==============================================
		function sendToDropbox() {

			$scope.success = null;

            var urls  = selectedLinks();
			var files = _.map(urls, function(url) { return { url : url }; });

			if(!files.length)
				return;

			signedInToDropbox = true;

			var started = false;

			Dropbox.save({
			    files : files,
			    progress : function () {

					if(started)
						return;

					started = true;

					$scope.$applyAsync(function() {
						$scope.success = 'dropbox';
                        logDownloadHit(urls);
					});
				},
			    error : function (errorMessage) {

					console.error('DROPBOX ERROR', errorMessage);

					$scope.$applyAsync(function() {
						$scope.error = {
							error   : 'DROPBOX',
							message : errorMessage
						};
					});
				}
			});
		}

		//==============================================
		//
		//
		//==============================================
		function signoutDropbox() {

			angular.element('body').append('');
		}

    //==============================================
		//
		//
		//==============================================
    function closeDialogRemote(event) {

      var msg = event.data

      if(msg && typeof msg === 'string' && /^(\{|\[)/.test(msg))) {

        msg = JSON.parse(msg)

        if(msg.type === 'closeDialogRemote')
          $scope.closeThisDialog($scope.success && 'clear');
      }
		}

		//==============================================
		//
		//
		//==============================================
		function close(target) {

			if(signedInToDropbox && publicComputer)
				signoutDropbox();

            $scope.closeThisDialog(target);
		}
	}];
});
<commit_msg>Remove extra parenthesis <commit_after>define(['angular', 'lodash',  'directives/checkbox'], function(angular, _ ) {'use strict';
    var Dropbox;

    return ['$scope', '$http', 'documents','$rootScope', 'allowBack','$window', function ($scope, $http, documents,$rootScope, allowBack,$window) {

    if(!$scope.viewOnly)
      require(['dropbox-dropins'],function(val){
        Dropbox = val;
      })
		var publicComputer    = true; // TODO
		var signedInToDropbox = false;

		$scope.close            = close;
		$scope.documents        = documents;
		$scope.allowBack        = allowBack;
		$scope.languages        = _(documents).map('files').flatten().map('language').uniq().sortBy().value();
		$scope.formats          = _(documents).map('files').flatten().map('type'  ).uniq().sortBy().value();
		$scope.selectedLanguages= {};
		$scope.selectedFormats  = {};
        $scope.canDropbox       = canDropbox;
        $scope.sendToDropbox    = sendToDropbox;
    $scope.download        = download

		if($scope.languages.length==1) $scope.selectedLanguages[$scope.languages[0]] = true;
		if($scope.formats  .length==1) $scope.selectedFormats[$scope.formats[0]] = true;

		$scope.$watch('selectedFormats', initDownloadLink, true);
		$scope.$watch('selectedLanguages', initDownloadLink, true);

    if($scope.viewOnly) {
      $window.addEventListener('message', closeDialogRemote)
      $scope.$on('$destroy', function(){
        $window.removeEventListener('message', closeDialogRemote)
      });
    }

		if(canDropbox && publicComputer)
			signoutDropbox();

		//==============================================
		//
		//
		//==============================================
		function initDownloadLink()	{

			delete $scope.success;
			delete $scope.downloadLink;

			var urls = selectedLinks();

			if(urls.length) {

				$http.post('/api/v2014/printsmart-downloads', urls).then(function(res){
					$scope.downloadLink = '/api/v2014/printsmart-downloads/'+res.data._id;
				}).catch(function(err){
					console.error(err);
				});
			}
		}

    function download(event){

      if($scope.viewOnly ) {
        $scope.success='download'
        event.preventDefault()
        event.stopPropagation()
        console.log(selectedLinks(true))
        $window.parent.postMessage({type:'saveFiles',data:selectedLinks(true)},'*');
      } else if(!$scope.downloadLink){
        event.preventDefault()
        event.stopPropagation()
      }

    }
        //==============================================
        //
        //
        //==============================================
        function logDownloadHit(urls) {

            if(urls && urls.length) {
                $http.post('/api/v2014/printsmart-downloads/hit', urls);
            }
        }

		//==============================================
		//
		//
		//==============================================
		function selectedLinks(allProps) {

            return _(documents).map(function(doc){
                if(allProps) {
                  return _(doc.files||[])
                      .filter(function(f){ return $scope.selectedLanguages[f.language] && $scope.selectedFormats[f.type]; })
                      .value()
                }
                return _(doc.files||[])
                    .filter(function(f){ return $scope.selectedLanguages[f.language] && $scope.selectedFormats[f.type]; })
                    .pluck('url')
                    .value();
            }).flatten()
              .compact()
              .uniq()
              .value();
		}

		//==============================================
		//
		//
		//==============================================
		function canDropbox() {

			return !$scope.viewOnly && Dropbox && Dropbox.isBrowserSupported();
		}

		//==============================================
		//
		//
		//==============================================
		function sendToDropbox() {

			$scope.success = null;

            var urls  = selectedLinks();
			var files = _.map(urls, function(url) { return { url : url }; });

			if(!files.length)
				return;

			signedInToDropbox = true;

			var started = false;

			Dropbox.save({
			    files : files,
			    progress : function () {

					if(started)
						return;

					started = true;

					$scope.$applyAsync(function() {
						$scope.success = 'dropbox';
                        logDownloadHit(urls);
					});
				},
			    error : function (errorMessage) {

					console.error('DROPBOX ERROR', errorMessage);

					$scope.$applyAsync(function() {
						$scope.error = {
							error   : 'DROPBOX',
							message : errorMessage
						};
					});
				}
			});
		}

		//==============================================
		//
		//
		//==============================================
		function signoutDropbox() {

			angular.element('body').append('');
		}

    //==============================================
		//
		//
		//==============================================
    function closeDialogRemote(event) {

      var msg = event.data

      if(msg && typeof msg === 'string' && /^(\{|\[)/.test(msg)) {

        msg = JSON.parse(msg)

        if(msg.type === 'closeDialogRemote')
          $scope.closeThisDialog($scope.success && 'clear');
      }
		}

		//==============================================
		//
		//
		//==============================================
		function close(target) {

			if(signedInToDropbox && publicComputer)
				signoutDropbox();

            $scope.closeThisDialog(target);
		}
	}];
});
<|endoftext|>


<commit_before>function initProjectEditor(options) {
    var editor = new gbi.Editor({
       map: {
            element: 'map',
            numZoomLevels : numZoomLevels,
            theme: OpenlayersThemeURL
        },
        imgPath: OpenlayersImageURL
    });
    editor.addLayer(backgroundLayer)

    var layermanager = new gbi.widgets.LayerManager(editor, {
        tiny: true,
        showActiveLayer: false
    });
    editor.widgets = {
        'layermanager': layermanager
    };

    if (options.toolbar) {
        new gbi.Toolbar(editor, {
            element: 'toolbar',
            tools: {
                'drawPolygon': true,
                'drawRect': true,
                'edit': true,
                'delete': true
            }
        });
    }

    // vectorlayer for drawing
    var drawLayer = new gbi.Layers.Vector({
        name: 'Draw Layer',
        styleMap: styleMap,
        displayInLayerSwitcher: false,
        eventListeners: {
            featureadded: function(f) {
                if (!drawLayer.loading) {
                    toggleStartButton(editor);
                    getDataVolume(editor);
                }
            },
            featuresadded: function() {
                toggleStartButton(editor);
            },
            featureremoved: function(f) {
                if (f.feature) {
                    f.feature.destroy();
                }
                getDataVolume(editor)
                toggleStartButton(editor);
            },
            featuresremoved: function() {
                toggleStartButton(editor);
            },
            afterfeaturemodified: function(feature) {
                if (feature.modified) {
                    getDataVolume(editor)
                }
            }
        }

    });
    editor.addLayer(drawLayer);
    editor.layerManager.active(drawLayer);
    editor.map.olMap.addControl(new OpenLayers.Control.ZoomStatus({
        prefix: '
Level: ',
        suffix: '
'
    }));
    editor.map.center();

    return editor;
}

function deleteAllFeatures(editor) {
    var drawLayer = editor.layerManager.active();
    drawLayer.olLayer.removeAllFeatures();
    drawLayer.features = [];
    getDataVolume(editor);
    return false;
}

function loadFeatures(editor, data, complete) {
    var drawLayer = editor.layerManager.active();
    drawLayer.loading = true;
    var parser = new OpenLayers.Format.GeoJSON();

    if (jQuery.isArray(data) && complete == true) {
        drawLayer.addFeatures(data);
    } else if (jQuery.isArray(data)) {
       $.each(data, function(index, geom) {
            // check if data is geojson or openlayers.features e.g. from couch layer
            if (geom.CLASS_NAME && geom.CLASS_NAME == 'OpenLayers.Feature.Vector') {
                drawLayer.addFeatures(geom);
            } else {
                drawLayer.addFeatures(parser.read(geom.geometry));
            }
       });
    } else {
        featureCollection = parser.read(data);
        if (featureCollection)
            drawLayer.addFeatures(featureCollection);
    }
    if (drawLayer.olLayer.features.length > 0) {
        editor.map.olMap.zoomToExtent(drawLayer.olLayer.getDataExtent());
    }
    getDataVolume(editor);
    drawLayer.loading = false;
}<commit_msg>Reduced event listeners<commit_after>function initProjectEditor(options) {
    var editor = new gbi.Editor({
       map: {
            element: 'map',
            numZoomLevels : numZoomLevels,
            theme: OpenlayersThemeURL
        },
        imgPath: OpenlayersImageURL
    });
    editor.addLayer(backgroundLayer)

    var layermanager = new gbi.widgets.LayerManager(editor, {
        tiny: true,
        showActiveLayer: false
    });
    editor.widgets = {
        'layermanager': layermanager
    };

    if (options.toolbar) {
        new gbi.Toolbar(editor, {
            element: 'toolbar',
            tools: {
                'drawPolygon': true,
                'drawRect': true,
                'edit': true,
                'delete': true
            }
        });
    }

    // vectorlayer for drawing
    var drawLayer = new gbi.Layers.Vector({
        name: 'Draw Layer',
        styleMap: styleMap,
        displayInLayerSwitcher: false,
        eventListeners: {
            featuresadded: function(f) {
                getDataVolume(editor)
                toggleStartButton(editor);
            },
            featuresremoved: function(f) {
                getDataVolume(editor)
                toggleStartButton(editor);
            },
            afterfeaturemodified: function(feature) {
                if (feature.modified) {
                    getDataVolume(editor)
                }
            }
        }
    });
    editor.addLayer(drawLayer);
    editor.layerManager.active(drawLayer);
    editor.map.olMap.addControl(new OpenLayers.Control.ZoomStatus({
        prefix: '
Level: ',
        suffix: '
'
    }));
    editor.map.center();

    return editor;
}

function deleteAllFeatures(editor) {
    var drawLayer = editor.layerManager.active();
    drawLayer.olLayer.removeAllFeatures();
    drawLayer.features = [];
    getDataVolume(editor);
    return false;
}

function loadFeatures(editor, data, complete) {
    var drawLayer = editor.layerManager.active();
    drawLayer.loading = true;
    var parser = new OpenLayers.Format.GeoJSON();

    if (jQuery.isArray(data) && complete == true) {
        drawLayer.addFeatures(data);
    } else if (jQuery.isArray(data)) {
       $.each(data, function(index, geom) {
            // check if data is geojson or openlayers.features e.g. from couch layer
            if (geom.CLASS_NAME && geom.CLASS_NAME == 'OpenLayers.Feature.Vector') {
                drawLayer.addFeatures(geom);
            } else {
                drawLayer.addFeatures(parser.read(geom.geometry));
            }
       });
    } else {
        featureCollection = parser.read(data);
        if (featureCollection)
            drawLayer.addFeatures(featureCollection);
    }
    if (drawLayer.olLayer.features.length > 0) {
        editor.map.olMap.zoomToExtent(drawLayer.olLayer.getDataExtent());
    }
    getDataVolume(editor);
    drawLayer.loading = false;
}<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true, nonpropdel: true */
/*global require, ArangoConnection, SYS_ARANGO */

////////////////////////////////////////////////////////////////////////////////
/// @brief module "internal"
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2013 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 Module "internal"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

(function () {
  var internal = require("internal");

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief hide global variables
////////////////////////////////////////////////////////////////////////////////

    if (typeof ArangoConnection !== "undefined") {
      internal.ArangoConnection = ArangoConnection;
      delete ArangoConnection;
    }

    if (typeof SYS_ARANGO !== "undefined") {
      internal.arango = SYS_ARANGO;
      delete SYS_ARANGO;
    }

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief flushes the module cache of the server
////////////////////////////////////////////////////////////////////////////////

  internal.flushServerModules = function () {
    if (typeof internal.arango !== 'undefined') {
      internal.arango.POST("/_admin/modules/flush", "");
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the routing cache
////////////////////////////////////////////////////////////////////////////////

  internal.reloadRouting = function () {
    if (typeof internal.arango !== 'undefined') {
      internal.arango.POST("/_admin/routing/reload", "");
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the routing cache
////////////////////////////////////////////////////////////////////////////////

  internal.routingCache = function () {
    var result;

    if (typeof internal.arango !== 'undefined') {
      result = internal.arango.GET("/_admin/routing/routes", "");
    }

    return result;
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the authentication cache
////////////////////////////////////////////////////////////////////////////////

  internal.reloadAuth = function () {
    if (typeof internal.arango !== 'undefined') {
      internal.arango.POST("/_admin/auth/reload", "");
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief logs a request in curl format
////////////////////////////////////////////////////////////////////////////////

  internal.appendCurlRequest = function (appender) {
    return function (method, url, body) {
      var response;
      var curl;

      if (typeof body !== 'string') {
        body = JSON.stringify(body);
      }

      curl = "unix> curl ";

      if (method === 'POST') {
        response = internal.arango.POST_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'PUT') {
        response = internal.arango.PUT_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'GET') {
        response = internal.arango.GET_RAW(url, body);
      }
      else if (method === 'DELETE') {
        response = internal.arango.DELETE_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'PATCH') {
        response = internal.arango.PATCH_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'OPTION') {
        response = internal.arango.OPTION_RAW(url, body);
        curl += "-X " + method + " ";
      }

      if (body !== "") {
        curl += "--data @- ";
      }

      curl += "--dump - http://localhost:8529" + url;

      appender(curl + "\n");

      if (body !== "") {
        appender(body += "\n");
      }

      appender("\n");

      return response;
    };
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief logs a response in JSON
////////////////////////////////////////////////////////////////////////////////

  internal.appendJsonResponse = function (appender) {
    return function (response) {
      var key;
      var headers = response.headers;
      var output;

      // generate header
      appender("HTTP/1.1 " + headers['http/1.1'] + "\n");

      for (key in headers) {
        if (key === 'http/1.1' || key === 'server' || key === 'connection'
           || key === 'content-length') {
          continue;
        }

        if (headers.hasOwnProperty(key)) {
          appender(key + ": " + headers[key] + "\n");
        }
      }

      appender("\n");

      // pretty print body
      internal.startCaptureMode();
      print(JSON.parse(response.body));
      output = internal.stopCaptureMode();
      appender(output);
      appender("\n");
    };
  };

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief log function
////////////////////////////////////////////////////////////////////////////////

  internal.log = function (level, msg) {
    internal.output(level, ": ", msg, "\n");
  };

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

}());

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\|/\\*jslint"
// End:
<commit_msg>shut up jslint<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true, nonpropdel: true */
/*global require, ArangoConnection, print, SYS_ARANGO */

////////////////////////////////////////////////////////////////////////////////
/// @brief module "internal"
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2013 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 Module "internal"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

(function () {
  var internal = require("internal");

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief hide global variables
////////////////////////////////////////////////////////////////////////////////

    if (typeof ArangoConnection !== "undefined") {
      internal.ArangoConnection = ArangoConnection;
      delete ArangoConnection;
    }

    if (typeof SYS_ARANGO !== "undefined") {
      internal.arango = SYS_ARANGO;
      delete SYS_ARANGO;
    }

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief flushes the module cache of the server
////////////////////////////////////////////////////////////////////////////////

  internal.flushServerModules = function () {
    if (typeof internal.arango !== 'undefined') {
      internal.arango.POST("/_admin/modules/flush", "");
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the routing cache
////////////////////////////////////////////////////////////////////////////////

  internal.reloadRouting = function () {
    if (typeof internal.arango !== 'undefined') {
      internal.arango.POST("/_admin/routing/reload", "");
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the routing cache
////////////////////////////////////////////////////////////////////////////////

  internal.routingCache = function () {
    var result;

    if (typeof internal.arango !== 'undefined') {
      result = internal.arango.GET("/_admin/routing/routes", "");
    }

    return result;
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the authentication cache
////////////////////////////////////////////////////////////////////////////////

  internal.reloadAuth = function () {
    if (typeof internal.arango !== 'undefined') {
      internal.arango.POST("/_admin/auth/reload", "");
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief logs a request in curl format
////////////////////////////////////////////////////////////////////////////////

  internal.appendCurlRequest = function (appender) {
    return function (method, url, body) {
      var response;
      var curl;

      if (typeof body !== 'string') {
        body = JSON.stringify(body);
      }

      curl = "unix> curl ";

      if (method === 'POST') {
        response = internal.arango.POST_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'PUT') {
        response = internal.arango.PUT_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'GET') {
        response = internal.arango.GET_RAW(url, body);
      }
      else if (method === 'DELETE') {
        response = internal.arango.DELETE_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'PATCH') {
        response = internal.arango.PATCH_RAW(url, body);
        curl += "-X " + method + " ";
      }
      else if (method === 'OPTION') {
        response = internal.arango.OPTION_RAW(url, body);
        curl += "-X " + method + " ";
      }

      if (body !== "") {
        curl += "--data @- ";
      }

      curl += "--dump - http://localhost:8529" + url;

      appender(curl + "\n");

      if (body !== "") {
        appender(body += "\n");
      }

      appender("\n");

      return response;
    };
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief logs a response in JSON
////////////////////////////////////////////////////////////////////////////////

  internal.appendJsonResponse = function (appender) {
    return function (response) {
      var key;
      var headers = response.headers;
      var output;

      // generate header
      appender("HTTP/1.1 " + headers['http/1.1'] + "\n");

      for (key in headers) {
        if (headers.hasOwnProperty(key)) {
          if (key !== 'http/1.1' && key !== 'server' && key !== 'connection'
              && key !== 'content-length') {
            appender(key + ": " + headers[key] + "\n");
          }
        }
      }

      appender("\n");

      // pretty print body
      internal.startCaptureMode();
      print(JSON.parse(response.body));
      output = internal.stopCaptureMode();
      appender(output);
      appender("\n");
    };
  };

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief log function
////////////////////////////////////////////////////////////////////////////////

  internal.log = function (level, msg) {
    internal.output(level, ": ", msg, "\n");
  };

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

}());

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\|/\\*jslint"
// End:
<|endoftext|>


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

	return ["api", function(api) {

		return {

			restrict: 'A',

			transclude: true,

			templateUrl: "/partials/content/QuestionTabs.html",

			link: function(scope, element, attrs, ctrls, transclude) {

				if (scope.accordionChildMetrics) {
					scope.accordionChildMetrics.questionCount++;
				}

				if (scope.doc.bestAttempt) {
					scope.validationResponse = scope.doc.bestAttempt;
					scope.selectedChoice = scope.validationResponse.answer;
				} else {

					// We have to explicitly initialise to null so that the
					// validationResponse watcher fires on the question. This
					// can allow it to remove the accordion watcher.

					scope.validationResponse = null;
				}
				scope.validationResponseSet = true;

				scope.activateTab = function(i) {
					scope.activeTab = i;
					rv.updateAll();

					if (i > -1) {
						api.logger.log({
							type : "VIEW_HINT",
							questionId : scope.doc.id,
							hintIndex : i,
						})
					}
				}

				scope.activateTab(-1); // Activate "Answer now" tab by default.

				// prevent undefined errors when we don't know which gameboard a person is working on.
				if(scope.gameBoard){
					scope.state.gameBoardCompletedPassed = false;
					scope.state.gameBoardCompletedPerfect = false;
				}

				scope.checkAnswer = function() {
					if (scope.selectedChoice != null) {

						if (scope.doc.type == "isaacSymbolicQuestion") {
							var symbols = JSON.parse(scope.selectedChoice.value).symbols;
							if (Object.keys(symbols).length == 0) {
								return;
							}
						}

						var s = api.questionValidator.validate({id: scope.doc.id}, scope.selectedChoice);

						s.$promise.then(function foo(r) {
							scope.validationResponse = r;

							// Check the gameboard progress
							if (scope.gameBoard) {
								// Re-load the game board to check for updated progress
								var initialGameBoardPercent = scope.gameBoard.percentageCompleted;
								var gameBoardCompletedPassed =  true;
								var gameBoardCompletedPerfect =  true;

								api.gameBoards.get({id: scope.gameBoard.id}).$promise.then(function(board) {
									scope.state.gameBoardPercentComplete = board.percentageCompleted;

									//We want to know if they have (a) completed the gameboard, (b) passed the gameboard
									for(var i = 0; i < board.questions.length; i++){
										if(board.questions[i].state != "PERFECT" ){
											gameBoardCompletedPerfect = false;
										}
										if(board.questions[i].state != "PASSED" && board.questions[i].state != "PERFECT"){
											gameBoardCompletedPassed = false;
										}
									}

									// If things have changed, and the answer is correct, show the modal
									if ((gameBoardCompletedPassed != !!scope.state.gameBoardCompletedPassed ||
									   gameBoardCompletedPerfect != !!scope.state.gameBoardCompletedPerfect ||
									   initialGameBoardPercent < board.percentageCompleted) && r.correct) {
										scope.state.gameBoardCompletedPassed = gameBoardCompletedPassed;
										scope.state.gameBoardCompletedPerfect = gameBoardCompletedPerfect;
										scope.modals["congrats"].show();
									}

									// NOTE: We can't just rely on percentageCompleted as it gives us 100% when there is one
									// question for a gameboard and the question has been passed, not completed. See issue #419

								});
							}

						}, function bar(e) {
							console.error("Error validating answer:", e);
						});

					} else {
						// TODO: Somehow tell the user that they need to choose an option before clicking Check.
					}
				}

				scope.$watch("selectedChoice", function(newVal, oldVal) {
					if (newVal === oldVal)
						return; // Init

					delete scope.validationResponse;
				}, true);

				// Prevent the transcluded template from getting a new child scope - attach it to our scope.
				transclude(scope, function(clone, scope) {
					element.find(".transclude-here").append(clone);
				})

				scope.$on("ensureVisible", function(e) {
					if (e.targetScope == scope)
						return;

					e.stopPropagation();

					var i = e.targetScope.questionTabIndex;

					scope.activateTab(i);

					scope.$emit("ensureVisible");
				});

			}
		};
	}];
});<commit_msg>Avoid rage clicking by ensuring answer has changed before accepting a new one (needs thorough testing), also display toast popup for any server error received!<commit_after>/**
 * Copyright 2014 Ian Davies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define(["app/honest/responsive_video"], function(rv) {

	return ["api", function(api) {

		return {

			restrict: 'A',

			transclude: true,

			templateUrl: "/partials/content/QuestionTabs.html",

			link: function(scope, element, attrs, ctrls, transclude) {

				scope.previousAnswerChoice = null;

				if (scope.accordionChildMetrics) {
					scope.accordionChildMetrics.questionCount++;
				}

				if (scope.doc.bestAttempt) {
					scope.validationResponse = scope.doc.bestAttempt;
					scope.selectedChoice = scope.validationResponse.answer;
				} else {

					// We have to explicitly initialise to null so that the
					// validationResponse watcher fires on the question. This
					// can allow it to remove the accordion watcher.

					scope.validationResponse = null;
				}
				scope.validationResponseSet = true;

				scope.activateTab = function(i) {
					scope.activeTab = i;
					rv.updateAll();

					if (i > -1) {
						api.logger.log({
							type : "VIEW_HINT",
							questionId : scope.doc.id,
							hintIndex : i,
						})
					}
				}

				scope.activateTab(-1); // Activate "Answer now" tab by default.

				// prevent undefined errors when we don't know which gameboard a person is working on.
				if(scope.gameBoard){
					scope.state.gameBoardCompletedPassed = false;
					scope.state.gameBoardCompletedPerfect = false;
				}

				scope.checkAnswer = function() {
					if (scope.selectedChoice != null && scope.selectedChoice != scope.previousAnswerChoice) {
						scope.previousAnswerChoice = scope.selectedChoice;

						if (scope.doc.type == "isaacSymbolicQuestion") {
							var symbols = JSON.parse(scope.selectedChoice.value).symbols;
							if (Object.keys(symbols).length == 0) {
								return;
							}
						}

						var s = api.questionValidator.validate({id: scope.doc.id}, scope.selectedChoice);

						s.$promise.then(function foo(r) {
							scope.validationResponse = r;

							// Check the gameboard progress
							if (scope.gameBoard) {
								// Re-load the game board to check for updated progress
								var initialGameBoardPercent = scope.gameBoard.percentageCompleted;
								var gameBoardCompletedPassed =  true;
								var gameBoardCompletedPerfect =  true;

								api.gameBoards.get({id: scope.gameBoard.id}).$promise.then(function(board) {
									scope.state.gameBoardPercentComplete = board.percentageCompleted;

									//We want to know if they have (a) completed the gameboard, (b) passed the gameboard
									for(var i = 0; i < board.questions.length; i++){
										if(board.questions[i].state != "PERFECT" ){
											gameBoardCompletedPerfect = false;
										}
										if(board.questions[i].state != "PASSED" && board.questions[i].state != "PERFECT"){
											gameBoardCompletedPassed = false;
										}
									}

									// If things have changed, and the answer is correct, show the modal
									if ((gameBoardCompletedPassed != !!scope.state.gameBoardCompletedPassed ||
									   gameBoardCompletedPerfect != !!scope.state.gameBoardCompletedPerfect ||
									   initialGameBoardPercent < board.percentageCompleted) && r.correct) {
										scope.state.gameBoardCompletedPassed = gameBoardCompletedPassed;
										scope.state.gameBoardCompletedPerfect = gameBoardCompletedPerfect;
										scope.modals["congrats"].show();
									}

									// NOTE: We can't just rely on percentageCompleted as it gives us 100% when there is one
									// question for a gameboard and the question has been passed, not completed. See issue #419

								});
							}

						}, function bar(e) {
							console.error("Error validating answer:", e);
							scope.showToast(scope.toastTypes.Failure, "Can't Submit Answer", e.data.errorMessage != undefined ? e.data.errorMessage : "");
						});

					} else {
						// TODO: Somehow tell the user that they need to choose an option before clicking Check.
					}
				}

				scope.$watch("selectedChoice", function(newVal, oldVal) {
					if (newVal === oldVal)
						return; // Init

					delete scope.validationResponse;
				}, true);

				// Prevent the transcluded template from getting a new child scope - attach it to our scope.
				transclude(scope, function(clone, scope) {
					element.find(".transclude-here").append(clone);
				})

				scope.$on("ensureVisible", function(e) {
					if (e.targetScope == scope)
						return;

					e.stopPropagation();

					var i = e.targetScope.questionTabIndex;

					scope.activateTab(i);

					scope.$emit("ensureVisible");
				});

			}
		};
	}];
});<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * Abstract base type for accordion box that displays the interactive equation and related controls.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const AccordionBox = require( 'SUN/AccordionBox' );
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const HSeparator = require( 'SUN/HSeparator' );
  const SaveEraseButtons = require( 'GRAPHING_QUADRATICS/common/view/SaveEraseButtons' );
  const Tandem = require( 'TANDEM/Tandem' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  class EquationAccordionBox extends AccordionBox {

    /**
     * @param {ExploreModel} model
     * @param {BooleanProperty} expandedProperty
     * @param {Node} titleNode
     * @param {Node} content
     * @param {Object} [options]
     * @abstract
     */
    constructor( model, expandedProperty, titleNode, content, options ) {

      options = _.extend( {
        tandem: Tandem.required
      }, GQConstants.ACCORDION_BOX_OPTIONS, options );

      assert && assert( !options.expandedProperty, 'EquationAccordionBox sets expandedProperty' );
      options.expandedProperty = expandedProperty;

      assert && assert( !options.titleNode, 'EquationAccordionBox sets titleNode' );
      options.titleNode = titleNode;

      const saveEraseButtons = new SaveEraseButtons(
        model.saveQuadratic.bind( model ),
        model.eraseQuadratic.bind( model ),
        model.savedQuadraticProperty, {
          tandem: options.tandem.createTandem( 'saveEraseButtons' ),
          phetioInstanceDocumentation: 'buttons to save and erase a quadratic on the graph'
        } );

      const separatorWidth = Math.max( content.width, saveEraseButtons.width );

      const separatorOptions = { stroke: GQColors.SEPARATOR };

      const vBox = new VBox( {
        align: 'center',
        spacing: 10,
        children: [
          new HSeparator( separatorWidth, separatorOptions ),
          content,
          new HSeparator( separatorWidth, separatorOptions ),
          saveEraseButtons
        ]
      } );

      super( vBox, options );
    }
  }

  return graphingQuadratics.register( 'EquationAccordionBox', EquationAccordionBox );
} );<commit_msg>reduce spacing in VBox to gain a few pixels for F&D screen<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * Abstract base type for accordion box that displays the interactive equation and related controls.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const AccordionBox = require( 'SUN/AccordionBox' );
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const HSeparator = require( 'SUN/HSeparator' );
  const SaveEraseButtons = require( 'GRAPHING_QUADRATICS/common/view/SaveEraseButtons' );
  const Tandem = require( 'TANDEM/Tandem' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  class EquationAccordionBox extends AccordionBox {

    /**
     * @param {ExploreModel} model
     * @param {BooleanProperty} expandedProperty
     * @param {Node} titleNode
     * @param {Node} content
     * @param {Object} [options]
     * @abstract
     */
    constructor( model, expandedProperty, titleNode, content, options ) {

      options = _.extend( {
        tandem: Tandem.required
      }, GQConstants.ACCORDION_BOX_OPTIONS, options );

      assert && assert( !options.expandedProperty, 'EquationAccordionBox sets expandedProperty' );
      options.expandedProperty = expandedProperty;

      assert && assert( !options.titleNode, 'EquationAccordionBox sets titleNode' );
      options.titleNode = titleNode;

      const saveEraseButtons = new SaveEraseButtons(
        model.saveQuadratic.bind( model ),
        model.eraseQuadratic.bind( model ),
        model.savedQuadraticProperty, {
          tandem: options.tandem.createTandem( 'saveEraseButtons' ),
          phetioInstanceDocumentation: 'buttons to save and erase a quadratic on the graph'
        } );

      const separatorWidth = Math.max( content.width, saveEraseButtons.width );

      const separatorOptions = { stroke: GQColors.SEPARATOR };

      const vBox = new VBox( {
        align: 'center',
        spacing: 8,
        children: [
          new HSeparator( separatorWidth, separatorOptions ),
          content,
          new HSeparator( separatorWidth, separatorOptions ),
          saveEraseButtons
        ]
      } );

      super( vBox, options );
    }
  }

  return graphingQuadratics.register( 'EquationAccordionBox', EquationAccordionBox );
} );<|endoftext|>