<commit_before>var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var taskManager = require('../common/manager/taskManager');
var pomelo = require('../pomelo');
var rsa = require("node-bignumber");
var events = require('../util/events');
var utils = require('../util/utils');

module.exports = function(app, opts) {
  return new Component(app, opts);
};

/**
 * Connector component. Receive client requests and attach session with socket.
 *
 * @param {Object} app  current application context
 * @param {Object} opts attach parameters
 *                      opts.connector {Object} provides low level network and protocol details implementation between server and clients.
 */
var Component = function(app, opts) {
  opts = opts || {};
  this.app = app;
  this.connector = getConnector(app, opts);
  this.encode = opts.encode;
  this.decode = opts.decode;
  this.useCrypto = opts.useCrypto;
  this.useAsyncCoder = opts.useAsyncCoder;
  this.blacklistFun = opts.blacklistFun;
  this.keys = {};
  this.blacklist = [];

  if (opts.useDict) {
    app.load(pomelo.dictionary, app.get('dictionaryConfig'));
  }

  if (opts.useProtobuf) {
    app.load(pomelo.protobuf, app.get('protobufConfig'));
  }

  // component dependencies
  this.server = null;
  this.session = null;
  this.connection = null;
};

var pro = Component.prototype;

pro.name = '__connector__';

pro.start = function(cb) {
  this.server = this.app.components.__server__;
  this.session = this.app.components.__session__;
  this.connection = this.app.components.__connection__;

  // check component dependencies
  if (!this.server) {
    process.nextTick(function() {
      utils.invokeCallback(cb, new Error('fail to start connector component for no server component loaded'));
    });
    return;
  }

  if (!this.session) {
    process.nextTick(function() {
      utils.invokeCallback(cb, new Error('fail to start connector component for no session component loaded'));
    });
    return;
  }

  process.nextTick(cb);
};

pro.afterStart = function(cb) {
  this.connector.start(cb);
  this.connector.on('connection', hostFilter.bind(this, bindEvents));
};

pro.stop = function(force, cb) {
  if (this.connector) {
    this.connector.stop(force, cb);
    this.connector = null;
    return;
  } else {
    process.nextTick(cb);
  }
};

pro.send = function(reqId, route, msg, recvs, opts, cb) {
  logger.debug('[%s] send message reqId: %s, route: %s, msg: %j, receivers: %j, opts: %j', this.app.serverId, reqId, route, msg, recvs, opts);
  if (this.useAsyncCoder) {
    return this.sendAsync(reqId, route, msg, recvs, opts, cb);
  }

  var emsg = msg;
  if (this.encode) {
    // use costumized encode
    emsg = this.encode.call(this, reqId, route, msg);
  } else if (this.connector.encode) {
    // use connector default encode
    emsg = this.connector.encode(reqId, route, msg);
  }

  this.doSend(reqId, route, emsg, recvs, opts, cb);
};

pro.sendAsync = function(reqId, route, msg, recvs, opts, cb) {
  var emsg = msg;
  var self = this;

  if (this.encode) {
    // use costumized encode
    this.encode.call(this, reqId, route, msg, function(err, encodeMsg) {
      if (err) {
        return cb(err);
      }

      emsg = encodeMsg;
      self.doSend(reqId, route, emsg, recvs, opts, cb);
    });
  } else if (this.connector.encode) {
    // use connector default encode
    this.connector.encode(reqId, route, msg, function(err, encodeMsg) {
      if (err) {
        return cb(err);
      }

      emsg = encodeMsg;
      self.doSend(reqId, route, emsg, recvs, opts, cb);
    });
  }
}

pro.doSend = function(reqId, route, emsg, recvs, opts, cb) {
  if (!emsg) {
    process.nextTick(function() {
      return cb && cb(new Error('fail to send message for encode result is empty.'));
    });
  }

  this.app.components.__pushScheduler__.schedule(reqId, route, emsg,
    recvs, opts, cb);
}

pro.setPubKey = function(id, key) {
  var pubKey = new rsa.Key();
  pubKey.n = new rsa.BigInteger(key.rsa_n, 16);
  pubKey.e = key.rsa_e;
  this.keys[id] = pubKey;
};

pro.getPubKey = function(id) {
  return this.keys[id];
};

var getConnector = function(app, opts) {
  var connector = opts.connector;
  if (!connector) {
    return getDefaultConnector(app, opts);
  }

  if (typeof connector !== 'function') {
    return connector;
  }

  var curServer = app.getCurServer();
  return connector(curServer.clientPort, curServer.host, opts);
};

var getDefaultConnector = function(app, opts) {
  var DefaultConnector = require('../connectors/sioconnector');
  var curServer = app.getCurServer();
  return new DefaultConnector(curServer.clientPort, curServer.host, opts);
};

var hostFilter = function(cb, socket) {
  var ip = socket.remoteAddress.ip;
  var check = function(list) {
    for (var address in list) {
      var exp = new RegExp(list[address]);
      if (exp.test(ip)) {
        socket.disconnect();
        return true;
      }
    }
    return false;
  };
  // dynamical check
  if (this.blacklist.length !== 0 && !!check(this.blacklist)) {
    return;
  }
  // static check
  if (!!this.blacklistFun && typeof this.blacklistFun === 'function') {
    var self = this;
    self.blacklistFun(function(err, list) {
      if (!!err) {
        logger.error('connector blacklist error: %j', err.stack);
        utils.invokeCallback(cb, self, socket);
        return;
      }
      if (!Array.isArray(list)) {
        logger.error('connector blacklist is not array: %j', list);
        utils.invokeCallback(cb, self, socket);
        return;
      }
      if (!!check(list)) {
        return;
      } else {
        utils.invokeCallback(cb, self, socket);
        return;
      }
    });
  } else {
    utils.invokeCallback(cb, this, socket);
  }
};

var bindEvents = function(self, socket) {
  if (self.connection) {
    self.connection.increaseConnectionCount();
    var statisticInfo = self.connection.getStatisticsInfo();
    var curServer = self.app.getCurServer();
    if (statisticInfo.totalConnCount > curServer['max-connections']) {
      logger.warn('the server %s has reached the max connections %s', curServer.id, curServer['max-connections']);
      socket.disconnect();
      return;
    }
  }

  //create session for connection
  var session = getSession(self, socket);
  var closed = false;

  socket.on('disconnect', function() {
    if (closed) {
      return;
    }
    closed = true;
    if (self.connection) {
      self.connection.decreaseConnectionCount(session.uid);
    }
  });

  socket.on('error', function() {
    if (closed) {
      return;
    }
    closed = true;
    if (self.connection) {
      self.connection.decreaseConnectionCount(session.uid);
    }
  });

  // new message
  socket.on('message', function(msg) {
    var dmsg = msg;
    if (self.useAsyncCoder) {
      return handleMessageAsync(self, msg, session, socket);
    }

    if (self.decode) {
      dmsg = self.decode(msg, session);
    } else if (self.connector.decode) {
      dmsg = self.connector.decode(msg, socket);
    }
    if (!dmsg) {
      // discard invalid message
      return;
    }

    // use rsa crypto
    if (self.useCrypto) {
      var verified = verifyMessage(self, session, dmsg);
      if (!verified) {
        logger.error('fail to verify the data received from client.');
        return;
      }
    }

    handleMessage(self, session, dmsg);
  }); //on message end
};

var handleMessageAsync = function(self, msg, session, socket) {
  if (self.decode) {
    self.decode(msg, session, function(err, dmsg) {
      if (err) {
        logger.error('fail to decode message from client %s .', err.stack);
        return;
      }

      doHandleMessage(self, dmsg, session);
    });
  } else if (self.connector.decode) {
    self.connector.decode(msg, socket, function(err, dmsg) {
      if (err) {
        logger.error('fail to decode message from client %s .', err.stack);
        return;
      }

      doHandleMessage(self, dmsg, session);
    });
  }
}

var doHandleMessage = function(self, dmsg, session) {
  if (!dmsg) {
    // discard invalid message
    return;
  }

  // use rsa crypto
  if (self.useCrypto) {
    var verified = verifyMessage(self, session, dmsg);
    if (!verified) {
      logger.error('fail to verify the data received from client.');
      return;
    }
  }

  handleMessage(self, session, dmsg);
}

/**
 * get session for current connection
 */
var getSession = function(self, socket) {
  var app = self.app,
    sid = socket.id;
  var session = self.session.get(sid);
  if (session) {
    return session;
  }

  session = self.session.create(sid, app.getServerId(), socket);
  logger.debug('[%s] getSession session is created with session id: %s', app.getServerId(), sid);

  // bind events for session
  socket.on('disconnect', session.closed.bind(session));
  socket.on('error', session.closed.bind(session));
  session.on('closed', onSessionClose.bind(null, app));
  session.on('bind', function(uid) {
    logger.debug('session on [%s] bind with uid: %s', self.app.serverId, uid);
    // update connection statistics if necessary
    if (self.connection) {
      self.connection.addLoginedUser(uid, {
        loginTime: Date.now(),
        uid: uid,
        address: socket.remoteAddress.ip + ':' + socket.remoteAddress.port
      });
    }
    self.app.event.emit(events.BIND_SESSION, session);
  });

  session.on('unbind', function(uid) {
    if (self.connection) {
      self.connection.removeLoginedUser(uid);
    }
    self.app.event.emit(events.UNBIND_SESSION, session);
  });

  return session;
};

var onSessionClose = function(app, session, reason) {
  taskManager.closeQueue(session.id, true);
  app.event.emit(events.CLOSE_SESSION, session);
};

var handleMessage = function(self, session, msg) {
  logger.debug('[%s] handleMessage session id: %s, msg: %j', self.app.serverId, session.id, msg);
  var type = checkServerType(msg.route);
  if (!type) {
    logger.error('invalid route string. route : %j', msg.route);
    return;
  }
  self.server.globalHandle(msg, session.toFrontendSession(), function(err, resp, opts) {
    if (resp && !msg.id) {
      logger.warn('try to response to a notify: %j', msg.route);
      return;
    }
    if (!msg.id && !resp) return;
    if (!resp) resp = {};
    if (!!err && !resp.code) {
      resp.code = 500;
    }
    opts = {
      type: 'response',
      userOptions: opts || {}
    };
    // for compatiablity
    opts.isResponse = true;

    self.send(msg.id, msg.route, resp, [session.id], opts,
      function() {});
  });
};

