<commit_before>require('newrelic');
var express = require('express');
var jsdom = require("jsdom");
var request = require('request');
var db = require('./config/db');
var Posts = require('./models/posts');
var Comments = require('./models/comments');

var app = express();

var BASE_URL = 'http://www.producthunt.com';

app.configure(function (){
  app.set('port', process.env.PORT || 8888);
  app.use(express.cookieParser('keyboard cat'));
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(app.router);
});

app.get('/', function (req, res) {
  res.redirect('https://github.com/karan/Hook');
});

app.get('/today', function (req, res) {

  var today = new Date().toJSON().slice(0,10);

  Posts.findOne({date: today}, function (err, obj) {

    if (obj && obj.expires < Date.now()) {
      // post expired, scrape again, and save
      console.log("posts expired - " + today);
      getHomePosts(null, function (posts) {
        Posts.findOneAndUpdate({date: today}, {posts: posts, expires: new Date(Date.now() + 60*60*1000)}, {new: true}, function (err, newObj) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });
    } else if (obj) {
      console.log("posts not expired - " + today);
      // not expired, just return this
      res.send(200, {
        status: 'success',
        hunts: obj.posts
      });
    } else {
      // not in the db, scrape and send
      console.log("posts not found in db - " + today);

      getHomePosts(null, function (posts) {
        console.log("got details");
        new Posts({
          date: today,
          posts: posts
        }).save(function (err) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });

    }

  });

});

app.get("/posts/:slug", function (req, res) {

  var post_url = '/posts/'+req.params.slug;

  Comments.findOne({'permalink': post_url}, function(err, commentobj) {

    if (commentobj && commentobj.expires < Date.now()) {
      // expired. Scrape again, save and send
      getPostDetails(post_url, function (post) {
        post = post[0];
        getComments(post_url, function (err, comments, related) {
          Comments.findOneAndUpdate({permalink: post_url}, {post: post, comments: comments, expires: new Date(Date.now() + 2*60*60*1000)}, function (err, newObj) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });
    } else if (commentobj) {
      // not expired, just send response
      res.send(200, {
        status: 'success',
        post: commentobj.post,
        comments: commentobj.comments
      });
    } else {
      // not in db, scrape, save and send
      getPostDetails(post_url, function (post) {
        post = post[0];
        getComments(post_url, function (err, comments, related) {
          new Comments({
            post: post,
            permalink: post.permalink,
            comments: comments
          }).save(function(err) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });

    }

  });

});

function getPostDetails(post_url, callback) {
  var url = post_url ? BASE_URL + post_url : BASE_URL;
  console.log(url);

  jsdom.env(
    url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var header_dom = $(".modal-container").find(".comments-header");

      var votes = +header_dom.find(".vote-count").text()
      var name = header_dom.find(".posted-by").text().trim().replace(/"/g, "");
      var username = header_dom.find(".user-with-tooltip").attr("href").slice(1).trim().replace(/"/g, "").match("Posted\sby\s(.*)\s\d+\shours\sago");
      console.log(username);
      var title = $(this).find(".post-url").text();
      var tagline = $(this).find(".post-tagline").text();

      if (container) {
        var comment_count = $(container.find(".subhead")[2]).text().trim().match(/(\d+)/g);
      } else {
        var comment_count = $(this).find(".view-discussion").text().trim().match(/(\d+)/g);
      }
      comment_count = comment_count ? comment_count[0] : 0;

      var permalink = post_url ? post_url : $(this).find(".view-discussion").attr("data-url");

      request({url: BASE_URL+$(this).find(".post-url").attr("href"), followRedirect: false}, function (error, response, body) {
        url = response.headers.location;

        posts.push({
          'title': title,
          'votes': votes,
          'user': {
            'username': username,
            'name': name
          },
          'rank': rank + 1,
          'tagline': tagline,
          'comment_count': comment_count,
          'permalink': permalink,
          'url': url
        });

        console.log(posts);

        if (posts.length === $ph_posts.length) {
          callback(posts);
        }

      });

    }
  );
}

function getComments(url, callback) {

  jsdom.env(
    BASE_URL+url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var comments = [];

      var comments_dom = $(".modal-container");

      if (comments_dom.length === 0) {
        return callback(null, comments);
      }

      comments_dom.each(function (index) {
        var name = $(this).find(".comment-user-name a").text();
        var username = $(this).find(".comment-user-handle").text().match(/\(\@(.*)\)/)[1];
        var timestamp = $(this).find(".comment-timestamp").text();
        var comment = $(this).find(".comment-body").find(".comment-user-name").remove().end().text();
        var comment_html = $(this).find(".comment-body").find(".comment-user-name").remove().end().html();

        comments.push({
          index: index+1,
          user: {
            username: username,
            name: name
          },
          timestamp: timestamp,
          comment: comment,
          comment_html: comment_html
        });

        if (comments.length === comments_dom.length) {
          callback(null, comments);
        }

      });

    }
  );

}

function getHomePosts(post_url, callback) {
  var url = post_url ? BASE_URL + post_url : BASE_URL;
  console.log(url);
  var posts = [];

  jsdom.env(
    url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var container = post_url ? $(".modal-container") : null;
      var $ph_posts = post_url ? $(".modal-container .posts-group tr") : $(".today tr");

      $ph_posts.each(function (rank) {

        var votes = +$(this).find(".upvote").text();
        var name = $(this).find("h3.user-name").clone().children().remove().end().text().trim().replace(/"/g, "");
        var username = $(this).find("span.user-handle").text().trim().replace(/"/g, "").match(/\(\@(.*)\)/)[1];
        var title = $(this).find(".post-url").text();
        var tagline = $(this).find(".post-tagline").text();

        if (container) {
          var comment_count = $(container.find(".subhead")[2]).text().trim().match(/(\d+)/g);;
        } else {
          var comment_count = $(this).find(".view-discussion").text().trim().match(/(\d+)/g);
        }
        comment_count = comment_count ? comment_count[0] : 0;

        var permalink = post_url ? post_url : $(this).find(".view-discussion").attr("data-url");

        request({url: BASE_URL+$(this).find(".post-url").attr("href"), followRedirect: false}, function (error, response, body) {
          url = response.headers.location;

          posts.push({
            'title': title,
            'votes': votes,
            'user': {
              'username': username,
              'name': name
            },
            'rank': rank + 1,
            'tagline': tagline,
            'comment_count': comment_count,
            'permalink': permalink,
            'url': url
          });

          console.log(posts);

          if (posts.length === $ph_posts.length) {
            callback(posts);
          }

        });

      });
    }
  );
}

app.listen(app.get('port'));
<commit_msg>fix getting post details from comment page<commit_after>require('newrelic');
var express = require('express');
var jsdom = require("jsdom");
var request = require('request');
var db = require('./config/db');
var Posts = require('./models/posts');
var Comments = require('./models/comments');

var app = express();

var BASE_URL = 'http://www.producthunt.com';

app.configure(function (){
  app.set('port', process.env.PORT || 8888);
  app.use(express.cookieParser('keyboard cat'));
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(app.router);
});

app.get('/', function (req, res) {
  res.redirect('https://github.com/karan/Hook');
});

app.get('/today', function (req, res) {

  var today = new Date().toJSON().slice(0,10);

  Posts.findOne({date: today}, function (err, obj) {

    if (obj && obj.expires < Date.now()) {
      // post expired, scrape again, and save
      console.log("posts expired - " + today);
      getHomePosts(null, function (posts) {
        Posts.findOneAndUpdate({date: today}, {posts: posts, expires: new Date(Date.now() + 60*60*1000)}, {new: true}, function (err, newObj) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });
    } else if (obj) {
      console.log("posts not expired - " + today);
      // not expired, just return this
      res.send(200, {
        status: 'success',
        hunts: obj.posts
      });
    } else {
      // not in the db, scrape and send
      console.log("posts not found in db - " + today);

      getHomePosts(null, function (posts) {
        console.log("got details");
        new Posts({
          date: today,
          posts: posts
        }).save(function (err) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });

    }

  });

});

app.get("/posts/:slug", function (req, res) {

  var post_url = '/posts/'+req.params.slug;

  Comments.findOne({'permalink': post_url}, function(err, commentobj) {

    if (commentobj && commentobj.expires < Date.now()) {
      // expired. Scrape again, save and send
      getPostDetails(post_url, function (post) {
        post = post[0];
        getComments(post_url, function (err, comments, related) {
          Comments.findOneAndUpdate({permalink: post_url}, {post: post, comments: comments, expires: new Date(Date.now() + 2*60*60*1000)}, function (err, newObj) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });
    } else if (commentobj) {
      // not expired, just send response
      res.send(200, {
        status: 'success',
        post: commentobj.post,
        comments: commentobj.comments
      });
    } else {
      // not in db, scrape, save and send
      getPostDetails(post_url, function (post) {
        console.log(post);
        getComments(post_url, function (err, comments, related) {
          new Comments({
            post: post,
            permalink: post.permalink,
            comments: comments
          }).save(function(err) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });

    }

  });

});

function getPostDetails(post_url, callback) {
  var url = post_url ? BASE_URL + post_url : BASE_URL;
  console.log(url);

  jsdom.env(
    url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var header_dom = $(".modal-container").find(".comments-header");

      var votes = +header_dom.find(".vote-count").text()
      var name = /Posted by (.*) \d+ .*/g.exec(header_dom.find(".posted-by").text().trim().replace(/"/g, ""))[1];
      var username = header_dom.find(".user-with-tooltip").attr("href").slice(1).trim().replace(/"/g, "");
      var title = header_dom.find(".post-url").text();
      var tagline = header_dom.find(".post-tagline").text();

      var comment_count = $($(".modal-container").find(".subhead")[2]).text().trim().match(/(\d+)/g);
      comment_count = comment_count ? comment_count[0] : 0;

      var permalink = post_url;

      request({url: BASE_URL+header_dom.find(".post-url").attr("href"), followRedirect: false}, function (error, response, body) {
        url = response.headers.location;

        callback({
          'title': title,
          'votes': votes,
          'user': {
            'username': username,
            'name': name
          },
          'rank': 1,
          'tagline': tagline,
          'comment_count': comment_count,
          'permalink': permalink,
          'url': url
        });

      });

    }
  );
}

function getComments(url, callback) {

  jsdom.env(
    BASE_URL+url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var comments = [];

      var comments_dom = $(".modal-container");

      if (comments_dom.length === 0) {
        return callback(null, comments);
      }

      comments_dom.each(function (index) {
        var name = $(this).find(".comment-user-name a").text();
        var username = $(this).find(".comment-user-handle").text().match(/\(\@(.*)\)/)[1];
        var timestamp = $(this).find(".comment-timestamp").text();
        var comment = $(this).find(".comment-body").find(".comment-user-name").remove().end().text();
        var comment_html = $(this).find(".comment-body").find(".comment-user-name").remove().end().html();

        comments.push({
          index: index+1,
          user: {
            username: username,
            name: name
          },
          timestamp: timestamp,
          comment: comment,
          comment_html: comment_html
        });

        if (comments.length === comments_dom.length) {
          callback(null, comments);
        }

      });

    }
  );

}

function getHomePosts(post_url, callback) {
  var url = post_url ? BASE_URL + post_url : BASE_URL;
  console.log(url);
  var posts = [];

  jsdom.env(
    url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var container = post_url ? $(".modal-container") : null;
      var $ph_posts = post_url ? $(".modal-container .posts-group tr") : $(".today tr");

      $ph_posts.each(function (rank) {

        var votes = +$(this).find(".upvote").text();
        var name = $(this).find("h3.user-name").clone().children().remove().end().text().trim().replace(/"/g, "");
        var username = $(this).find("span.user-handle").text().trim().replace(/"/g, "").match(/\(\@(.*)\)/)[1];
        var title = $(this).find(".post-url").text();
        var tagline = $(this).find(".post-tagline").text();

        if (container) {
          var comment_count = $(container.find(".subhead")[2]).text().trim().match(/(\d+)/g);;
        } else {
          var comment_count = $(this).find(".view-discussion").text().trim().match(/(\d+)/g);
        }
        comment_count = comment_count ? comment_count[0] : 0;

        var permalink = post_url ? post_url : $(this).find(".view-discussion").attr("data-url");

        request({url: BASE_URL+$(this).find(".post-url").attr("href"), followRedirect: false}, function (error, response, body) {
          url = response.headers.location;

          posts.push({
            'title': title,
            'votes': votes,
            'user': {
              'username': username,
              'name': name
            },
            'rank': rank + 1,
            'tagline': tagline,
            'comment_count': comment_count,
            'permalink': permalink,
            'url': url
          });

          console.log(posts);

          if (posts.length === $ph_posts.length) {
            callback(posts);
          }

        });

      });
    }
  );
}

app.listen(app.get('port'));
<|endoftext|>


<commit_before>var express = require("express"),
    jade = require("jade"),
    pg = require("pg"),
    routes = require("./routes");

var app = module.exports = express();

app.configure(function () {
    app.locals(require("./config")); // Get site configuration from config.js
    app.locals.pretty = true;
    app.set("views", __dirname + "/jade");
    app.set("view engine", "jade");
    app.use(express.urlencoded());
    app.use(express.json());
    app.use(express.cookieParser());
    app.use(express.session({ secret: "egress-secret-goes-right-here-now"}));
    app.use(express.static(__dirname + "/public"));
    app.use(app.router);
    app.use(function(req, res){
        res.redirect("/404");
    });
});

routes.init(app);<commit_msg>Cleanup app.js<commit_after>var express = require("express");
var jade = require("jade");
var pg = require("pg");
var routes = require("./routes");

var app = module.exports = express();

app.configure(function () {
    app.locals(require("./config")); // Get site configuration from config.js
    app.locals.pretty = true;
    app.set("views", __dirname + "/jade");
    app.set("view engine", "jade");
    app.use(express.urlencoded());
    app.use(express.json());
    app.use(express.cookieParser());
    app.use(express.session({ secret: "egress-secret-goes-right-here-now"}));
    app.use(express.static(__dirname + "/public"));
    app.use(app.router);
    app.use(function(req, res){
        res.redirect("/404");
    });
});

routes.init(app);<|endoftext|>


<commit_before>"use strict";

var roon                 = require("node-roon-api"),
    DevialetExpert       = require("node-devialet-expert"),
    RoonApi              = require("node-roon-api"),
    RoonApiSettings      = require('node-roon-api-settings'),
    RoonApiStatus        = require('node-roon-api-status'),
    RoonApiVolumeControl = require('node-roon-api-volume-control'),
    RoonApiSourceControl = require('node-roon-api-source-control');

var devialet = { rs232: new DevialetExpert() };

var roon = new RoonApi();

var mysettings = roon.load_config("settings") || {
    serialport: "",
    source:     "USB",
};

function makelayout(settings) {
    var l = {
	layout:    [],
	has_error: false
    };

    l.layout.push({
        type:      "string",
        title:     "Serial Port",
        maxlength: 256,
        setting:   "serialport",
    });

    l.layout.push({
        type:    "dropdown",
        title:   "Source for Convenience Switch",
        values:  [
            { value: "USB"       },
            { value: "AES/EBU"   },
            { value: "Digital 1" },
            { value: "Digital 2" },
            { value: "Digital 3" },
            { value: "Digital 4" },
            { value: "Phono 2"   },
            { value: "Line 1"    },
            { value: "Line 2"    },
            { value: "Phono"     },
            { value: "Optical 1" },
            { value: "Optical 2" },
            { value: "HDMI"      },
            { value: "Air"       },
        ],
        setting: "source",
    });

    return l;
}

var svc_settings = new RoonApiSettings(roon, {
    get_settings: function(cb) {
        cb(mysettings, makelayout(mysettings).layout);
    },
    save_settings: function(req, isdryrun, settings) {
	let l = makelayout(settings);
	if (l.has_error) {
	    req.send_complete("NotValid", { settings: settings, layout: l.layout });
            return;
        }
        req.send_complete("Success", { settings: settings, layout: l.layout });
        if (!isdryrun) {
            var oldport = mysettings.serialport;
            mysettings = settings;
            svc_settings.set_settings(mysettings, l.layout);
            if (oldport != settings.serialport)
                setup_serial_port(settings.serialport);
            roon.save_config("settings", mysettings);
        }
    }
});

var svc_status = new RoonApiStatus(roon);
var svc_volume_control = new RoonApiVolumeControl(roon);
var svc_source_control = new RoonApiSourceControl(roon);

function setup_serial_port(port) {
    devialet.rs232.stop();
    if (devialet.source_control) { devialet.source_control.destroy(); delete(devialet.source_control); }
    if (devialet.volume_control)   { devialet.volume_control.destroy();   delete(devialet.volume_control);   }

    if (port)
        devialet.rs232.start(port, 115200);
    else
        svc_status.set_status("Not configured, please check settings.", true);
}

devialet.rs232.on('status', ev_status);
devialet.rs232.on('changed', ev_changed);
setup_serial_port(mysettings.serialport);

function ev_status(status) {
    let rs232 = devialet.rs232;

    if (status == "disconnected") {
        svc_status.set_status("Could not connect to Devialet Expert on \"" + mysettings.serialport + "\"", true);
        if (devialet.source_control) { devialet.source_control.destroy(); delete(devialet.source_control); }
        if (devialet.volume_control)   { devialet.volume_control.destroy();   delete(devialet.volume_control);   }

    } else if (status == "connected") {
        svc_status.set_status("Connected to Devialet Expert", false);
        devialet.source_control = svc_source_control.new_device({
            state: {
                display_name:     "Devialet Expert", // XXX need better less generic name -- can we get serial number from the RS232?
                supports_standby: true,
                status:           !rs232.get_power() ? "standby" : (rs232.get_source() == mysettings.source ? "selected" : "deselected")
            },
            convenience_switch: function (req) {
                devialet.set_source(mysettings.source, err => { req.send_complete(err ? "Failed" : "Success"); });
            },
            standby: function (req) {
                this.state.status = "standby";
                devialet.set_power(0, err => { req.send_complete(err ? "Failed" : "Success"); });
            }
        });

        devialet.volume_control = svc_volume_control.new_device({
            state: {
                display_name: "Devialet Expert", // XXX need better less generic name -- can we get serial number from the RS232?
                type:         "db",
                min:          -97.5,
                max:          30,
                value:        rs232.get_volume(),
                step:         0.5,
                is_muted:     !!rs232.get_mute()
            },
            set_volume: function (req, mode, value) {
                rs232.set_volume(mode == "absolute" ? value : (rs232.get_volume() + value),
                                    (err) => { req.send_complete(err ? "Failed" : "Success"); });
            },
            set_mute: function (req, action) {
                rs232.set_mute(action == "on" ? 1 : (action == "off" ? 0 : "!"),
                                (err) => { req.send_complete(err ? "Failed" : "Success"); });
            }
        });
    } else if (status == "initializing") {
        svc_status.set_status("Connecting to Devialet Expert on \"" + mysettings.serialport + "\"", true);
    }
}

function ev_changed(name, val) {
    let rs232 = devialet.rs232;
    if (name == "volume" && devialet.volume_control) devialet.volume_control.update_state({ value: val });
    if (name == "mute"   && devialet.volume_control) devialet.volume_control.update_state({ is_muted: !!val });
    if ((name == "source" || name == "power") && devialet.source_control)
        devialet.source_control.update_state({ status: !rs232.get_power() ? "standby" : (val == mysettings.source ? "selected" : "deselected") });
}

var extension = roon.extension({
    extension_id:        'com.roonlabs.devialet.expert',
    display_name:        'Devialet Expert Volume and Source Control',
    display_version:     "1.0.0",
    publisher:           'Roon Labs, LLC',
    email:               'contact@roonlabs.com',
    website:             'https://github.com/RoonLabs/roon-extension-devialet-expert',
    required_services:   [ ],
    optional_services:   [ ],
    provided_services:   [ svc_volume_control, svc_source_control, svc_settings, svc_status ]
});

var go;
go = function() { extension.connect("localhost:9100", () => setTimeout(go, 3000)); };
go();
<commit_msg>polish across the board<commit_after>"use strict";

var roon                 = require("node-roon-api"),
    DevialetExpert       = require("node-devialet-expert"),
    RoonApi              = require("node-roon-api"),
    RoonApiSettings      = require('node-roon-api-settings'),
    RoonApiStatus        = require('node-roon-api-status'),
    RoonApiVolumeControl = require('node-roon-api-volume-control'),
    RoonApiSourceControl = require('node-roon-api-source-control');

var devialet = { rs232: new DevialetExpert() };

var roon = new RoonApi();

var mysettings = roon.load_config("settings") || {
    serialport: "",
    source:     "USB",
};

function makelayout(settings) {
    var l = {
        values:    settings,
	layout:    [],
	has_error: false
    };

    l.layout.push({
        type:      "string",
        title:     "Serial Port",
        maxlength: 256,
        setting:   "serialport",
    });

    l.layout.push({
        type:    "dropdown",
        title:   "Source for Convenience Switch",
        values:  [
            { value: "USB"       },
            { value: "AES/EBU"   },
            { value: "Digital 1" },
            { value: "Digital 2" },
            { value: "Digital 3" },
            { value: "Digital 4" },
            { value: "Phono 2"   },
            { value: "Line 1"    },
            { value: "Line 2"    },
            { value: "Phono"     },
            { value: "Optical 1" },
            { value: "Optical 2" },
            { value: "HDMI"      },
            { value: "Air"       },
        ],
        setting: "source",
    });

    return l;
}

var svc_settings = new RoonApiSettings(roon, {
    get_settings: function(cb) {
        cb(makelayout(mysettings));
    },
    save_settings: function(req, isdryrun, settings) {
	let l = makelayout(settings.values);
        req.send_complete(l.has_error ? "NotValid" : "Success", { settings: l });

        if (!isdryrun && !l.has_error) {
            var oldport = mysettings.serialport;
            mysettings = l.values;
            svc_settings.update_settings(l);
            if (oldport != mysettings.serialport) setup_serial_port(mysettings.serialport);
            roon.save_config("settings", mysettings);
        }
    }
});

var svc_status = new RoonApiStatus(roon);
var svc_volume_control = new RoonApiVolumeControl(roon);
var svc_source_control = new RoonApiSourceControl(roon);

function setup_serial_port(port) {
    devialet.rs232.stop();
    if (devialet.source_control) { devialet.source_control.destroy(); delete(devialet.source_control); }
    if (devialet.volume_control)   { devialet.volume_control.destroy();   delete(devialet.volume_control);   }

    if (port)
        devialet.rs232.start(port, 115200);
    else
        svc_status.set_status("Not configured, please check settings.", true);
}

devialet.rs232.on('status', ev_status);
devialet.rs232.on('changed', ev_changed);
setup_serial_port(mysettings.serialport);

function ev_status(status) {
    let rs232 = devialet.rs232;

    console.log("devialet rs232 status", status);

    if (status == "disconnected") {
        svc_status.set_status("Could not connect to Devialet Expert on \"" + mysettings.serialport + "\"", true);
        if (devialet.source_control) { devialet.source_control.destroy(); delete(devialet.source_control); }
        if (devialet.volume_control)   { devialet.volume_control.destroy();   delete(devialet.volume_control);   }

    } else if (status == "connected") {
        svc_status.set_status("Connected to Devialet Expert", false);
        devialet.source_control = svc_source_control.new_device({
            state: {
                display_name:     "Devialet Expert", // XXX need better less generic name -- can we get serial number from the RS232?
                supports_standby: true,
                status:           !rs232.properties.power ? "standby" : (rs232.properties.source == mysettings.source ? "selected" : "deselected")
            },
            convenience_switch: function (req) {
                rs232.set_source(mysettings.source, err => { req.send_complete(err ? "Failed" : "Success"); });
            },
            standby: function (req) {
                this.state.status = "standby";
                rs232.set_power(0, err => { req.send_complete(err ? "Failed" : "Success"); });
            }
        });

        devialet.volume_control = svc_volume_control.new_device({
            state: {
                display_name: "Devialet Expert", // XXX need better less generic name -- can we get serial number from the RS232?
                volume_type:  "db",
                volume_min:   -97.5,
                volume_max:   30,
                volume_value: rs232.properties.volume,
                volume_step:  0.5,
                is_muted:     !!rs232.properties.mute
            },
            set_volume: function (req, mode, value) {
                let newvol = mode == "absolute" ? value : (rs232.properties.volume + value);
                if      (newvol < this.state.volume_min) newvol = this.state.volume_min;
                else if (newvol > this.state.volume_max) newvol = this.state.volume_max;
                rs232.set_volume(newvol, (err) => { req.send_complete(err ? "Failed" : "Success"); });
            },
            set_mute: function (req, action) {
                rs232.set_mute(action == "on" ? 1 : (action == "off" ? 0 : "!"),
                                (err) => { req.send_complete(err ? "Failed" : "Success"); });
            }
        });
    } else if (status == "initializing") {
        svc_status.set_status("Connecting to Devialet Expert on \"" + mysettings.serialport + "\"", true);
    }
}

function ev_changed(name, val) {
    let rs232 = devialet.rs232;
    if (name == "volume" && devialet.volume_control)
        devialet.volume_control.update_state({ volume_value: val });
    else if (name == "mute"   && devialet.volume_control)
        devialet.volume_control.update_state({ is_muted: !!val });
    if ((name == "source" || name == "power") && devialet.source_control)
        devialet.source_control.update_state({ status: !rs232.properties.power ? "standby" : (val == mysettings.source ? "selected" : "deselected") });
}

var extension = roon.extension({
    extension_id:        'com.roonlabs.devialet.expert',
    display_name:        'Devialet Expert Volume and Source Control',
    display_version:     "1.0.0",
    publisher:           'Roon Labs, LLC',
    email:               'contact@roonlabs.com',
    website:             'https://github.com/RoonLabs/roon-extension-devialet-expert',
    required_services:   [ ],
    optional_services:   [ ],
    provided_services:   [ svc_volume_control, svc_source_control, svc_settings, svc_status ]
});

roon.start_discovery();

var go;
go = function() { extension.connect("localhost:9100", () => setTimeout(go, 3000)); };
go();
<|endoftext|>


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

var fs = require('fs'),
    path = require('path'),
    app = require('express')(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    op = require('open'),
    THREE = require('three');

var fileName1 = path.normalize(process.argv[2]),
    fileName2 = path.normalize(process.argv[3]),
    filePath1 = path.resolve(process.cwd(), fileName1),
    filePath2 = path.resolve(process.cwd(), fileName2),
    baseName1 = '/' + path.basename(fileName1),
    baseName2 = '/' + path.basename(fileName2);

//serve client files
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

app.get('/bundle.js', function(req, res){
  res.sendFile(__dirname + '/bundle.js');
});

app.get(baseName1, function(req, res){
  res.sendFile(filePath1);
});

app.get(baseName2, function(req, res){
  res.sendFile(filePath2);
});

app.get('/favicon.ico', function(req, res){
  res.sendFile(__dirname + '/favicon.ico');
});

io.on('connection', function(socket) {
  console.log('We have made contact...');
  socket.emit('mesh1', baseName1);
  socket.emit('mesh2', baseName2);
  socket.on('newMesh', function(msg){
    socket.emit('newMesher', 'newMesh');
  });
  socket.on('oldMesh', function(msg){
    socket.emit('oldMesher', 'oldMesh');
  });
});

var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

http.listen(port, ip_address, function(){
  console.log( "Listening on:");
  console.log('http://'+ ip_address  + ':' + port + '/');
  op('http://'+ ip_address  + ':' + port + '/');
});
<commit_msg>removed unneeded THREEJS dependency.<commit_after>#!/usr/bin/env node

var fs = require('fs'),
    path = require('path'),
    app = require('express')(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    op = require('open');

var fileName1 = path.normalize(process.argv[2]),
    fileName2 = path.normalize(process.argv[3]),
    filePath1 = path.resolve(process.cwd(), fileName1),
    filePath2 = path.resolve(process.cwd(), fileName2),
    baseName1 = '/' + path.basename(fileName1),
    baseName2 = '/' + path.basename(fileName2);

//serve client files
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

app.get('/bundle.js', function(req, res){
  res.sendFile(__dirname + '/bundle.js');
});

app.get(baseName1, function(req, res){
  res.sendFile(filePath1);
});

app.get(baseName2, function(req, res){
  res.sendFile(filePath2);
});

app.get('/favicon.ico', function(req, res){
  res.sendFile(__dirname + '/favicon.ico');
});

io.on('connection', function(socket) {
  console.log('We have made contact...');
  socket.emit('mesh1', baseName1);
  socket.emit('mesh2', baseName2);
  socket.on('newMesh', function(msg){
    socket.emit('newMesher', 'newMesh');
  });
  socket.on('oldMesh', function(msg){
    socket.emit('oldMesher', 'oldMesh');
  });
});

var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

http.listen(port, ip_address, function(){
  console.log( "Listening on:");
  console.log('http://'+ ip_address  + ':' + port + '/');
  op('http://'+ ip_address  + ':' + port + '/');
});
<|endoftext|>


<commit_before>// Tela
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");

var debug = document.getElementById("debug");
var stepDiv = document.getElementById("step");
var runDiv = document.getElementById("run");
var stopDiv = document.getElementById("stop");

stepDiv.addEventListener("click", step, false);
runDiv.addEventListener("click", run, false);
stopDiv.addEventListener("click", stop, false);

var x = 0;

// Memoria Principal
var mem = new Uint8Array(4096);

// Memoria de Video
var gfx = new Uint8Array(64*32);

// Registradores
var V = new Uint8Array(16);

// Input
var keys = new Uint8Array(16);

// Program Counter
var PC = 512;

// Instruction Pointer
var I = 0;

// Stack
var stack = new Uint8Array(16);
var SP = 0;

function stack_push(value)
{
  stack[SP] = value;
  SP++;
}

function stack_pop()
{
  SP--;
  value = stack[SP]
  return value;
}

// Delay Timers
var delay_timer = 0;
var sound_timer = 0;

// Default Font
var chip8Font = [
  0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
  0x20, 0x60, 0x20, 0x20, 0x70, // 1
  0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
  0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
  0x90, 0x90, 0xF0, 0x10, 0x10, // 4
  0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
  0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
  0xF0, 0x10, 0x20, 0x40, 0x40, // 7
  0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
  0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
  0xF0, 0x90, 0xF0, 0x90, 0x90, // A
  0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
  0xF0, 0x80, 0x80, 0x80, 0xF0, // C
  0xE0, 0x90, 0x90, 0x90, 0xE0, // D
  0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
  0xF0, 0x80, 0xF0, 0x80, 0x80  // F
];

// Run flag
var running = false;

window.addEventListener("load", function() {
  loadROM("INVADERS");
});

function init()
{
  for(var i = 0; i<V.length; i++)
  {
    V[i] = 0;
  }

  for(var i = 0; i<gfx.length; i++)
  {
    gfx[i] = 0;
  }

  for(var i = 0; i<chip8Font.length; i++)
  {
    mem[i] = chip8Font[i];
  }
}

function loadROM(name)
{
  // Provavelmente existem formas melhores de fazer isso
  var oReq = new XMLHttpRequest();
  oReq.open("GET", "/roms/" + name, true);
  oReq.responseType = "blob";

  oReq.onload = function(oEvent) {
    var blob = oReq.response;
    var reader = new FileReader();

    reader.onloadend = function() {
      console.log("ROM Carregada");
      rom = new Uint8Array(reader.result);

      for(var i=0; i<rom.length; i++)
      {
        init();
        mem[512 + i] = rom[i];
      }
    }

    reader.readAsArrayBuffer(blob);
  };

  oReq.send();
}

function step() {
  opcode = (mem[PC] << 8 | mem[PC + 1]);
  debug.innerHTML = "Opcode: " + opcode.toString(16);

  if (delay_timer > 0)
  {
   delay_timer--;
  }

  switch(opcode & 0xF000)
  {
    case 0x0000:
      switch (opcode & 0x000F)
      {
        case 0x0000:
          for(var i = 0; i<gfx.length; i++)
          {
            gfx[i] = 0;
          }
          PC += 2;
          break;

        case 0x000E:
          PC = stack_pop();
          PC += 2;
          break;

        default:
          break;
      }
      break;

    case 0x1000:
      PC = opcode & 0x0FFF;
      break;

    case 0x2000:
      stack_push(PC);
      PC = opcode & 0x0FFF;
      break;

    case 0x3000:
      if(V[(opcode & 0x0F00) >> 8] == (opcode & 0x00FF))
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0x4000:
      if(V[(opcode & 0x0F00) >> 8] != (opcode & 0x00FF))
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0x5000:
      if(V[(opcode & 0x0F00) >> 8] == V[(opcode & 0x00F0) >> 4])
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0x6000:
      V[(opcode & 0x0F00) >> 8] = opcode & 0x00FF;
      PC += 2;
      break;

    case 0x7000:
      V[(opcode & 0x0F00) >> 8] += opcode & 0x00FF;
      PC += 2;
      break;

    case 0x8000:
      switch(opcode & 0x000F)
      {
        case 0x0000:
          V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0001:
          V[(opcode & 0x0F00) >> 8] |= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0002:
          V[(opcode & 0x0F00) >> 8] &= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0003:
          V[(opcode & 0x0F00) >> 8] ^= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0004:
          if((V[(opcode & 0x0F00) >> 8] + V[(opcode & 0x00F0) >> 4]) > 10)
          {
            V[0xF] = 1;
          } else {
            V[0xF] = 0;
          }
          PC += 2;
          break;

        case 0x0005:
          if (V[(opcode & 0x00F0) >> 4] > V[(opcode & 0x0F00) >> 8])
          {
           V[0xF] = 0;
          }
          else
          {
           V[0xF] = 1;
          }
          V[(opcode & 0x0F00) >> 8] -= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0006:
          V[0xF] = V[(opcode & 0x0F00) >> 8] & 0x1;
          V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] >> 1;
          PC += 2;
          break;

        case 0x000E:
          V[0xF] = v[(opcode & 0x0F00) >> 8] & 0x80 >> 7;
          V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] << 1;
          PC += 2;
          break;
      }
      break;

    case 0x9000:
      if(V[(opcode & 0x0F00) >> 8] != V[(opcode & 0x00F0) >> 4])
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0xA000:
      I = opcode & 0x0FFF;
      PC += 2;
      break;

    case 0xC000:
      V[(opcode & 0x0F00) >> 8] = Math.floor(Math.random() * 0xFF);
      PC += 2;
      break;

    case 0xD000:
      var x = V[(opcode & 0x0F00) >> 8];
      var y = V[(opcode & 0x00F0) >> 4];
      var height = opcode & 0x000F;
      var pixel;

      V[0xF] = 0;

      for(var _y = 0; _y < height; _y++)
      {
        pixel = mem[i + _y];
        for(var _x = 0; _x < 8; _x++)
        {
          if((pixel & (0x80 >> _x)) != 0)
          {
            if (gfx[(x + _x + ((y + _y) * 64))] == 1)
            {
             V[0xF] = 1;
            }
          gfx[x + _x + ((y + _y) * 64)] ^= 1;
          }
        }
      }
      PC += 2;
      break;

    case 0xE000:
      switch(opcode & 0x000F)
      {
        case 0x000E:
          console.log("INPUT: Opcode não implementado!");
          PC += 2;
          break;

        case 0x0001:
          console.log("INPUT: Opcode não implementado!");
          PC += 2;
          break;
      }
      break;

    case 0xF000:
      switch(opcode & 0x00FF)
      {
        case 0x0007:
          V[(opcode & 0x0F00) >> 8] = delay_timer;
          PC += 2;
          break;

        case 0x000A:
          console.log("INPUT: Opcode não implementado!");
          break;

        case 0x0015:
          delay_timer = V[(opcode & 0x0F00) >> 8];
          PC += 2;
          break;

        case 0x0018:
          delay_timer = V[(opcode & 0x0F00) >> 8];
          PC += 2;
          break;

        case 0x001E:
          if(I + V[(opcode & 0x0F00) >> 8] > 0xFFF)
          {
            V[0xF] = 1;
          } else {
            V[0xF0] = 0;
          }
          I += V[(opcode & 0x0F00) >> 8];
          PC += 2;
          break;

        case 0x0029:
          I = V[(opcode & 0x0F00) >> 8] * 5;
          PC += 2;
          break;

        case 0x0033:
          mem[i] = V[(opcode & 0x0F00) >> 8] / 100;
          mem[i+1] = (V[(opcode & 0x0F00) >> 8] / 10) % 10;
          mem[i+2] = (V[(opcode & 0x0F00) >> 8] % 100) % 10;
          PC += 2;
          break;

        case 0x0055:
          for (var j = 0; j <= ((opcode & 0x0F00) >> 8); j++)
          {
            mem[i + j] = V[j];
          }
            I += ((opcode & 0x0F00) >> 8) + 1;
            PC += 2;
          break;

        case 0x0065:
          for (var j = 0; j <= ((opcode & 0x0F00) >> 8); j++)
          {
            V[j] = mem[i + j];
          }
          I += ((opcode & 0x0F00) >> 8) + 1;
          PC += 2;
          break;
      }
      break;

    default:
      console.log("Opcode: " + opcode.toString(16) + " não implementado!");
      break;
  }
}

function run()
{
  step();
  draw();
  window.requestAnimationFrame(run);
}

function draw()
{
  console.log("draw");
  for(var k=0; k<gfx.length; k++)
    {
      var Y = Math.floor(k/64);
      var X = Math.floor(k - (Y * 64));

      if(gfx[k] == 1)
      {
        console.log("1");
        ctx.fillRect(X*10, Y*10, 10, 10);
      } else {
        console.log("not 1");
      }
    }
}

function stop()
{
  running = false;
}<commit_msg>Corrigida função draw()<commit_after>// Tela
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");

var debug = document.getElementById("debug");
var stepDiv = document.getElementById("step");
var runDiv = document.getElementById("run");
var stopDiv = document.getElementById("stop");

stepDiv.addEventListener("click", step, false);
runDiv.addEventListener("click", run, false);
stopDiv.addEventListener("click", stop, false);

var x = 0;

// Memoria Principal
var mem = new Uint8Array(4096);

// Memoria de Video
var gfx = new Uint8Array(64*32);

// Registradores
var V = new Uint8Array(16);

// Input
var keys = new Uint8Array(16);

// Program Counter
var PC = 512;

// Instruction Pointer
var I = 0;

// Stack
var stack = new Uint8Array(16);
var SP = 0;

function stack_push(value)
{
  stack[SP] = value;
  SP++;
}

function stack_pop()
{
  SP--;
  value = stack[SP]
  return value;
}

// Delay Timers
var delay_timer = 0;
var sound_timer = 0;

// Default Font
var chip8Font = [
  0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
  0x20, 0x60, 0x20, 0x20, 0x70, // 1
  0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
  0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
  0x90, 0x90, 0xF0, 0x10, 0x10, // 4
  0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
  0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
  0xF0, 0x10, 0x20, 0x40, 0x40, // 7
  0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
  0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
  0xF0, 0x90, 0xF0, 0x90, 0x90, // A
  0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
  0xF0, 0x80, 0x80, 0x80, 0xF0, // C
  0xE0, 0x90, 0x90, 0x90, 0xE0, // D
  0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
  0xF0, 0x80, 0xF0, 0x80, 0x80  // F
];

// Run flag
var running = false;

window.addEventListener("load", function() {
  loadROM("INVADERS");
  init();
});

function init()
{
  for(var i = 0; i<V.length; i++)
  {
    V[i] = 0;
  }

  for(var i = 0; i<gfx.length; i++)
  {
    gfx[i] = 0;
  }

  for(var i = 0; i<chip8Font.length; i++)
  {
    mem[i] = chip8Font[i];
  }
}

function loadROM(name)
{
  // Provavelmente existem formas melhores de fazer isso
  var oReq = new XMLHttpRequest();
  oReq.open("GET", "/roms/" + name, true);
  oReq.responseType = "blob";

  oReq.onload = function(oEvent) {
    var blob = oReq.response;
    var reader = new FileReader();

    reader.onloadend = function() {
      console.log("ROM Carregada");
      rom = new Uint8Array(reader.result);

      for(var i=0; i<rom.length; i++)
      {
        init();
        mem[512 + i] = rom[i];
      }
    }

    reader.readAsArrayBuffer(blob);
  };

  oReq.send();
}

function step() {
  opcode = (mem[PC] << 8 | mem[PC + 1]);
  debug.innerHTML = "Opcode: " + opcode.toString(16);

  if (delay_timer > 0)
  {
   delay_timer--;
  }

  switch(opcode & 0xF000)
  {
    case 0x0000:
      switch (opcode & 0x000F)
      {
        case 0x0000:
          for(var i = 0; i<gfx.length; i++)
          {
            gfx[i] = 0;
          }
          PC += 2;
          break;

        case 0x000E:
          PC = stack_pop();
          PC += 2;
          break;

        default:
          break;
      }
      break;

    case 0x1000:
      PC = opcode & 0x0FFF;
      break;

    case 0x2000:
      stack_push(PC);
      PC = opcode & 0x0FFF;
      break;

    case 0x3000:
      if(V[(opcode & 0x0F00) >> 8] == (opcode & 0x00FF))
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0x4000:
      if(V[(opcode & 0x0F00) >> 8] != (opcode & 0x00FF))
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0x5000:
      if(V[(opcode & 0x0F00) >> 8] == V[(opcode & 0x00F0) >> 4])
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0x6000:
      V[(opcode & 0x0F00) >> 8] = opcode & 0x00FF;
      PC += 2;
      break;

    case 0x7000:
      V[(opcode & 0x0F00) >> 8] += opcode & 0x00FF;
      PC += 2;
      break;

    case 0x8000:
      switch(opcode & 0x000F)
      {
        case 0x0000:
          V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0001:
          V[(opcode & 0x0F00) >> 8] |= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0002:
          V[(opcode & 0x0F00) >> 8] &= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0003:
          V[(opcode & 0x0F00) >> 8] ^= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0004:
          if((V[(opcode & 0x0F00) >> 8] + V[(opcode & 0x00F0) >> 4]) > 10)
          {
            V[0xF] = 1;
          } else {
            V[0xF] = 0;
          }
          PC += 2;
          break;

        case 0x0005:
          if (V[(opcode & 0x00F0) >> 4] > V[(opcode & 0x0F00) >> 8])
          {
           V[0xF] = 0;
          }
          else
          {
           V[0xF] = 1;
          }
          V[(opcode & 0x0F00) >> 8] -= V[(opcode & 0x00F0) >> 4];
          PC += 2;
          break;

        case 0x0006:
          V[0xF] = V[(opcode & 0x0F00) >> 8] & 0x1;
          V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] >> 1;
          PC += 2;
          break;

        case 0x000E:
          V[0xF] = v[(opcode & 0x0F00) >> 8] & 0x80 >> 7;
          V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] << 1;
          PC += 2;
          break;
      }
      break;

    case 0x9000:
      if(V[(opcode & 0x0F00) >> 8] != V[(opcode & 0x00F0) >> 4])
      {
        PC += 4;
      } else {
        PC += 2;
      }
      break;

    case 0xA000:
      I = opcode & 0x0FFF;
      PC += 2;
      break;

    case 0xC000:
      V[(opcode & 0x0F00) >> 8] = Math.floor(Math.random() * 0xFF);
      PC += 2;
      break;

    case 0xD000:
      var x = V[(opcode & 0x0F00) >> 8];
      var y = V[(opcode & 0x00F0) >> 4];
      var height = opcode & 0x000F;
      var pixel;

      V[0xF] = 0;

      for(var _y = 0; _y < height; _y++)
      {
        pixel = mem[I + _y];
        for(var _x = 0; _x < 8; _x++)
        {
          if((pixel & (0x80 >> _x)) != 0)
          {
            if (gfx[(x + _x + ((y + _y) * 64))] == 1)
            {
             V[0xF] = 1;
            }
          gfx[x + _x + ((y + _y) * 64)] ^= 1;
          }
        }
      }
      PC += 2;
      break;

    case 0xE000:
      switch(opcode & 0x000F)
      {
        case 0x000E:
          console.log("INPUT: Opcode não implementado!");
          PC += 2;
          break;

        case 0x0001:
          console.log("INPUT: Opcode não implementado!");
          PC += 2;
          break;
      }
      break;

    case 0xF000:
      switch(opcode & 0x00FF)
      {
        case 0x0007:
          V[(opcode & 0x0F00) >> 8] = delay_timer;
          PC += 2;
          break;

        case 0x000A:
          console.log("INPUT: Opcode não implementado!");
          break;

        case 0x0015:
          delay_timer = V[(opcode & 0x0F00) >> 8];
          PC += 2;
          break;

        case 0x0018:
          delay_timer = V[(opcode & 0x0F00) >> 8];
          PC += 2;
          break;

        case 0x001E:
          if(I + V[(opcode & 0x0F00) >> 8] > 0xFFF)
          {
            V[0xF] = 1;
          } else {
            V[0xF0] = 0;
          }
          I += V[(opcode & 0x0F00) >> 8];
          PC += 2;
          break;

        case 0x0029:
          I = V[(opcode & 0x0F00) >> 8] * 5;
          PC += 2;
          break;

        case 0x0033:
          mem[i] = V[(opcode & 0x0F00) >> 8] / 100;
          mem[i+1] = (V[(opcode & 0x0F00) >> 8] / 10) % 10;
          mem[i+2] = (V[(opcode & 0x0F00) >> 8] % 100) % 10;
          PC += 2;
          break;

        case 0x0055:
          for (var j = 0; j <= ((opcode & 0x0F00) >> 8); j++)
          {
            mem[i + j] = V[j];
          }
            I += ((opcode & 0x0F00) >> 8) + 1;
            PC += 2;
          break;

        case 0x0065:
          for (var j = 0; j <= ((opcode & 0x0F00) >> 8); j++)
          {
            V[j] = mem[i + j];
          }
          I += ((opcode & 0x0F00) >> 8) + 1;
          PC += 2;
          break;
      }
      break;

    default:
      console.log("Opcode: " + opcode.toString(16) + " não implementado!");
      break;
  }
}

function run()
{
  step();
  draw();
  window.requestAnimationFrame(run);
}

function draw()
{
  console.log("draw");
  for(var k=0; k<gfx.length; k++)
    {
      var Y = Math.floor(k/64);
      var X = Math.floor(k - (Y * 64));

      if(gfx[k] == 1)
      {
        ctx.fillRect(X*2, Y*2, 2, 2);
      }
    }
}

function stop()
{
  running = false;
}<|endoftext|>


<commit_before>var express = require('express');
var Milight = require('node-milight-promise').MilightController;
var commands = require('node-milight-promise').commandsV6;

var app = express();

// Sunrise
app.get('/', function(req, res) {
	res.send('Starting sunrise...')

	var light = new Milight({
	        ip: "192.168.1.9",
	        type: 'v6'
	    });

	var bedroom = 2;
	var red = 26;
	var yellow = 52;
	var totalBrightness = 100;
	var totalTimeInMinutes = 45;
	var pauseTime = (totalTimeInMinutes * 60 * 1000) / totalBrightness;

  light.sendCommands(commands.rgbw.on(bedroom));

  var color = red;
  for (var brightness = 0; brightness <= totalBrightness; brightness++) {
  		light.sendCommands(commands.rgbw.brightness(bedroom, brightness))
  		light.sendCommands(commands.rgbw.hue(bedroom, color));
  		light.pause(pauseTime);

  		if (brightness % 3 == 0 && brightness < yellow) {
  			color++;
  		}
  }

	light.close();
});

var server = app.listen(3000, function() {
  console.log('Home Automation server has started on port 3000');

  // var discoverBridges = require('node-milight-promise').discoverBridges;
	// discoverBridges({
	//     type: 'all'
	// }).then(function (results) {
	//     console.log(results);
	// });
});

<commit_msg>changing timing<commit_after>var express = require('express');
var Milight = require('node-milight-promise').MilightController;
var commands = require('node-milight-promise').commandsV6;

var app = express();

// Sunrise
app.get('/', function(req, res) {
	res.send('Starting sunrise...')

	var light = new Milight({
	        ip: "192.168.1.9",
	        type: 'v6'
	    });

	var bedroom = 2;
	var red = 26;
	var yellow = 52;
	var totalBrightness = 100;
	var totalTimeInMinutes = 60;
	var pauseTime = (totalTimeInMinutes * 60 * 1000) / totalBrightness;

  light.sendCommands(commands.rgbw.brightness(bedroom, 0));
  //light.sendCommands(commands.rgbw.hue(bedroom, red));
  light.sendCommands(commands.rgbw.on(bedroom));

  var color = red;
  for (var brightness = 0; brightness <= totalBrightness; brightness++) {
  		light.sendCommands(commands.rgbw.brightness(bedroom, brightness));

  		if (brightness % 3 == 0 && brightness < yellow) {
  			light.sendCommands(commands.rgbw.hue(bedroom, color));
  			color++;
  		}

  		light.pause(pauseTime);
  }

	light.close();
});

var server = app.listen(3000, function() {
  console.log('Home Automation server has started on port 3000');

  // var discoverBridges = require('node-milight-promise').discoverBridges;
	// discoverBridges({
	//     type: 'all'
	// }).then(function (results) {
	//     console.log(results);
	// });
});

<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var partials = require('express-partials');
var flash = require('express-flash');
var methodOverride = require('method-override');

var routes = require('./routes/index');
//var users = require('./routes/users');

var app = express(); //Crea aplicacion express

// view engine setup
app.set('views', path.join(__dirname, 'views'));//Instalaparametro de views, se le pasa en ruta el views como directorio. join es un metodo del modulo path que asocia el directorio de quiz con el directorio views y crea el path
app.set('view engine', 'ejs');//Proque hemos puesto ejs al generar al proyecto. ejs es el renderizador utilizado por Ruby

// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico')); //_dirname representa el directorio absoluto del sistema (donde est'a app.js (directorio quiz en nuestro caso))
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({secret:"Quiz 2016",
                 resave: false,
                 saveUninitialized: true}));
app.use(methodOverride('_method', {methods: ["POST", "GET"]}));
app.use(express.static(path.join(__dirname, 'public')));

app.use(partials());
app.use(flash());

// Helper dinamico:
app.use(function(req, res, next) {

   // Hacer visible req.session en las vistas
   res.locals.session = req.session;

   next();
});

app.use('/', routes);//Instalar enrutadores. El index en la ruta base
//app.use('/users', users);//El segundo lo instalamos en la ruta users

// catch 404 and forward to error handler
//Va a estar asociadas a todo el resto de rutas que no sean las otras dos. Se ejecutara esto siempre que no sea una de las rutas definidas arriba
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {//parametro env de la aplicacion sea development (estamos en dfase esarrolo)
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            title: 'Error',
            message: err.message,
            error: err //print err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        title: 'Error',
        error: {}//Stack de errores esta vacio
    });
});

module.exports = app;
<commit_msg>Autologout sin completar<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var partials = require('express-partials');
var flash = require('express-flash');
var methodOverride = require('method-override');

var routes = require('./routes/index');
//var users = require('./routes/users');

var sessionController = require ('./controllers/session_controller');

var app = express(); //Crea aplicacion express

// view engine setup
app.set('views', path.join(__dirname, 'views'));//Instalaparametro de views, se le pasa en ruta el views como directorio. join es un metodo del modulo path que asocia el directorio de quiz con el directorio views y crea el path
app.set('view engine', 'ejs');//Proque hemos puesto ejs al generar al proyecto. ejs es el renderizador utilizado por Ruby

// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico')); //_dirname representa el directorio absoluto del sistema (donde est'a app.js (directorio quiz en nuestro caso))
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({secret:"Quiz 2016",
                 resave: false,
                 saveUninitialized: true,
                 cookie: {maxAge: 20000}}));
app.use(methodOverride('_method', {methods: ["POST", "GET"]}));
app.use(express.static(path.join(__dirname, 'public')));

app.use(partials());
app.use(flash());

// Helper dinamico:
app.use(function(req, res, next) {

   // Hacer visible req.session en las vistas
   res.locals.session = req.session;

   next();
});

app.use('/', routes);//Instalar enrutadores. El index en la ruta base
//app.use('/users', users);//El segundo lo instalamos en la ruta users

app.get('*', function (req, res, next) {
     if (req.session.user) {
        if (req.session.cookie.maxAge === 0 || req.session.cookie.maxAge<0){
            sessionController.destroy;
        } else {
            req.session.cookie.maxAge = 20000;
        }
    } else {
        next();
    }
});
// catch 404 and forward to error handler
//Va a estar asociadas a todo el resto de rutas que no sean las otras dos. Se ejecutara esto siempre que no sea una de las rutas definidas arriba
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {//parametro env de la aplicacion sea development (estamos en dfase esarrolo)
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            title: 'Error',
            message: err.message,
            error: err //print err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        title: 'Error',
        error: {}//Stack de errores esta vacio
    });
});

module.exports = app;
<|endoftext|>


<commit_before>var hackaNews = require('./src/hacka-news');
var cliProcessor = require('commander');

var cmdGiven = null;

cliProcessor
    .version('1.0.0')
    .arguments("<cmd> [arguments...]")
    .option("-l, --headlines", "headlines only")
    .option("-v, --verbose", "verbosity")
    .action(function(cmd, arguments, options){
        cmdGiven = cmd;
        if (cmd == "favs"){
            hackaNews.openSavedPostsJSON();
            hackaNews.printFavourites(options);
        }else if (cmd == "top"){
            hackaNews.printFeed("top", options);
            return;
        }else if (cmd == "new"){
            hackaNews.printFeed("new", options);
            return;
        }else if (cmd == "ask"){
            hackaNews.printFeed("ask", options);
            return;
        }else if (cmd == "show"){
            hackaNews.printFeed("show", options);
            return;
        }else if (cmd == "jobs"){
            hackaNews.printFeed("job", options);
            return;
        }else if (cmd == "url"){
            if (arguments.length < 1){
                console.log("expected: an index number of the favourite story to get the url of")
            } else {
                hackaNews.openSavedPostsJSON();
                var indexOfStory = parseInt(arguments[0]);
                try {
                    var hackaURL = hackaNews.getURL(hackaNews.getSavedPostID(indexOfStory));
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
                console.log(hackaURL);
            }
            return;
        }else if (cmd == "idurl"){
            if (arguments.length < 1){
                console.log("expected: an id of the hacker news post")
            } else {
                var storyID = parseInt(arguments[0]);
                try {
                    var hackaURL = hackaNews.getURL(storyID);
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
                console.log(hackaURL);
            }
            return;
        }else if (cmd == "favid"){
            if (arguments.length < 1){
                console.log("expected: an index number of the favourite story to get the id of")
            } else {
                hackaNews.openSavedPostsJSON();
                var indexOfStory = parseInt(arguments[0]);
                try {
                    var hackaID = hackaNews.getSavedPostID(indexOfStory);
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
                console.log(hackaID);
            }
            return;
        }else if (cmd == "save"){
            hackaNews.savePostID(parseInt(arguments[0]));
        }else if (cmd == "unsave"){
            hackaNews.unsavePostID(parseInt(arguments[0]));
        }else if (cmd == "topid"){
            var indexOfStory = 0;
            if (arguments.length > 1){
                indexOfStory = parseInt(arguments[0]);
            }
            try{
                hackaNews.fetchTopID(indexOfStory, function(id){
                    console.log(id);
                });
            }catch (e){
                if (e == -1){
                    console.log("No list article exists at that index number.");
                }else{
                    console.log("Unknown error!");
                }
            }
        }else if (cmd == "topurl"){
            var indexOfStory = 0;
            if (arguments.length > 1){
                indexOfStory = parseInt(arguments[0]);
            }
            try{
                hackaNews.fetchTopURL(indexOfStory, function(url){
                    console.log(url);
                });
            }catch (e){
                if (e == -1){
                    console.log("No list article exists at that index number.");
                }else{
                    console.log("Unknown error!");
                }
            }
        }else if (cmd == "view"){
            if (arguments.length < 1){
                console.log("expected: an id of the hacker news post")
            } else {
                var storyID = parseInt(arguments[0]);
                try {
                    hackaNews.printStory(storyID, options);
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
            }
            return;
        }else{
            console.log("ERROR: Invalid command.");
        }
    })
    .on('--help', function(){
        console.log("  Commands:");
        console.log('');
        console.log("   top\t\t\tDisplays top stories.");
        console.log("   new\t\t\tDisplays new stories.");
        console.log("   ask\t\t\tDisplays Ask HN stories.");
        console.log("   show\t\t\tDisplays Show HN stories.");
        console.log("   jobs\t\t\tDisplays job stories.");
        console.log("   favs\t\t\tDisplays stories saved in favourites.");
        console.log("   url [fav_index]\tPrints HN url of a post of fav_index index in favourites.");
        console.log("   idurl [id]\t\tPrints HN url of a post of HN id.");
        console.log("   favid [fav_index]\tPrints HN url of a post of HN id.");
        console.log("   save [id]\t\tSave HN post by id to favourites.");
        console.log("   unsave [id]\t\tRemove HN post by id from favourites.");
        console.log("   topid [index]\tGrabs the id of the current n top post on HN, where n is the optional index argument.");
        console.log("   topurl [index]\tGrabs the url of the current n top post on HN, where n is the optional index argument.");
        console.log("   view [id]\t\tView HN post of id.");
        console.log('');
    })
    .parse(process.argv);

if (cmdGiven === null){
    cliProcessor.outputHelp();
}
<commit_msg>Update version number.<commit_after>var hackaNews = require('./src/hacka-news');
var cliProcessor = require('commander');

var cmdGiven = null;

cliProcessor
    .version('1.0.1')
    .arguments("<cmd> [arguments...]")
    .option("-l, --headlines", "headlines only")
    .option("-v, --verbose", "verbosity")
    .action(function(cmd, arguments, options){
        cmdGiven = cmd;
        if (cmd == "favs"){
            hackaNews.openSavedPostsJSON();
            hackaNews.printFavourites(options);
        }else if (cmd == "top"){
            hackaNews.printFeed("top", options);
            return;
        }else if (cmd == "new"){
            hackaNews.printFeed("new", options);
            return;
        }else if (cmd == "ask"){
            hackaNews.printFeed("ask", options);
            return;
        }else if (cmd == "show"){
            hackaNews.printFeed("show", options);
            return;
        }else if (cmd == "jobs"){
            hackaNews.printFeed("job", options);
            return;
        }else if (cmd == "url"){
            if (arguments.length < 1){
                console.log("expected: an index number of the favourite story to get the url of")
            } else {
                hackaNews.openSavedPostsJSON();
                var indexOfStory = parseInt(arguments[0]);
                try {
                    var hackaURL = hackaNews.getURL(hackaNews.getSavedPostID(indexOfStory));
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
                console.log(hackaURL);
            }
            return;
        }else if (cmd == "idurl"){
            if (arguments.length < 1){
                console.log("expected: an id of the hacker news post")
            } else {
                var storyID = parseInt(arguments[0]);
                try {
                    var hackaURL = hackaNews.getURL(storyID);
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
                console.log(hackaURL);
            }
            return;
        }else if (cmd == "favid"){
            if (arguments.length < 1){
                console.log("expected: an index number of the favourite story to get the id of")
            } else {
                hackaNews.openSavedPostsJSON();
                var indexOfStory = parseInt(arguments[0]);
                try {
                    var hackaID = hackaNews.getSavedPostID(indexOfStory);
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
                console.log(hackaID);
            }
            return;
        }else if (cmd == "save"){
            hackaNews.savePostID(parseInt(arguments[0]));
        }else if (cmd == "unsave"){
            hackaNews.unsavePostID(parseInt(arguments[0]));
        }else if (cmd == "topid"){
            var indexOfStory = 0;
            if (arguments.length > 1){
                indexOfStory = parseInt(arguments[0]);
            }
            try{
                hackaNews.fetchTopID(indexOfStory, function(id){
                    console.log(id);
                });
            }catch (e){
                if (e == -1){
                    console.log("No list article exists at that index number.");
                }else{
                    console.log("Unknown error!");
                }
            }
        }else if (cmd == "topurl"){
            var indexOfStory = 0;
            if (arguments.length > 1){
                indexOfStory = parseInt(arguments[0]);
            }
            try{
                hackaNews.fetchTopURL(indexOfStory, function(url){
                    console.log(url);
                });
            }catch (e){
                if (e == -1){
                    console.log("No list article exists at that index number.");
                }else{
                    console.log("Unknown error!");
                }
            }
        }else if (cmd == "view"){
            if (arguments.length < 1){
                console.log("expected: an id of the hacker news post")
            } else {
                var storyID = parseInt(arguments[0]);
                try {
                    hackaNews.printStory(storyID, options);
                }catch (e){
                    if (e == -1){
                        console.log("ERROR: Index entered is not a number.");
                    }else if (e == -2){
                        console.log("ERROR: This index is greater than the total amount of favourites saved.");
                    }else{
                        console.log("ERROR: Unknown error.");
                    }
                    return;
                }
            }
            return;
        }else{
            console.log("ERROR: Invalid command.");
        }
    })
    .on('--help', function(){
        console.log("  Commands:");
        console.log('');
        console.log("   top\t\t\tDisplays top stories.");
        console.log("   new\t\t\tDisplays new stories.");
        console.log("   ask\t\t\tDisplays Ask HN stories.");
        console.log("   show\t\t\tDisplays Show HN stories.");
        console.log("   jobs\t\t\tDisplays job stories.");
        console.log("   favs\t\t\tDisplays stories saved in favourites.");
        console.log("   url [fav_index]\tPrints HN url of a post of fav_index index in favourites.");
        console.log("   idurl [id]\t\tPrints HN url of a post of HN id.");
        console.log("   favid [fav_index]\tPrints HN url of a post of HN id.");
        console.log("   save [id]\t\tSave HN post by id to favourites.");
        console.log("   unsave [id]\t\tRemove HN post by id from favourites.");
        console.log("   topid [index]\tGrabs the id of the current n top post on HN, where n is the optional index argument.");
        console.log("   topurl [index]\tGrabs the url of the current n top post on HN, where n is the optional index argument.");
        console.log("   view [id]\t\tView HN post of id.");
        console.log('');
    })
    .parse(process.argv);

if (cmdGiven === null){
    cliProcessor.outputHelp();
}
<|endoftext|>


<commit_before>/*************************************************
 *
 * BJS.js (Bollinger JavaScript Library) v0.0.1
 *
 ************************************************/
var bjl = bjl || {};

bjl.cloneObject = function (src, dest) {
    for(var attr in src.prototype) {
        dest.prototype[attr] = src.prototype[attr];
    }
};

var Builder = (function () {
function Builder() {
}
Builder.prototype.build = function (builder) {
return builder.build();
};
return Builder;
})();
blj.Builder = Builder;
<commit_msg>improved formatting<commit_after>/*************************************************
 *
 * BJS.js (Bollinger JavaScript Library) v0.0.1
 *
 ************************************************/
var bjl = bjl || {};

bjl.cloneObject = function (src, dest) {
    for(var attr in src.prototype) {
        dest.prototype[attr] = src.prototype[attr];
    }
};

var Builder = (function () {

    function Builder() {}

    Builder.prototype.build = function (builder) {
        return builder.build();
    };

    return Builder;
})();
blj.Builder = Builder;
<|endoftext|>


<commit_before>const __WHITESPACES = [ ' ', '\t', '\n', '\r', '\f', '\v' ],
      __SYNTAXCHARS = [ '[', ']', '{', '}', ',', ':' ]

const __ESCAPE_TABLE = {
    '"': '"', '\\': '\\', '/': '/',
    'b': '\b', 'f': '\f', 'n': '\n',
    'r': '\r', 't': '\t', 'v': '\v'
}

const __REVERSE_ESCAPE_TABLE = {
    '"': '\\"', '\\': '\\\\', '/': '\\/',
    '\b': '\\b', '\f': '\\f', '\n': '\\n',
    '\r': '\\r', '\t': '\\t', '\v': '\\v'
}

// BonParser class

function BonParser() {
    this.__text = '';
    this.__index = 0;
}

BonParser.prototype.parse = function(text) {
    this.__text = text;
    this.__index = 0;

    this.__skip_spaces();

    try {
        var value = this.__read_value();
        this.__skip_spaces();
        if (!this.__peek_char()) {
            return value;
        }
    } catch (e) {
        console.log(e);
    }
}

BonParser.prototype.__read_value = function() {
    var value = this.__read_array();

    if (!value) {
        value = this.__read_object();

        if (!value) {
            value = this.__read_string();
        }
    }

    return value;
}

BonParser.prototype.__read_array = function() {
    if (this.__match_char('[')) {
        this.__skip_spaces();

        var array = [];

        while (true) {
            if (this.__match_char(']')) {
                return array;
            }

            var value = this.__read_value();

            if (!value) {
                break;
            }

            array.push(value);

            this.__skip_spaces();

            if (this.__match_char(',')) {
                this.__skip_spaces();
            } else if (this.__match_char(']')) {
                return array;
            } else {
                break;
            }
        }

        throw 'malformed array';
    }
}

BonParser.prototype.__read_object = function() {
    if (this.__match_char('{')) {
        this.__skip_spaces();

        var object = {}

        while (true) {
            if (this.__match_char('}')) {
                return object;
            }

            var key = this.__read_string();

            if (!key) {
                break;
            }

            this.__skip_spaces();

            if (!this.__match_char(':')) {
                break;
            }

            this.__skip_spaces();

            var value = this.__read_value();

            if (!value) {
                break;
            }

            object[key] = value;

            this.__skip_spaces();

            if (this.__match_char(',')) {
                this.__skip_spaces();
            } else if (this.__match_char('}')) {
                return object;
            } else {
                break;
            }
        }

        throw 'malformed object';
    }
}

BonParser.prototype.__read_string = function() {
    var ch = this.__peek_char();

    if (!__SYNTAXCHARS.includes(ch)) {
        var string = '';

        if (ch === '"') {
            this.__consume_char();

            while (true) {
                ch = this.__peek_char();

                if (!ch) {
                    break;
                }

                this.__consume_char();

                if (ch === '"') {
                    return string;
                }

                if (ch === '\\') {
                    ch = this.__peek_char();

                    if (!ch) {
                        break;
                    }

                    if (__ESCAPE_TABLE.hasOwnProperty(ch)) {
                        ch = __ESCAPE_TABLE[ch];
                    }

                    this.__consume_char();
                }

                string = string + ch;
            }

            throw 'wrong quoted string';
        } else {
            while (true) {
                var ch = this.__peek_char();

                if (!ch) {
                    break;
                }

                if (__WHITESPACES.includes(ch) || __SYNTAXCHARS.includes(ch)) {
                    break;
                }

                string = string + ch;

                this.__consume_char();
            }

            return string;
        }
    }
}

BonParser.prototype.__peek_char = function() {
    if (this.__index < this.__text.length) {
        return this.__text.charAt(this.__index);
    }
}

BonParser.prototype.__consume_char = function() {
    this.__index += 1;
}

BonParser.prototype.__match_char = function(ch) {
    if (this.__peek_char() == ch) {
        this.__consume_char();

        return true;
    }

    return false;
}

BonParser.prototype.__skip_spaces = function() {
    while (true) {
        var ch = this.__peek_char();

        if (!__WHITESPACES.includes(ch)) {
            break;
        }

        this.__consume_char();
    }
}

// BonStringifier class

function BonStringifier(use_indent) {
    this.__use_indent = use_indent;
    this.__indent = 0;
}

BonStringifier.prototype.stringify = function(value) {
    this.__indent = 0;

    try {
        return this.__stringify_value(value);
    } catch (e) {
        console.log(e);
    }
}

BonStringifier.prototype.__stringify_value = function(value) {
    if (Array.isArray(value)) {
        return this.__stringify_array(value);
    }

    if (typeof(value) === 'object') {
        return this.__stringify_object(value);
    }

    if (typeof(value) === 'string') {
        return this.__stringify_string(value);
    }

    throw 'Unsupported type'
}

BonStringifier.prototype.__stringify_array = function(array) {
    var text = '[';

    text += this.__append_newline();
    this.__increment_indent();

    var once = true;
    for (var v in array) {
        if (once) {
            once = false;
        } else {
            text += ',';
            text += this.__append_newline();
        }

        text += this.__append_indent();
        text += this.__stringify_value(v);
    }

    text += this.__append_newline();
    this.__decrement_indent();
    text += this.__append_indent();

    text += ']';

    return text;
}

BonStringifier.prototype.__stringify_object = function(object) {
    var text = '{';

    text += this.__append_newline();
    this.__increment_indent();

    var once = true;
    for (var [ k, v ] of Object.entries(object)) {
        if (once) {
            once = false;
        } else {
            text += ',';
            text += this.__append_newline();
        }

        text += this.__append_indent();
        text += k + ':' + (this.__use_indent ? ' ' : '');
        text += this.__stringify_value(v);
    }

    text += this.__append_newline();
    this.__decrement_indent();
    text += this.__append_indent();

    text += '}';

    return text;
}

BonStringifier.prototype.__stringify_string = function(string) {
    var text = '';
    var quote_str = false;

    for (var ch of string) {
        if (__SYNTAXCHARS.includes(ch) ||
            __WHITESPACES.includes(ch) ||
            __REVERSE_ESCAPE_TABLE.hasOwnProperty(ch)) {
            quote_str = true;
            break;
        }
    }

    if (string.length == 0) {
        quote_str = true;
    }

    if (quote_str) {
        text += '"';
        for (var ch of string) {
            if (__REVERSE_ESCAPE_TABLE.hasOwnProperty(ch)) {
                text += __REVERSE_ESCAPE_TABLE[ch];
            } else {
                text += ch;
            }
        }
        text += '"';
    } else {
        text += string;
    }

    return text;
}

BonStringifier.prototype.__increment_indent = function() {
    if (this.__use_indent) {
        this.__indent += 4;
    }
}

BonStringifier.prototype.__decrement_indent = function() {
    if (this.__use_indent) {
        this.__indent -= 4;
    }
}

BonStringifier.prototype.__append_indent = function() {
    var text = '';

    if (this.__use_indent) {
        for (var i = 0; i < this.__indent; ++i) {
            text += ' ';
        }
    }

    return text;
}

BonStringifier.prototype.__append_newline = function() {
    if (this.__use_indent) {
        return '\n';
    }

    return '';
}

module.exports = {
    parse : function(text) {
        return new BonParser().parse(text);
    },

    stringify : function(value) {
        return new BonStringifier(true).stringify(value);
    }
}
<commit_msg>Fix the bug for publishing a book<commit_after>const __WHITESPACES = [ ' ', '\t', '\n', '\r', '\f', '\v' ],
      __SYNTAXCHARS = [ '[', ']', '{', '}', ',', ':' ]

const __ESCAPE_TABLE = {
    '"': '"', '\\': '\\', '/': '/',
    'b': '\b', 'f': '\f', 'n': '\n',
    'r': '\r', 't': '\t', 'v': '\v'
}

const __REVERSE_ESCAPE_TABLE = {
    '"': '\\"', '\\': '\\\\', '/': '\\/',
    '\b': '\\b', '\f': '\\f', '\n': '\\n',
    '\r': '\\r', '\t': '\\t', '\v': '\\v'
}

// BonParser class

function BonParser() {
    this.__text = '';
    this.__index = 0;
}

BonParser.prototype.parse = function(text) {
    this.__text = text;
    this.__index = 0;

    this.__skip_spaces();

    try {
        var value = this.__read_value();
        this.__skip_spaces();
        if (!this.__peek_char()) {
            return value;
        }
    } catch (e) {
        console.log(e);
    }
}

BonParser.prototype.__read_value = function() {
    var value = this.__read_array();

    if (!value) {
        value = this.__read_object();

        if (!value) {
            value = this.__read_string();
        }
    }

    return value;
}

BonParser.prototype.__read_array = function() {
    if (this.__match_char('[')) {
        this.__skip_spaces();

        var array = [];

        while (true) {
            if (this.__match_char(']')) {
                return array;
            }

            var value = this.__read_value();

            if (!value) {
                break;
            }

            array.push(value);

            this.__skip_spaces();

            if (this.__match_char(',')) {
                this.__skip_spaces();
            } else if (this.__match_char(']')) {
                return array;
            } else {
                break;
            }
        }

        throw 'malformed array';
    }
}

BonParser.prototype.__read_object = function() {
    if (this.__match_char('{')) {
        this.__skip_spaces();

        var object = {}

        while (true) {
            if (this.__match_char('}')) {
                return object;
            }

            var key = this.__read_string();

            if (!key) {
                break;
            }

            this.__skip_spaces();

            if (!this.__match_char(':')) {
                break;
            }

            this.__skip_spaces();

            var value = this.__read_value();

            if (!value) {
                break;
            }

            object[key] = value;

            this.__skip_spaces();

            if (this.__match_char(',')) {
                this.__skip_spaces();
            } else if (this.__match_char('}')) {
                return object;
            } else {
                break;
            }
        }

        throw 'malformed object';
    }
}

BonParser.prototype.__read_string = function() {
    var ch = this.__peek_char();

    if (!__SYNTAXCHARS.includes(ch)) {
        var string = '';

        if (ch === '"') {
            this.__consume_char();

            while (true) {
                ch = this.__peek_char();

                if (!ch) {
                    break;
                }

                this.__consume_char();

                if (ch === '"') {
                    return string;
                }

                if (ch === '\\') {
                    ch = this.__peek_char();

                    if (!ch) {
                        break;
                    }

                    if (__ESCAPE_TABLE.hasOwnProperty(ch)) {
                        ch = __ESCAPE_TABLE[ch];
                    }

                    this.__consume_char();
                }

                string = string + ch;
            }

            throw 'wrong quoted string';
        } else {
            while (true) {
                var ch = this.__peek_char();

                if (!ch) {
                    break;
                }

                if (__WHITESPACES.includes(ch) || __SYNTAXCHARS.includes(ch)) {
                    break;
                }

                string = string + ch;

                this.__consume_char();
            }

            return string;
        }
    }
}

BonParser.prototype.__peek_char = function() {
    if (this.__index < this.__text.length) {
        return this.__text.charAt(this.__index);
    }
}

BonParser.prototype.__consume_char = function() {
    this.__index += 1;
}

BonParser.prototype.__match_char = function(ch) {
    if (this.__peek_char() == ch) {
        this.__consume_char();

        return true;
    }

    return false;
}

BonParser.prototype.__skip_spaces = function() {
    while (true) {
        var ch = this.__peek_char();

        if (!__WHITESPACES.includes(ch)) {
            break;
        }

        this.__consume_char();
    }
}

// BonStringifier class

function BonStringifier(use_indent) {
    this.__use_indent = use_indent;
    this.__indent = 0;
}

BonStringifier.prototype.stringify = function(value) {
    this.__indent = 0;

    try {
        return this.__stringify_value(value);
    } catch (e) {
        console.log(e);
    }
}

BonStringifier.prototype.__stringify_value = function(value) {
    if (Array.isArray(value)) {
        return this.__stringify_array(value);
    }

    if (typeof(value) === 'object') {
        return this.__stringify_object(value);
    }

    if (typeof(value) === 'string') {
        return this.__stringify_string(value);
    }

    throw 'Unsupported type'
}

BonStringifier.prototype.__stringify_array = function(array) {
    var text = '[';

    text += this.__append_newline();
    this.__increment_indent();

    var once = true;
    for (var v in array) {
        if (once) {
            once = false;
        } else {
            text += ',';
            text += this.__append_newline();
        }

        text += this.__append_indent();
        text += this.__stringify_value(v);
    }

    text += this.__append_newline();
    this.__decrement_indent();
    text += this.__append_indent();

    text += ']';

    return text;
}

BonStringifier.prototype.__stringify_object = function(object) {
    var text = '{';

    text += this.__append_newline();
    this.__increment_indent();

    var once = true;
    for (var [ k, v ] of Object.entries(object)) {
        if (once) {
            once = false;
        } else {
            text += ',';
            text += this.__append_newline();
        }

        text += this.__append_indent();
        text += k + ':' + (this.__use_indent ? ' ' : '');
        text += this.__stringify_value(v);
    }

    text += this.__append_newline();
    this.__decrement_indent();
    text += this.__append_indent();

    text += '}';

    return text;
}

BonStringifier.prototype.__stringify_string = function(string) {
    var text = '';
    var quote_str = false;

    for (var ch of string) {
        if (__SYNTAXCHARS.includes(ch) ||
            __WHITESPACES.includes(ch) ||
            __REVERSE_ESCAPE_TABLE.hasOwnProperty(ch)) {
            quote_str = true;
            break;
        }
    }

    if (string.length == 0) {
        quote_str = true;
    }

    if (quote_str) {
        text += '"';

        for (var ch of string) {
            if (__REVERSE_ESCAPE_TABLE.hasOwnProperty(ch)) {
                text += __REVERSE_ESCAPE_TABLE[ch];
            } else {
                text += ch;
            }
        }

        text += '"';
    } else {
        text += string;
    }

    return text;
}

BonStringifier.prototype.__increment_indent = function() {
    if (this.__use_indent) {
        this.__indent += 4;
    }
}

BonStringifier.prototype.__decrement_indent = function() {
    if (this.__use_indent) {
        this.__indent -= 4;
    }
}

BonStringifier.prototype.__append_indent = function() {
    var text = '';

    if (this.__use_indent) {
        for (var i = 0; i < this.__indent; ++i) {
            text += ' ';
        }
    }

    return text;
}

BonStringifier.prototype.__append_newline = function() {
    if (this.__use_indent) {
        return '\n';
    }

    return '';
}

module.exports = {
    parse : function(text) {
        return new BonParser().parse(text);
    },

    stringify : function(value) {
        return new BonStringifier(true).stringify(value);
    }
}
<|endoftext|>


<commit_before>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const yaml = require('js-yaml')
const config = require('./config')
const http = require('http')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
})

exports.bot = bot
exports.config = config
exports.commands = {
  master: {},
  moderator: {},
  default: {},
  dm: {}
}

registerCommand = function (name, type, callback, aliases, description, usage) {
  exports.commands[type][name] = {}
  exports.commands[type][name]['aliases'] = aliases
  exports.commands[type][name]['description'] = description
  exports.commands[type][name]['usage'] = usage
  exports.commands[type][name]['process'] = callback
}

var loadScript = (path, reload) => {
  var req = require(path)
  if (reload) {
    console.log('Reloaded script at ' + path)
  } else {
    console.log('Script loaded at ' + path)
  }
}
exports.registerCommand = registerCommand
exports.loadScript = loadScript

var commands = fs.readdirSync('./commands/')
commands.forEach(script => {
  if (script.substring(script.length - 3, script.length) === '.js') {
    exports.loadScript('./commands/' + script)
  }
})

var modules = fs.readdirSync('./modules/')
modules.forEach(script => {
  if (script.substring(script.length - 3, script.length) === '.js') {
    loadScript('./modules/' + script)
  }
})

bot.login(process.env.BOT_TOKEN)<commit_msg>:zap: A fix<commit_after>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const yaml = require('js-yaml')
const config = require('./config')
const http = require('http')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
})

exports.bot = bot
exports.config = config
exports.commands = {
  master: {},
  moderator: {},
  default: {},
  dm: {}
}

registerCommand = function (name, type, callback, aliases, description, usage) {
  exports.commands[type][name] = {}
  exports.commands[type][name]['aliases'] = aliases
  exports.commands[type][name]['description'] = description
  exports.commands[type][name]['usage'] = usage
  exports.commands[type][name]['process'] = callback
}

var loadScript = (path, reload) => {
  var req = require(path)
  if (reload) {
    console.log('Reloaded script at ' + path)
  } else {
    console.log('Script loaded at ' + path)
  }
}
exports.registerCommand = registerCommand
exports.loadScript = loadScript

var commands = fs.readdirSync('./commands/')
commands.forEach(script => {
  if (script.substring(script.length - 3, script.length) === '.js') {
    exports.loadScript('./commands/' + script)
  }
})

// var modules = fs.readdirSync('./modules/')
// modules.forEach(script => {
//   if (script.substring(script.length - 3, script.length) === '.js') {
//     loadScript('./modules/' + script)
//   }
// })

bot.login(process.env.BOT_TOKEN)<|endoftext|>