<commit_before>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012-2013 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs          = require('fs'),
    http        = require('http'),
    https       = require('https'),
    url         = require('url'),
    stream      = require('stream'),
    stringify   = require('qs').stringify,
    multipart   = require('./multipart'),
    auth        = require('./auth'),
    parsers     = require('./parsers'),
    decoder     = require('./decoder');

//////////////////////////////////////////
// variabilia
//////////////////////////////////////////

var version     = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debugging   = !!process.env.DEBUG,
    debug       = debugging ? console.log : function() { /* noop */ };

var user_agent  = 'Needle/' + version;
user_agent     += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')';

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol';

//////////////////////////////////////////
// decompressors for gzip/deflate bodies
//////////////////////////////////////////

var decompressors = {};

try {

  var zlib = require('zlib')

  decompressors['x-deflate'] = zlib.Inflate;
  decompressors['deflate']   = zlib.Inflate;
  decompressors['x-gzip']    = zlib.Gunzip;
  decompressors['gzip']      = zlib.Gunzip;

} catch(e) { /* zlib not available */ }

//////////////////////////////////////////
// defaults
//////////////////////////////////////////

var defaults = {
  accept          : '*/*',
  connection      : 'close',
  user_agent      : user_agent,
  follow          : 0,
  decode_response : true,
  parse_response  : true,
  timeout         : 10000,
  encoding        : 'utf8',
  boundary        : '--------------------NODENEEDLEHTTPCLIENT'
}

//////////////////////////////////////////
// the main act
//////////////////////////////////////////

var Needle = {

  request: function(method, uri, data, options, callback) {

    var self     = this,
        out      = new stream.PassThrough({ objectMode: false }),
        callback = (typeof options == 'function') ? options : callback,
        options  = options || {};

    // if no 'http' is found on URL, prepend it
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts       : {},
      proxy           : options.proxy,
      output          : options.output,
      encoding        : options.encoding || (options.multipart ? 'binary' : defaults.encoding),
      decode_response : options.decode === false ? false : defaults.decode_response,
      parse_response  : options.parse === false ? false : defaults.parse_response,
      follow          : options.follow === true ? 10 : typeof options.follow == 'number' ? options.follow : defaults.follow,
      timeout         : (typeof options.timeout == 'number') ? options.timeout : defaults.timeout
    }

    // if any of node's TLS options are passed, let them be passed to https.request()
    node_tls_opts.split(' ').forEach(function(key) {
      if (typeof options[key] != 'undefined') {
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept'     : options.accept     || defaults.accept,
      'Connection' : options.connection || defaults.connection,
      'User-Agent' : options.user_agent || defaults.user_agent
    }

    if (options.compressed && typeof zlib != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username) {
      if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) {
        config.credentials = [options.username, options.password];
      } else {
        var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
        config.headers[auth_header] = auth.basic(options.username, options.password);
      }
    }

    if (data) {
      if (method.toUpperCase() == 'GET') { // build query string and append to URI

        uri  = uri.replace(/\?.*|$/, '?' + stringify(data));
        data = null;

      } else if (options.multipart) { // build multipart body for request

        var boundary = options.boundary || defaults.boundary;

        multipart.build(data, boundary, function(err, body) {
          if (err) throw(err);

          config.headers['Content-Type']   = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, out, callback);
        });

        return out; // stream

      } else if (this.is_stream(data)) {

        post_data = data;

      } else { // format data according to content type, and send request

        var post_data = (typeof(data) === 'string') ? data :
            options.json ? JSON.stringify(data) : stringify(data);

        if (!config.headers['Content-Type']) {
          config.headers['Content-Type'] = options.json
          ? 'application/json'
          : 'application/x-www-form-urlencoded';
        }

        post_data = new Buffer(post_data, config.encoding);
        config.headers['Content-Length'] = post_data.length;

      }
    }

    return this.send_request(1, method, uri, config, post_data, out, callback);
  },

  get_request_opts: function(method, uri, config) {
    var opts      = config.base_opts,
        proxy     = config.proxy,
        remote    = proxy ? url.parse(proxy) : url.parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;

    opts.headers['Host'] = proxy ? url.parse(uri).hostname : remote.hostname;
    if (opts.port != 80 && opts.port != 443)
      opts.headers['Host'] += ':' + opts.port;

    return opts;
  },

  get_auth_header: function(header, credentials, request_opts) {
    var type = header.split(' ')[0],
        user = credentials[0],
        pass = credentials[1];

    if (type == 'Digest') {
      return auth.digest(header, user, pass, request_opts.method, request_opts.path);
    } else if (type == 'Basic') {
      return auth.basic(user, pass);
    }
  },

  send_request: function(count, method, uri, config, post_data, out, callback) {

    var timer,
        self               = this,
        request_opts       = this.get_request_opts(method, uri, config),
        protocol           = request_opts.protocol == 'https:' ? https : http;

    var error_stop = function(err) {
      if (callback)
        callback(err);
      else
        out.emit('end', err);
    }

    debug('Making request #' + count, request_opts);
    var request = protocol.request(request_opts, function(resp) {

      var headers = resp.headers;
      debug('Got response', headers);
      if (timer) clearTimeout(timer);

      // if redirect code is found, send a GET request to that location if enabled via 'follow' option
      if ([301, 302].indexOf(resp.statusCode) != -1 && headers.location) {
        if (count <= config.follow) {
          out.emit('redirect', headers.location);
          return self.send_request(++count, 'GET', url.resolve(uri, headers.location), config, null, out, callback);
        } else if (config.follow > 0) {
          return error_stop(new Error('Max redirects reached. Possible loop in: ' + headers.location));
        }
      }

      // if authentication is requested and credentials were not passed, resend request if we have user/pass
      if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
        if (!config.headers['Authorization']) { // only if authentication hasn't been sent
          var auth_header = self.get_auth_header(headers['www-authenticate'], config.credentials, request_opts);

          if (auth_header) {
            config.headers['Authorization'] = auth_header;
            return self.send_request(count, method, uri, config, post_data, out, callback);
          }
        }
      }

      // ok so we got a valid (non-redirect & authorized) response. notify the stream guys.
      out.emit('headers', headers);

      var pipeline      = [],
          parsed        = false,
          mime          = self.parse_content_type(headers['content-type']),
          text_response = mime.type && mime.type.indexOf('text/') != -1;

      // To start, if our body is compressed and we're able to inflate it, do it.
      if (headers['content-encoding'] && decompressors[headers['content-encoding']]) {
        pipeline.push(decompressors[headers['content-encoding']]());
      }

      // If parse is enabled and we have a parser for it, then go for it.
      if (config.parse_response && parsers[mime.type]) {
        parsed = true;
        pipeline.push(parsers[mime.type]());

        // set objectMode on out stream to improve performance
        out._writableState.objectMode = true;
        out._readableState.objectMode = true;

      // If we're not parsing, and unless decoding was disabled, we'll try
      // decoding non UTF-8 bodies to UTF-8, using the iconv-lite library.
      } else if (text_response && config.decode_response
        && mime.charset && !mime.charset.match(/utf-?8$/i)) {
          pipeline.push(decoder(mime.charset));
      }

      // And `out` is the stream we finally push the decoded/parsed output to.
      pipeline.push(out);

      // Process the pipeline!
      var tmp = resp;
      while (pipeline.length) {
        tmp = tmp.pipe(pipeline.shift());
      }

      // If the user has requested and output file, pipe the output stream to it.
      // In stream mode, we will still get the response stream to play with.
      if (config.output && resp.statusCode == 200) {
        resp.pipe(fs.createWriteStream(config.output))
      }

      // Only aggregate the full body if a callback was requested.
      if (callback) {
        resp.body  = [];
        resp.bytes = 0;

        // Count the amount of (raw) bytes passed using a PassThrough stream.
        var bytesCounter = new stream.PassThrough();
        resp.pipe(bytesCounter);

        bytesCounter.on('readable', function() {
          while (chunk = this.read()) {
            resp.bytes += chunk.length;
          }
        })

        // Listen on the 'readable' event to aggregate the chunks.
        out.on('readable', function() {
          while (chunk = this.read()) {
            // We're either pushing buffers or objects, never strings.
            if (typeof chunk == 'string') chunk = new Buffer(chunk);

            // Push all chunks to resp.body. We'll bind them in resp.end().
            resp.body.push(chunk);
          }
        })

        // And set the .body property once all data is in.
        out.on('end', function() {

          // if parse was successful, we should have an array with one object
          if (resp.body[0] && !Buffer.isBuffer(resp.body[0])) {
            resp.body = resp.body[0];
          } else { // we got one or several buffers
            resp.body = Buffer.concat(resp.body);

            // if we got a text response, of parsing failed, stringify it
            if (text_response || parsed)
              resp.body = resp.body.toString();
          }

          callback(null, resp, resp.body);
        });

      }

    });

    // unless timeout was disabled, set a timeout to abort the request
    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      debug('Request error', err);
      if (timer) clearTimeout(timer);

      error_stop(err || new Error('Unknown error when making request.'));
    });

    if (post_data) {
      if (this.is_stream(post_data)) {
        post_data.pipe(request);
      } else {
        request.write(post_data, config.encoding);
        request.end();
      }
    } else {
      request.end();
    }

    return out;
  },

  parse_content_type: function(header) {
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  is_stream: function(obj) {
    return typeof obj.pipe === 'function';
  }
}

