<commit_before>// View model for the projects page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjecttypeTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjecttypeTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeManual");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.currentCourseId = null;

    /*
     * Update the location dropdown list
     */
    gvm.updateLocations = function() {
        $.getJSON('/api/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: "/api/project/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
        url: "/api/project",
        type: "POST",
        data: serialData,
        success: function(data) {
            viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(gvm.currentCourseId, 1); //TODO now it is refreshing table after updating but it redirects to pagenr 1
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewProjectTypeTitle"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \
        </form>');

    addGeneralModalButton(i18n.__("AddBtn"), function(){
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function initPage() {
    viewModel.updateLocations();

    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });
}<commit_msg>courses page and project page merged<commit_after>// View model for the projects page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjecttypeTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjecttypeTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeManual");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.currentCourseId = null;

    /*
     * Update the location dropdown list
     */
    gvm.updateLocations = function() {
        $.getJSON('/api/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: "/api/project/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
        url: "/api/project",
        type: "POST",
        data: serialData,
        success: function(data) {
            viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(viewModel.currentCourseId, 1); //TODO now it is refreshing table after updating but it redirects to pagenr 1
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewProjectTypeTitle"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \
        </form>');

    addGeneralModalButton(i18n.__("AddBtn"), function(){
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function initPage() {
    viewModel.updateLocations();

    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });
}<|endoftext|>


<commit_before>
var http = require('http');
var path = require('path');

var async = require('async');

var express = require('express');
var getRawBody = require('raw-body');

var Configuration = require("./configuration.js");
var WebSocketEvents = require("./lib/websockets.js");

var config = new Configuration();

var wsserver = new WebSocketEvents(config.WebSocket);

var logger=console;

var router = express();
var server = http.createServer(router);
var auth_token=config.Web.auth_token;

/*
router.use(function (req, res, next) {
  getRawBody(req, { limit: config.Web.requestLimit, encoding: config.Web.encoding},
  function (err, string) {
    if (err) return next(err)
    req.text = string
    logger.log("data="+string)
    next()
  })
});
*/

router.post('/data/:id',function(req,res) {
   var id=req.params.id;
   var body='';
   req.on('data',function(chunk) {
       body+=chunk;
       if(body.length>config.Web.requestLimit) req.connection.destroy();
   });
   req.on('end',function() {
        //var body=req.text;
        logger.log("id:"+id+",post:"+body);
        bodyjson=null;
        try {
           var bodyjson=JSON.parse(body);
           if(bodyjson.auth_token==null) {
               res.statusCode=401;
               return res.end("No auth token");
           }
           if(bodyjson.auth_token!=auth_token) {
               res.statusCode=401;
               return res.end("Invalid token");
           }
           delete bodyjson.auth_token;
        } catch(err) {
           res.statusCode = 400;
           return res.end('error: ' + err.toString());
        }
           wsserver.send_event(id,bodyjson);
           res.statusCode=204;
           res.end();
   });

});

server.listen(config.Web.port,config.Web.hostname);<commit_msg>commented raw-body in the server.js<commit_after>
var http = require('http');
var path = require('path');

var async = require('async');

var express = require('express');
//var getRawBody = require('raw-body');

var Configuration = require("./configuration.js");
var WebSocketEvents = require("./lib/websockets.js");

var config = new Configuration();

var wsserver = new WebSocketEvents(config.WebSocket);

var logger=console;

var router = express();
var server = http.createServer(router);
var auth_token=config.Web.auth_token;

/*
router.use(function (req, res, next) {
  getRawBody(req, { limit: config.Web.requestLimit, encoding: config.Web.encoding},
  function (err, string) {
    if (err) return next(err)
    req.text = string
    logger.log("data="+string)
    next()
  })
});
*/

router.post('/data/:id',function(req,res) {
   var id=req.params.id;
   var body='';
   req.on('data',function(chunk) {
       body+=chunk;
       if(body.length>config.Web.requestLimit) req.connection.destroy();
   });
   req.on('end',function() {
        //var body=req.text;
        logger.log("id:"+id+",post:"+body);
        bodyjson=null;
        try {
           var bodyjson=JSON.parse(body);
           if(bodyjson.auth_token==null) {
               res.statusCode=401;
               return res.end("No auth token");
           }
           if(bodyjson.auth_token!=auth_token) {
               res.statusCode=401;
               return res.end("Invalid token");
           }
           delete bodyjson.auth_token;
        } catch(err) {
           res.statusCode = 400;
           return res.end('error: ' + err.toString());
        }
           wsserver.send_event(id,bodyjson);
           res.statusCode=204;
           res.end();
   });

});

server.listen(config.Web.port,config.Web.hostname);<|endoftext|>


<commit_before>const Discordie = require('discordie')
const UserVoice = require('uservoice-nodejs')
const Events = Discordie.Events
const Config = require('./config.js')
const Commands = require('./Utils/command_engine').Commands
const AccessChecker = require('./Utils/access_checker')
const ErrorLog = require('./Utils/error_loggers')
const GenericLog = require('./Utils/generic_logger')
const bot = new Discordie({
  autoReconnect: true
})

var bugsnag = require('bugsnag')
bugsnag.register(Config.discord.bugsnag)

const UVRegex = /http[s]?:\/\/[\w.]*\/forums\/([0-9]{6,})-[\w-]+\/suggestions\/([0-9]{8,})-[\w-]*/

var uvClient = {
  v1: new UserVoice.Client({
    subdomain: Config.uservoice.subdomain.trim(),
    domain: Config.uservoice.domain.trim(),
    apiKey: Config.uservoice.key.trim(),
    apiSecret: Config.uservoice.secret.trim()
  }),
  v2: new UserVoice.ClientV2({
    clientId: Config.uservoice.key.trim(),
    subdomain: Config.uservoice.domain.trim()
  })
}

bot.Dispatcher.on(Events.MESSAGE_CREATE, (c) => {
  if (c.message.channel.id !== Config.discord.feedChannel && c.message.content.match(UVRegex) !== null && c.message.content.indexOf(Config.discord.prefix) !== 0) {
    let parts = c.message.content.match(UVRegex)
    Commands['chatVoteInit'].fn(c.message, parts[2], uvClient)
  }
  if (c.message.channel.id === Config.discord.feedChannel && c.message.author.id !== bot.User.id && c.message.author.bot) {
    Commands['newCardInit'].fn(c.message)
    return
  }
  if (c.message.isPrivate === true) return
  if (c.message.content.indexOf(Config.discord.prefix) === 0) {
    var cmd = c.message.content.substr(Config.discord.prefix.length).split(' ')[0].toLowerCase()
    var suffix
    suffix = c.message.content.substr(Config.discord.prefix.length).split(' ')
    suffix = suffix.slice(1, suffix.length).join(' ')
    var msg = c.message
    if (Commands[cmd]) {
      if (Commands[cmd].internal === true) return
      AccessChecker.getLevel(msg.member, (level) => {
        if (level === 0 && Commands[cmd].modOnly === true) {
          if (Commands[cmd].phantom !== undefined) msg.reply('this command is restricted, and not available to you.')
          return
        } else if (level !== 2 && Commands[cmd].adminOnly === true) return
        try {
          Commands[cmd].fn(bot, msg, suffix, uvClient, function (res) {
            GenericLog.log(bot, c.message.author, {
              message: `Ran the command \`${cmd}\``,
              result: res.result,
              affected: res.affected
            })
          })
        } catch (e) {
          ErrorLog.log(bot, {
            cause: cmd,
            message: e.message
          })
          msg.reply('an error occurred while processing this command, the admins have been alerted, please try again later')
        }
      })
    }
  }
})

bot.Dispatcher.on(Events.MESSAGE_REACTION_ADD, (m) => {
  if (m.user.id !== bot.User.id) {
    bot.Channels.get(Config.discord.feedChannel).fetchMessages().then(() => {
      Commands['registerVote'].fn(m.message, m.emoji, bot, uvClient, m.user)
    })
  }
})

bot.Dispatcher.on(Events.GATEWAY_READY, () => {
  setInterval(() => {
    bot.Users.fetchMembers() // Hacky way to cache offline users, #blamelazyloading
  }, 600000)
  console.log('Feedback bot is ready!')
})

process.on('unhandledRejection', (reason, p) => {
  if (p !== null && reason !== null) {
    bugsnag.notify(new Error(`Unhandled promise: ${require('util').inspect(p, {depth: 3})}: ${reason}`))
  }
})

bot.Dispatcher.on(Events.DISCONNECTED, (e) => {
  console.error('Connection to Discord has been lost... Delay till reconnect:', e.delay)
})

bot.Dispatcher.on(Events.GATEWAY_RESUMED, () => {
  console.log('Reconnected.')
})

bot.connect({
  token: Config.discord.token
})
<commit_msg>Auto-fetch messages when vote regsitering is bound to fail<commit_after>const Discordie = require('discordie')
const UserVoice = require('uservoice-nodejs')
const Events = Discordie.Events
const Config = require('./config.js')
const Commands = require('./Utils/command_engine').Commands
const AccessChecker = require('./Utils/access_checker')
const ErrorLog = require('./Utils/error_loggers')
const GenericLog = require('./Utils/generic_logger')
const bot = new Discordie({
  autoReconnect: true
})

var bugsnag = require('bugsnag')
bugsnag.register(Config.discord.bugsnag)

const UVRegex = /http[s]?:\/\/[\w.]*\/forums\/([0-9]{6,})-[\w-]+\/suggestions\/([0-9]{8,})-[\w-]*/

var uvClient = {
  v1: new UserVoice.Client({
    subdomain: Config.uservoice.subdomain.trim(),
    domain: Config.uservoice.domain.trim(),
    apiKey: Config.uservoice.key.trim(),
    apiSecret: Config.uservoice.secret.trim()
  }),
  v2: new UserVoice.ClientV2({
    clientId: Config.uservoice.key.trim(),
    subdomain: Config.uservoice.domain.trim()
  })
}

bot.Dispatcher.on(Events.MESSAGE_CREATE, (c) => {
  if (c.message.channel.id !== Config.discord.feedChannel && c.message.content.match(UVRegex) !== null && c.message.content.indexOf(Config.discord.prefix) !== 0) {
    let parts = c.message.content.match(UVRegex)
    Commands['chatVoteInit'].fn(c.message, parts[2], uvClient)
  }
  if (c.message.channel.id === Config.discord.feedChannel && c.message.author.id !== bot.User.id && c.message.author.bot) {
    Commands['newCardInit'].fn(c.message)
    return
  }
  if (c.message.isPrivate === true) return
  if (c.message.content.indexOf(Config.discord.prefix) === 0) {
    var cmd = c.message.content.substr(Config.discord.prefix.length).split(' ')[0].toLowerCase()
    var suffix
    suffix = c.message.content.substr(Config.discord.prefix.length).split(' ')
    suffix = suffix.slice(1, suffix.length).join(' ')
    var msg = c.message
    if (Commands[cmd]) {
      if (Commands[cmd].internal === true) return
      AccessChecker.getLevel(msg.member, (level) => {
        if (level === 0 && Commands[cmd].modOnly === true) {
          if (Commands[cmd].phantom !== undefined) msg.reply('this command is restricted, and not available to you.')
          return
        } else if (level !== 2 && Commands[cmd].adminOnly === true) return
        try {
          Commands[cmd].fn(bot, msg, suffix, uvClient, function (res) {
            GenericLog.log(bot, c.message.author, {
              message: `Ran the command \`${cmd}\``,
              result: res.result,
              affected: res.affected
            })
          })
        } catch (e) {
          ErrorLog.log(bot, {
            cause: cmd,
            message: e.message
          })
          msg.reply('an error occurred while processing this command, the admins have been alerted, please try again later')
        }
      })
    }
  }
})

bot.Dispatcher.on(Events.MESSAGE_REACTION_ADD, (m) => {
  if (m.user.id !== bot.User.id) {
    if (m.message === null) {
      bot.Channels.get(m.data.channel_id).fetchMessages().then(() => {
        m.message = bot.Messages.get(m.data.message_id)
      })
    }
    Commands['registerVote'].fn(m.message, m.emoji, bot, uvClient, m.user)
  }
})

bot.Dispatcher.on(Events.GATEWAY_READY, () => {
  setInterval(() => {
    bot.Users.fetchMembers() // Hacky way to cache offline users, #blamelazyloading
  }, 600000)
  console.log('Feedback bot is ready!')
})

process.on('unhandledRejection', (reason, p) => {
  if (p !== null && reason !== null) {
    bugsnag.notify(new Error(`Unhandled promise: ${require('util').inspect(p, {depth: 3})}: ${reason}`))
  }
})

bot.Dispatcher.on(Events.DISCONNECTED, (e) => {
  console.error('Connection to Discord has been lost... Delay till reconnect:', e.delay)
})

bot.Dispatcher.on(Events.GATEWAY_RESUMED, () => {
  console.log('Reconnected.')
})

bot.connect({
  token: Config.discord.token
})
<|endoftext|>


<commit_before>var request = require('request');
var cheerio = require('cheerio');
var path = require('path');
var config = require('../config');

var Item = require('../models/item').Item;
var ItemTypes = require('../models/item').ItemTypes;
var ItemStates = require('../models/item').ItemStates;

var notifier;

var transmissionSessionId;
var torrentAddTries = 5;

function findTorrent(item) {
	console.log("Searching for " + item.name);

	var query = encodeURIComponent(item.name);
	var url = config.torrentSearchUrl.replace('${query}', query);

	request(url, function(err, resp, body) {
		console.log(url + " done");

		if (err) {
			console.log(err);
			//TODO done(err);
			item.state = ItemStates.wanted;
			item.planNextCheck(config.defaultInterval);
			item.save(function(err) {
				if (err)
					console.log(err);
			});
			return;
		}

		$ = cheerio.load(body);
		fetchBestMovieResult(item, $(".detName"));
	});
}

function checkFinished(item) {
	var rpc = {};
	rpc.arguments = {};
	rpc.method = 'torrent-get';
	rpc.arguments.ids = [ item.torrentHash ];
	rpc.arguments.fields = [ 'isFinished', 'downloadDir', 'files', 'name' ];

	var options = {
		url : 'http://localhost:9091/transmission/rpc',
		method : 'POST',
		json : rpc,
		headers : {
			'X-Transmission-Session-Id' : transmissionSessionId
		}
	};

	console.log(options.url);

	request(options, function(error, response, body) {
		console.log(options.url + " done");

		if (error) {
			console.log(error);
			item.planNextCheck(config.defaultInterval);
			item.save(function(err) {});
			return;
		}

		if (response.statusCode == 409) {
			transmissionSessionId = response.headers['x-transmission-session-id'];
			tryAgainOrFail(function() { checkFinished(item); }, "Too many tries, getting 409, giving up.");
			return;
		}

		console.log(body);

		if (body.result !== 'success') {

			console.log('Not success. What do?'); //TODO
			item.planNextCheck(config.defaultInterval);

		} else {

			if (body.arguments.torrents.length == 0) {

				console.log('Torrent removed.');
				item.state = ItemStates.wanted;
				item.planNextCheck(config.defaultInterval);

			} else if (body.arguments.torrents[0].isFinished) {

				var torrentInfo = body.arguments.torrents[0];
				var filesInfo = torrentInfo.files;

				var maxLength = 0;
				var maxFileInfo;

				for (var index in filesInfo) {
					var fileInfo = filesInfo[index];
					if (fileInfo.length > maxLength) {
						maxLength = fileInfo.length;
						maxFileInfo = fileInfo;
					}
				}

				console.log(torrentInfo);

				var fileDir = path.dirname(maxFileInfo.name);
				var fileName = path.basename(maxFileInfo.name);

				item.downloadDir = path.join(torrentInfo.downloadDir, fileDir);
				//TODO item.mainFile = fileName;

				item.state = ItemStates.downloaded;
				item.planNextCheck(1); /// So that rename goes right on.

				if (notifier)
					notifier.notifyDownloaded(item);

			} else {

				console.log(body.arguments.torrents[0].isFinished);
				item.planNextCheck(config.defaultInterval);

			}

		}

		console.log('Check finished for item ' + item.name + ', state: ' + item.state);

		item.save(function(err) {
			if (err)
				console.log(err);
		});
	});
}

function fetchBestMovieResult(item, $rootElements) {
	if ($rootElements.length == 0) {
		console.log("No result for " + item.name + ", rescheduling (1 day)."); //TODO should be like 1 day or what.
		item.planNextCheck(24*3600);
		item.save(function(err) {}); //TODO err
		return;
	}

	doNext(item, $rootElements, 0);
}

function doNext(item, rootElements, index) {
	var rootElement = rootElements[index];
	var $descElement = $(rootElement).siblings('font');
	var desc = $descElement.text();

	console.log(desc);

	var sizeMatches = desc.match(/([0-9]+[.]?[0-9]*)\s+(MiB|GiB)/);
	console.log(sizeMatches);

	var size = parseFloat(sizeMatches[1]);

	if (sizeMatches[2] === 'GiB')
		size = size * 1000;

	console.log(size);
	console.log(config.movieSizeLimit);

	if (size > config.movieSizeLimit) {
		console.log('Reached size limit'); //TODO better log
		doNext(item, rootElements, index + 1);
		return;
	}

	var url = 'http://thepiratebay.se' + $(rootElement).children('.detLink').attr('href');
	console.log(url);

	request(url, function(error, response, body) {
		console.log(url + " done");

		if (error) {
			console.log(error);
			return;
		}

		$ = cheerio.load(body);
		var nfo = $('.nfo').text();
		var comments = $('#comments').text().toLowerCase();

		var isGoodKeywords = true;

		for (var index in config.movieRequiredKeywords) {
			isGoodKeywords = nfo.indexOf(config.movieRequiredKeywords[index]) >= 0;
			if (isGoodKeywords)
				break;
		}
		var isNotShit = comments.indexOf('shit') < 0 && comments.indexOf('crap') < 0 && comments.indexOf('hardcoded') < 0  && comments.indexOf('hard coded') < 0;

		if (isGoodKeywords && isNotShit) {
			addTorrent(item, $(rootElement).next().attr('href'));
		} else {
			if (index < rootElements.length) {
				doNext(item, rootElements, index + 1);
			}
		}
	});
}

function addTorrent(item, magnetLink) {
	var rpc = {};
	rpc.arguments = {};
	rpc.method = 'torrent-add';
	rpc.arguments.filename = magnetLink;

	var options = {
		url : 'http://localhost:9091/transmission/rpc',
		method : 'POST',
		json : rpc,
		headers : {
			'X-Transmission-Session-Id' : transmissionSessionId
		}
	};

	console.log(options.url);

	request(options, function(error, response, body) {
		console.log(options.url + " done");

		if (error) {
			console.log(error);
			tryAgainOrFail(function() { addTorrent(item, magnetLink); }, "Too many tries, getting error, giving up.");
			return;
		}

		if (response.statusCode == 409) {
			transmissionSessionId = response.headers['x-transmission-session-id'];
			tryAgainOrFail(function() { addTorrent(item, magnetLink); }, "Too many tries, getting 409, giving up.");
			return;
		}

		console.log(body);

		item.planNextCheck(config.defaultInterval);

		if (body.result === 'success') {
			item.state = ItemStates.snatched;
			item.torrentHash = body.arguments['torrent-added'].hashString;

			if (notifier)
				notifier.notifySnatched(item);

			console.log('Success. Torrent hash ' + item.torrentHash + '.');
		} else {
			console.log('No success. Sorry. Transmission down or what?');
		}

		item.save(function(err) {
			if (err)
				console.log(err);
		});
	});
}

function tryAgainOrFail(doWhat, message) {
	torrentAddTries--;

	if (torrentAddTries >= 0) {
		doWhat();
	} else {
		console.log(message);
		return;
	}
}

function setNotifier(notifierToSet) {
	notifier = notifierToSet;
}

module.exports.findTorrent = findTorrent;
module.exports.checkFinished = checkFinished;
module.exports.setNotifier = setNotifier;<commit_msg>Added some logging.<commit_after>var request = require('request');
var cheerio = require('cheerio');
var path = require('path');
var config = require('../config');

var Item = require('../models/item').Item;
var ItemTypes = require('../models/item').ItemTypes;
var ItemStates = require('../models/item').ItemStates;

var notifier;

var transmissionSessionId;
var torrentAddTries = 5;

function findTorrent(item) {
	console.log("Searching for " + item.name);

	var query = encodeURIComponent(item.name);
	var url = config.torrentSearchUrl.replace('${query}', query);

	request(url, function(err, resp, body) {
		console.log(url + " done");

		if (err) {
			console.log(err);
			//TODO done(err);
			item.state = ItemStates.wanted;
			item.planNextCheck(config.defaultInterval);
			item.save(function(err) {
				if (err)
					console.log(err);
			});
			return;
		}

		$ = cheerio.load(body);
		fetchBestMovieResult(item, $(".detName"));
	});
}

function checkFinished(item) {
	var rpc = {};
	rpc.arguments = {};
	rpc.method = 'torrent-get';
	rpc.arguments.ids = [ item.torrentHash ];
	rpc.arguments.fields = [ 'isFinished', 'downloadDir', 'files', 'name' ];

	var options = {
		url : 'http://localhost:9091/transmission/rpc',
		method : 'POST',
		json : rpc,
		headers : {
			'X-Transmission-Session-Id' : transmissionSessionId
		}
	};

	console.log(options.url);

	request(options, function(error, response, body) {
		console.log(options.url + " done");

		if (error) {
			console.log(error);
			item.planNextCheck(config.defaultInterval);
			item.save(function(err) {});
			return;
		}

		if (response.statusCode == 409) {
			transmissionSessionId = response.headers['x-transmission-session-id'];
			tryAgainOrFail(function() { checkFinished(item); }, "Too many tries, getting 409, giving up.");
			return;
		}

		console.log(body);

		if (body.result !== 'success') {

			console.log('Not success. What do?'); //TODO
			item.planNextCheck(config.defaultInterval);

		} else {

			if (body.arguments.torrents.length == 0) {

				console.log('Torrent removed.');
				item.state = ItemStates.wanted;
				item.planNextCheck(config.defaultInterval);

			} else if (body.arguments.torrents[0].isFinished) {

				var torrentInfo = body.arguments.torrents[0];
				var filesInfo = torrentInfo.files;

				var maxLength = 0;
				var maxFileInfo;

				for (var index in filesInfo) {
					var fileInfo = filesInfo[index];
					if (fileInfo.length > maxLength) {
						maxLength = fileInfo.length;
						maxFileInfo = fileInfo;
					}
				}

				console.log(torrentInfo);

				var fileDir = path.dirname(maxFileInfo.name);
				var fileName = path.basename(maxFileInfo.name);

				item.downloadDir = path.join(torrentInfo.downloadDir, fileDir);
				//TODO item.mainFile = fileName;

				item.state = ItemStates.downloaded;
				item.planNextCheck(1); /// So that rename goes right on.

				if (notifier)
					notifier.notifyDownloaded(item);

			} else {

				console.log(body.arguments.torrents[0].isFinished);
				item.planNextCheck(config.defaultInterval);

			}

		}

		console.log('Check finished for item ' + item.name + ', state: ' + item.state);

		item.save(function(err) {
			if (err)
				console.log(err);
		});
	});
}

function fetchBestMovieResult(item, $rootElements) {
	if ($rootElements.length == 0) {
		console.log("No result for " + item.name + ", rescheduling (1 day)."); //TODO should be like 1 day or what.
		item.planNextCheck(24*3600);
		item.save(function(err) {}); //TODO err
		return;
	}

	doNext(item, $rootElements, 0);
}

function doNext(item, rootElements, index) {
	var rootElement = rootElements[index];

	//TODO remove
	console.log('**** START ****');
	console.log($(rootElement).html());
	console.log('**** END ****');

	var $descElement = $(rootElement).siblings('font');
	var desc = $descElement.text();

	console.log(desc);

	var sizeMatches = desc.match(/([0-9]+[.]?[0-9]*)\s+(MiB|GiB)/);
	console.log(sizeMatches);

	var size = parseFloat(sizeMatches[1]);

	if (sizeMatches[2] === 'GiB')
		size = size * 1000;

	console.log(size);
	console.log(config.movieSizeLimit);

	if (size > config.movieSizeLimit) {
		console.log('Reached size limit'); //TODO better log
		doNext(item, rootElements, index + 1);
		return;
	}

	var url = 'http://thepiratebay.se' + $(rootElement).children('.detLink').attr('href');
	console.log(url);

	request(url, function(error, response, body) {
		console.log(url + " done");

		if (error) {
			console.log(error);
			return;
		}

		$ = cheerio.load(body);
		var nfo = $('.nfo').text();
		var comments = $('#comments').text().toLowerCase();

		var isGoodKeywords = true;

		for (var index in config.movieRequiredKeywords) {
			isGoodKeywords = nfo.indexOf(config.movieRequiredKeywords[index]) >= 0;
			if (isGoodKeywords)
				break;
		}
		var isNotShit = comments.indexOf('shit') < 0 && comments.indexOf('crap') < 0 && comments.indexOf('hardcoded') < 0  && comments.indexOf('hard coded') < 0;

		if (isGoodKeywords && isNotShit) {
			addTorrent(item, $(rootElement).next().attr('href'));
		} else {
			if (index < rootElements.length) {
				doNext(item, rootElements, index + 1);
			}
		}
	});
}

function addTorrent(item, magnetLink) {
	var rpc = {};
	rpc.arguments = {};
	rpc.method = 'torrent-add';
	rpc.arguments.filename = magnetLink;

	var options = {
		url : 'http://localhost:9091/transmission/rpc',
		method : 'POST',
		json : rpc,
		headers : {
			'X-Transmission-Session-Id' : transmissionSessionId
		}
	};

	console.log(options.url);

	request(options, function(error, response, body) {
		console.log(options.url + " done");

		if (error) {
			console.log(error);
			tryAgainOrFail(function() { addTorrent(item, magnetLink); }, "Too many tries, getting error, giving up.");
			return;
		}

		if (response.statusCode == 409) {
			transmissionSessionId = response.headers['x-transmission-session-id'];
			tryAgainOrFail(function() { addTorrent(item, magnetLink); }, "Too many tries, getting 409, giving up.");
			return;
		}

		console.log(body);

		item.planNextCheck(config.defaultInterval);

		if (body.result === 'success') {
			item.state = ItemStates.snatched;
			item.torrentHash = body.arguments['torrent-added'].hashString;

			if (notifier)
				notifier.notifySnatched(item);

			console.log('Success. Torrent hash ' + item.torrentHash + '.');
		} else {
			console.log('No success. Sorry. Transmission down or what?');
		}

		item.save(function(err) {
			if (err)
				console.log(err);
		});
	});
}

function tryAgainOrFail(doWhat, message) {
	torrentAddTries--;

	if (torrentAddTries >= 0) {
		doWhat();
	} else {
		console.log(message);
		return;
	}
}

function setNotifier(notifierToSet) {
	notifier = notifierToSet;
}

module.exports.findTorrent = findTorrent;
module.exports.checkFinished = checkFinished;
module.exports.setNotifier = setNotifier;<|endoftext|>


<commit_before>/**
*
* FunctionForm
*
*/

import React from 'react';
// import styled from 'styled-components';

import AceEditor from 'react-ace';
import 'brace/mode/java';
import 'brace/mode/php';
import 'brace/mode/javascript';
import 'brace/theme/github';

class FunctionTabForm extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    const { onChange, environments, item } = this.props;
    return (
      <form>

              Function name
              <input type="text" className="form-control" id="formFunctionName" name="name" value={item.name} onChange={onChange} />

              Environment
              <select className="form-control" defaultValue={item.environment}>
                {
                  environments.map((environment, index) => (
                    <option value={environment.name} key={`environmentSelect-${index}`}>{environment.name}</option>
                  ))
                }
              </select>

            <AceEditor
              mode="javascript"
              theme="github"
              name="FunctionForm"
              defaultValue={item.code}
              editorProps={{ $blockScrolling: true }}
            />

            Syntax
            <select className="form-control">
              <option value="javascript">Javascript</option>
              <option value="java">Java</option>
              <option value="php">Php</option>
            </select>
            Test code { ' ' }

              TODO Test code result

      </form>
    );
  }
}

FunctionTabForm.propTypes = {
  item: React.PropTypes.object,
  environments: React.PropTypes.array,
  onChange: React.PropTypes.func.isRequired,
};

export default FunctionTabForm;
<commit_msg>Fix editor to hold the updated code<commit_after>/**
*
* FunctionForm
*
*/

import React from 'react';
// import styled from 'styled-components';

import AceEditor from 'react-ace';
import 'brace/mode/java';
import 'brace/mode/php';
import 'brace/mode/javascript';
import 'brace/mode/python';
import 'brace/theme/github';

class FunctionTabForm extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);

    this.state = {
      mode: 'javascript',
    };

    this.onCodeChange = this.onCodeChange.bind(this);
    this.onModeChange = this.onModeChange.bind(this);
  }

  onCodeChange(newValue) {
    const { item } = this.props;
    item.code = newValue;
  }

  onModeChange(e) {
    this.state.mode = e.target.value;
    this.forceUpdate();
  }

  render() {
    const { onChange, environments, item } = this.props;
    const { mode } = this.state;
    return (
      <form>

              Function name
              <input type="text" className="form-control" id="formFunctionName" name="name" value={item.name} onChange={onChange} />

              Environment
              <select className="form-control" defaultValue={item.environment}>
                {
                  environments.map((environment, index) => (
                    <option value={environment.name} key={`environmentSelect-${index}`}>{environment.name}</option>
                  ))
                }
              </select>

            <AceEditor
              mode={mode}
              theme="github"
              name="FunctionForm"
              value={item.code}
              editorProps={{ $blockScrolling: true }}
              onChange={this.onCodeChange}
            />

            Syntax
            <select className="form-control" onChange={this.onModeChange}>
              <option value="javascript">Javascript</option>
              <option value="java">Java</option>
              <option value="php">Php</option>
              <option value="python">Python</option>
            </select>
            Test code { ' ' }

              TODO Test code result

      </form>
    );
  }
}

FunctionTabForm.propTypes = {
  item: React.PropTypes.object,
  environments: React.PropTypes.array,
  onChange: React.PropTypes.func.isRequired,
};

export default FunctionTabForm;
<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });
    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name)
    ];

    //var layer = L.layerGroup(markers).addTo(map);
    //
    // var myZoom = {
    //  start:  map.getZoom(),
    //  end: map.getZoom()
    //};

    var layerx = L.conditionalMarkers(markers, {maxMarkers: 2}).addTo(map);
    var layer = L.layerGroup(layerx).addTo(map);
    //map.on('zoomend', function(e) {
    //    myZoom.end = map.getZoom();
    //    if (myZoom.end <= 10){
    //        layer.eachLayer(function (marker) {
    //            marker.hideLabel();
    //        });
    //    }
    //    if (myZoom.end > 10){
    //        layer.eachLayer(function (marker) {
    //            marker.showLabel();
    //        });
    //    }
    //});

    this.makerpoint_creadas.push(layer);
    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      //var bounds = new L.LatLngBounds([]);
      //var bounds = [];
      var boxpolys = new Array(boxes.length);
      /*
      for (var i = 0; i < boxes.length; i++) {
        //bounds.extend(boxes[i]);
        bounds.push(boxes[i]);
      }*/

      route.addTo(this.activeMap);
      //this.activeMap.fitBounds(bounds);
};

