<commit_before>'use strict';

var unrealFs = {};

var tree;

unrealFs.getTree = function(){
    return tree;
};

unrealFs.setTree = function(paramTree){
    tree = paramTree;
};

var forceStack = {};

unrealFs.setForce = function(method, returnOrCallback){

    if (undefined === forceStack[method]){
        forceStack[method] = [];
    }
    forceStack[method].push(returnOrCallback);

};

unrealFs.clearForce = function(method){

    forceStack[method] = [];

};

unrealFs.hasForce = function(method){

    if (undefined === forceStack[method]){
        return false;
    }

    return ( 0 < forceStack[method].length);

};

unrealFs.doForce = function(method){

    if (undefined === forceStack[method]){
        return undefined;
    }

    method = forceStack[method].shift();

    return method(unrealFs);

};

unrealFs.access = function(path, mode, callback){
    console.log('access', arguments);
};

unrealFs.accessSync = function(path, mode){
    console.log('accessSync', arguments);
};

unrealFs.appendFile = function(file, data, options, callback){

    unrealFs.appendFileSync(file, data, options);

    callbackParam = null;

    if (true === unrealFs.hasForce('appendFile')){
        callbackParam = unrealFs.doForce('appendFile');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });

};

unrealFs.appendFileSync = function(file, data, options){

    if (false === tree.exists(file)){
        tree.addFile(file);
    }

    var content = tree.getByFqn(file).getContent();

    tree.getByFqn(file).setContent(content + data);

};

unrealFs.chmod = function(path, mode, callback){
    console.log('chmod', arguments);
};

unrealFs.chmodSync = function(path, mode){
    console.log('chmodSync', arguments);
};

unrealFs.chown = function(path, uid, gid, callback){
    console.log('chown', arguments);
};

unrealFs.chownSync = function(path, uid, gid){
    console.log('chownSync', arguments);
};

unrealFs.close = function(fd, callback){
    console.log('close', arguments);
};

unrealFs.closeSync = function(fd){
    console.log('closeSync', arguments);
};

unrealFs.createReadStream = function(path, options){
    console.log('createReadStream', arguments);
};

unrealFs.createWriteStream = function(path, options){
    console.log('createWriteStream', arguments);
};

unrealFs.exists = function(path, callback){
    var exists = tree.exists(path);

    process.nextTick(function () {
        callback(exists);
    });

};

unrealFs.existsSync = function(path){
    return tree.exists(path);
};

unrealFs.fchmod = function(fd, mode, callback){
    console.log('fchmod', arguments);
};

unrealFs.fchmodSync = function(fd, mode){
    console.log('fchmodSync', arguments);
};

unrealFs.fchown = function(fd, uid, gid, callback){
    console.log('fchown', arguments);
};

unrealFs.fchownSync = function(fd, uid, gid){
    console.log('fchownSync', arguments);
};

unrealFs.fdatasync = function(fd, callback){
    console.log('fdatasync', arguments);
};

unrealFs.fdatasyncSync = function(fd){
    console.log('fdatasyncSync', arguments);
};

unrealFs.fstat = function(fd, callback){
    console.log('fstat', arguments);
};

unrealFs.fstatSync = function(fd){
    console.log('fstatSync', arguments);
};

unrealFs.fsync = function(fd, callback){
    console.log('fsync', arguments);
};

unrealFs.fsyncSync = function(fd){
    console.log('fsyncSync', arguments);
};

unrealFs.ftruncate = function(fd, len, callback){
    console.log('ftruncate', arguments);
};

unrealFs.ftruncateSync = function(fd, len){
    console.log('ftruncateSync', arguments);
};

unrealFs.futimes = function(fd, atime, mtime, callback){
    console.log('futimes', arguments);
};

unrealFs.futimesSync = function(fd, atime, mtime){
    console.log('futimesSync', arguments);
};

unrealFs.lchmod = function(path, mode, callback){
    console.log('lchmod', arguments);
};

unrealFs.lchmodSync = function(path, mode){
    console.log('lchmodSync', arguments);
};

unrealFs.lchown = function(path, uid, gid, callback){
    console.log('lchown', arguments);
};

unrealFs.lchownSync = function(path, uid, gid){
    console.log('lchownSync', arguments);
};

unrealFs.link = function(srcpath, dstpath, callback){
    console.log('link', arguments);
};

unrealFs.linkSync = function(srcpath, dstpath){
    console.log('linkSync', arguments);
};

unrealFs.lstat = function(path, callback){
    console.log('lstat', arguments);
};

unrealFs.lstatSync = function(path){
    console.log('lstatSync', arguments);
};

unrealFs.mkdir = function(path, mode, callback){

    if (undefined === callback){
        callback = mode;
        mode = '0755';
    }

    callbackParam = null;

    if (true === unrealFs.hasForce('mkdir')){
        callbackParam = unrealFs.doForce('mkdir');
    }

    unrealFs.mkdirSync(path, mode);

    process.nextTick(function () {
        callback(callbackParam);
    });

};

unrealFs.mkdirSync = function(path, mode){

    var alreadyExists = tree.exists(path);

    if (true === alreadyExists){
        throw new Error('EEXIST, file already exists \'' + path + '\'');
    }

    tree.addDir(path);
};

unrealFs.open = function(path, flags, mode, callback){
    console.log('open', arguments);
};

unrealFs.openSync = function(path, flags, mode){
    console.log('openSync', arguments);
};

unrealFs.read = function(fd, buffer, offset, length, position, callback){
    console.log('read', arguments);
};

unrealFs.readdir = function(path, callback){

    var error = null;
    var files = null;

    try {
        var files = unrealFs.readdirSync(path);
    }
    catch (e){
        error = e;
    }

    process.nextTick(function () {
        callback(error, files);
    });

};

unrealFs.readdirSync = function(path){
    if (false === tree.exists(path)){
        throw new Error('ENOENT: no such file or directory, scandir \'' + path + '\'');
    }

    var children = tree.getChildrenByPath(path);

    var childrenNames = [];
    children.forEach(function(child){
        childrenNames.push(child.getName());
    });

    return childrenNames;
};

unrealFs.readFile = function(file, options, callback){
    var error = null;

    try {
        var content = unrealFs.readFileSync(file);
    }
    catch (e){
        error = e.message;
    }

    process.nextTick(function () {
        callback(error, content);
    });
};

unrealFs.readFileSync = function(file, options){

    if (false === tree.exists(file)){
        throw new Error('Error: ENOENT, no such file or directory \'' + file + '\'');
    }
    return tree.getNodeByPath(file).getContent();
};

unrealFs.readlink = function(path, callback){
    console.log('readlink', arguments);
};

unrealFs.readlinkSync = function(path){
    console.log('readlinkSync', arguments);
};

unrealFs.realpath = function(path, cache, callback){
    console.log('realpath', arguments);
};

unrealFs.readSync = function(fd, buffer, offset, length, position){
    console.log('readSync', arguments);
};

unrealFs.realpathSync = function(path, cache){
    console.log('realpathSync', arguments);
};

unrealFs.rename = function(oldPath, newPath, callback){
    unrealFs.renameSync(oldPath, newPath);

    var callbackParam = null;

    if (true === unrealFs.hasForce('rename')){
        callbackParam = unrealFs.doForce('rename');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });
};

//@TODO implement a real rename by seperating items from tree
unrealFs.renameSync = function(oldPath, newPath){

    if (false === tree.exists(oldPath)){
        throw new Error(oldPath + ' does not exists.');
    }

    tree.rename(oldPath, newPath);

    return;
    console.log('thats is wrong');

    var node = tree.getNodeByPath(oldPath);

    tree.remove(oldPath);

    if (true === node.isDir()){
        tree.addDir(newPath);
    }
    else if (true === node.isFile()){
        unrealFs.writeFileSync(newPath, node.getContent, {encoding: 'UTF-8'});
    }

};

unrealFs.rmdir = function(path, callback){
    console.log('rmdir', arguments);
};

unrealFs.rmdirSync = function(path){
    tree.remove(path);
};

unrealFs.stat = function(path, callback){
    console.log('stat', arguments);
};

unrealFs.statSync = function(path){
    var node = tree.getNodeByPath(path);
    return node.getStats();
};

unrealFs.symlink = function(target, path, type, callback){
    console.log('symlink', arguments);
};

unrealFs.symlinkSync = function(target, path, type){
    console.log('symlinkSync', arguments);
};

unrealFs.truncate = function(path, len, callback){
    console.log('truncate', arguments);
};

unrealFs.truncateSync = function(path, len){
    console.log('truncateSync', arguments);
};

unrealFs.unlink = function(path, callback){

    tree.remove(path);

    callbackParam = null;

    if (true === unrealFs.hasForce('unlink')){
        callbackParam = unrealFs.doForce('unlink');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });
};

unrealFs.unlinkSync = function(path){
    tree.remove(path);
    return null;
};

unrealFs.unwatchFile = function(filename, listener){
    console.log('unwatchFile', arguments);
};

unrealFs.utimes = function(path, atime, mtime, callback){
    console.log('utimes', arguments);
};

unrealFs.utimesSync = function(path, atime, mtime){
    console.log('utimesSync', arguments);
};

unrealFs.watch = function(filename, options, listener){
    console.log('watch', arguments);
};

unrealFs.watchFile = function(filename, options, listener){
    console.log('watchFile', arguments);
};

/**
 * @TODO param options is optional
 * @TODO add errors to callback
 */
unrealFs.writeFile = function(file, data, options, callback){

    unrealFs.writeFileSync(file, data, options);

    var callbackParam = null;

    if (true === unrealFs.hasForce('writeFile')){
        callbackParam = unrealFs.doForce('writeFile');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });

};

/**
 * @TODO param options is optional
 */
unrealFs.writeFileSync = function(file, data, options){
    if (false === tree.exists(file)){
        tree.addFile(file);
    }

    tree.getNodeByPath(file).setContent(data);

};

module.exports = unrealFs;

<commit_msg>fix unrealFs.mkdir callback and error handling<commit_after>'use strict';

var unrealFs = {};

var tree;

unrealFs.getTree = function(){
    return tree;
};

unrealFs.setTree = function(paramTree){
    tree = paramTree;
};

var forceStack = {};

unrealFs.setForce = function(method, returnOrCallback){

    if (undefined === forceStack[method]){
        forceStack[method] = [];
    }
    forceStack[method].push(returnOrCallback);

};

unrealFs.clearForce = function(method){

    forceStack[method] = [];

};

unrealFs.hasForce = function(method){

    if (undefined === forceStack[method]){
        return false;
    }

    return ( 0 < forceStack[method].length);

};

unrealFs.doForce = function(method){

    if (undefined === forceStack[method]){
        return undefined;
    }

    method = forceStack[method].shift();

    return method(unrealFs);

};

unrealFs.access = function(path, mode, callback){
    console.log('access', arguments);
};

unrealFs.accessSync = function(path, mode){
    console.log('accessSync', arguments);
};

unrealFs.appendFile = function(file, data, options, callback){

    unrealFs.appendFileSync(file, data, options);

    callbackParam = null;

    if (true === unrealFs.hasForce('appendFile')){
        callbackParam = unrealFs.doForce('appendFile');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });

};

