<commit_before>'use strict';

var opennms = require('../../util/opennms')(casper),
	utils = require('utils');

var x = require('casper').selectXPath;
var nextButton = 'div#next > span.v-button-wrap > span.v-icon';
var previousButton = 'div#previous > span.v-button-wrap > span.v-icon';

var vaadinTax = 500; // milliseconds

casper.test.begin('JMX Configuration Generator', {
	setUp: function() {
		opennms.initialize();
		opennms.login();
		casper.thenOpen(opennms.root() + '/admin/jmxConfigGenerator.jsp');
		casper.then(function() {
			this.page.switchToChildFrame(0);
		});
	},

	test: function(test) {
		/*
		 * In Vaadin 7 a Navigator was introduced to navigate within Vaadin applications
		 * Somehow normal links cause a vaadin exception. This verifies that no exception
		 * is thrown when clicking the Header links
		 */
		casper.waitForText('1. Service Configuration');
		casper.then(function() {
			casper.clickLabel('1. Service Configuration');
		});
		casper.then(function() {
			// sometimes empty v-errormessage divs are present, so we can't rely on just counting them
			var errorText = casper.fetchText('div.v-errormessage');
			test.assertTruthy(!errorText || errorText.trim().length === 0, 'v-errormessage elements should be empty');
		});

		/*
		 * Verify that navigation works.
		 */
		casper.then(function() {
			casper.sendKeys('input#port', '18980', {reset:true});
			var info = casper.getElementInfo('span#authenticate input[type="checkbox"]');
			test.assertTruthy(!info.attributes.hasOwnProperty('checked'), 'Authentication checkbox should be checked');
			casper.click('span#authenticate label');
		});
		casper.wait(vaadinTax);
		casper.then(function() {
			var info = casper.getElementInfo('span#authenticate input[type="checkbox"]');
			test.assertTruthy(info.attributes.hasOwnProperty('checked'), 'Authentication checkbox should be checked');
			casper.sendKeys('input#authenticateUser', opennms.options().username, {reset:true});
			casper.sendKeys('input#authenticatePassword', opennms.options().password, {reset:true});
		});
		casper.then(function() {
			casper.click(nextButton);
		});
		casper.waitForText('com.mchange.v2.c3p0');
		casper.then(function() {
			test.assertTextExists('com.mchange.v2.c3p0', 'After navigating to next page, "com.mchange.v2.c3p0" should be in the tree view');
			casper.click(nextButton);
		});
		casper.waitForText('collectd-configuration.xml');
		casper.then(function() {
			test.assertTextExists('collectd-configuration.xml', 'After navigating to the last page, "collectd-configuration.xml" should be visible');
			casper.click(previousButton);
		});
		casper.waitForText('com.mchange.v2.c3p0');
		casper.then(function() {
			test.assertTextExists('com.mchange.v2.c3p0', 'After navigating to the previous page, "com.mchange.v2.c3p0" should be in the tree view');
			casper.click(previousButton);
		});
		casper.waitForText('Skip JVM MBeans');
		casper.then(function() {
			test.assertTextExists('Skip JVM MBeans', 'After navigating to the previous page, "Skip JVM beans" should be visible');
		});

		/*
		 * Verify that selected CompMembers do show up in the generated jmx-datacollection-config.xml snippet.
		 */
		casper.then(function() {
			var info = casper.getElementInfo('span#skipDefaultVM input[type="checkbox"]');
			test.assertTruthy(info.attributes.hasOwnProperty('checked'), 'Skip JVM MBeans should be checked');
			casper.click('span#skipDefaultVM input');
		});
		casper.wait(vaadinTax);
		casper.then(function() {
			var info = casper.getElementInfo('span#skipDefaultVM input[type="checkbox"]');
			test.assertTruthy(!info.attributes.hasOwnProperty('checked'), 'Skip JVM MBeans should not be checked');
			casper.click(nextButton);
		});
		casper.waitForText('com.mchange.v2.c3p0');
		casper.then(function() {
			opennms.scrollToElementWithText('span', 'Code Cache');
		});
		casper.then(function() {
			this.mouse.rightclick(x('//span[text()=\'Code Cache\']'));
		});
		casper.wait(vaadinTax);
		casper.then(function() {
			casper.click(x('//td[@role="menuitem"]/div[text()=\'select\']'));
		});
		casper.wait(vaadinTax);
		opennms.scrollToElementWithText('span', 'Code Cache');
		casper.then(function() {
			casper.click(nextButton);
		});
		casper.waitForText('collectd-configuration.xml');
		casper.then(function() {
			test.assertTextExists('collectd-configuration.xml', 'collectd-configuration.xml tab should exist');
			test.assertTextExists('jmx-datacollection-config.xml', 'jmx-datacollection-config.xml tab should exist');
			casper.clickLabel('jmx-datacollection-config.xml');
		});
		casper.waitForText('JMXMP protocol');
		casper.then(function() {
			var info = casper.fetchText('textarea');
			test.assertEquals(info.match(/\<comp-attrib/g).length, 2, 'There should be 2 <comp-attrib/> tags in jmx-datacollection-config.xml');
			test.assertEquals(info.match(/\<comp-member/g).length, 8, 'There should be 8 <comp-member/> tags in jmx-datacollection-config.xml');
		});

		opennms.finished(test);
	}
});
<commit_msg>change these tests to check jmx-datacollection-config.xml a bit differently<commit_after>'use strict';

var opennms = require('../../util/opennms')(casper),
	utils = require('utils');

var x = require('casper').selectXPath;
var nextButton = 'div#next > span.v-button-wrap > span.v-icon';
var previousButton = 'div#previous > span.v-button-wrap > span.v-icon';

var vaadinTax = 500; // milliseconds

casper.test.begin('JMX Configuration Generator', {
	setUp: function() {
		opennms.initialize();
		opennms.login();
		casper.thenOpen(opennms.root() + '/admin/jmxConfigGenerator.jsp');
		casper.then(function() {
			this.page.switchToChildFrame(0);
		});
	},

	test: function(test) {
		/*
		 * In Vaadin 7 a Navigator was introduced to navigate within Vaadin applications
		 * Somehow normal links cause a vaadin exception. This verifies that no exception
		 * is thrown when clicking the Header links
		 */
		casper.waitForText('1. Service Configuration');
		casper.then(function() {
			casper.clickLabel('1. Service Configuration');
		});
		casper.then(function() {
			// sometimes empty v-errormessage divs are present, so we can't rely on just counting them
			var errorText = casper.fetchText('div.v-errormessage');
			test.assertTruthy(!errorText || errorText.trim().length === 0, 'v-errormessage elements should be empty');
		});

		/*
		 * Verify that navigation works.
		 */
		casper.then(function() {
			casper.sendKeys('input#port', '18980', {reset:true});
			var info = casper.getElementInfo('span#authenticate input[type="checkbox"]');
			test.assertTruthy(!info.attributes.hasOwnProperty('checked'), 'Authentication checkbox should be checked');
			casper.click('span#authenticate label');
		});
		casper.wait(vaadinTax);
		casper.then(function() {
			var info = casper.getElementInfo('span#authenticate input[type="checkbox"]');
			test.assertTruthy(info.attributes.hasOwnProperty('checked'), 'Authentication checkbox should be checked');
			casper.sendKeys('input#authenticateUser', opennms.options().username, {reset:true});
			casper.sendKeys('input#authenticatePassword', opennms.options().password, {reset:true});
		});
		casper.then(function() {
			casper.click(nextButton);
		});
		casper.waitForText('com.mchange.v2.c3p0');
		casper.then(function() {
			test.assertTextExists('com.mchange.v2.c3p0', 'After navigating to next page, "com.mchange.v2.c3p0" should be in the tree view');
			casper.click(nextButton);
		});
		casper.waitForText('collectd-configuration.xml');
		casper.then(function() {
			test.assertTextExists('collectd-configuration.xml', 'After navigating to the last page, "collectd-configuration.xml" should be visible');
			casper.clickLabel('jmx-datacollection-config.xml');
		});
		casper.waitForText('JMXMP protocol');
		casper.then(function() {
			var info = casper.fetchText('textarea');
			test.assertEquals(info.match(/\<mbeans\/\>/g).length, 1, 'There should be 1 <mbeans/> tags in jmx-datacollection-config.xml');
			test.assertEquals(info.match(/\<mbean /g), null, 'There should be no <mbean/> tags in jmx-datacollection-config.xml');
			test.assertEquals(info.match(/\<attrib /g), null, 'There should be no <attrib/> tags in jmx-datacollection-config.xml');
			casper.click(previousButton);
		});
		casper.waitForText('com.mchange.v2.c3p0');
		casper.then(function() {
			test.assertTextExists('com.mchange.v2.c3p0', 'After navigating to the previous page, "com.mchange.v2.c3p0" should be in the tree view');
			casper.click(previousButton);
		});
		casper.waitForText('Skip JVM MBeans');
		casper.then(function() {
			test.assertTextExists('Skip JVM MBeans', 'After navigating to the previous page, "Skip JVM beans" should be visible');
		});

		/*
		 * Verify that selected CompMembers do show up in the generated jmx-datacollection-config.xml snippet.
		 */
		casper.then(function() {
			var info = casper.getElementInfo('span#skipDefaultVM input[type="checkbox"]');
			test.assertTruthy(info.attributes.hasOwnProperty('checked'), 'Skip JVM MBeans should be checked');
			casper.click('span#skipDefaultVM input');
		});
		casper.wait(vaadinTax);
		casper.then(function() {
			var info = casper.getElementInfo('span#skipDefaultVM input[type="checkbox"]');
			test.assertTruthy(!info.attributes.hasOwnProperty('checked'), 'Skip JVM MBeans should not be checked');
			casper.click(nextButton);
		});
		casper.waitForText('com.mchange.v2.c3p0');
		// look for a few known entities in the OpenNMS and JVM beans
		casper.then(function() {
			test.assertTextExists('JMImplementation', 'JMImplementation should be in the MBean list');
			test.assertTextExists('HotSpotDiagnostic', 'HotSpotDiagnostic should be in the MBean list');
			test.assertTextExists('PS MarkSweep', 'PS MarkSweep should be in the MBean list');
			test.assertTextExists('org.apache.karaf', 'org.apache.karaf should be in the MBean list');
		});
		casper.then(function() {
			this.mouse.rightclick(x('//span[text()=\'OpenNMS\']'));
		});
		casper.wait(vaadinTax);
		casper.then(function() {
			casper.click(x('//td[@role="menuitem"]/div[text()=\'select\']'));
		});
		casper.then(function() {
			casper.click(nextButton);
		});
		casper.waitForText('collectd-configuration.xml');
		casper.then(function() {
			test.assertTextExists('collectd-configuration.xml', 'collectd-configuration.xml tab should exist');
			test.assertTextExists('jmx-datacollection-config.xml', 'jmx-datacollection-config.xml tab should exist');
			casper.clickLabel('jmx-datacollection-config.xml');
		});
		casper.waitForText('JMXMP protocol');
		casper.then(function() {
			var info = casper.fetchText('textarea');
			test.assertEquals(info.match(/\<mbeans\>/g).length, 1, 'There should be 1 <mbeans/> tags in jmx-datacollection-config.xml');
			test.assertEquals(info.match(/\<mbean /g).length, 24, 'There should be 24 <mbean/> tags in jmx-datacollection-config.xml');
			test.assertEquals(info.match(/\<attrib /g).length, 108, 'There should be 108 <attrib/> tags in jmx-datacollection-config.xml');
		});

		opennms.finished(test);
	}
});
<|endoftext|>