/**
 * Get server type form request message.
 */
var checkServerType = function(route) {
  if (!route) {
    return null;
  }
  var idx = route.indexOf('.');
  if (idx < 0) {
    return null;
  }
  return route.substring(0, idx);
};

var verifyMessage = function(self, session, msg) {
  var sig = msg.body.__crypto__;
  if (!sig) {
    logger.error('receive data from client has no signature [%s]', self.app.serverId);
    return false;
  }

  var pubKey;

  if (!session) {
    logger.error('could not find session.');
    return false;
  }

  if (!session.get('pubKey')) {
    pubKey = self.getPubKey(session.id);
    if (!!pubKey) {
      delete self.keys[session.id];
      session.set('pubKey', pubKey);
    } else {
      logger.error('could not get public key, session id is %s', session.id);
      return false;
    }
  } else {
    pubKey = session.get('pubKey');
  }

  if (!pubKey.n || !pubKey.e) {
    logger.error('could not verify message without public key [%s]', self.app.serverId);
    return false;
  }

  delete msg.body.__crypto__;

  var message = JSON.stringify(msg.body);
  if (utils.hasChineseChar(message))
    message = utils.unicodeToUtf8(message);

  return pubKey.verifyString(message, sig);
};<commit_msg>review connector.js<commit_after>var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var taskManager = require('../common/manager/taskManager');
var pomelo = require('../pomelo');
var rsa = require("node-bignumber");
var events = require('../util/events');
var utils = require('../util/utils');

module.exports = function(app, opts) {
  return new Component(app, opts);
};

/**
 * Connector component. Receive client requests and attach session with socket.
 *
 * @param {Object} app  current application context
 * @param {Object} opts attach parameters
 *                      opts.connector {Object} provides low level network and protocol details implementation between server and clients.
 */
var Component = function(app, opts) {
  opts = opts || {};
  this.app = app;
  this.connector = getConnector(app, opts);
  this.encode = opts.encode;
  this.decode = opts.decode;
  this.useCrypto = opts.useCrypto;
  this.useAsyncCoder = opts.useAsyncCoder;
  this.blacklistFun = opts.blacklistFun;
  this.keys = {};
  this.blacklist = [];

  if (opts.useDict) {
    app.load(pomelo.dictionary, app.get('dictionaryConfig'));
  }

  if (opts.useProtobuf) {
    app.load(pomelo.protobuf, app.get('protobufConfig'));
  }

  // component dependencies
  this.server = null;
  this.session = null;
  this.connection = null;
};

var pro = Component.prototype;

pro.name = '__connector__';

pro.start = function(cb) {
  this.server = this.app.components.__server__;
  this.session = this.app.components.__session__;
  this.connection = this.app.components.__connection__;

  // check component dependencies
  if (!this.server) {
    process.nextTick(function() {
      utils.invokeCallback(cb, new Error('fail to start connector component for no server component loaded'));
    });
    return;
  }

  if (!this.session) {
    process.nextTick(function() {
      utils.invokeCallback(cb, new Error('fail to start connector component for no session component loaded'));
    });
    return;
  }

  process.nextTick(cb);
};

pro.afterStart = function(cb) {
  this.connector.start(cb);
  this.connector.on('connection', hostFilter.bind(this, bindEvents));
};

pro.stop = function(force, cb) {
  if (this.connector) {
    this.connector.stop(force, cb);
    this.connector = null;
    return;
  } else {
    process.nextTick(cb);
  }
};

pro.send = function(reqId, route, msg, recvs, opts, cb) {
  logger.debug('[%s] send message reqId: %s, route: %s, msg: %j, receivers: %j, opts: %j', this.app.serverId, reqId, route, msg, recvs, opts);
  if (this.useAsyncCoder) {
    return this.sendAsync(reqId, route, msg, recvs, opts, cb);
  }

  var emsg = msg;
  if (this.encode) {
    // use costumized encode
    emsg = this.encode.call(this, reqId, route, msg);
  } else if (this.connector.encode) {
    // use connector default encode
    emsg = this.connector.encode(reqId, route, msg);
  }

  this.doSend(reqId, route, emsg, recvs, opts, cb);
};

pro.sendAsync = function(reqId, route, msg, recvs, opts, cb) {
  var emsg = msg;
  var self = this;

  if (this.encode) {
    // use costumized encode
    this.encode(reqId, route, msg, function(err, encodeMsg) {
      if (err) {
        return cb(err);
      }

      emsg = encodeMsg;
      self.doSend(reqId, route, emsg, recvs, opts, cb);
    });
  } else if (this.connector.encode) {
    // use connector default encode
    this.connector.encode(reqId, route, msg, function(err, encodeMsg) {
      if (err) {
        return cb(err);
      }

      emsg = encodeMsg;
      self.doSend(reqId, route, emsg, recvs, opts, cb);
    });
  }
}

pro.doSend = function(reqId, route, emsg, recvs, opts, cb) {
  if (!emsg) {
    process.nextTick(function() {
      return cb && cb(new Error('fail to send message for encode result is empty.'));
    });
  }

  this.app.components.__pushScheduler__.schedule(reqId, route, emsg,
    recvs, opts, cb);
}

pro.setPubKey = function(id, key) {
  var pubKey = new rsa.Key();
  pubKey.n = new rsa.BigInteger(key.rsa_n, 16);
  pubKey.e = key.rsa_e;
  this.keys[id] = pubKey;
};

pro.getPubKey = function(id) {
  return this.keys[id];
};

var getConnector = function(app, opts) {
  var connector = opts.connector;
  if (!connector) {
    return getDefaultConnector(app, opts);
  }

  if (typeof connector !== 'function') {
    return connector;
  }

  var curServer = app.getCurServer();
  return connector(curServer.clientPort, curServer.host, opts);
};

var getDefaultConnector = function(app, opts) {
  var DefaultConnector = require('../connectors/sioconnector');
  var curServer = app.getCurServer();
  return new DefaultConnector(curServer.clientPort, curServer.host, opts);
};

var hostFilter = function(cb, socket) {
  var ip = socket.remoteAddress.ip;
  var check = function(list) {
    for (var address in list) {
      var exp = new RegExp(list[address]);
      if (exp.test(ip)) {
        socket.disconnect();
        return true;
      }
    }
    return false;
  };
  // dynamical check
  if (this.blacklist.length !== 0 && !!check(this.blacklist)) {
    return;
  }
  // static check
  if (!!this.blacklistFun && typeof this.blacklistFun === 'function') {
    var self = this;
    self.blacklistFun(function(err, list) {
      if (!!err) {
        logger.error('connector blacklist error: %j', err.stack);
        utils.invokeCallback(cb, self, socket);
        return;
      }
      if (!Array.isArray(list)) {
        logger.error('connector blacklist is not array: %j', list);
        utils.invokeCallback(cb, self, socket);
        return;
      }
      if (!!check(list)) {
        return;
      } else {
        utils.invokeCallback(cb, self, socket);
        return;
      }
    });
  } else {
    utils.invokeCallback(cb, this, socket);
  }
};

var bindEvents = function(self, socket) {
  if (self.connection) {
    self.connection.increaseConnectionCount();
    var statisticInfo = self.connection.getStatisticsInfo();
    var curServer = self.app.getCurServer();
    if (statisticInfo.totalConnCount > curServer['max-connections']) {
      logger.warn('the server %s has reached the max connections %s', curServer.id, curServer['max-connections']);
      socket.disconnect();
      return;
    }
  }

  //create session for connection
  var session = getSession(self, socket);
  var closed = false;

  socket.on('disconnect', function() {
    if (closed) {
      return;
    }
    closed = true;
    if (self.connection) {
      self.connection.decreaseConnectionCount(session.uid);
    }
  });

  socket.on('error', function() {
    if (closed) {
      return;
    }
    closed = true;
    if (self.connection) {
      self.connection.decreaseConnectionCount(session.uid);
    }
  });

  // new message
  socket.on('message', function(msg) {
    var dmsg = msg;
    if (self.useAsyncCoder) {
      return handleMessageAsync(self, msg, session, socket);
    }

    if (self.decode) {
      dmsg = self.decode(msg, session);
    } else if (self.connector.decode) {
      dmsg = self.connector.decode(msg, socket);
    }
    if (!dmsg) {
      // discard invalid message
      return;
    }

    // use rsa crypto
    if (self.useCrypto) {
      var verified = verifyMessage(self, session, dmsg);
      if (!verified) {
        logger.error('fail to verify the data received from client.');
        return;
      }
    }

    handleMessage(self, session, dmsg);
  }); //on message end
};

var handleMessageAsync = function(self, msg, session, socket) {
  if (self.decode) {
    self.decode(msg, session, function(err, dmsg) {
      if (err) {
        logger.error('fail to decode message from client %s .', err.stack);
        return;
      }

      doHandleMessage(self, dmsg, session);
    });
  } else if (self.connector.decode) {
    self.connector.decode(msg, socket, function(err, dmsg) {
      if (err) {
        logger.error('fail to decode message from client %s .', err.stack);
        return;
      }

      doHandleMessage(self, dmsg, session);
    });
  }
}

var doHandleMessage = function(self, dmsg, session) {
  if (!dmsg) {
    // discard invalid message
    return;
  }

  // use rsa crypto
  if (self.useCrypto) {
    var verified = verifyMessage(self, session, dmsg);
    if (!verified) {
      logger.error('fail to verify the data received from client.');
      return;
    }
  }

  handleMessage(self, session, dmsg);
}

/**
 * get session for current connection
 */
