<commit_before>define(function (require) {
    'use strict';

    var COMMAND_ID = 'hirse.beautify';
    var COMMAND_SAVE_ID = COMMAND_ID + '.autosave';

    /* beautify preserve:start */
    var CommandManager     = brackets.getModule('command/CommandManager');
    var Commands           = brackets.getModule('command/Commands');
    var Menus              = brackets.getModule('command/Menus');
    var DocumentManager    = brackets.getModule('document/DocumentManager');
    var Editor             = brackets.getModule('editor/Editor').Editor;
    var EditorManager      = brackets.getModule('editor/EditorManager');
    var FileSystem         = brackets.getModule('filesystem/FileSystem');
    var FileSystemError    = brackets.getModule('filesystem/FileSystemError');
    var LanguageManager    = brackets.getModule('language/LanguageManager');
    var PreferencesManager = brackets.getModule('preferences/PreferencesManager');
    var ProjectManager     = brackets.getModule('project/ProjectManager');
    var AppInit            = brackets.getModule('utils/AppInit');
    var DefaultDialogs     = brackets.getModule('widgets/DefaultDialogs');
    var Dialogs            = brackets.getModule('widgets/Dialogs');
    /* beautify preserve:end */

    var Strings = require('strings');
    var beautifiers = {
        js: require('thirdparty/beautify').js_beautify,
        css: require('thirdparty/beautify-css').css_beautify,
        html: require('thirdparty/beautify-html').html_beautify
    };

    var settingsFileName = '.jsbeautifyrc';
    var settings = JSON.parse(require('text!default.jsbeautifyrc'));
    var beautifyPrefs = PreferencesManager.getExtensionPrefs(COMMAND_ID);
    var keyBindings = [
        {
            key: 'Cmd-Shift-L',
            platform: 'mac'
        }, {
            key: 'Ctrl-Shift-L'
        }
    ];

    var beautifyOnSave = beautifyPrefs.get('onSave') || false;
    if (!beautifyOnSave) {
        beautifyPrefs.set('onSave', false);
        beautifyPrefs.save();
    }

    function batchUpdate(formattedText, isSelection) {
        var editor = EditorManager.getCurrentFullEditor();
        var cursorPos = editor.getCursorPos();
        var scrollPos = editor.getScrollPos();
        var doc = DocumentManager.getCurrentDocument();
        var selection = editor.getSelection();
        doc.batchOperation(function () {
            if (isSelection) {
                doc.replaceRange(formattedText, selection.start, selection.end);
            } else {
                doc.setText(formattedText);
            }
            editor.setCursorPos(cursorPos);
            editor.setScrollPos(scrollPos.x, scrollPos.y);
        });
    }

    function format(autoSave) {
        var beautifierType;
        var document = DocumentManager.getCurrentDocument();
        switch (document.getLanguage().getId()) {
            case 'javascript':
            case 'json':
                beautifierType = 'js';
                break;
            case 'html':
            case 'xml':
            case 'svg':
            case 'php':
            case 'ejs':
            case 'handlebars':
                beautifierType = 'html';
                break;
            case 'css':
            case 'scss':
            case 'less':
                beautifierType = 'css';
                break;
            default:
                if (!autoSave) {
                    Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, Strings.UNSUPPORTED_TITLE, Strings.UNSUPPORTED_MESSAGE);
                }
                return;
        }

        var unformattedText;
        var editor = EditorManager.getCurrentFullEditor();
        var options = $.extend({}, settings[beautifierType] || settings);
        if (Editor.getUseTabChar()) {
            options.indent_with_tabs = true;
        } else {
            options.indent_size = Editor.getSpaceUnits();
            options.indent_char = ' ';
        }
        if (editor.hasSelection()) {
            options.indentation_level = editor.getSelection().start.ch;
            options.end_with_newline = false;
            unformattedText = editor.getSelectedText();
        } else {
            unformattedText = document.getText();
        }
        var formattedText = beautifiers[beautifierType](unformattedText, options);
        if (formattedText !== unformattedText) {
            batchUpdate(formattedText, editor.hasSelection());
        }
    }

    function onSave(event, doc) {
        if (doc.__beautifySaving) {
            return;
        }
        var context = PreferencesManager._buildContext(doc.file.fullPath, doc.getLanguage().getId());
        if (beautifyPrefs.get('onSave', context)) {
            doc.addRef();
            doc.__beautifySaving = true;
            format(true);
            setTimeout(function () {
                CommandManager.execute(Commands.FILE_SAVE, {
                    doc: doc
                }).always(function () {
                    delete doc.__beautifySaving;
                    doc.releaseRef();
                });
            });
        }
    }

    function loadConfig(settingsFile) {
        if (!settingsFile) {
            settingsFile = FileSystem.getFileForPath(ProjectManager.getProjectRoot().fullPath + settingsFileName);
        }
        settingsFile.read(function (err, content) {
            if (err === FileSystemError.NOT_FOUND) {
                return;
            }
            try {
                settings = JSON.parse(content);
            } catch (e) {
                console.error('Brackets Beautify - Error parsing options (' + settingsFile.fullPath + '). Using default.');
                return;
            }
        });
    }

    function loadConfigOnChange(e, document) {
        if (document.file.fullPath === ProjectManager.getProjectRoot().fullPath + settingsFileName) {
            loadConfig(document.file);
        }
    }

    function toggle(command, fromCheckbox) {
        var newValue = (typeof fromCheckbox === 'undefined') ? beautifyOnSave : fromCheckbox;
        DocumentManager[newValue ? 'on' : 'off']('documentSaved', onSave);
        command.setChecked(newValue);
        beautifyPrefs.set('onSave', newValue);
        beautifyPrefs.save();
    }

    CommandManager.register(Strings.BEAUTIFY, COMMAND_ID, format);
    var commandOnSave = CommandManager.register(Strings.BEAUTIFY_ON_SAVE, COMMAND_SAVE_ID, function () {
        toggle(this, !this.getChecked());
    });
    toggle(commandOnSave);

    var editMenu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    editMenu.addMenuDivider();
    editMenu.addMenuItem(COMMAND_ID, keyBindings);
    editMenu.addMenuItem(COMMAND_SAVE_ID);
    Menus.getContextMenu(Menus.ContextMenuIds.EDITOR_MENU).addMenuItem(COMMAND_ID);

    var jsonLanguage = LanguageManager.getLanguage('json');
    jsonLanguage.addFileExtension(settingsFileName);
    jsonLanguage.addFileName(settingsFileName);

    AppInit.appReady(function () {
        DocumentManager.on('documentSaved.beautify', loadConfigOnChange);
        DocumentManager.on('documentRefreshed.beautify', loadConfigOnChange);
        ProjectManager.on('projectOpen.beautify', function () {
            loadConfig();
        });
        loadConfig();
    });
});
<commit_msg>Update COMMAND_ID<commit_after>define(function (require) {
    'use strict';

    var PREFIX = 'hirse.beautify';
    var COMMAND_ID = PREFIX + '.beautify';
    var COMMAND_SAVE_ID = PREFIX + '.autosave';

    /* beautify preserve:start */
    var CommandManager     = brackets.getModule('command/CommandManager');
    var Commands           = brackets.getModule('command/Commands');
    var Menus              = brackets.getModule('command/Menus');
    var DocumentManager    = brackets.getModule('document/DocumentManager');
    var Editor             = brackets.getModule('editor/Editor').Editor;
    var EditorManager      = brackets.getModule('editor/EditorManager');
    var FileSystem         = brackets.getModule('filesystem/FileSystem');
    var FileSystemError    = brackets.getModule('filesystem/FileSystemError');
    var LanguageManager    = brackets.getModule('language/LanguageManager');
    var PreferencesManager = brackets.getModule('preferences/PreferencesManager');
    var ProjectManager     = brackets.getModule('project/ProjectManager');
    var AppInit            = brackets.getModule('utils/AppInit');
    var DefaultDialogs     = brackets.getModule('widgets/DefaultDialogs');
    var Dialogs            = brackets.getModule('widgets/Dialogs');
    /* beautify preserve:end */

    var Strings = require('strings');
    var beautifiers = {
        js: require('thirdparty/beautify').js_beautify,
        css: require('thirdparty/beautify-css').css_beautify,
        html: require('thirdparty/beautify-html').html_beautify
    };

    var settingsFileName = '.jsbeautifyrc';
    var settings = JSON.parse(require('text!default.jsbeautifyrc'));
    var beautifyPrefs = PreferencesManager.getExtensionPrefs(PREFIX);
    var keyBindings = [
        {
            key: 'Cmd-Shift-L',
            platform: 'mac'
        }, {
            key: 'Ctrl-Shift-L'
        }
    ];

    var beautifyOnSave = beautifyPrefs.get('onSave') || false;
    if (!beautifyOnSave) {
        beautifyPrefs.set('onSave', false);
        beautifyPrefs.save();
    }

    function batchUpdate(formattedText, isSelection) {
        var editor = EditorManager.getCurrentFullEditor();
        var cursorPos = editor.getCursorPos();
        var scrollPos = editor.getScrollPos();
        var doc = DocumentManager.getCurrentDocument();
        var selection = editor.getSelection();
        doc.batchOperation(function () {
            if (isSelection) {
                doc.replaceRange(formattedText, selection.start, selection.end);
            } else {
                doc.setText(formattedText);
            }
            editor.setCursorPos(cursorPos);
            editor.setScrollPos(scrollPos.x, scrollPos.y);
        });
    }

    function format(autoSave) {
        var beautifierType;
        var document = DocumentManager.getCurrentDocument();
        switch (document.getLanguage().getId()) {
            case 'javascript':
            case 'json':
                beautifierType = 'js';
                break;
            case 'html':
            case 'xml':
            case 'svg':
            case 'php':
            case 'ejs':
            case 'handlebars':
                beautifierType = 'html';
                break;
            case 'css':
            case 'scss':
            case 'less':
                beautifierType = 'css';
                break;
            default:
                if (!autoSave) {
                    Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, Strings.UNSUPPORTED_TITLE, Strings.UNSUPPORTED_MESSAGE);
                }
                return;
        }

        var unformattedText;
        var editor = EditorManager.getCurrentFullEditor();
        var options = $.extend({}, settings[beautifierType] || settings);
        if (Editor.getUseTabChar()) {
            options.indent_with_tabs = true;
        } else {
            options.indent_size = Editor.getSpaceUnits();
            options.indent_char = ' ';
        }
        if (editor.hasSelection()) {
            options.indentation_level = editor.getSelection().start.ch;
            options.end_with_newline = false;
            unformattedText = editor.getSelectedText();
        } else {
            unformattedText = document.getText();
        }
        var formattedText = beautifiers[beautifierType](unformattedText, options);
        if (formattedText !== unformattedText) {
            batchUpdate(formattedText, editor.hasSelection());
        }
    }

    function onSave(event, doc) {
        if (doc.__beautifySaving) {
            return;
        }
        var context = PreferencesManager._buildContext(doc.file.fullPath, doc.getLanguage().getId());
        if (beautifyPrefs.get('onSave', context)) {
            doc.addRef();
            doc.__beautifySaving = true;
            format(true);
            setTimeout(function () {
                CommandManager.execute(Commands.FILE_SAVE, {
                    doc: doc
                }).always(function () {
                    delete doc.__beautifySaving;
                    doc.releaseRef();
                });
            });
        }
    }

    function loadConfig(settingsFile) {
        if (!settingsFile) {
            settingsFile = FileSystem.getFileForPath(ProjectManager.getProjectRoot().fullPath + settingsFileName);
        }
        settingsFile.read(function (err, content) {
            if (err === FileSystemError.NOT_FOUND) {
                return;
            }
            try {
                settings = JSON.parse(content);
            } catch (e) {
                console.error('Brackets Beautify - Error parsing options (' + settingsFile.fullPath + '). Using default.');
                return;
            }
        });
    }

    function loadConfigOnChange(e, document) {
        if (document.file.fullPath === ProjectManager.getProjectRoot().fullPath + settingsFileName) {
            loadConfig(document.file);
        }
    }

    function toggle(command, fromCheckbox) {
        var newValue = (typeof fromCheckbox === 'undefined') ? beautifyOnSave : fromCheckbox;
        DocumentManager[newValue ? 'on' : 'off']('documentSaved', onSave);
        command.setChecked(newValue);
        beautifyPrefs.set('onSave', newValue);
        beautifyPrefs.save();
    }

    CommandManager.register(Strings.BEAUTIFY, COMMAND_ID, format);
    var commandOnSave = CommandManager.register(Strings.BEAUTIFY_ON_SAVE, COMMAND_SAVE_ID, function () {
        toggle(this, !this.getChecked());
    });
    toggle(commandOnSave);

    var editMenu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    editMenu.addMenuDivider();
    editMenu.addMenuItem(COMMAND_ID, keyBindings);
    editMenu.addMenuItem(COMMAND_SAVE_ID);
    Menus.getContextMenu(Menus.ContextMenuIds.EDITOR_MENU).addMenuItem(COMMAND_ID);

    var jsonLanguage = LanguageManager.getLanguage('json');
    jsonLanguage.addFileExtension(settingsFileName);
    jsonLanguage.addFileName(settingsFileName);

    AppInit.appReady(function () {
        DocumentManager.on('documentSaved.beautify', loadConfigOnChange);
        DocumentManager.on('documentRefreshed.beautify', loadConfigOnChange);
        ProjectManager.on('projectOpen.beautify', function () {
            loadConfig();
        });
        loadConfig();
    });
});
<|endoftext|>