<commit_msg>adding compoments<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });
    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name)
    ];

    //var layer = L.layerGroup(markers).addTo(map);
    //
    // var myZoom = {
    //  start:  map.getZoom(),
    //  end: map.getZoom()
    //};

    //var layerx = L.conditionalMarkers(markers, {maxMarkers: 2}).addTo(map);
    var layer = L.layerGroup(markers).addTo(map);
    //map.on('zoomend', function(e) {
    //    myZoom.end = map.getZoom();
    //    if (myZoom.end <= 10){
    //        layer.eachLayer(function (marker) {
    //            marker.hideLabel();
    //        });
    //    }
    //    if (myZoom.end > 10){
    //        layer.eachLayer(function (marker) {
    //            marker.showLabel();
    //        });
    //    }
    //});

    this.makerpoint_creadas.push(layer);
    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      //var bounds = new L.LatLngBounds([]);
      //var bounds = [];
      var boxpolys = new Array(boxes.length);
      /*
      for (var i = 0; i < boxes.length; i++) {
        //bounds.extend(boxes[i]);
        bounds.push(boxes[i]);
      }*/

      route.addTo(this.activeMap);
      //this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>const common = require('../../common/quadrigacx')
const coinUtils = require('../../../coin-utils')

function buy (account, cryptoAtoms, fiatCode, cryptoCode) {
  return trade('buy', account, cryptoAtoms, fiatCode, cryptoCode)
}