exports.version = version;

exports.defaults = function(obj) {
  for (var key in obj) {
    if (defaults[key] && typeof obj[key] != 'undefined')
      defaults[key] = obj[key];
  }
  return defaults;
}

'head get'.split(' ').forEach(function(method) {
  exports[method] = function(uri, options, callback) {
    return Needle.request(method, uri, null, options, callback);
  }
})

'post put delete'.split(' ').forEach(function(method) {
  exports[method] = function(uri, data, options, callback) {
    return Needle.request(method, uri, data, options, callback);
  }
})

exports.request = function(method, uri, data, opts, callback) {
  return Needle.request(method.toUpperCase(), uri, data, opts, callback);
};
<commit_msg>fixing accidental global variable<commit_after>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012-2013 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs          = require('fs'),
    http        = require('http'),
    https       = require('https'),
    url         = require('url'),
    stream      = require('stream'),
    stringify   = require('qs').stringify,
    multipart   = require('./multipart'),
    auth        = require('./auth'),
    parsers     = require('./parsers'),
    decoder     = require('./decoder');

//////////////////////////////////////////
// variabilia
//////////////////////////////////////////

var version     = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debugging   = !!process.env.DEBUG,
    debug       = debugging ? console.log : function() { /* noop */ };

var user_agent  = 'Needle/' + version;
user_agent     += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')';

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol';

//////////////////////////////////////////
// decompressors for gzip/deflate bodies
//////////////////////////////////////////

var decompressors = {};

try {

  var zlib = require('zlib')

  decompressors['x-deflate'] = zlib.Inflate;
  decompressors['deflate']   = zlib.Inflate;
  decompressors['x-gzip']    = zlib.Gunzip;
  decompressors['gzip']      = zlib.Gunzip;

} catch(e) { /* zlib not available */ }

//////////////////////////////////////////
// defaults
//////////////////////////////////////////

var defaults = {
  accept          : '*/*',
  connection      : 'close',
  user_agent      : user_agent,
  follow          : 0,
  decode_response : true,
  parse_response  : true,
  timeout         : 10000,
  encoding        : 'utf8',
  boundary        : '--------------------NODENEEDLEHTTPCLIENT'
}

//////////////////////////////////////////
// the main act
//////////////////////////////////////////

var Needle = {

  request: function(method, uri, data, options, callback) {

    var self     = this,
        out      = new stream.PassThrough({ objectMode: false }),
        callback = (typeof options == 'function') ? options : callback,
        options  = options || {};

    // if no 'http' is found on URL, prepend it
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts       : {},
      proxy           : options.proxy,
      output          : options.output,
      encoding        : options.encoding || (options.multipart ? 'binary' : defaults.encoding),
      decode_response : options.decode === false ? false : defaults.decode_response,
      parse_response  : options.parse === false ? false : defaults.parse_response,
      follow          : options.follow === true ? 10 : typeof options.follow == 'number' ? options.follow : defaults.follow,
      timeout         : (typeof options.timeout == 'number') ? options.timeout : defaults.timeout
    }

    // if any of node's TLS options are passed, let them be passed to https.request()
    node_tls_opts.split(' ').forEach(function(key) {
      if (typeof options[key] != 'undefined') {
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept'     : options.accept     || defaults.accept,
      'Connection' : options.connection || defaults.connection,
      'User-Agent' : options.user_agent || defaults.user_agent
    }

    if (options.compressed && typeof zlib != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username) {
      if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) {
        config.credentials = [options.username, options.password];
      } else {
        var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
        config.headers[auth_header] = auth.basic(options.username, options.password);
      }
    }

    if (data) {
      if (method.toUpperCase() == 'GET') { // build query string and append to URI

        uri  = uri.replace(/\?.*|$/, '?' + stringify(data));
        data = null;

      } else if (options.multipart) { // build multipart body for request

        var boundary = options.boundary || defaults.boundary;

        multipart.build(data, boundary, function(err, body) {
          if (err) throw(err);

          config.headers['Content-Type']   = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, out, callback);
        });

        return out; // stream

      } else if (this.is_stream(data)) {

        post_data = data;

      } else { // format data according to content type, and send request

        var post_data = (typeof(data) === 'string') ? data :
            options.json ? JSON.stringify(data) : stringify(data);

        if (!config.headers['Content-Type']) {
          config.headers['Content-Type'] = options.json
          ? 'application/json'
          : 'application/x-www-form-urlencoded';
        }

        post_data = new Buffer(post_data, config.encoding);
        config.headers['Content-Length'] = post_data.length;

      }
    }

    return this.send_request(1, method, uri, config, post_data, out, callback);
  },

  get_request_opts: function(method, uri, config) {
    var opts      = config.base_opts,
        proxy     = config.proxy,
        remote    = proxy ? url.parse(proxy) : url.parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;

    opts.headers['Host'] = proxy ? url.parse(uri).hostname : remote.hostname;
    if (opts.port != 80 && opts.port != 443)
      opts.headers['Host'] += ':' + opts.port;

    return opts;
  },

  get_auth_header: function(header, credentials, request_opts) {
    var type = header.split(' ')[0],
        user = credentials[0],
        pass = credentials[1];

    if (type == 'Digest') {
      return auth.digest(header, user, pass, request_opts.method, request_opts.path);
    } else if (type == 'Basic') {
      return auth.basic(user, pass);
    }
  },

  send_request: function(count, method, uri, config, post_data, out, callback) {

    var timer,
        self               = this,
        request_opts       = this.get_request_opts(method, uri, config),
        protocol           = request_opts.protocol == 'https:' ? https : http;

    var error_stop = function(err) {
      if (callback)
        callback(err);
      else
        out.emit('end', err);
    }

    debug('Making request #' + count, request_opts);
    var request = protocol.request(request_opts, function(resp) {

      var headers = resp.headers;
      debug('Got response', headers);
      if (timer) clearTimeout(timer);

      // if redirect code is found, send a GET request to that location if enabled via 'follow' option
      if ([301, 302].indexOf(resp.statusCode) != -1 && headers.location) {
        if (count <= config.follow) {
          out.emit('redirect', headers.location);
          return self.send_request(++count, 'GET', url.resolve(uri, headers.location), config, null, out, callback);
        } else if (config.follow > 0) {
          return error_stop(new Error('Max redirects reached. Possible loop in: ' + headers.location));
        }
      }

      // if authentication is requested and credentials were not passed, resend request if we have user/pass
      if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
        if (!config.headers['Authorization']) { // only if authentication hasn't been sent
          var auth_header = self.get_auth_header(headers['www-authenticate'], config.credentials, request_opts);

          if (auth_header) {
            config.headers['Authorization'] = auth_header;
            return self.send_request(count, method, uri, config, post_data, out, callback);
          }
        }
      }

      // ok so we got a valid (non-redirect & authorized) response. notify the stream guys.
      out.emit('headers', headers);

      var pipeline      = [],
          parsed        = false,
          mime          = self.parse_content_type(headers['content-type']),
          text_response = mime.type && mime.type.indexOf('text/') != -1;

      // To start, if our body is compressed and we're able to inflate it, do it.
      if (headers['content-encoding'] && decompressors[headers['content-encoding']]) {
        pipeline.push(decompressors[headers['content-encoding']]());
      }

      // If parse is enabled and we have a parser for it, then go for it.
      if (config.parse_response && parsers[mime.type]) {
        parsed = true;
        pipeline.push(parsers[mime.type]());

        // set objectMode on out stream to improve performance
        out._writableState.objectMode = true;
        out._readableState.objectMode = true;

      // If we're not parsing, and unless decoding was disabled, we'll try
      // decoding non UTF-8 bodies to UTF-8, using the iconv-lite library.
      } else if (text_response && config.decode_response
        && mime.charset && !mime.charset.match(/utf-?8$/i)) {
          pipeline.push(decoder(mime.charset));
      }

      // And `out` is the stream we finally push the decoded/parsed output to.
      pipeline.push(out);

      // Process the pipeline!
      var tmp = resp;
      while (pipeline.length) {
        tmp = tmp.pipe(pipeline.shift());
      }

      // If the user has requested and output file, pipe the output stream to it.
      // In stream mode, we will still get the response stream to play with.
      if (config.output && resp.statusCode == 200) {
        resp.pipe(fs.createWriteStream(config.output))
      }

      // Only aggregate the full body if a callback was requested.
      if (callback) {
        resp.body  = [];
        resp.bytes = 0;

        // Count the amount of (raw) bytes passed using a PassThrough stream.
        var bytesCounter = new stream.PassThrough();
        resp.pipe(bytesCounter);

        bytesCounter.on('readable', function() {
          var chunk;
          while (chunk = this.read()) {
            resp.bytes += chunk.length;
          }
        })

        // Listen on the 'readable' event to aggregate the chunks.
        out.on('readable', function() {
          var chunk;
          while (chunk = this.read()) {
            // We're either pushing buffers or objects, never strings.
            if (typeof chunk == 'string') chunk = new Buffer(chunk);

            // Push all chunks to resp.body. We'll bind them in resp.end().
            resp.body.push(chunk);
          }
        })

        // And set the .body property once all data is in.
        out.on('end', function() {

          // if parse was successful, we should have an array with one object
          if (resp.body[0] && !Buffer.isBuffer(resp.body[0])) {
            resp.body = resp.body[0];
          } else { // we got one or several buffers
            resp.body = Buffer.concat(resp.body);

            // if we got a text response, of parsing failed, stringify it
            if (text_response || parsed)
              resp.body = resp.body.toString();
          }

          callback(null, resp, resp.body);
        });

      }

    });

    // unless timeout was disabled, set a timeout to abort the request
    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      debug('Request error', err);
      if (timer) clearTimeout(timer);

      error_stop(err || new Error('Unknown error when making request.'));
    });

    if (post_data) {
      if (this.is_stream(post_data)) {
        post_data.pipe(request);
      } else {
        request.write(post_data, config.encoding);
        request.end();
      }
    } else {
      request.end();
    }

    return out;
  },

  parse_content_type: function(header) {
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  is_stream: function(obj) {
    return typeof obj.pipe === 'function';
  }
}