unrealFs.appendFileSync = function(file, data, options){

    if (false === tree.exists(file)){
        tree.addFile(file);
    }

    var content = tree.getByFqn(file).getContent();

    tree.getByFqn(file).setContent(content + data);

};

unrealFs.chmod = function(path, mode, callback){
    console.log('chmod', arguments);
};

unrealFs.chmodSync = function(path, mode){
    console.log('chmodSync', arguments);
};

unrealFs.chown = function(path, uid, gid, callback){
    console.log('chown', arguments);
};

unrealFs.chownSync = function(path, uid, gid){
    console.log('chownSync', arguments);
};

unrealFs.close = function(fd, callback){
    console.log('close', arguments);
};

unrealFs.closeSync = function(fd){
    console.log('closeSync', arguments);
};

unrealFs.createReadStream = function(path, options){
    console.log('createReadStream', arguments);
};

unrealFs.createWriteStream = function(path, options){
    console.log('createWriteStream', arguments);
};

unrealFs.exists = function(path, callback){
    var exists = tree.exists(path);

    process.nextTick(function () {
        callback(exists);
    });

};

unrealFs.existsSync = function(path){
    return tree.exists(path);
};

unrealFs.fchmod = function(fd, mode, callback){
    console.log('fchmod', arguments);
};

unrealFs.fchmodSync = function(fd, mode){
    console.log('fchmodSync', arguments);
};

unrealFs.fchown = function(fd, uid, gid, callback){
    console.log('fchown', arguments);
};

unrealFs.fchownSync = function(fd, uid, gid){
    console.log('fchownSync', arguments);
};

unrealFs.fdatasync = function(fd, callback){
    console.log('fdatasync', arguments);
};

unrealFs.fdatasyncSync = function(fd){
    console.log('fdatasyncSync', arguments);
};

unrealFs.fstat = function(fd, callback){
    console.log('fstat', arguments);
};

unrealFs.fstatSync = function(fd){
    console.log('fstatSync', arguments);
};

unrealFs.fsync = function(fd, callback){
    console.log('fsync', arguments);
};

unrealFs.fsyncSync = function(fd){
    console.log('fsyncSync', arguments);
};

unrealFs.ftruncate = function(fd, len, callback){
    console.log('ftruncate', arguments);
};

unrealFs.ftruncateSync = function(fd, len){
    console.log('ftruncateSync', arguments);
};

unrealFs.futimes = function(fd, atime, mtime, callback){
    console.log('futimes', arguments);
};

unrealFs.futimesSync = function(fd, atime, mtime){
    console.log('futimesSync', arguments);
};

unrealFs.lchmod = function(path, mode, callback){
    console.log('lchmod', arguments);
};

unrealFs.lchmodSync = function(path, mode){
    console.log('lchmodSync', arguments);
};

unrealFs.lchown = function(path, uid, gid, callback){
    console.log('lchown', arguments);
};

unrealFs.lchownSync = function(path, uid, gid){
    console.log('lchownSync', arguments);
};

unrealFs.link = function(srcpath, dstpath, callback){
    console.log('link', arguments);
};

unrealFs.linkSync = function(srcpath, dstpath){
    console.log('linkSync', arguments);
};

unrealFs.lstat = function(path, callback){
    console.log('lstat', arguments);
};

unrealFs.lstatSync = function(path){
    console.log('lstatSync', arguments);
};

unrealFs.mkdir = function(path, mode, callback){

    if (undefined === callback){
        callback = mode;
        mode = '0755';
    }

    var callbackParam = null;

    if (true === unrealFs.hasForce('mkdir')){
        callbackParam = unrealFs.doForce('mkdir');
    }

    try{
        unrealFs.mkdirSync(path, mode);
    }
    catch(e){
        callbackParam = e.message;
    }

    process.nextTick(function () {
        callback(callbackParam);
    });

};

unrealFs.mkdirSync = function(path, mode){

    var alreadyExists = tree.exists(path);

    if (true === alreadyExists){
        throw new Error('EEXIST, file already exists \'' + path + '\'');
    }

    tree.addDir(path);
};

unrealFs.open = function(path, flags, mode, callback){
    console.log('open', arguments);
};

unrealFs.openSync = function(path, flags, mode){
    console.log('openSync', arguments);
};

unrealFs.read = function(fd, buffer, offset, length, position, callback){
    console.log('read', arguments);
};

unrealFs.readdir = function(path, callback){

    var error = null;
    var files = null;

    try {
        var files = unrealFs.readdirSync(path);
    }
    catch (e){
        error = e;
    }

    process.nextTick(function () {
        callback(error, files);
    });

};

unrealFs.readdirSync = function(path){
    if (false === tree.exists(path)){
        throw new Error('ENOENT: no such file or directory, scandir \'' + path + '\'');
    }

    var children = tree.getChildrenByPath(path);

    var childrenNames = [];
    children.forEach(function(child){
        childrenNames.push(child.getName());
    });

    return childrenNames;
};

unrealFs.readFile = function(file, options, callback){
    var error = null;

    try {
        var content = unrealFs.readFileSync(file);
    }
    catch (e){
        error = e.message;
    }

    process.nextTick(function () {
        callback(error, content);
    });
};

unrealFs.readFileSync = function(file, options){

    if (false === tree.exists(file)){
        throw new Error('Error: ENOENT, no such file or directory \'' + file + '\'');
    }
    return tree.getNodeByPath(file).getContent();
};

unrealFs.readlink = function(path, callback){
    console.log('readlink', arguments);
};

unrealFs.readlinkSync = function(path){
    console.log('readlinkSync', arguments);
};

unrealFs.realpath = function(path, cache, callback){
    console.log('realpath', arguments);
};

unrealFs.readSync = function(fd, buffer, offset, length, position){
    console.log('readSync', arguments);
};

unrealFs.realpathSync = function(path, cache){
    console.log('realpathSync', arguments);
};

unrealFs.rename = function(oldPath, newPath, callback){
    unrealFs.renameSync(oldPath, newPath);

    var callbackParam = null;

    if (true === unrealFs.hasForce('rename')){
        callbackParam = unrealFs.doForce('rename');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });
};

//@TODO implement a real rename by seperating items from tree
unrealFs.renameSync = function(oldPath, newPath){

    if (false === tree.exists(oldPath)){
        throw new Error(oldPath + ' does not exists.');
    }

    tree.rename(oldPath, newPath);

    return;
    console.log('thats is wrong');

    var node = tree.getNodeByPath(oldPath);

    tree.remove(oldPath);

    if (true === node.isDir()){
        tree.addDir(newPath);
    }
    else if (true === node.isFile()){
        unrealFs.writeFileSync(newPath, node.getContent, {encoding: 'UTF-8'});
    }

};

unrealFs.rmdir = function(path, callback){
    console.log('rmdir', arguments);
};

unrealFs.rmdirSync = function(path){
    tree.remove(path);
};

unrealFs.stat = function(path, callback){
    console.log('stat', arguments);
};

unrealFs.statSync = function(path){
    var node = tree.getNodeByPath(path);
    return node.getStats();
};

unrealFs.symlink = function(target, path, type, callback){
    console.log('symlink', arguments);
};

unrealFs.symlinkSync = function(target, path, type){
    console.log('symlinkSync', arguments);
};

unrealFs.truncate = function(path, len, callback){
    console.log('truncate', arguments);
};

unrealFs.truncateSync = function(path, len){
    console.log('truncateSync', arguments);
};

unrealFs.unlink = function(path, callback){

    tree.remove(path);

    callbackParam = null;

    if (true === unrealFs.hasForce('unlink')){
        callbackParam = unrealFs.doForce('unlink');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });
};

unrealFs.unlinkSync = function(path){
    tree.remove(path);
    return null;
};

unrealFs.unwatchFile = function(filename, listener){
    console.log('unwatchFile', arguments);
};

unrealFs.utimes = function(path, atime, mtime, callback){
    console.log('utimes', arguments);
};

unrealFs.utimesSync = function(path, atime, mtime){
    console.log('utimesSync', arguments);
};

unrealFs.watch = function(filename, options, listener){
    console.log('watch', arguments);
};

unrealFs.watchFile = function(filename, options, listener){
    console.log('watchFile', arguments);
};

/**
 * @TODO param options is optional
 * @TODO add errors to callback
 */
unrealFs.writeFile = function(file, data, options, callback){

    unrealFs.writeFileSync(file, data, options);

    var callbackParam = null;

    if (true === unrealFs.hasForce('writeFile')){
        callbackParam = unrealFs.doForce('writeFile');
    }

    process.nextTick(function () {
        callback(callbackParam);
    });

};

/**
 * @TODO param options is optional
 */
unrealFs.writeFileSync = function(file, data, options){
    if (false === tree.exists(file)){
        tree.addFile(file);
    }

    tree.getNodeByPath(file).setContent(data);

};

module.exports = unrealFs;

<|endoftext|>


<commit_before>const { join } = require('path')
const { existsSync, outputFileSync } = require('fs-extra')

module.exports = function outputHTML({
  template: tag,
  path,
  data,
  engine = 'swig',
}) {
  const { base, public: publicDir, templatePath } = this.config

  if (!templatePath) {
    return
  }

  const { methods, defaultMethods } = this.helper
  const tpl = join(templatePath, 'layout', `${tag}.html`)
  const helpers = {}

  if (!existsSync(tpl)) {
    this.logger.error(`Cannot find template: ${tag}.html`)
    return
  }

  Object.keys(methods).forEach((name) => {
    if (!defaultMethods.includes(name)
      && Object.prototype.hasOwnProperty.call(methods[name], 'prototype') // if bound function
    ) {
      helpers[name] = methods[name].bind(data)
    } else {
      helpers[name] = methods[name]
    }
  })

  const html = this.renderer.renderFile(engine, tpl, {
    config: this.config,
    page: data,
    ...helpers,
  })

  outputFileSync(join(base, publicDir, path), html)
  this.logger({ interactive: true }).success(path)
}
<commit_msg>fix: output log [ci skip]<commit_after>const { join } = require('path')
const { existsSync, outputFileSync } = require('fs-extra')

module.exports = function outputHTML({
  template: tag,
  path,
  data,
  engine = 'swig',
}) {
  const { base, public: publicDir, templatePath } = this.config

  if (!templatePath) {
    return
  }

  const { methods, defaultMethods } = this.helper
  const tpl = join(templatePath, 'layout', `${tag}.html`)
  const helpers = {}

  if (!existsSync(tpl)) {
    this.logger.error(`Cannot find template: ${tag}.html`)
    return
  }

  Object.keys(methods).forEach((name) => {
    if (!defaultMethods.includes(name)
      && Object.prototype.hasOwnProperty.call(methods[name], 'prototype') // if bound function
    ) {
      helpers[name] = methods[name].bind(data)
    } else {
      helpers[name] = methods[name]
    }
  })

  const html = this.renderer.renderFile(engine, tpl, {
    config: this.config,
    page: data,
    ...helpers,
  })

  outputFileSync(join(base, publicDir, path), html)
  this.logger.success(path)
}
<|endoftext|>