<commit_before>Accounts.oauth.registerService('linkedin');

if (Meteor.isClient) {
  Meteor.loginWithLinkedIn = function(options, callback) {
    // support a callback without options
    if (! callback && typeof options === "function") {
      callback = options;
      options = null;
    }
    var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
    LinkedIn.requestCredential(options, credentialRequestCompleteCallback);
  };
} else {
  Accounts.addAutopublishFields({
    forLoggedInUser: ['services.linkedin'],
  });
}

<commit_msg>#27 fix loginWithLinkedin<commit_after>Accounts.oauth.registerService('linkedin');

if (Meteor.isClient) {
  Meteor.loginWithLinkedin = function(options, callback) {
    // support a callback without options
    if (! callback && typeof options === "function") {
      callback = options;
      options = null;
    }
    var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
    LinkedIn.requestCredential(options, credentialRequestCompleteCallback);
  };
} else {
  Accounts.addAutopublishFields({
    forLoggedInUser: ['services.linkedin'],
  });
}

<|endoftext|>


<commit_before>(function(win, doc){
  'use strict';

  var
    getRootPath = function(){
      var parts = win.location.pathname.split('/');
      parts.shift(); // remove first
      parts.pop(); // remove last
      parts.pop(); // yes, twice
      var path = parts.join('/');
      return '/' + path;
    },
    root_http = getRootPath(),
    browser_plugin = 'filebrowser_upload',
    plugin_dir = root_http + '/externs/ckeditor/plugins/',
    openshift = 'http://filebrowser4openshift-jwalker.rhcloud.com',
    browser = new FileBrowser({
      root_http: openshift + '/server-side/writable',
      server_http: openshift + '/server-side/filebrowser.php',
    })
  ;
  CKEDITOR.plugins.addExternal(browser_plugin, plugin_dir + browser_plugin + '/');

  window.showUploadDialog = function(){
    browser.show();
  };
  var ckeditor = CKEDITOR.replace('editor', {
    extraPlugins: 'filebrowser_upload',
    toolbarGroups: [
      { name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'colors'] },
      { name: 'tools', groups: ['tools'] },
      { name: 'upload', groups: ['filebrowser'] }
    ]
  });
  browser.setEditor(ckeditor);

})(window, document);

<commit_msg>Add 'extraAllowedContent' to CKEditor config<commit_after>(function(win, doc){
  'use strict';

  var
    getRootPath = function(){
      var parts = win.location.pathname.split('/');
      parts.shift(); // remove first
      parts.pop(); // remove last
      parts.pop(); // yes, twice
      var path = parts.join('/');
      return '/' + path;
    },
    root_http = getRootPath(),
    browser_plugin = 'filebrowser_upload',
    plugin_dir = root_http + '/externs/ckeditor/plugins/',
    openshift = 'http://filebrowser4openshift-jwalker.rhcloud.com',
    browser = new FileBrowser({
      root_http: openshift + '/server-side/writable',
      server_http: openshift + '/server-side/filebrowser.php',
    })
  ;
  CKEDITOR.plugins.addExternal(browser_plugin, plugin_dir + browser_plugin + '/');

  window.showUploadDialog = function(){
    browser.show();
  };
  var ckeditor = CKEDITOR.replace('editor', {
    extraPlugins: 'filebrowser_upload',
    extraAllowedContent: 'img[src,alt,width,height]',
    toolbarGroups: [
      { name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'colors'] },
      { name: 'tools', groups: ['tools'] },
      { name: 'upload', groups: ['filebrowser'] }
    ]
  });
  browser.setEditor(ckeditor);

})(window, document);

<|endoftext|>


<commit_before>$(function () {
    var $friends = $('#friendsList');
    var $name = $('#name');
    var $age = $('#age');

    function addFriend(friend) {
        $friends.append('
Name: '+ friend.name +'
Age: ' + friend.age + '<button class="remove" data-id="' + friend.id + '"> X </button>
');
    }

    $.ajax( {
       type: 'GET',
        url: 'http://rest.learncode.academy/api/John/friends',
        success: function(friends) {
            $.each(friends, function(i, friend){
                addFriend(friend);
            });
        },
        error: function() {
            alert('error fetching date');
        }

    });
    $('#add-friend').on('click', function(){
        var friend = {
            name: $name.val(),
            age: $age.val()
        };
        $.ajax({
            type: 'POST',
            url: 'http://rest.learncode.academy/api/John/friends',
            data: friend,
            success: function(newFriend) {
                addFriend(newFriend);
            }
        })
    });

    $friends.delegate('.remove','click', function(){
        var $li = $(this).closest('li');
        $.ajax({
            type: 'DELETE',
            url: 'http://rest.learncode.academy/api/John/friends/' + $(this).attr('data-id'),
            success: function() {
                $li.remove();
            }
        })
    });

});<commit_msg>igin/master'.<commit_after>$(function () {
    var $friends = $('#friendsList');
    var $name = $('#name');
    var $age = $('#age');

    function addFriend(friend) {
        $friends.append('
Name: '+ friend.name +'
Age: ' + friend.age + '<button class="remove" data-id="' + friend.id + '"> X </button>
');
    }

    $.ajax( {
       type: 'GET',
        url: 'http://rest.learncode.academy/api/John/friends',
        success: function(friends) {
            $.each(friends, function(i, friend){
                addFriend(friend);
            });
        },
        error: function() {
            alert('error fetching date' + error);
        }

    });
    $('#add-friend').on('click', function(){
        var friend = {
            name: $name.val(),
            age: $age.val()
        };
        $.ajax({
            type: 'POST',
            url: 'http://rest.learncode.academy/api/John/friends',
            data: friend,
            success: function(newFriend) {
                addFriend(newFriend);
            }
        })
    });

    $friends.delegate('.remove','click', function(){
        var $li = $(this).closest('li');
        $.ajax({
            type: 'DELETE',
            url: 'http://rest.learncode.academy/api/John/friends/' + $(this).attr('data-id'),
            success: function() {
                $li.remove();
            }
        })
    });

});<|endoftext|>


<commit_before>/*Darrel Kathan*/
var cluster = require('cluster'),
	url = require('url'),
	fs = require('fs'),
	vm = require('vm'),
	os = require('os'),
	util = require('util'),
	path = require('path'),
	express = require('express'),
	cookieParser = require('cookie-parser'),
	app = express(),
	config_name = 'js-cgi.config',
	config,
	lconsole = {
		log:function(msg){
			util.log('('+process.pid+'): '+msg);
		},
		error:function(msg, stack){
			util.error('('+process.pid+'): '+msg, stack);
		}
	},
	error = function(err) {
		lconsole.error('Error:'+err);
	};