function sell (account, cryptoAtoms, fiatCode, cryptoCode) {
  return trade('sell', account, cryptoAtoms, fiatCode, cryptoCode)
}

function trade (type, account, cryptoAtoms, fiatCode, cryptoCode) {
  return Promise.resolve()
  .then(() => {
    const market = common.buildMarket(fiatCode, cryptoCode)
    const options = {
      book: market,
      amount: coinUtils.toUnit(cryptoAtoms, cryptoCode).toFixed(8)
    }

    return common.authRequest(account, '/' + type, options)
  })
}

module.exports = {
  buy,
  sell
}
<commit_msg>Delete quadrigacx.js<commit_after><|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

const colors = require('colors');
const frontmatter = require('frontmatter');
const marked = require('marked');
const hbs = require('handlebars');
const _ = require('lodash');
const recursive = require('recursive-readdir');

const FILE_TEST = '../sq2/sass/ui-components/_tabs.scss';
const DIR_SRC = '../sq2/sass/';
const DIR_TARGET = './'

const TEMPL_EXAMPLE = fs.readFileSync('templates/example.hbs', "utf8");
const TEMPL_DOC = fs.readFileSync('templates/index.hbs', "utf8");

marked.setOptions({
	gfm: true,
	breaks: false,
	tables: true
})