<commit_before>import $ from 'jquery';
import getScrubbedData from './dataUtils';
import testData from '../../test/data/test-data';
import apiKey from '../../test/apiKey';

const getWeatherData = location => {
  if (parseInt(location, 10)) {
    return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${location}.json`)
      .then(data => {
        return getScrubbedData(data);
      })
      .catch(error => console.log('catch', error));
  } else {
    const cityStateArr = location.split(', ');
    return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${cityStateArr[1]}/${cityStateArr[0]}.json`)
      .then(data => {
        return getScrubbedData(data);
      })
      .catch(error => console.log('catch', error));
  }
};

const getTestWeatherData = () => {
  return getScrubbedData(testData);
};

export { getWeatherData, getTestWeatherData };
<commit_msg>Fix test data coming back as undefined.<commit_after>import $ from 'jquery';
import getScrubbedData from './dataUtils';
import { testData } from '../../test/data/test-data';
import apiKey from '../../test/apiKey';

const getWeatherData = location => {
  if (parseInt(location, 10)) {
    return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${location}.json`)
      .then(data => {
        return getScrubbedData(data);
      })
      .catch(error => console.log('catch', error));
  } else {
    const cityStateArr = location.split(', ');
    return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${cityStateArr[1]}/${cityStateArr[0]}.json`)
      .then(data => {
        return getScrubbedData(data);
      })
      .catch(error => console.log('catch', error));
  }
};

const getTestWeatherData = () => {
  return getScrubbedData(testData);
};

export { getWeatherData, getTestWeatherData };
<|endoftext|>


<commit_before>var Promise = global.Packages.Promise,
Hold = global.Packages.Hold,
Memcached = global.Packages.Memcached;

var _cacheClient, _defaultExpiryInSeconds = 60 * 60;

var issue = function(details){
    global.Logger.error(JSON.stringify(details));

};

var failure = function(details){
    global.Logger.error(JSON.stringify(details));

};

var reconnecting = function(details){
    global.Logger.error(JSON.stringify(details));

};

var getCacheClient = function(ctx) {

    var needstoreload = false;

	if (!_cacheClient) {
		needstoreload = true;
	}

	if (needstoreload) {

		return ctx.getServers().then(function(servers) {

				if (_cacheClient) {
					_cacheClient.end();
				}
				var memcached_servers = [];
				for(var index = 0; index < servers.length; index++){

				    memcached_servers.push(servers[index].server + ":" + servers[index].port);
				}

				_cacheClient = new Memcached(memcached_servers);
				_cacheClient.setMaxListeners(0);
			    return _cacheClient;

		});
	} else {
		return new Promise(function(resolve){
		    resolve(_cacheClient);
		    return;
		});
	}
};

function MemCache(){

}

MemCache.prototype.getServers = function getServers(){
    return new Promise(function (resolve){
        return resolve([
            {
                server : "localhost",
                port : 11211
        }]);
    });
};

function setValue(cache_client,key, value, expiry_in_seconds, callback){
    cache_client.set(key, value, expiry_in_seconds, function(err){
        if(err){
            callback(err);
            return;
        }
        callback(null);
        return;
    });
}

function getValue(cache_client,key, callback){
    cache_client.get(key, function(err, val){
        if(err){
            callback(err, null);
            return;
        }
        callback(null, val);
        return;
    });
}

function removeValue(cache_client, key , callback){
    cache_client.del(key, function(err){
        if(err){
            callback(err);
            return;
        }
        callback(null);
        return;
    });
}

MemCache.prototype.set = function set(key, value, expiry_in_seconds){
    var self = this;
    expiry_in_seconds = (expiry_in_seconds && expiry_in_seconds > 0) ? expiry_in_seconds : _defaultExpiryInSeconds;
   return getCacheClient(self).then(function(cache) {

		return Promise.promisify(setValue)(cache, key, value, _defaultExpiryInSeconds).then(function(){
			return;
		});

	}).then(function(){
	    return;
	});
};

MemCache.prototype.get = function get(key) {
    var self = this;
	return getCacheClient(self).then(function(cache) {

		return Promise.promisify(getValue)(cache, key).then(function(value){
			if(value === false) {
			    return null;
			}
			else{
			    return value;
			}
		});

	}).then(function(val){
	    return val;
	});

};

MemCache.prototype.remove = function remove(key){
      var self = this;
	return getCacheClient(self).then(function(cache) {
		return Promise.promisify(removeValue)(cache, key).then(function(){
			return;
		});

	}).then(function(){
	    return;
	});

};

module.exports = MemCache;

<commit_msg>lint fix1 memcache<commit_after>var Promise = global.Packages.Promise,
    Memcached = global.Packages.Memcached;

var _cacheClient, _defaultExpiryInSeconds = 60 * 60;

var issue = function(details) {
    global.Logger.error(JSON.stringify(details));

};

var failure = function(details) {
    global.Logger.error(JSON.stringify(details));

};

var reconnecting = function(details) {
    global.Logger.error(JSON.stringify(details));

};

var getCacheClient = function(ctx) {

    var needstoreload = false;

    if (!_cacheClient) {
        needstoreload = true;
    }

    if (needstoreload) {

        return ctx.getServers().then(function(servers) {

            if (_cacheClient) {
                _cacheClient.end();
            }
            var memcached_servers = [];
            for (var index = 0; index < servers.length; index++) {

                memcached_servers.push(servers[index].server + ":" + servers[index].port);
            }

            _cacheClient = new Memcached(memcached_servers);
            _cacheClient.setMaxListeners(0);
            return _cacheClient;

        });
    }
    else {
        return new Promise(function(resolve) {
            resolve(_cacheClient);
            return;
        });
    }
};

function MemCache() {

}

MemCache.prototype.getServers = function getServers() {
    return new Promise(function(resolve) {
        return resolve([{
            server: "localhost",
            port: 11211
        }]);
    });
};

function setValue(cache_client, key, value, expiry_in_seconds, callback) {
    cache_client.set(key, value, expiry_in_seconds, function(err) {
        if (err) {
            callback(err);
            return;
        }
        callback(null);
        return;
    });
}

function getValue(cache_client, key, callback) {
    cache_client.get(key, function(err, val) {
        if (err) {
            callback(err, null);
            return;
        }
        callback(null, val);
        return;
    });
}

function removeValue(cache_client, key, callback) {
    cache_client.del(key, function(err) {
        if (err) {
            callback(err);
            return;
        }
        callback(null);
        return;
    });
}

MemCache.prototype.set = function set(key, value, expiry_in_seconds) {
    var self = this;
    expiry_in_seconds = (expiry_in_seconds && expiry_in_seconds > 0) ? expiry_in_seconds : _defaultExpiryInSeconds;
    return getCacheClient(self).then(function(cache) {

        return Promise.promisify(setValue)(cache, key, value, _defaultExpiryInSeconds).then(function() {
            return;
        });

    }).then(function() {
        return;
    });
};

MemCache.prototype.get = function get(key) {
    var self = this;
    return getCacheClient(self).then(function(cache) {

        return Promise.promisify(getValue)(cache, key).then(function(value) {
            if (value === false) {
                return null;
            }
            else {
                return value;
            }
        });

    }).then(function(val) {
        return val;
    });

};

MemCache.prototype.remove = function remove(key) {
    var self = this;
    return getCacheClient(self).then(function(cache) {
        return Promise.promisify(removeValue)(cache, key).then(function() {
            return;
        });

    }).then(function() {
        return;
    });

};

module.exports = MemCache;
<|endoftext|>


<commit_before>'use strict';

var cacheTimes = require('../../web/config/cache-times');
var _ = require('lodash');
_.mixin(require("lodash-deep"));