<commit_before>"use strict"

var createShell = require("gl-now")
var createCamera = require("game-shell-fps-camera")
var ndarray = require("ndarray")
var createTerrain = require("./lib/terrain.js") // TODO: replace with shama's chunker mentioned in https://github.com/voxel/issues/issues/4#issuecomment-39644684
var createVoxelMesh = require("voxel-mesher")

var createPlugins = require('voxel-plugins')
require('voxel-registry')
require('voxel-stitch')
require('voxel-shader')

var BUILTIN_PLUGINS = ['voxel-registry', 'voxel-stitch', 'voxel-shader'];

var game = {};
global.game = game; // for debugging

var main = function(opts) {
  opts = opts || {};
  opts.clearColor = [0.75, 0.8, 0.9, 1.0]
  opts.pointerLock = true;

  var shell = createShell(opts);
  var camera = createCamera(shell);
  shell.camera = camera; // TODO: move to a plugin instead of hanging off shell instance?
  shell.meshes = []; // populated below TODO: move to voxels.meshes

  camera.position[0] = -20;
  camera.position[1] = -33;
  camera.position[2] = -40;

  game.isClient = true;
  game.shell = shell;

  // TODO: should plugin creation this be moved into gl-init?? see z-index note below

  var plugins = createPlugins(game, {require: function(name) {
    // we provide the built-in plugins ourselves; otherwise check caller's require, if any
    // TODO: allow caller to override built-ins? better way to do this?
    if (BUILTIN_PLUGINS.indexOf(name) !== -1) {
      return require(name);
    } else {
      return opts.require ? opts.require(name) : require(name);
    }
  }});

  var pluginOpts = opts.pluginOpts || {}; // TODO: persist

  BUILTIN_PLUGINS.forEach(function(name) {
    opts.pluginOpts[name] = opts.pluginOpts[name] || {};
  });

  for (var name in pluginOpts) {
    plugins.add(name, pluginOpts[name]);
  }
  plugins.loadAll();

// bit in voxel array to indicate voxel is opaque (transparent if not set)
var OPAQUE = 1<<15;

shell.on("gl-init", function() {
  var gl = shell.gl

  // since the plugins are loaded before gl-init, the <canvas> element will be
  // below other UI widgets in the DOM tree, so by default the z-order will cause
  // the canvas to cover the other widgets - to fix this, set z-index below
  shell.canvas.style.zIndex = '-1';
  shell.canvas.parentElement.style.zIndex = '-1';

  // TODO: is this right? see https://github.com/mikolalysenko/ao-shader/issues/2
  //gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  //gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  gl.enable(gl.BLEND)
  // premultiply alpha when loading textures, so can use gl.ONE blending, see http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl
  // TODO: move to gl-texture2d?
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)

  //Lookup voxel materials for terrain generation
  var registry = plugins.get('voxel-registry')
  if (registry) {
    var terrainMaterials = {};
    for (var blockName in registry.blockName2Index) {
      var blockIndex = registry.blockName2Index[blockName];
      if (registry.getProp(blockName, 'transparent')) {
        terrainMaterials[blockName] = blockIndex - 1
      } else {
        terrainMaterials[blockName] = OPAQUE|(blockIndex - 1) // TODO: separate arrays? https://github.com/mikolalysenko/ao-mesher/issues/2
      }
    }
  } else {
    console.warn('voxel-registry plugin not found, expect no textures')
  }

  //Create texture atlas
  var stitcher = game.plugins.get('voxel-stitch')
  if (stitcher) {
    var updateTexture = function() {
      console.log('updateTexture() calling createGLTexture()')

      stitcher.createGLTexture(gl, function(err, tex) {
        if (err) throw new Error('stitcher createGLTexture error: ' + err)
        stitcher.texture = tex // TODO: fix this awkward roundaboutness. voxel-shader uses this
      })

      // the voxels!
      var mesh = createVoxelMesh(shell.gl, createTerrain(terrainMaterials), stitcher.voxelSideTextureIDs, stitcher.voxelSideTextureSizes)
      shell.meshes = [mesh] // for voxel-wireframe TODO: refactor
      var c = mesh.center
      camera.lookAt([c[0]+mesh.radius*2, c[1], c[2]], c, [0,1,0])
    }
    stitcher.on('updateTexture', updateTexture)
    stitcher.stitch()
  } else {
    console.warn('voxel-stitch plugin not found, expect no textures')
  }
})

shell.on("gl-error", function(err) {
  var a = document.createElement('a')
  a.textContent = 'You need a modern WebGL browser (Chrome/Firefox) to play this game. Click here for more information. (WebGL error: ' + err + ')'
  a.style.webkitUserSelect = ''
  a.href = 'http://get.webgl.org/';

  while(document.body.firstChild) document.body.removeChild(document.body.firstChild)

  document.body.appendChild(a)
})

shell.on("gl-render", function(t) {
  var gl = shell.gl

})

  return shell // TODO: fix indenting
}

module.exports = main

<commit_msg>Remove now-unused gl-render<commit_after>"use strict"