var DocumentView = {};

function addBlock(block) {
	var catKey = _.camelCase(block.category);

	if ( !DocumentView[catKey] ) {
		DocumentView[catKey]  = {
			title: block.category,
			blocks: []
		}
	}

	console.log("Adding component: ".yellow, block.title);
	DocumentView[catKey].blocks.push(block);
}

// returns a new component description string
// with `html_example` code blocks replaced
// inline with rendered/escaped output
function renderHtmlExamples(blockDescription) {
	return new String(
		blockDescription.replace(/```html_example\n(.|\n)*?\n```/g, function(match) {
			var example = _.trim(match.replace(/```html_example/, '').replace(/```/, '')),
				template = hbs.compile(TEMPL_EXAMPLE);

			return template({
				html: example
			});
		})
	);
}

function parseDocComment(comment) {
	var cleanComment = _.trim(comment.replace(/\/\*doc/, '').replace(/\*\//, ''));
		C = frontmatter(cleanComment),
		block = {};

	if ( !C.data ) {
		return;
	}

	block["name"] = C.data.name;
	block["title"] = C.data.title;
	block["category"] = C.data.category;
	block["description"] = marked( renderHtmlExamples(C.content) );

	addBlock(block);
}

function handleFile(file) {
	console.log("\nREADING FILE: ".magenta, file);
	var content = fs.readFileSync(file, "utf8"),
		comments = content.match(/\/\*doc\n(.|\n)*?\n\*\//g);

	if ( comments ) {
		comments.forEach(parseDocComment);
	} else {
		console.warn("No documentation comments found.".italic);
	}
}

recursive(DIR_SRC, [], function(err, files) {
	var template = hbs.compile(TEMPL_DOC);
	files.forEach(handleFile);

	var doc = new Buffer(template({
		categoryObj: DocumentView
	}));

	fs.writeFile(DIR_TARGET+'doc.html', doc, function(err) {
		if(err) {
			return console.log(err);
		}
		console.log('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'.rainbow);
		console.log("BUILD IS SUCCESS OK GOOD JOB NICE".cyan);
		console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'.rainbow);
	});
});
<commit_msg>cleanup<commit_after>const fs = require('fs');
const path = require('path');

const colors = require('colors');
const frontmatter = require('frontmatter');
const marked = require('marked');
const hbs = require('handlebars');
const _ = require('lodash');
const recursive = require('recursive-readdir');

// TODO: read from a config.json to set these
const DIR_SRC = '../sq2/sass/';
const DIR_TARGET = './'

const TEMPL_EXAMPLE = fs.readFileSync('templates/example.hbs', "utf8");
const TEMPL_DOC = fs.readFileSync('templates/index.hbs', "utf8");

marked.setOptions({
	gfm: true,
	breaks: false,
	tables: true
})

var DocumentView = {};

function addBlock(block) {
	var catKey = _.camelCase(block.category);

	if ( !DocumentView[catKey] ) {
		DocumentView[catKey]  = {
			title: block.category,
			blocks: []
		}
	}

	console.log("Adding component: ".yellow, block.title);
	DocumentView[catKey].blocks.push(block);
}

// returns a new component description string
// with `html_example` code blocks replaced
// inline with rendered/escaped output
function renderHtmlExamples(blockDescription) {
	return new String(
		blockDescription.replace(/```html_example\n(.|\n)*?\n```/g, function(match) {
			var example = _.trim(match.replace(/```html_example/, '').replace(/```/, '')),
				template = hbs.compile(TEMPL_EXAMPLE);

			return template({
				html: example
			});
		})
	);
}

function parseDocComment(comment) {
	var cleanComment = _.trim(comment.replace(/\/\*doc/, '').replace(/\*\//, ''));
		C = frontmatter(cleanComment),
		block = {};

	if ( !C.data ) {
		return;
	}

	block["name"] = C.data.name;
	block["title"] = C.data.title;
	block["category"] = C.data.category;
	block["description"] = marked( renderHtmlExamples(C.content) );

	addBlock(block);
}

function handleFile(file) {
	console.log("\nREADING FILE: ".magenta, file);
	var content = fs.readFileSync(file, "utf8"),
		comments = content.match(/\/\*doc\n(.|\n)*?\n\*\//g);

	if ( comments ) {
		comments.forEach(parseDocComment);
	} else {
		console.warn("No documentation comments found.".italic);
	}
}

recursive(DIR_SRC, [], function(err, files) {
	var template = hbs.compile(TEMPL_DOC);
	files.forEach(handleFile);

	var doc = new Buffer(template({
		categoryObj: DocumentView
	}));

	fs.writeFile(DIR_TARGET+'doc.html', doc, function(err) {
		if(err) {
			return console.log(err);
		}
		console.log('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'.rainbow);
		console.log("BUILD IS SUCCESS OK GOOD JOB NICE".cyan);
		console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'.rainbow);
	});
});
<|endoftext|>


<commit_before>'use strict'
// require
const { app, BrowserWindow, protocol, ipcMain } = require('electron')
const path = require('path')
const url = require('url')
const fs = require('fs')

//open server
require('./server/app.js')

// const
const dirname = '__dirname'
const PATH_DATA = JSON.parse(fs.readFileSync('./screen_info.json', 'utf-8'))

// global
let win
let spwin

app.on('ready', () => {
  protocol.interceptFileProtocol('file', (req, callback) => {
    let requrl = req.url.substr(7)

    // ルート以下の1番目を抽出
    if(requrl.split('/')[1] === dirname) {
      // /__dirnameをパース
      requrl = requrl.replace(/\/__dirname/, __dirname)
      // URLパラメータを除去
      requrl = requrl.replace(/\?.*/, '')
    }
    // ノーマライズして返す
    callback(path.normalize(requrl))
  })
})

function createWindow(path){
  win = new BrowserWindow({
    'width': 1200,
    'height': 800,
    'icon': __dirname + '/resource/img/icon@128px.png',
  })

  win.loadURL(url.format({
    pathname: __dirname + path,
    protocol: 'file:',
    slashes: true,
  }))

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

//splash window
function splashWindow(){
  spwin = new BrowserWindow({
    'width': 510,
    'height': 620,
 /* 'transparent': true,
    'frame': false,
    "resizable": false */
  })

  spwin.loadURL(url.format({
    pathname: __dirname + PATH_DATA.splash_path,
    protocol: 'file:',
    slashes: true
  }))

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

app.on('ready', splashWindow)

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

app.on('activate', () => {
  if(win === null){
    createWindow()
  }
})

ipcMain.on(PATH_DATA.event, (event, req) => {
  switch(req){
    case PATH_DATA.edit_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.edit_path,
        protocol: 'file:',
        slashes: true,
      }))
      break
    case PATH_DATA.main_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.main_path,
        protocol: 'file:',
        slashes: true,
      }))
      break
    case PATH_DATA.pdf_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.pdf_path,
        protocol: 'file:',
        slashes: true,
      }))
      break
    case PATH_DATA.settings_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.settings_path,
        protocol: 'file:',
        slashes: true,
    }))
    break
  }
})