var getSession = function(self, socket) {
  var app = self.app,
    sid = socket.id;
  var session = self.session.get(sid);
  if (session) {
    return session;
  }

  session = self.session.create(sid, app.getServerId(), socket);
  logger.debug('[%s] getSession session is created with session id: %s', app.getServerId(), sid);

  // bind events for session
  socket.on('disconnect', session.closed.bind(session));
  socket.on('error', session.closed.bind(session));
  session.on('closed', onSessionClose.bind(null, app));
  session.on('bind', function(uid) {
    logger.debug('session on [%s] bind with uid: %s', self.app.serverId, uid);
    // update connection statistics if necessary
    if (self.connection) {
      self.connection.addLoginedUser(uid, {
        loginTime: Date.now(),
        uid: uid,
        address: socket.remoteAddress.ip + ':' + socket.remoteAddress.port
      });
    }
    self.app.event.emit(events.BIND_SESSION, session);
  });

  session.on('unbind', function(uid) {
    if (self.connection) {
      self.connection.removeLoginedUser(uid);
    }
    self.app.event.emit(events.UNBIND_SESSION, session);
  });

  return session;
};

var onSessionClose = function(app, session, reason) {
  taskManager.closeQueue(session.id, true);
  app.event.emit(events.CLOSE_SESSION, session);
};

var handleMessage = function(self, session, msg) {
  logger.debug('[%s] handleMessage session id: %s, msg: %j', self.app.serverId, session.id, msg);
  var type = checkServerType(msg.route);
  if (!type) {
    logger.error('invalid route string. route : %j', msg.route);
    return;
  }
  self.server.globalHandle(msg, session.toFrontendSession(), function(err, resp, opts) {
    if (resp && !msg.id) {
      logger.warn('try to response to a notify: %j', msg.route);
      return;
    }
    if (!msg.id && !resp) return;
    if (!resp) resp = {};
    if (!!err && !resp.code) {
      resp.code = 500;
    }
    opts = {
      type: 'response',
      userOptions: opts || {}
    };
    // for compatiablity
    opts.isResponse = true;

    self.send(msg.id, msg.route, resp, [session.id], opts,
      function() {});
  });
};

/**
 * Get server type form request message.
 */
var checkServerType = function(route) {
  if (!route) {
    return null;
  }
  var idx = route.indexOf('.');
  if (idx < 0) {
    return null;
  }
  return route.substring(0, idx);
};

var verifyMessage = function(self, session, msg) {
  var sig = msg.body.__crypto__;
  if (!sig) {
    logger.error('receive data from client has no signature [%s]', self.app.serverId);
    return false;
  }

  var pubKey;

  if (!session) {
    logger.error('could not find session.');
    return false;
  }

  if (!session.get('pubKey')) {
    pubKey = self.getPubKey(session.id);
    if (!!pubKey) {
      delete self.keys[session.id];
      session.set('pubKey', pubKey);
    } else {
      logger.error('could not get public key, session id is %s', session.id);
      return false;
    }
  } else {
    pubKey = session.get('pubKey');
  }

  if (!pubKey.n || !pubKey.e) {
    logger.error('could not verify message without public key [%s]', self.app.serverId);
    return false;
  }

  delete msg.body.__crypto__;

  var message = JSON.stringify(msg.body);
  if (utils.hasChineseChar(message))
    message = utils.unicodeToUtf8(message);

  return pubKey.verifyString(message, sig);
};<|endoftext|>


<commit_before>console.log("in script.js");

var g_params = '';
var g_iframe = '';

function checkUserDevice() {

    var isIPhone = false;
    var useragent = navigator.userAgent.toLowerCase();

    if( useragent.search("iphone") )
        isIPhone = true;
    else if( useragent.search("ipod") )
        ; // ipod
    else if( useragent.search("android") )
        ; // android

    console.log("is iphone : " + isIPhone);
    return isIPhone;
}

function generateEmbedPlayer(playlistid, ownerid) {

    var iframe = ''

    iframe = iframe.replace("__OWNERID__", ownerid);
    iframe = iframe.replace("__PLAYLISTID__","playlistid");

    return iframe;
}

