<commit_before>const { CompositeDisposable } = require('atom');
const fs = require('fs-extra');
const path = require('path');
const InputDialog = require('../InputDialog.js');
const sync = require('../dynapp/sync');
const config = require('../dynapp/config');

var treeView;

// Ensure path exists
async function ensurePath(path) {
  if (!fs.existsSync(path)) {
    await fs.mkdir(path, {
      recursive: true
    });
  }
}

async function createWorkFolder(workpath) {
  await ensurePath(workpath);

  try {
    await fs.mkdir(path.join(workpath, 'data-source-items'));
  } catch(ex) {
    // data-source-items already exists
  }
  try {
    await fs.mkdir(path.join(workpath, 'data-objects'));
  } catch(ex) {
    // data-objects already exists
  }
  try {
    await fs.mkdir(path.join(workpath, 'data-items'));
  } catch(ex) {
    // data-items already exists
  }
}

module.exports = {
  subscriptions: null,
  activate(state) {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();
    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'dynapp-atom:download': () => this.download(),
      'dynapp-atom:createConfig': () => this.createConfig(),
      'dynapp-atom:createHgIgnore': () => this.createIgnore(true, '.hgignore'),
      'dynapp-atom:createGitIgnore': () => this.createIgnore(true, '.gitignore'),
      'dynapp-atom:upload': () => this.upload(),
      'dynapp-atom:newDataObject': () => this.newDataObject(),
      'dynapp-atom:newDataSourceItem': () => this.newDataSourceItem()
    }));
    this.sync = new sync.Sync();
  },
  // TODO: Very similar to newDataObject
  // Could probably be a method of DataSourceItem class
  newDataSourceItem() {
    let dialog = new InputDialog({
      labelText: 'Filename',
      async callback (fileName) {
        let projectPath = config.projectPath();
        let python = `#!/usr/bin/env python
import json

def transform(logger, item, username, password, parameterMap):
    response = {}
    return 200, json.dumps(response)

`
        let meta = {
          'name': fileName,
          'stylesheet': '<See corresponding .py file>',
          'dataSourceUri': '',
          'cacheSeconds': 0,
          'jtidy': false,
          'category': 2,
          'key': '',
          'cron': false
        }
        await Promise.all([
          fs.writeFile(path.join(projectPath, 'data-source-items', fileName + '.meta.json'), JSON.stringify(meta, null, 4), 'utf8'),
          fs.writeFile(path.join(projectPath, 'data-source-items', fileName + '.py'), python, 'utf8')
        ]);
      }
    });

    dialog.attach();
  },
  // TODO: Very similar to newDataSourceItem
  // Could probably be a method of DataObject class
  newDataObject () {
    let dialog = new InputDialog({
      labelText: 'Filename',
      async callback (fileName) {
        let projectPath = config.projectPath();
        let python = `#!/usr/bin/env python

import json

def process(fullUrl, method, inHeaders, inputStream, remoteAddr, protocol):
    responseHeaders = {'Content-Type': ['application/json']}
    return json.dumps({}), responseHeaders, 200

`
        let meta = {
          'name': fileName,
          'stylesheet': '<See corresponding .py file>',
          'backendUri': ''
        }
        await Promise.all([
          fs.writeFile(path.join(projectPath, 'data-objects', fileName + '.meta.json'), JSON.stringify(meta, null, 4), 'utf8'),
          fs.writeFile(path.join(projectPath, 'data-objects', fileName + '.py'), python, 'utf8')
        ]);
      }
    });

    dialog.attach();
  },
  async upload () {
    atom.notifications.addInfo('Uploading files', {});
    try {
      // TODO: Move config out of dynapp/ and pass config to upload
      await this.sync.upload();
      console.log('Uploading Done!');
      atom.notifications.addInfo('Files are uploaded', {dismissable: true});
    } catch (err) {
      console.error(err);
      var error_message = 'Check logs for more info.';
      if (err.name === 'StatusCodeError') {
        error_message = ''+err.statusCode +', '
        if (err.statusCode == 401 || err.statusCode == 403) {
          error_message += 'Check credentials.';
        } else if (err.statusCode == 404) {
          error_message += 'Check group, app and baseurl.';
        } else {
          error_message += 'Check logs for more info.';
        }
      } else if (err.name === 'RequestError' && err.error.code === 'ENOTFOUND') {
        error_message = "Couldn't find host.";
      }
      error_message = 'Upload failed. ' + error_message;
      atom.notifications.addError(error_message, {dismissable: true});
    }
  },
  async createConfig() {
    atom.notifications.addInfo('Creating config file', {});
    await config.create();
    await createWorkFolder(config.workPath());
  },
  consumeTreeView(_treeView) {
    treeView = _treeView
  },
  deactivate() {
    this.subscriptions.dispose();
  },
  async download() {
    console.log('Downloading...');
    atom.notifications.addInfo('Downloading project', {});

    try {
      await createWorkFolder(config.workPath());
      await this.sync.download();
      if (treeView) {
        // Force tree view to update by emulating two clicks on root folder
        var elem = treeView.entryForPath(config.projectPath())
        elem.click();
        elem.click();
      }
      console.log('Downloading Done!');
      atom.notifications.addInfo('Project downloaded', {});
    } catch (err) {
      console.error(err);
      var error_message = 'Check logs for more info.';
      if (err.name === 'StatusCodeError') {
        error_message = ''+err.statusCode +', '
        if (err.statusCode == 401 || err.statusCode == 403) {
          error_message += 'Check credentials.';
        } else if (err.statusCode == 404) {
          error_message += 'Check group, app and baseurl.';
        } else {
          error_message += 'Check logs for more info.';
        }
      } else if (err.name === 'RequestError' && err.error.code === 'ENOTFOUND') {
        error_message = "Couldn't find host.";
      } else if (err.name === 'Error' && err.message.indexOf('is this a zip file') !== -1) {
        error_message = "Couldn't parse zip. Is url correct?";
      }
      error_message = 'Download failed. ' + error_message;
      atom.notifications.addError(error_message, {dismissable: true});
    }
  },
  async createIgnore (messages, name) {
    if (messages) {
      atom.notifications.addInfo('Creating ignore file', {});
    }

    let projectPath = config.projectPath();
    let content = `syntax: regexp
.dynapp-state$
^dynappconfig.json$
data-items/version-android.json$
data-items/version-ios.json$
node_modules/
.DS_Store
dist/
data-items/web/
\#$
~$
`;
    let file = path.join(projectPath, name);
    let fileExists = await fs.exists(file);
    if (!fileExists) {
      await fs.writeFile(file, content);
    } else if (messages) {
      atom.notifications.addError('A file named ' + name + ' already exists.', {});
    }
  }
};
<commit_msg>Adjusted ignore template<commit_after>const { CompositeDisposable } = require('atom');
const fs = require('fs-extra');
const path = require('path');
const InputDialog = require('../InputDialog.js');
const sync = require('../dynapp/sync');
const config = require('../dynapp/config');

var treeView;

// Ensure path exists
async function ensurePath(path) {
  if (!fs.existsSync(path)) {
    await fs.mkdir(path, {
      recursive: true
    });
  }
}

async function createWorkFolder(workpath) {
  await ensurePath(workpath);

  try {
    await fs.mkdir(path.join(workpath, 'data-source-items'));
  } catch(ex) {
    // data-source-items already exists
  }
  try {
    await fs.mkdir(path.join(workpath, 'data-objects'));
  } catch(ex) {
    // data-objects already exists
  }
  try {
    await fs.mkdir(path.join(workpath, 'data-items'));
  } catch(ex) {
    // data-items already exists
  }
}