ipcMain.on('move_from_splash', (event, path) => {
  switch(path){
    case PATH_DATA.edit_path:
      createWindow(path)
      break
    case PATH_DATA.pdf_path:
      createWindow(path)
      break
  }
})

<commit_msg>fix ,<commit_after>'use strict'
// require
const { app, BrowserWindow, protocol, ipcMain } = require('electron')
const path = require('path')
const url = require('url')
const fs = require('fs')

//open server
require('./server/app.js')

// const
const dirname = '__dirname'
const PATH_DATA = JSON.parse(fs.readFileSync('./screen_info.json', 'utf-8'))

// global
let win
let spwin

app.on('ready', () => {
  protocol.interceptFileProtocol('file', (req, callback) => {
    let requrl = req.url.substr(7)

    // ルート以下の1番目を抽出
    if(requrl.split('/')[1] === dirname) {
      // /__dirnameをパース
      requrl = requrl.replace(/\/__dirname/, __dirname)
      // URLパラメータを除去
      requrl = requrl.replace(/\?.*/, '')
    }
    // ノーマライズして返す
    callback(path.normalize(requrl))
  })
})

function createWindow(path){
  win = new BrowserWindow({
    'width': 1200,
    'height': 800,
    'icon': __dirname + '/resource/img/icon@128px.png'
  })

  win.loadURL(url.format({
    pathname: __dirname + path,
    protocol: 'file:',
    slashes: true
  }))

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

//splash window
function splashWindow(){
  spwin = new BrowserWindow({
    'width': 510,
    'height': 620,
 /* 'transparent': true,
    'frame': false,
    "resizable": false */
  })

  spwin.loadURL(url.format({
    pathname: __dirname + PATH_DATA.splash_path,
    protocol: 'file:',
    slashes: true
  }))

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

app.on('ready', splashWindow)

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

app.on('activate', () => {
  if(win === null){
    createWindow()
  }
})

ipcMain.on(PATH_DATA.event, (event, req) => {
  switch(req){
    case PATH_DATA.edit_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.edit_path,
        protocol: 'file:',
        slashes: true
      }))
      break
    case PATH_DATA.main_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.main_path,
        protocol: 'file:',
        slashes: true
      }))
      break
    case PATH_DATA.pdf_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.pdf_path,
        protocol: 'file:',
        slashes: true
      }))
      break
    case PATH_DATA.settings_path:
      win.loadURL(url.format({
        pathname: __dirname + PATH_DATA.settings_path,
        protocol: 'file:',
        slashes: true
    }))
    break
  }
})

