<commit_before>document.app = {
    debug: false,
    parameters: [],

    log: function (message) {
        if (document.app.debug)
            console.log(message);
    },

    createAgenda: function () {
        [].forEach.call(document.getElementsByClassName("agenda"), function (agenda) {
            function getTitle(slideIndex) {
                var slide = document.app.slides[slideIndex];
                if (slide.dataset.title != undefined &&
                    !slide.dataset.title.endsWith(" cont.") &&
                    !(slideIndex > 0 && slide.dataset.title == document.app.slides[slideIndex - 1].dataset.title))
                    return (slideIndex + 1) + ". " + slide.dataset.title;
                else {
                    return undefined;
                }
            }
            var list = document.createElement("ol");
            agenda.appendChild(list);
            var indexOfAgenda = document.app.slides.indexOf(agenda);
            [].forEach.call(document.app.slides, function (slide, index) {
                if (index <= indexOfAgenda ||
                    slide.classList.contains("title") ||
                    slide.childElementCount == 0)
                    return;
                var title = getTitle(index)
                if (title == undefined)
                    return;
                var entry = document.createElement("a");
                entry.href = "javascript:document.app.switcher.setSlide(" + index + ")";
                entry.textContent = title;
                list.appendChild(entry);
            });
        });
    },

    initCodeHighlighting: function () {
        hljs.configure({
            languages: ["csharp "]
        });
        if (document.location.host.startsWith("127.0.0.1"))
            return;
        var codes = document.getElementsByTagName("code");
        for (i = 0; i < codes.length; i++) {
            codes[i].classList.add("language-csharp");
            hljs.highlightBlock(codes[i]);
            codes[i].classList.remove("hljs");
        }
    },

    addTotalNumberOfSlidesToCounter: function () {
        var style = document.createElement('style');
        style.textContent = `section::after { content: counter(slide) "/${document.app.slides.length}"; }`;
        document.head.appendChild(style);
    },

    switchToDarkStyle: function () {
        if (document.app.parameters.indexOf("light") < 0) {
            var style = document.createElement('style');
            style.textContent = `
                body {
                    --background-color: #151515;
                    --content-color: white;
                }

                section[data-title]:before, section h1,
                section:empty::before, .shout {
                    background: transparent;
                    color: var(--content-color);
                    font-family: inherit;
                    font-weight: 100;
                    font-size: 3em;
                    padding-left: 0;
                }

                section {
                    background: transparent;
                }

                section:empty,
                section.title,
                section.full-background {
                    background: var(--background-color) url('images/background-blurred.svg');
                }

                section code {
                    border: none;
                    padding: 1em 0;
                    background: transparent;
                }

                section code .hljs-meta {
                    color: #a16fff;
                }

                section code .hljs-title {
                    color: #2b92ff;
                }

                section code .hljs-comment {
                    color: #58ff58;
                }

                section code .hljs-string,
                section code .hljs-number,
                section code .hljs-literal {
                    color: #ff5a5a;
                }

                .shout {
                    font-size: 4em;
                }`;
            document.head.appendChild(style);
            Array.prototype.slice.call(document.getElementsByTagName("img")).forEach(function (img) {
                if (!img.classList.contains("preserve-colors"))
                    img.style.filter = "invert(100%)";
            });
        }
    },

    addFootnotes: function () {
        document.app.slides.forEach(function (slide) {
            var footnotes = document.createElement("footer");
            footnotes.classList.add("footnotes");
            Array.prototype.slice.call(slide.querySelectorAll("*[data-footnote]")).forEach(function (hyperlink) {
                var footnote = document.createElement("a");
                footnote.href = hyperlink.href;
                footnote.textContent = hyperlink.dataset.footnote;
                footnotes.appendChild(footnote);
            });
            if (footnotes.childElementCount > 0)
                slide.appendChild(footnotes);
        });
    },

    loadParameters: function () {
        document.location.search.substr(1).split("&").forEach(function (param) {
            if (param.length > 0) {
                document.app.parameters.push(param);
                document.body.classList.add(param);
            }
        });
    },

    setupDebugging: function () {
        if (document.app.parameters.indexOf("debug") >= 0) {
            document.app.debug = true;
            var consoleView = document.createElement("div");
            consoleView.id = "consoleView";
            consoleView.style.position = "fixed";
            consoleView.style.bottom = "0";
            consoleView.style.left = "0";
            consoleView.style.padding = "2em";
            consoleView.style.font = "14px monospace";
            consoleView.style.color = "black";
            consoleView.style.background = "rgba(255,255,255,0.8)";
            document.body.appendChild(consoleView);
            var oldLog = console.log;
            console.log = function () {
                consoleView.innerHTML += Array.prototype.slice.call(arguments).join(" ") + "
";
                oldLog.apply(console, arguments);
            };
        }
    },

    switcher: {
        onswitch: function (id) {},

        activeSlideId: 0,

        isScrollingBack: function (event) {
            var backScrollingKeys = ["ArrowUp", "ArrowLeft", "PageUp"];
            return (event instanceof WheelEvent && event.deltaY < 0) ||
                (event instanceof KeyboardEvent && backScrollingKeys.indexOf(event.key) >= 0) ||
                (event instanceof TouchEvent &&
                    (event.changedTouches[0].clientY - document.app.switcher.touchStart.y > 0 ||
                        document.app.switcher.touchStart.x - event.changedTouches[0].clientX < 0));
        },

        setSlide: function (id) {
            document.app.switcher.activeSlideId = id;
            document.app.slides[id].scrollIntoView(true);
            document.app.switcher.onswitch(id);
            document.app.updateProgressbar();
        },

        onSlideChange: function (event) {
            document.app.log(`document.app.switcher.onSlideChange(${event.type})`);
            var newSlide = document.app.switcher.activeSlideId + (document.app.switcher.isScrollingBack(event) ? -1 : 1);
            if (newSlide >= document.app.slides.length)
                newSlide = 0;
            else if (newSlide < 0)
                newSlide = document.app.slides.length - 1;
            document.app.switcher.setSlide(newSlide);
        },

        init: function () {
            document.body.addEventListener("click", document.app.switcher.onSlideChange);
            document.body.addEventListener("wheel", document.app.switcher.onSlideChange);
            document.body.addEventListener("keydown", document.app.switcher.onSlideChange);
            document.body.addEventListener("touchstart", function (event) {
                document.app.switcher.touchStart = {
                    x: event.touches[0].clientX,
                    y: event.touches[0].clientY
                }
            });
            document.body.addEventListener("touchend", document.app.switcher.onSlideChange);
        }
    },

    progressbar: undefined,

    timeLengthMinutes: 30,
    startTime: undefined,

    initProgressbar: function () {
        if (document.app.parameters.indexOf("progress") > -1) {
            document.app.slides.forEach(function (slide) {
                // var svgNS = "http://www.w3.org/2000/svg";
                // var progressbar = document.createElementNS(svgNS, "svg");
                // progressbar.classList.add("progressbar");
                // progressbar.setAttributeNS(svgNS, "viewBox", "0 0 100 100");
                // var path = document.createElementNS(svgNS, "path");
                // progressbar.appendChild(path);
                // slide.appendChild(progressbar);
                // ABOVE DOES NOT RENDER IN CHROME, UGLY HACK INSTEAD
                slide.innerHTML += '<svg class="progressbar" viewBox="0 0 100 100"><path></path></svg>';
            });
            document.app.startTime = new Date().getTime();
            document.app.updateProgressbar = function () {
                var minutesElapsed = (new Date().getTime() - document.app.startTime) / 1000 / 60;
                var progress = minutesElapsed / document.app.timeLengthMinutes;
                if (progress >= 1) {
                    progress = 1;
                    clearInterval(loop);
                }
                document.body.style.setProperty("--progress", progress);

                var slideCount = document.app.slides.length;
                var slideProgress = document.app.switcher.activeSlideId / slideCount;
                var progressColor;
                if (slideProgress < progress - (1/slideCount))
                    progressColor = "blue";
                else if (slideProgress > progress + (1/slideCount))
                    progressColor = "red";
                else
                    progressColor = "rgb(128,128,128)";
                document.body.style.setProperty("--progress-color", progressColor);
            }
            var loop = setInterval(document.app.updateProgressbar, 60*1000);
        }
    },

    turnBgOn: function() {
        if (document.app.parameters.indexOf("image-bg") < 0)
            return;
        var style = document.createElement('style');
        style.textContent = `
            body {
                background: url(https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-507918.jpg);
                background-size: 100vw 100vh;
                background-attachment: fixed;
            }
            section {
                background: transparent !important;
            }`;
        document.head.appendChild(style);
    },

    init: function () {
        document.app.slides = Array.prototype.slice.call(document.getElementsByTagName("section"));
        document.app.createAgenda();
        document.app.initCodeHighlighting();
        document.app.addTotalNumberOfSlidesToCounter();
        document.app.addFootnotes();
        document.app.loadParameters();
        document.app.setupDebugging();
        document.app.switcher.init();
        document.app.initProgressbar();
        document.app.switchToDarkStyle();
        document.app.turnBgOn();
    }
}