module.exports = function(options){
  var seneca = this;
  var plugin = 'users-proxy';
  var version = '1.0';

  options = seneca.util.deepextend({
    prefix: '/api/'
  }, options);

  seneca.add({role: plugin, cmd: 'list'}, proxy);
  seneca.add({role: plugin, cmd: 'register'}, proxy);
  seneca.add({role: plugin, cmd: 'promote'}, proxy);
  seneca.add({role: plugin, cmd: 'get_users_by_emails'}, proxy);
  seneca.add({role: plugin, cmd: 'update'}, proxy);
  seneca.add({role: plugin, cmd: 'load'}, proxy);
  seneca.add({role: plugin, cmd: 'get_init_user_types'}, proxy);
  seneca.add({role: plugin, cmd: 'is_champion'}, proxy);
  seneca.add({role: plugin, cmd: 'reset_password'}, proxy);
  seneca.add({role: plugin, cmd: 'execute_reset'}, proxy);
  seneca.add({role: plugin, cmd: 'load_champions_for_user'}, proxy);
  seneca.add({role: plugin, cmd: 'load_dojo_admins_for_user'}, proxy);
  seneca.add({role: plugin, cmd: 'kpi_number_of_youths_registered'}, proxyNeedCDFAdmin);

  function proxy(args, done) {
    var user;
    var zenHostname = args.req$.headers.host || '127.0.0.1:8000';
    var locality = (args.req$ && args.req$.cookies.NG_TRANSLATE_LANG_KEY && args.req$.cookies.NG_TRANSLATE_LANG_KEY.replace(/\"/g, '')) || args.req$ && args.req$.headers['accept-language'];
    locality = formatLocaleCode(locality);
    if(args.req$.seneca.user) user = args.req$.seneca.user;
    seneca.act(seneca.util.argprops(
      {user:user, zenHostname: zenHostname, locality: locality, fatal$: false},
      args,
      {role: 'cd-users'}
    ), done);
  }

  function proxyNeedCDFAdmin(args, done) {
    if(!_.deepHas(args.req$, 'user.user') || !_.contains(args.req$.seneca.user.roles, 'cdf-admin')) return done(null, {ok: false, why: 'You must be a cdf admin to access this data'});
    return proxy(args, done);
  }

  function formatLocaleCode(code) {
    return code.slice(0, 3) + code.charAt(3).toUpperCase() + code.charAt(4).toUpperCase();
  }

  seneca.act({ role: 'web', use: {
    prefix: options.prefix+version+'/users',
    pin: {role: plugin,  cmd: '*'},
    map: {
      'list': {POST: true, alias: 'list'},
      'register': {POST: true, alias: 'register'},
      'promote': {PUT: true, alias: 'promote/:id'},
      'get_users_by_emails': {POST: true, alias: 'emails'},
      'update': {PUT: true, alias: 'update/:id'},
      'load': {GET: true, alias: 'load/:id'},
      'get_init_user_types': {GET: true, alias: 'init_user_types', expiresIn: cacheTimes.long},
      'is_champion': {POST: true, alias:'isChampion'},
      'reset_password': {POST: true, alias: 'reset_password'},
      'execute_reset': {POST: true, alias: 'execute_reset'},
      'load_champions_for_user': {GET: true, alias: 'champions_for_user/:userId'},
      'load_dojo_admins_for_user': {GET: true, alias: 'dojo_admins_for_user/:userId'},
      'kpi_number_of_youths_registered': {GET: true, alias: 'kpi/number_of_youths_registered'}
    }
  }});

  return {
    name: plugin
  }

};
<commit_msg>add champions and mentors registered kpi<commit_after>'use strict';

var cacheTimes = require('../../web/config/cache-times');
var _ = require('lodash');
_.mixin(require("lodash-deep"));

module.exports = function(options){
  var seneca = this;
  var plugin = 'users-proxy';
  var version = '1.0';

  options = seneca.util.deepextend({
    prefix: '/api/'
  }, options);

  seneca.add({role: plugin, cmd: 'list'}, proxy);
  seneca.add({role: plugin, cmd: 'register'}, proxy);
  seneca.add({role: plugin, cmd: 'promote'}, proxy);
  seneca.add({role: plugin, cmd: 'get_users_by_emails'}, proxy);
  seneca.add({role: plugin, cmd: 'update'}, proxy);
  seneca.add({role: plugin, cmd: 'load'}, proxy);
  seneca.add({role: plugin, cmd: 'get_init_user_types'}, proxy);
  seneca.add({role: plugin, cmd: 'is_champion'}, proxy);
  seneca.add({role: plugin, cmd: 'reset_password'}, proxy);
  seneca.add({role: plugin, cmd: 'execute_reset'}, proxy);
  seneca.add({role: plugin, cmd: 'load_champions_for_user'}, proxy);
  seneca.add({role: plugin, cmd: 'load_dojo_admins_for_user'}, proxy);
  seneca.add({role: plugin, cmd: 'kpi_number_of_youths_registered'}, proxyNeedCDFAdmin);
  seneca.add({role: plugin, cmd: 'kpi_number_of_champions_and_mentors_registered'}, proxyNeedCDFAdmin);

  function proxy(args, done) {
    var user;
    var zenHostname = args.req$.headers.host || '127.0.0.1:8000';
    var locality = (args.req$ && args.req$.cookies.NG_TRANSLATE_LANG_KEY && args.req$.cookies.NG_TRANSLATE_LANG_KEY.replace(/\"/g, '')) || args.req$ && args.req$.headers['accept-language'];
    locality = formatLocaleCode(locality);
    if(args.req$.seneca.user) user = args.req$.seneca.user;
    seneca.act(seneca.util.argprops(
      {user:user, zenHostname: zenHostname, locality: locality, fatal$: false},
      args,
      {role: 'cd-users'}
    ), done);
  }

  function proxyNeedCDFAdmin(args, done) {
    if(!_.deepHas(args.req$, 'user.user') || !_.contains(args.req$.seneca.user.roles, 'cdf-admin')) return done(null, {ok: false, why: 'You must be a cdf admin to access this data'});
    return proxy(args, done);
  }

  function formatLocaleCode(code) {
    return code.slice(0, 3) + code.charAt(3).toUpperCase() + code.charAt(4).toUpperCase();
  }

  seneca.act({ role: 'web', use: {
    prefix: options.prefix+version+'/users',
    pin: {role: plugin,  cmd: '*'},
    map: {
      'list': {POST: true, alias: 'list'},
      'register': {POST: true, alias: 'register'},
      'promote': {PUT: true, alias: 'promote/:id'},
      'get_users_by_emails': {POST: true, alias: 'emails'},
      'update': {PUT: true, alias: 'update/:id'},
      'load': {GET: true, alias: 'load/:id'},
      'get_init_user_types': {GET: true, alias: 'init_user_types', expiresIn: cacheTimes.long},
      'is_champion': {POST: true, alias:'isChampion'},
      'reset_password': {POST: true, alias: 'reset_password'},
      'execute_reset': {POST: true, alias: 'execute_reset'},
      'load_champions_for_user': {GET: true, alias: 'champions_for_user/:userId'},
      'load_dojo_admins_for_user': {GET: true, alias: 'dojo_admins_for_user/:userId'},
      'kpi_number_of_youths_registered': {GET: true, alias: 'kpi/number_of_youths_registered'},
      'kpi_number_of_champions_and_mentors_registered': {GET: true, alias: 'kpi/number_of_champions_and_mentors_registered'}
    }
  }});

  return {
    name: plugin
  }

};
<|endoftext|>


<commit_before>/**
 * Patternslib pattern for Masonry
 * Copyright 2015 Syslab.com GmBH
 */

(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define([
            "jquery",
            "pat-logger",
            "pat-registry",
            "pat-parser",
            "pat-base",
            "pat-utils",
            "masonry",
            "imagesloaded"
            ], function() {
                return factory.apply(this, arguments);
        });
    } else {
        factory(root.$, root.patterns, root.patterns.Parser, root.Base, root.Masonry, root.imagesLoaded);
    }
}(this, function($, logger, registry, Parser, Base, utils, Masonry, imagesLoaded) {
    "use strict";
    var log = logger.getLogger("pat.masonry");
    var parser = new Parser("masonry");
    parser.addArgument("column-width");
    parser.addArgument("container-style", '{ "position": "relative" }');
    parser.addArgument("gutter");
    parser.addArgument("hidden-style", "{ opacity: 0, transform: 'scale(0.001)' }");
    parser.addArgument("is-fit-width", false);
    parser.addArgument("is-origin-left", true);
    parser.addArgument("is-origin-top", true);
    parser.addArgument("item-selector", ".item");
    parser.addArgument("stamp", "");
    parser.addArgument("transition-duration", "0.4s");
    parser.addArgument("visible-style", "{ opacity: 1, transform: 'scale(1)' }");

    return Base.extend({
        name: "masonry",
        trigger: ".pat-masonry",

        init: function masonryInit($el, opts) {
            this.options = parser.parse(this.$el, opts);
            this.initMasonry();
            var imgLoad = imagesLoaded(this.$el);
            imgLoad.on("progress", function() {
                this.msnry.layout();
            }.bind(this));
            imgLoad.on("done", this.layout.bind(this));
            // Update if something gets injected inside the pat-masonry
            // element.
            this.$el.on("patterns-injected.pat-masonry",
                    utils.debounce(this.update.bind(this), 100));
        },

        initMasonry: function () {
            var containerStyle;
            try {
                containerStyle = JSON.parse(this.options.containerStyle);
            } catch (e) {
                containerStyle = { "position": "relative" };
                log.warn(
                    "Invalid value passed in as containerStyle. Needs to "+
                    "be valid JSON so that it can be converted to an object for Masonry."
                );
            }
            this.msnry = new Masonry(this.$el[0], {
                columnWidth:         this.getTypeCastedValue(this.options.columnWidth),
                containerStyle:      containerStyle,
                gutter:              this.getTypeCastedValue(this.options.gutter),
                hiddenStyle:         this.options.hiddenStyle,
                isFitWidth:          this.options.is["fit-width"],
                isInitLayout:        false,
                isOriginLeft:        this.options.is["origin-left"],
                isOriginTOp:         this.options.is["origin-top"],
                itemSelector:        this.options.itemSelector,
                stamp:               this.options.stamp,
                transitionDuration:  this.options.transitionDuration,
                visibleStyle:        this.options.visibleStyle
            });
        },

        update: function () {
            this.msnry.remove();
            this.initMasonry();
            this.layout();
        },

        layout: function () {
            this.$el.removeClass("masonry-ready");
            this.msnry.on("layoutComplete", function() {
                this.$el.addClass("masonry-ready");
            }.bind(this));
            this.msnry.layout();
        },

        getTypeCastedValue: function (original) {
            var val = Number(original);
            return (isNaN(val)) ? (original || 0) : val;
        }
    });
}));
<commit_msg>https://github.com/Patternslib/Patterns/commit/e243605ae097ef45cee065c2ae4a95794aedb937 breaks because the masonry-ready class is now only set if imgLoad actually throws a done. If all images are cached, this doesn't happen. I would like to actually call this.layout simply twice, instead of doing only this.msnry.layout() in line 48<commit_after>/**
 * Patternslib pattern for Masonry
 * Copyright 2015 Syslab.com GmBH
 */

(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define([
            "jquery",
            "pat-logger",
            "pat-registry",
            "pat-parser",
            "pat-base",
            "pat-utils",
            "masonry",
            "imagesloaded"
            ], function() {
                return factory.apply(this, arguments);
        });
    } else {
        factory(root.$, root.patterns, root.patterns.Parser, root.Base, root.Masonry, root.imagesLoaded);
    }
}(this, function($, logger, registry, Parser, Base, utils, Masonry, imagesLoaded) {
    "use strict";
    var log = logger.getLogger("pat.masonry");
    var parser = new Parser("masonry");
    parser.addArgument("column-width");
    parser.addArgument("container-style", '{ "position": "relative" }');
    parser.addArgument("gutter");
    parser.addArgument("hidden-style", "{ opacity: 0, transform: 'scale(0.001)' }");
    parser.addArgument("is-fit-width", false);
    parser.addArgument("is-origin-left", true);
    parser.addArgument("is-origin-top", true);
    parser.addArgument("item-selector", ".item");
    parser.addArgument("stamp", "");
    parser.addArgument("transition-duration", "0.4s");
    parser.addArgument("visible-style", "{ opacity: 1, transform: 'scale(1)' }");

    return Base.extend({
        name: "masonry",
        trigger: ".pat-masonry",

        init: function masonryInit($el, opts) {
            this.options = parser.parse(this.$el, opts);
            this.initMasonry();
            var imgLoad = imagesLoaded(this.$el);
            imgLoad.on("progress", function() {
                this.layout();
            }.bind(this));
            imgLoad.on("done", this.layout.bind(this));
            // Update if something gets injected inside the pat-masonry
            // element.
            this.$el.on("patterns-injected.pat-masonry",
                    utils.debounce(this.update.bind(this), 100));
        },

        initMasonry: function () {
            var containerStyle;
            try {
                containerStyle = JSON.parse(this.options.containerStyle);
            } catch (e) {
                containerStyle = { "position": "relative" };
                log.warn(
                    "Invalid value passed in as containerStyle. Needs to "+
                    "be valid JSON so that it can be converted to an object for Masonry."
                );
            }
            this.msnry = new Masonry(this.$el[0], {
                columnWidth:         this.getTypeCastedValue(this.options.columnWidth),
                containerStyle:      containerStyle,
                gutter:              this.getTypeCastedValue(this.options.gutter),
                hiddenStyle:         this.options.hiddenStyle,
                isFitWidth:          this.options.is["fit-width"],
                isInitLayout:        false,
                isOriginLeft:        this.options.is["origin-left"],
                isOriginTOp:         this.options.is["origin-top"],
                itemSelector:        this.options.itemSelector,
                stamp:               this.options.stamp,
                transitionDuration:  this.options.transitionDuration,
                visibleStyle:        this.options.visibleStyle
            });
        },

        update: function () {
            this.msnry.remove();
            this.initMasonry();
            this.layout();
        },

        layout: function () {
            this.$el.removeClass("masonry-ready");
            this.msnry.on("layoutComplete", function() {
                this.$el.addClass("masonry-ready");
            }.bind(this));
            this.msnry.layout();
        },

        getTypeCastedValue: function (original) {
            var val = Number(original);
            return (isNaN(val)) ? (original || 0) : val;
        }
    });
}));
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