var createShell = require("gl-now")
var createCamera = require("game-shell-fps-camera")
var ndarray = require("ndarray")
var createTerrain = require("./lib/terrain.js") // TODO: replace with shama's chunker mentioned in https://github.com/voxel/issues/issues/4#issuecomment-39644684
var createVoxelMesh = require("voxel-mesher")

var createPlugins = require('voxel-plugins')
require('voxel-registry')
require('voxel-stitch')
require('voxel-shader')

var BUILTIN_PLUGINS = ['voxel-registry', 'voxel-stitch', 'voxel-shader'];

var game = {};
global.game = game; // for debugging

var main = function(opts) {
  opts = opts || {};
  opts.clearColor = [0.75, 0.8, 0.9, 1.0]
  opts.pointerLock = true;

  var shell = createShell(opts);
  var camera = createCamera(shell);
  shell.camera = camera; // TODO: move to a plugin instead of hanging off shell instance?
  shell.meshes = []; // populated below TODO: move to voxels.meshes

  camera.position[0] = -20;
  camera.position[1] = -33;
  camera.position[2] = -40;

  game.isClient = true;
  game.shell = shell;

  // TODO: should plugin creation this be moved into gl-init?? see z-index note below

  var plugins = createPlugins(game, {require: function(name) {
    // we provide the built-in plugins ourselves; otherwise check caller's require, if any
    // TODO: allow caller to override built-ins? better way to do this?
    if (BUILTIN_PLUGINS.indexOf(name) !== -1) {
      return require(name);
    } else {
      return opts.require ? opts.require(name) : require(name);
    }
  }});

  var pluginOpts = opts.pluginOpts || {}; // TODO: persist

  BUILTIN_PLUGINS.forEach(function(name) {
    opts.pluginOpts[name] = opts.pluginOpts[name] || {};
  });

  for (var name in pluginOpts) {
    plugins.add(name, pluginOpts[name]);
  }
  plugins.loadAll();

// bit in voxel array to indicate voxel is opaque (transparent if not set)
var OPAQUE = 1<<15;

shell.on("gl-init", function() {
  var gl = shell.gl

  // since the plugins are loaded before gl-init, the <canvas> element will be
  // below other UI widgets in the DOM tree, so by default the z-order will cause
  // the canvas to cover the other widgets - to fix this, set z-index below
  shell.canvas.style.zIndex = '-1';
  shell.canvas.parentElement.style.zIndex = '-1';

  // TODO: is this right? see https://github.com/mikolalysenko/ao-shader/issues/2
  //gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  //gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  gl.enable(gl.BLEND)
  // premultiply alpha when loading textures, so can use gl.ONE blending, see http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl
  // TODO: move to gl-texture2d?
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)

  //Lookup voxel materials for terrain generation
  var registry = plugins.get('voxel-registry')
  if (registry) {
    var terrainMaterials = {};
    for (var blockName in registry.blockName2Index) {
      var blockIndex = registry.blockName2Index[blockName];
      if (registry.getProp(blockName, 'transparent')) {
        terrainMaterials[blockName] = blockIndex - 1
      } else {
        terrainMaterials[blockName] = OPAQUE|(blockIndex - 1) // TODO: separate arrays? https://github.com/mikolalysenko/ao-mesher/issues/2
      }
    }
  } else {
    console.warn('voxel-registry plugin not found, expect no textures')
  }

  //Create texture atlas
  var stitcher = game.plugins.get('voxel-stitch')
  if (stitcher) {
    var updateTexture = function() {
      console.log('updateTexture() calling createGLTexture()')

      stitcher.createGLTexture(gl, function(err, tex) {
        if (err) throw new Error('stitcher createGLTexture error: ' + err)
        stitcher.texture = tex // TODO: fix this awkward roundaboutness. voxel-shader uses this
      })

      // the voxels!
      var mesh = createVoxelMesh(shell.gl, createTerrain(terrainMaterials), stitcher.voxelSideTextureIDs, stitcher.voxelSideTextureSizes)
      shell.meshes = [mesh] // for voxel-wireframe TODO: refactor
      var c = mesh.center
      camera.lookAt([c[0]+mesh.radius*2, c[1], c[2]], c, [0,1,0])
    }
    stitcher.on('updateTexture', updateTexture)
    stitcher.stitch()
  } else {
    console.warn('voxel-stitch plugin not found, expect no textures')
  }
})

shell.on("gl-error", function(err) {
  var a = document.createElement('a')
  a.textContent = 'You need a modern WebGL browser (Chrome/Firefox) to play this game. Click here for more information. (WebGL error: ' + err + ')'
  a.style.webkitUserSelect = ''
  a.href = 'http://get.webgl.org/';

  while(document.body.firstChild) document.body.removeChild(document.body.firstChild)

  document.body.appendChild(a)
})

  return shell // TODO: fix indenting
}

module.exports = main

<|endoftext|>


<commit_before>/*
    Mercy.js
    Copyright (C) 2016 - Wesley Rhodes
    This software may be modified and distributed under the terms
    of the MIT license.  See the LICENSE file for details.

*/

/*
    #Version 0.01

    This bot is a very very very basic barebones implementation of what a Discord bot can do.
    I started this project to see what all the bot was capable of, and look forward to adding
    to it as frequently as I can.  I want to integrate more useful and powerful API's in the
    near future, and hopefully more functionality.

    TO DO NEXT:
        Admin functionality.
*/

// auth.json is used to store token information in token : "<Your Token>".
var AuthInfo = require("./auth.json");
// List of quotes
var quotes = require("./quotes.json");

var Cleverbot = require('cleverbot-node');
cleverBot = new Cleverbot;

// In Debug roles will be printed to console.
var debugMode = 0

// Neccesary dependency.
var DiscordClient = require('discord.io');

// Starting the bot with the supplied token.
var bot = new DiscordClient({
    autorun: true,
    token: AuthInfo.token
});

// Setting command prefixes.
var userPre = "~";
var adminPre = "!";

bot.on('ready', function () {
    console.log(bot.username + " online @ " + Date());
    if (debugMode === 1) {
        console.log(bot.servers[servID].roles);
    } else {
        return;
    }
});

bot.on('disconnected', function () {
    console.log(bot.username + " (" + bot.id + ") disconnected!");
    process.exit(1);
});

bot.on('message', function (user, userID, channelID, message, rawEvent) {

    // For parsing multiple arguments.
    var messageParts = message.split(" ");

    if (userID === bot.id) {
        return;
    }

    // If userID is defined, define replyID.
    if (typeof userID !== 'undefined') {
        var replyID = "<@" + userID + "> "
    }

    // Simple hello back script.
    if (message === "Hi Mercy!") {
        if (typeof userID !== 'undefined') {
            console.log("I was greeted!");
            bot.sendMessage({
                to: channelID,
                message: "Hello " + replyID + "!"
            });
        }

        else {
            bot.sendMessage({
                to: channelID,
                message: "Hiya!"
            });
        }

    }

    if (message === userPre + "Leeki") {
        bot.sendMessage({
            to: channelID,
            message: quotes.Leeki
        })
    }

    if (message === userPre + "shrug") {
        bot.sendMessage({
            to: channelID,
            message: "¯\\_(ツ)_/¯"
        });
    }

	if (message === userPre + "ayy") {
	    bot.sendMessage({
	        to: channelID,
	        message: quotes.ayy
	    });
	}

    // Array of all possible 8-ball responses.
    var eightBall = ["It is certain.",
                     "It is decidely so.",
                     "Without a doubt.",
                     "Yes, definitely.",
                     "You may rely on it.",
                     "As I see it, yes.",
                     "Most likely.",
                     "Outlook good.",
                     "Yes.",
                     "Signs point to yes.",
                     "Reply hazy, try again.",
                     "Ask again later.",
                     "Cannot predict now.",
                     "Concentrate and ask again.",
                     "Don't count on it.",
                     "My reply is no.",
                     "My sources say no.",
                     "Outlook not so good.",
                     "Very doubtful"];

    // 8-ball implementation.
    if (messageParts[0] === userPre + "8ball") {
        var response = eightBall[Math.floor(Math.random() * eightBall.length)];
        var question = "\"";

        // Reconstruct question.
        for (i = 1; i < messageParts.length; i++) {
            if (i + 1 !== messageParts.length) {
                question += messageParts[i] + " ";
            }

            else {
                question += messageParts[i] + "\" ";
            }
        }

        // Send formatted response.
        bot.sendMessage({
            to: channelID,
            message: replyID + "You asked: " + question + "I respond with: " + response
        });
    }

    if (messageParts[0] === userPre) {
        // Reconstruct phrase.
        var statement = "";
        for (i = 1; i <= messageParts.length; i++) {
            if (i !== messageParts.length) {
                statement += messageParts[i] + " ";
            }
        }

        Cleverbot.prepare(function () {
            cleverBot.write(statement, function (response) {
                bot.sendMessage({
                    to: channelID,
                    message: response.message
                });
            });
        });
    }
});<commit_msg>Add files via upload<commit_after>/*
    Mercy.js
    Copyright (C) 2016 - Wesley Rhodes
    This software may be modified and distributed under the terms
    of the MIT license.  See the LICENSE file for details.

*/