app.use(cookieParser());

if(fs.existsSync(path.join(__dirname, config_name))){
	//Load the congfig file
	lconsole.log('Loading '+config_name+'...');
	config = require('./'+config_name);
}else{
	//Use the default congfig
	lconsole.log('Loading default config...');
	config = {
		port:3000,
		localhostOnly:true,
		//workers:2,
		timeout:30000
	};
	config.workers = (os.cpus().length/2)-1;//For some reason cpus.length is reports twice as many cores than actual.
}

if (cluster.isMaster) {
	cluster.globals = {};
	cluster.fork();//At least one worker is required.

	for(var w = 2; w <= config.workers;w++){
		cluster.fork().on('error', error);
	}

	cluster.on('disconnect', function(worker) {
		lconsole.error('disconnect!');
		cluster.fork().on('error', error);
	});
} else {
	// the worker
	var domain = require('domain'),
		server,
		d = domain.create();

	d.on('error', function(er) {
		lconsole.error('error', er.stack);
		try {
			// make sure we close down if it times out
			var killtimer = setTimeout(function() {
				lconsole.error('Killing process. Timeout expired ('+config.timeout+' ms)');
				return process.exit(1);
			}, config.timeout);
			// But don't keep the process open just for that!
			killtimer.unref();

			// stop taking new requests.
			server.close();

			// Let the master know we're dead.  This will trigger a
			// 'disconnect' in the cluster master, and then it will fork
			// a new worker.
			cluster.worker.disconnect();
		} catch (er2) {
			// oh well, not much we can do at this point.
			lconsole.error(er2.stack);
		}
	});

    // Now run the handler function in the domain.
    d.run(function() {
		lconsole.log('Listening on '+config.port);

		server = app.listen(config.port);

		app.all('*', function(req, res){
			//console.log('req');
			return handleRequest(req, res);
		});
	});
}

function handleRequestScript(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }

  function myRequire(name) {
    return require(resolveModule(name));
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
    	fs.readFile(file_path, function(err, content){
	      try{
	      	var path_dir = file_path.split("/");
	      	path_dir.pop();
	      	path_dir = path_dir.join('/');
	      	//console.log(path_dir);
	      	process.chdir(path_dir);
	      	//console.log(process.cwd());
	      	var script = Function('req', 'res', 'globals', 'require', content);
	      	//console.log(script.toString());
	      	lconsole.log(file_path);
	      	script(req, res, cluster.globals, myRequire);

	      }catch(err){
	      	res.writeHead(500);
	      	lconsole.error(err.stack)
	      	res.end(err+' in '+file_path);
	      }
	    });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      res.end('File '+file_path+' not found.');
    }
  });
}

function handleRequestRequire(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      var script = require(file_path);
      if(typeof script === 'function'){
      	script(req, res, cluster.globals);
      }else{
      	res.writeHead(500);
      	return res.send('Script is not configured correctly.');
      }
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File '+file_path+' not found.');
    }
  });
}

function handleRequestRIC(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }
  //console.log('file_path:'+file_path);
  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }
  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      fs.readFile(file_path, function (err, source) {
        if(err){
          //Error reading file
          lconsole.error(err, err.stack);
          res.writeHead(500, err);
          return res.send(err.toString());
        }
        try{
          //console.log('filename:'+file_path);

          var script = vm.createScript('try{\n'+source+'\n}catch(err){console.error(err, err.stack);res.writeHead(500);res.end(err.toString());}');
          //console.log('pre execute:'+g);
          var sandbox = {
                  //globals: globals,
                  console: lconsole,
                  require: function(name) {
                           return require(resolveModule(name));
                       },
                req: req,
                res: res,
                displayErrors: true
            };

          return script.runInNewContext(sandbox);

        }catch(err){
          lconsole.error(err, err.stack);
          res.writeHead(500);
          return res.send(err.toString());
        }
      });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File not found.');
    }
  });
}

function handleRequest(req, res) {
	var url_obj = url.parse(req.url, true),
		file_path;
	/*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
		//res.writeHead(401);
		res.end(401);
	}*/

	if(req.headers.path_translated && url_obj.pathname){
		file_path = req.headers.path_translated+url_obj.pathname;
	}else{
		file_path = url_obj.pathname;
	}

	//console.log('file_path:'+file_path);
	function resolveModule(module) {
		if (module.charAt(0) !== '.'){
			//console.log('No need to resolve '+module);
			return module;
		}
		//console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
		return path.resolve(path.dirname(file_path), module);
	}

	//If the requested file exists...
	fs.exists(file_path, function(exists){
		if(exists){
			fs.readFile(file_path, function (err, source) {
				if(err){
					//Error reading file
					lconsole.error(err, err.stack);
					res.writeHead(500, err);
					return res.send(err.toString());
				}
				try{
					lconsole.log('Request: '+file_path);

					var sandbox = {
						//globals: globals,
						console: lconsole,
						setImmediate: setImmediate,
						require: function(name) {
							return require(resolveModule(name));
						},
						req: req,
						res: res
					};
					var c = vm.createContext(sandbox);

					return vm.runInContext(source, c, {displayErrors: true});
				}catch(err){
					lconsole.error(err, err.stack);
					//res.writeHead(500);
					return res.status(500).send(err.toString());
				}
			});
		}else{
			//File does not exist
			//res.writeHead(404, 'File not found.');
			return res.status(404).send('File not found.');
		}
	});
}<commit_msg>CI Wed Sep  2 12:38:57 CDT 2015<commit_after>/*Darrel Kathan*/
var cluster = require('cluster'),
	url = require('url'),
	fs = require('fs'),
	vm = require('vm'),
	os = require('os'),
	util = require('util'),
	path = require('path'),
	express = require('express'),
	cookieParser = require('cookie-parser'),
	app = express(),
	config_name = 'js-cgi.config',
	config = {},
	lconsole = {
		log: function(msg){
			var log_msg = '('+process.pid+'): '+msg;
			util.log(log_msg);
			if(config.output_log){
				fs.appendFile(config.output_log, log_msg+'\n', function(){});
			}
		},
		error: function(msg, stack){
			var log_msg = '('+process.pid+'): '+msg;
			util.error(log_msg, stack);
			if(config.output_log){
				fs.appendFile(config.output_log, log_msg+'\n', function(){});
			}
		}
	},
	error = function(err) {
		lconsole.error('Error:'+err);
	};

app.use(cookieParser());
app.set('json spaces', 4);

config.output_log = path.dirname(process.argv[1])+'/js-cgi.log';
//console.log(config.output_log);
if(fs.existsSync(path.join(__dirname, config_name))){
	//Load the congfig file
	lconsole.log('Loading '+config_name+'...');
	config = require('./'+config_name);
}else{
	//Use the default congfig
	lconsole.log('Loading default config...');
	config.port = 3000;
	config.localhostOnly = true;
	//config.workers = 2;
	config.timeout = 30000;
	config.workers = (os.cpus().length/2)-1;//For some reason cpus.length is reports twice as many cores than actual.
}

if (cluster.isMaster) {
	cluster.globals = {};
	cluster.fork();//At least one worker is required.

	for(var w = 2; w <= config.workers;w++){
		cluster.fork().on('error', error);
	}

	cluster.on('disconnect', function(worker) {
		lconsole.error('disconnect!');
		cluster.fork().on('error', error);
	});
} else {
	// the worker
	var domain = require('domain'),
		server,
		d = domain.create();

	d.on('error', function(er) {
		lconsole.error('error', er.stack);
		try {
			// make sure we close down if it times out
			var killtimer = setTimeout(function() {
				lconsole.error('Killing process. Timeout expired ('+config.timeout+' ms)');
				return process.exit(1);
			}, config.timeout);
			// But don't keep the process open just for that!
			killtimer.unref();

			// stop taking new requests.
			server.close();

			// Let the master know we're dead.  This will trigger a
			// 'disconnect' in the cluster master, and then it will fork
			// a new worker.
			cluster.worker.disconnect();
		} catch (er2) {
			// oh well, not much we can do at this point.
			lconsole.error(er2.stack);
		}
	});

    // Now run the handler function in the domain.
    d.run(function() {
		lconsole.log('Listening on '+config.port);

		server = app.listen(config.port);

		app.all('*', function(req, res){
			//console.log('req');
			return handleRequest(req, res);
		});
	});
}

function clearRequiredCache(name){

}

function setRequiredCacheTimestamp(name){
	if(require.cache[process.execPath][name]){
		return require.cache[process.execPath][name];
	}
}

function handleRequestScript(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }

  function myRequire(name) {
    return require(resolveModule(name));
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
    	fs.readFile(file_path, function(err, content){
	      try{
	      	var path_dir = file_path.split("/");
	      	path_dir.pop();
	      	path_dir = path_dir.join('/');
	      	//console.log(path_dir);
	      	process.chdir(path_dir);
	      	//console.log(process.cwd());
	      	var script = Function('req', 'res', 'globals', 'require', content);
	      	//console.log(script.toString());
	      	lconsole.log(file_path);
	      	script(req, res, cluster.globals, myRequire);

	      }catch(err){
	      	res.writeHead(500);
	      	lconsole.error(err.stack)
	      	res.end(err+' in '+file_path);
	      }
	    });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      res.end('File '+file_path+' not found.');
    }
  });
}