class StringXor {
	constructor() {
		this._value = undefined;
		this._buffer = undefined;
	}

	add(str) {
		let buf = this._buffer;
		let value;
		if (buf === undefined) {
			buf = this._buffer = Buffer.from(str, "latin1");
			this._value = Buffer.from(buf);
			return;
		} else if (buf.length !== str.length) {
			value = this._value;
			buf = this._buffer = Buffer.from(str, "latin1");
			if (value.length < buf.length) {
				this._value = Buffer.allocUnsafe(buf.length);
				value.copy(this._value);
				this._value.fill(0, value.length);
				value = this._value;
			}
		} else {
			value = this._value;
			buf.write(str, "latin1");
		}
		const len = buf.length;
		for (let i = 0; i < len; i++) {
			value[i] = value[i] ^ buf[i];
		}
	}

	toString() {
		return this._value === undefined ? "" : this._value.toString("latin1");
	}

	updateHash(hash) {
		if (this._value !== undefined) hash.update(this._value);
	}
}

module.exports = StringXor;
<commit_msg>faster StringXor<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

class StringXor {
	constructor() {
		this._value = undefined;
	}

	/**
	 * @param {string} str string
	 * @returns {void}
	 */
	add(str) {
		const len = str.length;
		const value = this._value;
		if (value === undefined) {
			const newValue = (this._value = Buffer.allocUnsafe(len));
			for (let i = 0; i < len; i++) {
				newValue[i] = str.charCodeAt(i);
			}
			return;
		}
		const valueLen = value.length;
		if (valueLen < len) {
			const newValue = (this._value = Buffer.allocUnsafe(len));
			let i;
			for (i = 0; i < valueLen; i++) {
				newValue[i] = value[i] ^ str.charCodeAt(i);
			}
			for (; i < len; i++) {
				newValue[i] = str.charCodeAt(i);
			}
		} else {
			for (let i = 0; i < len; i++) {
				value[i] = value[i] ^ str.charCodeAt(i);
			}
		}
	}

	toString() {
		const value = this._value;
		return value === undefined ? "" : value.toString("latin1");
	}

	updateHash(hash) {
		const value = this._value;
		if (value !== undefined) hash.update(value);
	}
}

module.exports = StringXor;
<|endoftext|>


<commit_before>var parse = require('url').parse;