/*
    #Version 0.01

    This bot is a very very very basic barebones implementation of what a Discord bot can do.
    I started this project to see what all the bot was capable of, and look forward to adding
    to it as frequently as I can.  I want to integrate more useful and powerful API's in the
    near future, and hopefully more functionality.

    TO DO NEXT:
        Admin functionality.
*/

// auth.json is used to store token information in token : "<Your Token>".
var AuthInfo = require("./auth.json");

var Cleverbot = require('cleverbot-node');
cleverBot = new Cleverbot;

// In Debug roles will be printed to console.
var debugMode = 0

// Neccesary dependency.
var DiscordClient = require('discord.io');

// Starting the bot with the supplied token.
var bot = new DiscordClient({
    autorun: true,
    token: AuthInfo.token
});

// Setting command prefixes.
var userPre = "~";
var adminPre = "!";

bot.on('ready', function () {
    console.log(bot.username + " online @ " + Date());
    if (debugMode === 1) {
        console.log(bot.servers[servID].roles);
    } else {
        return;
    }
});

bot.on('disconnected', function () {
    console.log(bot.username + " (" + bot.id + ") disconnected!");
    process.exit(1);
});

bot.on('message', function (user, userID, channelID, message, rawEvent) {

    // For parsing multiple arguments.
    var messageParts = message.split(" ");

    if (userID === bot.id) {
        return;
    }

    // If userID is defined, define replyID.
    if (typeof userID !== 'undefined') {
        var replyID = "<@" + userID + "> "
    }

    if (message === userPre + "shrug") {
        bot.sendMessage({
            to: channelID,
            message: "¯\\_(ツ)_/¯"
        });
    }

    // Array of all possible 8-ball responses.
    var eightBall = ["It is certain.",
                     "It is decidely so.",
                     "Without a doubt.",
                     "Yes, definitely.",
                     "You may rely on it.",
                     "As I see it, yes.",
                     "Most likely.",
                     "Outlook good.",
                     "Yes.",
                     "Signs point to yes.",
                     "Reply hazy, try again.",
                     "Ask again later.",
                     "Cannot predict now.",
                     "Concentrate and ask again.",
                     "Don't count on it.",
                     "My reply is no.",
                     "My sources say no.",
                     "Outlook not so good.",
                     "Very doubtful"];

    // 8-ball implementation.
    if (messageParts[0] === userPre + "8ball") {
        var response = eightBall[Math.floor(Math.random() * eightBall.length)];
        var question = "\"";

        // Reconstruct question.
        for (i = 1; i < messageParts.length; i++) {
            if (i + 1 !== messageParts.length) {
                question += messageParts[i] + " ";
            }

            else {
                question += messageParts[i] + "\" ";
            }
        }

        // Send formatted response.
        bot.sendMessage({
            to: channelID,
            message: replyID + "You asked: " + question + "I respond with: " + response
        });
    }

    if (messageParts[0] === userPre) {
        // Reconstruct phrase.
        var statement = "";
        for (i = 1; i <= messageParts.length; i++) {
            if (i !== messageParts.length) {
                statement += messageParts[i] + " ";
            }
        }

        Cleverbot.prepare(function () {
            cleverBot.write(statement, function (response) {
                bot.sendMessage({
                    to: channelID,
                    message: response.message
                });
            });
        });
    }
});<|endoftext|>


<commit_before>'use strict';

const { app, BrowserWindow, dialog, ipcMain, Menu } = require('electron');
const file = require('./src/utils/file');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 1200, height: 800});

  // and load the index.html of the app.
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('file://' + __dirname + '/src/index.html');
  } else if (process.env.NODE_ENV === 'production') {
    mainWindow.loadURL('file://' + __dirname + '/index.html');
  }

  // Open the DevTools.
  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools();
  }

  // Emitted when the window is closed.
  mainWindow.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
  createWindow();
  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

// Set up application menu.
let template = [
  {
    label: 'File',
    submenu: [
      {
        label: 'New File',
        accelerator: 'CmdOrCtrl+N',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            file.fileNew();
          }
        }
      },
      {
        label: 'Open File',
        accelerator: 'CmdOrCtrl+O',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            dialog.showOpenDialog({
              properties: ['fileOpen'],
              filters: [
                { name: 'Caption Files', extensions: ['srt', 'smi', 'vtt'] }
              ]}, (filenames) => {
              file.fileOpen(filenames[0]);
            });
          }
        }
      },
      {
        label: 'Open Video',
        accelerator: 'CmdOrCtrl+Shift+O',
        click: (item, focusedWindow) => {
          if(focusedWindow) {
            dialog.showOpenDialog({
              properties: ['fileOpen'],
              filters: [
                { name: 'Video Files', extensions: ['mp4', 'webm', 'ogg'] }
              ]}, (filenames) => {
              file.fileOpen(filenames[0]);
            });
          }
        }
      },
      {
        label: 'Save',
        accelerator: 'CmdOrCtrl+S',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            mainWindow.webContents.send('file-state-req');
            ipcMain.on('file-state-res', (event, state, filename) => {
              if(state == 'unsaved') {
                dialog.showSaveDialog({
                  filters: [
                    { name: 'SubRip', extensions: ['srt'] },
                    { name: 'WebVTT', extensions: ['vtt'] },
                    { name: 'SAMI', extensions: ['smi'] }
                  ]}, (filename) => {
                  file.fileSave(filename);
                });
              } else if(state == 'saved') {
                file.fileSave(filename);
              }
            });
          }
        }
      },
      {
        label: 'Save As',
        accelerator: 'CmdOrCtrl+Shift+S',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            dialog.showSaveDialog({
              filters: [
                { name: 'SubRip', extensions: ['srt'] },
                { name: 'WebVTT', extensions: ['vtt'] },
                { name: 'SAMI', extensions: ['smi'] }
              ]}, (filename) => {
              file.fileSave(filename);
            });
          }
        }
      }
    ]
  },
  {
    label: 'Edit',
    submenu: [
      {
        label: 'Undo',
        accelerator: 'CmdOrCtrl+Z',
        role: 'undo'
      },
      {
        label: 'Redo',
        accelerator: 'Shift+CmdOrCtrl+Z',
        role: 'redo'
      },
      {
        type: 'separator'
      },
      {
        label: 'Cut',
        accelerator: 'CmdOrCtrl+X',
        role: 'cut'
      },
      {
        label: 'Copy',
        accelerator: 'CmdOrCtrl+C',
        role: 'copy'
      },
      {
        label: 'Paste',
        accelerator: 'CmdOrCtrl+V',
        role: 'paste'
      },
      {
        label: 'Select All',
        accelerator: 'CmdOrCtrl+A',
        role: 'selectall'
      }
    ]
  },
  {
    label: 'View',
    submenu: [
      {
        label: 'Reload',
        accelerator: 'CmdOrCtrl+R',
        click: (item, focusedWindow) => {
          if (focusedWindow)
            focusedWindow.reload();
        }
      },
      {
        label: 'Toggle Full Screen',
        accelerator: (() => {
          if (process.platform == 'darwin')
            return 'Ctrl+Command+F';
          else
            return 'F11';
        })(),
        click: (item, focusedWindow) => {
          if (focusedWindow)
            focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: (() => {
          if (process.platform == 'darwin')
            return 'Alt+Command+I';
          else
            return 'Ctrl+Shift+I';
        })(),
        click: (item, focusedWindow) => {
          if (focusedWindow)
            focusedWindow.toggleDevTools();
        }
      }
    ]
  },
  {
    label: 'Window',
    role: 'window',
    submenu: [
      {
        label: 'Minimize',
        accelerator: 'CmdOrCtrl+M',
        role: 'minimize'
      },
      {
        label: 'Close',
        accelerator: 'CmdOrCtrl+W',
        role: 'close'
      }
    ]
  },
  {
    label: 'Help',
    role: 'help',
    submenu: [
      {
        label: 'Learn More',
        click: () => { require('electron').shell.openExternal('http://electron.atom.io'); }
      }
    ]
  }
];
if (process.platform == 'darwin') {
  var name = require('electron').remote.app.getName();
  template.unshift({
    label: name,
    submenu: [
      {
        label: 'About ' + name,
        role: 'about'
      },
      {
        type: 'separator'
      },
      {
        label: 'Services',
        role: 'services',
        submenu: []
      },
      {
        type: 'separator'
      },
      {
        label: 'Hide ' + name,
        accelerator: 'Command+H',
        role: 'hide'
      },
      {
        label: 'Hide Others',
        accelerator: 'Command+Alt+H',
        role: 'hideothers'
      },
      {
        label: 'Show All',
        role: 'unhide'
      },
      {
        type: 'separator'
      },
      {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: () => { app.quit(); }
      }
    ]
  });
  // Window menu.
  template[3].submenu.push(
    {
      type: 'separator'
    },
    {
      label: 'Bring All to Front',
      role: 'front'
    }
  );
}
<commit_msg>Developer tools in only dev env.<commit_after>'use strict';

const { app, BrowserWindow, dialog, ipcMain, Menu } = require('electron');
const file = require('./src/utils/file');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 1200, height: 800});

  // and load the index.html of the app.
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('file://' + __dirname + '/src/index.html');
  } else if (process.env.NODE_ENV === 'production') {
    mainWindow.loadURL('file://' + __dirname + '/index.html');
  }

  // Open the DevTools.
  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools();
  }

  // Emitted when the window is closed.
  mainWindow.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
  createWindow();
  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

