<commit_before>/* http://prismjs.com/download.html?themes=prism-okaidia&languages=clike+javascript&plugins=line-numbers */
self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{};var Prism=function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{encode:function(e){return e instanceof n?new n(e.type,t.util.encode(e.content),e.alias):"Array"===t.util.type(e)?e.map(t.util.encode):e.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var a={};for(var r in e)e.hasOwnProperty(r)&&(a[r]=t.util.clone(e[r]));return a;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var a=t.util.clone(t.languages[e]);for(var r in n)a[r]=n[r];return a},insertBefore:function(e,n,a,r){r=r||t.languages;var i=r[e],l={};for(var o in i)if(i.hasOwnProperty(o)){if(o==n)for(var s in a)a.hasOwnProperty(s)&&(l[s]=a[s]);l[o]=i[o]}return r[e]=l},DFS:function(e,n,a){for(var r in e)e.hasOwnProperty(r)&&(n.call(e,r,e[r],a||r),"Object"===t.util.type(e[r])?t.languages.DFS(e[r],n):"Array"===t.util.type(e[r])&&t.languages.DFS(e[r],n,r))}},highlightAll:function(e,n){for(var a,r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'),i=0;a=r[i++];)t.highlightElement(a,e===!0,n)},highlightElement:function(a,r,i){for(var l,o,s=a;s&&!e.test(s.className);)s=s.parentNode;if(s&&(l=(s.className.match(e)||[,""])[1],o=t.languages[l]),o){a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+l,s=a.parentNode,/pre/i.test(s.nodeName)&&(s.className=s.className.replace(e,"").replace(/\s+/g," ")+" language-"+l);var c=a.textContent;if(c){var g={element:a,language:l,grammar:o,code:c};if(t.hooks.run("before-highlight",g),r&&self.Worker){var u=new Worker(t.filename);u.onmessage=function(e){g.highlightedCode=n.stringify(JSON.parse(e.data),l),t.hooks.run("before-insert",g),g.element.innerHTML=g.highlightedCode,i&&i.call(g.element),t.hooks.run("after-highlight",g)},u.postMessage(JSON.stringify({language:g.language,code:g.code}))}else g.highlightedCode=t.highlight(g.code,g.grammar,g.language),t.hooks.run("before-insert",g),g.element.innerHTML=g.highlightedCode,i&&i.call(a),t.hooks.run("after-highlight",g)}}},highlight:function(e,a,r){var i=t.tokenize(e,a);return n.stringify(t.util.encode(i),r)},tokenize:function(e,n){var a=t.Token,r=[e],i=n.rest;if(i){for(var l in i)n[l]=i[l];delete n.rest}e:for(var l in n)if(n.hasOwnProperty(l)&&n[l]){var o=n[l];o="Array"===t.util.type(o)?o:[o];for(var s=0;s<o.length;++s){var c=o[s],g=c.inside,u=!!c.lookbehind,f=0,h=c.alias;c=c.pattern||c;for(var p=0;p<r.length;p++){var d=r[p];if(r.length>e.length)break e;if(!(d instanceof a)){c.lastIndex=0;var m=c.exec(d);if(m){u&&(f=m[1].length);var y=m.index-1+f,m=m[0].slice(f),v=m.length,k=y+v,b=d.slice(0,y+1),w=d.slice(k+1),N=[p,1];b&&N.push(b);var O=new a(l,g?t.tokenize(m,g):m,h);N.push(O),w&&N.push(w),Array.prototype.splice.apply(r,N)}}}}}return r},hooks:{all:{},add:function(e,n){var a=t.hooks.all;a[e]=a[e]||[],a[e].push(n)},run:function(e,n){var a=t.hooks.all[e];if(a&&a.length)for(var r,i=0;r=a[i++];)r(n)}}},n=t.Token=function(e,t,n){this.type=e,this.content=t,this.alias=n};if(n.stringify=function(e,a,r){if("string"==typeof e)return e;if("[object Array]"==Object.prototype.toString.call(e))return e.map(function(t){return n.stringify(t,a,e)}).join("");var i={type:e.type,content:n.stringify(e.content,a,r),tag:"span",classes:["token",e.type],attributes:{},language:a,parent:r};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var l="Array"===t.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,l)}t.hooks.run("wrap",i);var o="";for(var s in i.attributes)o+=s+'="'+(i.attributes[s]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+o+">"+i.content+"</"+i.tag+">"},!self.document)return self.addEventListener?(self.addEventListener("message",function(e){var n=JSON.parse(e.data),a=n.language,r=n.code;self.postMessage(JSON.stringify(t.util.encode(t.tokenize(r,t.languages[a])))),self.close()},!1),self.Prism):self.Prism;var a=document.getElementsByTagName("script");return a=a[a.length-1],a&&(t.filename=a.src,document.addEventListener&&!a.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)),self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism);;
Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//g,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*?(\r?\n|$)/g,lookbehind:!0}],string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/gi,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/gi,inside:{punctuation:/\(/}},number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};;
Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|get|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/


<commit_before>var testRunner = require('./ui_test_runner.js');

var waitFor = testRunner.waitFor;

testRunner.run(function homepageTest (page) {
    page.evaluate(function () { localStorage.clear(); });
    waitFor(function clientReady () {
        return page.evaluate(function () {
            return window.openerp && window.openerp.website
                && window.openerp.website.TestConsole
                && window.openerp.website.TestConsole.test('banner');
        });
    }, function executeTest () {
        var before = page.evaluate(function () {
            var result = {
                carousel: $('#wrap [data-snippet-id=carousel]').length,
                columns: $('#wrap [data-snippet-id=three-columns]').length,
            };
            window.openerp.website.TestConsole.test('banner').run(true);
            return result;
        });
        waitFor(function testExecuted () {
            var after = page.evaluate(function () {
                if ($('button[data-action=edit]').is(":visible")) {
                    return {
                        carousel: $('#wrap [data-snippet-id=carousel]').length,
                        columns: $('#wrap [data-snippet-id=three-columns]').length,
                    };
                }
            });
            return after && after.carousel === before.carousel + 1 && after.columns === before.columns + 1;
        }, function finish () {
            console.log('{ "event": "success" }');
            phantom.exit();
        }, 90000);
    }, 20000);
});<commit_msg>[IMP] Code cleanup<commit_after>var testRunner = require('./ui_test_runner.js');

var waitFor = testRunner.waitFor;

testRunner.run(function homepageTest (page) {
    page.evaluate(function () { localStorage.clear(); });
    waitFor(function clientReady () {
        return page.evaluate(function () {
            return window.openerp && window.openerp.website
                && window.openerp.website.TestConsole
                && window.openerp.website.TestConsole.test('banner');
        });
    }, function executeTest () {
        var before = page.evaluate(function () {
            var result = {
                carousel: $('#wrap [data-snippet-id=carousel]').length,
                columns: $('#wrap [data-snippet-id=three-columns]').length,
            };
            window.openerp.website.TestConsole.test('banner').run(true);
            return result;
        });
        waitFor(function testExecuted () {
            var after = page.evaluate(function () {
                return $('button[data-action=edit]').is(":visible") && {
                    carousel: $('#wrap [data-snippet-id=carousel]').length,
                    columns: $('#wrap [data-snippet-id=three-columns]').length,
                };
            });
            return after && after.carousel === before.carousel + 1 && after.columns === before.columns + 1;
        }, function finish () {
            console.log('{ "event": "success" }');
            phantom.exit();
        }, 90000);
    }, 20000);
});<|endoftext|>


<commit_before>const {of} = require('rx')
const {catchError, map, switchMap} = require('rx/operators')
const {fromPromise} = require('sepal/rxjs')
const fs = require('fs')
const Path = require('path')

const ls$ = (path, options = {}) =>
    fromPromise(fs.promises.readdir(path, options))

const mkdir$ = (path, options = {}) =>
    fromPromise(fs.promises.mkdir(path, options)).pipe(
        map(() => path)
    )

const exists$ = path =>
    fromPromise(fs.promises.stat(path)).pipe(
        catchError(() => of(null)),
        map(stat => !!stat)
    )

const getPostfixIndex = (name, preferredName) => {
    const match = name.match(new RegExp(`^${preferredName}_(\\d)$`))
    return match && match[1]
        ? parseInt(match[1]) + 1
        : 1
}

const mkdirSafe$ = (preferredPath, options = {}) => {
    const preferredName = Path.basename(preferredPath)
    const parent = Path.dirname(preferredPath)
    const mkdirPostfix$ = () => ls$(parent).pipe(
        map(names => names
            .filter(name => name.startsWith(preferredName))
            .map(name => getPostfixIndex(name, preferredName))
        ),
        map(postfixIndexes => Math.max(...postfixIndexes)),
        switchMap(postfixIndex =>
            mkdir$(Path.join(parent, `${preferredName}_${postfixIndex}`), options))
    )
    return exists$(preferredPath).pipe(
        switchMap(exists => exists
            ? mkdirPostfix$()
            : mkdir$(preferredPath, options)
        )
    )
}

module.exports = {exists$, ls$, mkdir$, mkdirSafe$}
<commit_msg>Deferred file system operations.<commit_after>const {defer, of} = require('rx')
const {catchError, map, switchMap} = require('rx/operators')
const {fromPromise} = require('sepal/rxjs')
const fs = require('fs')
const Path = require('path')

const ls$ = (path, options = {}) => defer(() =>
    fromPromise(fs.promises.readdir(path, options))
)

const mkdir$ = (path, options = {}) => defer(() =>
    fromPromise(fs.promises.mkdir(path, options)).pipe(
        map(() => path)
    )
)

const exists$ = path => defer(() =>
    fromPromise(fs.promises.stat(path)).pipe(
        catchError(() => of(null)),
        map(stat => !!stat)
    )
)

const getPostfixIndex = (name, preferredName) => defer(() => {
    const match = name.match(new RegExp(`^${preferredName}_(\\d)$`))
    return match && match[1]
        ? parseInt(match[1]) + 1
        : 1
})

const mkdirSafe$ = (preferredPath, options = {}) => defer(() => {
    const preferredName = Path.basename(preferredPath)
    const parent = Path.dirname(preferredPath)
    const mkdirPostfix$ = () => ls$(parent).pipe(
        map(names => names
            .filter(name => name.startsWith(preferredName))
            .map(name => getPostfixIndex(name, preferredName))
        ),
        map(postfixIndexes => Math.max(...postfixIndexes)),
        switchMap(postfixIndex =>
            mkdir$(Path.join(parent, `${preferredName}_${postfixIndex}`), options))
    )
    return exists$(preferredPath).pipe(
        switchMap(exists => exists
            ? mkdirPostfix$()
            : mkdir$(preferredPath, options)
        )
    )
})

module.exports = {exists$, ls$, mkdir$, mkdirSafe$}
<|endoftext|>


<commit_before>/* eslint-disable no-console */
// <nowiki>
(function() {

    $('a').each(function(i, e) {
        try {
            var url = new URL(e.href);
            if (url.host.match(/\.(wikipedia|wiktionary|wikiquote|wikisource|wikinews|wikivoyage|wikibooks|wikiversity|wikimedia|mediawiki|wikidata)\.org$/)) {
                url.searchParams.set('dtenable', '1');
                e.href = url.href;
            }
        } catch (err) {
            console.log(e.href);
        }
    });

}
)();
// </nowiki>
<commit_msg>Add PortletLink<commit_after>/* eslint-disable no-console */
// <nowiki>
(function() {

    $('a').each(function(i, e) {
        try {
            var url = new URL(e.href);
            if (url.host.match(/\.(wikipedia|wiktionary|wikiquote|wikisource|wikinews|wikivoyage|wikibooks|wikiversity|wikimedia|mediawiki|wikidata)\.org$/)) {
                url.searchParams.set('dtenable', '1');
                e.href = url.href;
            }
        } catch (err) {
            console.log(e.href);
        }
    });

    var url = new URL(window.location.href);
    url.searchParams.set('dtenable', '1');
    mw.util.addPortletLink(
		'p-tb',
		url.href,
		'Enable DiscussionTools',
		't-debug'
    );

}
)();
// </nowiki>
<|endoftext|>


<commit_before>/*
 * Base 64 implementation in JavaScript
 * Copyright (c) 2009 Nicholas C. Zakas. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * Accepts an array of bits and pads with zeros to the left up to a certain
 * length.
 * @param {Array} bits An array of bits (strings either "0" or "1").
 * @param {int} length The length that the array of bits should be.
 * @return {Array} The array of bits.
 */
function padLeft(bits, length){
    while (bits.length < length){
        bits.unshift("0");
    }
    return bits;
}

/**
 * Accepts an array of bits and pads with zeros to the right up to a certain
 * length.
 * @param {Array} bits An array of bits (strings either "0" or "1").
 * @param {int} length The length that the array of bits should be.
 * @return {Array} The array of bits.
 */
function padRight(bits, length){
    while (bits.length < length){
        bits.push("0");
    }
    return bits;
}

/**
 * Base64-encodes a string of text.
 * @param {String} text The text to encode.
 * @return {String} The base64-encoded string.
 */
function base64Encode(text){

    if (/([^\u0000-\u00ff])/.test(text)){
        throw new Error("Can't base64 encode non-ASCII characters.");
    }

    var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
        i = 0,
        cur, prev, byteNum,
        result=[];

    while(i < text.length){

        cur = text.charCodeAt(i);
        byteNum = i % 3;

        switch(byteNum){
            case 0: //first byte
                result.push(digits.charAt(cur >> 2));
                break;

            case 1: //second byte
                result.push(digits.charAt((prev & 3) << 4 | (cur >> 4)));
                break;

            case 2: //third byte
                result.push(digits.charAt((prev & 0x0f) << 2 | (cur >> 6)));
                result.push(digits.charAt(cur & 0x3f));
                break;
        }

        prev = cur;
        i++;
    }

    if (byteNum == 0){
        result.push(digits.charAt((prev & 3) << 4));
        result.push("==");
    } else if (byteNum == 1){
        result.push(digits.charAt((prev & 0x0f) << 2));
        result.push("=");
    }

    return result.join("");
}

/**
 * Base64-decodes a string of text.
 * @param {String} text The text to decode.
 * @return {String} The base64-decoded string.
 */
function base64Decode(text){

    //first check for any unexpected input
    if(!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text))){
        throw new Error("Not a base64-encode string.");
    }

    //local variables
    var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
        cur, prev, digitNum,
        i=0,
        result = [];

    //remove any whitespace and equals signs
    text = text.replace(/[\s=]/g, "");

    //loop over each character
    while(i < text.length){

        cur = digits.indexOf(text.charAt(i));
        digitNum = i % 4;

        switch(digitNum){

            //case 0: do nothing, not enough info to work with

            case 1: //second digit
                result.push(String.fromCharCode(prev << 2 | cur >> 4));
                break;

            case 2: //third digit
                result.push(String.fromCharCode((prev & 0x0f) << 4 | cur >> 2));
                break;

            case 3: //fourth digit
                result.push(String.fromCharCode((prev & 3) << 6 | cur));
                break;
        }

        prev = cur;
        i++;
    }

    //return a string
    return result.join("");

}<commit_msg>Removed unused code<commit_after>/*
 * Base 64 implementation in JavaScript
 * Copyright (c) 2009 Nicholas C. Zakas. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * Base64-encodes a string of text.
 * @param {String} text The text to encode.
 * @return {String} The base64-encoded string.
 */