module.exports = {
  subscriptions: null,
  activate(state) {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();
    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'dynapp-atom:download': () => this.download(),
      'dynapp-atom:createConfig': () => this.createConfig(),
      'dynapp-atom:createHgIgnore': () => this.createIgnore(true, '.hgignore'),
      'dynapp-atom:createGitIgnore': () => this.createIgnore(true, '.gitignore'),
      'dynapp-atom:upload': () => this.upload(),
      'dynapp-atom:newDataObject': () => this.newDataObject(),
      'dynapp-atom:newDataSourceItem': () => this.newDataSourceItem()
    }));
    this.sync = new sync.Sync();
  },
  // TODO: Very similar to newDataObject
  // Could probably be a method of DataSourceItem class
  newDataSourceItem() {
    let dialog = new InputDialog({
      labelText: 'Filename',
      async callback (fileName) {
        let projectPath = config.projectPath();
        let python = `#!/usr/bin/env python
import json

def transform(logger, item, username, password, parameterMap):
    response = {}
    return 200, json.dumps(response)

`
        let meta = {
          'name': fileName,
          'stylesheet': '<See corresponding .py file>',
          'dataSourceUri': '',
          'cacheSeconds': 0,
          'jtidy': false,
          'category': 2,
          'key': '',
          'cron': false
        }
        await Promise.all([
          fs.writeFile(path.join(projectPath, 'data-source-items', fileName + '.meta.json'), JSON.stringify(meta, null, 4), 'utf8'),
          fs.writeFile(path.join(projectPath, 'data-source-items', fileName + '.py'), python, 'utf8')
        ]);
      }
    });

    dialog.attach();
  },
  // TODO: Very similar to newDataSourceItem
  // Could probably be a method of DataObject class
  newDataObject () {
    let dialog = new InputDialog({
      labelText: 'Filename',
      async callback (fileName) {
        let projectPath = config.projectPath();
        let python = `#!/usr/bin/env python

import json

def process(fullUrl, method, inHeaders, inputStream, remoteAddr, protocol):
    responseHeaders = {'Content-Type': ['application/json']}
    return json.dumps({}), responseHeaders, 200

`
        let meta = {
          'name': fileName,
          'stylesheet': '<See corresponding .py file>',
          'backendUri': ''
        }
        await Promise.all([
          fs.writeFile(path.join(projectPath, 'data-objects', fileName + '.meta.json'), JSON.stringify(meta, null, 4), 'utf8'),
          fs.writeFile(path.join(projectPath, 'data-objects', fileName + '.py'), python, 'utf8')
        ]);
      }
    });

    dialog.attach();
  },
  async upload () {
    atom.notifications.addInfo('Uploading files', {});
    try {
      // TODO: Move config out of dynapp/ and pass config to upload
      await this.sync.upload();
      console.log('Uploading Done!');
      atom.notifications.addInfo('Files are uploaded', {dismissable: true});
    } catch (err) {
      console.error(err);
      var error_message = 'Check logs for more info.';
      if (err.name === 'StatusCodeError') {
        error_message = ''+err.statusCode +', '
        if (err.statusCode == 401 || err.statusCode == 403) {
          error_message += 'Check credentials.';
        } else if (err.statusCode == 404) {
          error_message += 'Check group, app and baseurl.';
        } else {
          error_message += 'Check logs for more info.';
        }
      } else if (err.name === 'RequestError' && err.error.code === 'ENOTFOUND') {
        error_message = "Couldn't find host.";
      }
      error_message = 'Upload failed. ' + error_message;
      atom.notifications.addError(error_message, {dismissable: true});
    }
  },
  async createConfig() {
    atom.notifications.addInfo('Creating config file', {});
    await config.create();
    await createWorkFolder(config.workPath());
  },
  consumeTreeView(_treeView) {
    treeView = _treeView
  },
  deactivate() {
    this.subscriptions.dispose();
  },
  async download() {
    console.log('Downloading...');
    atom.notifications.addInfo('Downloading project', {});

    try {
      await createWorkFolder(config.workPath());
      await this.sync.download();
      if (treeView) {
        // Force tree view to update by emulating two clicks on root folder
        var elem = treeView.entryForPath(config.projectPath())
        elem.click();
        elem.click();
      }
      console.log('Downloading Done!');
      atom.notifications.addInfo('Project downloaded', {});
    } catch (err) {
      console.error(err);
      var error_message = 'Check logs for more info.';
      if (err.name === 'StatusCodeError') {
        error_message = ''+err.statusCode +', '
        if (err.statusCode == 401 || err.statusCode == 403) {
          error_message += 'Check credentials.';
        } else if (err.statusCode == 404) {
          error_message += 'Check group, app and baseurl.';
        } else {
          error_message += 'Check logs for more info.';
        }
      } else if (err.name === 'RequestError' && err.error.code === 'ENOTFOUND') {
        error_message = "Couldn't find host.";
      } else if (err.name === 'Error' && err.message.indexOf('is this a zip file') !== -1) {
        error_message = "Couldn't parse zip. Is url correct?";
      }
      error_message = 'Download failed. ' + error_message;
      atom.notifications.addError(error_message, {dismissable: true});
    }
  },
  async createIgnore (messages, name) {
    if (messages) {
      atom.notifications.addInfo('Creating ignore file', {});
    }

    let projectPath = config.projectPath();
    let content = `syntax: regexp
.dynapp-state$
^dynappconfig.json$
data-items/version-android.json
data-items/version-ios.json
node_modules/
.DS_Store
dist/
data-items/web/
\#$
~$
`;
    let file = path.join(projectPath, name);
    let fileExists = await fs.exists(file);
    if (!fileExists) {
      await fs.writeFile(file, content);
    } else if (messages) {
      atom.notifications.addError('A file named ' + name + ' already exists.', {});
    }
  }
};
<|endoftext|>


<commit_before>function addNewCommand(key,value){
    var name = key + value;
    editor.commands.addCommand({
        name: name,
        bindKey: {
            win: key,
            mac: key
        },
        exec: function (editor) {
            console.log(value);
            editor.insert(value);
        },
        readOnly: true
    });
}
// default keys https://searchcode.com/codesearch/view/58959997/
editor.commands.addCommand({
    name: 'cut-1',
    bindKey: {win: 'Ctrl-X', mac: 'Command-X'},
    exec: function (editor) {

        var textRange = editor.session.getTextRange(editor.getSelectionRange());

        if (textRange.length == 0) {
            editor.removeLines();
            return;
        }

        app.cutCopy(textRange);
        editor.remove(editor.getSelectionRange());

    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'close-1',
    bindKey: {win: 'Ctrl-W', mac: 'Command-W'},
    exec: function (editor) {
        app.saveAndCloseCurrentTab();
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'copy-1',
    bindKey: {win: 'Ctrl-C', mac: 'Command-C'},
    exec: function (editor) {
        app.cutCopy(editor.session.getTextRange(editor.getSelectionRange()));
    },
    readOnly: false
});

editor.commands.addCommand({
    name: 'paste-1',
    bindKey: {win: 'Ctrl-V', mac: 'Command-V'},
    exec: function (editor) {
        editor.insert(app.paste());
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-enter-1',
    bindKey: {win: 'Ctrl-Enter', mac: 'Command-Enter'},
    exec: function (editor) {
        editor.insert("\r\n");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-duplicate',
    bindKey: {win: 'Ctrl-D', mac: 'Command-D'},
    exec: function (editor) {
        editor.copyLinesDown();
    },
    readOnly: true
});

function formatText(editor, matcher, firstCharacter, lastCharacter) {
    var range = editor.getSelectionRange();
    var text = editor.session.getTextRange(range);
    var firstCharLength = firstCharacter.length;
    var lastCharLength = lastCharacter.length;

    if (matcher(text)) {
        text = text.substring(firstCharLength, text.length - lastCharLength);
        editor.session.replace(range, text);
    }
    else {
        var virtualRange = editor.getSelectionRange();
        virtualRange.setStart(range.start.row, range.start.column - firstCharLength);
        virtualRange.setEnd(range.end.row, range.end.column + lastCharLength);

        var virtualText = editor.session.getTextRange(virtualRange);
        if (matcher(virtualText)) {
            editor.session.replace(virtualRange, text);
        }
        else {
            editor.session.replace(range, firstCharacter + text + lastCharacter);
            if (range.end.column == range.start.column) {
                editor.navigateTo(range.end.row, range.end.column + firstCharLength);
            }
        }
    }
}

function boldText() {
    formatText(editor, matchBoldText, "*", "*");
}

function italicizeText() {
    formatText(editor, matchItalicizedText, "_", "_");
}

function superScript() {
    formatText(editor, matchSuperScriptText, "^", "^");
}

function subScript() {
    formatText(editor, matchSubScriptText, "~", "~");
}

function underlinedText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function addStrikeThroughText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function highlightedText() {
    formatText(editor, matchHighlightedText, "#", "#");
}

function isURL(text) {
    var myRegExp = /^(.*?)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;

    return myRegExp.test(text);

}

function addHyperLink() {
    var cursorPosition = editor.getCursorPosition();
    var session = editor.getSession();
    var pasted = app.paste();
    if (isURL(pasted)) {
        if (pasted.indexOf("http") == -1)
            session.insert(cursorPosition, "http://" + pasted + "[text]");
        else
            session.insert(cursorPosition, pasted + "[text]");
        return;
    }
    session.insert(cursorPosition, "http://url[text]");
}

function addSourceCode() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[source,java]\n----\n\n----");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addMathBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[math,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addUmlBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[uml,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addTreeBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[tree,file=\"\"]\n--\n#\n--");

    editor.gotoLine(range.end.row + 3, 1, true);
}

function addImageSection() {
    editor.removeToLineStart();
    editor.insert("image::images/image.png[]");
}

function addHeading() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    var line = session.getLine(cursorPosition.row);
    var first = line[0] || "";
    session.insert(cursorPosition, (first == "=") ? "=" : "= ");
}

function addOlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "1. ");
}

function addUlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "* ");
}

function showLineNumbers() {
    editor.renderer.getShowGutter() ? editor.renderer.setShowGutter(false) : editor.renderer.setShowGutter(true);
}

editor.commands.addCommand({
    name: 'underline-selected',
    bindKey: {win: 'Ctrl-U', mac: 'Command-U'},
    exec: underlinedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'bold-selected',
    bindKey: {win: 'Ctrl-B', mac: 'Command-B'},
    exec: boldText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'highlight-selected',
    bindKey: {win: 'Ctrl-H', mac: 'Command-H'},
    exec: highlightedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'line-numbers',
    bindKey: {win: 'Ctrl-L', mac: 'Command-L'},
    exec: showLineNumbers,
    readOnly: true
});

editor.commands.addCommand({
    name: 'codify-selected',
    bindKey: {win: 'Ctrl-Shift-C', mac: 'Command-Shift-C'},
    exec: function (editor) {
        console.log("in old");
        formatText(editor, matchCode, "`", "`");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'italicize-selected',
    bindKey: {
        win: 'Ctrl-i|Ctrl-İ|Ctrl-ı|Ctrl-I',
        mac: 'Command-i|Command-İ|Command-ı|Command-I'
    },
    exec: italicizeText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'firebug-lite',
    bindKey: {
        win: 'F12',
        mac: 'F12'
    },
    exec: function () {
        if (!document.querySelectorAll("#firebug-script").length){
            var head = document.querySelector("head");
            var js = document.createElement("script");
            js.type = "text/javascript";
            js.src = "http://getfirebug.com/firebug-lite.js#startOpened=true";
            head.appendChild(js);
        }
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'source-generate',
    bindKey: {win: 'Tab', mac: 'Tab'},
    exec: function (editor, selection) {

        var cursorPosition = editor.getCursorPosition();
        var currentRow = cursorPosition.row;
        var currentColumn = cursorPosition.column;

        var range = editor.getSelectionRange();
        range.start.row = currentRow;
        range.start.column = 0;
        range.end.row = currentRow;
        range.end.column = currentColumn;

        var textRange = editor.session.getTextRange(range);

        // img tab
        if (textRange == "img") {
            addImageSection();
            return;
        }

        // book tab
        if (textRange == "book") { // source generator
            editor.removeToLineStart();

            editor.insert("= Book Name\nAuthor's Name\n:doctype: book\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n\n\n");

            return;
        }

        // article tab
        if (textRange == "article") { // source generator
            editor.removeToLineStart();

            editor.insert("= Book Name\nAuthor's Name\n:doctype: article\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n\n\n");

            return;
        }

        // math tab
        if (textRange == "math") { // math block generator
            addMathBlock();
            return;
        }

        // uml tab
        if (textRange == "uml") { // uml block generator
            addUmlBlock();
            return;
        }

        // tree tab
        if (textRange == "tree") { // uml block generator
            addTreeBlock();
            return;
        }

        // src tab
        if (textRange == "src") { // source generator
            addSourceCode();
            return;
        }
        // src,ruby or src.ruby tab
        var srcMatch = textRange.match(/src(\.|,)(\w+)/);
        if (Array.isArray(srcMatch)) {
            if (srcMatch.length == 3) {
                editor.removeToLineStart();

                var langName = srcMatch[2];

                editor.insert("[source," + langName + "]\n----\n\n----");

                editor.gotoLine(range.end.row + 3, 0, true);
                return;
            }
        }

//            "tbl3,2" tab
        var tableMatch = textRange.match(/tbl(\d+)(\.|,)(\d+)/);

        if (Array.isArray(tableMatch))
            if (tableMatch.length == 4) { // table generator

                editor.removeToLineStart();

                var row = tableMatch[1];
                var column = tableMatch[3];

                var tablePopupCtrl = app.getTablePopupController();
                tablePopupCtrl.createBasicTable(row, column);
                return;
            }

        editor.indent();
    },
    readOnly: true
});

editor.addEventListener("mousewheel", mouseWheelHandler);

function mouseWheelHandler(event) {
    if (!event)
        return;
    event = window.event;

    if (event.ctrlKey && editor.getValue().length) {

        var fontSize = parseInt(editor.getFontSize());

        if (event.wheelDelta < 0 && fontSize > 8) {
            //mouse scroll down - min size 8
            editor.setFontSize((fontSize - 1) + "px");
        }
        else if (event.wheelDelta >= 0 && fontSize < 24) {
            //mouse scroll up - max size 24
            editor.setFontSize((fontSize + 1) + "px");
        }
    }
}

function matchBoldText(text) {
    return text.match(/\*.*\*/g);
}

function matchItalicizedText(text) {
    return text.match(/\_.*\_/g);
}

function matchSuperScriptText(text) {
    return text.match(/\^.*\^/g);
}

function matchSubScriptText(text) {
    return text.match(/\~.*\~/g);
}

function matchCode(text) {
    return text.match(/\`.*\`/g);
}

function matchHighlightedText(text) {
    return text.match(/\#.*\#/g);
}

function matchHtmlTagText(text) {
    return text.match(/(\+\+\+\<(u|del)\>).*(\<\/(u|del)\>\+\+\+)/g);
}

<commit_msg>update article header<commit_after>function addNewCommand(key,value){
    var name = key + value;
    editor.commands.addCommand({
        name: name,
        bindKey: {
            win: key,
            mac: key
        },
        exec: function (editor) {
            console.log(value);
            editor.insert(value);
        },
        readOnly: true
    });
}
// default keys https://searchcode.com/codesearch/view/58959997/
editor.commands.addCommand({
    name: 'cut-1',
    bindKey: {win: 'Ctrl-X', mac: 'Command-X'},
    exec: function (editor) {

        var textRange = editor.session.getTextRange(editor.getSelectionRange());

        if (textRange.length == 0) {
            editor.removeLines();
            return;
        }

        app.cutCopy(textRange);
        editor.remove(editor.getSelectionRange());

    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'close-1',
    bindKey: {win: 'Ctrl-W', mac: 'Command-W'},
    exec: function (editor) {
        app.saveAndCloseCurrentTab();
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'copy-1',
    bindKey: {win: 'Ctrl-C', mac: 'Command-C'},
    exec: function (editor) {
        app.cutCopy(editor.session.getTextRange(editor.getSelectionRange()));
    },
    readOnly: false
});

editor.commands.addCommand({
    name: 'paste-1',
    bindKey: {win: 'Ctrl-V', mac: 'Command-V'},
    exec: function (editor) {
        editor.insert(app.paste());
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-enter-1',
    bindKey: {win: 'Ctrl-Enter', mac: 'Command-Enter'},
    exec: function (editor) {
        editor.insert("\r\n");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-duplicate',
    bindKey: {win: 'Ctrl-D', mac: 'Command-D'},
    exec: function (editor) {
        editor.copyLinesDown();
    },
    readOnly: true
});

function formatText(editor, matcher, firstCharacter, lastCharacter) {
    var range = editor.getSelectionRange();
    var text = editor.session.getTextRange(range);
    var firstCharLength = firstCharacter.length;
    var lastCharLength = lastCharacter.length;

    if (matcher(text)) {
        text = text.substring(firstCharLength, text.length - lastCharLength);
        editor.session.replace(range, text);
    }
    else {
        var virtualRange = editor.getSelectionRange();
        virtualRange.setStart(range.start.row, range.start.column - firstCharLength);
        virtualRange.setEnd(range.end.row, range.end.column + lastCharLength);

        var virtualText = editor.session.getTextRange(virtualRange);
        if (matcher(virtualText)) {
            editor.session.replace(virtualRange, text);
        }
        else {
            editor.session.replace(range, firstCharacter + text + lastCharacter);
            if (range.end.column == range.start.column) {
                editor.navigateTo(range.end.row, range.end.column + firstCharLength);
            }
        }
    }
}

function boldText() {
    formatText(editor, matchBoldText, "*", "*");
}

function italicizeText() {
    formatText(editor, matchItalicizedText, "_", "_");
}

function superScript() {
    formatText(editor, matchSuperScriptText, "^", "^");
}

function subScript() {
    formatText(editor, matchSubScriptText, "~", "~");
}

function underlinedText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function addStrikeThroughText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function highlightedText() {
    formatText(editor, matchHighlightedText, "#", "#");
}

function isURL(text) {
    var myRegExp = /^(.*?)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;

    return myRegExp.test(text);

}

function addHyperLink() {
    var cursorPosition = editor.getCursorPosition();
    var session = editor.getSession();
    var pasted = app.paste();
    if (isURL(pasted)) {
        if (pasted.indexOf("http") == -1)
            session.insert(cursorPosition, "http://" + pasted + "[text]");
        else
            session.insert(cursorPosition, pasted + "[text]");
        return;
    }
    session.insert(cursorPosition, "http://url[text]");
}

function addSourceCode() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[source,java]\n----\n\n----");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addMathBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[math,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addUmlBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[uml,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addTreeBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[tree,file=\"\"]\n--\n#\n--");

    editor.gotoLine(range.end.row + 3, 1, true);
}

function addImageSection() {
    editor.removeToLineStart();
    editor.insert("image::images/image.png[]");
}

function addHeading() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    var line = session.getLine(cursorPosition.row);
    var first = line[0] || "";
    session.insert(cursorPosition, (first == "=") ? "=" : "= ");
}

function addOlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "1. ");
}

function addUlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "* ");
}

function showLineNumbers() {
    editor.renderer.getShowGutter() ? editor.renderer.setShowGutter(false) : editor.renderer.setShowGutter(true);
}

editor.commands.addCommand({
    name: 'underline-selected',
    bindKey: {win: 'Ctrl-U', mac: 'Command-U'},
    exec: underlinedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'bold-selected',
    bindKey: {win: 'Ctrl-B', mac: 'Command-B'},
    exec: boldText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'highlight-selected',
    bindKey: {win: 'Ctrl-H', mac: 'Command-H'},
    exec: highlightedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'line-numbers',
    bindKey: {win: 'Ctrl-L', mac: 'Command-L'},
    exec: showLineNumbers,
    readOnly: true
});

editor.commands.addCommand({
    name: 'codify-selected',
    bindKey: {win: 'Ctrl-Shift-C', mac: 'Command-Shift-C'},
    exec: function (editor) {
        console.log("in old");
        formatText(editor, matchCode, "`", "`");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'italicize-selected',
    bindKey: {
        win: 'Ctrl-i|Ctrl-İ|Ctrl-ı|Ctrl-I',
        mac: 'Command-i|Command-İ|Command-ı|Command-I'
    },
    exec: italicizeText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'firebug-lite',
    bindKey: {
        win: 'F12',
        mac: 'F12'
    },
    exec: function () {
        if (!document.querySelectorAll("#firebug-script").length){
            var head = document.querySelector("head");
            var js = document.createElement("script");
            js.type = "text/javascript";
            js.src = "http://getfirebug.com/firebug-lite.js#startOpened=true";
            head.appendChild(js);
        }
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'source-generate',
    bindKey: {win: 'Tab', mac: 'Tab'},
    exec: function (editor, selection) {

        var cursorPosition = editor.getCursorPosition();
        var currentRow = cursorPosition.row;
        var currentColumn = cursorPosition.column;

        var range = editor.getSelectionRange();
        range.start.row = currentRow;
        range.start.column = 0;
        range.end.row = currentRow;
        range.end.column = currentColumn;

        var textRange = editor.session.getTextRange(range);

        // img tab
        if (textRange == "img") {
            addImageSection();
            return;
        }

        // book tab
        if (textRange == "book") { // source generator
            editor.removeToLineStart();

            editor.insert("= Book Name\nAuthor's Name\n:doctype: book\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n\n\n");

            return;
        }

        // article tab
        if (textRange == "article") { // source generator
            editor.removeToLineStart();

            editor.insert("= Article Name\nAuthor's Name\n:doctype: article\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n\n\n");

            return;
        }

        // math tab
        if (textRange == "math") { // math block generator
            addMathBlock();
            return;
        }

        // uml tab
        if (textRange == "uml") { // uml block generator
            addUmlBlock();
            return;
        }

        // tree tab
        if (textRange == "tree") { // uml block generator
            addTreeBlock();
            return;
        }

        // src tab
        if (textRange == "src") { // source generator
            addSourceCode();
            return;
        }
        // src,ruby or src.ruby tab
        var srcMatch = textRange.match(/src(\.|,)(\w+)/);
        if (Array.isArray(srcMatch)) {
            if (srcMatch.length == 3) {
                editor.removeToLineStart();

                var langName = srcMatch[2];

                editor.insert("[source," + langName + "]\n----\n\n----");

                editor.gotoLine(range.end.row + 3, 0, true);
                return;
            }
        }

//            "tbl3,2" tab
        var tableMatch = textRange.match(/tbl(\d+)(\.|,)(\d+)/);

        if (Array.isArray(tableMatch))
            if (tableMatch.length == 4) { // table generator

                editor.removeToLineStart();

                var row = tableMatch[1];
                var column = tableMatch[3];

                var tablePopupCtrl = app.getTablePopupController();
                tablePopupCtrl.createBasicTable(row, column);
                return;
            }

        editor.indent();
    },
    readOnly: true
});

editor.addEventListener("mousewheel", mouseWheelHandler);

function mouseWheelHandler(event) {
    if (!event)
        return;
    event = window.event;

    if (event.ctrlKey && editor.getValue().length) {

        var fontSize = parseInt(editor.getFontSize());

        if (event.wheelDelta < 0 && fontSize > 8) {
            //mouse scroll down - min size 8
            editor.setFontSize((fontSize - 1) + "px");
        }
        else if (event.wheelDelta >= 0 && fontSize < 24) {
            //mouse scroll up - max size 24
            editor.setFontSize((fontSize + 1) + "px");
        }
    }
}

function matchBoldText(text) {
    return text.match(/\*.*\*/g);
}

function matchItalicizedText(text) {
    return text.match(/\_.*\_/g);
}

function matchSuperScriptText(text) {
    return text.match(/\^.*\^/g);
}

function matchSubScriptText(text) {
    return text.match(/\~.*\~/g);
}

function matchCode(text) {
    return text.match(/\`.*\`/g);
}

function matchHighlightedText(text) {
    return text.match(/\#.*\#/g);
}

function matchHtmlTagText(text) {
    return text.match(/(\+\+\+\<(u|del)\>).*(\<\/(u|del)\>\+\+\+)/g);
}

<|endoftext|>


<commit_before>var credentials = require('./salesforce-credentials.js');
var jsforce = require('jsforce');

var conn = new jsforce.Connection({});

conn.login(credentials.user, credentials.passwordtoken, function(err, userInfo) {
  if (err) { return console.error(err); }

  console.log("Bearer " + conn.accessToken);

  console.log(conn.instanceUrl);

  console.log("User ID: " + userInfo.id);
  console.log("Org ID: " + userInfo.organizationId);
});

// conn.logout(function(err) {
//   if (err) { return console.error(err); }
//   console.log("Logged out.");
// });
<commit_msg>Remove logout commented code<commit_after>var credentials = require('./salesforce-credentials.js');
var jsforce = require('jsforce');

var conn = new jsforce.Connection({});

conn.login(credentials.user, credentials.passwordtoken, function(err, userInfo) {
  if (err) { return console.error(err); }

  console.log("Bearer " + conn.accessToken);

  console.log(conn.instanceUrl);

  console.log("User ID: " + userInfo.id);
  console.log("Org ID: " + userInfo.organizationId);
});
<|endoftext|>


<commit_before>// dna.js
// Mocha Specification Cases
//
// Run specs:
//    $ cd dna.js
//    $ npm test

const url = 'http://example.com?a=one&b=two';
const html = `
<!doctype html>
<html lang=en>
    <head>
        <meta charset=utf-8>
        <title>Specification Runner</title>
    </head>
    <body>
    </body>
</html>
`;

const assert =    require('assert');
const { JSDOM } = require('jsdom');
const window =    new JSDOM(html, { url: url }).window;
const $ =         require('jquery')(window);
const dna =       require('./dna.js')(window, $);

//Unit tests for dna.array
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.last()', () => {

 it('returns last object in array', () => {
   var actual = dna.array.last([3, 21, 7]);
   expected = '7';
   assert.equal(actual, expected);
   });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.find()', () => {

  it('finds a key in an array and returns the value', () => {
    var array = [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }];
    var actual = dna.array.find(array, 'b').word;
    expected = 'Bat';
    assert.equal(actual, expected);
    });

});

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.toMap()', () => {

  it('Converts an array of objects into an object (hash map)', () => {
     var dataSet = [
        {
           inputArray: [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }],
           expected: { a: { code: 'a', word: 'Ant' }, b: { code: 'b', word: 'Bat' } }
        }];
     function evalData(data) {
        var output = dna.array.toMap(data.inputArray, data.inputKey);
        assert.deepEqual(output, data.expected);
        }
     dataSet.forEach(evalData);
     });

  });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.fromMap()', () => {

  it('converts a map into an array of maps', () => {
     var dataSet = [
        {
           inputMap: { a: { word: 'Ant' }, b: { word: 'Bat' } },
           expected: [{ word: 'Ant', code: 'a' }, { word: 'Bat', code: 'b' }]
        },
        {
           inputMap: { x0: 100, x1: 101, x2: 102 },
           inputKey: 'key',
           expected: [{ value: 100, key: 'x0' }, { value: 101, key: 'x1' }, { value: 102, key: 'x2' }]
        }];
     function evalData(data) {
        var output = dna.array.fromMap(data.inputMap, data.inputKey);
        assert.deepEqual(output, data.expected);
        }
     dataSet.forEach(evalData);
     });

  });

//Unit tests for dna.util
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.toCamel()', () => {

   it('converts a kebab (dashes) name to camelCase', () => {
      var dataSet = [
         { input: 'ready-set-go', expected: 'readySetGo' },
         { input: 'dna',          expected: 'dna' }
         ];
      function evalData(data) {
         assert.equal(dna.util.toCamel(data.input), data.expected);
         }
      dataSet.forEach(evalData);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.toKebab()', () => {

 it('converts kebab (dashes) name to camelCase', () => {
   var dataSet = [
        { input: 'readySetGo', expected: 'ready-set-go' },
        { input: 'dna',          expected: 'dna' }
        ];
     function evalData(data) {
        assert.equal(dna.util.toKebab(data.input), data.expected);
        }
     dataSet.forEach(evalData);
     });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.value()', () => {

 it('returns value from key', () => {
   var actual = dna.util.value({ a: { b: 7 }}, 'a.b');
   expected = '7';
   assert.equal(actual, expected);
   });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.realTruth()', () => {

 it('returns a boolean', () => {
   var dataSet = [
        { input: '7', expected: true },
        { input: '0', expected: false }
        ];
     function evalData(data) {
        assert.equal(dna.util.realTruth(data.input), data.expected);
        }
     dataSet.forEach(evalData);
     });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.printf()', () => {

 it('builds a string from variables', () => {
   var actual = dna.util.printf('%s: %s', 'Lives', 3);
   expected = 'Lives: 3';
   assert.equal(actual, expected);
   });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.apply()', () => {

 it('calls fn (string name or actual function) passing in params', () => {
   var app = {
     priceCatalog: { 3: 19.95, 7: 14.95, 21: 39.95 },
     cart: {
       buy: function(itemNum) {
         return app.priceCatalog[itemNum];
       }
     }
   }
   dna.registerContext('app', app);
   var actual = dna.util.apply('app.cart.buy', 7);
   expected = '14.95';
   assert.equal(actual, expected);
   });

 });
<commit_msg>jshint compliance<commit_after>// dna.js
// Mocha Specification Cases
//
// Run specs:
//    $ cd dna.js
//    $ npm test

const url = 'http://example.com?a=one&b=two';
const html = `
<!doctype html>
<html lang=en>
    <head>
        <meta charset=utf-8>
        <title>Specification Runner</title>
    </head>
    <body>
    </body>
</html>
`;

const assert =    require('assert');
const { JSDOM } = require('jsdom');
const window =    new JSDOM(html, { url: url }).window;
const $ =         require('jquery')(window);
const dna =       require('./dna.js')(window, $);

//Unit tests for dna.array
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.last()', () => {

 it('returns last object in array', () => {
   var actual = dna.array.last([3, 21, 7]);
   var expected = '7';
   assert.equal(actual, expected);
   });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.find()', () => {

  it('finds a key in an array and returns the value', () => {
    var array = [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }];
    var actual = dna.array.find(array, 'b').word;
    var expected = 'Bat';
    assert.equal(actual, expected);
    });

});

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.toMap()', () => {

  it('Converts an array of objects into an object (hash map)', () => {
     var dataSet = [
        {
           inputArray: [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }],
           expected: { a: { code: 'a', word: 'Ant' }, b: { code: 'b', word: 'Bat' } }
        }];
     function evalData(data) {
        var output = dna.array.toMap(data.inputArray, data.inputKey);
        assert.deepEqual(output, data.expected);
        }
     dataSet.forEach(evalData);
     });

  });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.fromMap()', () => {

  it('converts a map into an array of maps', () => {
     var dataSet = [
        {
           inputMap: { a: { word: 'Ant' }, b: { word: 'Bat' } },
           expected: [{ word: 'Ant', code: 'a' }, { word: 'Bat', code: 'b' }]
        },
        {
           inputMap: { x0: 100, x1: 101, x2: 102 },
           inputKey: 'key',
           expected: [{ value: 100, key: 'x0' }, { value: 101, key: 'x1' }, { value: 102, key: 'x2' }]
        }];
     function evalData(data) {
        var output = dna.array.fromMap(data.inputMap, data.inputKey);
        assert.deepEqual(output, data.expected);
        }
     dataSet.forEach(evalData);
     });

  });

//Unit tests for dna.util
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.toCamel()', () => {

   it('converts a kebab (dashes) name to camelCase', () => {
      var dataSet = [
         { input: 'ready-set-go', expected: 'readySetGo' },
         { input: 'dna',          expected: 'dna' }
         ];
      function evalData(data) {
         assert.equal(dna.util.toCamel(data.input), data.expected);
         }
      dataSet.forEach(evalData);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.toKebab()', () => {

 it('converts kebab (dashes) name to camelCase', () => {
   var dataSet = [
        { input: 'readySetGo', expected: 'ready-set-go' },
        { input: 'dna',          expected: 'dna' }
        ];
     function evalData(data) {
        assert.equal(dna.util.toKebab(data.input), data.expected);
        }
     dataSet.forEach(evalData);
     });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.value()', () => {

 it('returns value from key', () => {
   var actual = dna.util.value({ a: { b: 7 }}, 'a.b');
   var expected = '7';
   assert.equal(actual, expected);
   });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.realTruth()', () => {

 it('returns a boolean', () => {
   var dataSet = [
        { input: '7', expected: true },
        { input: '0', expected: false }
        ];
     function evalData(data) {
        assert.equal(dna.util.realTruth(data.input), data.expected);
        }
     dataSet.forEach(evalData);
     });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.printf()', () => {

 it('builds a string from variables', () => {
   var actual = dna.util.printf('%s: %s', 'Lives', 3);
   var expected = 'Lives: 3';
   assert.equal(actual, expected);
   });

 });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.apply()', () => {

 it('calls fn (string name or actual function) passing in params', () => {
   var app = {
     priceCatalog: { 3: 19.95, 7: 14.95, 21: 39.95 },
     cart: {
       buy: function(itemNum) {
         return app.priceCatalog[itemNum];
       }
     }
   };
   dna.registerContext('app', app);
   var actual = dna.util.apply('app.cart.buy', 7);
   var expected = '14.95';
   assert.equal(actual, expected);
   });

 });
<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    console.log('Checking alive key for key : ' + adapterShortName);
    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    objects.getObject('system.adapter.history.0.memRss', function (err, obj) {
                        obj.common.custom = {
                            'history.0': {
                                enabled:      true,
                                changesOnly:  false,
                                debounce:     0,
                                retention:    31536000,
                                maxLength:    3
                            }
                        };
                        objects.setObject('system.adapter.history.0.memRss', obj, function (err) {
                            // wait till adapter receives the new settings
                            setTimeout(function () {
                                done();
                            }, 2000);
                        });
                    });
                });
        });
    });
    it('Test ' + adapterShortName + ': Write values into DB', function (done) {
        this.timeout(25000);
        var now = new Date().getTime();

        states.setState('system.adapter.history.0.memRss', {val: 1, ts: now - 2000}, function (err) {
            if (err) {
                console.log(err);
            }
            setTimeout(function () {
                states.setState('system.adapter.history.0.memRss', {val: 2, ts: now - 1000}, function (err) {
                    if (err) {
                        console.log(err);
                    }
                    setTimeout(function () {
                        states.setState('system.adapter.history.0.memRss', {val: 3, ts: now}, function (err) {
                            if (err) {
                                console.log(err);
                            }
                            done();
                        });
                    }, 100);
                });
            }, 100);
        });
    });
    it('Test ' + adapterShortName + ': Read values from DB using GetHistory', function (done) {
        this.timeout(25000);

        sendTo('history.0', 'getHistory', {
            id: 'system.adapter.history.0.memRss',
            options: {
                start:     new Date().getTime()-1000000,
                end:       new Date().getTime(),
                count:     50,
                aggregate: 'onchange'
            }
        }, function (result) {
            console.log(JSON.stringify(result.result, null, 2));
            expect(result.result.length).to.be.at.least(3);
            var found = 0;
            for (var i = 0; i < result.result.length; i++) {
                if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++;
            }
            expect(found).to.be.equal(3);

            sendTo('history.0', 'getHistory', {
                id: 'system.adapter.history.0.memRss',
                options: {
                    start:     new Date().getTime()-1000000,
                    end:       new Date().getTime(),
                    count:     2,
                    aggregate: 'onchange'
                }
            }, function (result) {
                console.log(JSON.stringify(result.result, null, 2));
                expect(result.result.length).to.be.at.least(2);
                var found = 0;
                for (var i = 0; i < result.result.length; i++) {
                    if (result.result[i].val >= 1 && result.result[i].val <= 2) found ++;
                }
                expect(found).to.be.equal(2);
                done();
            });
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<commit_msg>fix test<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

var now;

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    console.log('Checking alive key for key : ' + adapterShortName);
    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    objects.getObject('system.adapter.history.0.memRss', function (err, obj) {
                        obj.common.custom = {
                            'history.0': {
                                enabled:      true,
                                changesOnly:  false,
                                debounce:     0,
                                retention:    31536000,
                                maxLength:    3
                            }
                        };
                        objects.setObject('system.adapter.history.0.memRss', obj, function (err) {
                            // wait till adapter receives the new settings
                            setTimeout(function () {
                                done();
                            }, 2000);
                        });
                    });
                });
        });
    });
    it('Test ' + adapterShortName + ': Write values into DB', function (done) {
        this.timeout(25000);
        now = new Date().getTime();

        states.setState('system.adapter.history.0.memRss', {val: 1, ts: now - 2000}, function (err) {
            if (err) {
                console.log(err);
            }
            setTimeout(function () {
                states.setState('system.adapter.history.0.memRss', {val: 2, ts: now - 1000}, function (err) {
                    if (err) {
                        console.log(err);
                    }
                    setTimeout(function () {
                        states.setState('system.adapter.history.0.memRss', {val: 3, ts: now}, function (err) {
                            if (err) {
                                console.log(err);
                            }
                            done();
                        });
                    }, 100);
                });
            }, 100);
        });
    });
    it('Test ' + adapterShortName + ': Read values from DB using GetHistory', function (done) {
        this.timeout(25000);

        sendTo('history.0', 'getHistory', {
            id: 'system.adapter.history.0.memRss',
            options: {
                start:     now-5000,
                count:     50,
                aggregate: 'onchange'
            }
        }, function (result) {
            console.log(JSON.stringify(result.result, null, 2));
            expect(result.result.length).to.be.at.least(3);
            var found = 0;
            for (var i = 0; i < result.result.length; i++) {
                if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++;
            }
            expect(found).to.be.equal(3);

            sendTo('history.0', 'getHistory', {
                id: 'system.adapter.history.0.memRss',
                options: {
                    start:     now-5000,
                    count:     2,
                    aggregate: 'onchange'
                }
            }, function (result) {
                console.log(JSON.stringify(result.result, null, 2));
                expect(result.result.length).to.be.equal(2);
                done();
            });
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>


<commit_before>/* global $ */
/* eslint prefer-reflect: "off" */

(function() {
  'use strict';

  // Our form's behavior depends significantly on whether we're creating
  // a new review, or editing an old one.
  let editing = window.config.editing;
  let textFields = editing ? '#review-title,#review-text' :
    '#review-url,#review-title,#review-text';

  // A library we rely on to persist form data, but only for new reviews for now
  let sisyphus;

  // Add inputs used only with JS here so they don't appear/conflict when JS is disabled
  $('#star-rating-control').append(`<input id="review-rating" name="review-rating" type="hidden" data-required>`);

  // Get rating value from previous POST request, if any
  let postRating = $('#star-rating-control').attr('data-post') || '';

  // Highlight rating from POST request
  if (postRating)
    selectStar.apply($(`#star-button-${postRating}`)[0]);

  // Register event handlers

  $('[id^=star-button-]')
    .mouseout(clearStars)
    .mouseover(indicateStar)
    .click(selectStar)
    .keyup(maybeSelectStar);
  $('#live-preview').change(toggleLivePreview);
  $('#preview').click(showPreviewOnce);

  if (!editing) {
    $(textFields).change(hideAbandonDraft);
    $('#review-url').change(validateURL);
    $('#dismiss-draft-notice').click(hideDraftNotice);
    $('#abandon-draft').click(emptyAllFormFields);
    $('#add-http').click(addHTTP);
    $('#add-https').click(addHTTPS);
    sisyphus = $('#review-form').sisyphus({
      onRestore: processLoadedData,
      excludeFields: $('#live-preview,#review-token,#review-language')
    });
  }

  function hideDraftNotice() {
    if ($('#draft-notice').is(':visible'))
      $('#draft-notice').fadeOut(200);
  }

  function hideAbandonDraft() {
    if ($('#abandon-draft').is(':visible'))
      $('#abandon-draft').fadeOut(200);
  }

  function addProtocol(protocol) {
    $('#review-url').val(protocol + '://' + $('#review-url').val());
    $('#review-url').trigger('change');
  }

  function addHTTP(event) {
    addProtocol('http');
    $('#review-title').focus();
    event.preventDefault();
  }

  function addHTTPS(event) {
    addProtocol('https');
    $('#review-title').focus();
    event.preventDefault();
  }

  function validateURL() {
    let maybeURL = this.value;
    let urlRegex = /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
    let protocolRegex = /^(https?|ftp):\/\//;
    if (maybeURL && !urlRegex.test(maybeURL)) {
      $('#review-url-error').show();
      if (!protocolRegex.test(maybeURL)) {
        $('#helper-links').show();
        $('#add-https').focus();
      } else {
        $('#helper-links').hide();
      }
    } else {
      $('#review-url-error').hide();
      $('#helper-links').hide();
    }
  }

  // For clearing out old drafts
  function emptyAllFormFields(event) {
    clearStars();
    $('#review-url,#review-title,#review-text,#review-rating').val('');
    $('#review-url').trigger('change');
    sisyphus.manuallyReleaseData();
    hideDraftNotice();
    event.preventDefault();
  }

  // For processing draft data
  function processLoadedData() {
    let rating = Number($('#review-rating').val());

    // Trim just in case whitespace got persisted
    $('input[data-auto-trim],textarea[data-auto-trim]').each(window.libreviews.trimInput);

    // Only show notice if we've actually recovered some data
    if (rating || $('#review-url').val() || $('#review-title').val() || $('#review-text').val()) {
      if (rating)
        selectStar.apply($(`#star-button-${rating}`)[0]);

      $('#draft-notice').show();
      // Repaint help in case it got pushed down
      window.libreviews.repaintFocusedHelp();
    }

    // Show URL issues if appropriate
    validateURL.apply($('#review-url')[0]);
  }

  function clearStars(start) {
    if (!start || typeof start !== "number")
      start = 1;
    for (let i = start; i < 6; i++)
      replaceStar(i, `/static/img/star-placeholder.svg`, 'star-holder');
  }

  function replaceStar(id, src, className) {
    $(`#star-button-${id}`)
      .attr('src', src)
      .removeClass()
      .addClass(className);
  }

  function restoreSelected() {
    let selectedStar = $('#star-rating-control').attr('data-selected');
    if (selectedStar) {
      selectStar.apply($(`#star-button-${selectedStar}`)[0]);
    }
  }

  function indicateStar() {
    let selectedStar = Number(this.id.match(/\d/)[0]); // We want to set all stars to the color of the selected star
    for (let i = 1; i <= selectedStar; i++)
      replaceStar(i, `/static/img/star-${selectedStar}-full.svg`, 'star-full');
    if (selectedStar < 5)
      clearStars(selectedStar + 1);
    return selectedStar;
  }

  function selectStar() {
    let selectedStar = indicateStar.apply(this);
    $('#star-rating-control').attr('data-selected', selectedStar);
    $('#star-rating-control img[id^=star-button-]')
      .off('mouseout')
      .mouseout(restoreSelected);
    $('#review-rating').val(selectedStar);
    $('#review-rating').trigger('change');
  }

  function maybeSelectStar(event) {
    if (event.keyCode == 13 || event.keyCode == 32) {
      selectStar.apply(this);
    }
  }

  function showPreviewOnce(event) {
    $('#preview-contents').removeClass('hidden');
    renderPreview();
    event.preventDefault();
  }

  function renderPreview() {
    let text = $('#review-text').val();
    let parsed = window.markdown.render(text);
    let reviewURL = $('#review-url').val();
    let rating = $('#review-rating').val();
    if (reviewURL) {
      $('#preview-review-url').removeClass('hidden');
      $('#preview-review-url-link').attr('href', encodeURI(reviewURL));
      $('#preview-review-url-link').html(escapeHTML(prettifyURL(reviewURL)));
    } else {
      $('#preview-review-url').addClass('hidden');
    }
    if (rating)
      renderPreviewStars(rating);

    $('#preview-review-text').html(parsed);
    $('#preview-review-title').html(escapeHTML($('#review-title').val()));
    $('#preview-review-byline-date').html(new Date().toLocaleString(window.config.language));

    // For handling events inside content, e.g., spoiler warnings
    window.libreviews.updateContentClickHandlers();
    // Re-render help in case it got pushed down by preview
    window.libreviews.repaintFocusedHelp();
  }

  function renderPreviewStars(rating) {
    if (!rating || Number($('#preview-review-rating').attr('data-preview-stars')) == rating)
      return; // Nothing to do

    let img = `<img src="/static/img/star-${rating}-full.svg" width="20" class="preview-star">`;

    $('#preview-review-rating').html('');
    for (let i = 1; i <= rating; i++) {
      $('#preview-review-rating').append(img);
    }
    $('#preview-review-rating').attr('data-preview-stars', rating);

  }

  function toggleLivePreview() {
    if ($(this).prop('checked')) {
      renderPreview();
      $('#preview-contents').removeClass('hidden');
      $('#review-title').keyup(renderPreview);
      $('#review-text').keyup(renderPreview);
      $('#review-url').change(renderPreview);
      $('#review-rating').change(renderPreview);
    } else {
      $('#preview-contents').addClass('hidden');
      $('#review-text').off('keyup', renderPreview);
      $('#review-title').off('keyup', renderPreview);
      $('#review-url').off('change', renderPreview);
      $('#review-rating').off('change', renderPreview);
    }
  }

  function escapeHTML(html) {
    return html
      .replace(/&/g, "&")
      .replace(/</g, "<")
      .replace(/>/g, ">");
  }

  // For link labels when we only have a URL
  function prettifyURL(url) {
    return url
      .replace(/^.*?:\/\//, '') // strip protocol
      .replace(/\/$/, ''); // remove trailing slashes for display only
  }
}());
<commit_msg>Fix rating widget behavior when editing reviews<commit_after>/* global $ */
/* eslint prefer-reflect: "off" */

(function() {
  'use strict';

  // Our form's behavior depends significantly on whether we're creating
  // a new review, or editing an old one.
  let editing = window.config.editing;
  let textFields = editing ? '#review-title,#review-text' :
    '#review-url,#review-title,#review-text';

  // A library we rely on to persist form data, but only for new reviews for now
  let sisyphus;

  // Add inputs used only with JS here so they don't appear/conflict when JS is disabled
  $('#star-rating-control').append(`<input id="review-rating" name="review-rating" type="hidden" data-required>`);

  // Get rating value from previous POST request, if any
  let postRating = $('#star-rating-control').attr('data-post') || '';

  // Register event handlers

  $('[id^=star-button-]')
    .mouseout(clearStars)
    .mouseover(indicateStar)
    .click(selectStar)
    .keyup(maybeSelectStar);

  // Highlight rating from POST request
  if (postRating)
    selectStar.apply($(`#star-button-${postRating}`)[0]);

  $('#live-preview').change(toggleLivePreview);
  $('#preview').click(showPreviewOnce);

  if (!editing) {
    $(textFields).change(hideAbandonDraft);
    $('#review-url').change(validateURL);
    $('#dismiss-draft-notice').click(hideDraftNotice);
    $('#abandon-draft').click(emptyAllFormFields);
    $('#add-http').click(addHTTP);
    $('#add-https').click(addHTTPS);
    sisyphus = $('#review-form').sisyphus({
      onRestore: processLoadedData,
      excludeFields: $('#live-preview,#review-token,#review-language')
    });
  }

  function hideDraftNotice() {
    if ($('#draft-notice').is(':visible'))
      $('#draft-notice').fadeOut(200);
  }

  function hideAbandonDraft() {
    if ($('#abandon-draft').is(':visible'))
      $('#abandon-draft').fadeOut(200);
  }

  function addProtocol(protocol) {
    $('#review-url').val(protocol + '://' + $('#review-url').val());
    $('#review-url').trigger('change');
  }

  function addHTTP(event) {
    addProtocol('http');
    $('#review-title').focus();
    event.preventDefault();
  }

  function addHTTPS(event) {
    addProtocol('https');
    $('#review-title').focus();
    event.preventDefault();
  }

  function validateURL() {
    let maybeURL = this.value;
    let urlRegex = /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
    let protocolRegex = /^(https?|ftp):\/\//;
    if (maybeURL && !urlRegex.test(maybeURL)) {
      $('#review-url-error').show();
      if (!protocolRegex.test(maybeURL)) {
        $('#helper-links').show();
        $('#add-https').focus();
      } else {
        $('#helper-links').hide();
      }
    } else {
      $('#review-url-error').hide();
      $('#helper-links').hide();
    }
  }

  // For clearing out old drafts
  function emptyAllFormFields(event) {
    clearStars();
    $('#review-url,#review-title,#review-text,#review-rating').val('');
    $('#review-url').trigger('change');
    sisyphus.manuallyReleaseData();
    hideDraftNotice();
    event.preventDefault();
  }

  // For processing draft data
  function processLoadedData() {
    let rating = Number($('#review-rating').val());

    // Trim just in case whitespace got persisted
    $('input[data-auto-trim],textarea[data-auto-trim]').each(window.libreviews.trimInput);

    // Only show notice if we've actually recovered some data
    if (rating || $('#review-url').val() || $('#review-title').val() || $('#review-text').val()) {
      if (rating)
        selectStar.apply($(`#star-button-${rating}`)[0]);

      $('#draft-notice').show();
      // Repaint help in case it got pushed down
      window.libreviews.repaintFocusedHelp();
    }

    // Show URL issues if appropriate
    validateURL.apply($('#review-url')[0]);
  }

  function clearStars(start) {
    if (!start || typeof start !== "number")
      start = 1;
    for (let i = start; i < 6; i++)
      replaceStar(i, `/static/img/star-placeholder.svg`, 'star-holder');
  }

  function replaceStar(id, src, className) {
    $(`#star-button-${id}`)
      .attr('src', src)
      .removeClass()
      .addClass(className);
  }

  function restoreSelected() {
    let selectedStar = $('#star-rating-control').attr('data-selected');
    if (selectedStar) {
      selectStar.apply($(`#star-button-${selectedStar}`)[0]);
    }
  }

  function indicateStar() {
    let selectedStar = Number(this.id.match(/\d/)[0]); // We want to set all stars to the color of the selected star
    for (let i = 1; i <= selectedStar; i++)
      replaceStar(i, `/static/img/star-${selectedStar}-full.svg`, 'star-full');
    if (selectedStar < 5)
      clearStars(selectedStar + 1);
    return selectedStar;
  }

  function selectStar() {
    let selectedStar = indicateStar.apply(this);
    $('#star-rating-control').attr('data-selected', selectedStar);
    $('#star-rating-control img[id^=star-button-]')
      .off('mouseout')
      .mouseout(restoreSelected);
    $('#review-rating').val(selectedStar);
    $('#review-rating').trigger('change');
  }

  function maybeSelectStar(event) {
    if (event.keyCode == 13 || event.keyCode == 32) {
      selectStar.apply(this);
    }
  }

  function showPreviewOnce(event) {
    $('#preview-contents').removeClass('hidden');
    renderPreview();
    event.preventDefault();
  }

  function renderPreview() {
    let text = $('#review-text').val();
    let parsed = window.markdown.render(text);
    let reviewURL = $('#review-url').val();
    let rating = $('#review-rating').val();
    if (reviewURL) {
      $('#preview-review-url').removeClass('hidden');
      $('#preview-review-url-link').attr('href', encodeURI(reviewURL));
      $('#preview-review-url-link').html(escapeHTML(prettifyURL(reviewURL)));
    } else {
      $('#preview-review-url').addClass('hidden');
    }
    if (rating)
      renderPreviewStars(rating);

    $('#preview-review-text').html(parsed);
    $('#preview-review-title').html(escapeHTML($('#review-title').val()));
    $('#preview-review-byline-date').html(new Date().toLocaleString(window.config.language));

    // For handling events inside content, e.g., spoiler warnings
    window.libreviews.updateContentClickHandlers();
    // Re-render help in case it got pushed down by preview
    window.libreviews.repaintFocusedHelp();
  }

  function renderPreviewStars(rating) {
    if (!rating || Number($('#preview-review-rating').attr('data-preview-stars')) == rating)
      return; // Nothing to do

    let img = `<img src="/static/img/star-${rating}-full.svg" width="20" class="preview-star">`;

    $('#preview-review-rating').html('');
    for (let i = 1; i <= rating; i++) {
      $('#preview-review-rating').append(img);
    }
    $('#preview-review-rating').attr('data-preview-stars', rating);

  }

  function toggleLivePreview() {
    if ($(this).prop('checked')) {
      renderPreview();
      $('#preview-contents').removeClass('hidden');
      $('#review-title').keyup(renderPreview);
      $('#review-text').keyup(renderPreview);
      $('#review-url').change(renderPreview);
      $('#review-rating').change(renderPreview);
    } else {
      $('#preview-contents').addClass('hidden');
      $('#review-text').off('keyup', renderPreview);
      $('#review-title').off('keyup', renderPreview);
      $('#review-url').off('change', renderPreview);
      $('#review-rating').off('change', renderPreview);
    }
  }

  function escapeHTML(html) {
    return html
      .replace(/&/g, "&")
      .replace(/</g, "<")
      .replace(/>/g, ">");
  }

  // For link labels when we only have a URL
  function prettifyURL(url) {
    return url
      .replace(/^.*?:\/\//, '') // strip protocol
      .replace(/\/$/, ''); // remove trailing slashes for display only
  }
}());
<|endoftext|>


<commit_before>var Db = require('../lib/db');
var config = require('./config.json');

module.exports = {
  init: init
};

function init() {
    var schema = config.schema || 'pgboss';
    var emptyJobsCommand = 'truncate table ' + schema + '.job';

    var db = new Db(config);

    return db.executeSql(emptyJobsCommand)
        .catch(error => console.error(error));
}<commit_msg>and the arrow function..... omg<commit_after>var Db = require('../lib/db');
var config = require('./config.json');

module.exports = {
  init: init
};

function init() {
    var schema = config.schema || 'pgboss';
    var emptyJobsCommand = 'truncate table ' + schema + '.job';

    var db = new Db(config);

    return db.executeSql(emptyJobsCommand)
        .catch(function(error) { console.error(error); });
}<|endoftext|>