// Set up application menu.
let template = [
  {
    label: 'File',
    submenu: [
      {
        label: 'New File',
        accelerator: 'CmdOrCtrl+N',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            file.fileNew();
          }
        }
      },
      {
        label: 'Open File',
        accelerator: 'CmdOrCtrl+O',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            dialog.showOpenDialog({
              properties: ['fileOpen'],
              filters: [
                { name: 'Caption Files', extensions: ['srt', 'smi', 'vtt'] },
                { name: 'All Files', extensions: ['*'] }
              ]}, (filenames) => {
              if (filenames) {
                file.fileOpen(filenames[0]);
              }
            });
          }
        }
      },
      {
        label: 'Open Video',
        accelerator: 'CmdOrCtrl+Shift+O',
        click: (item, focusedWindow) => {
          if(focusedWindow) {
            dialog.showOpenDialog({
              properties: ['fileOpen'],
              filters: [
                { name: 'Video Files', extensions: ['mp4', 'webm', 'ogg'] },
                { name: 'All Files', extensions: ['*'] }
              ]}, (filenames) => {
              if (filenames) {
                file.fileOpen(filenames[0]);
              }
            });
          }
        }
      },
      {
        label: 'Save',
        accelerator: 'CmdOrCtrl+S',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            mainWindow.webContents.send('file-state-req');
            ipcMain.on('file-state-res', (event, state, filename) => {
              if(state == 'unsaved') {
                dialog.showSaveDialog({
                  filters: [
                    { name: 'SubRip', extensions: ['srt'] },
                    { name: 'WebVTT', extensions: ['vtt'] },
                    { name: 'SAMI', extensions: ['smi'] }
                  ]}, (filename) => {
                  file.fileSave(filename);
                });
              } else if(state == 'saved') {
                file.fileSave(filename);
              }
            });
          }
        }
      },
      {
        label: 'Save As',
        accelerator: 'CmdOrCtrl+Shift+S',
        click: (item, focusedWindow) => {
          if (focusedWindow) {
            dialog.showSaveDialog({
              filters: [
                { name: 'SubRip', extensions: ['srt'] },
                { name: 'WebVTT', extensions: ['vtt'] },
                { name: 'SAMI', extensions: ['smi'] }
              ]}, (filename) => {
              file.fileSave(filename);
            });
          }
        }
      }
    ]
  },
  {
    label: 'Edit',
    submenu: [
      {
        label: 'Undo',
        accelerator: 'CmdOrCtrl+Z',
        role: 'undo'
      },
      {
        label: 'Redo',
        accelerator: 'Shift+CmdOrCtrl+Z',
        role: 'redo'
      },
      {
        type: 'separator'
      },
      {
        label: 'Cut',
        accelerator: 'CmdOrCtrl+X',
        role: 'cut'
      },
      {
        label: 'Copy',
        accelerator: 'CmdOrCtrl+C',
        role: 'copy'
      },
      {
        label: 'Paste',
        accelerator: 'CmdOrCtrl+V',
        role: 'paste'
      },
      {
        label: 'Select All',
        accelerator: 'CmdOrCtrl+A',
        role: 'selectall'
      }
    ]
  },
  {
    label: 'View',
    submenu: [
      {
        label: 'Reload',
        accelerator: 'CmdOrCtrl+R',
        click: (item, focusedWindow) => {
          if (focusedWindow)
            focusedWindow.reload();
        }
      },
      {
        label: 'Toggle Full Screen',
        accelerator: (() => {
          if (process.platform == 'darwin')
            return 'Ctrl+Command+F';
          else
            return 'F11';
        })(),
        click: (item, focusedWindow) => {
          if (focusedWindow)
            focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      }
    ]
  },
  {
    label: 'Window',
    role: 'window',
    submenu: [
      {
        label: 'Minimize',
        accelerator: 'CmdOrCtrl+M',
        role: 'minimize'
      },
      {
        label: 'Close',
        accelerator: 'CmdOrCtrl+W',
        role: 'close'
      }
    ]
  },
  {
    label: 'Help',
    role: 'help',
    submenu: [
      {
        label: 'GitHub',
        click: () => { require('electron').shell.openExternal('https://github.com/Heeryong-Kang/jamak'); }
      }
    ]
  }
];
if (process.platform == 'darwin') {
  var name = require('electron').remote.app.getName();
  template.unshift({
    label: name,
    submenu: [
      {
        label: 'About ' + name,
        role: 'about'
      },
      {
        type: 'separator'
      },
      {
        label: 'Services',
        role: 'services',
        submenu: []
      },
      {
        type: 'separator'
      },
      {
        label: 'Hide ' + name,
        accelerator: 'Command+H',
        role: 'hide'
      },
      {
        label: 'Hide Others',
        accelerator: 'Command+Alt+H',
        role: 'hideothers'
      },
      {
        label: 'Show All',
        role: 'unhide'
      },
      {
        type: 'separator'
      },
      {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: () => { app.quit(); }
      }
    ]
  });
  // Window menu.
  template[3].submenu.push(
    {
      type: 'separator'
    },
    {
      label: 'Bring All to Front',
      role: 'front'
    }
  );
}

if (process.env.NODE_ENV === 'development') {
  template[2].submenu.push(
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform == 'darwin')
          return 'Alt+Command+I';
        else
          return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow)
          focusedWindow.toggleDevTools();
      }
    }
  );
}
<|endoftext|>


<commit_before>'use strict';

const electron = require('electron');
const ipcMain = require('electron').ipcMain;
const fetch = require('node-fetch');
const app = electron.app;
const Menu = electron.Menu;
const MenuItem = electron.MenuItem;
const Tray = electron.Tray;
const BrowserWindow = electron.BrowserWindow;
const environment = process.env.NODE_ENV || 'production';

let mainWindow;
let appIcon;
let menu;
let projectURL;
let projectName;

ipcMain.on('project-updated', (event, data) => {
  projectURL = data.newURL;
  projectName = data.newURL.split('https://api.waffle.io/projects/',2)[1];
});

function getPullRequests(projectName) {
  fetch('https://api.waffle.io/'+ projectName + '/cards')
  .then((res) => {
    return res.json()
  })
  .then((json) => {
    return json.filter((item) => item.githubMetadata.pull_request && item.githubMetadata.state === 'open');
  })
  .then((res) => {
    appIcon.setTitle('' + res.length);
    app.dock.setBadge('' + res.length);
  })
}

function createWindow () {
  mainWindow = new BrowserWindow({width: 800, height: 600, alwaysOnTop: false, frame: false});
  mainWindow.loadURL('file://' + __dirname + '/app/index.html');
  mainWindow.maximize();
  mainWindow.setResizable(false);

  appIcon = new Tray(__dirname + '/images/visible.png');

  setInterval(() => {
    if(projectName) {
      getPullRequests(projectName);
    }
  },5000)

  let template = [
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Undo',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo'
        },
        {
          label: 'Redo',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo'
        },
        {
          type: 'separator'
        },
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        },
      ]
    }
  ];

  if (process.platform == 'darwin') {
    let name = require('electron').app.getName();
    template.unshift({
      label: name,
      submenu: [
        {
          label: 'About ' + name,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide ' + name,
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click: () => app.quit()
        },
      ]
    });
  }

  let menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

  appIcon.setToolTip('Waffle.io');
  appIcon.on('click', () => {
    mainWindow.isVisible() ? hideWindow() : showWindow()
  })

  mainWindow.on('blur', () => {
    hideWindow();
  });

  let hideWindow = () => {
    mainWindow.hide()
    appIcon.setImage(__dirname + '/images/hidden.png');
  };

  let showWindow = () => {
    mainWindow.show()
    appIcon.setImage(__dirname + '/images/visible.png');
  };

  if(environment === 'development') {
    mainWindow.webContents.openDevTools();
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});
<commit_msg>Clear badge if there are 0 pull requests<commit_after>'use strict';

const electron = require('electron');
const ipcMain = require('electron').ipcMain;
const fetch = require('node-fetch');
const app = electron.app;
const Menu = electron.Menu;
const MenuItem = electron.MenuItem;
const Tray = electron.Tray;
const BrowserWindow = electron.BrowserWindow;
const environment = process.env.NODE_ENV || 'production';

let mainWindow;
let appIcon;
let menu;
let projectURL;
let projectName;

ipcMain.on('project-updated', (event, data) => {
  projectURL = data.newURL;
  projectName = data.newURL.split('https://api.waffle.io/projects/',2)[1];
});

function getPullRequests(projectName) {
  fetch('https://api.waffle.io/'+ projectName + '/cards')
  .then((res) => {
    return res.json()
  })
  .then((json) => {
    return json.filter((item) => item.githubMetadata.pull_request && item.githubMetadata.state === 'open');
  })
  .then((res) => {
    if(res.length > 0) {
      appIcon.setTitle('' + res.length);
      app.dock.setBadge('' + res.length);
    }else{
      appIcon.setTitle('');
      app.dock.setBadge('');
    }
  })
}