window.addEventListener("load", document.app.init);
<commit_msg>Dimmed progress counter when progress is optimal<commit_after>document.app = {
    debug: false,
    parameters: [],

    log: function (message) {
        if (document.app.debug)
            console.log(message);
    },

    createAgenda: function () {
        [].forEach.call(document.getElementsByClassName("agenda"), function (agenda) {
            function getTitle(slideIndex) {
                var slide = document.app.slides[slideIndex];
                if (slide.dataset.title != undefined &&
                    !slide.dataset.title.endsWith(" cont.") &&
                    !(slideIndex > 0 && slide.dataset.title == document.app.slides[slideIndex - 1].dataset.title))
                    return (slideIndex + 1) + ". " + slide.dataset.title;
                else {
                    return undefined;
                }
            }
            var list = document.createElement("ol");
            agenda.appendChild(list);
            var indexOfAgenda = document.app.slides.indexOf(agenda);
            [].forEach.call(document.app.slides, function (slide, index) {
                if (index <= indexOfAgenda ||
                    slide.classList.contains("title") ||
                    slide.childElementCount == 0)
                    return;
                var title = getTitle(index)
                if (title == undefined)
                    return;
                var entry = document.createElement("a");
                entry.href = "javascript:document.app.switcher.setSlide(" + index + ")";
                entry.textContent = title;
                list.appendChild(entry);
            });
        });
    },

    initCodeHighlighting: function () {
        hljs.configure({
            languages: ["csharp "]
        });
        if (document.location.host.startsWith("127.0.0.1"))
            return;
        var codes = document.getElementsByTagName("code");
        for (i = 0; i < codes.length; i++) {
            codes[i].classList.add("language-csharp");
            hljs.highlightBlock(codes[i]);
            codes[i].classList.remove("hljs");
        }
    },

    addTotalNumberOfSlidesToCounter: function () {
        var style = document.createElement('style');
        style.textContent = `section::after { content: counter(slide) "/${document.app.slides.length}"; }`;
        document.head.appendChild(style);
    },

    switchToDarkStyle: function () {
        if (document.app.parameters.indexOf("light") < 0) {
            var style = document.createElement('style');
            style.textContent = `
                body {
                    --background-color: #151515;
                    --content-color: white;
                }

                section[data-title]:before, section h1,
                section:empty::before, .shout {
                    background: transparent;
                    color: var(--content-color);
                    font-family: inherit;
                    font-weight: 100;
                    font-size: 3em;
                    padding-left: 0;
                }

                section {
                    background: transparent;
                }

                section:empty,
                section.title,
                section.full-background {
                    background: var(--background-color) url('images/background-blurred.svg');
                }

                section code {
                    border: none;
                    padding: 1em 0;
                    background: transparent;
                }

                section code .hljs-meta {
                    color: #a16fff;
                }

                section code .hljs-title {
                    color: #2b92ff;
                }

                section code .hljs-comment {
                    color: #58ff58;
                }

                section code .hljs-string,
                section code .hljs-number,
                section code .hljs-literal {
                    color: #ff5a5a;
                }

                .shout {
                    font-size: 4em;
                }`;
            document.head.appendChild(style);
            Array.prototype.slice.call(document.getElementsByTagName("img")).forEach(function (img) {
                if (!img.classList.contains("preserve-colors"))
                    img.style.filter = "invert(100%)";
            });
        }
    },

    addFootnotes: function () {
        document.app.slides.forEach(function (slide) {
            var footnotes = document.createElement("footer");
            footnotes.classList.add("footnotes");
            Array.prototype.slice.call(slide.querySelectorAll("*[data-footnote]")).forEach(function (hyperlink) {
                var footnote = document.createElement("a");
                footnote.href = hyperlink.href;
                footnote.textContent = hyperlink.dataset.footnote;
                footnotes.appendChild(footnote);
            });
            if (footnotes.childElementCount > 0)
                slide.appendChild(footnotes);
        });
    },

    loadParameters: function () {
        document.location.search.substr(1).split("&").forEach(function (param) {
            if (param.length > 0) {
                document.app.parameters.push(param);
                document.body.classList.add(param);
            }
        });
    },

    setupDebugging: function () {
        if (document.app.parameters.indexOf("debug") >= 0) {
            document.app.debug = true;
            var consoleView = document.createElement("div");
            consoleView.id = "consoleView";
            consoleView.style.position = "fixed";
            consoleView.style.bottom = "0";
            consoleView.style.left = "0";
            consoleView.style.padding = "2em";
            consoleView.style.font = "14px monospace";
            consoleView.style.color = "black";
            consoleView.style.background = "rgba(255,255,255,0.8)";
            document.body.appendChild(consoleView);
            var oldLog = console.log;
            console.log = function () {
                consoleView.innerHTML += Array.prototype.slice.call(arguments).join(" ") + "
";
                oldLog.apply(console, arguments);
            };
        }
    },

    switcher: {
        onswitch: function (id) {},

        activeSlideId: 0,

        isScrollingBack: function (event) {
            var backScrollingKeys = ["ArrowUp", "ArrowLeft", "PageUp"];
            return (event instanceof WheelEvent && event.deltaY < 0) ||
                (event instanceof KeyboardEvent && backScrollingKeys.indexOf(event.key) >= 0) ||
                (event instanceof TouchEvent &&
                    (event.changedTouches[0].clientY - document.app.switcher.touchStart.y > 0 ||
                        document.app.switcher.touchStart.x - event.changedTouches[0].clientX < 0));
        },

        setSlide: function (id) {
            document.app.switcher.activeSlideId = id;
            document.app.slides[id].scrollIntoView(true);
            document.app.switcher.onswitch(id);
            document.app.updateProgressbar();
        },

        onSlideChange: function (event) {
            document.app.log(`document.app.switcher.onSlideChange(${event.type})`);
            var newSlide = document.app.switcher.activeSlideId + (document.app.switcher.isScrollingBack(event) ? -1 : 1);
            if (newSlide >= document.app.slides.length)
                newSlide = 0;
            else if (newSlide < 0)
                newSlide = document.app.slides.length - 1;
            document.app.switcher.setSlide(newSlide);
        },

        init: function () {
            document.body.addEventListener("click", document.app.switcher.onSlideChange);
            document.body.addEventListener("wheel", document.app.switcher.onSlideChange);
            document.body.addEventListener("keydown", document.app.switcher.onSlideChange);
            document.body.addEventListener("touchstart", function (event) {
                document.app.switcher.touchStart = {
                    x: event.touches[0].clientX,
                    y: event.touches[0].clientY
                }
            });
            document.body.addEventListener("touchend", document.app.switcher.onSlideChange);
        }
    },

    progressbar: undefined,

    timeLengthMinutes: 30,
    startTime: undefined,

    initProgressbar: function () {
        if (document.app.parameters.indexOf("progress") > -1) {
            document.app.slides.forEach(function (slide) {
                // var svgNS = "http://www.w3.org/2000/svg";
                // var progressbar = document.createElementNS(svgNS, "svg");
                // progressbar.classList.add("progressbar");
                // progressbar.setAttributeNS(svgNS, "viewBox", "0 0 100 100");
                // var path = document.createElementNS(svgNS, "path");
                // progressbar.appendChild(path);
                // slide.appendChild(progressbar);
                // ABOVE DOES NOT RENDER IN CHROME, UGLY HACK INSTEAD
                slide.innerHTML += '<svg class="progressbar" viewBox="0 0 100 100"><path></path></svg>';
            });
            document.app.startTime = new Date().getTime();
            document.app.updateProgressbar = function () {
                var minutesElapsed = (new Date().getTime() - document.app.startTime) / 1000 / 60;
                var progress = minutesElapsed / document.app.timeLengthMinutes;
                if (progress >= 1) {
                    progress = 1;
                    clearInterval(loop);
                }
                document.body.style.setProperty("--progress", progress);

                var slideCount = document.app.slides.length;
                var slideProgress = document.app.switcher.activeSlideId / slideCount;
                var progressColor;
                if (slideProgress < progress - (1/slideCount))
                    progressColor = "blue";
                else if (slideProgress > progress + (1/slideCount))
                    progressColor = "red";
                else
                    progressColor = "rgba(128,128,128, 0.2)";
                document.body.style.setProperty("--progress-color", progressColor);
            }
            var loop = setInterval(document.app.updateProgressbar, 60*1000);
        }
    },

    turnBgOn: function() {
        if (document.app.parameters.indexOf("image-bg") < 0)
            return;
        var style = document.createElement('style');
        style.textContent = `
            body {
                background: url(https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-507918.jpg);
                background-size: 100vw 100vh;
                background-attachment: fixed;
            }
            section {
                background: transparent !important;
            }`;
        document.head.appendChild(style);
    },

    init: function () {
        document.app.slides = Array.prototype.slice.call(document.getElementsByTagName("section"));
        document.app.createAgenda();
        document.app.initCodeHighlighting();
        document.app.addTotalNumberOfSlidesToCounter();
        document.app.addFootnotes();
        document.app.loadParameters();
        document.app.setupDebugging();
        document.app.switcher.init();
        document.app.initProgressbar();
        document.app.switchToDarkStyle();
        document.app.turnBgOn();
    }
}

window.addEventListener("load", document.app.init);
<|endoftext|>


<commit_before>import React, { useState } from 'react';
import {
  useInput,
  useNonNativeInput,
} from './hooks/useInput';
import TextInput from './TextInput';
import ArtistInput from './ArtistInput';
import TabEditor from './TabEditor';

import './TabForm.scss';

const tabPlaceholder = `e|-------------
B|-------------
G|-------------
D|-------------
A|-------------
E|-------------
`;

function TabForm({
onSave,
...props
}) {
  const { value: title, bind: bindTitle } = useInput(props.title || "");
  const { value: artist, bind: bindArtist } = useNonNativeInput(props.artist || {id: null, name: ""});
  const { value: tab, bind: bindTab } = useNonNativeInput(props.tab || tabPlaceholder);
  const [codeMirrorInstance, setCodeMirrorInstance] = useState(null);
  const [overwriting, setOverwriting] = useState(false);

  const onToggleOverwrite = event => {
    event.preventDefault();

    const willBeOverwriting = !overwriting;

    setOverwriting(willBeOverwriting);
    codeMirrorInstance.toggleOverwrite(willBeOverwriting);

    if (willBeOverwriting) {
      codeMirrorInstance.on('beforeChange', onOverwritingBeforeChange);
    } else {
      // TODO: does not correctly remove the event handler
      //       checking `editor.state.overwrite` in onOverwritingBeforeChange as workaround
      codeMirrorInstance.off('beforeChange', null);
    }
  };

  const onOverwritingBeforeChange = (editor, data) => {
    if (!editor.state.overwrite) return;

    const { from, to, cancel, origin } = data;
    const deleting = origin === "+delete";
    const selecting = from.line !== to.line || to.ch - from.ch > (deleting && from.sticky === 1 ? 1 : 0);

    if (deleting && !selecting) {
      const lines = editor.doc.children[0].lines;
      const line = lines[from.line].text;
      const lastChar = line.charAt(from.ch);
      const cursorMovementOnly = from.ch === 0 || ['-', '\n', '', '|'].indexOf(lastChar) > -1;

      cancel();

      if (cursorMovementOnly) {
        if (lastChar === '-') {
          editor.execCommand('goColumnLeft');
        }
      } else {
        editor.doc.replaceRange("-", from, to);
        editor.execCommand('goColumnLeft');
      }
    }
  };

  const onSubmit = event => {
    event.preventDefault();

    return onSave({title, artist, tab});
  };

  return(
    <form onSubmit={onSubmit} className="tab-form">

          <TextInput
            required
            placeholder="tab song title"
            {...bindTitle}
          />

          <ArtistInput
            required
            placeholder="artist of song"
            {...bindArtist}
          />

        <button
          className={`btn-primary ${overwriting ? 'toggled' : ''}`}
          onClick={onToggleOverwrite}
        >
          overwriting {`${overwriting ? 'ON' : 'OFF'}`}
        </button>

        <TabEditor
          {...bindTab}
          overwriting={overwriting}
          codeMirrorInstance={codeMirrorInstance}
          setCodeMirrorInstance={setCodeMirrorInstance}
        />

        <input
          className="btn-primary"
          type="submit"
          value="save"
        />

    </form>
  );
}

export default TabForm;
<commit_msg>adds temp workaround for event on/off issues<commit_after>import React, { useState } from 'react';
import {
  useInput,
  useNonNativeInput,
} from './hooks/useInput';
import TextInput from './TextInput';
import ArtistInput from './ArtistInput';
import TabEditor from './TabEditor';

import './TabForm.scss';

const tabPlaceholder = `e|-------------
B|-------------
G|-------------
D|-------------
A|-------------
E|-------------
`;