ipcMain.on('move_from_splash', (event, path) => {
  switch(path){
    case PATH_DATA.edit_path:
      createWindow(path)
      break
    case PATH_DATA.pdf_path:
      createWindow(path)
      break
  }
})

<|endoftext|>


<commit_before>function updateSliderMax(max){
    max = max ? Math.round((max/50 + 1)) * 50 : 0;

    $( "#slider-range" ).slider({
        max: max,
        values: [0, max],
    });

    $( "#amount" ).text( "Worldwide Gross: $" + 0 + "m - $" + max + "m" );
};

function filterIfSteady(min, max){
    if (min == $( "#slider-range" ).slider( "values", 0 ) && max == $( "#slider-range" ).slider( "values", 1 ))
        renderSelection();
};

function renderSelection(){
    var stories = [];
    $(".btn.story").each(function(i, e){
        var btn = $(e);
        if(btn.hasClass("btn-primary"))
            stories.push(btn.text().toLowerCase());
    });

    var years = [];
    $(".btn.year").each(function(i, e){
        var btn = $(e);
        if(btn.hasClass("btn-primary"))
            years.push(parseInt(btn.text()));
    });

    var grossRange = [];
    grossRange.push($( "#slider-range" ).slider( "values", 0 ));
    grossRange.push($( "#slider-range" ).slider( "values", 1 ));

    showFiltered(years, stories, grossRange);
}

function addPopovers(stories){
    function content(desc, e1, e2){
        return desc +
            "

" +
            "
" + e1 + "
" +
            "
" + e2 + "
" +
            "
";
    }

    function formatTitle(title, colour){
        return "

" +
            title;
    }

    $('.btn.story').each(function(i, e){
        var btn = $(e);
        var title = btn.text();
        var story = stories[title];
        var colour = story.Colour;
        var description = story.Description;
        var example_one = story.ExampleOne;
        var example_two = story.ExampleTwo;

        btn.popover({
            placement: "bottom",
            delay: {
                show: 300,
                hide: 50
            },
            title: formatTitle(title, colour),
            content: content(description, example_one, example_two),
            animation: false,
            selector: false,
            trigger: 'hover'
        });
    });
}

$(document).ready(function() {

    $( "#slider-range" ).slider({
        animate: true,
        range: true,
        min: 0,
        step: 50,
        max: 2750,
        values: [0, 2750],
        slide: function( event, ui ) {
            $( "#amount" ).text( "Worldwide Gross: $" + ui.values[ 0 ] + "m - $" + ui.values[ 1 ] + "m");

            setTimeout("filterIfSteady(" + ui.values[ 0 ] + "," + ui.values[ 1 ] + ")" , 200);
        },
        stop: function(){
            renderSelection();
        }
    });

    $( "#amount" ).text( "Worldwide Gross: $" + 0 + "m - $" + $( "#slider-range" ).slider( "values", 1 ) + "m" );

    $('.btn.all-years').click(function(e){
        $('.btn.year').each(function(i, e){
                $(e).addClass("btn-primary");
            });
        renderSelection();
    });

    $('.btn.all-stories').click(function(e){
        $('.btn.story').each(function(i, e){
            $(e).addClass("btn-primary");
        });
        renderSelection();
    });

    $('.btn.deselect-all').click(function(e){
        $('.btn.year').each(function(i, e){
            $(e).removeClass("btn-primary");
        });
        $('.btn.story').each(function(i, e){
            $(e).removeClass("btn-primary");
        });
        removeAllFilms();
    });

    $(".btn.year").click(function(e){
        var target = $(e.target);
        target.toggleClass("btn-primary");

        renderSelection();
        if(!target.hasClass("btn-primary"))
            hideAllTooltips();
    });

    $(".btn.story").click(function(e){
        var target = $(e.target);
        target.toggleClass("btn-primary");

        renderSelection();
        if(!target.hasClass("btn-primary"))
            hideAllTooltips();
        else
            highlightStories(target.text());
    });

    $(".btn.story").hover(
        function(e){
            var btn = $(e.target);
            if(btn.hasClass("btn-primary"))
                setTimeout(delayedAction, 0);

            function delayedAction(){
                highlightStories(btn.text())
            }
        },
        function(e){
            unhighlight();
        }
    );

    $(".btn.year").hover(
        function(e){
            var btn = $(e.target);
            if(btn.hasClass("btn-primary"))
                setTimeout(delayedAction, 0);

            function delayedAction(){
                highlightYear(parseInt(btn.text()));
            }
        },
        function(e){
            unhighlight();
        }
    );
});<commit_msg>added hoverover tooltips and highlight graph on stories legend table<commit_after>function updateSliderMax(max){
    max = max ? Math.round((max/50 + 1)) * 50 : 0;

    $( "#slider-range" ).slider({
        max: max,
        values: [0, max],
    });

    $( "#amount" ).text( "Worldwide Gross: $" + 0 + "m - $" + max + "m" );
};