var URL_RE = /^([a-z0-9.+-]+:)\/\/([^/?#]+)(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i;
var HOST_RE = /^(.+)(?::(\d*))$/;

module.exports = function(url) {
  if (!URL_RE.test(url)) {
    return parse(url);
  }
  var protocol = RegExp.$1;
  var host = RegExp.$2;
  var pathname = RegExp.$3 || '/';
  var search = RegExp.$4;
  var port = null;
  var hostname = host;
  if (HOST_RE.test(host)) {
    hostname = RegExp.$1;
    port = RegExp.$2;
  }

  return {
    protocol: protocol,
    slashes: true,
    auth: null,
    host: host,
    port: port,
    hostname: hostname,
    hash: RegExp.$5 || null,
    search: search || null,
    query: search ? search.substring(1) : null,
    pathname: pathname,
    path: pathname + search,
    href: url
  };
};
<commit_msg>refactor: url.parse<commit_after>var parse = require('url').parse;

var URL_RE = /^([a-z0-9.+-]+:)\/\/([^/?#]+)(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i;
var HOST_RE = /^(.+)(?::(\d*))$/;

module.exports = function(url) {
  if (!URL_RE.test(url)) {
    return parse(url);
  }
  var protocol = RegExp.$1;
  var host = RegExp.$2;
  var pathname = RegExp.$3 || '/';
  var search = RegExp.$4;
  var hash = RegExp.$5 || null;
  var port = null;
  var hostname = host;
  if (HOST_RE.test(host)) {
    hostname = RegExp.$1;
    port = RegExp.$2;
  }

  return {
    protocol: protocol,
    slashes: true,
    auth: null,
    host: host,
    port: port,
    hostname: hostname,
    hash: hash,
    search: search || null,
    query: search ? search.substring(1) : null,
    pathname: pathname,
    path: pathname + search,
    href: url
  };
};
<|endoftext|>


<commit_before>modules.define('util.dom', [

], function (provide) {

    var utilDom = {
        /**
         * @param {String} selector
         * @param {HTMLElement} [parentElement = document]
         * @param {Boolean} [findAll = false]
         */
        find: function (options) {
            var element,
                parent = parentElement || document;

            element = findAll ?
                parentElement.querySelectorAll(selector) :
                parentElement.querySelector(selector);

            return element;
        },

        findById: function (query, parentElement) {
            var element;
            if (parentElement) {
                element = parentElement.getElementById(elementId);
            } else {
                element = document.getElementById(elementId);
            }

            return element;
        },

        /**
         * @param {Object|String} [options] Options or element tag name.
         * @param {String} [options.tag = 'div']
         * @param {String} [options.content]
         * @param {Object} [options.attrs]
         * @param {HTMLElement} [options.parentElement]
         * @returns {HTMLElement} Created element.
         */
        create: function (options) {
            options = options || {};

            var tagName = typeof options == 'string' ? options : (options.tag || 'div'),
                element = document.createElement(tagName);

            if (optios.attrs) {
                for (var attribute in options.attrs) {
                    if (options.attrs.hadOwnProperty(attribute)) {
                        element.setAttribute(attribute, options.attrs[attribute]);
                    }
                }
            }

            if (options.parentElement) {
                options.parentElement.appendChild(element);
            }

            return element;
        }
    }

    provide(utilDom);
});
<commit_msg>[util.dom] add .remove<commit_after>modules.define('util.dom', [

], function (provide) {

    var utilDom = {
        /**
         * @param {String} selector
         * @param {HTMLElement} [parentElement = document]
         * @param {Boolean} [findAll = false]
         */
        find: function (options) {
            var element,
                parent = parentElement || document;

            element = findAll ?
                parentElement.querySelectorAll(selector) :
                parentElement.querySelector(selector);

            return element;
        },

        findById: function (query, parentElement) {
            var element;
            if (parentElement) {
                element = parentElement.getElementById(elementId);
            } else {
                element = document.getElementById(elementId);
            }

            return element;
        },

        /**
         * @param {Object|String} [options] Options or element tag name.
         * @param {String} [options.tag = 'div']
         * @param {String} [options.content]
         * @param {Object} [options.attrs]
         * @param {HTMLElement} [options.parentElement]
         * @returns {HTMLElement} Created element.
         */
        create: function (options) {
            options = options || {};

            var tagName = typeof options == 'string' ? options : (options.tag || 'div'),
                element = document.createElement(tagName);

            if (optios.attrs) {
                for (var attribute in options.attrs) {
                    if (options.attrs.hadOwnProperty(attribute)) {
                        element.setAttribute(attribute, options.attrs[attribute]);
                    }
                }
            }

            if (options.parentElement) {
                options.parentElement.appendChild(element);
            }

            return element;
        },

        /**
         * @param {HTMLElement} node
         */
        remove: function (node) {
            if (node.parentNode) {
                node.parentNode.removeChild(node);
            }
        }
    }

    provide(utilDom);
});
<|endoftext|>


<commit_before>/*!
 * layout-browser.js - walletdb and txdb layout for browser.
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var utils = require('../utils/utils');
var pad32 = utils.pad32;
var layout = exports;

layout.walletdb = {
  p: function p(hash) {
    return 'p' + hash;
  },
  pp: function pp(key) {
    return key.slice(1);
  },
  P: function P(wid, hash) {
    return 'p' + pad32(wid) + hash;
  },
  Pp: function Pp(key) {
    return key.slice(11);
  },
  w: function w(wid) {
    return 'w' + pad32(wid);
  },
  ww: function ww(key) {
    return +key.slice(1);
  },
  l: function l(id) {
    return 'l' + id;
  },
  ll: function ll(key) {
    return key.slice(1);
  },
  a: function a(wid, index) {
    return 'a' + pad32(wid) + pad32(index);
  },
  i: function i(wid, name) {
    return 'i' + pad32(wid) + name;
  },
  ii: function ii(key) {
    return [+key.slice(1, 11), key.slice(11)];
  },
  R: 'R',
  c: function c(height) {
    return 'b' + pad32(height);
  },
  cc: function cc(key) {
    return +key.slice(1);
  },
  b: function b(height) {
    return 'b' + pad32(height);
  },
  bb: function bb(key) {
    return +key.slice(1);
  },
  e: function e(hash) {
    return 'e' + hash;
  },
  ee: function ee(key) {
    return key.slice(1);
  }
};

layout.txdb = {
  prefix: function prefix(wid, key) {
    return 't' + pad32(wid) + key;
  },
  pre: function prefix(key) {
    return +key.slice(1, 11);
  },
  R: 'R',
  hi: function hi(ch, hash, index) {
    return ch + hash + pad32(index);
  },
  hii: function hii(key) {
    key = key.slice(12);
    return [key.slice(0, 64), +key.slice(64)];
  },
  ih: function ih(ch, index, hash) {
    return ch + pad32(index) + hash;
  },
  ihh: function ihh(key) {
    key = key.slice(12);
    return [+key.slice(0, 10), key.slice(10)];
  },
  iih: function iih(ch, index, num, hash) {
    return ch + pad32(index) + pad32(num) + hash;
  },
  iihh: function iihh(key) {
    key = key.slice(12);
    return [+key.slice(0, 10), +key.slice(10, 20), key.slice(20)];
  },
  ihi: function ihi(ch, index, hash, num) {
    return ch + pad32(index) + hash + pad32(num);
  },
  ihii: function ihii(key) {
    key = key.slice(12);
    return [+key.slice(0, 10), key.slice(10, 74), +key.slice(74)];
  },
  ha: function ha(ch, hash) {
    return ch + hash;
  },
  haa: function haa(key) {
    key = key.slice(12);
    return key;
  },
  t: function t(hash) {
    return this.ha('t', hash);
  },
  tt: function tt(key) {
    return this.haa(key);
  },
  c: function c(hash, index) {
    return this.hi('c', hash, index);
  },
  cc: function cc(key) {
    return this.hii(key);
  },
  d: function d(hash, index) {
    return this.hi('d', hash, index);
  },
  dd: function dd(key) {
    return this.hii(key);
  },
  s: function s(hash, index) {
    return this.hi('s', hash, index);
  },
  ss: function ss(key) {
    return this.hii(key);
  },
  S: function S(hash, index) {
    return this.hi('S', hash, index);
  },
  Ss: function Ss(key) {
    return this.hii(key);
  },
  p: function p(hash) {
    return this.ha('p', hash);
  },
  pp: function pp(key) {
    return this.haa(key);
  },
  m: function m(time, hash) {
    return this.ih('m', time, hash);
  },
  mm: function mm(key) {
    return this.ihh(key);
  },
  h: function h(height, hash) {
    return this.ih('h', height, hash);
  },
  hh: function hh(key) {
    return this.ihh(key);
  },
  T: function T(account, hash) {
    return this.ih('T', account, hash);
  },
  Tt: function Tt(key) {
    return this.ihh(key);
  },
  P: function P(account, hash) {
    return this.ih('P', account, hash);
  },
  Pp: function Pp(key) {
    return this.ihh(key);
  },
  M: function M(account, time, hash) {
    return this.iih('M', account, time, hash);
  },
  Mm: function Mm(key) {
    return this.iihh(key);
  },
  H: function H(account, height, hash) {
    return this.iih('H', account, height, hash);
  },
  Hh: function Hh(key) {
    return this.iihh(key);
  },
  C: function C(account, hash, index) {
    return this.ihi('C', account, hash, index);
  },
  Cc: function Cc(key) {
    return this.ihii(key);
  },
  r: function r(hash) {
    return this.ha('r', hash);
  }
};

/*
 * Expose
 */

module.exports = layout;
<commit_msg>walletdb: browser key.<commit_after>/*!
 * layout-browser.js - walletdb and txdb layout for browser.
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var utils = require('../utils/utils');
var pad32 = utils.pad32;
var layout = exports;

layout.walletdb = {
  p: function p(hash) {
    return 'p' + hash;
  },
  pp: function pp(key) {
    return key.slice(1);
  },
  P: function P(wid, hash) {
    return 'p' + pad32(wid) + hash;
  },
  Pp: function Pp(key) {
    return key.slice(11);
  },
  w: function w(wid) {
    return 'w' + pad32(wid);
  },
  ww: function ww(key) {
    return +key.slice(1);
  },
  l: function l(id) {
    return 'l' + id;
  },
  ll: function ll(key) {
    return key.slice(1);
  },
  a: function a(wid, index) {
    return 'a' + pad32(wid) + pad32(index);
  },
  i: function i(wid, name) {
    return 'i' + pad32(wid) + name;
  },
  ii: function ii(key) {
    return [+key.slice(1, 11), key.slice(11)];
  },
  R: 'R',
  c: function c(height) {
    return 'c' + pad32(height);
  },
  cc: function cc(key) {
    return +key.slice(1);
  },
  b: function b(height) {
    return 'b' + pad32(height);
  },
  bb: function bb(key) {
    return +key.slice(1);
  },
  e: function e(hash) {
    return 'e' + hash;
  },
  ee: function ee(key) {
    return key.slice(1);
  }
};

layout.txdb = {
  prefix: function prefix(wid, key) {
    return 't' + pad32(wid) + key;
  },
  pre: function prefix(key) {
    return +key.slice(1, 11);
  },
  R: 'R',
  hi: function hi(ch, hash, index) {
    return ch + hash + pad32(index);
  },
  hii: function hii(key) {
    key = key.slice(12);
    return [key.slice(0, 64), +key.slice(64)];
  },
  ih: function ih(ch, index, hash) {
    return ch + pad32(index) + hash;
  },
  ihh: function ihh(key) {
    key = key.slice(12);
    return [+key.slice(0, 10), key.slice(10)];
  },
  iih: function iih(ch, index, num, hash) {
    return ch + pad32(index) + pad32(num) + hash;
  },
  iihh: function iihh(key) {
    key = key.slice(12);
    return [+key.slice(0, 10), +key.slice(10, 20), key.slice(20)];
  },
  ihi: function ihi(ch, index, hash, num) {
    return ch + pad32(index) + hash + pad32(num);
  },
  ihii: function ihii(key) {
    key = key.slice(12);
    return [+key.slice(0, 10), key.slice(10, 74), +key.slice(74)];
  },
  ha: function ha(ch, hash) {
    return ch + hash;
  },
  haa: function haa(key) {
    key = key.slice(12);
    return key;
  },
  t: function t(hash) {
    return this.ha('t', hash);
  },
  tt: function tt(key) {
    return this.haa(key);
  },
  c: function c(hash, index) {
    return this.hi('c', hash, index);
  },
  cc: function cc(key) {
    return this.hii(key);
  },
  d: function d(hash, index) {
    return this.hi('d', hash, index);
  },
  dd: function dd(key) {
    return this.hii(key);
  },
  s: function s(hash, index) {
    return this.hi('s', hash, index);
  },
  ss: function ss(key) {
    return this.hii(key);
  },
  S: function S(hash, index) {
    return this.hi('S', hash, index);
  },
  Ss: function Ss(key) {
    return this.hii(key);
  },
  p: function p(hash) {
    return this.ha('p', hash);
  },
  pp: function pp(key) {
    return this.haa(key);
  },
  m: function m(time, hash) {
    return this.ih('m', time, hash);
  },
  mm: function mm(key) {
    return this.ihh(key);
  },
  h: function h(height, hash) {
    return this.ih('h', height, hash);
  },
  hh: function hh(key) {
    return this.ihh(key);
  },
  T: function T(account, hash) {
    return this.ih('T', account, hash);
  },
  Tt: function Tt(key) {
    return this.ihh(key);
  },
  P: function P(account, hash) {
    return this.ih('P', account, hash);
  },
  Pp: function Pp(key) {
    return this.ihh(key);
  },
  M: function M(account, time, hash) {
    return this.iih('M', account, time, hash);
  },
  Mm: function Mm(key) {
    return this.iihh(key);
  },
  H: function H(account, height, hash) {
    return this.iih('H', account, height, hash);
  },
  Hh: function Hh(key) {
    return this.iihh(key);
  },
  C: function C(account, hash, index) {
    return this.ihi('C', account, hash, index);
  },
  Cc: function Cc(key) {
    return this.ihii(key);
  },
  r: function r(hash) {
    return this.ha('r', hash);
  }
};

/*
 * Expose
 */

module.exports = layout;
<|endoftext|>


<commit_before>/**
 * UX Rocket Modal
 * jQuery based modal
 * @author Bilal Cinarli
 */

(function(factory) {
    'use strict';
    if(typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if(typeof exports === 'object' && typeof require === 'function') {
        // Browserify
        factory(jQuery);
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {
    var ux,
        rocketName = 'uxrModal',
        instance = 1,

        overlay = '

',
        content = '
' +
                  '

' +
                  '

' +
                  '    ' +
                  '
',
        openedInstances = {},

        defaults = {
            className    : '',
            href         : '',
            width        : '',
            height       : '',
            maxWidth     : '',
            maxHeight    : '',
            appendTo     : 'body',
            allowMultiple: false,
            blockUI      : true,
            overlayClose : true,
            close        : true,
            iframe       : false,
            html         : false,
            fixed        : false,

            onReady : false,
            onOpen  : false,
            onStart : false,
            onLoad  : false,
            onClose : false,
            onRemove: false
        },

        events = {
            click     : 'click.' + rocketName,
            touchstart: 'touchstart.' + rocketName,
            toucemove : 'touchmove.' + rocketName,
            touchend  : 'touchend.' + rocketName,
            mousedown : 'mousedown.' + rocketName,
            mousemove : 'mousemove.' + rocketName,
            mouseup   : 'mouseup.' + rocketName,
            open      : 'uxropen.' + rocketName,
            start     : 'uxrstart.' + rocketName,
            load      : 'uxrload.' + rocketName,
            close     : 'uxrclose.' + rocketName,
            ready     : 'uxrready.' + rocketName,
            resize    : 'uxrresize.' + rocketName,
            remove    : 'uxrremove.' + rocketName
        },

        ns = {
            prefix : 'uxr-',
            rocket : 'uxRocket',
            data   : rocketName,
            name   : 'modal',
            classes: {
                ready    : 'ready',
                overlay  : 'overlay',
                container: 'container',
                drag     : 'drag',
                content  : 'content',
                loading  : 'loading',
                close    : 'close',
                hide     : 'hide'
            }
        };

    var Modal = function(el, options, selector) {
        this._name = rocketName;
        this._defaults = defaults;
        this._instance = instance;

        this.el = el;
        this.$el = $(el);
        this.$content = null;
        this.options = $.extend(true, {}, defaults, options, this.$el.data());
        this.href = this.options.href || this.$el.attr('href') || false;
        this.selector = selector;

        instance++;

        this.init();

    };

    Modal.prototype.init = function() {
        var uxrocket = this.$el.data(ns.rocket) || {};

        // register plugin data to rocket
        uxrocket[ns.data] = {hasWrapper: false, ready: utils.getClassname('ready'), selector: this.selector, options: this.options};
        this.$el.data(ns.rocket, uxrocket);

        this.bindUIActions();

        this.$el.addClass(utils.getClassname('ready'));

        // direct call
        if(this.el === null) {
            this.bindGenericActions();
            this.prepare();
        }

        this.emitEvent('ready');
    };

    Modal.prototype.bindUIActions = function() {
        var _this = this;

        if(this.el) {
            this.$el.on(events.click, function(e) {
                e.preventDefault();

                // do not open same modal more then once
                if(typeof openedInstances[_this._instance] !== 'undefined') {
                    return;
                }

                _this.emitEvent('start');
                _this.prepare();
            })
                .on(events.ready, function() {
                    _this.onReady();
                })
                .on(events.open, function() {
                    _this.onOpen();
                })
                .on(events.start, function() {
                    _this.onStart();
                })
                .on(events.load, function() {
                    _this.onLoad();
                })
                .on(events.close, function() {
                    _this.onClose();
                })
                .on(events.remove, function() {
                    _this.onRemove();
                });
        }

        $('body')
            .on(events.click + ' ' + events.touchstart, '#uxr-modal-overlay', function() {
                modal.closeFromOverlay();
            })
            .on(events.click + ' ' + events.touchstart, '#uxr-modal-instance-' + _this._instance + ' .' + utils.getClassname('close'), function(e) {
                e.preventDefault();
                _this.close();
            })
            .on(events.mousedown + ' ' + events.touchstart, '#uxr-modal-instance-' + _this._instance + ' .' + utils.getClassname('drag'), function(e) {
                e.preventDefault();
                modal.move.start(_this, e);
            });

        $(document)
            .on(events.mousemove + ' ' + events.touchmove, function(e) {
                modal.move.drag(e);
            }).on(events.mouseup + ' ' + events.touchend, function() {
                modal.move.stop();
            });
    };

    Modal.prototype.bindGenericActions = function() {
        var _this = this;

        $('body')
            .on(events.open, function() {
                _this.onOpen();
            })
            .on(events.start, function() {
                _this.onStart();
            })
            .on(events.load, function() {
                _this.onLoad();
            })
            .on(events.close, function() {
                _this.onClose();
            })
            .on(events.remove, function() {
                _this.onRemove();
            });
    };

    Modal.prototype.prepare = function() {
        var css = {},
            $overlay = $('#uxr-modal-overlay'),
            _content = content.replace('{{id}}', 'uxr-modal-instance-' + this._instance),
            _appendTo = 'body';

        if(this.options.appendTo !== 'body') {
            _appendTo = ($(utils.escapeSelector(this.options.appendTo)).length === 0) ? 'body' : this.options.appendTo;
        }

        if(!this.options.allowMultiple && modal.isOnlyInstance()) {
            modal.closeFromOverlay();
        }

        if(this.options.blockUI) {
            if($overlay.length === 0) {
                $(utils.escapeSelector(_appendTo)).append(overlay);
            }
            else {
                $overlay.removeClass(utils.getClassname('hide'));
            }
        }

        if(this.$content === null) {
            this.$content = $(_content);

            if(this.options.fixed) {
                css.position = 'fixed';
            }

            if(this.options.maxWidth !== '') {
                css.maxWidth = this.options.maxWidth;
            }

            if(this.options.maxHeight !== '') {
                css.maxHeight = this.options.maxHeight;
            }

            if(Object.keys(css).length > 0) {
                this.$content.css(css);
            }

            $(utils.escapeSelector(_appendTo)).append(this.$content);
        }

        else {
            this.$content.removeClass(utils.getClassname('hide'));
        }

        this.$content.addClass(utils.getClassname('loading'));

        modal.registerInstance(this);

        this.open();
    };

    Modal.prototype.open = function() {
        this.emitEvent('open');
        this.get();
    };

    Modal.prototype.get = function() {
        var _this = this,
            iframe;

        if(this.options.iframe) {
            this.options.width = this.options.width || 800;
            this.options.height = this.options.height || 600;

            iframe = '';
            this.html = iframe;
            _this.emitEvent('load');
        }

        else if(!this.isInpage()) {
            $.get(this.href).done(function(data) {
                _this.html = data;
                setTimeout(function() {
                    _this.emitEvent('load');
                });
            });
        }
        else if(this.href !== false) {
            this.html = $(utils.escapeSelector(this.href));
            _this.emitEvent('load');
        }
        else {
            this.html = this.options.html;
            _this.emitEvent('load');
        }
    };

    Modal.prototype.load = function() {
        var loadedContent = this.$content.find('.' + utils.getClassname('content'));

        this.$content.removeClass(utils.getClassname('loading'));

        if(this.options.close) {
            this.$content
                .find('.' + utils.getClassname('close'))
                .removeClass(utils.getClassname('hide'));
        }

        if(this.options.allowMultiple) {
            this.$content
                .find('.' + utils.getClassname('drag'))
                .removeClass(utils.getClassname('hide'));
        }

        if(!this.inpage) {
            loadedContent.html(this.html);
        }

        else {
            loadedContent.append(this.html);
        }

        this.resize();
    };

    Modal.prototype.close = function() {
        if(modal.isOnlyInstance()) {
            $('#uxr-modal-overlay').addClass(utils.getClassname('hide'));
        }

        this.$content
            .addClass(utils.getClassname('hide'))
            .find('.' + utils.getClassname('close'))
            .addClass(utils.getClassname('hide'));

        modal.close(this);

        this.emitEvent('close');
    };

    Modal.prototype.resize = function() {
        var css = {},
            loadedContent = this.$content.find('.' + utils.getClassname('content'));

        if(this.options.width !== '') {
            css.width = this.options.width;
        }

        if(this.options.height !== '') {
            css.height = this.options.height;
        }

        loadedContent.css(css);

        if(this.$content.height() < loadedContent.height()) {
            this.$content.css('overflowY', 'scroll');
        }
    };

    Modal.prototype.isInpage = function() {
        if(typeof this.inpage === 'undefined') {
            this.inpage = false;

            if(this.href === false) {
                this.inpage = true;
            }

            else if(this.href.charAt(0) === '#') {
                this.inpage = true;
            }

            else {
                var loc = window.location.href.replace(location.hash, '').replace(location.protocol, ''),
                    test = this.href.replace(location.hash, '').replace(location.protocol, '');

                if(loc === test) {
                    this.inpage = true;
                }
            }
        }

        return this.inpage;
    };

    Modal.prototype.onReady = function() {
        utils.callback(this.options.onReady);
    };

    Modal.prototype.onOpen = function() {
        utils.callback(this.options.onOpen);
    };

    Modal.prototype.onStart = function() {
        utils.callback(this.options.onStart);
    };

    Modal.prototype.onLoad = function() {
        this.load();

        utils.callback(this.options.onLoad);
    };

    Modal.prototype.onClose = function() {
        utils.callback(this.options.onClose);
    };

    Modal.prototype.onRemove = function() {
        utils.callback(this.options.onRemove);
    };

    Modal.prototype.emitEvent = function(which) {
        var $el = (this.el !== null) ? this.$el : $('body');

        $el.trigger(events[which]);
    };

    Modal.prototype.getOpenedInstances = function() {
        return openedInstances;
    };

    var modal = {
        registerInstance: function(instance) {
            openedInstances[instance._instance] = instance;
            instance.previousInstance = openedInstances.lastInstance || instance._instance;
            openedInstances.lastInstance = instance._instance;
        },
        close           : function(instance) {
            openedInstances.lastInstance = instance.previousInstance;
            delete openedInstances[instance._instance];
        },
        closeFromOverlay: function() {
            var activeInstance = openedInstances[openedInstances.lastInstance];

            if(this.hasInstances()) {
                if(!activeInstance.options.overlayClose) {
                    return;
                }

                activeInstance.close();
            }
        },
        hasInstances    : function() {
            return Object.keys(openedInstances).length > 1;
        },
        isOnlyInstance  : function() {
            return (Object.keys(openedInstances).length - 1) === 1;
        },
        move            : {
            pos     : {},
            selected: false,
            previous: false,
            start   : function(instance, e) {
                var pointer = this.pointer(e);

                this.selected = instance;
                this.selected.$content.css('zIndex', 10001);
                this.pos.top = pointer.y - this.selected.$content[0].offsetTop;
                this.pos.left = pointer.x - this.selected.$content[0].offsetLeft;

                if(!this.previous) {
                    this.previous = instance;
                }
                else {
                    this.previous.$content.css('zIndex', 10000);
                }
            },
            drag    : function(e) {
                var pointer = this.pointer(e);

                if(this.selected) {
                    this.selected.$content[0].style.top = pointer.y + 'px';
                    this.selected.$content[0].style.left = pointer.x + 'px';
                }
            },
            stop    : function() {
                if(this.selected) {
                    this.previous = this.selected;
                    this.selected = false;
                }
            },
            pointer : function(e) {
                var out = {x: 0, y: 0};
                if(e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
                    var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                    out.x = touch.pageX;
                    out.y = touch.pageY;
                } else if(e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
                    out.x = e.pageX;
                    out.y = e.pageY;
                }
                return out;
            }
        }
    };

    var utils = {
        callback: function(fn) {
            // if callback string is function call it directly
            if(typeof fn === 'function') {
                fn.apply(this);
            }

            // if callback defined via data-attribute, call it via new Function
            else {
                if(fn !== false) {
                    var func = new Function('return ' + fn);
                    func();
                }
            }
        },

        escapeSelector: function(selector) {
            var is_ID = selector.charAt(0) === '#',
                re = /([ !"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g;

            return is_ID ? '#' + selector.substring(1).replace(re, '\\$1') : selector;
        },

        getStringVariable: function(str) {
            var val;
            // check if it is chained
            if(str.indexOf('.') > -1) {
                var chain = str.split('.'),
                    chainVal = window[chain[0]];

                for(var i = 1; i < chain.length; i++) {
                    chainVal = chainVal[chain[i]];
                }

                val = chainVal;
            }

            else {
                val = window[str];
            }

            return val;
        },

        getClassname: function(which) {
            return ns.prefix + ns.name + '-' + ns.classes[which];
        }
    };

    ux = $.fn.modal = $.fn.uxrmodal = $.uxrmodal = function(options) {
        var selector = this.selector;

        // direct call to dialog
        if(typeof this === 'function') {
            new Modal(null, options, null);
            return;
        }

        return this.each(function() {
            if($.data(this, ns.data)) {
                return;
            }

            // Bind the plugin and attach the instance to data
            $.data(this, ns.data, new Modal(this, options, selector));
        });
    };

    ux.resize = function() {
        var activeInstance = openedInstances[openedInstances.lastInstance];

        if(modal.hasInstances()) {
            activeInstance.resize();
        }
    };

    ux.close = function() {
        var activeInstance = openedInstances[openedInstances.lastInstance];

        if(modal.hasInstances()) {
            activeInstance.close();
        }
    };

    ux.version = '1.2.1';

    ux.settings = defaults;
}));<commit_msg>Modal content will removed<commit_after>/**
 * UX Rocket Modal
 * jQuery based modal
 * @author Bilal Cinarli
 */

(function(factory) {
    'use strict';
    if(typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if(typeof exports === 'object' && typeof require === 'function') {
        // Browserify
        factory(jQuery);
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {
    var ux,
        rocketName = 'uxrModal',
        instance = 1,

        overlay = '

',
        content = '
' +
                  '

' +
                  '

' +
                  '    ' +
                  '
',
        openedInstances = {},

        defaults = {
            className    : '',
            href         : '',
            width        : '',
            height       : '',
            maxWidth     : '',
            maxHeight    : '',
            appendTo     : 'body',
            allowMultiple: false,
            blockUI      : true,
            overlayClose : true,
            close        : true,
            iframe       : false,
            html         : false,
            fixed        : false,

            onReady : false,
            onOpen  : false,
            onStart : false,
            onLoad  : false,
            onClose : false,
            onRemove: false
        },

        events = {
            click     : 'click.' + rocketName,
            touchstart: 'touchstart.' + rocketName,
            toucemove : 'touchmove.' + rocketName,
            touchend  : 'touchend.' + rocketName,
            mousedown : 'mousedown.' + rocketName,
            mousemove : 'mousemove.' + rocketName,
            mouseup   : 'mouseup.' + rocketName,
            open      : 'uxropen.' + rocketName,
            start     : 'uxrstart.' + rocketName,
            load      : 'uxrload.' + rocketName,
            close     : 'uxrclose.' + rocketName,
            ready     : 'uxrready.' + rocketName,
            resize    : 'uxrresize.' + rocketName,
            remove    : 'uxrremove.' + rocketName
        },

        ns = {
            prefix : 'uxr-',
            rocket : 'uxRocket',
            data   : rocketName,
            name   : 'modal',
            classes: {
                ready    : 'ready',
                overlay  : 'overlay',
                container: 'container',
                drag     : 'drag',
                content  : 'content',
                loading  : 'loading',
                close    : 'close',
                hide     : 'hide'
            }
        };

    var Modal = function(el, options, selector) {
        this._name = rocketName;
        this._defaults = defaults;
        this._instance = instance;

        this.el = el;
        this.$el = $(el);
        this.$content = null;
        this.options = $.extend(true, {}, defaults, options, this.$el.data());
        this.href = this.options.href || this.$el.attr('href') || false;
        this.selector = selector;

        instance++;

        this.init();

    };

    Modal.prototype.init = function() {
        var uxrocket = this.$el.data(ns.rocket) || {};

        // register plugin data to rocket
        uxrocket[ns.data] = {hasWrapper: false, ready: utils.getClassname('ready'), selector: this.selector, options: this.options};
        this.$el.data(ns.rocket, uxrocket);

        this.bindUIActions();

        this.$el.addClass(utils.getClassname('ready'));

        // direct call
        if(this.el === null) {
            this.bindGenericActions();
            this.prepare();
        }

        this.emitEvent('ready');
    };

    Modal.prototype.bindUIActions = function() {
        var _this = this;

        if(this.el) {
            this.$el.on(events.click, function(e) {
                e.preventDefault();

                // do not open same modal more then once
                if(typeof openedInstances[_this._instance] !== 'undefined') {
                    return;
                }

                _this.emitEvent('start');
                _this.prepare();
            })
                .on(events.ready, function() {
                    _this.onReady();
                })
                .on(events.open, function() {
                    _this.onOpen();
                })
                .on(events.start, function() {
                    _this.onStart();
                })
                .on(events.load, function() {
                    _this.onLoad();
                })
                .on(events.close, function() {
                    _this.onClose();
                })
                .on(events.remove, function() {
                    _this.onRemove();
                });
        }

        $('body')
            .on(events.click + ' ' + events.touchstart, '#uxr-modal-overlay', function() {
                modal.closeFromOverlay();
            })
            .on(events.click + ' ' + events.touchstart, '#uxr-modal-instance-' + _this._instance + ' .' + utils.getClassname('close'), function(e) {
                e.preventDefault();
                _this.close();
            })
            .on(events.mousedown + ' ' + events.touchstart, '#uxr-modal-instance-' + _this._instance + ' .' + utils.getClassname('drag'), function(e) {
                e.preventDefault();
                modal.move.start(_this, e);
            });

        $(document)
            .on(events.mousemove + ' ' + events.touchmove, function(e) {
                modal.move.drag(e);
            }).on(events.mouseup + ' ' + events.touchend, function() {
                modal.move.stop();
            });
    };

    Modal.prototype.bindGenericActions = function() {
        var _this = this;

        $('body')
            .on(events.open, function() {
                _this.onOpen();
            })
            .on(events.start, function() {
                _this.onStart();
            })
            .on(events.load, function() {
                _this.onLoad();
            })
            .on(events.close, function() {
                _this.onClose();
            })
            .on(events.remove, function() {
                _this.onRemove();
            });
    };

    Modal.prototype.prepare = function() {
        var css = {},
            $overlay = $('#uxr-modal-overlay'),
            _content = content.replace('{{id}}', 'uxr-modal-instance-' + this._instance),
            _appendTo = 'body';

        if(this.options.appendTo !== 'body') {
            _appendTo = ($(utils.escapeSelector(this.options.appendTo)).length === 0) ? 'body' : this.options.appendTo;
        }

        if(!this.options.allowMultiple && modal.isOnlyInstance()) {
            modal.closeFromOverlay();
        }

        if(this.options.blockUI) {
            if($overlay.length === 0) {
                $(utils.escapeSelector(_appendTo)).append(overlay);
            }
            else {
                $overlay.removeClass(utils.getClassname('hide'));
            }
        }

        if(this.$content === null) {
            this.$content = $(_content);

            if(this.options.fixed) {
                css.position = 'fixed';
            }

            if(this.options.maxWidth !== '') {
                css.maxWidth = this.options.maxWidth;
            }

            if(this.options.maxHeight !== '') {
                css.maxHeight = this.options.maxHeight;
            }

            if(Object.keys(css).length > 0) {
                this.$content.css(css);
            }

            $(utils.escapeSelector(_appendTo)).append(this.$content);
        }

        else {
            this.$content.removeClass(utils.getClassname('hide'));
        }

        this.$content.addClass(utils.getClassname('loading')).find('.' + utils.getClassname('content')).html('');

        modal.registerInstance(this);

        this.open();
    };

    Modal.prototype.open = function() {
        this.emitEvent('open');
        this.get();
    };

    Modal.prototype.get = function() {
        var _this = this,
            iframe;

        if(this.options.iframe) {
            this.options.width = this.options.width || 800;
            this.options.height = this.options.height || 600;

            iframe = '';
            this.html = iframe;
            _this.emitEvent('load');
        }

        else if(!this.isInpage()) {
            $.get(this.href).done(function(data) {
                _this.html = data;
                setTimeout(function() {
                    _this.emitEvent('load');
                });
            });
        }
        else if(this.href !== false) {
            var $target = $(utils.escapeSelector(this.href)),
                $ph = $('
').addClass('.' + utils.getClassname('hide')).insertBefore($target);

            this.$el.one(events.close, function() {
                $ph.replaceWith($target);
            });

            this.html = $target;

            _this.emitEvent('load');
        }
        else {
            this.html = this.options.html;
            _this.emitEvent('load');
        }
    };

    Modal.prototype.load = function() {
        var loadedContent = this.$content.find('.' + utils.getClassname('content'));

        loadedContent.html();

        this.$content.removeClass(utils.getClassname('loading'));

        if(this.options.close) {
            this.$content
                .find('.' + utils.getClassname('close'))
                .removeClass(utils.getClassname('hide'));
        }

        if(this.options.allowMultiple) {
            this.$content
                .find('.' + utils.getClassname('drag'))
                .removeClass(utils.getClassname('hide'));
        }

        loadedContent.append(this.html);

        this.resize();
    };

    Modal.prototype.close = function() {
        if(modal.isOnlyInstance()) {
            $('#uxr-modal-overlay').addClass(utils.getClassname('hide'));
        }

        this.$content
            .addClass(utils.getClassname('hide'))
            .find('.' + utils.getClassname('close'))
            .addClass(utils.getClassname('hide'));

        modal.close(this);

        this.emitEvent('close');
    };

    Modal.prototype.resize = function() {
        var css = {},
            loadedContent = this.$content.find('.' + utils.getClassname('content'));

        if(this.options.width !== '') {
            css.width = this.options.width;
        }

        if(this.options.height !== '') {
            css.height = this.options.height;
        }

        loadedContent.css(css);

        if(this.$content.height() < loadedContent.height()) {
            this.$content.css('overflowY', 'scroll');
        }
    };

    Modal.prototype.isInpage = function() {
        if(typeof this.inpage === 'undefined') {
            this.inpage = false;

            if(this.href === false) {
                this.inpage = true;
            }

            else if(this.href.charAt(0) === '#') {
                this.inpage = true;
            }

            else {
                var loc = window.location.href.replace(location.hash, '').replace(location.protocol, ''),
                    test = this.href.replace(location.hash, '').replace(location.protocol, '');

                if(loc === test) {
                    this.inpage = true;
                }
            }
        }

        return this.inpage;
    };

    Modal.prototype.onReady = function() {
        utils.callback(this.options.onReady);
    };

    Modal.prototype.onOpen = function() {
        utils.callback(this.options.onOpen);
    };

    Modal.prototype.onStart = function() {
        utils.callback(this.options.onStart);
    };

    Modal.prototype.onLoad = function() {
        this.load();

        utils.callback(this.options.onLoad);
    };

    Modal.prototype.onClose = function() {
        utils.callback(this.options.onClose);
    };

    Modal.prototype.onRemove = function() {
        utils.callback(this.options.onRemove);
    };

    Modal.prototype.emitEvent = function(which) {
        var $el = (this.el !== null) ? this.$el : $('body');

        $el.trigger(events[which]);
    };

    Modal.prototype.getOpenedInstances = function() {
        return openedInstances;
    };

    var modal = {
        registerInstance: function(instance) {
            openedInstances[instance._instance] = instance;
            instance.previousInstance = openedInstances.lastInstance || instance._instance;
            openedInstances.lastInstance = instance._instance;
        },
        close           : function(instance) {
            openedInstances.lastInstance = instance.previousInstance;
            delete openedInstances[instance._instance];
        },
        closeFromOverlay: function() {
            var activeInstance = openedInstances[openedInstances.lastInstance];

            if(this.hasInstances()) {
                if(!activeInstance.options.overlayClose) {
                    return;
                }

                activeInstance.close();
            }
        },
        hasInstances    : function() {
            return Object.keys(openedInstances).length > 1;
        },
        isOnlyInstance  : function() {
            return (Object.keys(openedInstances).length - 1) === 1;
        },
        move            : {
            pos     : {},
            selected: false,
            previous: false,
            start   : function(instance, e) {
                var pointer = this.pointer(e);

                this.selected = instance;
                this.selected.$content.css('zIndex', 10001);
                this.pos.top = pointer.y - this.selected.$content[0].offsetTop;
                this.pos.left = pointer.x - this.selected.$content[0].offsetLeft;

                if(!this.previous) {
                    this.previous = instance;
                }
                else {
                    this.previous.$content.css('zIndex', 10000);
                }
            },
            drag    : function(e) {
                var pointer = this.pointer(e);

                if(this.selected) {
                    this.selected.$content[0].style.top = pointer.y + 'px';
                    this.selected.$content[0].style.left = pointer.x + 'px';
                }
            },
            stop    : function() {
                if(this.selected) {
                    this.previous = this.selected;
                    this.selected = false;
                }
            },
            pointer : function(e) {
                var out = {x: 0, y: 0};
                if(e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
                    var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                    out.x = touch.pageX;
                    out.y = touch.pageY;
                } else if(e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
                    out.x = e.pageX;
                    out.y = e.pageY;
                }
                return out;
            }
        }
    };

    var utils = {
        callback: function(fn) {
            // if callback string is function call it directly
            if(typeof fn === 'function') {
                fn.apply(this);
            }

            // if callback defined via data-attribute, call it via new Function
            else {
                if(fn !== false) {
                    var func = new Function('return ' + fn);
                    func();
                }
            }
        },

        escapeSelector: function(selector) {
            var is_ID = selector.charAt(0) === '#',
                re = /([ !"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g;

            return is_ID ? '#' + selector.substring(1).replace(re, '\\$1') : selector;
        },

        getStringVariable: function(str) {
            var val;
            // check if it is chained
            if(str.indexOf('.') > -1) {
                var chain = str.split('.'),
                    chainVal = window[chain[0]];

                for(var i = 1; i < chain.length; i++) {
                    chainVal = chainVal[chain[i]];
                }

                val = chainVal;
            }

            else {
                val = window[str];
            }

            return val;
        },

        getClassname: function(which) {
            return ns.prefix + ns.name + '-' + ns.classes[which];
        }
    };

    ux = $.fn.modal = $.fn.uxrmodal = $.uxrmodal = function(options) {
        var selector = this.selector;

        // direct call to dialog
        if(typeof this === 'function') {
            new Modal(null, options, null);
            return;
        }

        return this.each(function() {
            if($.data(this, ns.data)) {
                return;
            }

            // Bind the plugin and attach the instance to data
            $.data(this, ns.data, new Modal(this, options, selector));
        });
    };

    ux.resize = function() {
        var activeInstance = openedInstances[openedInstances.lastInstance];

        if(modal.hasInstances()) {
            activeInstance.resize();
        }
    };

    ux.close = function() {
        var activeInstance = openedInstances[openedInstances.lastInstance];

        if(modal.hasInstances()) {
            activeInstance.close();
        }
    };

    ux.version = '1.2.2';

    ux.settings = defaults;
}));<|endoftext|>