function createWindow () {
  mainWindow = new BrowserWindow({width: 800, height: 600, alwaysOnTop: false, frame: false});
  mainWindow.loadURL('file://' + __dirname + '/app/index.html');
  mainWindow.maximize();
  mainWindow.setResizable(false);

  appIcon = new Tray(__dirname + '/images/visible.png');

  setInterval(() => {
    if(projectName) {
      getPullRequests(projectName);
    }
  },5000)

  let template = [
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Undo',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo'
        },
        {
          label: 'Redo',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo'
        },
        {
          type: 'separator'
        },
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        },
      ]
    }
  ];

  if (process.platform == 'darwin') {
    let name = require('electron').app.getName();
    template.unshift({
      label: name,
      submenu: [
        {
          label: 'About ' + name,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide ' + name,
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click: () => app.quit()
        },
      ]
    });
  }

  let menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

  appIcon.setToolTip('Waffle.io');
  appIcon.on('click', () => {
    mainWindow.isVisible() ? hideWindow() : showWindow()
  })

  mainWindow.on('blur', () => {
    hideWindow();
  });

  let hideWindow = () => {
    mainWindow.hide()
    appIcon.setImage(__dirname + '/images/hidden.png');
  };

  let showWindow = () => {
    mainWindow.show()
    appIcon.setImage(__dirname + '/images/visible.png');
  };

  if(environment === 'development') {
    mainWindow.webContents.openDevTools();
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});
<|endoftext|>


<commit_before>'use restrict';
document.addEventListener('DOMContentLoaded', function (event) {
  var sourceUri = 'https://www.pixiv.net/ranking.php?mode=daily&format=json&content=illust';
  var promiseList = [];

  for (var i = 1; i <= 3; i++) {
    var p = axios.get(sourceUri + '&p=' + i);
    promiseList.push(p);
  }

  Promise.all(promiseList).then(function (values) {
    var items = [];
    var illustrations = [];
    values.forEach(function (response) {
      if (response.status === 200) {
        // Extracting illustration info
        response.data.contents.forEach(function (e) {
            illustrations.push({
              'illustrationId': e.illust_id,
              'illustrationUrl': e.url,
              'illustrationTitle': e.title,
              'userName': e.user_name,
            });
        });
      }
    });

    // Shuffle.
    illustrations = shuffle(illustrations);

    // Inserting elements to a New tab page body.
    illustrations.forEach(function (illust) {
      items.push(createGalleryItem(
        illust.illustrationId,
        illust.illustrationUrl,
        illust.illustrationTitle,
        illust.userName
      ));
    });

    items.forEach(function (item) {
      document.body.querySelector('#gallery').appendChild(item);
    });
  }).catch(function (response) {
    console.log(response);
  });
});

function createIllustrationElement(imageUrl, title, author) {
  var img = new Image();
  img.src = imageUrl;
  img.addEventListener('load', function (e) {
    e.target.classList.add('loaded');
  });
  img.alt = author + ' / ' + title;
  return img;
}

function createGalleryItem(illustrationId, imageUrl, title, author) {
    var linkUrl = 'https://www.pixiv.net/i/' + illustrationId;
    var img = createIllustrationElement(imageUrl, title, author);
    var anchor = document.createElement('a');
    anchor.setAttribute('href', linkUrl);
    anchor.appendChild(img);
    return anchor;
}

function shuffle(array) {
  var n = array.length, t, i;

  while (n) {
    i = Math.floor(Math.random() * n--);
    t = array[n];
    array[n] = array[i];
    array[i] = t;
  }

  return array;
}
<commit_msg>e to content<commit_after>'use restrict';
document.addEventListener('DOMContentLoaded', function (event) {
  var sourceUri = 'https://www.pixiv.net/ranking.php?mode=daily&format=json&content=illust';
  var promiseList = [];

  for (var i = 1; i <= 3; i++) {
    var p = axios.get(sourceUri + '&p=' + i);
    promiseList.push(p);
  }

  Promise.all(promiseList).then(function (values) {
    var items = [];
    var illustrations = [];
    values.forEach(function (response) {
      if (response.status === 200) {
        // Extracting illustration info
        response.data.contents.forEach(function (content) {
            illustrations.push({
              'illustrationId': content.illust_id,
              'illustrationUrl': content.url,
              'illustrationTitle': content.title,
              'userName': content.user_name,
            });
        });
      }
    });

    // Shuffle.
    illustrations = shuffle(illustrations);

    // Inserting elements to a New tab page body.
    illustrations.forEach(function (illust) {
      items.push(createGalleryItem(
        illust.illustrationId,
        illust.illustrationUrl,
        illust.illustrationTitle,
        illust.userName
      ));
    });

    items.forEach(function (item) {
      document.body.querySelector('#gallery').appendChild(item);
    });
  }).catch(function (response) {
    console.log(response);
  });
});

function createIllustrationElement(imageUrl, title, author) {
  var img = new Image();
  img.src = imageUrl;
  img.addEventListener('load', function (e) {
    e.target.classList.add('loaded');
  });
  img.alt = author + ' / ' + title;
  return img;
}

function createGalleryItem(illustrationId, imageUrl, title, author) {
    var linkUrl = 'https://www.pixiv.net/i/' + illustrationId;
    var img = createIllustrationElement(imageUrl, title, author);
    var anchor = document.createElement('a');
    anchor.setAttribute('href', linkUrl);
    anchor.appendChild(img);
    return anchor;
}

function shuffle(array) {
  var n = array.length, t, i;

  while (n) {
    i = Math.floor(Math.random() * n--);
    t = array[n];
    array[n] = array[i];
    array[i] = t;
  }

  return array;
}
<|endoftext|>


<commit_before>function debug(s){ if(prefs.debug){ console.log('main: '+s) }}

const defs = {
	addHist:'500',
	debug:false,
	delay:'500',
	dstBlock:'',
	hImgur:true,
	hReddit:true,
	hTinypic:true,
	keys:true,
	maxSize:'95',
	scrapeList:'500px.com, artstation.com, craigslist.org, deviantart.com, dropbox.com, explosm.net, goo.gl, ibb.co, imdb.com, imgflip.com, imgtc.com, facebook.com, fav.me, flic.kr, flickr.com, gifly.org, gfycat.com, giphy.com, imgly.org, imly.me, instagram.com, livememe.com, makeameme.org, redgifs.com, streamable.com, tumblr.com, twitter.com, vid.me, vidble.com, vine.co, wikipedia.org',
	scrapeListBlock:'icon.png, profile_images',
	srcBlock:'craigslist.org, flickr.com, imgur.com',
	textLoc:'bottom:6px; left:50%;'
}

var prefs = {}
const sto = browser.storage.sync;
function checkPrefs(p){
	if(!p){ var p = {} }
	var	op = JSON.stringify(prefs);
	for(let [k,v] of Object.entries(defs)){
		prefs[k] = (p[k] == undefined) ? v : p[k]
		debug(k+" : "+prefs[k])
	}
	if(JSON.stringify(prefs) != op){
		debug('prefs have changed');
		ports.forEach(function(p){ p.postMessage({ 'prefs':prefs }) });
		var w = sto.set({ 'prefs':prefs });
		w.then(function(){ debug('prefs saved to storage') });
	}else{
		debug('prefs checked, no changes');
	}
}

var ports = [];
var portsNum = 0;
browser.runtime.onConnect.addListener(function(p){
	p.num = portsNum;
	p.onMessage.addListener(function(m){
		debug('req: '+m.req);
		switch(m.req){
			case 'addHist':
				debug('adding to history: '+m.url);
				browser.history.addUrl({ url:m.url });
				break;
			case 'getPrefs':
				p.postMessage({ 'prefs':prefs });
				break;
			case 'resetPrefs':
				var w = sto.clear();
				w.then(function(){
					prefs = {}
					checkPrefs(prefs);
				});
				break;
			case 'savePrefs':
				checkPrefs(m.prefs);
				break;
			default:
				debug('unknown request');
		}
	});
	p.onDisconnect.addListener(function(){
		debug('port disconnected: '+p.num);
		ports.splice(ports.findIndex(i => i.num == p.num), 1);
	});
	ports.push(p);
	++portsNum;
});

sto.get('prefs').then(function(s){
	if(s.prefs){ prefs = s.prefs }
	checkPrefs(s.prefs);
});<commit_msg>ordered scrapeList<commit_after>function debug(s){ if(prefs.debug){ console.log('main: '+s) }}

const defs = {
	addHist:'500',
	debug:false,
	delay:'500',
	dstBlock:'',
	hImgur:true,
	hReddit:true,
	hTinypic:true,
	keys:true,
	maxSize:'95',
	scrapeList:'500px.com, artstation.com, craigslist.org, deviantart.com, dropbox.com, explosm.net, facebook.com, fav.me, flic.kr, flickr.com, gfycat.com, gifly.org, giphy.com, goo.gl, ibb.co, imdb.com, imgflip.com, imgly.org, imgtc.com, imly.me, instagram.com, livememe.com, makeameme.org, redgifs.com, streamable.com, tumblr.com, twitter.com, vid.me, vidble.com, vine.co, wikipedia.org',
	scrapeListBlock:'icon.png, profile_images',
	srcBlock:'craigslist.org, flickr.com, imgur.com',
	textLoc:'bottom:6px; left:50%;'
}