function TabForm({
onSave,
...props
}) {
  const { value: title, bind: bindTitle } = useInput(props.title || "");
  const { value: artist, bind: bindArtist } = useNonNativeInput(props.artist || {id: null, name: ""});
  const { value: tab, bind: bindTab } = useNonNativeInput(props.tab || tabPlaceholder);
  const [codeMirrorInstance, setCodeMirrorInstance] = useState(null);
  const [overwriting, setOverwriting] = useState(false);

  const initialSetCodeMirrorInstance = instance => {
    setCodeMirrorInstance(instance);
    instance.on('beforeChange', onOverwritingBeforeChange);
  };

  const onToggleOverwrite = event => {
    event.preventDefault();

    const willBeOverwriting = !overwriting;

    setOverwriting(willBeOverwriting);
    codeMirrorInstance.toggleOverwrite(willBeOverwriting);
  };

  const onOverwritingBeforeChange = (editor, data) => {
    if (!editor.state.overwrite) return;

    const { from, to, cancel, origin } = data;
    const deleting = origin === "+delete";
    const selecting = from.line !== to.line || to.ch - from.ch > (deleting && from.sticky === 1 ? 1 : 0);

    if (deleting && !selecting) {
      const lines = editor.doc.children[0].lines;
      const line = lines[from.line].text;
      const lastChar = line.charAt(from.ch);
      const cursorMovementOnly = from.ch === 0 || ['-', '\n', '', '|'].indexOf(lastChar) > -1;

      cancel();

      if (cursorMovementOnly) {
        if (lastChar === '-') {
          editor.execCommand('goColumnLeft');
        }
      } else {
        editor.doc.replaceRange("-", from, to);
        editor.execCommand('goColumnLeft');
      }
    }
  };

  const onSubmit = event => {
    event.preventDefault();

    return onSave({title, artist, tab});
  };

  return(
    <form onSubmit={onSubmit} className="tab-form">

          <TextInput
            required
            placeholder="tab song title"
            {...bindTitle}
          />

          <ArtistInput
            required
            placeholder="artist of song"
            {...bindArtist}
          />

        <button
          className={`btn-primary ${overwriting ? 'toggled' : ''}`}
          onClick={onToggleOverwrite}
        >
          overwriting {`${overwriting ? 'ON' : 'OFF'}`}
        </button>

        <TabEditor
          {...bindTab}
          overwriting={overwriting}
          codeMirrorInstance={codeMirrorInstance}
          setCodeMirrorInstance={initialSetCodeMirrorInstance}
        />

        <input
          className="btn-primary"
          type="submit"
          value="save"
        />

    </form>
  );
}

export default TabForm;
<|endoftext|>


<commit_before>import React from 'react';
import Sidebar from './components/Sidebar';
import './App.css';
import axios from 'axios';

import {
  apiConstants
} from './constants/constants';
const {
  baseURL,
  apiKey,
  userName,
  getMethod
} = apiConstants;