function filterIfSteady(min, max){
    if (min == $( "#slider-range" ).slider( "values", 0 ) && max == $( "#slider-range" ).slider( "values", 1 ))
        renderSelection();
};

function renderSelection(){
    var stories = [];
    $(".btn.story").each(function(i, e){
        var btn = $(e);
        if(btn.hasClass("btn-primary"))
            stories.push(btn.text().toLowerCase());
    });

    var years = [];
    $(".btn.year").each(function(i, e){
        var btn = $(e);
        if(btn.hasClass("btn-primary"))
            years.push(parseInt(btn.text()));
    });

    var grossRange = [];
    grossRange.push($( "#slider-range" ).slider( "values", 0 ));
    grossRange.push($( "#slider-range" ).slider( "values", 1 ));

    showFiltered(years, stories, grossRange);
}

function addPopovers(stories){
    function content(desc, e1, e2){
        return desc +
            "

" +
            "
" + e1 + "
" +
            "
" + e2 + "
" +
            "
";
    }

    function formatTitle(title, colour){
        return "

" +
            title;
    }

    $('.btn.story').each(function(i, e){
        var btn = $(e);
        var title = btn.text();
        var story = stories[title];
        var colour = story.Colour;
        var description = story.Description;
        var example_one = story.ExampleOne;
        var example_two = story.ExampleTwo;

        btn.popover({
            placement: "bottom",
            delay: {
                show: 300,
                hide: 50
            },
            title: formatTitle(title, colour),
            content: content(description, example_one, example_two),
            animation: false,
            selector: false,
            trigger: 'hover'
        });
    });

    $('div.stories-legend table td').each(function(i, e){
        var td = $(e);
        var title = td.text();
        var story = stories[title];
        var colour = story.Colour;
        var description = story.Description;
        var example_one = story.ExampleOne;
        var example_two = story.ExampleTwo;

        td.popover({
            placement: "bottom",
            delay: {
                show: 300,
                hide: 50
            },
            title: formatTitle(title, colour),
            content: content(description, example_one, example_two),
            animation: false,
            selector: false,
            trigger: 'hover'
        });
    });
}

$(document).ready(function() {

    $( "#slider-range" ).slider({
        animate: true,
        range: true,
        min: 0,
        step: 50,
        max: 2750,
        values: [0, 2750],
        slide: function( event, ui ) {
            $( "#amount" ).text( "Worldwide Gross: $" + ui.values[ 0 ] + "m - $" + ui.values[ 1 ] + "m");

            setTimeout("filterIfSteady(" + ui.values[ 0 ] + "," + ui.values[ 1 ] + ")" , 200);
        },
        stop: function(){
            renderSelection();
        }
    });

    $( "#amount" ).text( "Worldwide Gross: $" + 0 + "m - $" + $( "#slider-range" ).slider( "values", 1 ) + "m" );

    $('.btn.all-years').click(function(e){
        $('.btn.year').each(function(i, e){
                $(e).addClass("btn-primary");
            });
        renderSelection();
    });

    $('.btn.all-stories').click(function(e){
        $('.btn.story').each(function(i, e){
            $(e).addClass("btn-primary");
        });
        renderSelection();
    });

    $('.btn.deselect-all').click(function(e){
        $('.btn.year').each(function(i, e){
            $(e).removeClass("btn-primary");
        });
        $('.btn.story').each(function(i, e){
            $(e).removeClass("btn-primary");
        });
        removeAllFilms();
    });

    $(".btn.year").click(function(e){
        var target = $(e.target);
        target.toggleClass("btn-primary");

        renderSelection();
        if(!target.hasClass("btn-primary"))
            hideAllTooltips();
    });

    $(".btn.story").click(function(e){
        var target = $(e.target);
        target.toggleClass("btn-primary");

        renderSelection();
        if(!target.hasClass("btn-primary"))
            hideAllTooltips();
        else
            highlightStories(target.text());
    });

    $(".btn.story").hover(
        function(e){
            var btn = $(e.target);
            if(btn.hasClass("btn-primary"))
                setTimeout(delayedAction, 0);

            function delayedAction(){
                highlightStories(btn.text())
            }
        },
        function(e){
            unhighlight();
        }
    );

    $("div.stories-legend table td").hover(
        function(e){
            var td = $(e.target);
            setTimeout(delayedAction, 0);

            function delayedAction(){
                highlightStories(td.text())
            }
        },
        function(e){
            unhighlight();
        }
    );

    $(".btn.year").hover(
        function(e){
            var btn = $(e.target);
            if(btn.hasClass("btn-primary"))
                setTimeout(delayedAction, 0);

            function delayedAction(){
                highlightYear(parseInt(btn.text()));
            }
        },
        function(e){
            unhighlight();
        }
    );
});<|endoftext|>


<commit_before>var stageController = require('controller.stage');
var rolesController = require('controller.roles');
var economy = require('controller.economy');
var immobileTower = require('immobile.tower');
var immobileLink = require('immobile.link');

var s = require('shared');

const attackersPresent = function attackersPresent(creep) {
  return !creep.my && (creep.getActiveBodyparts(HEAL) > 0 || creep.getActiveBodyparts(ATTACK) > 0);
};