function base64Encode(text){

    if (/([^\u0000-\u00ff])/.test(text)){
        throw new Error("Can't base64 encode non-ASCII characters.");
    }

    var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
        i = 0,
        cur, prev, byteNum,
        result=[];

    while(i < text.length){

        cur = text.charCodeAt(i);
        byteNum = i % 3;

        switch(byteNum){
            case 0: //first byte
                result.push(digits.charAt(cur >> 2));
                break;

            case 1: //second byte
                result.push(digits.charAt((prev & 3) << 4 | (cur >> 4)));
                break;

            case 2: //third byte
                result.push(digits.charAt((prev & 0x0f) << 2 | (cur >> 6)));
                result.push(digits.charAt(cur & 0x3f));
                break;
        }

        prev = cur;
        i++;
    }

    if (byteNum == 0){
        result.push(digits.charAt((prev & 3) << 4));
        result.push("==");
    } else if (byteNum == 1){
        result.push(digits.charAt((prev & 0x0f) << 2));
        result.push("=");
    }

    return result.join("");
}

/**
 * Base64-decodes a string of text.
 * @param {String} text The text to decode.
 * @return {String} The base64-decoded string.
 */
function base64Decode(text){

    //first check for any unexpected input
    if(!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text))){
        throw new Error("Not a base64-encode string.");
    }

    //local variables
    var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
        cur, prev, digitNum,
        i=0,
        result = [];

    //remove any whitespace and equals signs
    text = text.replace(/[\s=]/g, "");

    //loop over each character
    while(i < text.length){

        cur = digits.indexOf(text.charAt(i));
        digitNum = i % 4;

        switch(digitNum){

            //case 0: do nothing, not enough info to work with

            case 1: //second digit
                result.push(String.fromCharCode(prev << 2 | cur >> 4));
                break;

            case 2: //third digit
                result.push(String.fromCharCode((prev & 0x0f) << 4 | cur >> 2));
                break;

            case 3: //fourth digit
                result.push(String.fromCharCode((prev & 3) << 6 | cur));
                break;
        }

        prev = cur;
        i++;
    }

    //return a string
    return result.join("");

}<|endoftext|>


<commit_before>/*global define, $, _, document, WebSyncData, WebSyncAuth, JST, NProgress*/

//= require templates/note-nav-inner
//= require templates/note-nav-sidebar