function handleRequestRequire(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }

  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      var script = require(file_path);
      if(typeof script === 'function'){
      	script(req, res, cluster.globals);
      }else{
      	res.writeHead(500);
      	return res.send('Script is not configured correctly.');
      }
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File '+file_path+' not found.');
    }
  });
}

function handleRequestRIC(req, res) {
  var url_obj = url.parse(req.url, true);
  /*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
    //res.writeHead(401);
    res.end(401);
  }*/

  var file_path;
  if(req.headers.path_translated && url_obj.pathname){
    file_path = req.headers.path_translated+url_obj.pathname;
  }else{
    file_path = url_obj.pathname;
  }
  //console.log('file_path:'+file_path);
  function resolveModule(module) {
    if (module.charAt(0) !== '.'){
      //console.log('No need to resolve '+module);
      return module;
    }
    //console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
    return path.resolve(path.dirname(file_path), module);
  }
  //If the requested file exists...
  fs.exists(file_path, function(exists){
    if(exists){
      fs.readFile(file_path, function (err, source) {
        if(err){
          //Error reading file
          lconsole.error(err, err.stack);
          res.writeHead(500, err);
          return res.send(err.toString());
        }
        try{
          //console.log('filename:'+file_path);

          var script = vm.createScript('try{\n'+source+'\n}catch(err){console.error(err, err.stack);res.writeHead(500);res.end(err.toString());}');
          //console.log('pre execute:'+g);
          var sandbox = {
                  //globals: globals,
                  console: lconsole,
                  require: function(name) {
                           return require(resolveModule(name));
                       },
                req: req,
                res: res,
                displayErrors: true
            };

          return script.runInNewContext(sandbox);

        }catch(err){
          lconsole.error(err, err.stack);
          res.writeHead(500);
          return res.send(err.toString());
        }
      });
    }else{
      //File does not exist
      res.writeHead(404, 'File not found.');
      return res.send('File not found.');
    }
  });
}

function handleRequest(req, res) {
	var url_obj = url.parse(req.url, true),
		file_path;
	/*if(config.localhostOnly && req.connection.remoteAddress !== '127.0.0.1'){
		//res.writeHead(401);
		res.end(401);
	}*/

	if(req.headers.path_translated && url_obj.pathname){
		file_path = req.headers.path_translated+url_obj.pathname;
	}else{
		file_path = url_obj.pathname;
	}

	//console.log('file_path:'+file_path);
	function resolveModule(module) {
		if (module.charAt(0) !== '.'){
			//console.log('No need to resolve '+module);
			return module;
		}
		//console.log('Resolved '+module+' to '+path.resolve(path.dirname(file_path), module));
		return path.resolve(path.dirname(file_path), module);
	}

	//If the requested file exists...
	fs.exists(file_path, function(exists){
		if(exists){
			fs.readFile(file_path, function (err, source) {
				if(err){
					//Error reading file
					lconsole.error(err, err.stack);
					res.writeHead(500, err);
					return res.send(err.toString());
				}
				try{
					lconsole.log('Request: '+file_path);
					//console.log(require.cache);
					var sandbox = {
						//globals: globals,
						console: lconsole,
						setImmediate: setImmediate,
						require: function(name) {
							return require(resolveModule(name));
						},
						req: req,
						res: res
					};
					var c = vm.createContext(sandbox);

					return vm.runInContext(source, c, {displayErrors: true});
				}catch(err){
					lconsole.error(err, err.stack);
					//res.writeHead(500);
					return res.status(500).send(err.toString());
				}
			});
		}else{
			//File does not exist
			//res.writeHead(404, 'File not found.');
			return res.status(404).send('File not found.');
		}
	});
}
<|endoftext|>