var prefs = {}
const sto = browser.storage.sync;
function checkPrefs(p){
	if(!p){ var p = {} }
	var	op = JSON.stringify(prefs);
	for(let [k,v] of Object.entries(defs)){
		prefs[k] = (p[k] == undefined) ? v : p[k]
		debug(k+" : "+prefs[k])
	}
	if(JSON.stringify(prefs) != op){
		debug('prefs have changed');
		ports.forEach(function(p){ p.postMessage({ 'prefs':prefs }) });
		var w = sto.set({ 'prefs':prefs });
		w.then(function(){ debug('prefs saved to storage') });
	}else{
		debug('prefs checked, no changes');
	}
}

var ports = [];
var portsNum = 0;
browser.runtime.onConnect.addListener(function(p){
	p.num = portsNum;
	p.onMessage.addListener(function(m){
		debug('req: '+m.req);
		switch(m.req){
			case 'addHist':
				debug('adding to history: '+m.url);
				browser.history.addUrl({ url:m.url });
				break;
			case 'getPrefs':
				p.postMessage({ 'prefs':prefs });
				break;
			case 'resetPrefs':
				var w = sto.clear();
				w.then(function(){
					prefs = {}
					checkPrefs(prefs);
				});
				break;
			case 'savePrefs':
				checkPrefs(m.prefs);
				break;
			default:
				debug('unknown request');
		}
	});
	p.onDisconnect.addListener(function(){
		debug('port disconnected: '+p.num);
		ports.splice(ports.findIndex(i => i.num == p.num), 1);
	});
	ports.push(p);
	++portsNum;
});

sto.get('prefs').then(function(s){
	if(s.prefs){ prefs = s.prefs }
	checkPrefs(s.prefs);
});<|endoftext|>


<commit_before>'use strict'

const loki = require("lokijs")

const db = new loki('mainDatabase.ffdb',
  {
    autoload: true,
    autoloadCallback : loadHandler,
    autosave: true,
    autosaveInterval: 10000,
  });

  const db2 = new loki('flowDB.ffdb',
    {
      autoload: true,
      autoloadCallback : loadHandler,
      autosave: true,
      autosaveInterval: 10000,
    });

function loadHandler() {
  var coll = db.getCollection('cards');
  if (coll === null) {
    coll = db.addCollection('cards');
  }
}

function addCardToLoki(datab, cardTagline, cardTags, cardCitation, cardContent, cardNotes) {
	var cards = datab.getCollection("cards")
	console.log(cardTags)
	cards.insert({
		tagLine: cardTagline,
		sTags: cardTags,
		citation: cardCitation,
		content: cardContent,
		notes: cardNotes
	})
	datab.saveDatabase()
}
/**/
function removeCard(datab, cardTagline, cardTags, cardCitation, cardContent, CardNotes) {
	var cards = datab.getCollection("cards")
	cards.remove({
		tagLine: cardTagline,
		sTags: cardTags,
		citation: cardCitation,
		content: cardContent,
		notes: cardNotes
	})
	datab.saveDatabase()
}

function tagindex (datab) {
  //tab index will return JSON in the form of a map of sTag:[CardTitles]
  /* example JSON
  {
    Aff: [card1, card2, card3],
    Pro: [card1, card22, card4]
  }
  */
  var dict = {}
  var PFST = [] //Previously Found S Tags, to avoid needless transversal of dict
  var cards = datab.getCollection("cards").data;
  var card, s, sTags
  for (card in cards) {                           //  go through each card
    sTags = JSON.parse(cards[card].sTags)         // turn sTags String into an array for transversal
    for (s in sTags) {                            // go through each sTag
      if(dict.hasOwnProperty(sTags[s]) && !dict[sTags[s].includes(cards[card].tagLine)]) {       // if the node already exists and tag is not already in node then
        console.log('Adding card ' + cards[card].tagLine +' to tag ' + sTags[s])
        dict[sTags[s]].push(cards[card].tagLine)                                                 // add the tag to the node
      } else {
        console.log('Adding card ' + cards[card].tagLine +' to newly created tag ' + sTags[s])
        dict[sTags[s]] = [cards[card].tagLine]                                                   // if the node does not already exist then create it and add tag
      }
    }
  }
  console.log(dict)

  return dict;
}

function flowindex (datab) {
  /* flowindexing */
  var cards = datab.getCollection("cards");
  var flowArray = [];
  var flows;
  var card;
  for(flows in cards.data){
    flowArray.push([flows["name"], flows["content"]])
  }
  console.log(flowArray)
  return flowArray;
}

var path = require('path')
var fs = require('fs')
const Regex = require("regex");
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const Menu = electron.Menu
const crashReporter = electron.crashReporter
const shell = electron.shell
const ipcMain = require('electron').ipcMain
let menu
let template
let mainWindow = null

crashReporter.start()

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')()
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

require('electron-debug')({
  showDevTools: true
})

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 728
  })

  mainWindow.loadURL(`file://${__dirname}/app/app.html`)

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools()
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit()
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.restart()
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools()
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io')
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron')
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues')
        }
      }]
    }]

    menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click () {
          mainWindow.close()
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click () {
          mainWindow.reload()
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click () {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click () {
          mainWindow.toggleDevTools()
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click () {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click () {
          shell.openExternal('http://electron.atom.io')
        }
      }, {
        label: 'Documentation',
        click () {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        }
      }, {
        label: 'Community Discussions',
        click () {
          shell.openExternal('https://discuss.atom.io/c/electron')
        }
      }, {
        label: 'Search Issues',
        click () {
          shell.openExternal('https://github.com/atom/electron/issues')
        }
      }]
    }]
    menu = Menu.buildFromTemplate(template)
    mainWindow.setMenu(menu)
  }

  function uniq(a) {
    var prims = {"boolean":{}, "number":{}, "string":{}}, objs = [];

    return a.filter(function(item) {
        var type = typeof item;
        if(type in prims)
            return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);
        else
            return objs.indexOf(item) >= 0 ? false : objs.push(item);
    });
  }

function deleteCard(datab, cardName){
  var cards = datab.getCollection("cards");
  cards.removeWhere({'tagLine': {'$eq': cardName}})
}

function getCard(datab, searchTerm){
  var cards = datab.getCollection("cards");
  var cardNames = cards.find({'tagLine': {'$contains': searchTerm}});
  return cardNames;
}

  function searchSimple(datab, searchTerm){
    var cards = datab.getCollection("cards");
    var returnListCards = []
    var cardTags = cards.find({'tags': {'$contains': searchTerm}})
    var cardNames = cards.find({'name': {'$contains': searchTerm}})
    var temp1 = 0;
    var temp2 = 0;

    if(cardTags != []){
      for (temp1 in cardTags){
        returnListCards.push(cardTags[temp1].name)
      }
    }

    if(cardNames != []){
      for (temp2 in cardNames){
        returnListCards.push(cardNames[temp2].name)
      }
    }
    return uniq(returnListCards)
  }

  ipcMain.on('Search', function (event, arg) {
    console.log(arg)
    console.log("-----------")
    console.log(searchSimple(db, arg))
    event.returnValue = searchSimple(db, arg)
  })

  ipcMain.on('FileOpen', function (event, arg) {
    var cards = db.getCollection("cards")
    var foundCard = cards.find({'tagLine' : arg})
    if(foundCard[0]){
      console.log('opening: ' + foundCard[0])
      event.returnValue = foundCard[0]
    } else {
      event.returnValue = false
    }
  })

  ipcMain.on('FlowOpen', function (event, arg) {
    var cards = db2.getCollection("cards");
    var FileArray = arg
    var foundCard = cards.find({'name' : arg})
    var Title = foundCard[0].name
    var Tags = ""
    var Content = foundCard[0].content
    var TheArray = [Title, Tags, Content]
    console.log('array: ' + TheArray)
    event.returnValue = TheArray

  })

  ipcMain.on('FileRemove', function (event, arg) {

    //removeCard(db, cardName, cardTags, cardContent)
    deleteCard(db, arg)
    console.log("removing:")
    console.log(arg)
    console.log("---------------")
    //removeCard(db, arg[0], arg[1], arg[2])
  })

  ipcMain.on('FlowRemove', function (event, arg) {

    //removeCard(db, cardName, cardTags, cardContent)
    deleteCard(db2, arg)
    console.log("removing:")
    console.log(arg)
    console.log("---------------")
    //removeCard(db, arg[0], arg[1], arg[2])
  })

  ipcMain.on('CardManager', function (event, arg) {
    var dataJSON = tagindex(db)
    event.returnValue = dataJSON
  })

  /* card saving */
  ipcMain.on('FileSave', function (event, arg) {
    console.log(arg)
    // [TitleString, TagString, ContentString]
    var cards = db.getCollection("cards");
    var tagLine = arg.tagLine
    var sTags = arg.sTags
    var content = arg.content
    var notes = arg.notes
    var cite = arg.citation
    var temp = cards.find({'tagLine' : tagLine})
    if (temp.length !== 0){
      cards.removeWhere({'tagLine' : TitleString})
    }
    addCardToLoki(db, tagLine, sTags, cite, content, notes);
    tagindex(db)
  })
})

ipcMain.on('FlowSave', function (event, arg) {
  console.log(arg)
  // [TitleString, TagString, ContentString]
  var cards = db2.getCollection("cards");
  var TitleString = arg[0]
  var TagString = "";
  var ContentString = arg[2]
  var temp = cards.find({'name' : TitleString})
  if (temp.length == 0){
    addCardToLoki(db2, TitleString, TagString, ContentString);
  }else{
    console.log("hello")
      cards.removeWhere({'name' : TitleString})
      addCardToLoki(db2, TitleString, TagString, ContentString);
  }
})
<commit_msg>Database Cleaning Up<commit_after>'use strict'