function getHashParams(hashString) {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = hashString;
    while (e = r.exec(q)) {
        hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
}

deli = '?';

function main() {

    console.log("main fucntion");

    var hash = window.location.hash;

   var state;
   var params = {};
   var hashString;

   if (hash.length > 1) {

       var hashString = hash.substring(1);
       g_params = getHashParams(hashString);
       params = g_params;
   } else {
       state = 'init';
   }

   var playlistId = params.playlistid;
   var ownerId = params.ownerid;

   var iframe = generateEmbedPlayer(playlistId, ownerId);

   console.log("iframe : " + iframe);

   g_iframe = iframe;

    var div = document.createElement('div');
    div.innerHTML = iframe;
    var elements = div.childNodes;

//    var iframe = document.createElement('iframe');
//     iframe.style.display = "none";
//     iframe.src = /* your URL here */;
    document.body.appendChild(div);
    // 1 query string...

    // if ios redirect to sik app

    // else sik hompage load.
    // and embed player update.

    if (checkUserDevice()) {

        // redirect sik!!!!

    } else {

    }

}

main();<commit_msg>updated…<commit_after>console.log("in script.js");

var g_params = '';
var g_iframe = '';

function checkUserDevice() {

    var isIPhone = false;
    var useragent = navigator.userAgent.toLowerCase();

    if( useragent.search("iphone") )
        isIPhone = true;
    else if( useragent.search("ipod") )
        ; // ipod
    else if( useragent.search("android") )
        ; // android

    console.log("is iphone : " + isIPhone);
    return isIPhone;
}

function generateEmbedPlayer(playlistid, ownerid) {

    var iframe = ''

    iframe = iframe.replace("__OWNERID__", ownerid);
    iframe = iframe.replace("__PLAYLISTID__","playlistid");

    return iframe;
}

function generateSiklinkUrl(playlistid, ownerid) {

    // sik://play/playlist?playlistid=5O2ERf8kAYARVVdfCKZ9G7&ownerid=spotify
    var url = "sik:sik://play/playlist?playlistid=" + playlistid + "&" + "ownerid=" + ownerid;

    console.log("generated url : " + domain);

    window.location.replace(url);
    //     setTimeout(function () {
    //   window.location.replace("https://itunes.apple.com/app/id12345678");
}

function getHashParams(hashString) {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = hashString;
    while (e = r.exec(q)) {
        hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
}

deli = '?';

function main() {

    console.log("main fucntion");

    var hash = window.location.hash;

   var state;
   var params = {};
   var hashString;

   if (hash.length > 1) {

       var hashString = hash.substring(1);
       g_params = getHashParams(hashString);
       params = g_params;
   } else {
       state = 'init';
   }

   var playlistId = params.playlistid;
   var ownerId = params.ownerid;

   var iframe = generateEmbedPlayer(playlistId, ownerId);

   console.log("iframe : " + iframe);

   g_iframe = iframe;

    var div = document.createElement('div');
    div.innerHTML = iframe;
    var elements = div.childNodes;

//    var iframe = document.createElement('iframe');
//     iframe.style.display = "none";
//     iframe.src = /* your URL here */;
    document.body.appendChild(div);
    // 1 query string...

    // if ios redirect to sik app

    // else sik hompage load.
    // and embed player update.

    if (checkUserDevice()) {

        generateSiklinkUrl(playlistId, ownerId);

        // redirect sik!!!!

    } else {

    }

}

main();<|endoftext|>


<commit_before>// Imported from WordPress .jshinrc using https://github.com/brenolf/polyjuice

module.exports = {
	// Specify curly brace conventions for all control statements
	'curly': 'error',
	// Require the use of === and !==
	'eqeqeq': 'error',
	// Disallow use of arguments.caller or arguments.callee
	'no-caller': 'error',
	// Disallow assignment in conditional expressions
	'no-cond-assign': ['error', 'except-parens'],
	// Disallow comparisons to null without a type-checking operator
	'no-eq-null': 'error',
	// Disallow irregular whitespace outside of strings and comments
	'no-irregular-whitespace': 'error',
	// Disallow usage of expressions in statement position
	'no-unused-expressions': 'error',
	// Disallow use of undeclared variables unless mentioned in a /*global */ block
	'no-undef': 'error',
	// Disallow declaration of variables that are not used in the code
	'no-unused-vars': 'error',
	// Specify whether backticks, double or single quotes should be used
	'quotes': ['error', 'single'],
	// Require immediate function invocation to be wrapped in parentheses
	'wrap-iife': ['error', 'any']
};
<commit_msg>feat: Add `one-var` and `no-trailing-spaces` rules (#62)<commit_after>// Imported from WordPress .jshintrc using https://github.com/brenolf/polyjuice

module.exports = {
	// Specify curly brace conventions for all control statements
	'curly': 'error',
	// Require the use of === and !==
	'eqeqeq': 'error',
	// Disallow use of arguments.caller or arguments.callee
	'no-caller': 'error',
	// Disallow assignment in conditional expressions
	'no-cond-assign': ['error', 'except-parens'],
	// Disallow comparisons to null without a type-checking operator
	'no-eq-null': 'error',
	// Disallow irregular whitespace outside of strings and comments
	'no-irregular-whitespace': 'error',
	// Disallow trailing whitespace at the end of lines
	'no-trailing-spaces': 'error',
	// Disallow usage of expressions in statement position
	'no-unused-expressions': 'error',
	// Disallow use of undeclared variables unless mentioned in a /*global */ block
	'no-undef': 'error',
	// Disallow declaration of variables that are not used in the code
	'no-unused-vars': 'error',
	// Enforce variables to be declared either together or separately in functions
	'one-var': ['error', 'always'],
	// Specify whether backticks, double or single quotes should be used
	'quotes': ['error', 'single'],
	// Require immediate function invocation to be wrapped in parentheses
	'wrap-iife': ['error', 'any']
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    var results = document.getElementById("results"),
        inputbox = document.getElementById("formGroupInputLarge"),
        counter = document.getElementById("counter"),
        qtype_dropdown = document.getElementById("qtype_dropdown"),
        qtype_selected = document.getElementById("qtype_selected"),
        qtype = "album",
        xmlhttp = new XMLHttpRequest(),
        n_results = 0;

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               presentResult(JSON.parse(xmlhttp.responseText));
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    inputbox.onkeydown = function(key){
        if (key['keyCode'] == 13) {
            key.preventDefault();
            clearSearchResults();
            doSearch();
        }
    };

    for (var i = 0; i < qtype_dropdown.children.length; i++) {
         listElement = qtype_dropdown.children[i];
         aLink = listElement.getElementsByTagName("a")[0];
         aLink.onclick = function(e){
            e.preventDefault();
            qtype = this.getAttribute("x-qtype");
            qtype_selected.innerHTML = qtype;
            clearSearchResults();
         }
    }

    function presentResult(result) {
        counter.innerHTML = result["total_count"];
        result["items"].forEach(appendSearchResult);
        n_results = results.children.length;
        appendLoadMoreButton();
    }

    function appendSearchResult(result) {
        li_el = document.createElement("li");

        img_el = formatThumbnailElement();
        img_el.src = result["image"];
        li_el.appendChild(img_el);

        text_el = createResultNameElement(result["name"]);
        li_el.appendChild(text_el);

        results.appendChild(li_el);
    }

    function appendLoadMoreButton() {
        li_el = document.createElement("li");

        text_el = createResultNameElement("Load more results ");
        li_el.appendChild(text_el);

        square_down_icon = document.createElement("i");
        square_down_icon.className = "fa fa-caret-square-o-down";
        square_down_icon.setAttribute("aria-hidden", "true");
        li_el.appendChild(square_down_icon)

        li_el.onclick = removeThisAndDoSearch;

        results.appendChild(li_el);
    }

    function removeThisAndDoSearch() {
        results.removeChild(this);
        doSearch();
    }

    function createResultNameElement(name) {
        text_el = document.createElement("span");
        text_el.innerHTML = name;
        return text_el;
    }

    function formatThumbnailElement() {
        img_el = document.createElement("img");
        img_el.width = "64";
        img_el.height = "64";
        img_el.className = "thumb";
        return img_el;
    }

    function clearSearchResults() {
        results.innerHTML = "";
        n_results = 0;
    }

    function doSearch() {
        term = inputbox.value;
        xmlhttp.open("GET", "/search/" + qtype + "/" + term + '?limit=5&offset=' + n_results, true);
        xmlhttp.send();
    }
});<commit_msg>Load more button now only appears when there actually are more results to load<commit_after>$(document).ready(function() {
    var results = document.getElementById("results"),
        inputbox = document.getElementById("formGroupInputLarge"),
        counter = document.getElementById("counter"),
        qtype_dropdown = document.getElementById("qtype_dropdown"),
        qtype_selected = document.getElementById("qtype_selected"),
        qtype = "album",
        xmlhttp = new XMLHttpRequest(),
        n_results = 0;

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               presentResult(JSON.parse(xmlhttp.responseText));
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    inputbox.onkeydown = function(key){
        if (key['keyCode'] == 13) {
            key.preventDefault();
            clearSearchResults();
            doSearch();
        }
    };

    for (var i = 0; i < qtype_dropdown.children.length; i++) {
         listElement = qtype_dropdown.children[i];
         aLink = listElement.getElementsByTagName("a")[0];
         aLink.onclick = function(e){
            e.preventDefault();
            qtype = this.getAttribute("x-qtype");
            qtype_selected.innerHTML = qtype;
            clearSearchResults();
         }
    }

    function presentResult(result) {
        counter.innerHTML = result["total_count"];
        result["items"].forEach(appendSearchResult);
        n_results = results.children.length;
        if (result["total_count"] > n_results) {
            appendLoadMoreButton();
        }
    }

    function appendSearchResult(result) {
        li_el = document.createElement("li");

        img_el = formatThumbnailElement();
        img_el.src = result["image"];
        li_el.appendChild(img_el);

        text_el = createResultNameElement(result["name"]);
        li_el.appendChild(text_el);

        results.appendChild(li_el);
    }

    function appendLoadMoreButton() {
        li_el = document.createElement("li");

        text_el = createResultNameElement("Load more results ");
        li_el.appendChild(text_el);

        square_down_icon = document.createElement("i");
        square_down_icon.className = "fa fa-caret-square-o-down";
        square_down_icon.setAttribute("aria-hidden", "true");
        li_el.appendChild(square_down_icon)

        li_el.onclick = removeThisAndDoSearch;

        results.appendChild(li_el);
    }

    function removeThisAndDoSearch() {
        results.removeChild(this);
        doSearch();
    }

    function createResultNameElement(name) {
        text_el = document.createElement("span");
        text_el.innerHTML = name;
        return text_el;
    }

    function formatThumbnailElement() {
        img_el = document.createElement("img");
        img_el.width = "64";
        img_el.height = "64";
        img_el.className = "thumb";
        return img_el;
    }

    function clearSearchResults() {
        results.innerHTML = "";
        n_results = 0;
    }

    function doSearch() {
        term = inputbox.value;
        xmlhttp.open("GET", "/search/" + qtype + "/" + term + '?limit=5&offset=' + n_results, true);
        xmlhttp.send();
    }
});<|endoftext|>


<commit_before>'use strict'

describe('thresholds service', function () {
  var $rootScope
  var thresholdsService
  var angularNavDataMock // eslint-disable-line
  var testMod // eslint-disable-line

  beforeEach(function () {
    angularNavDataMock = angular.module('angularNavData', [])
      .service('lgasService', function ($q) {
        this.list = function () {
          var lga = angular.merge({ _id: 'zone:nc:state:kogi:lga:adavi' }, location)
          return $q.when([lga])
        }
      })
      .service('statesService', function ($q) {
        this.list = function () {
          var state = angular.merge({ _id: 'zone:nc:state:kogi' }, location)
          return $q.when([state])
        }
      })
    testMod = angular.module('testMod', ['angularNavData', 'angularNavThresholds'])
  })

  beforeEach(module('testMod'))

  beforeEach(inject(function (_$rootScope_, _thresholdsService_) {
    thresholdsService = _thresholdsService_
    $rootScope = _$rootScope_
  }))

  var location = {
    level: 'lga',
    allocations: [
      { version: 1,
        weeklyLevels: {
          'product:a': 50,
          'product:b': 100
        }
      },
      {
        version: 2,
        weeklyLevels: {
          'product:a': 100,
          'product:b': 200
        }
      }
    ],
    targetPopulation: {
      'product:a': 1000,
      'product:b': 2000
    },
    plans: [
      {
        version: 1,
        weeksOfStock: {
          max: 5,
          reOrder: 2,
          min: 1
        }
      }
    ]
  }

  var stockCount = {
    allocations: { version: 2 },
    plans: { version: 1 }
  }

  var stockCounts = [
    // { location: { zone: 'nc' }, allocations: { version: 2 }, plans: { version: 1 } },
    { location: { zone: 'nc', state: 'kogi' }, allocations: { version: 2 }, plans: { version: 1 } },
    { location: { zone: 'nc', state: 'kogi', lga: 'adavi' } }
  ]

  describe('calculateThresholds', function () {
    it('takes a location and a stockCount and returns the min, reOrder, max thresholds', function () {
      var expected = {
        'product:a': {
          min: 100,
          reOrder: 200,
          max: 500,
          targetPopulation: 1000
        },
        'product:b': {
          min: 200,
          reOrder: 400,
          max: 1000,
          targetPopulation: 2000
        }
      }
      var actual = thresholdsService.calculateThresholds(location, stockCount)
      expect(actual).toEqual(expected)
    })
    it('also works with zones where the thresholds are based on required allocation for zone state stores', function () {
      var zone = angular.extend({}, location, { level: 'zone' })
      // Note: `plans.weeksOfStock` is ignored (at least for now) in the case of zone stores
      var requiredStatesStoresAllocation = { 'product:a': 20, 'product:b': 50 }
      var expected = {
        'product:a': {
          min: 20,
          reOrder: 320,
          max: 620,
          targetPopulation: 1000
        },
        'product:b': {
          min: 50,
          reOrder: 650,
          max: 1250,
          targetPopulation: 2000
        }
      }
      var actual = thresholdsService.calculateThresholds(zone, stockCount, requiredStatesStoresAllocation)
      expect(actual).toEqual(expected)
    })
  })

  describe('getThresholdsFor', function () {
    it('takes an array of objects with location, allocations and plans fields and returns an object of location thresholds', function (done) {
      var expected = {
        // 'zone:nc': {
          // thresholds: {
            // 'product:a': { min: 100, reOrder: 200, max: 500 },
            // 'product:b': { min: 200, reOrder: 400, max: 1000 }
          // }
        // },
        'zone:nc:state:kogi': {
          allocations: { version: 2 },
          plans: { version: 1 },
          thresholds: {
            'product:a': { min: 100, reOrder: 200, max: 500, targetPopulation: 1000 },
            'product:b': { min: 200, reOrder: 400, max: 1000, targetPopulation: 2000 }
          }
        },
        'zone:nc:state:kogi:lga:adavi': {
          allocations: { version: 1 },
          plans: { version: 1 },
          thresholds: {
            'product:a': { min: 50, reOrder: 100, max: 250, targetPopulation: 1000 },
            'product:b': { min: 100, reOrder: 200, max: 500, targetPopulation: 2000 }
          }
        }
      }

      thresholdsService.getThresholdsFor(stockCounts)
        .then(function (thresholds) {
          expect(thresholds).toEqual(expected)
        })
      $rootScope.$digest()
      done()
    })
  })
})
<commit_msg>test: requiredStateStoresAllocation should not be mandatory<commit_after>'use strict'

describe('thresholds service', function () {
  var $rootScope
  var thresholdsService
  var angularNavDataMock // eslint-disable-line
  var testMod // eslint-disable-line

  beforeEach(function () {
    angularNavDataMock = angular.module('angularNavData', [])
      .service('lgasService', function ($q) {
        this.list = function () {
          var lga = angular.merge({ _id: 'zone:nc:state:kogi:lga:adavi' }, location)
          return $q.when([lga])
        }
      })
      .service('statesService', function ($q) {
        this.list = function () {
          var state = angular.merge({ _id: 'zone:nc:state:kogi' }, location)
          return $q.when([state])
        }
      })
    testMod = angular.module('testMod', ['angularNavData', 'angularNavThresholds'])
  })

  beforeEach(module('testMod'))

  beforeEach(inject(function (_$rootScope_, _thresholdsService_) {
    thresholdsService = _thresholdsService_
    $rootScope = _$rootScope_
  }))

  var location = {
    level: 'lga',
    allocations: [
      { version: 1,
        weeklyLevels: {
          'product:a': 50,
          'product:b': 100
        }
      },
      {
        version: 2,
        weeklyLevels: {
          'product:a': 100,
          'product:b': 200
        }
      }
    ],
    targetPopulation: {
      'product:a': 1000,
      'product:b': 2000
    },
    plans: [
      {
        version: 1,
        weeksOfStock: {
          max: 5,
          reOrder: 2,
          min: 1
        }
      }
    ]
  }

  var stockCount = {
    allocations: { version: 2 },
    plans: { version: 1 }
  }

  var stockCounts = [
    // { location: { zone: 'nc' }, allocations: { version: 2 }, plans: { version: 1 } },
    { location: { zone: 'nc', state: 'kogi' }, allocations: { version: 2 }, plans: { version: 1 } },
    { location: { zone: 'nc', state: 'kogi', lga: 'adavi' } }
  ]

  describe('calculateThresholds', function () {
    it('takes a location and a stockCount and returns the min, reOrder, max thresholds', function () {
      var expected = {
        'product:a': {
          min: 100,
          reOrder: 200,
          max: 500,
          targetPopulation: 1000
        },
        'product:b': {
          min: 200,
          reOrder: 400,
          max: 1000,
          targetPopulation: 2000
        }
      }
      var actual = thresholdsService.calculateThresholds(location, stockCount)
      expect(actual).toEqual(expected)
    })
    it('also works with zones', function () {
      var zone = angular.extend({}, location, { level: 'zone' })
      // Note: `plans.weeksOfStock` is ignored (at least for now) in the case of zone stores
      // See https://github.com/fielded/angular-nav-thresholds/issues/9
      var expected = {
        'product:a': {
          min: 0,
          reOrder: 300,
          max: 600,
          targetPopulation: 1000
        },
        'product:b': {
          min: 0,
          reOrder: 600,
          max: 1200,
          targetPopulation: 2000
        }
      }
      var actual = thresholdsService.calculateThresholds(zone, stockCount)
      expect(actual).toEqual(expected)
    })
    it('works with zones if there is a required allocation for zone state stores', function () {
      var zone = angular.extend({}, location, { level: 'zone' })
      // Note: `plans.weeksOfStock` is ignored (at least for now) in the case of zone stores
      // See https://github.com/fielded/angular-nav-thresholds/issues/9
      var requiredStatesStoresAllocation = { 'product:a': 20 }
      var expected = {
        'product:a': {
          min: 20,
          reOrder: 320,
          max: 620,
          targetPopulation: 1000
        },
        'product:b': {
          min: 0,
          reOrder: 600,
          max: 1200,
          targetPopulation: 2000
        }
      }
      var actual = thresholdsService.calculateThresholds(zone, stockCount, requiredStatesStoresAllocation)
      expect(actual).toEqual(expected)
    })
  })

  describe('getThresholdsFor', function () {
    it('takes an array of objects with location, allocations and plans fields and returns an object of location thresholds', function (done) {
      var expected = {
        // 'zone:nc': {
          // thresholds: {
            // 'product:a': { min: 100, reOrder: 200, max: 500 },
            // 'product:b': { min: 200, reOrder: 400, max: 1000 }
          // }
        // },
        'zone:nc:state:kogi': {
          allocations: { version: 2 },
          plans: { version: 1 },
          thresholds: {
            'product:a': { min: 100, reOrder: 200, max: 500, targetPopulation: 1000 },
            'product:b': { min: 200, reOrder: 400, max: 1000, targetPopulation: 2000 }
          }
        },
        'zone:nc:state:kogi:lga:adavi': {
          allocations: { version: 1 },
          plans: { version: 1 },
          thresholds: {
            'product:a': { min: 50, reOrder: 100, max: 250, targetPopulation: 1000 },
            'product:b': { min: 100, reOrder: 200, max: 500, targetPopulation: 2000 }
          }
        }
      }

      thresholdsService.getThresholdsFor(stockCounts)
        .then(function (thresholds) {
          expect(thresholds).toEqual(expected)
        })
      $rootScope.$digest()
      done()
    })
  })
})
<|endoftext|>


<commit_before>const Rx = require('rx');
const Sequelize = require('sequelize');

Sequelize.Model.prototype.streamAll = function streamAll(options = {}) {
  return Rx.Observable.create((observer) => {
    const chunkSize = options.chunkSize || 1000;
    options.offset = 0;
    options.limit = chunkSize;

    const findFn = (opts) => {
      this.findAll(opts).then((models = []) => {
        observer.onNext(models)
        if (models.length === chunkSize) {
          opts.offset = chunkSize;
          findFn(opts)
        } else {
          observer.onCompleted()
        }
      })
    }

    findFn(options)
  })
}

<commit_msg>[local-sync] Increment streamAll offset by chunkSize (#5)<commit_after>const Rx = require('rx');
const Sequelize = require('sequelize');

Sequelize.Model.prototype.streamAll = function streamAll(options = {}) {
  return Rx.Observable.create((observer) => {
    const chunkSize = options.chunkSize || 1000;
    options.offset = 0;
    options.limit = chunkSize;

    const findFn = (opts) => {
      this.findAll(opts).then((models = []) => {
        observer.onNext(models)
        if (models.length === chunkSize) {
          opts.offset += chunkSize;
          findFn(opts)
        } else {
          observer.onCompleted()
        }
      })
    }

    findFn(options)
  })
}

<|endoftext|>


<commit_before>const _ = global.$;
const BaseModule = require('./baseModule');

class AsomeBot extends BaseModule {
    constructor() {
        super();

        this.isDraing = false;
        this.sendBuffer = [];

        this.receivedText = "";

        this.msg_id = '';
        this.sendToEntry = {
            msg_id: "",
            distance: 0,
            udp_msg: "",
        };
    }

    connect() {
    }

    socketReconnection() {
        this.socket.send(this.handler.encode());
    }

    requestInitialData() {
        console.log("requestInitialData");

        var init_str = "import asomebot; import hcsr04; asomebot.ready(5, 6, 7,8); hcsr04.open(3, 2)\r";
        return Buffer.from(init_str, "ascii");
    }

    setSerialPort(sp) {
        this.sp = sp;
    }

    setSocket(socket) {
        this.socket = socket;
    }

    checkInitialData(data, config) {
        return true;
    }

    validateLocalData(data) {
        return true;
    }

    requestRemoteData(handler) {
        var sendToEntry = this.sendToEntry;
        // console.log("to Entry: ", sendToEntry);

        for (var key in sendToEntry) {
            handler.write(key, sendToEntry[key]);
        }
        return;
    }

    handleRemoteData({ receiveHandler = {} }) {
        const { data: handlerData } = receiveHandler;
        if (_.isEmpty(handlerData)) {
            return;
        }

        if (handlerData.msg_id == undefined) {
            console.log("from handlerData.msg_id == undefined", handlerData);
            return;
        }

        if (handlerData.msg_id != this.msg_id) {
            console.log("from Entry: ", handlerData);

            this.msg_id = handlerData.msg_id;
            this.sendBuffer.push(Buffer.from(handlerData.msg + "\r", 'ascii'));
            this.sendBuffer.push(Buffer.from("'#I'" + "'D " + handlerData.msg_id + "'\r", 'ascii'));

            // 초음파 센서를 이동 블록등과 함께 사용할 때 신호가 처리 안되는 경우가 있다.
            // 반복 실행해도 상관없는 코드이기 때문에 모든 명령 수행시에 추가로 실행하여 최신 측정값을 갱신해 둔다.
            this.sendBuffer.push(Buffer.from("print('#D' + 'T ' + str(hcsr04.get_distance()) + '  ###')\r"));
        }
    }

    requestLocalData() {
        var self = this;

        if (!this.isDraing && this.sendBuffer.length > 0) {
            this.isDraing = true;
            var msg = this.sendBuffer.shift();
            console.log("to AsomeBot: ", msg.toString(), this.sendBuffer.length);
            this.sp.write(msg, function() {
                if (self.sp) {
                    self.sp.drain(function() {
                        self.isDraing = false;
                    });
                }
            });
        }

        return null;
    }

    handleLocalData(data) {
        // console.log("handleLocalData: ", this.receivedText);

        this.receivedText = this.receivedText + data.toString();

        var index = this.receivedText.indexOf('\r');
        while (index >= 0) {
            var line = this.receivedText.substring(0, index);
            this.receivedText = this.receivedText.substring(index + 1);

            console.log("from AsomeBot: ", line);

            if (line.indexOf('#DT') >= 0) {
                var values = line.split(" ");
                if (values.length > 1) this.sendToEntry.distance = values[1];
            }
            if (line.indexOf('#UDP') >= 0) {
                var values = line.split(" ");
                if (values.length > 1) {
                    this.sendToEntry.udp_id = this.msg_id;
                    this.sendToEntry.udp_msg = values[1];
                }
            }
            if (line.indexOf('#ID') >= 0) this.sendToEntry.msg_id = line;

            index = this.receivedText.indexOf('\r');
        }
    }

    setSocketData({ socketData, data }) {
    }

    lostController() { }

    disconnect(connect) {
        connect.close();
        this.sp = null;
    }

    reset() {
        this.sp = null;
        this.isPlaying.set(0);
        this.sendBuffer = [];
        this.receivedText = "";
    }
}

module.exports = new AsomeBot();
<commit_msg>존재하지 않는 속성 접근으로 인한 오류 수정<commit_after>const _ = global.$;
const BaseModule = require('./baseModule');

class AsomeBot extends BaseModule {
    constructor() {
        super();

        this.isDraing = false;
        this.sendBuffer = [];

        this.receivedText = "";

        this.msg_id = '';
        this.sendToEntry = {
            msg_id: "",
            distance: 0,
            udp_msg: "",
        };
    }

    connect() {
    }

    socketReconnection() {
        this.socket.send(this.handler.encode());
    }

    requestInitialData() {
        console.log("requestInitialData");

        var init_str = "import asomebot; import hcsr04; asomebot.ready(5, 6, 7,8); hcsr04.open(3, 2)\r";
        return Buffer.from(init_str, "ascii");
    }

    setSerialPort(sp) {
        this.sp = sp;
    }

    setSocket(socket) {
        this.socket = socket;
    }

    checkInitialData(data, config) {
        return true;
    }

    validateLocalData(data) {
        return true;
    }

    requestRemoteData(handler) {
        var sendToEntry = this.sendToEntry;
        // console.log("to Entry: ", sendToEntry);

        for (var key in sendToEntry) {
            handler.write(key, sendToEntry[key]);
        }
        return;
    }

    handleRemoteData({ receiveHandler = {} }) {
        const { data: handlerData } = receiveHandler;
        if (_.isEmpty(handlerData)) {
            return;
        }

        if (handlerData.msg_id == undefined) {
            console.log("from handlerData.msg_id == undefined", handlerData);
            return;
        }

        if (handlerData.msg_id != this.msg_id) {
            console.log("from Entry: ", handlerData);

            this.msg_id = handlerData.msg_id;
            this.sendBuffer.push(Buffer.from(handlerData.msg + "\r", 'ascii'));
            this.sendBuffer.push(Buffer.from("'#I'" + "'D " + handlerData.msg_id + "'\r", 'ascii'));

            // 초음파 센서를 이동 블록등과 함께 사용할 때 신호가 처리 안되는 경우가 있다.
            // 반복 실행해도 상관없는 코드이기 때문에 모든 명령 수행시에 추가로 실행하여 최신 측정값을 갱신해 둔다.
            this.sendBuffer.push(Buffer.from("print('#D' + 'T ' + str(hcsr04.get_distance()) + '  ###')\r"));
        }
    }

    requestLocalData() {
        var self = this;

        if (!this.isDraing && this.sendBuffer.length > 0) {
            this.isDraing = true;
            var msg = this.sendBuffer.shift();
            console.log("to AsomeBot: ", msg.toString(), this.sendBuffer.length);
            this.sp.write(msg, function() {
                if (self.sp) {
                    self.sp.drain(function() {
                        self.isDraing = false;
                    });
                }
            });
        }

        return null;
    }

    handleLocalData(data) {
        // console.log("handleLocalData: ", this.receivedText);

        this.receivedText = this.receivedText + data.toString();

        var index = this.receivedText.indexOf('\r');
        while (index >= 0) {
            var line = this.receivedText.substring(0, index);
            this.receivedText = this.receivedText.substring(index + 1);

            console.log("from AsomeBot: ", line);

            if (line.indexOf('#DT') >= 0) {
                var values = line.split(" ");
                if (values.length > 1) this.sendToEntry.distance = values[1];
            }
            if (line.indexOf('#UDP') >= 0) {
                var values = line.split(" ");
                if (values.length > 1) {
                    this.sendToEntry.udp_id = this.msg_id;
                    this.sendToEntry.udp_msg = values[1];
                }
            }
            if (line.indexOf('#ID') >= 0) this.sendToEntry.msg_id = line;

            index = this.receivedText.indexOf('\r');
        }
    }

    setSocketData({ socketData, data }) {
    }

    lostController() { }

    disconnect(connect) {
        connect.close();
        this.sp = null;
    }

    reset() {
        this.sp = null;
        this.sendBuffer = [];
        this.receivedText = "";
    }
}

module.exports = new AsomeBot();
<|endoftext|>


<commit_before>/*!
 * VERSION: 0.0.2
 * DATE: 2017-05-06
 * UPDATES AND DOCS AT: https://chris-moody.github.io/mkr
 *
 * @license copyright 2017 Christopher C. Moody
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
 *  this software and associated documentation files (the "Software"), to deal in the
 *  Software without restriction, including without limitation the rights to use, copy,
 *  modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 *  and to permit persons to whom the Software is furnished to do so, subject to the
 *  following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 *  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 *  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 *  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 *  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @author: Christopher C. Moody, chris@moodydigital.com
 */

(function(global, className) {
    var _instances = {}, _count=-1;

    /**
     * @class grdnt
     * @classdesc Shortcut for creating SVG gradients
     * @description Initializes a new grdnt instance.
     * @param {Object} options - Options used to customize the grdnt
     * @param {*} [options.parent=document.body] - Element which the grdnt's svgRoot is appended
     * @param {String=} options.id - The id of the instance. Auto-generated when not provided
     * @param {*=} options.svgRoot - svg element which to append the grdnt. Can be a selector string or element. It is auto-generated and added to options.parent when not provided
     * @param {String} [options.type=grdnt.LINEAR] - The type of gradient to create. Can be grdnt.LINEAR or grdnt.RADIAL.
     * @param {Array} [options.stops=[]] - An array of objects containing stop element attributes. Used to initialize the stops for the gradient
     * @param {Object=} options.svg - Options used to create svgRoot when none is provided
     * @param {String} [options.svg.attr.class='grdnt-svg']
     * @param {String} [options.svg.css.overflow='visible']
     * @param {Object=} options.attr - Attributes to apply to the grdnt's gradient element.
     * @param {Object=} options.css - CSS Properties to apply to the grdnt's gradient element.

     * @requires {@link  grdnt}
     * @returns {msk} A new grdnt instance.
    **/
    var grdnt = function(options) {
		options = options || {};
		_count++;
        var id = this._id = options.id || className+'-'+_count;
		this._parent = mkr.getDefault(options, 'parent', document.body);

		mkr.setDefault(options, 'attr', {});
        mkr.setDefault(options.attr, 'id', id);
        mkr.setDefault(options, 'css', {});
        mkr.setDefault(options, 'svg', {});

        mkr.setDefault(options.svg, 'attr', {});
        mkr.setDefault(options.svg.attr, 'class', 'grdnt-svg');
        mkr.setDefault(options.svg, 'css', {});
        mkr.setDefault(options.svg.css, 'overflow', 'visible');

		var type = mkr.default(options.type, grdnt.LINEAR);
		var stops = mkr.default(options.stops, []);

		var s = this._svg = options.svgRoot || mkr.create('svg', options.svg, this._parent)
			var d = mkr.query('defs', s) || mkr.create('defs', {}, s)
				var grad = this._grad = mkr.create(type+'Gradient', {attr:options.attr, css:options.css}, d)
					for(var i=0; i<stops.length; i++) {
						this.addStop(stops[i]);
					}

		_instances[id] = this;
	};

	grdnt.prototype = {
        /**
         * @name grdnt#id
         * @public
         * @readonly
         * @type String
         * @description The id of this instance's gradient element
        **/
        get id() {return this.el.id;},

        /**
         * @name grdnt#fill
         * @public
         * @readonly
         * @type String
         * @description The function string used to assign the gradient as a fill, stroke, etc
        **/
        get fill() {return 'url(#'+this.id+')';},

        /**
         * @name grdnt#svg
         * @public
         * @readonly
         * @type SVGElement
         * @description The root svg element
        **/
        get svg() {return this._svg;},

        /**
         * @name grdnt#el
         * @public
         * @readonly
         * @type SVGElement
         * @description The gradient element associated with this instance
        **/
        get el() {return this._grad;},

        /**
	     * @function addStop
	     * @memberof grdnt.prototype
	     * @public
	     * @description Updates the points attribute of the polygon element.
	     * @param {Object} attr - Attributes to set on the stop element
	     * @param {Object} attr.color - Shortcut for 'stop-color'
	    **/
		addStop: function(attr) {
			mkr.setDefault(attr, 'stop-color', attr.color);
			return mkr.create('stop', {attr:attr}, this._grad);
		}
    };

	/**
    * @alias grdnt.LINEAR
    * @memberof grdnt
    * @static
    * @readonly
    * @type String
    * @description returns 'linear'
    **/
    Object.defineProperty(grdnt, 'LINEAR', {
        get: function() {
          return 'linear';
        }
    });

    /**
    * @alias grdnt.RADIAL
    * @memberof grdnt
    * @static
    * @readonly
    * @type String
    * @description returns 'radial'
    **/
    Object.defineProperty(grdnt, 'RADIAL', {
        get: function() {
          return 'radial';
        }
    });

    /**
    * @function getInstance
    * @memberof grdnt
    * @static
    * @description returns the grdnt instance associated with the id
    * @param {String} id - The lookup id
    * @returns {grdnt} The associate grdnt, if it exists
    **/
    grdnt.getInstance = function(id) {
        return _instances[id];
    };

    /**
    * @function getElInstance
    * @memberof grdnt
    * @static
    * @description returns the grdnt instance associated with the provided element's id attribute
    * @param {Element} el - The element with the lookup id
    * @returns {grdnt} The associate grdnt, if it exists
    **/
    grdnt.getElInstance = function(el) {
        return _instances[el.id];
    };

	/**
    * @alias grdnt.VERSION
    * @memberof grdnt
    * @static
    * @readonly
    * @type String
    * @description returns grdnt's version number
    **/
    Object.defineProperty(grdnt, 'VERSION', {
        get: function() {
          return '0.0.2';
        }
    });

    if(typeof define === 'function' && define.amd){ //AMD
        define(function () { return grdnt; });
    } else if (typeof module !== 'undefined' && module.exports){ //node
        module.exports = grdnt;
    } else { //browser
        global[className] = grdnt;
    }
})(mkr._constructs, 'grdnt');<commit_msg>docs(grdnt): update jsdoc comments<commit_after>/*!
 * VERSION: 0.0.2
 * DATE: 2017-05-06
 * UPDATES AND DOCS AT: https://chris-moody.github.io/mkr
 *
 * @license copyright 2017 Christopher C. Moody
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
 *  this software and associated documentation files (the "Software"), to deal in the
 *  Software without restriction, including without limitation the rights to use, copy,
 *  modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 *  and to permit persons to whom the Software is furnished to do so, subject to the
 *  following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 *  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 *  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 *  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 *  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @author: Christopher C. Moody, chris@moodydigital.com
 */

(function(global, className) {
    var _instances = {}, _count=-1;

    /**
     * @class grdnt
     * @classdesc Shortcut for creating SVG gradients
     * @description Initializes a new grdnt instance.
     * @param {Object} options - Options used to customize the grdnt
     * @param {*} [options.parent=document.body] - Element which the grdnt's svgRoot is appended
     * @param {String=} options.id - The id of the instance. Auto-generated when not provided
     * @param {*=} options.svgRoot - svg element which to append the grdnt. Can be a selector string or element. It is auto-generated and added to options.parent when not provided
     * @param {String} [options.type=grdnt.LINEAR] - The type of gradient to create. Can be grdnt.LINEAR or grdnt.RADIAL.
     * @param {Array} [options.stops=[]] - An array of objects containing stop element attributes. Used to initialize the stops for the gradient
     * @param {Object=} options.svg - Options used to create svgRoot when none is provided
     * @param {String} [options.svg.attr.class='grdnt-svg']
     * @param {String} [options.svg.css.overflow='visible']
     * @param {Object=} options.attr - Attributes to apply to the grdnt's gradient element.
     * @param {Object=} options.css - CSS Properties to apply to the grdnt's gradient element.

     * @requires {@link  grdnt}
     * @returns {msk} A new grdnt instance.
    **/
    var grdnt = function(options) {
		options = options || {};
		_count++;
        var id = this._id = options.id || className+'-'+_count;
		this._parent = mkr.getDefault(options, 'parent', document.body);

		mkr.setDefault(options, 'attr', {});
        mkr.setDefault(options.attr, 'id', id);
        mkr.setDefault(options, 'css', {});
        mkr.setDefault(options, 'svg', {});

        mkr.setDefault(options.svg, 'attr', {});
        mkr.setDefault(options.svg.attr, 'class', 'grdnt-svg');
        mkr.setDefault(options.svg, 'css', {});
        mkr.setDefault(options.svg.css, 'overflow', 'visible');

		var type = mkr.default(options.type, grdnt.LINEAR);
		var stops = mkr.default(options.stops, []);

		var s = this._svg = options.svgRoot || mkr.create('svg', options.svg, this._parent)
			var d = mkr.query('defs', s) || mkr.create('defs', {}, s)
				var grad = this._grad = mkr.create(type+'Gradient', {attr:options.attr, css:options.css}, d)
					for(var i=0; i<stops.length; i++) {
						this.addStop(stops[i]);
					}

		_instances[id] = this;
	};

	grdnt.prototype = {
        /**
         * @name grdnt#el
         * @public
         * @readonly
         * @type SVGElement
         * @description The gradient element associated with this instance
        **/
        get el() {return this._grad;},

        /**t
         * @name grdnt#id
         * @public
         * @readonly
         * @type String
         * @description The id of this instance's gradient element
        **/
        get id() {return this.el.id;},

        /**
         * @name grdnt#fill
         * @public
         * @readonly
         * @type String
         * @description The function string used to assign the gradient as a fill, stroke, etc
        **/
        get fill() {return 'url(#'+this.id+')';},

        /**
         * @name grdnt#svg
         * @public
         * @readonly
         * @type NodeList
         * @description A nodelist of the grdnt's stop elements
        **/
        get stops() {return mkr.queryAll('#'+this.id+' stop')},

        /**
         * @name grdnt#svg
         * @public
         * @readonly
         * @type SVGElement
         * @description The root svg element
        **/
        get svg() {return this._svg;},

        /**
	     * @function addStop
	     * @memberof grdnt.prototype
	     * @public
	     * @description Updates the points attribute of the polygon element.
	     * @param {Object} attr - Attributes to set on the stop element
	     * @param {Object} attr.color - Shortcut for 'stop-color'
         * @returns {SVGElement} The new stop element
	    **/
		addStop: function(attr) {
			mkr.setDefault(attr, 'stop-color', attr.color);
			return mkr.create('stop', {attr:attr}, this._grad);
		},

        /**
         * @function removeStop
         * @memberof grdnt.prototype
         * @public
         * @description Removes the stop element at the specified index
         * @param {int} index - The index of the stop element to remove
         * @returns {SVGElement} The stop element thatw as removed
        **/
        removeStop: function(index) {
            return mkr.remove(this.stops[index]);
        },

        /**
         * @function getStop
         * @memberof grdnt.prototype
         * @public
         * @description Returns the stop element at the specified index
         * @param {int} index - The index of the desired stop element
         * @returns {SVGElement} The stop element at the specified index
        **/
        getStop: function(index) {
            return this.stops[index];
        }
    };

	/**
    * @alias grdnt.LINEAR
    * @memberof grdnt
    * @static
    * @readonly
    * @type String
    * @description returns 'linear'
    **/
    Object.defineProperty(grdnt, 'LINEAR', {
        get: function() {
          return 'linear';
        }
    });

    /**
    * @alias grdnt.RADIAL
    * @memberof grdnt
    * @static
    * @readonly
    * @type String
    * @description returns 'radial'
    **/
    Object.defineProperty(grdnt, 'RADIAL', {
        get: function() {
          return 'radial';
        }
    });

    /**
    * @function getInstance
    * @memberof grdnt
    * @static
    * @description returns the grdnt instance associated with the id
    * @param {String} id - The lookup id
    * @returns {grdnt} The associate grdnt, if it exists
    **/
    grdnt.getInstance = function(id) {
        return _instances[id];
    };

    /**
    * @function getElInstance
    * @memberof grdnt
    * @static
    * @description returns the grdnt instance associated with the provided element's id attribute
    * @param {Element} el - The element with the lookup id
    * @returns {grdnt} The associate grdnt, if it exists
    **/
    grdnt.getElInstance = function(el) {
        return _instances[el.id];
    };

	/**
    * @alias grdnt.VERSION
    * @memberof grdnt
    * @static
    * @readonly
    * @type String
    * @description returns grdnt's version number
    **/
    Object.defineProperty(grdnt, 'VERSION', {
        get: function() {
          return '0.0.3';
        }
    });

    if(typeof define === 'function' && define.amd){ //AMD
        define(function () { return grdnt; });
    } else if (typeof module !== 'undefined' && module.exports){ //node
        module.exports = grdnt;
    } else { //browser
        global[className] = grdnt;
    }
})(mkr._constructs, 'grdnt');<|endoftext|>


<commit_before>console.log("in script.js");

var g_params = '';
var g_iframe = '';

function checkUserDevice() {

    var isIPhone = false;
    var useragent = navigator.userAgent.toLowerCase();

    if( useragent.search("iphone") )
        isIPhone = true;
    else if( useragent.search("ipod") )
        ; // ipod
    else if( useragent.search("android") )
        ; // android

    console.log("is iphone : " + isIPhone);
    return isIPhone;
}

function generateEmbedPlayer(playlistid, ownerid) {

{/**/}

    var iframe = ''

    iframe = iframe.replace("__OWNERID__", ownerid);
    iframe = iframe.replace("__PLAYLISTID__","playlistid");

    return iframe;
}

function generateSiklinkUrl(playlistid, ownerid) {

    // sik://play/playlist?playlistid=5O2ERf8kAYARVVdfCKZ9G7&ownerid=spotify
    var url = "sik://play/playlist?playlistid=" + playlistid + "&" + "ownerid=" + ownerid;

    console.log("generated url : " + url);

    window.location.replace(url);
    //     setTimeout(function () {
    //   window.location.replace("https://itunes.apple.com/app/id12345678");
}

function getHashParams(hashString) {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = hashString;
    while (e = r.exec(q)) {
        hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
}

deli = '?';

function main() {

    console.log("main fucntion");

    var hash = window.location.hash;

   var state;
   var params = {};
   var hashString;

   if (hash.length > 1) {

       var hashString = hash.substring(1);
       g_params = getHashParams(hashString);
       params = g_params;
   } else {
       state = 'init';
   }

   var playlistId = params.playlistid;
   var ownerId = params.ownerid;

   var iframe = generateEmbedPlayer(playlistId, ownerId);

   console.log("iframe : " + iframe);

   g_iframe = iframe;

    var div = document.createElement('div');
    div.innerHTML = iframe;
    var elements = div.childNodes;

//    var iframe = document.createElement('iframe');
//     iframe.style.display = "none";
//     iframe.src = /* your URL here */;
    document.body.appendChild(div);
    // 1 query string...

    // if ios redirect to sik app

    // else sik hompage load.
    // and embed player update.

    if (checkUserDevice()) {

        generateSiklinkUrl(playlistId, ownerId);

        // redirect sik!!!!

    } else {

    }

}

main();<commit_msg>fixed bug<commit_after>console.log("in script.js");

var g_params = '';
var g_iframe = '';

function checkUserDevice() {

    var isIPhone = false;
    var useragent = navigator.userAgent.toLowerCase();

    if( useragent.search("iphone") )
        isIPhone = true;
    else if( useragent.search("ipod") )
        ; // ipod
    else if( useragent.search("android") )
        ; // android

    console.log("is iphone : " + isIPhone);
    return isIPhone;
}

function generateEmbedPlayer(playlistid, ownerid) {

{/**/}

    var iframe = ''

    iframe = iframe.replace("__OWNERID__", ownerid);
    iframe = iframe.replace("__PLAYLISTID__",playlistid);

    return iframe;
}

function generateSiklinkUrl(playlistid, ownerid) {

    // sik://play/playlist?playlistid=5O2ERf8kAYARVVdfCKZ9G7&ownerid=spotify
    var url = "sik://play/playlist?playlistid=" + playlistid + "&" + "ownerid=" + ownerid;

    console.log("generated url : " + url);

    // window.location.replace(url);
    //     setTimeout(function () {
    //   window.location.replace("https://itunes.apple.com/app/id12345678");
}

function getHashParams(hashString) {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = hashString;
    while (e = r.exec(q)) {
        hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
}

deli = '?';

function main() {

    console.log("main fucntion");

    var hash = window.location.hash;

   var state;
   var params = {};
   var hashString;

   if (hash.length > 1) {

       var hashString = hash.substring(1);
       g_params = getHashParams(hashString);
       params = g_params;
   } else {
       state = 'init';
   }

   var playlistId = params.playlistid;
   var ownerId = params.ownerid;

   var iframe = generateEmbedPlayer(playlistId, ownerId);

   console.log("iframe : " + iframe);

   g_iframe = iframe;

    var div = document.createElement('div');
    div.innerHTML = iframe;
    var elements = div.childNodes;

//    var iframe = document.createElement('iframe');
//     iframe.style.display = "none";
//     iframe.src = /* your URL here */;
    document.body.appendChild(div);
    // 1 query string...

    // if ios redirect to sik app

    // else sik hompage load.
    // and embed player update.

    if (checkUserDevice()) {

        generateSiklinkUrl(playlistId, ownerId);

        // redirect sik!!!!

    } else {

    }

}

main();<|endoftext|>


<commit_before>function GuiEvent(graphRender) {
    // graph render for this gui event
    this.graphRender = graphRender;
    graphRender.draw();

    // extract input capture on enter
    $("#search").keypress(function(e) {
        // 13 is the ascii code for the enter key
        if (e.which == 13) {
	    alert("enter pressed with " + $("#searchbar").val());
        }
    });

    // toolbar animation and help overlay functions
    $("#toolbar").hide();
    $("#tab").click(
        function(){
            $("#toolbar").slideToggle("fast");
        }
    );

    // functions for controlling the help overlay visibility and position
    function loadPopup(){
        //loads popup only if it is disabled
        if($("#bgPopup").data("state")==0){
            $("#bgPopup").css({
                "opacity": "0.7"
            });
            $("#bgPopup").fadeIn("medium");
            $("#Popup").fadeIn("medium");
            $("#bgPopup").data("state",1);
        }
    }

    function disablePopup(){
        if ($("#bgPopup").data("state")==1){
            $("#bgPopup").fadeOut("medium");
            $("#Popup").fadeOut("medium");
            $("#bgPopup").data("state",0);
        }
    }

    function centerPopup(){
        var winw = $(window).width();
        var winh = $(window).height();
        var popw = $('#Popup').width();
        var poph = $('#Popup').height();
        $("#Popup").css({
            "position" : "absolute",
            "top" : winh/2 - poph/2,
            "left" : winw/2 - popw/2
        });
    }

    // selectors on the help button to trigger the functions
    $("#bgPopup").data("state",0);
    $("#help_button").click(function(){
        centerPopup();
        loadPopup();
    });
    $("#bgPopup").click(function(){
        disablePopup();
    });

    $(window).resize(function() {
        centerPopup();
    });
}<commit_msg>added in my slider zoom<commit_after>function GuiEvent(graphRender) {
    // graph render for this gui event
    this.graphRender = graphRender;
    graphRender.draw();

    // extract input capture on enter
    $("#search").keypress(function(e) {
        // 13 is the ascii code for the enter key
        if (e.which == 13) {
	    alert("enter pressed with " + $("#searchbar").val());
        }
    });

    var initial
    $("#slider").mousedown(function () {
        initial = this.value;
    }).bind("mouseup mouseleave", function () {
        //alert(this.value - initial);
        var diff = this.value - initial;
        if (diff < 0) {
            ChromeWheel( 1 , Math.abs(diff) / 5);
        }
        else {
            ChromeWheel( 0 , diff / 5);
        }
    });

    var view
    window.onload = function () {
        view = document.getElementById("inner");
    }

    function ChromeWheel ( shift_key , clicks) {
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent('dblclick', true, true, window, clicks, 10, 10,
        $(window).width() / 2, $(window).height() / 2, 0, 0, shift_key, 0, 1, null);
        view.dispatchEvent(evt);
    }

    // toolbar animation and help overlay functions
    $("#toolbar").hide();
    $("#tab").click(
        function(){
            $("#toolbar").slideToggle("fast");
        }
    );

    // functions for controlling the help overlay visibility and position
    function loadPopup(){
        //loads popup only if it is disabled
        if($("#bgPopup").data("state")==0){
            $("#bgPopup").css({
                "opacity": "0.7"
            });
            $("#bgPopup").fadeIn("medium");
            $("#Popup").fadeIn("medium");
            $("#bgPopup").data("state",1);
        }
    }

    function disablePopup(){
        if ($("#bgPopup").data("state")==1){
            $("#bgPopup").fadeOut("medium");
            $("#Popup").fadeOut("medium");
            $("#bgPopup").data("state",0);
        }
    }

    function centerPopup(){
        var winw = $(window).width();
        var winh = $(window).height();
        var popw = $('#Popup').width();
        var poph = $('#Popup').height();
        $("#Popup").css({
            "position" : "absolute",
            "top" : winh/2 - poph/2,
            "left" : winw/2 - popw/2
        });
    }

    // selectors on the help button to trigger the functions
    $("#bgPopup").data("state",0);
    $("#help_button").click(function(){
        centerPopup();
        loadPopup();
    });
    $("#bgPopup").click(function(){
        disablePopup();
    });

    $(window).resize(function() {
        centerPopup();
    });
}
<|endoftext|>


<commit_before>// ## Wu.js operators extension
//
// This extension to Wu.js provides the most common Javascript operators as
// self-currying functions. The operators live under the `wu.op` namespace, for
// example you could access the `&&` operator either as `wu.op.and` or as
// `wu.op["&&"]`. All of the operator functions are available in both literal (`wu.op["&&"]`)
// and english (`wu.op.and`) styles.

// This file relies on wu as a dependency.
//
// TODO: How to handle CommonJS support?
if (typeof wu !== "function") {
    throw new Error("wu.operators.js: `wu` is required");
}

(function (wu, op) {

    // ### Arithmetic Operators

    op["+"] = op.add = wu.autoCurry(function (a, b) {
        return a + b;
    });

    op["-"] = op.sub = wu.autoCurry(function (a, b) {
        return a - b;
    });

    op["*"] = op.mul = wu.autoCurry(function (a, b) {
        return a * b;
    });

    op["/"] = op.div = wu.autoCurry(function (a, b) {
        return a / b;
    });

    op["%"] = op.mod = wu.autoCurry(function (a, b) {
        return a % b;
    });

    // ### Logic Operators

    op["&&"] = op.and = wu.autoCurry(function (a, b) {
        return a && b;
    });

    op["||"] = op.or = wu.autoCurry(function (a, b) {
        return a || b;
    });

    op["=="] = op.eq = wu.autoCurry(function (a, b) {
        return a == b;
    });

    op["!="] = op.neq = wu.autoCurry(function (a, b) {
        return a != b;
    });

    op["==="] = op.is = wu.autoCurry(function (a, b) {
        return a === b;
    });

    op["!=="] = op.isnt = wu.autoCurry(function (a, b) {
        return a !== b;
    });

    op["<"] = op.lt = wu.autoCurry(function (a, b) {
        return a < b;
    });

    op["<"] = op.gt = wu.autoCurry(function (a, b) {
        return a < b;
    });

    op["<="] = op.lte = wu.autoCurry(function (a, b) {
        return a <= b;
    });

    op[">="] = op.gte = wu.autoCurry(function (a, b) {
        return a >= b;
    });

    op["in"] = op.in_ = wu.autoCurry(function (a, b) {
        return a in b;
    });

    op["!"] = op.not = function (a) {
        return !a;
    };

    // ### Misc. Operators

    op["typeof"] = op.typeof_ = function (a) {
        return typeof a;
    };

    op["instanceof"] = op.instanceof_ = wu.autoCurry(function (a, b) {
        return a instanceof b;
    });

    op["?"] = op.ternary = wu.autoCurry(function (a, b, c) {
        return a ? b : c;
    });

}(wu, wu.op = {}));<commit_msg>Remove wu.operators.js<commit_after><|endoftext|>


<commit_before><commit_msg>Database read/write files start<commit_after>function createRecordInDatabase(medicalRecordId){
    var medicalRecordObject = {_id = medicalRecordId}
    createHTTPPOSTConnectionRecord(medicalRecordObject);
}

function getRecordFromDatabase(medicalRecordId){
    return createHTTPGETConnection(medicalRecordId)
}

function writeDataToRecord(medicalRecordId){
  createHTTPPOSTConnection(medicalRecordId);
}

function removeDataFromDatabase(medicalRecordId, listOfDataPoints){

}

function updateDataInRecord(medicalRecordId){

  }

function createHTTPPOSTConnectionRecord(babyDataObject){
  var http = new XMLHttpRequest();
  var url = "http://196.42.86.86:5984/test1/"; //server will change //test server https://www.posttestserver.com/
  http.open("PUT", url, true);
  http.setRequestHeader("Content-type", "application/json");
  http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
    }
  }
  document.getElementById("xmlContent").innerHTML = JSON.stringify(babyDataObject);
  http.send(JSON.stringify(babyDataObject));
}

function createHTTPPOSTConnection(medicalRecordId){ // must change to pass in values
  var http = new XMLHttpRequest();
  var url = "http://196.42.86.86:5984/test1/" + babyDataObject._id; //server will change //test server https://www.posttestserver.com/
  http.open("PUT", url, true);
  http.setRequestHeader("Content-type", "application/json");
  http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
    }
  }
  document.getElementById("xmlContent").innerHTML = JSON.stringify(babyDataObject);
  http.send(JSON.stringify(babyDataObject));
}

function createHTTPGETConnection(medicalRecordId){
  var babyData = {idMisMatch: true};
  var http = new XMLHttpRequest();
  var url = "http://196.42.86.86:5984/test1/" + medicalRecordId; //server will change -> config file?
  http.open("GET", url, false);
  http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        babyData = this.responseText;
        //console.log(this.responseText);
    }
  }
  http.send();
    return babyData;
}
<|endoftext|>