exports.version = version;

exports.defaults = function(obj) {
  for (var key in obj) {
    if (defaults[key] && typeof obj[key] != 'undefined')
      defaults[key] = obj[key];
  }
  return defaults;
}

'head get'.split(' ').forEach(function(method) {
  exports[method] = function(uri, options, callback) {
    return Needle.request(method, uri, null, options, callback);
  }
})

'post put delete'.split(' ').forEach(function(method) {
  exports[method] = function(uri, data, options, callback) {
    return Needle.request(method, uri, data, options, callback);
  }
})

exports.request = function(method, uri, data, opts, callback) {
  return Needle.request(method.toUpperCase(), uri, data, opts, callback);
};
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require dataTables/jquery.dataTables.api.fnReloadAjax
//= require dataTables/extras/TableTools
//= require dataTables/jquery.dataTables.bootstrap3
//= require_tree
<commit_msg>Moved Keyframes asset to correct lib<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
// jquery should be required before this file is required

//= require dataTables/jquery.dataTables
//= require dataTables/jquery.dataTables.api.fnReloadAjax
//= require dataTables/extras/TableTools
//= require dataTables/jquery.dataTables.bootstrap3
//= require_tree
<|endoftext|>


<commit_before>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    url_parse = require('url').parse,
    stringify = require('qs').stringify,
    multipart = require('./multipart');

var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debug = !!process.env.DEBUG;

exports.version = version;
try { var unzip = require('zlib').unzip } catch(e) { /* zlib not supported */ }

var default_user_agent = "Needle/" + version;
default_user_agent += " (Node.js " + process.version + "; " + process.platform + " " + process.arch + ")";

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized';

var parsers = {
  'application/json': function(data, callback){
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback){
    var xml_parser = new xml2js.Parser({ explicitArray: false });
    xml_parser.parseString(data, callback);
  };
  parsers['text/xml'] = parsers['application/xml'];
} catch(e) { /* xml2js not found */ }