<commit_before>var repoExp = new RegExp("^https://github.com/([^/]+)/([^/]+)(/(tree|blob)/([^/]+)(/(.*))?)?");
var resolveUrl = function(repoUrl){
    if(typeof repoUrl != 'string') return;
    var matches = repoUrl.match(repoExp);
    if(matches && matches.length > 0){
        var root = (matches[5])?
            "https://github.com/" + matches[1] + "/" + matches[2] + "/tree/" + matches[5] :
            repoUrl;
        return {
            author: matches[1],
            project: matches[2],
            branch: matches[5],
            type: matches[4],
            path: matches[7] || '',
            inputUrl: repoUrl,
            rootUrl: root
        };
    }
};
var createURL = function(pathToFolder){
    var resolved = resolveUrl(pathToFolder);
    if(!resolved){
        throw "INVALID URL"
    }
    if(!resolved.path){
        // root
        var durl = [
            "https://github.com", resolved.author, resolved.project,
            "archive", (resolved.branch || 'master')
        ].join('/');
        var gitURL = durl + ".zip";
        downloadZip(gitURL);
    } else{
        // get up level url
        var originInput = resolved.inputUrl;
        if(resolved.type == "tree"){
            var news = originInput.split('/');
            news.pop();
            resolved = resolveUrl(news.join('/'));
        }
        $.ajax({
            url: "https://api.github.com/repos/"+ resolved.author +
                "/" + resolved.project + "/contents/" + resolved.path +
                (resolved.branch? ("?ref=" + resolved.branch) : ""),
            success: function(results) {
                var templateText = '';
                if(!Array.isArray(results)){
                    if(results.message) throw ("Error: " +  results.message);
                    else{
                        var gitURL = results.download_url;
                        downloadZip(btn);
                    };
                    return;
                }
                for(var i = 0, len = results.length; i < len; i++){
                    var item = results[i];
                    if(item.type == "dir" && item.html_url == originInput){
                        var valueText = item.path
                        var pathText = valueText.split('/').pop()
                        var urlText = item.git_url;
                        zipIt(pathText, urlText)
                        break;
                    }
                }
            },
            error: function(results){
                throw (JSON.stringify(results));
            }
        });
    }
}
var downloadZip = function(url){
    if(url){
        var down = document.createElement('a');
        down.setAttribute('download', true);
        down.href = url;
        down.addEventListener('click', function(e){ return; });
        setTimeout(function(){
            down.click();
        },100);
    }
}
var zipIt = function(zipName, url){
    if(url){
		$.ajax({
			url: url + "?recursive=1",
            success: function(results){
                var promises = [];
                var fileContents = [];
                if(results.truncated){
                    throw ("The tree travels is over than API limitation (500 files)");
                    return;
                };
                results.tree.forEach(function(item){
                    if(item.type == "blob"){
                        promises.push(Promise.resolve(
                            $.ajax({
                                url: item.url,
                                success: (function(path){
                                    return function(results){
                                        fileContents.push({path:path,content:results.content});
                                    };
                                })(item.path)
                            })
                        ));
                    }
                });
                Promise.all(promises).then(function() {
                    var zip = new JSZip();
                    fileContents.forEach(function(item){
                        zip.file(item.path, item.content, {createFolders:true,base64:true});
                    });
                    saveAs(zip.generate({type:"blob"}), zipName + ".zip");
                },function(item){
                    if(item) throw (JSON.stringify(item) + " ERROR");
                });
            },
            error:function(e){
                throw (e);
            }
        })
    }
}<commit_msg>Add progress callback; Fix bugs and rename api names.<commit_after>(function(scope){
    function fn(){};

    var repoExp = new RegExp("^https://github.com/([^/]+)/([^/]+)(/(tree|blob)/([^/]+)(/(.*))?)?");
    var githubProvidedUrl = new RegExp("^https://api.github.com/.*");
    var isBusy = false;

    var statusHandle = function(status){
        if(status == 'error' || status == 'done') isBusy = false;
        else isBusy = true;
    };

    /**
     * @typedef ResolvedURL
     * @type Object
     * @property {string} author - The project owner
     * @property {string} project - The project name
     * @property {string} branch - The default branch or other branches
     * @property {string} type - The type of url link, values: tree, blob, link?
     * @property {string} path - The path of target file/dir based on root repo url.
     * @property {string} inputUrl - The input url
     * @property {string} rootUrl - The root dir url
     */

    /**
     * This callback would call by each progress changes.
     * @callback progressCallback
     * @param {string} status - indicates the status description like 'error', 'prepare', 'processing', 'done'
     * @param {string} message - the messages of the above status.
     * @param {number} percent - from 0 to 100, indicates the progress percentage.
     */
    var progressCallback = function(status, message, percent){};

    /**
     * Resolve the github repo url for recognize author, project name, branch name, and so on.
     * @private
     * @param {string} repoUrl - The github repo url.
     * @param {ResolvedURL}
     */
    function resolveUrl(repoUrl){
        if(typeof repoUrl != 'string') return;
        var matches = repoUrl.match(repoExp);
        if(matches && matches.length > 0){
            var root = (matches[5])?
                "https://github.com/" + matches[1] + "/" + matches[2] + "/tree/" + matches[5] :
                repoUrl;
            return {
                author: matches[1],
                project: matches[2],
                branch: matches[5],
                type: matches[4],
                path: matches[7] || '',
                inputUrl: repoUrl,
                rootUrl: root
            };
        }
    }

    /**
     * Force to trigger download dialog for any mine-type files.
     * @param {string} url - The URL.
     * @param {object|undefined} callbackScope - The scope of the progressCallback function.
     */
    function downloadZip(url, callbackScope){
        callbackScope = callbackScope || scope;
        if(url){
            progressCallback.call(callbackScope, 'processing', 'Fetching target url: ' + url);
            var down = document.createElement('a');
            down.setAttribute('download', true);
            down.href = url;
            down.addEventListener('click', function(e){
                progressCallback.call(callbackScope, 'done', 'Saving File.');
            });
            setTimeout(function(){
                down.click();
            },100);
        }
    }

    /**
     * Download zip file from github api url.
     * @param {string} zipName - The zip file name.
     * @param {string} url - The github api url.
     * @param {object|undefined} callbackScope - The scope of the progressCallback function.
     */
    function zipIt(zipName, url, callbackScope){
        callbackScope = callbackScope || scope;
        if(url && githubProvidedUrl.test(url)){
            progressCallback.call(callbackScope, 'prepare', 'Fetching list of Dir contains files.');
            $.ajax({
                url: url + "?recursive=1",
                success: function(results){
                    var promises = [];
                    var fileContents = [];
                    if(results.truncated){
                        progressCallback.call(callbackScope, 'error', 'The tree travels is over than API limitation (500 files)');
                        throw ("The tree travels is over than API limitation (500 files)");
                    };
                    progressCallback._idx = 0;
                    progressCallback._len = 0;
                    results.tree.forEach(function(item){
                        if(item.type == "blob") progressCallback._len++;
                    });
                    results.tree.forEach(function(item){
                        if(item.type == "blob"){
                            promises.push(Promise.resolve(
                                $.ajax({
                                    url: item.url,
                                    success: (function(path){
                                        return function(results){
                                            fileContents.push({path:path,content:results.content});
                                            progressCallback.call(callbackScope, 'processing', 'Fetched ' + path,
                                                ++progressCallback._idx / (progressCallback._len * 2) * 100);
                                        };
                                    })(item.path)
                                })
                            ));
                        }
                    });

                    Promise.all(promises).then(function() {
                        var zip = new JSZip();
                        fileContents.forEach(function(item){
                            progressCallback.call(callbackScope, 'processing', 'Compressing ' + item.path,
                                ++progressCallback._idx / (progressCallback._len * 2) * 100);
                            zip.file(item.path, item.content, {createFolders:true,base64:true});
                        });
                        saveAs(zip.generate({type:"blob"}), zipName + ".zip");
                        progressCallback.call(callbackScope, 'done', 'Saving ' + zipName + '.zip');
                    },function(item){
                        if(item){
                            progressCallback.call(callbackScope, 'error', 'Error: ' + JSON.stringify(item));
                            throw (JSON.stringify(item) + " ERROR");
                        }
                    });
                },
                error:function(e){
                    progressCallback.call(callbackScope, 'error', 'Error: ' + e);
                    throw (e);
                }
            });
        }
    }

    /**
     * Download zip for single file from input repo URL.
     * @param {string} pathToFolder - The URL of the Github repository.
     * @param {object|undefined} callbackScope - The scope of the progressCallback function.
     */
    function createURL(pathToFolder, callbackScope){
        if(isBusy) throw "GitZip is busy...";
        callbackScope = callbackScope || scope;
        progressCallback.call(callbackScope, 'prepare', 'Resolving URL');
        var resolved = resolveUrl(pathToFolder);
        if(!resolved){
            progressCallback.call(callbackScope, 'error', 'Invalid URL: value is [' + pathToFolder.toString() + ']');
            throw "INVALID URL";
        }
        if(!resolved.path){
            // root
            var durl = [
                "https://github.com", resolved.author, resolved.project,
                "archive", (resolved.branch || 'master')
            ].join('/');
            var gitURL = durl + ".zip";
            downloadZip(gitURL, callbackScope);
        } else{
            // get up level url
            var originInput = resolved.inputUrl;
            if(resolved.type == "tree"){
                var news = originInput.split('/');
                news.pop();
                resolved = resolveUrl(news.join('/'));
            }
            progressCallback.call(callbackScope, 'prepare', 'Finding file/dir content path from resolved URL');
            $.ajax({
                url: "https://api.github.com/repos/"+ resolved.author +
                    "/" + resolved.project + "/contents/" + resolved.path +
                    (resolved.branch? ("?ref=" + resolved.branch) : ""),
                success: function(results) {
                    var templateText = '';
                    if(!Array.isArray(results)){
                        if(results.message){
                            progressCallback.call(callbackScope, 'error', 'Github said: '+results.message);
                            throw ("Error: " +  results.message);
                        }else downloadZip(results.download_url, callbackScope);
                        return;
                    }
                    for(var i = 0, len = results.length; i < len; i++){
                        var item = results[i];
                        // target has found
                        if(item.type == "dir" && item.html_url == originInput){
                            var valueText = item.path;
                            var pathText = valueText.split('/').pop();
                            var urlText = item.git_url;
                            zipIt(pathText, urlText, callbackScope);
                            break;
                        }
                        if(i + 1 == len){
                            progressCallback.call(callbackScope, 'error', 'File/Dir content not found.');
                        }
                    }
                },
                error: function(results){
                    progressCallback.call(callbackScope, 'error', 'Github said: ' + JSON.stringify(results));
                    throw (JSON.stringify(results));
                }
            });
        }
    }

    /**
     * Register the progress callback for handleing the progress is changing.
     * @param {progressCallback} inputFn - The progress callback.
     */
    function registerCallback(inputFn){
        if(typeof inputFn == 'function'){
            // progressCallback = callback;
            progressCallback = function(){
                inputFn.apply(this, arguments);
                statusHandle.apply(this, arguments);
            };
        }
    }

    fn.zipRepo = createURL;
    fn.zipFromApiUrl = zipIt;
    fn.downloadFile = downloadZip;
    fn.registerCallback = registerCallback;

    scope.GitZip = fn;

})(window);
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError, OrderNotFound } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class acx extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'acx',
            'name': 'ACX',
            'countries': 'AU',
            'rateLimit': 1000,
            'version': 'v2',
            'hasCORS': true,
            'hasFetchTickers': true,
            'hasFetchOHLCV': true,
            'hasWithdraw': true,
            'timeframes': {
                '1m': '1',
                '5m': '5',
                '15m': '15',
                '30m': '30',
                '1h': '60',
                '2h': '120',
                '4h': '240',
                '12h': '720',
                '1d': '1440',
                '3d': '4320',
                '1w': '10080',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/30247614-1fe61c74-9621-11e7-9e8c-f1a627afa279.jpg',
                'extension': '.json',
                'api': 'https://acx.io/api',
                'www': 'https://acx.io',
                'doc': 'https://acx.io/documents/api_v2',
            },
            'api': {
                'public': {
                    'get': [
                        'markets', // Get all available markets
                        'tickers', // Get ticker of all markets
                        'tickers/{market}', // Get ticker of specific market
                        'trades', // Get recent trades on market, each trade is included only once Trades are sorted in reverse creation order.
                        'order_book', // Get the order book of specified market
                        'depth', // Get depth or specified market Both asks and bids are sorted from highest price to lowest.
                        'k', // Get OHLC(k line) of specific market
                        'k_with_pending_trades', // Get K data with pending trades, which are the trades not included in K data yet, because there's delay between trade generated and processed by K data generator
                        'timestamp', // Get server current time, in seconds since Unix epoch
                    ],
                },
                'private': {
                    'get': [
                        'members/me', // Get your profile and accounts info
                        'deposits', // Get your deposits history
                        'deposit', // Get details of specific deposit
                        'deposit_address', // Where to deposit The address field could be empty when a new address is generating (e.g. for bitcoin), you should try again later in that case.
                        'orders', // Get your orders, results is paginated
                        'order', // Get information of specified order
                        'trades/my', // Get your executed trades Trades are sorted in reverse creation order.
                        'withdraws', // Get your cryptocurrency withdraws
                        'withdraw', // Get your cryptocurrency withdraw
                    ],
                    'post': [
                        'orders', // Create a Sell/Buy order
                        'orders/multi', // Create multiple sell/buy orders
                        'orders/clear', // Cancel all my orders
                        'order/delete', // Cancel an order
                        'withdraw', // Create a withdraw
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': false,
                    'percentage': true,
                    'maker': 0.0,
                    'taker': 0.0,
                },
                'funding': {
                    'tierBased': false,
                    'percentage': true,
                    'withdraw': 0.0, // There is only 1% fee on withdrawals to your bank account.
                },
            },
        });
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets.length; p++) {
            let market = markets[p];
            let id = market['id'];
            let symbol = market['name'];
            let [ base, quote ] = symbol.split ('/');
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetMembersMe ();
        let balances = response['accounts'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let currency = balance['currency'];
            let uppercase = currency.toUpperCase ();
            let account = {
                'free': parseFloat (balance['balance']),
                'used': parseFloat (balance['locked']),
                'total': 0.0,
            };
            account['total'] = this.sum (account['free'], account['used']);
            result[uppercase] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let orderbook = await this.publicGetDepth (this.extend ({
            'market': market['id'],
            'limit': 300,
        }, params));
        let timestamp = orderbook['timestamp'] * 1000;
        let result = this.parseOrderBook (orderbook, timestamp);
        result['bids'] = this.sortBy (result['bids'], 0, true);
        result['asks'] = this.sortBy (result['asks'], 0);
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['at'] * 1000;
        ticker = ticker['ticker'];
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high', undefined),
            'low': this.safeFloat (ticker, 'low', undefined),
            'bid': this.safeFloat (ticker, 'buy', undefined),
            'ask': this.safeFloat (ticker, 'sell', undefined),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': this.safeFloat (ticker, 'last', undefined),
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'vol', undefined),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetTickers (params);
        let ids = Object.keys (tickers);
        let result = {};
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let market = undefined;
            let symbol = id;
            if (id in this.markets_by_id) {
                market = this.markets_by_id[id];
                symbol = market['symbol'];
            } else {
                let base = id.slice (0, 3);
                let quote = id.slice (3, 6);
                base = base.toUpperCase ();
                quote = quote.toUpperCase ();
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            let ticker = tickers[id];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTickersMarket (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTicker (response, market);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        return {
            'id': trade['id'].toString (),
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': undefined,
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'volume'),
            'cost': this.safeFloat (trade, 'funds'),
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTrades (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
        return [
            ohlcv[0] * 1000,
            ohlcv[1],
            ohlcv[2],
            ohlcv[3],
            ohlcv[4],
            ohlcv[5],
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        if (!limit)
            limit = 500; // default is 30
        let request = {
            'market': market['id'],
            'period': this.timeframes[timeframe],
            'limit': limit,
        };
        if (since)
            request['timestamp'] = since;
        let response = await this.publicGetK (this.extend (request, params));
        return this.parseOHLCVs (response, market, timeframe, since, limit);
    }

    parseOrder (order, market = undefined) {
        let symbol = undefined;
        if (market) {
            symbol = market['symbol'];
        } else {
            let marketId = order['market'];
            symbol = this.marketsById[marketId]['symbol'];
        }
        let timestamp = this.parse8601 (order['created_at']);
        let state = order['state'];
        let status = undefined;
        if (state === 'done') {
            status = 'closed';
        } else if (state === 'wait') {
            status = 'open';
        } else if (state === 'cancel') {
            status = 'canceled';
        }
        return {
            'id': order['id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'status': status,
            'symbol': symbol,
            'type': order['ord_type'],
            'side': order['side'],
            'price': parseFloat (order['price']),
            'amount': parseFloat (order['volume']),
            'filled': parseFloat (order['executed_volume']),
            'remaining': parseFloat (order['remaining_volume']),
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let order = {
            'market': this.marketId (symbol),
            'side': side,
            'volume': amount.toString (),
            'ord_type': type,
        };
        if (type === 'limit') {
            order['price'] = price.toString ();
        }
        let response = await this.privatePostOrders (this.extend (order, params));
        let market = this.marketsById[response['market']];
        return this.parseOrder (response, market);
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let result = await this.privatePostOrderDelete ({ 'id': id });
        let order = this.parseOrder (result);
        if (order['status'] === 'closed') {
            throw new OrderNotFound (this.id + ' ' + result);
        }
        return order;
    }

    async withdraw (currency, amount, address, params = {}) {
        await this.loadMarkets ();
        let result = await this.privatePostWithdraw (this.extend ({
            'currency': currency.toLowerCase (),
            'sum': amount,
            'address': address,
        }, params));
        return {
            'info': result,
            'id': undefined,
        };
    }

    nonce () {
        return this.milliseconds ();
    }

    encodeParams (params) {
        if ('orders' in params) {
            let orders = params['orders'];
            let query = this.urlencode (this.keysort (this.omit (params, 'orders')));
            for (let i = 0; i < orders.length; i++) {
                let order = orders[i];
                let keys = Object.keys (order);
                for (let k = 0; k < keys.length; k++) {
                    let key = keys[k];
                    let value = order[key];
                    query += '&orders%5B%5D%5B' + key + '%5D=' + value.toString ();
                }
            }
            return query;
        }
        return this.urlencode (this.keysort (params));
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = '/api' + '/' + this.version + '/' + this.implodeParams (path, params);
        if ('extension' in this.urls)
            request += this.urls['extension'];
        let query = this.omit (params, this.extractParams (path));
        let url = this.urls['api'] + request;
        if (api === 'public') {
            if (Object.keys (query).length) {
                url += '?' + this.urlencode (query);
            }
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.encodeParams (this.extend ({
                'access_key': this.apiKey,
                'tonce': nonce,
            }, params));
            let auth = method + '|' + request + '|' + query;
            let signature = this.hmac (this.encode (auth), this.encode (this.secret));
            let suffix = query + '&signature=' + signature;
            if (method === 'GET') {
                url += '?' + suffix;
            } else {
                body = suffix;
                headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
            }
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('error' in response)
            throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
}
<commit_msg>acx withdraw tag and linting #1313<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError, OrderNotFound } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class acx extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'acx',
            'name': 'ACX',
            'countries': 'AU',
            'rateLimit': 1000,
            'version': 'v2',
            'hasCORS': true,
            'hasFetchTickers': true,
            'hasFetchOHLCV': true,
            'hasWithdraw': true,
            'timeframes': {
                '1m': '1',
                '5m': '5',
                '15m': '15',
                '30m': '30',
                '1h': '60',
                '2h': '120',
                '4h': '240',
                '12h': '720',
                '1d': '1440',
                '3d': '4320',
                '1w': '10080',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/30247614-1fe61c74-9621-11e7-9e8c-f1a627afa279.jpg',
                'extension': '.json',
                'api': 'https://acx.io/api',
                'www': 'https://acx.io',
                'doc': 'https://acx.io/documents/api_v2',
            },
            'api': {
                'public': {
                    'get': [
                        'markets', // Get all available markets
                        'tickers', // Get ticker of all markets
                        'tickers/{market}', // Get ticker of specific market
                        'trades', // Get recent trades on market, each trade is included only once Trades are sorted in reverse creation order.
                        'order_book', // Get the order book of specified market
                        'depth', // Get depth or specified market Both asks and bids are sorted from highest price to lowest.
                        'k', // Get OHLC(k line) of specific market
                        'k_with_pending_trades', // Get K data with pending trades, which are the trades not included in K data yet, because there's delay between trade generated and processed by K data generator
                        'timestamp', // Get server current time, in seconds since Unix epoch
                    ],
                },
                'private': {
                    'get': [
                        'members/me', // Get your profile and accounts info
                        'deposits', // Get your deposits history
                        'deposit', // Get details of specific deposit
                        'deposit_address', // Where to deposit The address field could be empty when a new address is generating (e.g. for bitcoin), you should try again later in that case.
                        'orders', // Get your orders, results is paginated
                        'order', // Get information of specified order
                        'trades/my', // Get your executed trades Trades are sorted in reverse creation order.
                        'withdraws', // Get your cryptocurrency withdraws
                        'withdraw', // Get your cryptocurrency withdraw
                    ],
                    'post': [
                        'orders', // Create a Sell/Buy order
                        'orders/multi', // Create multiple sell/buy orders
                        'orders/clear', // Cancel all my orders
                        'order/delete', // Cancel an order
                        'withdraw', // Create a withdraw
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': false,
                    'percentage': true,
                    'maker': 0.0,
                    'taker': 0.0,
                },
                'funding': {
                    'tierBased': false,
                    'percentage': true,
                    'withdraw': 0.0, // There is only 1% fee on withdrawals to your bank account.
                },
            },
        });
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets.length; p++) {
            let market = markets[p];
            let id = market['id'];
            let symbol = market['name'];
            let [ base, quote ] = symbol.split ('/');
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetMembersMe ();
        let balances = response['accounts'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let currency = balance['currency'];
            let uppercase = currency.toUpperCase ();
            let account = {
                'free': parseFloat (balance['balance']),
                'used': parseFloat (balance['locked']),
                'total': 0.0,
            };
            account['total'] = this.sum (account['free'], account['used']);
            result[uppercase] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let orderbook = await this.publicGetDepth (this.extend ({
            'market': market['id'],
            'limit': 300,
        }, params));
        let timestamp = orderbook['timestamp'] * 1000;
        let result = this.parseOrderBook (orderbook, timestamp);
        result['bids'] = this.sortBy (result['bids'], 0, true);
        result['asks'] = this.sortBy (result['asks'], 0);
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['at'] * 1000;
        ticker = ticker['ticker'];
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high', undefined),
            'low': this.safeFloat (ticker, 'low', undefined),
            'bid': this.safeFloat (ticker, 'buy', undefined),
            'ask': this.safeFloat (ticker, 'sell', undefined),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': this.safeFloat (ticker, 'last', undefined),
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'vol', undefined),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetTickers (params);
        let ids = Object.keys (tickers);
        let result = {};
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let market = undefined;
            let symbol = id;
            if (id in this.markets_by_id) {
                market = this.markets_by_id[id];
                symbol = market['symbol'];
            } else {
                let base = id.slice (0, 3);
                let quote = id.slice (3, 6);
                base = base.toUpperCase ();
                quote = quote.toUpperCase ();
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            let ticker = tickers[id];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTickersMarket (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTicker (response, market);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        return {
            'id': trade['id'].toString (),
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': undefined,
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'volume'),
            'cost': this.safeFloat (trade, 'funds'),
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTrades (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
        return [
            ohlcv[0] * 1000,
            ohlcv[1],
            ohlcv[2],
            ohlcv[3],
            ohlcv[4],
            ohlcv[5],
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        if (!limit)
            limit = 500; // default is 30
        let request = {
            'market': market['id'],
            'period': this.timeframes[timeframe],
            'limit': limit,
        };
        if (since)
            request['timestamp'] = since;
        let response = await this.publicGetK (this.extend (request, params));
        return this.parseOHLCVs (response, market, timeframe, since, limit);
    }

    parseOrder (order, market = undefined) {
        let symbol = undefined;
        if (market) {
            symbol = market['symbol'];
        } else {
            let marketId = order['market'];
            symbol = this.marketsById[marketId]['symbol'];
        }
        let timestamp = this.parse8601 (order['created_at']);
        let state = order['state'];
        let status = undefined;
        if (state === 'done') {
            status = 'closed';
        } else if (state === 'wait') {
            status = 'open';
        } else if (state === 'cancel') {
            status = 'canceled';
        }
        return {
            'id': order['id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'status': status,
            'symbol': symbol,
            'type': order['ord_type'],
            'side': order['side'],
            'price': parseFloat (order['price']),
            'amount': parseFloat (order['volume']),
            'filled': parseFloat (order['executed_volume']),
            'remaining': parseFloat (order['remaining_volume']),
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let order = {
            'market': this.marketId (symbol),
            'side': side,
            'volume': amount.toString (),
            'ord_type': type,
        };
        if (type === 'limit') {
            order['price'] = price.toString ();
        }
        let response = await this.privatePostOrders (this.extend (order, params));
        let market = this.marketsById[response['market']];
        return this.parseOrder (response, market);
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let result = await this.privatePostOrderDelete ({ 'id': id });
        let order = this.parseOrder (result);
        if (order['status'] === 'closed') {
            throw new OrderNotFound (this.id + ' ' + result);
        }
        return order;
    }

    async withdraw (currency, amount, address, tag = undefined, params = {}) {
        await this.loadMarkets ();
        let result = await this.privatePostWithdraw (this.extend ({
            'currency': currency.toLowerCase (),
            'sum': amount,
            'address': address,
        }, params));
        return {
            'info': result,
            'id': undefined,
        };
    }

    nonce () {
        return this.milliseconds ();
    }

    encodeParams (params) {
        if ('orders' in params) {
            let orders = params['orders'];
            let query = this.urlencode (this.keysort (this.omit (params, 'orders')));
            for (let i = 0; i < orders.length; i++) {
                let order = orders[i];
                let keys = Object.keys (order);
                for (let k = 0; k < keys.length; k++) {
                    let key = keys[k];
                    let value = order[key];
                    query += '&orders%5B%5D%5B' + key + '%5D=' + value.toString ();
                }
            }
            return query;
        }
        return this.urlencode (this.keysort (params));
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = '/api' + '/' + this.version + '/' + this.implodeParams (path, params);
        if ('extension' in this.urls)
            request += this.urls['extension'];
        let query = this.omit (params, this.extractParams (path));
        let url = this.urls['api'] + request;
        if (api === 'public') {
            if (Object.keys (query).length) {
                url += '?' + this.urlencode (query);
            }
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.encodeParams (this.extend ({
                'access_key': this.apiKey,
                'tonce': nonce,
            }, params));
            let auth = method + '|' + request + '|' + query;
            let signature = this.hmac (this.encode (auth), this.encode (this.secret));
            let suffix = query + '&signature=' + signature;
            if (method === 'GET') {
                url += '?' + suffix;
            } else {
                body = suffix;
                headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
            }
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('error' in response)
            throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
}
<|endoftext|>


<commit_before>var api = {
  backend: 'http://localhost:3000',

  ajax: function(config, cb) {
    $.ajax(config).done(function(data, textStatus, jqxhr) {
      cb(null, data);
    }).fail(function(jqxhr, status, error) {
      cb({jqxher: jqxhr, status: status, error: error});
    });
  },

  register: function register(credentials, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/signup',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(credentials),
      dataType: 'json'
    }, callback);
  },

  login: function login(credentials, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/login',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(credentials),
      dataType: 'json'
    }, callback);
  },

  logout: function logout(callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/logout',
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  changePass: function changePass(credentials, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/changePassword',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(credentials),
      dataType: 'json'
    }, callback);
  },

  getAllPosts: function getAllPosts(callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts',
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  getLoggedUserPosts: function getLoggedUserPosts(callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts/user',
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  getUserPosts: function getUserPosts(id, callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts/user/' + id,
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  getSinglePost: function getSinglePost(id, callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts/article/' + id,
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  newPost: function newPost(content, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/posts/user',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(content),
      dataType: 'json'
    }, callback);
  },

  deletePost: function deletePost(id, callback) {
    this.ajax({
      method: 'DELETE',
      url: this.backend + '/posts/article/' + id
    }, callback);
  },

  updatePost: function updatePost(id, content, callback) {
    this.ajax({
      method: 'PATCH',
      url: this.backend + '/posts/article/' + id,
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(content),
      dataType: 'json'
    }, callback);
  }
};

var switchView = function switchView(view) {
  $('#main-page').hide();
  $('#view-all').hide();
  $('#view-one').hide();
  $('#create').hide();
  $('#update-view').hide();

  if(view === 'view-all') {
    console.log('switched to view all');
    $('#view-all').show();
  } else if (view === 'view-one') {
    console.log('switched to view one');
    $('#view-one').show();
  } else if (view === 'create') {
    console.log('switched to create');
    $('#create').show();
  } else if (view === 'update-view') {
    $('#update-view').show();
  } else {
    console.log('switched to view main');
    $('#main-page').show();
  }
};

var form2object = function(form) {
  var data = {};
  $(form).children().each(function(index, element) {
    var type = $(this).attr('type');
    if ($(this).attr('name') && type !== 'submit' && type !== 'hidden') {
      data[$(this).attr('name')] = $(this).val();
    }
  });
  console.log("Form output:");
  console.log(data);
  return data;
};

var allPostTemplate = Handlebars.compile($('#template-view-all').html());
var onePostTemplate = Handlebars.compile($('#template-view-one').html());

var serverData;
var callback = function callback(error, data) {
  if (error) {
    console.error(error);
    return;
  }
  serverData = data;
  console.log(serverData);
};

var onePostCallback = function onePostCallback(error, data) {
  if(error) {
    console.error(err);
    return;
  }
  var html = onePostTemplate(data);
  $('#view-one').html(html);

  $('#delete').on('click', function() {
    api.deletePost(data._id, callback);
    switchView('view-all');
    api.getUserPosts(data.userID, function(err, data) {
      if(err) {
        console.error(err);
        return;
      }
      var html = allPostTemplate(data);
      $('#view-all').html(html);
    });

  });

  $('#update').on('click', function() {
    var oldTitle = data.title;
    var oldBody = data.body;
    var oldID = data._id;
    $('#update-title').val(oldTitle);
    $('#update-body').val(oldBody);
    $('#update-ID').val(oldID);
    $('#update-view').show();
  });
};

Handlebars.registerHelper('xbbcodeParse', function(input) {
  var result = XBBCODE.process({
      text: input,
      removeMisalignedTags: false,
      addInLineBreaks: true
  });
  console.log("Errors: " + result.error);
  console.dir(result.errorQueue);
  return result.html;
});
<commit_msg>Added to the hadlebars helper, removes anything resembling HTML from the body of a post before parsing the bbcode.<commit_after>var api = {
  backend: 'http://localhost:3000',

  ajax: function(config, cb) {
    $.ajax(config).done(function(data, textStatus, jqxhr) {
      cb(null, data);
    }).fail(function(jqxhr, status, error) {
      cb({jqxher: jqxhr, status: status, error: error});
    });
  },

  register: function register(credentials, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/signup',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(credentials),
      dataType: 'json'
    }, callback);
  },

  login: function login(credentials, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/login',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(credentials),
      dataType: 'json'
    }, callback);
  },

  logout: function logout(callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/logout',
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  changePass: function changePass(credentials, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/changePassword',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(credentials),
      dataType: 'json'
    }, callback);
  },

  getAllPosts: function getAllPosts(callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts',
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  getLoggedUserPosts: function getLoggedUserPosts(callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts/user',
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  getUserPosts: function getUserPosts(id, callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts/user/' + id,
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  getSinglePost: function getSinglePost(id, callback) {
    this.ajax({
      method: 'GET',
      url: this.backend + '/posts/article/' + id,
      contentType: 'application/json; charset=utf-8'
    }, callback);
  },

  newPost: function newPost(content, callback) {
    this.ajax({
      method: 'POST',
      url: this.backend + '/posts/user',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(content),
      dataType: 'json'
    }, callback);
  },

  deletePost: function deletePost(id, callback) {
    this.ajax({
      method: 'DELETE',
      url: this.backend + '/posts/article/' + id
    }, callback);
  },

  updatePost: function updatePost(id, content, callback) {
    this.ajax({
      method: 'PATCH',
      url: this.backend + '/posts/article/' + id,
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(content),
      dataType: 'json'
    }, callback);
  }
};

var switchView = function switchView(view) {
  $('#main-page').hide();
  $('#view-all').hide();
  $('#view-one').hide();
  $('#create').hide();
  $('#update-view').hide();

  if(view === 'view-all') {
    console.log('switched to view all');
    $('#view-all').show();
  } else if (view === 'view-one') {
    console.log('switched to view one');
    $('#view-one').show();
  } else if (view === 'create') {
    console.log('switched to create');
    $('#create').show();
  } else if (view === 'update-view') {
    $('#update-view').show();
  } else {
    console.log('switched to view main');
    $('#main-page').show();
  }
};

var form2object = function(form) {
  var data = {};
  $(form).children().each(function(index, element) {
    var type = $(this).attr('type');
    if ($(this).attr('name') && type !== 'submit' && type !== 'hidden') {
      data[$(this).attr('name')] = $(this).val();
    }
  });
  console.log("Form output:");
  console.log(data);
  return data;
};

var allPostTemplate = Handlebars.compile($('#template-view-all').html());
var onePostTemplate = Handlebars.compile($('#template-view-one').html());

var serverData;
var callback = function callback(error, data) {
  if (error) {
    console.error(error);
    return;
  }
  serverData = data;
  console.log(serverData);
};

var onePostCallback = function onePostCallback(error, data) {
  if(error) {
    console.error(err);
    return;
  }
  var html = onePostTemplate(data);
  $('#view-one').html(html);

  $('#delete').on('click', function() {
    api.deletePost(data._id, callback);
    switchView('view-all');
    api.getUserPosts(data.userID, function(err, data) {
      if(err) {
        console.error(err);
        return;
      }
      var html = allPostTemplate(data);
      $('#view-all').html(html);
    });

  });

  $('#update').on('click', function() {
    var oldTitle = data.title;
    var oldBody = data.body;
    var oldID = data._id;
    $('#update-title').val(oldTitle);
    $('#update-body').val(oldBody);
    $('#update-ID').val(oldID);
    $('#update-view').show();
  });
};

Handlebars.registerHelper('xbbcodeParse', function(input) {
  var noHTMLinput = input.replace(/<(?:.|\n)*?>/gm, '');

  var result = XBBCODE.process({
      text: noHTMLinput,
      removeMisalignedTags: false,
      addInLineBreaks: true
  });
  console.log("Errors: " + result.error);
  console.dir(result.errorQueue);
  return result.html;
});
<|endoftext|>


<commit_before>import { BodyComponent } from 'mjml-core'

export default class MjSocial extends BodyComponent {
  static allowedAttributes = {
    align: 'enum(left,right,center)',
    'border-radius': 'unit(px)',
    'container-background-color': 'color',
    color: 'color',
    'font-family': 'string',
    'font-size': 'unit(px,%)',
    'font-style': 'string',
    'font-weight': 'string',
    'icon-size': 'unit(px,%)',
    'inner-padding': 'unit(px,%)',
    'line-height': 'unit(px,%)',
    mode: 'enum(horizontal,vertical)',
    'padding-bottom': 'unit(px,%)',
    'padding-left': 'unit(px,%)',
    'padding-right': 'unit(px,%)',
    'padding-top': 'unit(px,%)',
    padding: 'unit(px,%){1,4}',
    'table-layout': 'enum(auto,fixed)',
    'vertical-align': 'enum(top,bottom,middle)',
  }

  static defaultAttributes = {
    align: 'center',
    'border-radius': '3px',
    color: '#333333',
    'font-family': 'Ubuntu, Helvetica, Arial, sans-serif',
    'font-size': '13px',
    'icon-size': '20px',
    'inner-padding': null,
    'line-height': '22px',
    mode: 'horizontal',
    padding: '10px 25px',
    'text-decoration': 'none',
  }

  getStyles() {
    return {
      tableVertical: {
        margin: '0px',
      },
    }
  }

  getSocialElementAttributes() {
    return [
      'border-radius',
      'color',
      'font-family',
      'font-size',
      'font-weight',
      'icon-size',
      'inner-padding',
      'line-height',
    ].reduce((res, attr) => {
      res[attr] = this.getAttribute(attr)
      return res
    }, {})
  }

  renderHorizontal() {
    const { children } = this.props

    return `

      ${this.renderChildren(children, {
        attributes: this.getSocialElementAttributes(),
        renderer: component => `

                ${component.render()}

          `,
      })}

    `
  }

  renderVertical() {
    const { children } = this.props

    return `

        ${this.renderChildren(children, {
          attributes: this.getSocialElementAttributes(),
        })}

    `
  }

  render() {
    return `
      ${this.getAttribute('mode') === 'horizontal'
        ? this.renderHorizontal()
        : this.renderVertical()}
    `
  }
}
<commit_msg>pass inner-padding to children as padding<commit_after>import { BodyComponent } from 'mjml-core'

export default class MjSocial extends BodyComponent {
  static allowedAttributes = {
    align: 'enum(left,right,center)',
    'border-radius': 'unit(px)',
    'container-background-color': 'color',
    color: 'color',
    'font-family': 'string',
    'font-size': 'unit(px,%)',
    'font-style': 'string',
    'font-weight': 'string',
    'icon-size': 'unit(px,%)',
    'inner-padding': 'unit(px,%)',
    'line-height': 'unit(px,%)',
    mode: 'enum(horizontal,vertical)',
    'padding-bottom': 'unit(px,%)',
    'padding-left': 'unit(px,%)',
    'padding-right': 'unit(px,%)',
    'padding-top': 'unit(px,%)',
    padding: 'unit(px,%){1,4}',
    'table-layout': 'enum(auto,fixed)',
    'vertical-align': 'enum(top,bottom,middle)',
  }

  static defaultAttributes = {
    align: 'center',
    'border-radius': '3px',
    color: '#333333',
    'font-family': 'Ubuntu, Helvetica, Arial, sans-serif',
    'font-size': '13px',
    'icon-size': '20px',
    'inner-padding': null,
    'line-height': '22px',
    mode: 'horizontal',
    padding: '10px 25px',
    'text-decoration': 'none',
  }

  getStyles() {
    return {
      tableVertical: {
        margin: '0px',
      },
    }
  }

  getSocialElementAttributes() {
    const base = {}
    if (this.getAttribute('inner-padding')) {
      base.padding = this.getAttribute('inner-padding')
    }

    return [
      'border-radius',
      'color',
      'font-family',
      'font-size',
      'font-weight',
      'icon-size',
      'line-height',
    ].reduce((res, attr) => {
      res[attr] = this.getAttribute(attr)
      return res
    }, base)
  }

  renderHorizontal() {
    const { children } = this.props

    return `

      ${this.renderChildren(children, {
        attributes: this.getSocialElementAttributes(),
        renderer: component => `

                ${component.render()}

          `,
      })}

    `
  }

  renderVertical() {
    const { children } = this.props

    return `

        ${this.renderChildren(children, {
          attributes: this.getSocialElementAttributes(),
        })}

    `
  }

  render() {
    return `
      ${this.getAttribute('mode') === 'horizontal'
        ? this.renderHorizontal()
        : this.renderVertical()}
    `
  }
}
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

<commit_msg>Service Weather<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
angular.module('myApp', [])
        .provider('Weather', function() {
            var apiKey = "";
            this.setApiKey = function(key) {
                if (key)
                    this.apiKey = key;
            };
            this.$get = function($q,$http) {
                var self = this;
                return {
                    getWeatherForecast: function(city){
                        var d = $q.defer();
                        $http({
                            method:'GET',
                            url: self.getUrl("forecast", city ),
                            cache: true
                        }).success(function(data){
                            //wgd return object
                            d.resolve(data.forecast.simpleforecast);
                        }).error(function(err){
                            d.reject(err);
                        });
                        return d.promise;
                    }
                    //Service object
                }
            }
            this.getUrl = function(type, ext) {
                return "http://api.wunderground.com/api/" +
                        this.apiKey + "/" + type + "/q/" +
                        ext + '.json';
            }
        })
        .config(function(WeatherProvider) {
            WeatherProvider.setApiKey('82921fa5ebe839db');
        })
        .controller('MainCtrl', function($scope, $timeout, Weather) {
            //Build the date object
            $scope.date = {};
            //Update function
            var updateTime = function() {
                $scope.date.raw = new Date();
                $timeout(updateTime, 1000)
            }
            //Kick off the update function
            updateTime();
            $scope.weather = {};
            Weather.getWeatherForecast("CA/San_Francisco")
                    .then(function(data){
                        $scope.weather.forecast =data;
                    });
        });<|endoftext|>