module.exports.loop = function () {
  PathFinder.use(true);
  s.setup();

  if ( Memory.fixedCreeps ) {
  	Memory.fixedCreeps = undefined;
  	Memory.resetCreeps = Game.time;
  } else if (Memory.resetCreeps < Game.time) {
    s.fixCreepsInMemory();
    Memory.resetCreeps = Game.time + 3000;
    console.log('reset creeps');
  }
  for (var r in Game.rooms) {
    const room = Game.rooms[r];
    let roomMem = room.memory;
    const spawn = room.find(FIND_STRUCTURES, { filter: { structureType: STRUCTURE_SPAWN } })[0];
    if (!roomMem.setup) {
      if (room.controller && room.controller.my && spawn) {
        Memory.spawns[spawn.name] = {
          id:spawn.id
        };
      }
      roomMem.sources = [];
      let roomSources = room.find(FIND_SOURCES);
      for (var sourceId in roomSources) {
        let src = roomSources[sourceId];
        let source = {id: src.id};
        let area = room.lookForAtArea(LOOK_TERRAIN, src.pos.y - 1, src.pos.x - 1, src.pos.y + 1, src.pos.x + 1, true);
        let freeCount = _.filter(area, (look) => {
          return look.terrain == 'plain';
        }).length;
        source.area = freeCount;
        roomMem.sources.push(source);
      }
      roomMem.setup = true;
    }

    let creeps = rolesController.countRoles(room);
    let err = OK;
    var role = '';

    if (room.controller && room.controller.my) {
      let stage = stageController.levelUp(room);
      let stageC = stageController.stageModule(stage);
      let canSafeMode = !room.controller.safeMode && !room.controller.safeModeCooldown && room.controller.safeModeAvailable > 0;
      let attackers = room.find(FIND_CREEPS, {
        filter: attackersPresent
      });
      let spawnPriority = false;
      if (attackers.length > 3) {
        if (canSafeMode) {
          room.controller.activateSafeMode();
        } else {
          spawnPriority = true;
        }
      }

      let towers = room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_TOWER } });
      for (let tower in towers) {
        immobileTower.run(towers[tower]);
      }
      let links = room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_LINK } });
      for (let link in links) {
        immobileLink.run(links[link]);
      }

      // let creeps = rolesController.countRoles(room);
      // let stageC = stageController.stages[room.memory.stage];
      // let err = OK;

      if (spawn) {
        if (!roomMem.economyAnalysis || roomMem.economyAnalysis.next < Game.time) {
          roomMem.economyAnalysis = economy.analyze(room);
        }

        if(spawn.spawning) {
          let spawningCreep = Game.creeps[spawn.spawning.name];
          s.structSay(spawn, spawningCreep.memory.role);
        } else if (spawnPriority) {
          err = spawn.createCreep(stageC.creeps.defender.body, undefined, {role: 'defender'});
        } else {
          let spawned = false;
          for (role in creeps) {
            if (creeps.hasOwnProperty(role)) {
              if(stageC.creeps[role] && creeps[role].length < stageC.creeps[role].desired) {
                spawned = true;
                err = spawn.createCreep(stageC.creeps[role].body, undefined, {role: role});
                switch (err) {
                  case OK:
                  case ERR_NOT_ENOUGH_RESOURCES:
                  break;
                  default:
                  s.structErr(spawn, err);
                }
                break;
              }
            }
          }
          if(!spawned && room.energyAvailable > 2000 && roomMem.charter && roomMem.charter.ready && roomMem.charter.count <= roomMem.charter.desired) {

            err = spawn.createCreep(roomMem.charter.body, undefined, {role:roomMem.charter.role, home: r});
            switch (err) {
                  case OK:
                    roomMem.charter.count++;
                    break;
                  case ERR_NOT_ENOUGH_RESOURCES:
                    break;
                  default:
                    s.structErr(spawn, err);
                }
          }
        }
      }

      room.visual.text(r, 0.1, 0.5, s.debugStyle);
      room.visual.text(stage, 10.0, 0.5, s.debugStyle);
      room.visual.text('energy: ' + room.energyAvailable, 20.0, 0.5, s.debugStyle);
      let i = 0;
      for (var typ in creeps) {
        room.visual.text(typ + ': ' +creeps[typ].length, 0.1, 1.5 + (i * 0.75), s.debugStyle);
        i++;
      }
      i++;
      for (var econ in room.memory.economyAnalysis) {
        if (room.memory.economyAnalysis.hasOwnProperty(econ)) {
          room.visual.text(econ + ' : ' + room.memory.economyAnalysis[econ], 0.1, 1.5 + (i * 0.75), s.debugStyle);
          i++;
        }
      }
    }
    for (role in creeps) {
        for (var i = 0; i < creeps[role].length; i++) {
          let creep = creeps[role][i];
          rolesController.run(creep);
        }
      }
  }
};<commit_msg>spawn correctly reports new creeps<commit_after>var stageController = require('controller.stage');
var rolesController = require('controller.roles');
var economy = require('controller.economy');
var immobileTower = require('immobile.tower');
var immobileLink = require('immobile.link');

var s = require('shared');

const attackersPresent = function attackersPresent(creep) {
  return !creep.my && (creep.getActiveBodyparts(HEAL) > 0 || creep.getActiveBodyparts(ATTACK) > 0);
};

module.exports.loop = function () {
  PathFinder.use(true);
  s.setup();

  if ( Memory.fixedCreeps ) {
  	Memory.fixedCreeps = undefined;
  	Memory.resetCreeps = Game.time;
  } else if (Memory.resetCreeps < Game.time) {
    s.fixCreepsInMemory();
    Memory.resetCreeps = Game.time + 3000;
    console.log('reset creeps');
  }
  for (var r in Game.rooms) {
    const room = Game.rooms[r];
    let roomMem = room.memory;
    const spawn = room.find(FIND_STRUCTURES, { filter: { structureType: STRUCTURE_SPAWN } })[0];
    if (!roomMem.setup) {
      if (room.controller && room.controller.my && spawn) {
        Memory.spawns[spawn.name] = {
          id:spawn.id
        };
      }
      roomMem.sources = [];
      let roomSources = room.find(FIND_SOURCES);
      for (var sourceId in roomSources) {
        let src = roomSources[sourceId];
        let source = {id: src.id};
        let area = room.lookForAtArea(LOOK_TERRAIN, src.pos.y - 1, src.pos.x - 1, src.pos.y + 1, src.pos.x + 1, true);
        let freeCount = _.filter(area, (look) => {
          return look.terrain == 'plain';
        }).length;
        source.area = freeCount;
        roomMem.sources.push(source);
      }
      roomMem.setup = true;
    }

    let creeps = rolesController.countRoles(room);
    let err = OK;
    var role = '';

    if (room.controller && room.controller.my) {
      let stage = stageController.levelUp(room);
      let stageC = stageController.stageModule(stage);
      let canSafeMode = !room.controller.safeMode && !room.controller.safeModeCooldown && room.controller.safeModeAvailable > 0;
      let attackers = room.find(FIND_CREEPS, {
        filter: attackersPresent
      });
      let spawnPriority = false;
      if (attackers.length > 3) {
        if (canSafeMode) {
          room.controller.activateSafeMode();
        } else {
          spawnPriority = true;
        }
      }

      let towers = room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_TOWER } });
      for (let tower in towers) {
        immobileTower.run(towers[tower]);
      }
      let links = room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_LINK } });
      for (let link in links) {
        immobileLink.run(links[link]);
      }

      // let creeps = rolesController.countRoles(room);
      // let stageC = stageController.stages[room.memory.stage];
      // let err = OK;

      if (spawn) {
        if (!roomMem.economyAnalysis || roomMem.economyAnalysis.next < Game.time) {
          roomMem.economyAnalysis = economy.analyze(room);
        }

        if(spawn.spawning) {
          let spawningCreep = Game.creeps[spawn.spawning.name];
          s.structSay(spawn, spawningCreep.memory.role);
        } else if (spawnPriority) {
          err = spawn.createCreep(stageC.creeps.defender.body, undefined, {role: 'defender'});
        } else {
          let spawned = false;
          for (role in creeps) {
            if (creeps.hasOwnProperty(role)) {
              if(stageC.creeps[role] && creeps[role].length < stageC.creeps[role].desired) {
                spawned = true;
                err = spawn.createCreep(stageC.creeps[role].body, undefined, {role: role});
                switch (err) {
                  case OK:
                  case ERR_NOT_ENOUGH_RESOURCES:
                  break;
                  default:
                  s.structErr(spawn, err);
                }
                break;
              }
            }
          }
          if(!spawned && room.energyAvailable > 2000 && roomMem.charter && roomMem.charter.ready && roomMem.charter.count <= roomMem.charter.desired) {

            err = spawn.createCreep(roomMem.charter.body, undefined, {role:roomMem.charter.role, home: r});
            switch (err) {
              case ERR_RCL_NOT_ENOUGH:
              case ERR_NOT_OWNER:
              case ERR_NAME_EXISTS:
              case ERR_BUSY:
              break;
              case ERR_NOT_ENOUGH_ENERGY:
              case ERR_INVALID_ARGS:
                s.structErr(spawn, err);
              break;
              default:
                roomMem.charter.count++;
                console.log('spawning pilgrim #' + roomMem.charter.count + ': ' + err + ' for ' + roomMem.charter.name);
                break;
            }
          }
        }
      }

      room.visual.text(r, 0.1, 0.5, s.debugStyle);
      room.visual.text(stage, 10.0, 0.5, s.debugStyle);
      room.visual.text('energy: ' + room.energyAvailable, 20.0, 0.5, s.debugStyle);
      let i = 0;
      for (var typ in creeps) {
        room.visual.text(typ + ': ' +creeps[typ].length, 0.1, 1.5 + (i * 0.75), s.debugStyle);
        i++;
      }
      i++;
      for (var econ in room.memory.economyAnalysis) {
        if (room.memory.economyAnalysis.hasOwnProperty(econ)) {
          room.visual.text(econ + ' : ' + room.memory.economyAnalysis[econ], 0.1, 1.5 + (i * 0.75), s.debugStyle);
          i++;
        }
      }
    }
    for (role in creeps) {
        for (var i = 0; i < creeps[role].length; i++) {
          let creep = creeps[role][i];
          rolesController.run(creep);
        }
      }
  }
};<|endoftext|>