var Needle = {

  default_boundary: '--------------------NODENEEDLEHTTPCLIENT',
  default_user_agent: default_user_agent,

  request: function(uri, method, data, options, callback){

    var self = this, post_data = null;
    var callback = (typeof options == 'function') ? options : callback;
    var options = options || {};
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts: {},
      proxy: options.proxy,
      output: options.output,
      encoding: options.encoding || (options.multipart ? 'binary' : 'utf8'),
      decode_response: options.decode === false ? false : true,
      parse_response: options.parse === false ? false : true,
      follow: options.follow === false ? 0 : options.follow || 10, // 10 by default
      timeout: (typeof options.timeout == 'number') ? options.timeout : 10000
    }

    node_tls_opts.split(' ').forEach(function(key){
      if (typeof options[key] != 'undefined'){
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept': options.accept || '*/*',
      'Connection': options.connection || 'close',
      'User-Agent': options.user_agent || this.default_user_agent
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password){
      var b = new Buffer([options.username, options.password].join(':'));
      var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
      config.headers[auth_header] = 'Basic ' + b.toString('base64');
    }

    if (data){
      if (options.multipart){

        var boundary = options.boundary || this.default_boundary;
        return multipart.build(data, boundary, function(err, body){

          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);

        });

      } else {
        post_data = (typeof(data) === "string") ? data : stringify(data);
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers['Content-Length'] = post_data.length;
      }

    }

    return this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config){
    var opts   = config.base_opts, proxy = config.proxy;
    var remote = proxy ? url_parse(proxy) : url_parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;
    opts.headers["Host"] = proxy ? url_parse(uri).hostname : remote.hostname;

    return opts;
  },

  send_request: function(count, method, uri, config, post_data, callback){

    var self = this, timer,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    var request = protocol.request(request_opts, function(resp){

      if (timer) clearTimeout(timer);

      if ([301, 302].indexOf(resp.statusCode) != -1 && resp.headers.location){
        if (count <= config.follow)
          return self.send_request(++count, 'GET', resp.headers.location, config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Redirect loop in ' + resp.headers.location));
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(resp.headers['content-encoding']),
          mime = self.parse_content_type(resp.headers['content-type']);

      var response_opts = {
        output: config.output,
        parse: config.parse_response, // parse XML or JSON
        content_type: mime.type,
        text: mime.type && mime.type.indexOf('text/') != -1,
        charset: mime.charset
      }

      if (response_opts.text)
        response_opts.decode = config.decode_response; // only allow iconv on text/*

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk){
        chunks.push(chunk);
        length += chunk.length;
      });

      resp.on('end', function(){

        var body = new Buffer(length), pos = 0;
        for (var i = 0, len = chunks.length; i < len; i++) {
          chunks[i].copy(body, pos);
          pos += chunks[i].length;
        }

        if (typeof unzip != 'undefined' && compressed)
          unzip(body, function(err, buff){
            self.response_end(response_opts, resp, buff, callback);
          });
        else
          self.response_end(response_opts, resp, body, callback);

      });

    });

    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      if (debug) console.log('Error on request: ' + err.toString());
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error("Unkown error on request."));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();
    return request;

  },

  parse_content_type: function(header){
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, response, body, callback){

    if (debug) console.log(response.headers);
    if (!callback) return;

    var handle_output = function(err, data){
      if (err || !opts.output)
        return callback(err, response, data);

      fs.writeFile(opts.output, data, function(err){
        callback(err, response, data);
      })
    }

    if (opts.parse && parsers[opts.content_type]) {
      parsers[opts.content_type](body.toString(), function(err, result){
        handle_output(err, result);
      });
    } else {
      if (opts.decode && opts.charset && !opts.charset.match(/utf-?8$/i)) // not utf-8
        body = require('iconv-lite').decode(body, opts.charset);

      handle_output(null, opts.text ? body.toString() : body);
    }

  }

}

exports.head = function(uri, options, callback){
  return Needle.request(uri, 'HEAD', null, options, callback);
}

exports.get = function(uri, options, callback){
  return Needle.request(uri, 'GET', null, options, callback);
}

exports.post = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('POST request expects data.');
  return Needle.request(uri, 'POST', data, options, callback);
}

exports.put = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('PUT request expects data.');
  return Needle.request(uri, 'PUT', data, options, callback);
}

exports.delete = function(uri, data, options, callback){
  return Needle.request(uri, 'DELETE', null, options, callback);
}
<commit_msg>Return original string if XML parsing fails.<commit_after>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    url_parse = require('url').parse,
    stringify = require('qs').stringify,
    multipart = require('./multipart');

var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debug = !!process.env.DEBUG;

exports.version = version;
try { var unzip = require('zlib').unzip } catch(e) { /* zlib not supported */ }

var default_user_agent = "Needle/" + version;
default_user_agent += " (Node.js " + process.version + "; " + process.platform + " " + process.arch + ")";

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized';

var parsers = {
  'application/json': function(data, callback){
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback){
    var xml_parser = new xml2js.Parser({ explicitRoot: true, explicitArray: false });
    xml_parser.parseString(data, function(err, result){
      callback(err, err ? data : result); // return original if err failed
    });
  };
  parsers['text/xml'] = parsers['application/xml'];
} catch(e) { /* xml2js not found */ }

var Needle = {

  default_boundary: '--------------------NODENEEDLEHTTPCLIENT',
  default_user_agent: default_user_agent,

  request: function(uri, method, data, options, callback){

    var self = this, post_data = null;
    var callback = (typeof options == 'function') ? options : callback;
    var options = options || {};
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts: {},
      proxy: options.proxy,
      output: options.output,
      encoding: options.encoding || (options.multipart ? 'binary' : 'utf8'),
      decode_response: options.decode === false ? false : true,
      parse_response: options.parse === false ? false : true,
      follow: options.follow === false ? 0 : options.follow || 10, // 10 by default
      timeout: (typeof options.timeout == 'number') ? options.timeout : 10000
    }

    node_tls_opts.split(' ').forEach(function(key){
      if (typeof options[key] != 'undefined'){
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept': options.accept || '*/*',
      'Connection': options.connection || 'close',
      'User-Agent': options.user_agent || this.default_user_agent
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password){
      var b = new Buffer([options.username, options.password].join(':'));
      var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
      config.headers[auth_header] = 'Basic ' + b.toString('base64');
    }

    if (data){
      if (options.multipart){

        var boundary = options.boundary || this.default_boundary;
        return multipart.build(data, boundary, function(err, body){

          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);

        });

      } else {
        post_data = (typeof(data) === "string") ? data : stringify(data);
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers['Content-Length'] = post_data.length;
      }

    }

    return this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config){
    var opts   = config.base_opts, proxy = config.proxy;
    var remote = proxy ? url_parse(proxy) : url_parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;
    opts.headers["Host"] = proxy ? url_parse(uri).hostname : remote.hostname;

    return opts;
  },

  send_request: function(count, method, uri, config, post_data, callback){

    var self = this, timer,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    var request = protocol.request(request_opts, function(resp){

      if (timer) clearTimeout(timer);

      if ([301, 302].indexOf(resp.statusCode) != -1 && resp.headers.location){
        if (count <= config.follow)
          return self.send_request(++count, 'GET', resp.headers.location, config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Redirect loop in ' + resp.headers.location));
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(resp.headers['content-encoding']),
          mime = self.parse_content_type(resp.headers['content-type']);

      var response_opts = {
        output: config.output,
        parse: config.parse_response, // parse XML or JSON
        content_type: mime.type,
        text: mime.type && mime.type.indexOf('text/') != -1,
        charset: mime.charset
      }

      if (response_opts.text)
        response_opts.decode = config.decode_response; // only allow iconv on text/*

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk){
        chunks.push(chunk);
        length += chunk.length;
      });

      resp.on('end', function(){

        var body = new Buffer(length), pos = 0;
        for (var i = 0, len = chunks.length; i < len; i++) {
          chunks[i].copy(body, pos);
          pos += chunks[i].length;
        }

        if (typeof unzip != 'undefined' && compressed)
          unzip(body, function(err, buff){
            self.response_end(response_opts, resp, buff, callback);
          });
        else
          self.response_end(response_opts, resp, body, callback);

      });

    });

    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      if (debug) console.log('Error on request: ' + err.toString());
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error("Unkown error on request."));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();
    return request;

  },

  parse_content_type: function(header){
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, response, body, callback){

    if (debug) console.log(response.headers);
    if (!callback) return;

    var handle_output = function(err, data){
      if (err || !opts.output)
        return callback(err, response, data);

      fs.writeFile(opts.output, data, function(err){
        callback(err, response, data);
      })
    }

    if (opts.parse && parsers[opts.content_type]) {
      parsers[opts.content_type](body.toString(), function(err, result){
        handle_output(err, result);
      });
    } else {
      if (opts.decode && opts.charset && !opts.charset.match(/utf-?8$/i)) // not utf-8
        body = require('iconv-lite').decode(body, opts.charset);

      handle_output(null, opts.text ? body.toString() : body);
    }

  }

}

exports.head = function(uri, options, callback){
  return Needle.request(uri, 'HEAD', null, options, callback);
}

exports.get = function(uri, options, callback){
  return Needle.request(uri, 'GET', null, options, callback);
}

exports.post = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('POST request expects data.');
  return Needle.request(uri, 'POST', data, options, callback);
}

exports.put = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('PUT request expects data.');
  return Needle.request(uri, 'PUT', data, options, callback);
}

exports.delete = function(uri, data, options, callback){
  return Needle.request(uri, 'DELETE', null, options, callback);
}
<|endoftext|>


<commit_before>/**
 * Created by grahamcapham on 16/02/2015.
 */

LeaveChart = (function(targID){

    var _scope = function(targID){
        this._targID        = targID;
        this._target        = null;
        this.width          = 1400;
        this.height         = 1000;
        this.backgroundColor     = "rgba(20,30,50, 10)";
        this._canvas        = null;
        this._data          = null;
        this._lines         = null;
        this._volumeArea    = null;
        this._dots          = null;
        this._brush         = null;

        this._vScale        = null;
        this._vMin          = null;
        this._vMax          = null;
        this._vDomainMin    = null;
        this._vDomainMax    = null;

        this._xScale        = null;
        this._brushXScale   = null;
        this._xMin          = null;
        this._xMax          = null;
        this._xDomainMin    = null;
        this._xDomainMax    = null;
        this._Yoffset        = 30;
        this._months         = 12

        this._view          = {svg:null, _linesHolder:null};
        this.padding        = {left:150, right:20, top:50, bottom:160}

        _init.call(this);
    }
    //----
    _scope.prototype = {
        setData:function(value){
            this._data = value;
            _onDataSet.call(this);
        }
    };
    //-- callbacks
    var _init = function(){
        this._target = document.getElementById( this._targID );

        console.log("SVG INITED ", this._target)

        _initSVG.call(this);
    };

    var _initScale = function(){
        this._vScale = d3.scale.linear()
            .domain([this._vMin, this._vMax])
            .range([this._vDomainMin, this._vDomainMax]);
        return Math.ceil( vScale(value) )
    };

    var _initSVG = function(){
        this._view._svg = d3.select(this._target)
            .style('position', 'relative')
            .style('width', this.width+ "px")
            .style('height', this.height+ "px")
            .style('background-color',  this.backgroundColor)
            .append('svg:svg')
            .attr('width',this.width)
            .attr('height',this.height )
            .attr('class', "myClass")
//            .attr('transform', "translate(" + this.padding.left + "," + this.padding.top  + ")");

        this._view._linesHolder = this._view._svg
            .append("g")
            .attr('class', 'lineHolder')
            .attr('transform', "translate(" + this.padding.left + "," + this.padding.top  + ")");

        this._view._dotHolder = this._view._svg
            .append("g")
            .attr('class', 'dotHolder')
            .attr('transform', "translate(" + this.padding.left + "," + this.padding.top  + ")");
    };

    var _initNameAxis = function(){
        this._view._nameHolder = this._view._svg
            .append("g")
            .attr('class', 'nameHolder')
            .attr('transform', "translate(" + 0 + "," + this.padding.top  + ")");

        var _names =  _.filter(_.uniq(_.map(this._data, "name")), function(n){
            return _.isString(n)
        })

        var names =  _.uniq(this._data, "name")

        console.log("_______________names ", names)

//        _.filter(_.uniq(_.map(this._data, "name")), function(n){
//            return _.isString(n)
//        })
        var _this = this

        this._nameList = this._view._nameHolder
            .selectAll(".names")
            .data(names)
            .enter().append('g')
            .attr("class", "names")
            .attr("transform", function(d, i) {
                return "translate("+0+","+ (d.userid-1) * _this._Yoffset +")";
            })

        this._nameList
            .attr('fill', 'rgba(0,0,0,.9)')
            .append("svg:rect")
            .attr('width',this.padding.left)
            .attr('height',_this._Yoffset )

        this._nameList
            .append("svg:line")
            .attr("x1", 0)
            .attr("y1", 0)
            .attr("x2", 1500)
            .attr("y2", 0)
            .style("stroke-dasharray", ("1, 1"))
            .attr("stroke-width", 1)
            .attr("stroke", "rgba(255, 255, 255, .2)");

        this._nameList
            .append("text")
            .attr('fill', '#ffffff')
            .text(function(d,i){return d.name })
            .attr("dy", "1.3em")
            .attr("dx", "1.3em")

      //  this._nameList.exit().remove();

    }

    var _initTimeAxis = function(){

        var _this = this;

        this._view._xAxis = d3.svg.axis()
            .scale(this._xScale)
            .orient("bottom")
            .ticks(d3.time.week,12)
            .tickSize(-_this.height, 0, 0)
            .tickFormat(d3.time.format("%b %d %Y"));

        this._view._xAxisBrush = d3.svg.axis()
            .scale(this._xScale)
            .orient("bottom")
            .ticks(d3.time.month,1)
            .tickFormat(d3.time.format("%b %Y"));

        var _this = this
        this._view._xAxisHolder = this._view._svg.append("g")
            .attr("transform","translate("+this.padding.left+"," + ( _this.height - _this.padding.bottom ) + ")")
            .attr("class", "x axis")
            .attr("class","xTimeAxis");

        this._view._xTickHolder = this._view._svg.append("g")
            .attr("transform","translate("+this.padding.left+"," + ( _this.height - _this.padding.bottom ) + ")")
            .attr("class","xTimeAxisTicks")

        this._view._xAxisTicks =  this._view._xTickHolder.selectAll('.tickY')
            .data(_this._xScale.ticks(d3.time.day))

        this._view._xAxisTicks
            .enter()
            .append("g")
            .attr('class', 'tickY')
            .append("svg:line")
            .attr("x1", _this._xScale)
            .attr("x2", _this._xScale)
//            .attr("y1", -300)
//            .attr("y2", 200 )
            .attr("class", "yTickLine" )

        this._view._xAxisTicks
            .exit()
            .remove();

        _updateTimeAxis.call(this);
    }

    var _updateTimeAxis = function(){
//        console.log("_updateTimeAxis ")
//        console.log("_updateTimeAxis _view._xAxisHolder ",this._view._xAxisHolder)
        //console.log("_updateTimeAxis _this._view._xAxis ", this._view._xAxis)
        var _this = this
        this._view._xAxisHolder
            .call(_this._view._xAxis);
    }

    var _intBrush = function(){
        var _this = this;

        this._brush = new d3.svg.brush()
            .x(this._brushXScale)
            .on("brush", function(){ _brushFunction.call(_this);  })
            .extent([this.min_max_date[0], this.min_max_date[1]]);

        this._view._brushHolder = this._view._svg
            .append("g")
            .attr('transform', "translate(" + this.padding.left + "," + 0 + ")")
            .attr("class", "x brush")
            .call(this._brush)

        this._view._brushHolder
            .selectAll("rect")
            .attr("y", -6)
            .attr("height", this.padding.top);

        var _this = this;

        this._view._brusAxishHolder = this._view._svg
            .append("g")
            .attr("class", "brushDateAxis")
            .attr('transform', "translate(" + this.padding.left + "," + 0  + ")")
            .call(this._view._xAxisBrush)

        var handles = this._view._brushHolder
            .selectAll(".resize")
            .append("svg:rect")
            .attr("width", 10)
            .attr("class", "brush-handle")
            .attr("height", this.padding.top)
            .attr("y", -6)
            .attr("fill", '#ff0000');

        console.log("_brusAxishHolder _",this._view._brusAxishHolder)
        console.log("HANDLES _",handles)

    }

    var monthDiff = function(d1, d2) {
        var months;
        months = (d2.getFullYear() - d1.getFullYear()) * 12;
        months -= d1.getMonth() + 1;
        months += d2.getMonth();
        return months <= 0 ? 0 : months;
    }

    var _brushFunction = function(e){
        this._xScale.domain(this._brush.empty() ? this._xScale.domain() : this._brush.extent());

        this._months  = monthDiff(this._brush.extent()[0], this._brush.extent()[1])

        console.log(this._months)

        if(this._months<=1){
            this._view._xAxis
                .ticks(d3.time.day,1)
                .tickFormat(d3.time.format("%b %d"));

        }
        if(this._months>1 && this._months<3){
            this._view._xAxis
                .ticks(d3.time.week,1)
                .tickFormat(d3.time.format("%b %Y"));

        }
        if(this._months>3){
            this._view._xAxis
                .ticks(d3.time.month,1)
                .tickFormat(d3.time.format("%b %d %Y"));
        }

        var _xAx = this._view._xAxisHolder
                    .call(this._view._xAxis);
        //_updateTimeAxis.call(this);
        //_drawLine.call(this);
        _updateDots.call(this);

//        x.domain(brush.empty() ? x2.domain() : brush.extent());
//        focus.select(".area").attr("d", area);
//        focus.select(".x.axis").call(xAxis);
    }

    var _onDataSet = function(){
        //console.log("this._data.DATES" , this._data);

        this.min_max_date = d3.extent(this._data, function(d) { return d.jsDate; })
        console.log("MIN AND MAX ",this.min_max_date)
//
       this._xScale = d3.time.scale()
           .domain( this.min_max_date  )
           .range([0, this.width - this.padding.left - this.padding.right]);

        this._brushXScale   = d3.time.scale()
            .domain( this.min_max_date  )
            .range([0 , this.width - this.padding.left - this.padding.right]);

        this._brushXScaleStatic   = d3.time.scale()
            .domain( this.min_max_date  )
            .range([0, this.width - this.padding.left - this.padding.right]);

        _draw.call(this);
    };

    var _draw = function(){
       // _drawLine.call(this);
        _initTimeAxis.call(this);
        // _drawSentiment.call(this);
        _intBrush.call(this);
        _drawDots.call(this);
        _initNameAxis.call(this);

    };

    var _drawDots = function(){
        var _this = this;
        this._dots = this._view._dotHolder.selectAll('.dot')
                    .data(this._data)
        this._dots
            .enter().append('g')
            .attr("class", "dot")
            .attr("transform", function(d, i) {
                return "translate("+_this._xScale(d.jsDate)+","+ ( (d.userid * _this._Yoffset) - _this._Yoffset)+")";
            })

        this._dots
            .append('rect')
            .attr("x", function(d, i) {
                return  0 ;
            })
            .attr("width", 12)
            .attr("y", function(d,i){
                //return d.userid * 20
                return   d.unit == 'AM' ? _this._Yoffset/2 : 0;
            })
            .attr("height", function(d,i) { return _this._Yoffset/2 })
            .attr('fill', function(d,i){return  d.unit == 'AM' ? 'rgba(127,0,0,1)' : 'rgba(255,0,0,1)'})
            .on('click', function(d,i){
                console.log(d)
                var _d = d
//                _.remove(_this._data, function(n) {
//                    return n == _d;
//                });
//
//                console.log(_this._data.length)
//                _updateDots.call(_this);
            })

        _updateDots.call(this)
    }

    var _updateDots = function(){
        var _this = this;

        this._dots = this._view._dotHolder.selectAll('.dot')
            .data(this._data)

        this._dots.exit().remove()

        var _this = this
        this._dots
            .transition()
            .duration(0)
            .attr("transform", function(d, i) {
                return "translate("+_this._xScale(d.jsDate)+","+ ( (d.userid * _this._Yoffset) - _this._Yoffset)+")";
            })
    }

    var _drawLine = function(){
        // The Volume line

        console.log("drawline called ")
        //console.log(this._xScale.domain)

        var _this = this;
        this._volumeArea = d3.svg.area()
            .interpolate("cardinal")
            .x(function(d, i) {
                console.log(" DATE ", _this._xScale(d.date) );
                return  _this._xScale(d.date) ;
            })
            .y0(function(d) {
                //console.log(d)
                return _this._vScale(d.volume);
            })
            .y1(function(d) {
                return _this.height-_this.padding.bottom;
            });

        var arr =   this._view._linesHolder.selectAll('path.areas')
            .data([this._data.VOLUME])
            .enter().append("path")
            .style("fill", '#cccccc')
            .attr("class", "areas")
            .attr("d", this._volumeArea);

        // _drawSentiment.call(this);
    }

    /// COLOUR TEST
    var _drawSentiment = function(){
        var _this = this;
        var _colourBars = this._view._linesHolder.selectAll('coloBar')
            .data(this.data.TICKS)
            .enter().append('rect')
            .attr("x", function(d, i) {
                return  _this._xScale(d.date) ;
            })
            .attr("width", 4)
            .attr("y", 10)

            .attr("height", function(d,i) { return 60 })
            .attr('fill', function(d,i){return ColourRamp.getColour( d.volume)})
    }

    return _scope;
})();

LeaveChart.stringToDate = function(string){
    var _arr = string.split(":");
    _arr[2] = "20"+ _arr[2]
    var _date = new Date();
    _date.setDate(_arr[0])
    _date.setMonth(_arr[1])
    _date.setFullYear(_arr[2])

    return _date
}<commit_msg>The circles now drawing for the days.<commit_after>/**
 * Created by grahamcapham on 16/02/2015.
 */

LeaveChart = (function(targID){

    var _scope = function(targID){
        this._targID        = targID;
        this._target        = null;
        this.width          = 1400;
        this.height         = 1000;
        this.backgroundColor     = "rgba(20,30,50, 10)";
        this._canvas        = null;
        this._data          = null;
        this._lines         = null;
        this._volumeArea    = null;
        this._dots          = null;
        this._brush         = null;
        this._vScale        = null;
        this._vMin          = null;
        this._vMax          = null;
        this._vDomainMin    = null;
        this._vDomainMax    = null;
        this._xScale        = null;
        this._brushXScale   = null;
        this._xMin          = null;
        this._xMax          = null;
        this._xDomainMin    = null;
        this._xDomainMax    = null;
        this._Yoffset        = 30;
        this._months         = 12

        this._view          = {svg:null, _linesHolder:null};
        this.padding        = {left:150, right:20, top:50, bottom:160}

        _init.call(this);
    }
    //----
    _scope.prototype = {
        setData:function(value){
            this._data = value;
            _onDataSet.call(this);
        }
    };
    //-- callbacks
    var _init = function(){
        this._target = document.getElementById( this._targID );

        console.log("SVG INITED ", this._target)

        _initSVG.call(this);
    };

    var _initScale = function(){
        this._vScale = d3.scale.linear()
            .domain([this._vMin, this._vMax])
            .range([this._vDomainMin, this._vDomainMax]);
        return Math.ceil( vScale(value) )
    };

    var _initSVG = function(){
        this._view._svg = d3.select(this._target)
            .style('position', 'relative')
            .style('width', this.width+ "px")
            .style('height', this.height+ "px")
            .style('background-color',  this.backgroundColor)
            .append('svg:svg')
            .attr('width',this.width)
            .attr('height',this.height )
            .attr('class', "myClass")
//            .attr('transform', "translate(" + this.padding.left + "," + this.padding.top  + ")");

        this._view._linesHolder = this._view._svg
            .append("g")
            .attr('class', 'lineHolder')
            .attr('transform', "translate(" + this.padding.left + "," + this.padding.top  + ")");

        this._view._dotHolder = this._view._svg
            .append("g")
            .attr('class', 'dotHolder')
            .attr('transform', "translate(" + this.padding.left + "," + this.padding.top  + ")");
    };

    var _initNameAxis = function(){
        this._view._nameHolder = this._view._svg
            .append("g")
            .attr('class', 'nameHolder')
            .attr('transform', "translate(" + 0 + "," + this.padding.top  + ")");

        var _names =  _.filter(_.uniq(_.map(this._data, "name")), function(n){
            return _.isString(n)
        })

        var names =  _.uniq(this._data, "name")
//        _.filter(_.uniq(_.map(this._data, "name")), function(n){
//            return _.isString(n)
//        })
        var _this = this

        this._nameList = this._view._nameHolder
            .selectAll(".names")
            .data(names)
            .enter().append('g')
            .attr("class", "names")
            .attr("transform", function(d, i) {
                return "translate("+0+","+ (d.userid-1) * _this._Yoffset +")";
            })

        this._nameList
            .attr('fill', 'rgba(0,0,0,.9)')
            .append("svg:rect")
            .attr('width',this.padding.left)
            .attr('height',_this._Yoffset )
            .attr("transform", function(d, i) {
                return "translate("+0+","+ -10 +")";
            })
        this._nameList
            .append("svg:line")
            .attr("x1", 0)
            .attr("y1", 0)
            .attr("x2", 1500)
            .attr("y2", 0)
            .style("stroke-dasharray", ("1, 1"))
            .attr("stroke-width", 1)
            .attr("stroke", "rgba(255, 255, 255, .2)");

        this._nameList
            .append("text")
            .attr('fill', '#ffffff')
            .text(function(d,i){return d.name })
            .attr("dy", "0.4em")
            .attr("dx", "1.3em")

      //  this._nameList.exit().remove();

    }

    var _initTimeAxis = function(){

        var _this = this;

        this._view._xAxis = d3.svg.axis()
            .scale(this._xScale)
            .orient("bottom")
            .ticks(d3.time.week,12)
            .tickSize(-_this.height, 0, 0)
            .tickFormat(d3.time.format("%b %d %Y"));

        this._view._xAxisBrush = d3.svg.axis()
            .scale(this._xScale)
            .orient("bottom")
            .ticks(d3.time.month,1)
            .tickFormat(d3.time.format("%b %Y"));

        var _this = this
        this._view._xAxisHolder = this._view._svg.append("g")
            .attr("transform","translate("+this.padding.left+"," + ( _this.height - _this.padding.bottom ) + ")")
            .attr("class", "x axis")
            .attr("class","xTimeAxis");

        this._view._xTickHolder = this._view._svg.append("g")
            .attr("transform","translate("+this.padding.left+"," + ( _this.height - _this.padding.bottom ) + ")")
            .attr("class","xTimeAxisTicks")

        this._view._xAxisTicks =  this._view._xTickHolder.selectAll('.tickY')
            .data(_this._xScale.ticks(d3.time.day))

        this._view._xAxisTicks
            .enter()
            .append("g")
            .attr('class', 'tickY')
            .append("svg:line")
            .attr("x1", _this._xScale)
            .attr("x2", _this._xScale)
//            .attr("y1", -300)
//            .attr("y2", 200 )
            .attr("class", "yTickLine" )

        this._view._xAxisTicks
            .exit()
            .remove();

        _updateTimeAxis.call(this);
    }

    var _updateTimeAxis = function(){
        var _this = this
        this._view._xAxisHolder
            .call(_this._view._xAxis);
    }

    var _intBrush = function(){
        var _this = this;

        this._brush = new d3.svg.brush()
            .x(this._brushXScale)
            .on("brush", function(){ _brushFunction.call(_this);  })
            .extent([this.min_max_date[0], this.min_max_date[1]]);

        this._view._brushHolder = this._view._svg
            .append("g")
            .attr('transform', "translate(" + this.padding.left + "," + 0 + ")")
            .attr("class", "x brush")
            .call(this._brush)

        this._view._brushHolder
            .selectAll("rect")
            .attr("y", -6)
            .attr("height", this.padding.top);

        var _this = this;

        this._view._brusAxishHolder = this._view._svg
            .append("g")
            .attr("class", "brushDateAxis")
            .attr('transform', "translate(" + this.padding.left + "," + 0  + ")")
            .call(this._view._xAxisBrush)

        var handles = this._view._brushHolder
            .selectAll(".resize")
            .append("svg:rect")
            .attr("width", 10)
            .attr("class", "brush-handle")
            .attr("height", this.padding.top)
            .attr("y", -6)
            .attr("fill", '#ff0000');

        console.log("_brusAxishHolder _",this._view._brusAxishHolder)
        console.log("HANDLES _",handles)
    }

    var monthDiff = function(d1, d2) {
        var months;
        months = (d2.getFullYear() - d1.getFullYear()) * 12;
        months -= d1.getMonth() + 1;
        months += d2.getMonth();
        return months <= 0 ? 0 : months;
    }

    var _brushFunction = function(e){
        this._xScale.domain(this._brush.empty() ? this._xScale.domain() : this._brush.extent());

        this._months  = monthDiff(this._brush.extent()[0], this._brush.extent()[1])

        console.log(this._months)

        if(this._months<=1){
            this._view._xAxis
                .ticks(d3.time.day,1)
                .tickFormat(d3.time.format("%b %d"));

        }
        if(this._months>1 && this._months<3){
            this._view._xAxis
                .ticks(d3.time.week,1)
                .tickFormat(d3.time.format("%b %Y"));

        }
        if(this._months>3){
            this._view._xAxis
                .ticks(d3.time.month,1)
                .tickFormat(d3.time.format("%b %d %Y"));
        }

        var _xAx = this._view._xAxisHolder
                    .call(this._view._xAxis);

        _updateDots.call(this);

    }

    var _onDataSet = function(){
        this.min_max_date = d3.extent(this._data, function(d) { return d.jsDate; });
        console.log("MIN AND MAX ",this.min_max_date);

       this._xScale = d3.time.scale()
           .domain( this.min_max_date  )
           .range([0, this.width - this.padding.left - this.padding.right]);

        this._brushXScale   = d3.time.scale()
            .domain( this.min_max_date  )
            .range([0 , this.width - this.padding.left - this.padding.right]);

        this._brushXScaleStatic   = d3.time.scale()
            .domain( this.min_max_date  )
            .range([0, this.width - this.padding.left - this.padding.right]);

        _draw.call(this);
    };

    var _draw = function(){
        _initTimeAxis.call(this);
        _intBrush.call(this);
        _drawDots.call(this);
        _initNameAxis.call(this);
    };

    var _drawDots = function(){
        var _this = this;
        this._dots = this._view._dotHolder.selectAll('.dot')
                    .data(this._data)

        var arc = d3.svg.arc()
            .outerRadius(6)
            .startAngle(0)
            .endAngle(function(d, i) { return Math.PI; });

        var _makeArc = function(){
            var arc = d3.svg.arc()
                .outerRadius(9)
                .innerRadius(3)
                .startAngle(0)
                .endAngle(function(d, i) { return Math.PI; });
            return arc
        }

        this._dots
            .enter().append('g')
            .attr("class", "dot")
            .attr("transform", function(d, i) {
                return "translate("+_this._xScale(d.jsDate)+","+ ( (d.userid * _this._Yoffset) - _this._Yoffset)+")";
            })
        var radius = _this._Yoffset/4

        this._dots
            .append('svg:path')
            .attr("d", _makeArc() )
            .attr("transform", function(d) {
                return d.unit == 'AM' ? "rotate(90)" : "rotate(-90)"
            })

        //.attr("x", function(d, i) {
        //        return  0 ;
        //    })
        //    .attr("r", radius)
        //    .attr("y", function(d,i){
        //        //return d.userid * 20
        //        return   d.unit == 'AM' ? radius*4 : 0;
        //    })
            //.attr("height", function(d,i) { return _this._Yoffset/2 })
            .attr('fill', function(d,i){return  d.unit == 'AM' ? 'rgba(0,255,0,.5)' : 'rgba(255,0,0,1)'})
            .on('click', function(d,i){
                console.log(d)
                var _d = d
//                _.remove(_this._data, function(n) {
//                    return n == _d;
//                });
//
//                console.log(_this._data.length)
//                _updateDots.call(_this);
            })
        _updateDots.call(this)
    }

    var _updateDots = function(){
        var _this = this;

        this._dots = this._view._dotHolder.selectAll('.dot')
            .data(this._data)

        this._dots.exit().remove()

        var _this = this
        this._dots
            .transition()
            .duration(0)
            .attr("transform", function(d, i) {
                return "translate("+_this._xScale(d.jsDate)+","+ ( (d.userid * _this._Yoffset) - _this._Yoffset)+")";
            })
    }

    /// COLOUR TEST

    return _scope;
})();

LeaveChart.stringToDate = function(string){
    var _arr = string.split(":");
    _arr[2] = "20"+ _arr[2]
    var _date = new Date();
    _date.setDate(_arr[0])
    _date.setMonth(_arr[1])
    _date.setFullYear(_arr[2])

    return _date
}
<|endoftext|>


<commit_before>/* global AutoForm, _, Template */

AutoForm.addInputType("noUiSlider", {
  template: "afNoUiSlider",
  valueOut: function(){
    var slider = this.find('.nouislider');

    if( this.attr("data-type") === "Object" ){
      var first = parseInt(slider.val()[0]);
      var second = parseInt(slider.val()[1]);
      var value = {
        lower: first > second ? second : first,
        upper: first > second ? first : second
      };
      return value;
    }else{
      return slider.val();
    }
  }
});

Template.afNoUiSlider.helpers({
  atts: function () {
    var data = Template.currentData(); // get data reactively
    var atts = data.atts;
    atts["data-type"] = data.schemaType.name;
    if( atts["class"] ){
      atts["class"] += " at-nouislider";
    }else{
      atts["class"] = "at-nouislider";
    }

    atts.doLabels = ( atts.labelLeft || atts.labelRight );

    return _.omit(atts, 'noUiSliderOptions', 'noUiSlider_pipsOptions');
  }
});

var calculateOptions = function(data){
  var schemaMinMax = _.pick(data, 'max', 'min');
  var autoformOptions = _.pick(data.atts || {}, 'max', 'min', 'step', 'start', 'range');
  var noUiSliderOptions = (data.atts || {}).noUiSliderOptions;

  var options = _.extend({}, schemaMinMax, autoformOptions, noUiSliderOptions);

  // Adjust data initalization based on schema type
  if( options.start === undefined ){
    if( data.schemaType.name === "Object" ){
      if( data.value && data.value.lower ){
        options.start = [
          data.value.lower,
          data.value.upper
        ];
      }else{
        options.start = [
          typeof data.min === "number" ? data.min : 0,
          typeof data.max === "number" ? data.max : 100
        ];
      }
      options.connect = true;
    }else{
      options.start = data.value || 0;
    }
  } else {
    options.start = JSON.parse(options.start);
  }

  if( options.range === undefined ){
    options.range = {
      min: typeof options.min === "number" ? options.min : 0,
      max: typeof options.max === "number" ? options.max : 100
    };
  } else {
    options.range = JSON.parse(options.range);
  }
  delete options.min;
  delete options.max;

  // default step to 1 if not otherwise defined
  if( options.step === undefined ){
    options.step = 1;
  }

  return options;
};

Template.afNoUiSlider.rendered = function () {
  var template = this;
  var $s = template.$('.nouislider');

  var setup = function(c){
    var data = Template.currentData(); // get data reactively
    var options = calculateOptions( data );
    $s.noUiSlider(options, true);

    if (c.firstRun) {
      $s.on('slide', function(){
        // This is a trick to fool some logic in AutoForm that makes
        // sure values have actually changed on whichever element
        // emits a change event. Eventually AutoForm will give
        // input types the control of indicating exactly when
        // their value changes rather than relying on the change event
        $s.parent()[0].value = JSON.stringify($s.val());
        $s.parent().change();
        $s.data('changed','true');
      });
    }

    if( data.atts.noUiSlider_pipsOptions ){
      $s.noUiSlider_pips(
        data.atts.noUiSlider_pipsOptions
      );
    }
  };

  template.autorun( setup );
};
<commit_msg>Decimal value support for range sliders<commit_after>/* global AutoForm, _, Template */

AutoForm.addInputType("noUiSlider", {
  template: "afNoUiSlider",
  valueOut: function(){
    var slider = this.find('.nouislider');
    var isDecimal = this.closest(".at-nouislider").data("decimal");

    if( this.attr("data-type") === "Object" ){
      var parser = (isDecimal)? parseFloat : parseInt;
      var first = parser.call(null, slider.val()[0]);
      var second = parser.call(null, slider.val()[1]);
      var value = {
        lower: first > second ? second : first,
        upper: first > second ? first : second
      };
      return value;
    }else{
      return slider.val();
    }
  }
});

Template.afNoUiSlider.helpers({
  atts: function () {
    var data = Template.currentData(); // get data reactively
    var atts = data.atts;
    atts["data-type"] = data.schemaType.name;
    if( atts["class"] ){
      atts["class"] += " at-nouislider";
    }else{
      atts["class"] = "at-nouislider";
    }

    atts.doLabels = ( atts.labelLeft || atts.labelRight );

    atts["data-decimal"] = data.decimal;

    return _.omit(atts, 'noUiSliderOptions', 'noUiSlider_pipsOptions');
  }
});

var calculateOptions = function(data){
  var schemaMinMax = _.pick(data, 'max', 'min');
  var autoformOptions = _.pick(data.atts || {}, 'max', 'min', 'step', 'start', 'range');
  var noUiSliderOptions = (data.atts || {}).noUiSliderOptions;

  var options = _.extend({}, schemaMinMax, autoformOptions, noUiSliderOptions);

  // Adjust data initalization based on schema type
  if( options.start === undefined ){
    if( data.schemaType.name === "Object" ){
      if( data.value && data.value.lower ){
        options.start = [
          data.value.lower,
          data.value.upper
        ];
      }else{
        options.start = [
          typeof data.min === "number" ? data.min : 0,
          typeof data.max === "number" ? data.max : 100
        ];
      }
      options.connect = true;
    }else{
      options.start = data.value || 0;
    }
  } else {
    options.start = JSON.parse(options.start);
  }

  if( options.range === undefined ){
    options.range = {
      min: typeof options.min === "number" ? options.min : 0,
      max: typeof options.max === "number" ? options.max : 100
    };
  } else {
    options.range = JSON.parse(options.range);
  }
  delete options.min;
  delete options.max;

  // default step to 1 if not otherwise defined
  if( options.step === undefined ){
    options.step = 1;
  }

  return options;
};

Template.afNoUiSlider.rendered = function () {
  var template = this;
  var $s = template.$('.nouislider');

  var setup = function(c){
    var data = Template.currentData(); // get data reactively
    var options = calculateOptions( data );
    $s.noUiSlider(options, true);

    if (c.firstRun) {
      $s.on('slide', function(){
        // This is a trick to fool some logic in AutoForm that makes
        // sure values have actually changed on whichever element
        // emits a change event. Eventually AutoForm will give
        // input types the control of indicating exactly when
        // their value changes rather than relying on the change event
        $s.parent()[0].value = JSON.stringify($s.val());
        $s.parent().change();
        $s.data('changed','true');
      });
    }

    if( data.atts.noUiSlider_pipsOptions ){
      $s.noUiSlider_pips(
        data.atts.noUiSlider_pipsOptions
      );
    }
  };

  template.autorun( setup );
};
<|endoftext|>


<commit_before>'use strict'

import { Component }        from 'react'
import DocumentTitle        from 'react-document-title'

import ContentSection       from '../components/ContentSection'
import TeamMembers       from '../components/TeamMembers'

class AboutPage extends Component {

  constructor(props) {
    super(props)
  }

  render() {

    return (
      <DocumentTitle title="Blockstack - About">

                          Our Mission

                    <ContentSection className="" markup="

                        Blockstack is a new decentralized internet where you own your data and apps run
                        locally without remote servers.

                        Blockstack is an open source project with core developers and contributors
                        located around the world, from New York City to Hong Kong.

                        At Blockstack, we welcome developers and entrepreneurs of all kinds. Join our
                        community and build your own app or contribute to the core software.

                    "/>

                          Blockstack Public Benefit Corp

                    <ContentSection className="" markup="

                        Blockstack is a new decentralized internet where you own your data and apps run
                        locally without remote servers.

                        Blockstack is an open source project with core developers and contributors
                        located around the world, from New York City to Hong Kong.

                        At Blockstack, we welcome developers and entrepreneurs of all kinds. Join our
                        community and build your own app or contribute to the core software.

                    "/>

                    <TeamMembers />

      </DocumentTitle>
    )
  }

}

export default AboutPage

<commit_msg>update to headline<commit_after>'use strict'

import { Component }        from 'react'
import DocumentTitle        from 'react-document-title'

import ContentSection       from '../components/ContentSection'
import TeamMembers       from '../components/TeamMembers'

class AboutPage extends Component {

  constructor(props) {
    super(props)
  }

  render() {

    return (
      <DocumentTitle title="Blockstack - About">

                          Our Mission

                    <ContentSection className="" markup="

                        Blockstack is a new decentralized internet where you own your data and apps run
                        locally without remote servers.

                        Blockstack is an open source project with core developers and contributors
                        located around the world, from New York City to Hong Kong.

                        At Blockstack, we welcome developers and entrepreneurs of all kinds. Join our
                        community and build your own app or contribute to the core software.

                    "/>

                          Blockstack is a Public Benefit Corp

                    <ContentSection className="" markup="

                        Blockstack is a new decentralized internet where you own your data and apps run
                        locally without remote servers.

                        Blockstack is an open source project with core developers and contributors
                        located around the world, from New York City to Hong Kong.

                        At Blockstack, we welcome developers and entrepreneurs of all kinds. Join our
                        community and build your own app or contribute to the core software.

                    "/>

                    <TeamMembers />

      </DocumentTitle>
    )
  }

}

export default AboutPage

<|endoftext|>


<commit_before>$(document).ready(function() {
  var meetingURL = "";
  var meetingId = "";
  // meetingLinkGrabber();
  joinYoMeeting();

});

var meetingFrame = function(){
  $('#user4').click(function () {
    event.preventDefault();
    console.log('clicked the video listener');

    document.getElementById('master-of-API').innerHTML='<object class="video" style="margin: 80px 0px 0px 0px; height: 85vh; width: 100%;" type="text/html" data=' + meetingURL + '></object>';
  });
};
// To Join a Meeting that is fleeting
var joinYoMeeting = function(){
  $.ajax(
  {
    url: "https://sandbox.liveh2h.com/tutormeetweb/rest/v1/meetings/join",
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(
    {
      "email":"hello@yomama.com",
      "meetingId": "011351636",
      "name":"Matt"
    }),
    success: function(resp, status, xhr){
      meetingURL = resp.data.meetingURL
      meetingFrame();
    },
    error: function () {
      //Error message or call back function
    }
  })
}
// Grabs meeting URL and meeting ID
var meetingLinkGrabber = function() {
  var request = $.ajax({
    url: "https://sandbox.liveh2h.com/tutormeetweb/rest/v1/meetings/createInstantMeeting",
    method: "POST",
    headers: {"Content-Type": "application/json"},
    data: JSON.stringify({
      "customLayouts":[
        {"component": "string",
        "width": 12,
        "height": 12
      }
    ],
    "applicationId": "9155BF89-2C10-4E43-88F3-73748AC158D0",
    "name": "mannah",
    "templateId": "DA22B2BF-19FE-4463-8FBC-508683D4A76D"
  })
});

request.done(function(response) {
  // console.log('response', response.data);
  meetingURL = response.data.meetingURL;
  console.log('meetingURL', meetingURL);
  meetingId = response.data.meetingId;
  console.log('meetingId', meetingId);
  meetingFrame();
});

request.fail(function(response) {
  alert("An error occured.");
});
};
<commit_msg>fix and suggest meeting solutions<commit_after>$(document).ready(function() {
  var meetingURL = "";
  var meetingId = "";
  // meetingLinkGrabber();
  joinYoMeeting();

});

var meetingFrame = function(){
  $('#user4').click(function () {
    event.preventDefault();
    console.log('clicked the video listener');

    document.getElementById('master-of-API').innerHTML='<object class="video" style="margin: 80px 0px 0px 0px; height: 85vh; width: 100%;" type="text/html" data=' + meetingURL + '></object>';
  });
};
// For the best meetings, hit up slack
// To Join a Meeting that is fleeting
var joinYoMeeting = function(){
  $.ajax(
  {
    url: "https://sandbox.liveh2h.com/tutormeetweb/rest/v1/meetings/join",
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(
    {
      "email":"hello@yomama.com",
      "meetingId": "011351636",
      "name":"Matt"
    }),
    success: function(resp, status, xhr){
      meetingURL = resp.data.meetingURL
      meetingFrame();
    },
    error: function () {
      //Error message or call back function
    }
  })
}
// Grabs meeting URL and meeting ID
var meetingLinkGrabber = function() {
  var request = $.ajax({
    url: "https://sandbox.liveh2h.com/tutormeetweb/rest/v1/meetings/createInstantMeeting",
    method: "POST",
    headers: {"Content-Type": "application/json"},
    data: JSON.stringify({
      "customLayouts":[
        {"component": "string",
        "width": 12,
        "height": 12
      }
    ],
    "applicationId": "9155BF89-2C10-4E43-88F3-73748AC158D0",
    "name": "mannah",
    "templateId": "DA22B2BF-19FE-4463-8FBC-508683D4A76D"
  })
});

request.done(function(response) {
  // console.log('response', response.data);
  meetingURL = response.data.meetingURL;
  console.log('meetingURL', meetingURL);
  meetingId = response.data.meetingId;
  console.log('meetingId', meetingId);
  meetingFrame();
});

request.fail(function(response) {
  alert("An error occured.");
});
};
<|endoftext|>


<commit_before>var User = require('../models/User.js');

var WeChatManager = function() {};

WeChatManager.prototype.doAction = function(req, res) {
    var oMsg = req.weixin;
    console.log('User OpenId: ' + oMsg.FromUserName);
    console.log('User text: ' + oMsg.Content);

    var sMsgType = oMsg.MsgType;
    if (sMsgType === 'event') {
        this.doEvent(sMsgType, req, res);
    } else {
        res.reply('Weaves Fun!! We are better with you!');
    }
};

WeChatManager.prototype.doEvent = function(sType, req, res) {
    var oMsg = req.weixin;
    var sWechatId = oMsg.FromUserName;
    if (sType === 'subscribe') {
        User.find({wechatId: sWechatId}, function(err, oUser) {

            if(!oUser) {
                var oNewUser = new User({
                    wechatId: sWechatId
                });

                oNewUser.save(function(err) {
                    if(err) {
                        console.log('Error while saving user: ' + err);
                        return;
                    } else {
                        console.log("User created");
                        return;
                    }
                });
            }

            if(!err) {
                res.reply('您已经关注了 微服私纺');
                return;
            } else {
                console.log('Internal error(%d): %s', res.statusCode, err.message);
                return;
                //return res.send({ error: 'Server error' });
            }
        });

        res.reply('感谢您关注 微服私纺');
        return;
    } else if (sType === 'unsubscribe') {
        console.log('Users: ' + sWechatId + ' has unsubscribed us!');
        return;
    } else {
        res.reply('Event not supported yet.');
        return;
    }
};

module.exports.WeChatManager = WeChatManager;
<commit_msg>api 6<commit_after>var User = require('../models/User.js');

var WeChatManager = function() {};

WeChatManager.prototype.doAction = function(req, res) {
    var oMsg = req.weixin;
    console.log('User OpenId: ' + oMsg.FromUserName);
    console.log('User text: ' + oMsg.Content);

    var sMsgType = oMsg.MsgType;
    if (sMsgType === 'event') {
        this.doEvent(req, res);
    } else {
        res.reply('Weaves Fun!! We are better with you!');
    }
};

WeChatManager.prototype.doEvent = function(req, res) {
    var oMsg = req.weixin;
    var sWechatId = oMsg.FromUserName;
    var sEventType = oMsg.Event;
    if (sEventType === 'subscribe') {
        User.find({wechatId: sWechatId}, function(err, oUser) {

            if(!oUser) {
                var oNewUser = new User({
                    wechatId: sWechatId
                });

                oNewUser.save(function(err) {
                    if(err) {
                        console.log('Error while saving user: ' + err);
                        return;
                    } else {
                        console.log("User created");
                        return;
                    }
                });
            }

            if(!err) {
                res.reply('您已经关注了 微服私纺');
                return;
            } else {
                console.log('Internal error(%d): %s', res.statusCode, err.message);
                return;
                //return res.send({ error: 'Server error' });
            }
        });

        res.reply('感谢您关注 微服私纺');
        return;
    } else if (sEventType === 'unsubscribe') {
        console.log('Users: ' + sWechatId + ' has unsubscribed us!');
        return;
    } else {
        res.reply('Event not supported yet.');
        return;
    }
};

module.exports.WeChatManager = WeChatManager;
<|endoftext|>