let App = React.createClass ({

  getInitialState: function() {
    return {
      user: []
    };
  },

  componentDidMount() {
    let getUserInfo = axios.create({
      getMethod,
      baseURL,
      url: `?format=json&method=user.getinfo&user=${userName}&api_key=${apiKey}`
    });
    getUserInfo()
    .then((user) => {
      this.setState({
        user: user.data.user
      });
    });
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render() {
    let user = this.state.user;
    return (

        <Sidebar
          user={user} />
        {this.props.children}

    );
  }
});

App.propTypes = {
  state: React.PropTypes.shape({}),
  children: React.PropTypes.node.isRequired
};

export default App;
<commit_msg>Destucture object<commit_after>import React from 'react';
import Sidebar from './components/Sidebar';
import './App.css';
import axios from 'axios';

import {
  apiConstants
} from './constants/constants';
const {
  baseURL,
  apiKey,
  userName,
  getMethod
} = apiConstants;

let App = React.createClass ({

  getInitialState: function() {
    return {
      user: []
    };
  },

  componentDidMount() {
    let getUserInfo = axios.create({
      getMethod,
      baseURL,
      url: `?format=json&method=user.getinfo&user=${userName}&api_key=${apiKey}`
    });
    getUserInfo()
    .then((user) => {
      this.setState({ user } = user.data);
    });
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render() {
    let user = this.state.user;
    return (

        <Sidebar
          user={user} />
        {this.props.children}

    );
  }
});

App.propTypes = {
  state: React.PropTypes.shape({}),
  children: React.PropTypes.node.isRequired
};

export default App;
<|endoftext|>


<commit_before>// @flow

const { logger } = require('@lagoon/commons/src/local-logging');
const { sendToLagoonLogs } = require('@lagoon/commons/src/logs');
const { createDeployTask } = require('@lagoon/commons/src/tasks');
const R = require('ramda');

import type { WebhookRequestData, deployData, ChannelWrapper, Project  } from '../types';

async function gitlabPush(webhook: WebhookRequestData, project: Project) {

    const {
      webhooktype,
      event,
      giturl,
      uuid,
      body,
    } = webhook;

    const branchName = body.ref.toLowerCase().replace('refs/heads/','')
    const sha = body.after

    const skip_deploy = R.pathOr('',['commits',0,'message'], body).match(/\[skip deploy\]|\[deploy skip\]/i)

    const meta = {
      branch: branchName,
      sha: sha
    }

    const data: deployData = {
      projectName: project.name,
      type: 'branch',
      branchName: branchName,
      sha: sha,
    }

    let logMessage = `\`<${body.project.http_url}/tree/${meta.branch}|${meta.branch}>\``
    if (sha && (body.commits.length > 0)) {
      const shortSha: string = sha.substring(0, 7)
      logMessage = `${logMessage} (<${body.commits[0].url}|${shortSha}>)`
    }

    if (skip_deploy) {
      sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:skipped`, meta,
        `*[${project.name}]* ${logMessage} pushed in <${body.repository.html_url}|${body.repository.full_name}> *deployment skipped*`
      )
      return;
    }

    try {
      const taskResult = await createDeployTask(data);
      sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handled`, meta,
        `*[${project.name}]* ${logMessage} pushed in <${body.project.http_url}|${body.project.path_with_namespace}>`
      )
      return;
    } catch (error) {
      switch (error.name) {
        case "ProjectNotFound":
        case "NoActiveSystemsDefined":
        case "UnknownActiveSystem":
        case "NoNeedToDeployBranch":
          // These are not real errors and also they will happen many times. We just log them locally but not throw an error
          sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handledButNoTask`, meta,
            `*[${project.name}]* ${logMessage}. No deploy task created, reason: ${error}`
          )
          return;

        default:
          // Other messages are real errors and should reschedule the message in RabbitMQ in order to try again
          throw error
      }
    }

}

module.exports = gitlabPush;
<commit_msg>#700 - add needed data to meta object<commit_after>// @flow

const { logger } = require('@lagoon/commons/src/local-logging');
const { sendToLagoonLogs } = require('@lagoon/commons/src/logs');
const { createDeployTask } = require('@lagoon/commons/src/tasks');
const R = require('ramda');

import type { WebhookRequestData, deployData, ChannelWrapper, Project  } from '../types';

async function gitlabPush(webhook: WebhookRequestData, project: Project) {

    const {
      webhooktype,
      event,
      giturl,
      uuid,
      body,
    } = webhook;

    const branchName = body.ref.toLowerCase().replace('refs/heads/','')
    const sha = body.after

    const skip_deploy = R.pathOr('',['commits',0,'message'], body).match(/\[skip deploy\]|\[deploy skip\]/i)

    const meta = {
      branch: branchName,
      sha: sha,
      shortSha: sha.substring(0, 7),
      repoName: body.project.name,
      pathWithNamespace: body.project.path_with_namespace,
      repoUrl: body.project.http_url,
      branchName: branchName,
      commitUrl: body.commits[0].url,
      event: event,
    }

    const data: deployData = {
      projectName: project.name,
      type: 'branch',
      branchName: branchName,
      sha: sha,
    }

    let logMessage = `\`<${body.project.http_url}/tree/${meta.branch}|${meta.branch}>\``
    if (sha && (body.commits.length > 0)) {
      const shortSha: string = sha.substring(0, 7)
      logMessage = `${logMessage} (<${body.commits[0].url}|${shortSha}>)`
    }

    if (skip_deploy) {
      sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:skipped`, meta,
        `*[${project.name}]* ${logMessage} pushed in <${body.repository.html_url}|${body.repository.full_name}> *deployment skipped*`
      )
      return;
    }

    try {
      const taskResult = await createDeployTask(data);
      sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handled`, meta,
        `*[${project.name}]* ${logMessage} pushed in <${body.project.http_url}|${body.project.path_with_namespace}>`
      )
      return;
    } catch (error) {
      switch (error.name) {
        case "ProjectNotFound":
        case "NoActiveSystemsDefined":
        case "UnknownActiveSystem":
        case "NoNeedToDeployBranch":
          // These are not real errors and also they will happen many times. We just log them locally but not throw an error
          sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handledButNoTask`, meta,
            `*[${project.name}]* ${logMessage}. No deploy task created, reason: ${error}`
          )
          return;

        default:
          // Other messages are real errors and should reschedule the message in RabbitMQ in order to try again
          throw error
      }
    }

}

module.exports = gitlabPush;
<|endoftext|>


<commit_before>angular.module('huntEdu.controllers')
    .controller('JobListingCtrl',['$scope', '$location', '$http', '$q', 'job',
        function ($scope, $location, $http, $q, job){

            $scope.$on('$routeChangeError', function() {
                $location.path('/searchError');
            });

            $scope.$on('$routeChangeSuccess', function(){
                $scope.jobListingData = job;
                $scope.hasVideo = job.hasVideo();
                $scope.hasImage = job.hasImage();
            });

            /**
             * Save a job as a bookmark
             */

            $scope.saveBookmark = function (){
                var jobId = job.meta.id;
                var deferred = $q.defer();
                $http.post('/bookmark/add', { 'id' : jobId })
                    .then(function(data){
                        deferred.resolve();
                    }, function(err){
                        deferred.reject();
                    });
                return deferred.promise;
            };
    }]);
<commit_msg>Fixed lint errors and added hide bookmark model<commit_after>angular.module('huntEdu.controllers')
    .controller('JobListingCtrl',['$scope', '$location', '$http', '$q', 'User', 'job',
        function ($scope, $location, $http, $q, User, job){

            $scope.$on('$routeChangeError', function() {
                $location.path('/searchError');
            });

            $scope.$on('$routeChangeSuccess', function(){
                $scope.jobListingData = job;
                $scope.hasVideo = job.hasVideo();
                $scope.hasImage = job.hasImage();
            });

            $scope.hideSaveBookmarkBtn = User.isLoggedIn();

            /**
             * Save a job as a bookmark
             */

            $scope.saveBookmark = function (){
                var jobId = job.meta.id;
                var deferred = $q.defer();
                $http.post('/bookmark/add', { 'id' : jobId })
                    .then(function(){
                        deferred.resolve();
                    }, function(){
                        deferred.reject();
                    });
                console.log(User.getProfileData());
                return deferred.promise;
            };
    }]);
<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

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.
*/

'use strict';

var React = require('react');
var MatrixClientPeg = require("../../../../../src/MatrixClientPeg");
var ComponentBroker = require('../../../../../src/ComponentBroker');
var MCallHangupTileController = require("../../../../../src/controllers/molecules/voip/MCallHangupTile");
var MessageTimestamp = ComponentBroker.get('atoms/MessageTimestamp');

module.exports = React.createClass({
    displayName: 'MCallHangupTile',
    mixins: [MCallHangupTileController],

    getHangupText: function(event) {
        var senderName = event.sender ? event.sender.name : "Someone";
        return senderName + " hung up.";
    },

    render: function() {
        // XXX: for now, just cheekily borrow the css from message tile...
        return (

                <MessageTimestamp ts={this.props.mxEvent.getTs()} />

                    {this.getHangupText(this.props.mxEvent)}

        );
    },
});

<commit_msg>'ended the call' kinda handles both cancelled and 'hung up'<commit_after>/*
Copyright 2015 OpenMarket Ltd

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.
*/

'use strict';

var React = require('react');
var MatrixClientPeg = require("../../../../../src/MatrixClientPeg");
var ComponentBroker = require('../../../../../src/ComponentBroker');
var MCallHangupTileController = require("../../../../../src/controllers/molecules/voip/MCallHangupTile");
var MessageTimestamp = ComponentBroker.get('atoms/MessageTimestamp');

module.exports = React.createClass({
    displayName: 'MCallHangupTile',
    mixins: [MCallHangupTileController],

    getHangupText: function(event) {
        var senderName = event.sender ? event.sender.name : "Someone";
        return senderName + " ended the call.";
    },

    render: function() {
        // XXX: for now, just cheekily borrow the css from message tile...
        return (

                <MessageTimestamp ts={this.props.mxEvent.getTs()} />

                    {this.getHangupText(this.props.mxEvent)}

        );
    },
});

<|endoftext|>


<commit_before>$(function () {
    $(document).on('blur', '.control-markdown', function () {
        var $viewer = $('[id="' + this.id + '.viewer"]');
        $viewer.html('' + getMarkedUp($(this).val()) + '');
        resizeEditor($(this), $viewer);
        switchControlMode($viewer, false);
    });
    $(document).on('paste', '.upload-image', function (e) {
        if (e.originalEvent.clipboardData !== undefined) {
            var items = e.originalEvent.clipboardData.items;
            for (var i = 0 ; i < items.length ; i++) {
                var item = items[i];
                if (item.type.indexOf('image') !== -1) {
                    var data = new FormData();
                    data.append('Images_Bin', item.getAsFile());
                    requestFile('/images/create', 'post', data);
                }
            }
        }
    });
});

var title_regex = /\[[^\]]+\]/i;
var url_regex_t = /(\[[^\]]+\]\(\b(https?|ftp):\/\/((?!\*|"|<|>|\||>|<).)+)/gi;
var url_regex = /(\b(https?|ftp):\/\/((?!\*|"|<|>|\||>|<).)+"?)/gi;
var unc_regex_t = /(\[[^\]]+\]\(\B\\\\((?!:|\*|"|<|>|\||>|<).)+\\((?!:|\*|"|<|>|\||>|<).)+\))/gi;
var unc_regex = /(\B\\\\((?!:|\*|"|<|>|\||>|<).)+\\((?!:|\*|"|<|>|\||>|<).)+"?)/gi;

function getMarkedUp(markdownValue, encoded) {
    var text = markdownValue;
    if (!encoded) text = getEncordedHtml(text);
    return getMarkedUpHtml(text)
        .replace(url_regex_t, function ($1) {
            return '' +
                cutBrackets($1.match(title_regex)[0], 1) +
                '';
        })
        .replace(url_regex, function ($1) {
            return $1.slice(-1) != '"'
                ? '' + $1 + ''
                : $1;
        })
        .replace(unc_regex_t, function ($1) {
            return '' +
                cutBrackets($1.match(title_regex)[0], 1) +
                '';
        })
        .replace(unc_regex, function ($1) {
            return $1.slice(-1) != '"'
                ? '' + $1 + ''
                : $1;
        });
}

function cutBrackets(str, start)
{
    return str.substring(start, str.length - 1);
}

function getMarkedUpHtml(markdownValue) {
    var paragraphsNumber = [0, 0, 0, 0, 0];
    var paragraphLevel = 0;
    var beforeIndex = 0;
    var header = false;
    var inSection = false;
    var $elements = $('
')
    markdownValue.split(/\r\n|\r|\n/).forEach(function (e) {
        paragraphLevel = /^\++|^\*+|^\+*/.exec(e)[0].length;
        var index = paragraphLevel - 1;
        var tag = 'h' + (paragraphLevel + 1);
        if (0 < paragraphLevel && paragraphLevel < 6) {
            var paragraphType = e.substring(0, 1);
            if (index < beforeIndex) {
                paragraphsNumber[beforeIndex] = 0;
            }
            if (paragraphType === '+') {
                paragraphsNumber[index]++;
            }
            $elements
                .append($('
').addClass(tag)
                    .append($('<' + tag + '/>').text(
                        joinParagraphNumber(paragraphType, paragraphsNumber, index) +
                        e.substring(paragraphLevel)))
                    .append($('
').addClass('paragraph')));
            beforeIndex = index;
            header = true;
            inSection = true;
        }
        else {
            if (!header && $elements.length > 0) {
                $elements.find('.paragraph').filter(':last').append($('
'));
            }
            if ($elements.find('.paragraph').length !== 0) {
                $elements.find('.paragraph').filter(':last').append(e);
            }
            else {
                $elements.append(e).append($('
'));
            }
            header = false;
        }
    });
    return $elements[0].outerHTML;
}

function getEncordedHtml(value) {
    return $('
').text(value).html();
}

function getGeneralId($self) {
    var controlId = $self.attr('id');
    return controlId.indexOf('.') === -1
        ? controlId
        : controlId.substring(0, controlId.indexOf('.'));
}

function switchControlMode($self, toEdit) {
    var id = getGeneralId($self);
    $('[id="' + id + '.viewer"]').toggle(!toEdit);
    $('[id="' + id + '.edit"]').toggle(!toEdit);
    $('[id="' + id + '"]').toggle(toEdit);
}

function joinParagraphNumber(paragraphType, paragraphsNumber, paragraphLevel) {
    if (paragraphType === '+') {
        var sum = [];
        for (var i = 0; i <= paragraphLevel; ++i) {
            sum[i] = paragraphsNumber[i];
        }
        return sum.join('.') + '. ';
    }
    else {
        return '';
    }
}

function resizeEditor(editor, $viewer) {
    if ($viewer.height() <= 300) {
        editor.height($viewer.height());
    }
    else {
        editor.height(300);
    }
}<commit_msg>URLリンクを別のタブで開く仕様に変更。<commit_after>$(function () {
    $(document).on('blur', '.control-markdown', function () {
        var $viewer = $('[id="' + this.id + '.viewer"]');
        $viewer.html('' + getMarkedUp($(this).val()) + '');
        resizeEditor($(this), $viewer);
        switchControlMode($viewer, false);
    });
    $(document).on('paste', '.upload-image', function (e) {
        if (e.originalEvent.clipboardData !== undefined) {
            var items = e.originalEvent.clipboardData.items;
            for (var i = 0 ; i < items.length ; i++) {
                var item = items[i];
                if (item.type.indexOf('image') !== -1) {
                    var data = new FormData();
                    data.append('Images_Bin', item.getAsFile());
                    requestFile('/images/create', 'post', data);
                }
            }
        }
    });
});

var title_regex = /\[[^\]]+\]/i;
var url_regex_t = /(\[[^\]]+\]\(\b(https?|ftp):\/\/((?!\*|"|<|>|\||>|<).)+)/gi;
var url_regex = /(\b(https?|ftp):\/\/((?!\*|"|<|>|\||>|<).)+"?)/gi;
var unc_regex_t = /(\[[^\]]+\]\(\B\\\\((?!:|\*|"|<|>|\||>|<).)+\\((?!:|\*|"|<|>|\||>|<).)+\))/gi;
var unc_regex = /(\B\\\\((?!:|\*|"|<|>|\||>|<).)+\\((?!:|\*|"|<|>|\||>|<).)+"?)/gi;

function getMarkedUp(markdownValue, encoded) {
    var text = markdownValue;
    if (!encoded) text = getEncordedHtml(text);
    return getMarkedUpHtml(text)
        .replace(url_regex_t, function ($1) {
            return '' +
                cutBrackets($1.match(title_regex)[0], 1) +
                '';
        })
        .replace(url_regex, function ($1) {
            return $1.slice(-1) != '"'
                ? '' + $1 + ''
                : $1;
        })
        .replace(unc_regex_t, function ($1) {
            return '' +
                cutBrackets($1.match(title_regex)[0], 1) +
                '';
        })
        .replace(unc_regex, function ($1) {
            return $1.slice(-1) != '"'
                ? '' + $1 + ''
                : $1;
        });
}

function cutBrackets(str, start)
{
    return str.substring(start, str.length - 1);
}

function getMarkedUpHtml(markdownValue) {
    var paragraphsNumber = [0, 0, 0, 0, 0];
    var paragraphLevel = 0;
    var beforeIndex = 0;
    var header = false;
    var inSection = false;
    var $elements = $('
')
    markdownValue.split(/\r\n|\r|\n/).forEach(function (e) {
        paragraphLevel = /^\++|^\*+|^\+*/.exec(e)[0].length;
        var index = paragraphLevel - 1;
        var tag = 'h' + (paragraphLevel + 1);
        if (0 < paragraphLevel && paragraphLevel < 6) {
            var paragraphType = e.substring(0, 1);
            if (index < beforeIndex) {
                paragraphsNumber[beforeIndex] = 0;
            }
            if (paragraphType === '+') {
                paragraphsNumber[index]++;
            }
            $elements
                .append($('
').addClass(tag)
                    .append($('<' + tag + '/>').text(
                        joinParagraphNumber(paragraphType, paragraphsNumber, index) +
                        e.substring(paragraphLevel)))
                    .append($('
').addClass('paragraph')));
            beforeIndex = index;
            header = true;
            inSection = true;
        }
        else {
            if (!header && $elements.length > 0) {
                $elements.find('.paragraph').filter(':last').append($('
'));
            }
            if ($elements.find('.paragraph').length !== 0) {
                $elements.find('.paragraph').filter(':last').append(e);
            }
            else {
                $elements.append(e).append($('
'));
            }
            header = false;
        }
    });
    return $elements[0].outerHTML;
}

function getEncordedHtml(value) {
    return $('
').text(value).html();
}

function getGeneralId($self) {
    var controlId = $self.attr('id');
    return controlId.indexOf('.') === -1
        ? controlId
        : controlId.substring(0, controlId.indexOf('.'));
}

function switchControlMode($self, toEdit) {
    var id = getGeneralId($self);
    $('[id="' + id + '.viewer"]').toggle(!toEdit);
    $('[id="' + id + '.edit"]').toggle(!toEdit);
    $('[id="' + id + '"]').toggle(toEdit);
}

function joinParagraphNumber(paragraphType, paragraphsNumber, paragraphLevel) {
    if (paragraphType === '+') {
        var sum = [];
        for (var i = 0; i <= paragraphLevel; ++i) {
            sum[i] = paragraphsNumber[i];
        }
        return sum.join('.') + '. ';
    }
    else {
        return '';
    }
}

function resizeEditor(editor, $viewer) {
    if ($viewer.height() <= 300) {
        editor.height($viewer.height());
    }
    else {
        editor.height(300);
    }
}<|endoftext|>


<commit_before>ace.define("ace/snippets/perl",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText = "# #!/usr/bin/perl\n\
snippet #!\n\
	#!/usr/bin/env perl\n\
\n\
# Hash Pointer\n\
snippet .\n\
	 =>\n\
# Function\n\
snippet sub\n\
	sub ${1:function_name} {\n\
		${2:#body ...}\n\
	}\n\
# Conditional\n\
snippet if\n\
	if (${1}) {\n\
		${2:# body...}\n\
	}\n\
# Conditional if..else\n\
snippet ife\n\
	if (${1}) {\n\
		${2:# body...}\n\
	}\n\
	else {\n\
		${3:# else...}\n\
	}\n\
# Conditional if..elsif..else\n\
snippet ifee\n\
	if (${1}) {\n\
		${2:# body...}\n\
	}\n\
	elsif (${3}) {\n\
		${4:# elsif...}\n\
	}\n\
	else {\n\
		${5:# else...}\n\
	}\n\
# Conditional One-line\n\
snippet xif\n\
	${1:expression} if ${2:condition};${3}\n\
# Unless conditional\n\
snippet unless\n\
	unless (${1}) {\n\
		${2:# body...}\n\
	}\n\
# Unless conditional One-line\n\
snippet xunless\n\
	${1:expression} unless ${2:condition};${3}\n\
# Try/Except\n\
snippet eval\n\
	local $@;\n\
	eval {\n\
		${1:# do something risky...}\n\
	};\n\
	if (my $e = $@) {\n\
		${2:# handle failure...}\n\
	}\n\
# While Loop\n\
snippet wh\n\
	while (${1}) {\n\
		${2:# body...}\n\
	}\n\
# While Loop One-line\n\
snippet xwh\n\
	${1:expression} while ${2:condition};${3}\n\
# C-style For Loop\n\
snippet cfor\n\
	for (my $${2:var} = 0; $$2 < ${1:count}; $$2${3:++}) {\n\
		${4:# body...}\n\
	}\n\
# For loop one-line\n\
snippet xfor\n\
	${1:expression} for @${2:array};${3}\n\
# Foreach Loop\n\
snippet for\n\
	foreach my $${1:x} (@${2:array}) {\n\
		${3:# body...}\n\
	}\n\
# Foreach Loop One-line\n\
snippet fore\n\
	${1:expression} foreach @${2:array};${3}\n\
# Package\n\
snippet package\n\
	package ${1:`substitute(Filename('', 'Page Title'), '^.', '\\u&', '')`};\n\
\n\
	${2}\n\
\n\
	1;\n\
\n\
	__END__\n\
# Package syntax perl >= 5.14\n\
snippet packagev514\n\
	package ${1:`substitute(Filename('', 'Page Title'), '^.', '\\u&', '')`} ${2:0.99};\n\
\n\
	${3}\n\
\n\
	1;\n\
\n\
	__END__\n\
#moose\n\
snippet moose\n\
	use Moose;\n\
	use namespace::autoclean;\n\
	${1:#}BEGIN {extends '${2:ParentClass}'};\n\
\n\
	${3}\n\
# parent\n\
snippet parent\n\
	use parent qw(${1:Parent Class});\n\
# Read File\n\
snippet slurp\n\
	my $${1:var} = do { local $/; open my $file, '<', \"${2:file}\"; <$file> };\n\
	${3}\n\
# strict warnings\n\
snippet strwar\n\
	use strict;\n\
	use warnings;\n\
# older versioning with perlcritic bypass\n\
snippet vers\n\
	## no critic\n\
	our $VERSION = '${1:version}';\n\
	eval $VERSION;\n\
	## use critic\n\
# new 'switch' like feature\n\
snippet switch\n\
	use feature 'switch';\n\
\n\
# Anonymous subroutine\n\
snippet asub\n\
	sub {\n\
	 	${1:# body }\n\
	}\n\
\n\
\n\
\n\
# Begin block\n\
snippet begin\n\
	BEGIN {\n\
		${1:# begin body}\n\
	}\n\
\n\
# call package function with some parameter\n\
snippet pkgmv\n\
	__PACKAGE__->${1:package_method}(${2:var})\n\
\n\
# call package function without a parameter\n\
snippet pkgm\n\
	__PACKAGE__->${1:package_method}()\n\
\n\
# call package \"get_\" function without a parameter\n\
snippet pkget\n\
	__PACKAGE__->get_${1:package_method}()\n\
\n\
# call package function with a parameter\n\
snippet pkgetv\n\
	__PACKAGE__->get_${1:package_method}(${2:var})\n\
\n\
# complex regex\n\
snippet qrx\n\
	qr/\n\
	     ${1:regex}\n\
	/xms\n\
\n\
#simpler regex\n\
snippet qr/\n\
	qr/${1:regex}/x\n\
\n\
#given\n\
snippet given\n\
	given ($${1:var}) {\n\
		${2:# cases}\n\
		${3:# default}\n\
	}\n\
\n\
# switch-like case\n\
snippet when\n\
	when (${1:case}) {\n\
		${2:# body}\n\
	}\n\
\n\
# hash slice\n\
snippet hslice\n\
	@{ ${1:hash}  }{ ${2:array} }\n\
\n\
\n\
# map\n\
snippet map\n\
	map {  ${2: body }    }  ${1: @array } ;\n\
\n\
\n\
\n\
# Pod stub\n\
snippet ppod\n\
	=head1 NAME\n\
\n\
	${1:ClassName} - ${2:ShortDesc}\n\
\n\
	=head1 SYNOPSIS\n\
\n\
	  use $1;\n\
\n\
	  ${3:# synopsis...}\n\
\n\
	=head1 DESCRIPTION\n\
\n\
	${4:# longer description...}\n\
\n\
\n\
	=head1 INTERFACE\n\
\n\
\n\
	=head1 DEPENDENCIES\n\
\n\
\n\
	=head1 SEE ALSO\n\
\n\
\n\
# Heading for a subroutine stub\n\
snippet psub\n\
	=head2 ${1:MethodName}\n\
\n\
	${2:Summary....}\n\
\n\
# Heading for inline subroutine pod\n\
snippet psubi\n\
	=head2 ${1:MethodName}\n\
\n\
	${2:Summary...}\n\
\n\
\n\
	=cut\n\
# inline documented subroutine\n\
snippet subpod\n\
	=head2 $1\n\
\n\
	Summary of $1\n\
\n\
	=cut\n\
\n\
	sub ${1:subroutine_name} {\n\
		${2:# body...}\n\
	}\n\
# Subroutine signature\n\
snippet parg\n\
	=over 2\n\
\n\
	=item\n\
	Arguments\n\
\n\
\n\
	=over 3\n\
\n\
	=item\n\
	C<${1:DataStructure}>\n\
\n\
	  ${2:Sample}\n\
\n\
\n\
	=back\n\
\n\
\n\
	=item\n\
	Return\n\
\n\
	=over 3\n\
\n\
\n\
	=item\n\
	C<${3:...return data}>\n\
\n\
\n\
	=back\n\
\n\
\n\
	=back\n\
\n\
\n\
\n\
# Moose has\n\
snippet has\n\
	has ${1:attribute} => (\n\
		is	    => '${2:ro|rw}',\n\
		isa 	=> '${3:Str|Int|HashRef|ArrayRef|etc}',\n\
		default => sub {\n\
			${4:defaultvalue}\n\
		},\n\
		${5:# other attributes}\n\
	);\n\
\n\
\n\
# override\n\
snippet override\n\
	override ${1:attribute} => sub {\n\
		${2:# my $self = shift;};\n\
		${3:# my ($self, $args) = @_;};\n\
	};\n\
\n\
\n\
# use test classes\n\
snippet tuse\n\
	use Test::More;\n\
	use Test::Deep; # (); # uncomment to stop prototype errors\n\
	use Test::Exception;\n\
\n\
# local test lib\n\
snippet tlib\n\
	use lib qw{ ./t/lib };\n\
\n\
#test methods\n\
snippet tmeths\n\
	$ENV{TEST_METHOD} = '${1:regex}';\n\
\n\
# runtestclass\n\
snippet trunner\n\
	use ${1:test_class};\n\
	$1->runtests();\n\
\n\
# Test::Class-style test\n\
snippet tsub\n\
	sub t${1:number}_${2:test_case} :Test(${3:num_of_tests}) {\n\
		my $self = shift;\n\
		${4:#  body}\n\
\n\
	}\n\
\n\
# Test::Routine-style test\n\
snippet trsub\n\
	test ${1:test_name} => { description => '${2:Description of test.}'} => sub {\n\
		my ($self) = @_;\n\
		${3:# test code}\n\
	};\n\
\n\
#prep test method\n\
snippet tprep\n\
	sub prep${1:number}_${2:test_case} :Test(startup) {\n\
		my $self = shift;\n\
		${4:#  body}\n\
	}\n\
\n\
# cause failures to print stack trace\n\
snippet debug_trace\n\
	use Carp; # 'verbose';\n\
	# cloak \"die\"\n\
	# warn \"warning\"\n\
	$SIG{'__DIE__'} = sub {\n\
		require Carp; Carp::confess\n\
	};\n\
\n\
";
exports.scope = "perl";

});
<commit_msg>Update public/libs/bower_components/ace-builds/src-noconflict/snippets/perl.js<commit_after><|endoftext|>


<commit_before>var BOARD_SIZE = 100,
    DEAD = 0,
    ALIVE = 1,
    RECT_WIDTH = 10,
    RECT_HEIGHT = 10,
    RECT_PADDING = 2,
    XOFFSET = 20,
    YOFFSET = 20;

function board(board) {
    if(board == null) {
        this.board = createBoard(BOARD_SIZE);
    }
    else {
        this.board = board;
    }
    // make sure the board is at least a rectangle
    // validateBoard(board);
    this.boardHeight = board.length;
    this.boardWidth = board[0].length;
    this.svgWidth =
        (boardWidth * (RECT_WIDTH + RECT_PADDING)) - RECT_PADDING + (XOFFSET * 2);
    this.svgHeight =
        (boardHeight * (RECT_HEIGHT + RECT_PADDING)) - RECT_PADDING + (YOFFSET * 2);
    this.svg = d3.select("body").append("svg")
                .attr("width", this.svgWidth)
                .attr("height", this.svgHeight);
}

/*
 * createBoard: Integer:boardSize -> Array<Array<Integer>>:board
 * given the size of a board, this function creates a 2d array for
 * the board that is boardSize x boardSize with all the values
 * initialized to 0. The resulting 2D array is then returned.
 */
function createBoard(boardSize) {
    if(boardSize == null) {
        boardSize = BOARD_SIZE;
    }
    var board = new Array(boardSize);
    for(var i = 0; i < boardSize; i++) {
        var currRow = new Array(boardSize);
        for(var j = 0; j < boardSize; j++) {
            currRow[j] = 0;
        }
        board[i] = currRow;
    }
    return board;
}

/*
 * createRandomBoard: Integer:boardSize -> Array<Array<Integer>>:board
 * given the size of a board, this function creates a 2d array for the
 * board that is boardSize x boardSize with all the values randomly
 * initialized to either 0 or 1. The resulting 2D array is then returned.
 */
function createRandomBoard(boardSize) {
    if(boardSize == null) {
        boardSize = BOARD_SIZE;
    }
    var board = new Array(boardSize);
    for(var i = 0; i < boardSize; i++) {
        var currRow = new Array(boardSize);
        for(var j = 0; j < boardSize; j++) {
            currRow[j] = Math.floor(Math.random() * 10) % 2;
        }
        board[i] = currRow;
    }
    return board;
}

/*
 * TODO: I need to create a method validateBoard that will take a given
 * board (that is, 2D array) and will check that it is a valid board. The
 * conditions for a valid board at this point are as follows:
 * - we aren't forcing square, so width and height can differ
 * - each row needs to be the same length
 */

/*
 * updateBoard: Array<Array<Integer>>:board -> Array<Array<Integer>>:board
 * given a board, this function will update the board according to the
 * rules of the game of life. The rules of the game of life are as follows:
 * - Any live cell with fewer than two live neighbours dies, as if caused by
 *   under-population
 * - Any live cell with two or three live neighbours lives on to the next
 *   generation
 * - Any live cell with more than three live neighbours dies, as if by
 *   overcrowding
 * - Any dead cell with exactly three live neighbours becomes a live cell,
 *   as if by reproduction
 */
function updateBoard(board) {
    updatedBoard = [];
    for(var i = 0; i < board.length; i++) {
        var row = board[i],
            updatedRow = [];
        for(var j = 0; j < row.length; j++) {
            var count = countLiveNeighbors(board, i, j),
                alive = (isLive(board,i,j) != DEAD);
            if(alive && count < 2) {
                updatedRow.push(DEAD);
            }
            else if(alive && count >= 2 && count <= 3) {
                updatedRow.push(ALIVE);
            }
            else if(alive && count > 3) {
                updatedRow.push(DEAD);
            }
            else if(!alive && count == 3) {
                updatedRow.push(ALIVE);
            }
            else {
                updatedRow.push(DEAD);
            }
        }
        updatedBoard.push(updatedRow);
    }
    return updatedBoard;
}

/*
 * getLivenessBoard:
 *  Array<Array<Integer>>:board -> Array<Array<Integer>>:lboard
 * this function will go through a given board and build a new board
 * that represents the liveness of the board. The new board will have
 * a value at each cell that represents the number of live neighbors
 * that the cell has.
 */
function getLivenessBoard(board) {
    var lboard = [];
    for(var i = 0; i < board.length; i++) {
        var row = board[i],
            lrow = [];
        for(var j = 0; j < row.length; j++) {
            lrow.push(countLiveNeighbors(board,i,j));
        }
        lboard.push(lrow);
    }
    return lboard;
}

/*
 * isLive: Array<Array<Integer>>:board, Integer:x, Integer:y -> Integer:val
 * given a board and the a coordinate on the board, this function will see
 * if the position specified by the coordinate is live or dead. If it is
 * live, then it will return a positive value (probably 1) otherwise it will
 * return 0.
 */
function isLive(board, x, y) {
    var row = board[x];
    if(row != undefined) {
        var val = row[y];
        if(val != undefined) {
            return val;
        }
    }
    return 0;
}

/*
 * countLiveNeighbors:
 *  Array<Array<Integer>>:board Integer:x Integer:y -> Integer:count
 * given a board, this function will look at the locations surrounding
 * the cell located at the coordinate (x,y). For each live cell around
 * that cell, the count will be incremented. The final count will be
 * returned. This function uses the isLive function to remove the need
 * to do bounds checking on every possible neighbor.
 */
function countLiveNeighbors(board,x,y) {
    var count = 0;
    count += isLive(board, x-1, y);
    count += isLive(board, x+1, y);
    count += isLive(board, x-1, y-1);
    count += isLive(board, x+1, y-1);
    count += isLive(board, x-1, y+1);
    count += isLive(board, x+1, y+1);
    count += isLive(board, x, y-1);
    count += isLive(board, x, y+1);
    return count;
}

/*
 * printBoard: Array<Array<Integer>:board -> void
 * given a 2D array of integers that represents a Game of Life game
 * board, this function will pretty print the board to the console
 * for everyone's viewing pleasure.
 */
function printBoard(board) {
    function printRow(element, index, array) {
        console.log(element.join(''));
    }
    board.forEach(printRow);
}

var b1 = createBoard();
var b2 = createBoard(20);
printBoard(b2);
<commit_msg>Added a function validateBoard that will check if a given board is valid.<commit_after>var BOARD_SIZE = 100,
    DEAD = 0,
    ALIVE = 1,
    RECT_WIDTH = 10,
    RECT_HEIGHT = 10,
    RECT_PADDING = 2,
    XOFFSET = 20,
    YOFFSET = 20;

function board(board) {
    if(board == null) {
        this.board = createBoard(BOARD_SIZE);
    }
    else {
        this.board = board;
    }
    // make sure the board is at least a rectangle
    // validateBoard(board);
    this.boardHeight = board.length;
    this.boardWidth = board[0].length;
    this.svgWidth =
        (boardWidth * (RECT_WIDTH + RECT_PADDING)) - RECT_PADDING + (XOFFSET * 2);
    this.svgHeight =
        (boardHeight * (RECT_HEIGHT + RECT_PADDING)) - RECT_PADDING + (YOFFSET * 2);
    this.svg = d3.select("body").append("svg")
                .attr("width", this.svgWidth)
                .attr("height", this.svgHeight);
}

/*
 * createBoard: Integer:boardSize -> Array<Array<Integer>>:board
 * given the size of a board, this function creates a 2d array for
 * the board that is boardSize x boardSize with all the values
 * initialized to 0. The resulting 2D array is then returned.
 */
function createBoard(boardSize) {
    if(boardSize == null) {
        boardSize = BOARD_SIZE;
    }
    var board = new Array(boardSize);
    for(var i = 0; i < boardSize; i++) {
        var currRow = new Array(boardSize);
        for(var j = 0; j < boardSize; j++) {
            currRow[j] = 0;
        }
        board[i] = currRow;
    }
    return board;
}

/*
 * createRandomBoard: Integer:boardSize -> Array<Array<Integer>>:board
 * given the size of a board, this function creates a 2d array for the
 * board that is boardSize x boardSize with all the values randomly
 * initialized to either 0 or 1. The resulting 2D array is then returned.
 */
function createRandomBoard(boardSize) {
    if(boardSize == null) {
        boardSize = BOARD_SIZE;
    }
    var board = new Array(boardSize);
    for(var i = 0; i < boardSize; i++) {
        var currRow = new Array(boardSize);
        for(var j = 0; j < boardSize; j++) {
            currRow[j] = Math.floor(Math.random() * 10) % 2;
        }
        board[i] = currRow;
    }
    return board;
}

/*
 * validateBoard: Array<Array<Integer>>:board -> boolean:valid
 * given a 2D array of integers that represents a board, this function will
 * check that it meets the criteria for a valid Game of Life board.
 * The criteria for a valid board is as follows:
 * - we aren't forcing square, so width and height can differ
 * - the width and height must both be greater than 0
 * - each row needs to be the same length
 */
function validateBoard(board) {
    if(board.length <= 0) {
        return false;
    }

    var width = board[0].length;
    if(width <= 0) {
        return false;
    }
    for(var i = 1; i < board.length; i++) {
        if(board[i].length != width) {
            return false;
        }
    }

    return true;
}

/*
 * updateBoard: Array<Array<Integer>>:board -> Array<Array<Integer>>:board
 * given a board, this function will update the board according to the
 * rules of the game of life. The rules of the game of life are as follows:
 * - Any live cell with fewer than two live neighbours dies, as if caused by
 *   under-population
 * - Any live cell with two or three live neighbours lives on to the next
 *   generation
 * - Any live cell with more than three live neighbours dies, as if by
 *   overcrowding
 * - Any dead cell with exactly three live neighbours becomes a live cell,
 *   as if by reproduction
 */
function updateBoard(board) {
    updatedBoard = [];
    for(var i = 0; i < board.length; i++) {
        var row = board[i],
            updatedRow = [];
        for(var j = 0; j < row.length; j++) {
            var count = countLiveNeighbors(board, i, j),
                alive = (isLive(board,i,j) != DEAD);
            if(alive && count < 2) {
                updatedRow.push(DEAD);
            }
            else if(alive && count >= 2 && count <= 3) {
                updatedRow.push(ALIVE);
            }
            else if(alive && count > 3) {
                updatedRow.push(DEAD);
            }
            else if(!alive && count == 3) {
                updatedRow.push(ALIVE);
            }
            else {
                updatedRow.push(DEAD);
            }
        }
        updatedBoard.push(updatedRow);
    }
    return updatedBoard;
}

/*
 * getLivenessBoard:
 *  Array<Array<Integer>>:board -> Array<Array<Integer>>:lboard
 * this function will go through a given board and build a new board
 * that represents the liveness of the board. The new board will have
 * a value at each cell that represents the number of live neighbors
 * that the cell has.
 */
function getLivenessBoard(board) {
    var lboard = [];
    for(var i = 0; i < board.length; i++) {
        var row = board[i],
            lrow = [];
        for(var j = 0; j < row.length; j++) {
            lrow.push(countLiveNeighbors(board,i,j));
        }
        lboard.push(lrow);
    }
    return lboard;
}

/*
 * isLive: Array<Array<Integer>>:board, Integer:x, Integer:y -> Integer:val
 * given a board and the a coordinate on the board, this function will see
 * if the position specified by the coordinate is live or dead. If it is
 * live, then it will return a positive value (probably 1) otherwise it will
 * return 0.
 */
function isLive(board, x, y) {
    var row = board[x];
    if(row != undefined) {
        var val = row[y];
        if(val != undefined) {
            return val;
        }
    }
    return 0;
}

/*
 * countLiveNeighbors:
 *  Array<Array<Integer>>:board Integer:x Integer:y -> Integer:count
 * given a board, this function will look at the locations surrounding
 * the cell located at the coordinate (x,y). For each live cell around
 * that cell, the count will be incremented. The final count will be
 * returned. This function uses the isLive function to remove the need
 * to do bounds checking on every possible neighbor.
 */
function countLiveNeighbors(board,x,y) {
    var count = 0;
    count += isLive(board, x-1, y);
    count += isLive(board, x+1, y);
    count += isLive(board, x-1, y-1);
    count += isLive(board, x+1, y-1);
    count += isLive(board, x-1, y+1);
    count += isLive(board, x+1, y+1);
    count += isLive(board, x, y-1);
    count += isLive(board, x, y+1);
    return count;
}

/*
 * printBoard: Array<Array<Integer>:board -> void
 * given a 2D array of integers that represents a Game of Life game
 * board, this function will pretty print the board to the console
 * for everyone's viewing pleasure.
 */
function printBoard(board) {
    function printRow(element, index, array) {
        console.log(element.join(''));
    }
    board.forEach(printRow);
}

var b1 = createBoard();
var b2 = createBoard(20);
printBoard(b2);
<|endoftext|>


<commit_before>Ext.namespace('Kwc.Abstract.Image');
Kwc.Abstract.Image.ImageUploadField = Ext.extend(Ext.Panel, {

    baseParams: null,

    initComponent: function() {
        this.baseParams = {};
        Kwc.Abstract.Image.ImageUploadField.superclass.initComponent.call(this);
        var dimensionField = this._getDimensionField();
        if (dimensionField) {// because it's possible to define only a single dimension
            dimensionField.on('render', function () {
                // fileUploadField also has to be rendered
                this._alignDimensionField();
            }, this);
            dimensionField.on('change', function (dimension) {
                this._setPreviewUrl(dimension);
            }, this);
        }
        var fileUploadField = this._getFileUploadField();
        fileUploadField.on('change', function (el, value) {
            var dimensionField = this._getDimensionField();
            if (!value || !value.mimeType.match(/(^image\/)/)) {
                dimensionField.newImageUploaded('');
                this._getFileUploadField().setPreviewUrl(null);
                return;
            }
            var dimension = null;
            if (dimensionField) {
                dimensionField.newImageUploaded(value);
                dimension = dimensionField.getValue();
            }
            this._setPreviewUrl(dimension);
        }, this);
    },

    _alignDimensionField: function () {
        var dimensionField = this._getDimensionField();
        var fileUploadField = this._getFileUploadField();
        if (dimensionField.getEl() && fileUploadField.getEl()) {
            dimensionField.getEl().parent().parent().addClass('kwc-dimensionfield-container');
            dimensionField.getEl().alignTo(fileUploadField.getEl().child('.box'), 'br', [10, -42]);
        }
    },

    _getFileUploadField: function () {
        return this.findByType('kwf.file')[0];
    },

    _getDimensionField: function () {
        return this.findByType('kwc.image.dimensionfield')[0];
    },

    _setPreviewUrl: function(dimension) {
        var previewParams = {
            componentId: this.baseParams.componentId
        };
        if (dimension && dimension.dimension != null) previewParams.dimension = dimension.dimension;

        value = this._getDimensionField().getValue();
        if (value.width != null) previewParams.width = value.width;
        if (value.height != null) previewParams.height = value.height;

        if (dimension && dimension.cropData) {
            if (dimension.cropData.x != null) previewParams.cropX = dimension.cropData.x;
            if (dimension.cropData.y != null) previewParams.cropY = dimension.cropData.y;
            if (dimension.cropData.width != null) previewParams.cropWidth = dimension.cropData.width;
            if (dimension.cropData.height != null) previewParams.cropHeight = dimension.cropData.height;
        }
        this._getFileUploadField().setPreviewUrl(this.previewUrl+'?'
            +Ext.urlEncode(previewParams)+'&'
        );
    },

    setFormBaseParams: function(params) {
        Ext.apply(this.baseParams, params);
    }
});

Ext.reg('kwc.image.imageuploadfield', Kwc.Abstract.Image.ImageUploadField);
<commit_msg>Check if mimeType is set before checking value<commit_after>Ext.namespace('Kwc.Abstract.Image');
Kwc.Abstract.Image.ImageUploadField = Ext.extend(Ext.Panel, {

    baseParams: null,

    initComponent: function() {
        this.baseParams = {};
        Kwc.Abstract.Image.ImageUploadField.superclass.initComponent.call(this);
        var dimensionField = this._getDimensionField();
        if (dimensionField) {// because it's possible to define only a single dimension
            dimensionField.on('render', function () {
                // fileUploadField also has to be rendered
                this._alignDimensionField();
            }, this);
            dimensionField.on('change', function (dimension) {
                this._setPreviewUrl(dimension);
            }, this);
        }
        var fileUploadField = this._getFileUploadField();
        fileUploadField.on('change', function (el, value) {
            var dimensionField = this._getDimensionField();
            if (!value || !value.mimeType || !value.mimeType.match(/(^image\/)/)) {
                dimensionField.newImageUploaded('');
                this._getFileUploadField().setPreviewUrl(null);
                return;
            }
            var dimension = null;
            if (dimensionField) {
                dimensionField.newImageUploaded(value);
                dimension = dimensionField.getValue();
            }
            this._setPreviewUrl(dimension);
        }, this);
    },

    _alignDimensionField: function () {
        var dimensionField = this._getDimensionField();
        var fileUploadField = this._getFileUploadField();
        if (dimensionField.getEl() && fileUploadField.getEl()) {
            dimensionField.getEl().parent().parent().addClass('kwc-dimensionfield-container');
            dimensionField.getEl().alignTo(fileUploadField.getEl().child('.box'), 'br', [10, -42]);
        }
    },

    _getFileUploadField: function () {
        return this.findByType('kwf.file')[0];
    },

    _getDimensionField: function () {
        return this.findByType('kwc.image.dimensionfield')[0];
    },

    _setPreviewUrl: function(dimension) {
        var previewParams = {
            componentId: this.baseParams.componentId
        };
        if (dimension && dimension.dimension != null) previewParams.dimension = dimension.dimension;

        value = this._getDimensionField().getValue();
        if (value.width != null) previewParams.width = value.width;
        if (value.height != null) previewParams.height = value.height;

        if (dimension && dimension.cropData) {
            if (dimension.cropData.x != null) previewParams.cropX = dimension.cropData.x;
            if (dimension.cropData.y != null) previewParams.cropY = dimension.cropData.y;
            if (dimension.cropData.width != null) previewParams.cropWidth = dimension.cropData.width;
            if (dimension.cropData.height != null) previewParams.cropHeight = dimension.cropData.height;
        }
        this._getFileUploadField().setPreviewUrl(this.previewUrl+'?'
            +Ext.urlEncode(previewParams)+'&'
        );
    },

    setFormBaseParams: function(params) {
        Ext.apply(this.baseParams, params);
    }
});

Ext.reg('kwc.image.imageuploadfield', Kwc.Abstract.Image.ImageUploadField);
<|endoftext|>


<commit_before>document.observe("dom:loaded", function() {
  function handleRemote(element) {
    var method, url, params;

    if (element.tagName.toLowerCase() == 'form') {
      method = element.readAttribute('method') || 'post';
      url    = element.readAttribute('action');
      params = element.serialize(true);
    } else {
      method = element.readAttribute('data-method') || 'get';
      // TODO: data-url support is going away, just use href
      url    = element.readAttribute('data-url') || element.readAttribute('href');
      params = {};
    }

    var event = element.fire("ajax:before");
    if (event.stopped) return false;

    new Ajax.Request(url, {
      method: method,
      parameters: params,
      asynchronous: true,
      evalScripts: true,

      onLoading:     function(request) { element.fire("ajax:loading", {request: request}); },
      onLoaded:      function(request) { element.fire("ajax:loaded", {request: request}); },
      onInteractive: function(request) { element.fire("ajax:interactive", {request: request}); },
      onComplete:    function(request) { element.fire("ajax:complete", {request: request}); },
      onSuccess:     function(request) { element.fire("ajax:success", {request: request}); },
      onFailure:     function(request) { element.fire("ajax:failure", {request: request}); }
    });

    element.fire("ajax:after");
  }

  $(document.body).observe("click", function(event) {
    var element = event.findElement("a[data-remote=true]");
    if (element) {
      handleRemote(element);
      event.stop();
    }
  });

  $(document.body).observe("ajax:before", function(event) {
    var message = event.element().readAttribute('data-confirm');
    if (message && !confirm(message)) event.stop();
  });

  // TODO: I don't think submit bubbles in IE
  $(document.body).observe("submit", function(event) {
    var inputs = event.element().select("input[type=submit][data-disable-with]");
    inputs.each(function(input) {
      input.disabled = true;
      input.writeAttribute('data-original-value', input.value);
      input.value = input.readAttribute('data-disable-with');
    });

    var element = event.findElement("form[data-remote=true]");
    if (element) {
      handleRemote(element);
      event.stop();
    }
  });

  $(document.body).observe("ajax:complete", function(event) {
    var element = event.element();

    if (element.tagName.toLowerCase() == 'form') {
      var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
      inputs.each(function(input) {
        input.value = input.readAttribute('data-original-value');
        input.writeAttribute('data-original-value', null);
        input.disabled = false;
      });
    }
  });
});
<commit_msg>Update prototype-ujs for data-confirm<commit_after>document.observe("dom:loaded", function() {
  function handleRemote(element) {
    var method, url, params;

    if (element.tagName.toLowerCase() == 'form') {
      method = element.readAttribute('method') || 'post';
      url    = element.readAttribute('action');
      params = element.serialize(true);
    } else {
      method = element.readAttribute('data-method') || 'get';
      // TODO: data-url support is going away, just use href
      url    = element.readAttribute('data-url') || element.readAttribute('href');
      params = {};
    }

    var event = element.fire("ajax:before");
    if (event.stopped) return false;

    new Ajax.Request(url, {
      method: method,
      parameters: params,
      asynchronous: true,
      evalScripts: true,

      onLoading:     function(request) { element.fire("ajax:loading", {request: request}); },
      onLoaded:      function(request) { element.fire("ajax:loaded", {request: request}); },
      onInteractive: function(request) { element.fire("ajax:interactive", {request: request}); },
      onComplete:    function(request) { element.fire("ajax:complete", {request: request}); },
      onSuccess:     function(request) { element.fire("ajax:success", {request: request}); },
      onFailure:     function(request) { element.fire("ajax:failure", {request: request}); }
    });

    element.fire("ajax:after");
  }

  $(document.body).observe("click", function(event) {
    var message = event.element().readAttribute('data-confirm');
    if (message && !confirm(message)) {
      event.stop();
      return false;
    }

    var element = event.findElement("a[data-remote=true]");
    if (element) {
      handleRemote(element);
      event.stop();
    }
  });

  // TODO: I don't think submit bubbles in IE
  $(document.body).observe("submit", function(event) {
    var message = event.element().readAttribute('data-confirm');
    if (message && !confirm(message)) {
      event.stop();
      return false;
    }

    var inputs = event.element().select("input[type=submit][data-disable-with]");
    inputs.each(function(input) {
      input.disabled = true;
      input.writeAttribute('data-original-value', input.value);
      input.value = input.readAttribute('data-disable-with');
    });

    var element = event.findElement("form[data-remote=true]");
    if (element) {
      handleRemote(element);
      event.stop();
    }
  });

  $(document.body).observe("ajax:complete", function(event) {
    var element = event.element();

    if (element.tagName.toLowerCase() == 'form') {
      var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
      inputs.each(function(input) {
        input.value = input.readAttribute('data-original-value');
        input.writeAttribute('data-original-value', null);
        input.disabled = false;
      });
    }
  });
});
<|endoftext|>


<commit_before>//////////////////////////////////
//           SWOOP JS           //
//////////////////////////////////
// Get data from backend        //
// Get requests from frontend   //
// Match up data                //
// Send to front end            //
//////////////////////////////////
var http = require('http'); // http protocol
var express = require('express'); // web server
var bodyParser = require('body-parser'); // http body parser
var mongodb = require('mongodb');
var socketio = require('socket.io');
var request = require('request');
var fs = require('fs');
var Mongo = mongodb.MongoClient;
var ObjectID = mongodb.ObjectID;
const MONGO_URL = 'mongodb://localhost:27017/swoop';
///////////////
// MONGO OPs //
///////////////
Mongo.connect(MONGO_URL, function (err, db) {
    if (err) log('error');
    else log('good to go');
    Mongo.ops = {};
    // TODO: Add needed Functions
    Mongo.ops.upsert = function (collection, query, json, callback) {
        db.collection(collection).updateOne(query, {
            $set: json
        }, {
            upsert: true
        }, function (err, result) {
            // TODO: handle err
            if (callback) callback(err, result);
        });
    };
    Mongo.ops.insert = function (collection, json, callback) {
        db.collection(collection).insert(json, function (err, result) {
            if (callback) callback(err, result);
        });
    };
});
////////////////////
// Cross Domains  //
////////////////////
/*function allowCrossDomain(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Authorization');
    // end pre flights
}
//
var app = express();
// use middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(allowCrossDomain);
*/
///////////////
//  NodeJS   //
///////////////
var app = express();
// use middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.post('/car1', function (req, res, next) {
    log('/car1 req.body =', req.body);
    var payload = req.body
    io.sockets.emit('addcar1', req.body);
    Mongo.ops.upsert('car1-current', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
    Mongo.ops.insert('car1-all', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
});
app.post('/car2', function (req, res, next) {
    log('/car2 req.body =', req.body);
    var payload = req.body
    io.sockets.emit('addcar2', req.body);
    Mongo.ops.upsert('car2-current', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
    Mongo.ops.insert('car2-all', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
});
app.post('/car3', function (req, res, next) {
    log('/car3 req.body =', req.body);
    var payload = req.body
    io.sockets.emit('addcar3', req.body);
    Mongo.ops.upsert('car3-current', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
    Mongo.ops.insert('car3-all', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
});
app.listen(3000, function () {
    log('listening on port 3000');
});
///////////////
// SOCKET iO //
///////////////
var server = app.listen(3000, function() {
    log('listening on port 3000');
});
var io = socketio.listen(server, { origins : '*:*' });

io.sockets.on('connection', function (socket) {
    log('new socket client: ', socket.id);
    socket.on('disconnect', function () {
        log('socket client disconnected: ', socket.id);
    });
    socket.on('addcar1', function (data) {
        log('car lat and long: ' + data.lat + ", " + data.long);
        socket.broadcast.emit('car1', data);
    })
    socket.on('addcar2', function (data) {
        log('car lat and long: ' + data.lat + ", " + data.long);
        socket.broadcast.emit('car2', data);
    })
    socket.on('addcar3', function (data) {
        log('car lat and long: ' + data.lat + ", " + data.long);
        socket.broadcast.emit('car3', data);
    })
});
///////////////
//    LOG    //
///////////////
function log(msg) {
    console.log(msg);
}<commit_msg>Server fixes<commit_after>//////////////////////////////////
//           SWOOP JS           //
//////////////////////////////////
// Get data from backend        //
// Get requests from frontend   //
// Match up data                //
// Send to front end            //
//////////////////////////////////
var http = require('http'); // http protocol
var express = require('express'); // web server
var bodyParser = require('body-parser'); // http body parser
var mongodb = require('mongodb');
var socketio = require('socket.io');
var request = require('request');
var fs = require('fs');
var Mongo = mongodb.MongoClient;
var ObjectID = mongodb.ObjectID;
const MONGO_URL = 'mongodb://localhost:27017/swoop';
///////////////
// MONGO OPs //
///////////////
Mongo.connect(MONGO_URL, function (err, db) {
    if (err) log('error');
    else log('good to go');
    Mongo.ops = {};
    // TODO: Add needed Functions
    Mongo.ops.upsert = function (collection, query, json, callback) {
        db.collection(collection).updateOne(query, {
            $set: json
        }, {
            upsert: true
        }, function (err, result) {
            // TODO: handle err
            if (callback) callback(err, result);
        });
    };
    Mongo.ops.insert = function (collection, json, callback) {
        db.collection(collection).insert(json, function (err, result) {
            if (callback) callback(err, result);
        });
    };
});
////////////////////
// Cross Domains  //
////////////////////
/*function allowCrossDomain(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Authorization');
    // end pre flights
}
//
var app = express();
// use middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(allowCrossDomain);
*/
///////////////
//  NodeJS   //
///////////////
var app = express();
// use middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.post('/car1', function (req, res, next) {
    log('/car1 req.body =', req.body);
    var payload = req.body
    io.sockets.emit('addcar1', req.body);
    Mongo.ops.upsert('car1-current', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
    Mongo.ops.insert('car1-all', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
});
app.post('/car2', function (req, res, next) {
    log('/car2 req.body =', req.body);
    var payload = req.body
    io.sockets.emit('addcar2', req.body);
    Mongo.ops.upsert('car2-current', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
    Mongo.ops.insert('car2-all', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
});
app.post('/car3', function (req, res, next) {
    log('/car3 req.body =', req.body);
    var payload = req.body
    io.sockets.emit('addcar3', req.body);
    Mongo.ops.upsert('car3-current', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
    Mongo.ops.insert('car3-all', payload, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.status(201).send('ok');
        }
    });
});
app.listen(3000, function () {
    log('listening on port 3000');
});
///////////////
// SOCKET iO //
///////////////
var server = http.listen(3000, function () {
    console.log('server listening on http://localhost:3000/');
});
var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
    log('new socket client: ', socket.id);
    socket.on('disconnect', function () {
        log('socket client disconnected: ', socket.id);
    });
    socket.on('addcar1', function (data) {
        log('car lat and long: ' + data.lat + ", " + data.long);
        socket.broadcast.emit('car1', data);
    })
    socket.on('addcar2', function (data) {
        log('car lat and long: ' + data.lat + ", " + data.long);
        socket.broadcast.emit('car2', data);
    })
    socket.on('addcar3', function (data) {
        log('car lat and long: ' + data.lat + ", " + data.long);
        socket.broadcast.emit('car3', data);
    })
});
///////////////
//    LOG    //
///////////////
function log(msg) {
    console.log(msg);
}<|endoftext|>


<commit_before>import React, {PropTypes, PureComponent} from "react"
import {connect} from "react-redux"
import cxs from "cxs"
import {mergeDeep} from "ramda-extra"
import {query} from "@lacqueristas/queries"
import {formSectionQuery} from "@lacqueristas/queries"
import {dispatched} from "@lacqueristas/signals"
import {updateInputSignal} from "@lacqueristas/signals"

const baseStyle = {
  display: "flex",
  flexDirection: "column",
}

export default connect(
  query([formSectionQuery]),
  dispatched({updateInput: updateInputSignal}),
)(class FormSection extends PureComponent {
  static propTypes = {
    updateInput: PropTypes.func.isRequired,
    slug: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    id: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    required: PropTypes.bool.isRequired,
    type: PropTypes.string.isRequired,
    style: PropTypes.object.isRequired,
  }

  static defaultProps = {
    required: false,
    stored: false,
    style: {},
    value: "",
  }

  state = {}

  state: {
    value: any
  }

  onChangeInput (): Function {
    return function thunk (event: Event) {
      const {slug} = this.props
      const {updateInput} = this.props
      const {target} = event
      const {name} = target
      const {value} = target

      this.setState({value})

      updateInput({
        slug,
        name,
        value,
      })
    }.bind(this)
  }

  render (): any {
    const {id} = this.props
    const {name} = this.props
    const {type} = this.props
    const {label} = this.props
    const {required} = this.props
    const {style} = this.props
    const {value: initialValue} = this.props
    const {value: localValue = initialValue} = this.state
    const combineStyle = mergeDeep(baseStyle, style)

    return

      {label}
      {type === "textarea" ? <textarea id={id} name={name} required={required} onChange={this.onChangeInput()} defaultValue={localValue} /> : <input id={id} name={name} type={type} required={required} onChange={this.onChangeInput()} value={localValue} />}

  }
})
<commit_msg>This was never used<commit_after>import React, {PropTypes, PureComponent} from "react"
import {connect} from "react-redux"
import cxs from "cxs"
import {mergeDeep} from "ramda-extra"
import {query} from "@lacqueristas/queries"
import {formSectionQuery} from "@lacqueristas/queries"
import {dispatched} from "@lacqueristas/signals"
import {updateInputSignal} from "@lacqueristas/signals"

const baseStyle = {
  display: "flex",
  flexDirection: "column",
}

export default connect(
  query([formSectionQuery]),
  dispatched({updateInput: updateInputSignal}),
)(class FormSection extends PureComponent {
  static propTypes = {
    updateInput: PropTypes.func.isRequired,
    slug: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    id: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    required: PropTypes.bool.isRequired,
    type: PropTypes.string.isRequired,
    style: PropTypes.object.isRequired,
  }

  static defaultProps = {
    required: false,
    style: {},
    value: "",
  }

  state = {}

  state: {
    value: any
  }

  onChangeInput (): Function {
    return function thunk (event: Event) {
      const {slug} = this.props
      const {updateInput} = this.props
      const {target} = event
      const {name} = target
      const {value} = target

      this.setState({value})

      updateInput({
        slug,
        name,
        value,
      })
    }.bind(this)
  }

  render (): any {
    const {id} = this.props
    const {name} = this.props
    const {type} = this.props
    const {label} = this.props
    const {required} = this.props
    const {style} = this.props
    const {value: initialValue} = this.props
    const {value: localValue = initialValue} = this.state
    const combineStyle = mergeDeep(baseStyle, style)

    return

      {label}
      {type === "textarea" ? <textarea id={id} name={name} required={required} onChange={this.onChangeInput()} defaultValue={localValue} /> : <input id={id} name={name} type={type} required={required} onChange={this.onChangeInput()} value={localValue} />}

  }
})
<|endoftext|>