const loki = require("lokijs")

const cardDb = new loki('mainDatabase.ffdb',
  {
    autoload: true,
    autoloadCallback : loadHandler,
    autosave: true,
    autosaveInterval: 1000,
  });

function loadHandler() {
  var coll = cardDb.getCollection('cards');
  if (coll === null) {
    coll = cardDb.addCollection('cards');
  }
}

function tagindex (datab) {
  //tab index will return JSON in the form of a map of sTag:[CardTitles]
  /* example JSON
  {
    Aff: [card1, card2, card3],
    Pro: [card1, card22, card4]
  }
  */
  var dict = {}
  var PFST = [] //Previously Found S Tags, to avoid needless transversal of dict
  var cards = datab.getCollection("cards").data;
  var card, s, sTags
  for (card in cards) {                           //  go through each card
    sTags = JSON.parse(cards[card].sTags)         // turn sTags String into an array for transversal
    for (s in sTags) {                            // go through each sTag
      if(dict.hasOwnProperty(sTags[s]) && !dict[sTags[s].includes(cards[card].tagLine)]) {       // if the node already exists and tag is not already in node then
        console.log('Adding card ' + cards[card].tagLine +' to tag ' + sTags[s])
        dict[sTags[s]].push(cards[card].tagLine)                                                 // add the tag to the node
      } else {
        console.log('Adding card ' + cards[card].tagLine +' to newly created tag ' + sTags[s])
        dict[sTags[s]] = [cards[card].tagLine]                                                   // if the node does not already exist then create it and add tag
      }
    }
  }
  console.log(dict)

  return dict;
}

var path = require('path')
var fs = require('fs')
const Regex = require("regex");
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const Menu = electron.Menu
const crashReporter = electron.crashReporter
const shell = electron.shell
const ipcMain = require('electron').ipcMain
let menu
let template
let mainWindow = null

crashReporter.start()

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')()
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

require('electron-debug')({
  showDevTools: true
})

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 728
  })

  mainWindow.loadURL(`file://${__dirname}/app/app.html`)

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools()
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit()
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.restart()
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools()
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io')
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron')
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues')
        }
      }]
    }]

    menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click () {
          mainWindow.close()
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click () {
          mainWindow.reload()
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click () {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click () {
          mainWindow.toggleDevTools()
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click () {
          mainWindow.setFullScreen(!mainWindow.isFullScreen())
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click () {
          shell.openExternal('http://electron.atom.io')
        }
      }, {
        label: 'Documentation',
        click () {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme')
        }
      }, {
        label: 'Community Discussions',
        click () {
          shell.openExternal('https://discuss.atom.io/c/electron')
        }
      }, {
        label: 'Search Issues',
        click () {
          shell.openExternal('https://github.com/atom/electron/issues')
        }
      }]
    }]
    menu = Menu.buildFromTemplate(template)
    mainWindow.setMenu(menu)
  }

function uniq(a){
  //Im not walking through this, cuz honestly, i dont know what this does anymore, but it works, so be happy
    var prims = {"boolean":{}, "number":{}, "string":{}}, objs = [];

    return a.filter(function(item) {
        var type = typeof item;
        if(type in prims)
            return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);
        else
            return objs.indexOf(item) >= 0 ? false : objs.push(item);
    });
  }

function addCardToLoki(datab, cardTagline, cardTags, cardCitation, cardContent, cardNotes) {
   //If you are reading this code and cant figure out what this does, then you need to stop reading this code right now and
   //get a different profession. It legit says "addCardToLoki" cuz thats what it does
    var cards = datab.getCollection("cards")
  	console.log(cardTags)
  	cards.insert({
  		tagLine: cardTagline,
  		sTags: cardTags,
  		citation: cardCitation,
  		content: cardContent,
  		notes: cardNotes
  	})
  	datab.saveDatabase()
  }

function deleteCard(datab, cardName){
  //Umm, its pretty obvious, it deletes a card, duh
    var cards = datab.getCollection("cards");
    cards.removeWhere({'tagLine': {'$eq': cardName}})
  }

function getCard(datab, searchTerm){
  //ok, so this should be used to get cards from anything, but as you can see, its not, so maybe we'll integrate that to make it better
    var cards = datab.getCollection("cards");
    var cardNames = cards.find({'tagLine': {'$contains': searchTerm}});
    return cardNames;
  }

function searchSimple(datab, searchTerm){
  /*Okie dokie kids, this should work, I'm fairly confident, but if it doesnt, Uncle Pranav
   has a long day ahead of him or maybe a short day depending on what he wants to do with it idk*/
    var cards = datab.getCollection("cards");
    var returnListCards = []
    var cardTags = cards.find({'sTags': {'$contains': searchTerm}})
    var cardNames = cards.find({'tagLine': {'$contains': searchTerm}})
    var temp1 = 0;
    var temp2 = 0;

    if(cardTags != []){
      for (temp1 in cardTags){
        returnListCards.push(cardTags[temp1].name)
      }
    }

    if(cardNames != []){
      for (temp2 in cardNames){
        returnListCards.push(cardNames[temp2].name)
      }
    }
    return uniq(returnListCards)
  }

/* The rest of this is IPC stuff */

  ipcMain.on('Search', function (event, arg) {
    console.log(arg)
    console.log("-----------")
    console.log(searchSimple(cardDb, arg))
    event.returnValue = searchSimple(cardDb, arg)
  })

  ipcMain.on('FileOpen', function (event, arg) {
    var foundCard = getCard(cardDb, arg)
    if(foundCard[0]){
      console.log('opening: ' + foundCard[0])
      event.returnValue = foundCard[0]
    } else {
      event.returnValue = false
    }
  })

  ipcMain.on('FileRemove', function (event, arg) {

    //removeCard(db, cardName, cardTags, cardContent)
    deleteCard(cardDb, arg)
    console.log("removing:")
    console.log(arg)
    console.log("---------------")
    //removeCard(cardDb, arg[0], arg[1], arg[2])
  })

  ipcMain.on('CardManager', function (event, arg) {
    var dataJSON = tagindex(cardDb)
    event.returnValue = dataJSON
  })

  /* card saving */
  ipcMain.on('FileSave', function (event, arg) {
    console.log(arg)
    // [TitleString, TagString, ContentString]
    var cards = cardDb.getCollection("cards");
    var tagLine = arg.tagLine
    var sTags = arg.sTags
    var content = arg.content
    var notes = arg.notes
    var cite = arg.citation
    var temp = cards.find({'tagLine' : tagLine})
    if (temp.length !== 0){
      cards.removeWhere({'tagLine' : TitleString})
    }
    addCardToLoki(cardDb, tagLine, sTags, cite, content, notes);
    tagindex(cardDb)
  })
})
<|endoftext|>


<commit_before>
var irc = require('irc');
var mongojs = require('mongojs');

var client = new irc.Client('irc.freenode.net', 'irclogs', {
	channels: ['#laravel'],
});

var logs = mongojs('irclogs').collection('logs');

client.addListener('message', function (nick, to, text, message) {
	console.log(nick + ' => ' + to + ': ' + text);
	logs.save({type: 'message', nick: nick, text: text}, {w: 0});
});

client.addListener('join', function (channel, nick, message) {
	console.log('JOIN', channel, nick, message);
	logs.save({type: 'join', nick: nick}, {w: 0});
});

client.addListener('part', function (channel, nick, reason, message) {
	console.log('PART', channel, nick, reason, message);
	logs.save({type: 'part', nick: nick, reason: reason}, {w: 0});
});

client.addListener('quit', function (nick, reason, channels, message) {
	console.log('QUIT', nick, reason, channels, message);
	logs.save({type: 'quit', nick: nick, reason: reason}, {w: 0});
});

////////////////////////////////////////////////////////////////////
/////////////////////////// ERROR HANDLING /////////////////////////
////////////////////////////////////////////////////////////////////

client.addListener('error', function(message) {
	console.log('error: ', message);
});

<commit_msg>Refactoring<commit_after>
var irc = require('irc');
var mongojs = require('mongojs');

var client = new irc.Client('irc.freenode.net', 'irclogs', {
	channels: ['#laravel'],
});

var logs = mongojs('irclogs').collection('logs');

var logSave = function(hash) {
	console.log(hash);
	hash.time = new IsoDate;
	logs.save(hash, {w: 0});
}

client.addListener('message', function (nick, to, text, message) {
	logSave({type: 'message', nick: nick, text: text});
});

client.addListener('join', function (channel, nick, message) {
	logSave({type: 'join', nick: nick});
});

client.addListener('part', function (channel, nick, reason, message) {
	logSave({type: 'part', nick: nick, reason: reason});
});

client.addListener('quit', function (nick, reason, channels, message) {
	logSave({type: 'quit', nick: nick, reason: reason});
});

////////////////////////////////////////////////////////////////////
/////////////////////////// ERROR HANDLING /////////////////////////
////////////////////////////////////////////////////////////////////

client.addListener('error', function(message) {
	console.log('error: ', message);
});

<|endoftext|>