define('/assets/note.js', ['websync'], function(WebSync) {
  'use strict';
  /**
   * WebSync: Notebook layout handler
   *
   * @exports note
   * @module note
   */
  var exports = {
    /** Trigger an update for the nav. */
    updateNav: function() {
      var activeSection = $('.note-section:visible')[0];
      var activePage = $('.note-page:visible')[0];

      var sections = _.map($('.note-section'), function(section) {
        var name = section.dataset.name || 'Unnamed Section';
        var pages = _.map($(section).children(), function(page) {
          var $children = $(page).children();
          var pageName = $children.filter('.note-title').text() ||
            $children.filter(":not('.note-title')").first().text() ||
            'Unnamed Page';

          return {
            active: page === activePage,
            name: pageName.trim()
          };
        });

        return {
          name: name,
          active: section === activeSection,
          pages: pages
        };
      });
      $('#notesView').html(JST['templates/note-nav-inner']({
        sections: sections
      }));
      var selectedElem = null;

      var dragElem = null;
      var secondLevel = false;
      $('#notesView li').on('dragstart', function(e) {
        secondLevel = $(this).parents('ul > li > ul').length !== 0;
        e.originalEvent.dataTransfer.effectAllowed = 'move';
        e.originalEvent.dataTransfer.setData('text/plain', $(this).data().index);
        dragElem = this;
        e.stopPropagation();
      }).on('dragenter', function(e) {
        e.preventDefault();
      }).on('dragover', function(e) {
        var c2 = $(e.target).parents('ul > li > ul').length !== 0;
        if (secondLevel && c2) {
          $(this).addClass('over');
        } else if (!secondLevel) {
          $(e.target).parents('#notesView > ul > li').addClass('over');
        }
        e.stopPropagation();
        e.preventDefault();
      }).on('dragleave', function() {
        $(this).removeClass('over');
      }).on('drop', function(e) {
        $('li.over').removeClass('over');
        var origSection, targetSection;
        if (secondLevel) {
          var origPage = $(dragElem).children('a').data().index;
          origSection = $(dragElem).
          parents('#notesView > ul > li').children('a').
          data().index;

          var targetPage = $(e.target).data().index;
          targetSection = $(e.target).
          parents('#notesView > ul > li').children('a').
          data().index;

          var page = $('.note-section').eq(origSection).children().eq(origPage);
          if ($(e.target).parents('#notesView > ul > li > ul').length !== 0) {
            $('.note-section').eq(targetSection).children().eq(targetPage).after(page);
          } else {
            $('.note-section').eq(targetSection).prepend(page);
          }
        } else {
          origSection = $(dragElem).children('a').data().index;
          targetSection = $(e.target).parents('#notesView > ul > li').
          children('a').data().index;
          var section = $('.note-section').eq(origSection);
          $('.note-section').eq(targetSection).after(section);
        }
        e.preventDefault();
        e.stopPropagation();
        exports.updateNav();
      });
      $('#notesView a').contextmenu({
        target: '#context-menu',
        before: function(element) {
          if ($(element).hasClass('page')) {
            $("#context-menu li:contains('Rename')").hide();
          } else {
            $("#context-menu li:contains('Rename')").show();
          }
          selectedElem = element[0];
          return true;
        },
        onItem: function(element, b) {
          var op = b.target.innerText;
          var target, section;
          var selectedElem = element[0];
          if ($(selectedElem.parentElement).hasClass('page')) {
            var page = $(selectedElem.parentElement).data().index;
            section = $(selectedElem.parentElement).parent().parent().parent().children().first().data().index;
            target = $('.note-section').eq(section).children().eq(page);
          } else if ($(selectedElem.parentElement).hasClass('section')) {
            section = $(selectedElem.parentElement).data().index;
            target = $('.note-section').eq(section);
          }
          if (op === 'Delete') {
            target.remove();
            exports.updateNav();
          } else if (op === 'Rename') {
            var finishRename = function(e) {
              // Enter or Escape
              target[0].dataset.name = $(selectedElem).text();
              if (!e.keyCode || e.keyCode === 13 || e.keyCode === 27) {
                e.preventDefault();
                $(selectedElem).unbind('blur.Note').unbind('keydown.Note');
                exports.updateNav();
              }
            };
            $(selectedElem).attr('contenteditable', true).focus().bind('blur.Note', finishRename).bind('keydown', finishRename);
          }
        }
      });
    },

    /** Check for empty notes to remove. */
    deselectNoteBubble: function() {
      $('#note-well .note-page section').attr('contenteditable', null).filter(":not('.note-title')").each(function(index, section) {
        if ($(section).text().trim() === '' && $(section).find('img, canvas').length === 0) {
          $(section).remove();
        }
      });
      exports.updateNav();
    },

    /**
     * Switches to the section with the corresponding index.
     *
     * @param section {Number} the section index
     */
    switchToSection: function(section) {
      $('.note-section').hide();
      $('.note-section').eq(section).show();
      $(document).trigger('clear_select');
    },

    /**
     * Switches to the page with the corresponding section and page indexes.
     *
     * @param section {Number} the section index
     * @param page {Number} the page index
     */
    switchToPage: function(section, page) {
      exports.switchToSection(section);
      $('.note-page').hide();
      $('.note-section').eq(section).children().eq(page).show();
      exports.updateNav();
    }
  };
  $('.content').hide().addClass('content-note').fadeIn();
  $('body').addClass('layout-note');
  $('.content').append($('

'));
  $('body').append(JST['templates/note-nav-sidebar']({}));

  var hidden = false;
  $('#note-nav .toggle-sidebar, .return_edit .menu').click(function() {
    var pos = -250;
    if (hidden) {
      pos = 0;
    }
    $('#note-nav').toggleClass('offscreen');
    $('.content_well').css({
      left: pos + 250
    });
    _.delay(function() {
      $(document).trigger('resize');
    }, 200);
    hidden = !hidden;
  });
  // Data storage
  if (!WebSyncData.body) {
    WebSyncData.body = [];
  }
  WebSync.toJSON = function() {
    WebSyncData.body = WebSync.DOMToJSON($('#note-well').get(0).childNodes);
    _.each(WebSyncData.body, function(section) {
      delete section.style;
      _.each(section.childNodes, function(node) {
        delete node.style;
      });
    });
  };
  WebSync.fromJSON = function(patch) {
    if (patch) {
      WebSync.applyPatch(patch, '/body/', $('#note-well').get(0));
    } else {
      $('.content #note-well').get(0).innerHTML = WebSync.JSONToDOM(WebSyncData.body);
    }
    exports.updateNav();
  };
  $(document).on('modules_loaded', function() {
    if (_.isEmpty(WebSyncData.body)) {
      $('#note-well').append("

");
      exports.updateNav();
    } else {
      WebSync.fromJSON();
    }
    NProgress.done();
    exports.switchToPage(0, 0);
  });
  $('.content_well').children().bind('mousedown selectstart', function(e) {
    e.stopPropagation();
  });
  $('#note-well').on('click', '.note-page section', function(e) {
    exports.deselectNoteBubble();
    if (WebSyncAuth.access !== 'viewer') {
      $(e.currentTarget).attr('contenteditable', true);
      e.stopPropagation();
    }
  });
  $('#addSection').on('click', function() {
    exports.deselectNoteBubble();
    $('.note-section').hide();
    $('#note-well').append("

");
    exports.updateNav();
  });
  $('#addPage').on('click', function() {
    exports.deselectNoteBubble();
    $('.note-page').hide();
    $('.note-section:visible').eq(0).append("

");
    exports.updateNav();
  });
  $('#note-well').on('click', '.note-page', function(e) {
    exports.deselectNoteBubble();
    if (WebSyncAuth.access !== 'viewer') {
      var page = e.currentTarget;
      var note = $('

 a', function() {
    var section = parseInt($(this).parent().data().index, 10);
    exports.switchToPage(section, 0);
  }).on('click', '.page > a', function() {
    var section = parseInt($(this).parents('.section').data().index, 10);
    var page = parseInt($(this).parent().data().index, 10);
    exports.switchToPage(section, page);
  });
  return exports;
});
<commit_msg>Added equation reflowing to note.js<commit_after>/*global define, $, _, document, WebSyncData, WebSyncAuth, JST, NProgress*/

//= require templates/note-nav-inner
//= require templates/note-nav-sidebar

define('/assets/note.js', ['websync'], function(WebSync) {
  'use strict';
  /**
   * WebSync: Notebook layout handler
   *
   * @exports note
   * @module note
   */
  var exports = {
    /** Trigger an update for the nav. */
    updateNav: function() {
      var activeSection = $('.note-section:visible')[0];
      var activePage = $('.note-page:visible')[0];

      var sections = _.map($('.note-section'), function(section) {
        var name = section.dataset.name || 'Unnamed Section';
        var pages = _.map($(section).children(), function(page) {
          var $children = $(page).children();
          var pageName = $children.filter('.note-title').text() ||
            $children.filter(":not('.note-title')").first().text() ||
            'Unnamed Page';

          return {
            active: page === activePage,
            name: pageName.trim()
          };
        });

        return {
          name: name,
          active: section === activeSection,
          pages: pages
        };
      });
      $('#notesView').html(JST['templates/note-nav-inner']({
        sections: sections
      }));
      var selectedElem = null;

      var dragElem = null;
      var secondLevel = false;
      $('#notesView li').on('dragstart', function(e) {
        secondLevel = $(this).parents('ul > li > ul').length !== 0;
        e.originalEvent.dataTransfer.effectAllowed = 'move';
        e.originalEvent.dataTransfer.setData('text/plain', $(this).data().index);
        dragElem = this;
        e.stopPropagation();
      }).on('dragenter', function(e) {
        e.preventDefault();
      }).on('dragover', function(e) {
        var c2 = $(e.target).parents('ul > li > ul').length !== 0;
        if (secondLevel && c2) {
          $(this).addClass('over');
        } else if (!secondLevel) {
          $(e.target).parents('#notesView > ul > li').addClass('over');
        }
        e.stopPropagation();
        e.preventDefault();
      }).on('dragleave', function() {
        $(this).removeClass('over');
      }).on('drop', function(e) {
        $('li.over').removeClass('over');
        var origSection, targetSection;
        if (secondLevel) {
          var origPage = $(dragElem).children('a').data().index;
          origSection = $(dragElem).
          parents('#notesView > ul > li').children('a').
          data().index;

          var targetPage = $(e.target).data().index;
          targetSection = $(e.target).
          parents('#notesView > ul > li').children('a').
          data().index;

          var page = $('.note-section').eq(origSection).children().eq(origPage);
          if ($(e.target).parents('#notesView > ul > li > ul').length !== 0) {
            $('.note-section').eq(targetSection).children().eq(targetPage).after(page);
          } else {
            $('.note-section').eq(targetSection).prepend(page);
          }
        } else {
          origSection = $(dragElem).children('a').data().index;
          targetSection = $(e.target).parents('#notesView > ul > li').
          children('a').data().index;
          var section = $('.note-section').eq(origSection);
          $('.note-section').eq(targetSection).after(section);
        }
        e.preventDefault();
        e.stopPropagation();
        exports.updateNav();
      });
      $('#notesView a').contextmenu({
        target: '#context-menu',
        before: function(element) {
          if ($(element).hasClass('page')) {
            $("#context-menu li:contains('Rename')").hide();
          } else {
            $("#context-menu li:contains('Rename')").show();
          }
          selectedElem = element[0];
          return true;
        },
        onItem: function(element, b) {
          var op = b.target.innerText;
          var target, section;
          var selectedElem = element[0];
          if ($(selectedElem.parentElement).hasClass('page')) {
            var page = $(selectedElem.parentElement).data().index;
            section = $(selectedElem.parentElement).parent().parent().parent().children().first().data().index;
            target = $('.note-section').eq(section).children().eq(page);
          } else if ($(selectedElem.parentElement).hasClass('section')) {
            section = $(selectedElem.parentElement).data().index;
            target = $('.note-section').eq(section);
          }
          if (op === 'Delete') {
            target.remove();
            exports.updateNav();
          } else if (op === 'Rename') {
            var finishRename = function(e) {
              // Enter or Escape
              target[0].dataset.name = $(selectedElem).text();
              if (!e.keyCode || e.keyCode === 13 || e.keyCode === 27) {
                e.preventDefault();
                $(selectedElem).unbind('blur.Note').unbind('keydown.Note');
                exports.updateNav();
              }
            };
            $(selectedElem).attr('contenteditable', true).focus().bind('blur.Note', finishRename).bind('keydown', finishRename);
          }
        }
      });
    },

    /** Check for empty notes to remove. */
    deselectNoteBubble: function() {
      $('#note-well .note-page section').attr('contenteditable', null).filter(":not('.note-title')").each(function(index, section) {
        if ($(section).text().trim() === '' && $(section).find('img, canvas').length === 0) {
          $(section).remove();
        }
      });
      exports.updateNav();
    },

    /**
     * Switches to the section with the corresponding index.
     *
     * @param section {Number} the section index
     */
    switchToSection: function(section) {
      $('.note-section').hide();
      $('.note-section').eq(section).show();
      $(document).trigger('clear_select');
    },

    /**
     * Switches to the page with the corresponding section and page indexes.
     *
     * @param section {Number} the section index
     * @param page {Number} the page index
     */
    switchToPage: function(section, page) {
      exports.switchToSection(section);
      $('.note-page').hide();
      var $page = $('.note-section').eq(section).children().eq(page);
      $page.show();
      exports.updateNav();
      if (window.MathQuill) {
        $page.find('.Equation-Editable').each(function(){
          MathQuill.MathField(this).reflow()
        });
      }
    }
  };
  $('.content').hide().addClass('content-note').fadeIn();
  $('body').addClass('layout-note');
  $('.content').append($('

'));
  $('body').append(JST['templates/note-nav-sidebar']({}));

  var hidden = false;
  $('#note-nav .toggle-sidebar, .return_edit .menu').click(function() {
    var pos = -250;
    if (hidden) {
      pos = 0;
    }
    $('#note-nav').toggleClass('offscreen');
    $('.content_well').css({
      left: pos + 250
    });
    _.delay(function() {
      $(document).trigger('resize');
    }, 200);
    hidden = !hidden;
  });
  // Data storage
  if (!WebSyncData.body) {
    WebSyncData.body = [];
  }
  WebSync.toJSON = function() {
    WebSyncData.body = WebSync.DOMToJSON($('#note-well').get(0).childNodes);
    _.each(WebSyncData.body, function(section) {
      delete section.style;
      _.each(section.childNodes, function(node) {
        delete node.style;
      });
    });
  };
  WebSync.fromJSON = function(patch) {
    if (patch) {
      WebSync.applyPatch(patch, '/body/', $('#note-well').get(0));
    } else {
      $('.content #note-well').get(0).innerHTML = WebSync.JSONToDOM(WebSyncData.body);
    }
    exports.updateNav();
  };
  $(document).on('modules_loaded', function() {
    if (_.isEmpty(WebSyncData.body)) {
      $('#note-well').append("

");
      exports.updateNav();
    } else {
      WebSync.fromJSON();
    }
    NProgress.done();
    exports.switchToPage(0, 0);
  });
  $('.content_well').children().bind('mousedown selectstart', function(e) {
    e.stopPropagation();
  });
  $('#note-well').on('click', '.note-page section', function(e) {
    exports.deselectNoteBubble();
    if (WebSyncAuth.access !== 'viewer') {
      $(e.currentTarget).attr('contenteditable', true);
      e.stopPropagation();
    }
  });
  $('#addSection').on('click', function() {
    exports.deselectNoteBubble();
    $('.note-section').hide();
    $('#note-well').append("

");
    exports.updateNav();
  });
  $('#addPage').on('click', function() {
    exports.deselectNoteBubble();
    $('.note-page').hide();
    $('.note-section:visible').eq(0).append("

");
    exports.updateNav();
  });
  $('#note-well').on('click', '.note-page', function(e) {
    exports.deselectNoteBubble();
    if (WebSyncAuth.access !== 'viewer') {
      var page = e.currentTarget;
      var note = $('

 a', function() {
    var section = parseInt($(this).parent().data().index, 10);
    exports.switchToPage(section, 0);
  }).on('click', '.page > a', function() {
    var section = parseInt($(this).parents('.section').data().index, 10);
    var page = parseInt($(this).parent().data().index, 10);
    exports.switchToPage(section, page);
  });
  return exports;
});
<|endoftext|>


<commit_before>'use strict';
var sequelizePaperTrailOptions = {
  revisionAttribute: 'revision',
  revisionModel: 'Revisions',
  revisionChangeModel: 'RevisionChange',
  enableRevisionChangeModel: false,
  UUID: false,
  underscored: true,
  underscoredAttributes: true,
  defaultAttributes: {
    documentId: 'document_id',
    revisionId: 'revision_id'
  },
  enableCompression: false,
  enableMigration: false,
  enableStrictDiff: true,
  continuationKey: 'userId'
};

module.exports = {
  up: function (queryInterface, Sequelize) {
    // Load default options.
    sequelizePaperTrailOptions.defaultAttributes = {
      documentId: 'document_id',
      revisionId: 'revision_id'
    };

    // Revision model
    var attributes = {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      model: {
        type: Sequelize.TEXT,
        allowNull: false
      },
      document: {
        type: Sequelize.TEXT('MEDIUMTEXT'),
        allowNull: false
      },
      'user_id': {
        type: Sequelize.INTEGER,
        allowNull: true
      },
      operation: {
        type: Sequelize.STRING(7),
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    };
    attributes[sequelizePaperTrailOptions.defaultAttributes.documentId] = {
      type: Sequelize.INTEGER,
      allowNull: false
    };
    attributes[sequelizePaperTrailOptions.revisionAttribute] = {
      type: Sequelize.INTEGER,
      allowNull: false
    };

    queryInterface.createTable(sequelizePaperTrailOptions.revisionModel, attributes);

    attributes = {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      path: {
        type: Sequelize.TEXT,
        allowNull: false
      },
      document: {
        type: Sequelize.TEXT('MEDIUMTEXT'),
        allowNull: false
      },
      diff: {
        type: Sequelize.TEXT('MEDIUMTEXT'),
        allowNull: false
      },
      revision_id: {
        allowNull: true,
        type: Sequelize.INTEGER
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    };

    // RevisionChange model
    queryInterface.createTable(sequelizePaperTrailOptions.revisionChangeModel, attributes);
  },

  down: function (queryInterface, Sequelize) {
    return Promise.all([
      queryInterface.dropTable(sequelizePaperTrailOptions.revisionModel),
      queryInterface.dropTable(sequelizePaperTrailOptions.revisionChangeModel)
    ]);
  }
};
<commit_msg>remove duplicate migration<commit_after><|endoftext|>


<commit_before>Ti.include('and-common.js');

var refreshing = false;

function getFormattedDate(){
    var date = new Date();
    return date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes();
}

var tableHeader = Ti.UI.createView({
    backgroundColor:'#e2e7ed',
    width:320, height:60
});

var border = Ti.UI.createView({
    backgroundColor:'#576c89',
    bottom:0,
    height:2
});

tableHeader.add(border);

var labelStatus = Ti.UI.createLabel({
    color:'#576c89',
    font:{fontSize:13, fontWeight:'bold'},
    text:'Updating...',
    textAlign:'center',
    left:55, bottom:30,
    width:200
});
tableHeader.add(labelStatus);

var labelLastUpdated = Ti.UI.createLabel({
    color:'#576c89',
    font:{fontSize:12},
    text:'Last Updated: ' + getFormattedDate(),
    textAlign:'center',
    left:55, bottom:15,
    width:200
});
tableHeader.add(labelLastUpdated);

var actInd = Ti.UI.createActivityIndicator({
    left:20, bottom:13,
    width:30, height:30
});

tableHeader.add(actInd);
var tableHeaderRow = Ti.UI.createTableViewRow({
	height: Ti.UI.SIZE,
});
tableHeaderRow.add(tableHeader);

var refresh = function(e){

	if (refreshing){
		return;
	}

	labelStatus.text = 'Updating...';
	tbl.insertRowBefore(0,tableHeaderRow);
	actInd.show();

	refreshing = true;

	var loader = Titanium.Network.createHTTPClient();

	loader.open("GET","http://dndev.staging.wpengine.com/api/adjacent/get_next_posts/?id="+parseInt(recentID,10));

	loader.onload = function()
	{
		var wordpress = JSON.parse(this.responseText);

		var wp_length = wordpress.posts.length;

		if (wp_length > 0){
			recentID = wordpress.posts[wp_length-1].id;
		}
		else{
			actInd.hide();
			labelStatus.text = 'That\'s all, folks!';
			setTimeout(function(){
				tbl.deleteRow(tableHeaderRow);
			}, 2000);
		}
		alert(wp_length);
		for (i = 0; i < wp_length; i++)
		{
			tbl.deleteRow(tableHeaderRow);

			if (firstAd == 0) {
				var adMobRow = createAdMobView();
				tbl.insertRowBefore(0, adMobRow);
				firstAd = 10;
			}c

			firstAd--;
			var articleContent = wordpress.posts[i].content; // The tweet message
			var articleTitle = wordpress.posts[i].title; // The screen name of the user
			var author = wordpress.posts[i].author.name;
			var id = wordpress.posts[i].id;
			var url = wordpress.posts[i].url;
			var date = wordpress.posts[i].date;
			var modified = wordpress.posts[i].modified;
			var thumbail;

			if (wordpress.posts[i].attachments.length > 0)
				thumbnail = wordpress.posts[i].attachments[0].images.small.url
			else
				thumbnail = 'images/default_thumb.png';

			// Create a row and set its height to auto
			alert(date);
			var articleRow = make_content_view(articleTitle, articleContent, thumbnail, url, id, date, author, modified);
			table_rows[id] = articleRow;

			tbl.insertRowBefore(0, articleRow);
		}

		articleData = tbl.data;
		update_content();
		refreshing = false;
	}

	loader.onerror = function(e){
		tbl.deleteRow(tableHeaderRow);
		//change_date_labels();
		update_content();
		refreshing = false;
	}

	loader.send();

    // and push this into our table.
    // now we're done; reset the loadData flag and start the interval up again
};

var change_date_labels = function(){
	refreshing = true;
	for (id in table_rows){
		date = get_relative_time(table_rows[id].date);
		table_rows[id].date_label.text = date;
	}
	refreshing = false;
};

var update_content = function(){
	var rows = {};
	for (id in table_rows){
		rows[id] = (table_rows[id].modified);
	}

	var json_rows = JSON.stringify(rows);

	var loader = Ti.Network.createHTTPClient({Timeout: 10000});
	loader.open('GET','http://dndev.staging.wpengine.com/api/refresh/check_date_modified/?outdated_posts=' + json_rows);

	loader.onload = function(){
		var modified_posts = JSON.parse(this.responseText);
		alert(modified_posts.posts.length);
		for (i = 0; i < modified_posts.posts.length; i++){
			var id = modified_posts.posts[i].id;

			table_rows[id].title_label.text = modified_posts.posts[i].title;
			table_rows[id].url = modified_posts.posts[i].url;
			table_rows[id].content = modified_posts.posts[i].content;
			table_rows[id].articleTitle = modified_posts.posts[i].title;
			table_rows[id].id = modified_posts.posts[i].id;
			table_rows[id].date = modified_posts.posts[i].date;
			table_rows[id].modified = modified_posts.posts[i].modified;
			alert(table_rows[id].title + ' ' + table_rows[id].date);
		}
	}

	loader.onerror = function(){
	}

	loader.send();
}

var refreshButton = Ti.UI.createButton({
	title: 'R',
	width: '40dp',
	height: '40dp',
});

refreshButton.addEventListener('click', function(){
	change_date_labels();
	refresh();
	//update_content();
});

header.add(refreshButton);<commit_msg>remove functions moved to wordpress<commit_after>Ti.include('and-common.js');

var refreshing = false;

function getFormattedDate(){
    var date = new Date();
    return date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes();
}

var tableHeader = Ti.UI.createView({
    backgroundColor:'#e2e7ed',
    width:320, height:60
});

var border = Ti.UI.createView({
    backgroundColor:'#576c89',
    bottom:0,
    height:2
});

tableHeader.add(border);

var labelStatus = Ti.UI.createLabel({
    color:'#576c89',
    font:{fontSize:13, fontWeight:'bold'},
    text:'Updating...',
    textAlign:'center',
    left:55, bottom:30,
    width:200
});
tableHeader.add(labelStatus);

var labelLastUpdated = Ti.UI.createLabel({
    color:'#576c89',
    font:{fontSize:12},
    text:'Last Updated: ' + getFormattedDate(),
    textAlign:'center',
    left:55, bottom:15,
    width:200
});
tableHeader.add(labelLastUpdated);

var actInd = Ti.UI.createActivityIndicator({
    left:20, bottom:13,
    width:30, height:30
});

tableHeader.add(actInd);
var tableHeaderRow = Ti.UI.createTableViewRow({
	height: Ti.UI.SIZE,
});
tableHeaderRow.add(tableHeader);

var refresh = function(e){

	if (refreshing){
		return;
	}

	labelStatus.text = 'Updating...';
	tbl.insertRowBefore(0,tableHeaderRow);
	actInd.show();

	var loader = Titanium.Network.createHTTPClient();

	loader.open("GET","http://dndev.staging.wpengine.com/api/adjacent/get_next_posts/?id="+parseInt(recentID,10));

	loader.onload = function()
	{
		var wordpress = JSON.parse(this.responseText);

		var wp_length = wordpress.posts.length;

		if (wp_length > 0){
			recentID = wordpress.posts[wp_length-1].id;
		}
		else{
			actInd.hide();
			labelStatus.text = 'That\'s all, folks!';
			setTimeout(function(){
				tbl.deleteRow(tableHeaderRow);
			}, 2000);
		}
		alert(wp_length);
		for (i = 0; i < wp_length; i++)
		{
			tbl.deleteRow(tableHeaderRow);

			if (firstAd == 0) {
				var adMobRow = createAdMobView();
				tbl.insertRowBefore(0, adMobRow);
				firstAd = 10;
			}

			firstAd--;
			var articleContent = wordpress.posts[i].content; // The tweet message
			var articleTitle = wordpress.posts[i].title; // The screen name of the user
			var author = wordpress.posts[i].author.name;
			var id = wordpress.posts[i].id;
			var url = wordpress.posts[i].url;
			var date = wordpress.posts[i].date;
			var modified = wordpress.posts[i].modified;
			var thumbail;

			if (wordpress.posts[i].attachments.length > 0)
				thumbnail = wordpress.posts[i].attachments[0].images.small.url
			else
				thumbnail = 'images/default_thumb.png';

			// Create a row and set its height to auto
			alert(date);
			var articleRow = make_content_view(articleTitle, articleContent, thumbnail, url, id, date, author, modified);
			table_rows[id] = articleRow;

			tbl.insertRowBefore(0, articleRow);
		}

		articleData = tbl.data;
		update_content();
	}

	loader.onerror = function(e){
		tbl.deleteRow(tableHeaderRow);
	}

	loader.send();
};

var change_date_labels = function(){
	for (id in table_rows){
		date = get_relative_time(table_rows[id].date);
		table_rows[id].date_label.text = date;
	}
};

var update_content = function(){
	var rows = {};
	for (id in table_rows){
		rows[id] = (table_rows[id].modified);
	}

	var json_rows = JSON.stringify(rows);

	var loader = Ti.Network.createHTTPClient({Timeout: 10000});
	loader.open('GET','http://dndev.staging.wpengine.com/api/refresh/check_date_modified/?outdated_posts=' + json_rows);

	loader.onload = function(){
		var modified_posts = JSON.parse(this.responseText);
		alert(modified_posts.posts.length);
		for (i = 0; i < modified_posts.posts.length; i++){
			var id = modified_posts.posts[i].id;

			table_rows[id].title_label.text = modified_posts.posts[i].title;
			table_rows[id].url = modified_posts.posts[i].url;
			table_rows[id].content = modified_posts.posts[i].content;
			table_rows[id].articleTitle = modified_posts.posts[i].title;
			table_rows[id].id = modified_posts.posts[i].id;
			table_rows[id].date = modified_posts.posts[i].date;
			table_rows[id].modified = modified_posts.posts[i].modified;
		}
		refreshing = false;
	}

	loader.onerror = function(){
		refreshing = false;
	}

	loader.send();
}<|endoftext|>


<commit_before>#!/usr/bin/env node

var path   = require('path');

// this must be set before "server.js" is loaded
process.env.HARAKA = process.env.HARAKA || path.resolve('.');
try {
    require.paths.unshift(path.join(process.env.HARAKA, 'node_modules'));
}
catch(e) {
    process.env.NODE_PATH += ':' + path.join(process.env.HARAKA, 'node_modules');
}

var fs     = require('fs');
var logger = require('./logger');
var server = require('./server');

exports.version = JSON.parse(
        fs.readFileSync(path.join(__dirname, './package.json'), 'utf8')
    ).version;

process.on('uncaughtException', function (err) {
    if (err.stack) {
        err.stack.split("\n").forEach(logger.logcrit);
    }
    else {
        logger.logcrit('Caught exception: ' + err);
    }
    if (!server.ready) {
        logger.logcrit('Server not ready yet. Stopping.');
        logger.dump_logs();
        process.exit();
    }
});

logger.log("INFO", "Starting up Haraka version " + exports.version);

server.createServer();
<commit_msg>Removed uncaughtException hook. Make v0.4.x require.paths work same as 0.5.x+ version<commit_after>#!/usr/bin/env node

var path   = require('path');

// this must be set before "server.js" is loaded
process.env.HARAKA = process.env.HARAKA || path.resolve('.');
try {
    require.paths.push(path.join(process.env.HARAKA, 'node_modules'));
}
catch(e) {
    process.env.NODE_PATH += ':' + path.join(process.env.HARAKA, 'node_modules');
}

var fs     = require('fs');
var logger = require('./logger');
var server = require('./server');

exports.version = JSON.parse(
        fs.readFileSync(path.join(__dirname, './package.json'), 'utf8')
    ).version;

logger.log("INFO", "Starting up Haraka version " + exports.version);

server.createServer();
<|endoftext|>


<commit_before>(function() {
	exports.getDefaultBackground = function() {
		return '#dfdfdf';
	}

	exports.getWhitishBackground = function() {
		return '#f9f9f9';
	}

	exports.getBarColor = function() {
		return '#bbbbbb';
	}

	exports.createLoadingWindow = function(top) {
		if(top === undefined) { top = '38%'; }

		var win = Ti.UI.createWindow({
			width: 320,
			height: Ti.Platform.displayCaps.platformHeight,
			orientationModes: [Ti.UI.PORTRAIT]
		});

		var view = Ti.UI.createView({
			height: 60,
			width: 60,
			top: top,
			borderRadius: 10,
			backgroundColor: '#000',
			opacity: 0.6
		});

		win.add(view);

		var spinWheel = Ti.UI.createActivityIndicator({
			style: Ti.UI.iPhone.ActivityIndicatorStyle.BIG
		});

		view.add(spinWheel);
		spinWheel.show();

		return win;
	}

	//just a few UI elements, so they can be used painlessly
	exports.createFlexibleSpace = function() {
		return Ti.UI.createButton({
			systemButton: Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE
		});
	}

	exports.createFixedSpace = function(width) {
		return Ti.UI.createButton({
			systemButton: Ti.UI.iPhone.SystemButton.FIXED_SPACE,
			width: width
		});
	}

	exports.createDestructionView = function(title) {
		var b_destruction = Ti.UI.createButton({
			backgroundImage: '/img/big_red_button.png',
			top: 10,
			height: 45,
			width: 300
		});

		var lbl_title = Ti.UI.createLabel({
			text: title,
			shadowColor: '#8c2a31',
			shadowOffset: {
				x: 0,
				y: -1
			},
			font: {
				fontSize: 19,
				fontWeight: 'bold',
				fontFamily: 'Helvetica Neue'
			},
			color: 'white',
			width: 300,
			height: 45,
			textAlign: 'center'
		});

		b_destruction.add(lbl_title);
		var view = Ti.UI.createView({
			height: b_destruction.height + 30
		});

		view.add(b_destruction);

		return view;
	}

	//returns a row containing a title and a value. opens a window when clicked
	exports.createParentRow = function(title, header, rowName, configID) {
		var row = Ti.UI.createTableViewRow({
			title: title,
			hasChild: true,
			header: header
		});

		//the label containing the value you want to display
		var lbl = Ti.UI.createLabel({
			right: 10,
			height: 35,
			textAlign: 'right',
			width: 150,
			highlightedColor: 'white',
			color: '#336699'
		});

		row.add(lbl);

		row.addEventListener('click', function(e) {
			var win = Ti.UI.createWindow({
				url: 'options_select.js',
				title: title,
				rowName: rowName,
				configID: configID,
				backgroundColor: exports.getDefaultBackground(),
				barColor: Ui.getBarColor()
			});
			Ti.UI.currentTab.open(win, {
				animated: true
			});
		});
		return row;
	}

	//returns a row containing a text field
	exports.createTextFieldRow = function(text) {
		var row = Ti.UI.createTableViewRow({
			title: text,
			selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.NONE
		});

		var textfield = Ti.UI.createTextField({
			color: '#336699',
			height: 35,
			top: 4,
			right: 20,
			width: 80,
			borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
			keyboardType: Ti.UI.KEYBOARD_NUMBERS_PUNCTUATION,
			appearance: Titanium.UI.KEYBOARD_APPEARANCE_ALERT,
			hintText: '12345678'
		});

		textfield.addEventListener('change', function(e) {
			//the value must be between 0 and 8(-9?) characters only
			e.source.value = e.source.value.slice(0, 9);
		});

		row.add(textfield);
		return row;
	}
})();<commit_msg>Vehicle reversing. Vehicle reversing.<commit_after>(function() {
	exports.getDefaultBackground = function() {
		return '#dfdfdf';
	}

	exports.getWhitishBackground = function() {
		return '#f9f9f9';
	}

	exports.getBarColor = function() {
		return '#909090';
	}

	exports.createLoadingWindow = function(top) {
		if(top === undefined) { top = '38%'; }

		var win = Ti.UI.createWindow({
			width: 320,
			height: Ti.Platform.displayCaps.platformHeight,
			orientationModes: [Ti.UI.PORTRAIT]
		});

		var view = Ti.UI.createView({
			height: 60,
			width: 60,
			top: top,
			borderRadius: 10,
			backgroundColor: '#000',
			opacity: 0.6
		});

		win.add(view);

		var spinWheel = Ti.UI.createActivityIndicator({
			style: Ti.UI.iPhone.ActivityIndicatorStyle.BIG
		});

		view.add(spinWheel);
		spinWheel.show();

		return win;
	}

	//just a few UI elements, so they can be used painlessly
	exports.createFlexibleSpace = function() {
		return Ti.UI.createButton({
			systemButton: Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE
		});
	}

	exports.createFixedSpace = function(width) {
		return Ti.UI.createButton({
			systemButton: Ti.UI.iPhone.SystemButton.FIXED_SPACE,
			width: width
		});
	}

	exports.createDestructionView = function(title) {
		var b_destruction = Ti.UI.createButton({
			backgroundImage: '/img/big_red_button.png',
			top: 10,
			height: 45,
			width: 300
		});

		var lbl_title = Ti.UI.createLabel({
			text: title,
			shadowColor: '#8c2a31',
			shadowOffset: {
				x: 0,
				y: -1
			},
			font: {
				fontSize: 19,
				fontWeight: 'bold',
				fontFamily: 'Helvetica Neue'
			},
			color: 'white',
			width: 300,
			height: 45,
			textAlign: 'center'
		});

		b_destruction.add(lbl_title);
		var view = Ti.UI.createView({
			height: b_destruction.height + 30
		});

		view.add(b_destruction);

		return view;
	}

	//returns a row containing a title and a value. opens a window when clicked
	exports.createParentRow = function(title, header, rowName, configID) {
		var row = Ti.UI.createTableViewRow({
			title: title,
			hasChild: true,
			header: header
		});

		//the label containing the value you want to display
		var lbl = Ti.UI.createLabel({
			right: 10,
			height: 35,
			textAlign: 'right',
			width: 150,
			highlightedColor: 'white',
			color: '#336699'
		});

		row.add(lbl);

		row.addEventListener('click', function(e) {
			var win = Ti.UI.createWindow({
				url: 'options_select.js',
				title: title,
				rowName: rowName,
				configID: configID,
				backgroundColor: exports.getDefaultBackground(),
				barColor: Ui.getBarColor()
			});
			Ti.UI.currentTab.open(win, {
				animated: true
			});
		});
		return row;
	}

	//returns a row containing a text field
	exports.createTextFieldRow = function(text) {
		var row = Ti.UI.createTableViewRow({
			title: text,
			selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.NONE
		});

		var textfield = Ti.UI.createTextField({
			color: '#336699',
			height: 35,
			top: 4,
			right: 20,
			width: 80,
			borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
			keyboardType: Ti.UI.KEYBOARD_NUMBERS_PUNCTUATION,
			appearance: Titanium.UI.KEYBOARD_APPEARANCE_ALERT,
			hintText: '12345678'
		});

		textfield.addEventListener('change', function(e) {
			//the value must be between 0 and 8(-9?) characters only
			e.source.value = e.source.value.slice(0, 9);
		});

		row.add(textfield);
		return row;
	}
})();<|endoftext|>


<commit_before>(function () {
    "use strict";

    Mapbender.Digitizer.Menu = function (schema) {

        var menu = this;
        menu.schema = schema;

        var frame = $("
").addClass('frame');

        frame.append('
');

        menu.appendResultTableControlButtons_(frame);

        menu.appendCurrentExtentSwitch_(frame);

        menu.generateResultTable_(frame);

        frame.hide();

        menu.currentExtentSearch = schema.currentExtentSearch;
    };

    Mapbender.Digitizer.Menu.prototype.appendResultTableControlButtons_ = function (frame) {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.showVisibilityNavigation && schema.allowChangeVisibility) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOff eyeOff");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.hideAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: true});
                });
            });
            buttons['hideAll'] = $button;

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOn eyeOn");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.showAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: false});
                });
            });
            buttons['showAll'] = $button;
        }
        if (schema.allowSaveAll) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-save save");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.saveAll'));
            $button.attr("disabled", "disabled");
            $button.click(function () {
                schema.layer.getSource().getFeatures().filter(function (feature) {
                    return (["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState")));
                }).forEach(function (feature) {
                    schema.saveFeature(feature);
                });
            });
            buttons['allowSaveAll'] = $button;

        }

        var $div = $("
");
        $div.addClass("resultTableControlButtons");
        $.each(buttons, function (name, $button) {
            $div.append($button);
        });
        frame.append($div);
    };

    Mapbender.Digitizer.Menu.prototype.appendCurrentExtentSwitch_ = function (frame) {
        var menu = this;
        var schema = menu.schema;
        if (schema.showExtendSearchSwitch) {
            var $checkbox = $("<input type='checkbox' />");
            var title = Mapbender.trans('mb.digitizer.toolset.current-extent');
            $checkbox.attr('title', title);
            if (schema.currentExtentSearch) {
                $checkbox.attr("checked", "checked");
            }
            $checkbox.change(function (e) {
                var currentExtentSearch = !!$(e.originalEvent.target).prop("checked");
                menu.changeCurrentExtentSearch_(currentExtentSearch)
            });
            frame.append("
");
            var $div = $("
");
            $div.addClass("form-group checkbox onlyExtent");
            var $label = $("");
            $label.append($checkbox);
            $label.append(title);
            $div.append($label);
            frame.append($div);
        }
    };

    Mapbender.Digitizer.Menu.prototype.changeCurrentExtentSearch_ = function(currentExtentSearch) {
        var widget = this.widget;
        this.currentExtentSearch = !!currentExtentSearch;
        if (this.resultTable) {
            var features = this.schema.layer.getSource().getFeatures();
            if (this.currentExtentSearch) {
                features = features.filter(function(feature) {
                    return widget.isInExtent(feature);
                });
            }
            this.resultTable.redraw(features);
        }
    };

    Mapbender.Digitizer.Menu.prototype.registerResultTableEvents = function (resultTable, frame) {
        var menu = this;
        var schema = menu.schema;
        var widget = schema.widget;
        var map = widget.map;
        menu.resultTable = resultTable;

        $(schema).on("Digitizer.FeaturesLoaded", function (event) {
            var features = event.features;
            resultTable.redraw(features);
        });

        $(schema).on("Digitizer.FeatureAddedManually", function (event) {
            var feature = event.feature;
            resultTable.addRow(feature);
        });

        map.on(ol.MapEventType.MOVEEND, function (event) {

            var resolution = map.getView().getResolution();

            if (resolution > schema.layer.getMaxResolution() || resolution < schema.layer.getMinResolution()) {

                resultTable.clear();

            } else {

                if (resultTable.currentExtentSearch) {
                    var features = schema.layer.getSource().getFeatures().filter(function (feature) {
                        return widget.isInExtent(feature);
                    });
                    resultTable.redraw(features);
                } else {
                    resultTable.redraw(schema.layer.getSource().getFeatures());
                }

            }

        });

        resultTable.element.delegate("tbody > tr", 'click', function () {
            var tr = this;
            var row = resultTable.getApi().row(tr);
            var feature = row.data();

            if (feature) {

                if (schema.zoomOnResultTableClick) {
                    schema.zoomToFeature(feature);
                }
                if (schema.openDialogOnResultTableClick) {
                    schema.openFeatureEditDialog(feature);
                }
            } else {
                console.warn("No Feature in row", row);
            }

        });

        schema.layer.getSource().on(ol.source.VectorEventType.ADDFEATURE, function (event) {
            var feature = event.feature;

            if (resultTable.currentExtentSearch && !widget.isInExtent(feature)) {
                return;
            }

            feature.on('Digitizer.HoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, true);

            });

            feature.on('Digitizer.UnhoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, false);

            });

            feature.on('Digitizer.ModifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.removeAttr("disabled");
                }

                frame.find(".resultTableControlButtons .save").removeAttr("disabled");

            });

            feature.on('Digitizer.UnmodifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.attr("disabled", "disabled");
                }

                var length = schema.layer.getSource().getFeatures().filter(function (feature) {
                    return ["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState"));
                }).length;

                if (length === 0) {
                    frame.find(".resultTableControlButtons .save").attr("disabled", "disabled");
                }

            });

            feature.on('Digitizer.toggleVisibility', function (event) {
                var $button = resultTable.getButtonByFeature('.visibility', feature);
                if (!$button) {
                    return;
                }
                if (event.hide) {
                    $button.addClass('icon-eyeOn').removeClass('icon-eyeOff');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleon'));
                } else {
                    $button.addClass('icon-eyeOff').removeClass('icon-eyeOn');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'));
                }
            });

        });

        schema.layer.getSource().on(ol.source.VectorEventType.REMOVEFEATURE, function (event) {
            resultTable.deleteRow(event.feature);
        });

    };

    Mapbender.Digitizer.Menu.prototype.generateResultDataTableButtons = function () {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.allowLocate) {
            buttons['locate'] = {
                title: Mapbender.trans('mb.digitizer.feature.zoomTo'),
                className: 'zoom',
                onClick: function (feature, ui) {
                    schema.zoomToFeature(feature);
                }
            };
        }

        if (schema.allowEditData && schema.allowSaveInResultTable) {
            buttons['save'] = {
                title: Mapbender.trans('mb.digitizer.feature.save.title'),
                className: 'save',
                disabled: true,
                onClick: function (feature, $button) {
                    schema.saveFeature(feature);
                }
            };
        }

        if (schema.allowEditData) {
            buttons['edit'] = {
                title: Mapbender.trans('mb.digitizer.feature.edit'),
                className: 'edit',
                onClick: function (feature, ui) {
                    schema.openFeatureEditDialog(feature);
                }
            };
        }
        if (schema.copy && schema.copy.enable) {
            buttons['copy'] = {
                title: Mapbender.trans('mb.digitizer.feature.clone.title'),
                className: 'copy',
                onClick: function (feature, ui) {
                    schema.copyFeature(feature);
                }
            };
        }
        if (schema.allowCustomStyle) {
            buttons['style'] = {
                title: Mapbender.trans('mb.digitizer.feature.style.change'),
                className: 'style',
                onClick: function (feature, ui) {
                    schema.openChangeStyleDialog(feature);
                }
            };
        }

        if (schema.allowChangeVisibility) {
            buttons['toggleVisibility'] = {
                title: Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'),
                className: 'visibility',
                cssClass: 'icon-eyeOff',
                onClick: function (feature, $button) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: !feature.get("hidden")});
                }
            };
        }

        if (schema.allowDelete) {

            buttons['delete'] = {
                title: Mapbender.trans("mb.digitizer.feature.remove.title"),
                className: 'remove',
                cssClass: 'critical',
                onClick: function (feature, ui) {
                    if (schema.allowDelete) {
                        schema.removeFeature(feature);
                    } else {
                        $.notify("Deletion is not allowed");
                    }
                }
            };
        }

        return buttons;

    };

    Object.assign(Mapbender.Digitizer.Menu.prototype, {
        generateResultDataTableColumns: function (schema) {

            var columns = [];

            var createResultTableDataFunction = function (columnId, fieldSettings) {

                return function (feature, type, val, meta) {

                    var escapeHtml = function (str) {

                        return str.replace(/["&'\/<>]/g, function (a) {
                            return {
                                '"': '"',
                                '&': '&',
                                "'": ''',
                                '/': '/',
                                '<': '<',
                                '>': '>'
                            }[a];
                        });
                    };

                    var data = feature.get('data') && feature.get('data').get(columnId);
                    if (typeof (data) == 'string') {
                        data = escapeHtml(data);
                    }
                    return data || '';
                };
            };

            $.each(schema.tableFields, function (columnId, fieldSettings) {
                fieldSettings.title = fieldSettings.label;
                fieldSettings.data = fieldSettings.data || createResultTableDataFunction(columnId, fieldSettings);
                columns.push(fieldSettings);
            });

            return columns;
        },
        getResultTableOptions: function(schema) {
            var menu = this;
            var widget = schema.widget;
            return {
                lengthChange: false,
                pageLength: schema.pageLength,
                searching: schema.inlineSearch,
                info: true,
                processing: false,
                ordering: true,
                paging: true,
                selectable: false,
                autoWidth: false,
                columns: menu.generateResultDataTableColumns(schema),
                buttons: menu.generateResultDataTableButtons(),
                oLanguage: widget.options.tableTranslation
            };
        },
        generateResultTable_: function (frame) {
            var menu = this;
            var schema = menu.schema;
            var widget = schema.widget;

            var resultTableSettings = this.getResultTableOptions(schema);

            var $div = $("
");
            var $table = $div.resultTable(resultTableSettings);

            var resultTable = $table.resultTable("instance");

            // ??? function does not exist
            // resultTable.initializeColumnTitles();

            resultTable.element.delegate("tbody > tr", 'mouseenter', function () {
                var tr = this;
                var row = resultTable.getApi().row(tr);
                var feature = row.data();
                if (feature) {
                    feature.dispatchEvent({type: widget.TYPE + '.HoverFeature'});
                }

            });

            resultTable.element.delegate("tbody > tr", 'mouseleave', function () {
                var tr = this;
                var row = resultTable.getApi().row(tr);
                var feature = row.data();
                if (feature) {
                    feature.dispatchEvent({type: widget.TYPE + '.UnhoverFeature'});
                }
            });

            // menu.registerResultTableEvents(resultTable, frame);

            frame.append($table);
        }
    });

})();
<commit_msg>Put all result table events into one place<commit_after>(function () {
    "use strict";

    Mapbender.Digitizer.Menu = function (schema) {

        var menu = this;
        menu.schema = schema;

        var frame = $("
").addClass('frame');

        frame.append('
');

        menu.appendResultTableControlButtons_(frame);

        menu.appendCurrentExtentSwitch_(frame);

        menu.generateResultTable_(frame);

        frame.hide();

        menu.currentExtentSearch = schema.currentExtentSearch;
    };

    Mapbender.Digitizer.Menu.prototype.appendResultTableControlButtons_ = function (frame) {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.showVisibilityNavigation && schema.allowChangeVisibility) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOff eyeOff");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.hideAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: true});
                });
            });
            buttons['hideAll'] = $button;

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOn eyeOn");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.showAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: false});
                });
            });
            buttons['showAll'] = $button;
        }
        if (schema.allowSaveAll) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-save save");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.saveAll'));
            $button.attr("disabled", "disabled");
            $button.click(function () {
                schema.layer.getSource().getFeatures().filter(function (feature) {
                    return (["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState")));
                }).forEach(function (feature) {
                    schema.saveFeature(feature);
                });
            });
            buttons['allowSaveAll'] = $button;

        }

        var $div = $("
");
        $div.addClass("resultTableControlButtons");
        $.each(buttons, function (name, $button) {
            $div.append($button);
        });
        frame.append($div);
    };

    Mapbender.Digitizer.Menu.prototype.appendCurrentExtentSwitch_ = function (frame) {
        var menu = this;
        var schema = menu.schema;
        if (schema.showExtendSearchSwitch) {
            var $checkbox = $("<input type='checkbox' />");
            var title = Mapbender.trans('mb.digitizer.toolset.current-extent');
            $checkbox.attr('title', title);
            if (schema.currentExtentSearch) {
                $checkbox.attr("checked", "checked");
            }
            $checkbox.change(function (e) {
                var currentExtentSearch = !!$(e.originalEvent.target).prop("checked");
                menu.changeCurrentExtentSearch_(currentExtentSearch)
            });
            frame.append("
");
            var $div = $("
");
            $div.addClass("form-group checkbox onlyExtent");
            var $label = $("");
            $label.append($checkbox);
            $label.append(title);
            $div.append($label);
            frame.append($div);
        }
    };

    Mapbender.Digitizer.Menu.prototype.changeCurrentExtentSearch_ = function(currentExtentSearch) {
        var widget = this.widget;
        this.currentExtentSearch = !!currentExtentSearch;
        if (this.resultTable) {
            var features = this.schema.layer.getSource().getFeatures();
            if (this.currentExtentSearch) {
                features = features.filter(function(feature) {
                    return widget.isInExtent(feature);
                });
            }
            this.resultTable.redraw(features);
        }
    };

    Mapbender.Digitizer.Menu.prototype.registerResultTableEvents = function (resultTable, frame) {
        var menu = this;
        var schema = menu.schema;
        var widget = schema.widget;
        var map = widget.map;
        menu.resultTable = resultTable;

        resultTable.element.delegate("tbody > tr", 'mouseenter', function () {
            var tr = this;
            var row = resultTable.getApi().row(tr);
            var feature = row.data();
            if (feature) {
                feature.dispatchEvent({type: widget.TYPE + '.HoverFeature'});
            }

        });

        resultTable.element.delegate("tbody > tr", 'mouseleave', function () {
            var tr = this;
            var row = resultTable.getApi().row(tr);
            var feature = row.data();
            if (feature) {
                feature.dispatchEvent({type: widget.TYPE + '.UnhoverFeature'});
            }
        });

        $(schema).on("Digitizer.FeaturesLoaded", function (event) {
            var features = event.features;
            resultTable.redraw(features);
        });

        $(schema).on("Digitizer.FeatureAddedManually", function (event) {
            var feature = event.feature;
            resultTable.addRow(feature);
        });

        map.on(ol.MapEventType.MOVEEND, function (event) {

            var resolution = map.getView().getResolution();

            if (resolution > schema.layer.getMaxResolution() || resolution < schema.layer.getMinResolution()) {

                resultTable.clear();

            } else {

                if (resultTable.currentExtentSearch) {
                    var features = schema.layer.getSource().getFeatures().filter(function (feature) {
                        return widget.isInExtent(feature);
                    });
                    resultTable.redraw(features);
                } else {
                    resultTable.redraw(schema.layer.getSource().getFeatures());
                }

            }

        });

        resultTable.element.delegate("tbody > tr", 'click', function () {
            var tr = this;
            var row = resultTable.getApi().row(tr);
            var feature = row.data();

            if (feature) {

                if (schema.zoomOnResultTableClick) {
                    schema.zoomToFeature(feature);
                }
                if (schema.openDialogOnResultTableClick) {
                    schema.openFeatureEditDialog(feature);
                }
            } else {
                console.warn("No Feature in row", row);
            }

        });

        schema.layer.getSource().on(ol.source.VectorEventType.ADDFEATURE, function (event) {
            var feature = event.feature;

            if (resultTable.currentExtentSearch && !widget.isInExtent(feature)) {
                return;
            }

            feature.on('Digitizer.HoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, true);

            });

            feature.on('Digitizer.UnhoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, false);

            });

            feature.on('Digitizer.ModifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.removeAttr("disabled");
                }

                frame.find(".resultTableControlButtons .save").removeAttr("disabled");

            });

            feature.on('Digitizer.UnmodifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.attr("disabled", "disabled");
                }

                var length = schema.layer.getSource().getFeatures().filter(function (feature) {
                    return ["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState"));
                }).length;

                if (length === 0) {
                    frame.find(".resultTableControlButtons .save").attr("disabled", "disabled");
                }

            });

            feature.on('Digitizer.toggleVisibility', function (event) {
                var $button = resultTable.getButtonByFeature('.visibility', feature);
                if (!$button) {
                    return;
                }
                if (event.hide) {
                    $button.addClass('icon-eyeOn').removeClass('icon-eyeOff');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleon'));
                } else {
                    $button.addClass('icon-eyeOff').removeClass('icon-eyeOn');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'));
                }
            });

        });

        schema.layer.getSource().on(ol.source.VectorEventType.REMOVEFEATURE, function (event) {
            resultTable.deleteRow(event.feature);
        });

    };

    Mapbender.Digitizer.Menu.prototype.generateResultDataTableButtons = function () {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.allowLocate) {
            buttons['locate'] = {
                title: Mapbender.trans('mb.digitizer.feature.zoomTo'),
                className: 'zoom',
                onClick: function (feature, ui) {
                    schema.zoomToFeature(feature);
                }
            };
        }

        if (schema.allowEditData && schema.allowSaveInResultTable) {
            buttons['save'] = {
                title: Mapbender.trans('mb.digitizer.feature.save.title'),
                className: 'save',
                disabled: true,
                onClick: function (feature, $button) {
                    schema.saveFeature(feature);
                }
            };
        }

        if (schema.allowEditData) {
            buttons['edit'] = {
                title: Mapbender.trans('mb.digitizer.feature.edit'),
                className: 'edit',
                onClick: function (feature, ui) {
                    schema.openFeatureEditDialog(feature);
                }
            };
        }
        if (schema.copy && schema.copy.enable) {
            buttons['copy'] = {
                title: Mapbender.trans('mb.digitizer.feature.clone.title'),
                className: 'copy',
                onClick: function (feature, ui) {
                    schema.copyFeature(feature);
                }
            };
        }
        if (schema.allowCustomStyle) {
            buttons['style'] = {
                title: Mapbender.trans('mb.digitizer.feature.style.change'),
                className: 'style',
                onClick: function (feature, ui) {
                    schema.openChangeStyleDialog(feature);
                }
            };
        }

        if (schema.allowChangeVisibility) {
            buttons['toggleVisibility'] = {
                title: Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'),
                className: 'visibility',
                cssClass: 'icon-eyeOff',
                onClick: function (feature, $button) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: !feature.get("hidden")});
                }
            };
        }

        if (schema.allowDelete) {

            buttons['delete'] = {
                title: Mapbender.trans("mb.digitizer.feature.remove.title"),
                className: 'remove',
                cssClass: 'critical',
                onClick: function (feature, ui) {
                    if (schema.allowDelete) {
                        schema.removeFeature(feature);
                    } else {
                        $.notify("Deletion is not allowed");
                    }
                }
            };
        }

        return buttons;

    };

    Object.assign(Mapbender.Digitizer.Menu.prototype, {
        generateResultDataTableColumns: function (schema) {

            var columns = [];

            var createResultTableDataFunction = function (columnId, fieldSettings) {

                return function (feature, type, val, meta) {

                    var escapeHtml = function (str) {

                        return str.replace(/["&'\/<>]/g, function (a) {
                            return {
                                '"': '"',
                                '&': '&',
                                "'": ''',
                                '/': '/',
                                '<': '<',
                                '>': '>'
                            }[a];
                        });
                    };

                    var data = feature.get('data') && feature.get('data').get(columnId);
                    if (typeof (data) == 'string') {
                        data = escapeHtml(data);
                    }
                    return data || '';
                };
            };

            $.each(schema.tableFields, function (columnId, fieldSettings) {
                fieldSettings.title = fieldSettings.label;
                fieldSettings.data = fieldSettings.data || createResultTableDataFunction(columnId, fieldSettings);
                columns.push(fieldSettings);
            });

            return columns;
        },
        getResultTableOptions: function(schema) {
            var menu = this;
            var widget = schema.widget;
            return {
                lengthChange: false,
                pageLength: schema.pageLength,
                searching: schema.inlineSearch,
                info: true,
                processing: false,
                ordering: true,
                paging: true,
                selectable: false,
                autoWidth: false,
                columns: menu.generateResultDataTableColumns(schema),
                buttons: menu.generateResultDataTableButtons(),
                oLanguage: widget.options.tableTranslation
            };
        },
        generateResultTable_: function (frame) {
            var menu = this;
            var schema = menu.schema;
            var widget = schema.widget;

            var resultTableSettings = this.getResultTableOptions(schema);

            var $div = $("
");
            var $table = $div.resultTable(resultTableSettings);

            var resultTable = $table.resultTable("instance");

            // ??? function does not exist
            // resultTable.initializeColumnTitles();

            menu.registerResultTableEvents(resultTable, frame);

            frame.append($table);
        }
    });

})();
<|endoftext|>


<commit_before>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var LocationSchema   = new Schema({
	name: String,
	city: String,
	address: String,
	img: String,
	description: String,
	email: String,
	sage_uid: String,
	sage_product_id: String,
	sage_taxtype_id: String,
	sage_message: String,
	_deleted: { type: Boolean, default: false, index: true },
});

LocationSchema.set("_perms", {
	admin: "crud",
	user: "r",
	all: "r"
});

module.exports = mongoose.model('Location', LocationSchema);<commit_msg>Datatill group id<commit_after>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var LocationSchema   = new Schema({
	name: String,
	city: String,
	address: String,
	img: String,
	description: String,
	email: String,
	sage_uid: String,
	sage_product_id: String,
	sage_taxtype_id: String,
	sage_message: String,
	datatill_group_id: Number,
	_deleted: { type: Boolean, default: false, index: true },
});

LocationSchema.set("_perms", {
	admin: "crud",
	user: "r",
	all: "r"
});

module.exports = mongoose.model('Location', LocationSchema);<|endoftext|>