<commit_before>var fs = require('fs'),

    path = require('path');

var cwd = process.cwd(),
    flagWin = /[a-zA-Z]:/.test(cwd);

function getUserDir() {
    var regx = flagWin ? '/\w:\\Users\\\w+/' : /\/Users\/\w+/,
        match = cwd.match(/\/Users\/\w+/g);

    return match ? match[0] : '';
}

function log(){
    console.log("------------------servermock log----------------\n",
                    Array.prototype.join.call(arguments, '\n'));
}

function classof(o) {
    return Object.prototype.toString.call(o).slice(8,-1);
}

function extend(){
    var iterator = {
        stack: [],
        reset: function(){
            stack = [];
        },
        watch:function(co, cb){ // co对象或数组 这里不做额外判断
            if(this.stack.indexOf(co) > -1) return;
            this.stack.push(co), cb();
        }
    };

    function copy(to, from, deep){
        for(var i in from){
            var fi = from[i];
            if(!deep){
                if(fi !== undefined){
                    to[i] = fi;
                }
            }else{
                var classFI = classof(fi),
                    isArr = classFI === 'Array',
                    isObj = classFI === 'Object';
                if(isArr || isObj){
                    var ti = to[i],
                        tiC = classof(ti);

                    isArr ? tiC !== 'Array' && (ti = []) :
                            tiC !== 'Object' && (ti = {});

                    iterator.watch(fi, function(){
                        copy(ti, fi, deep);
                    })
                }else{
                    if(fi !== undefined){
                        to[i] = fi;
                    }
                }
            }
        }
    }

    var re, len = arguments.length, deep, i = 0;

    deep = arguments[i] === true ? (i++, true): false;
    re   = arguments[i++];

    for(i; i < len; i++){
        classof(arguments[i]) === 'Object' && copy(re, arguments[i], deep);
    }

    return re;
}

var MIME = {
    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml"
};

function simpleTemplate(str, data) {

    if (!str || !data) return '';

    var type = Object.prototype.toString.call(data),
        strRes = '',
        regex = /\{\{\s*(\w+)\s*\}\}/g;

    switch (type) {
        case '[object Array]':
            for (var i = 0, len = data.length; i < len; i++) {
                strRes += simpleTemplate(str, data[i]);
            }
            break;
        case '[object Object]':
            strRes = str.replace(regex, function ($0, $1) {
                return data[$1];
            });
            break;
        case '[object String]':
            strRes = str.replace(regex, data);
            break;
        default:
            strRes = '';
    }

    return strRes;
}

function readFile(filepath){
    return fs.existsSync(filepath) ? fs.readFileSync(filepath).toString() : "";
}

function renderPage(pagepath, data){
    pagepath = path.join(__dirname, pagepath);
    return simpleTemplate(readFile(pagepath), data)
}

function readJson(filepath){
    var json = '', content = '';
    if(fs.existsSync(filepath)){
        try{
            content = readFile(filepath).replace(/[^:]\/\/.*\n/g, '\n');
            json = JSON.parse(content);
            log("open json file: " + filepath, content);
        } catch(e){
            log("error: json file error:\n", filepath, e);
        }
    }
    return json;
}

function inArray(va, arr){
    return arr.indexOf(va) > -1;
}

module.exports = {
    log: log,
    extend: extend,
    MIME: MIME,
    inArray: inArray,
    readFile:readFile,
    readJson:readJson,
    getUserDir: getUserDir,
    renderPage: renderPage,
    simpleTemplate:simpleTemplate
}<commit_msg>fix copy<commit_after>var fs = require('fs'),

    path = require('path');

var cwd = process.cwd(),
    flagWin = /[a-zA-Z]:/.test(cwd);

function getUserDir() {
    var regx = flagWin ? '/\w:\\Users\\\w+/' : /\/Users\/\w+/,
        match = cwd.match(/\/Users\/\w+/g);

    return match ? match[0] : '';
}

function log(){
    console.log("------------------servermock log----------------\n",
                    Array.prototype.join.call(arguments, '\n'));
}

function classof(o) {
    return Object.prototype.toString.call(o).slice(8,-1);
}

function extend(){
    var iterator = {
        stack: [],
        reset: function(){
            stack = [];
        },
        watch:function(co, cb){ // co对象或数组 这里不做额外判断
            if(this.stack.indexOf(co) > -1) return;
            this.stack.push(co), cb();
        }
    };

    function copy(to, from, deep){
        for(var i in from){
            var fi = from[i];
            if(!deep){
                if(fi !== undefined){
                    to[i] = fi;
                }
            }else{
                var classFI = classof(fi),
                    isArr = classFI === 'Array',
                    isObj = classFI === 'Object';
                if(isArr || isObj){
                    var tiC = classof(to[i]);

                    isArr ? tiC !== 'Array' && (to[i] = []) :
                            tiC !== 'Object' && (to[i] = {});

                    iterator.watch(fi, function(){
                        copy(to[i], fi, deep);
                    })
                }else{
                    if(fi !== undefined){
                        to[i] = fi;
                    }
                }
            }
        }
    }

    var re, len = arguments.length, deep, i = 0;

    deep = arguments[i] === true ? (i++, true): false;
    re   = arguments[i++];

    for(i; i < len; i++){
        classof(arguments[i]) === 'Object' && copy(re, arguments[i], deep);
    }

    return re;
}

var MIME = {
    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml"
};

function simpleTemplate(str, data) {

    if (!str || !data) return '';

    var type = Object.prototype.toString.call(data),
        strRes = '',
        regex = /\{\{\s*(\w+)\s*\}\}/g;

    switch (type) {
        case '[object Array]':
            for (var i = 0, len = data.length; i < len; i++) {
                strRes += simpleTemplate(str, data[i]);
            }
            break;
        case '[object Object]':
            strRes = str.replace(regex, function ($0, $1) {
                return data[$1];
            });
            break;
        case '[object String]':
            strRes = str.replace(regex, data);
            break;
        default:
            strRes = '';
    }

    return strRes;
}

function readFile(filepath){
    return fs.existsSync(filepath) ? fs.readFileSync(filepath).toString() : "";
}

function renderPage(pagepath, data){
    pagepath = path.join(__dirname, pagepath);
    return simpleTemplate(readFile(pagepath), data)
}

function readJson(filepath){
    var json = '', content = '';
    if(fs.existsSync(filepath)){
        try{
            content = readFile(filepath).replace(/[^:]\/\/.*\n/g, '\n');
            json = JSON.parse(content);
            log("open json file: " + filepath, content);
        } catch(e){
            log("error: json file error:\n", filepath, e);
        }
    }
    return json;
}

function inArray(va, arr){
    return arr.indexOf(va) > -1;
}

module.exports = {
    log: log,
    extend: extend,
    MIME: MIME,
    inArray: inArray,
    readFile:readFile,
    readJson:readJson,
    getUserDir: getUserDir,
    renderPage: renderPage,
    simpleTemplate:simpleTemplate
}<|endoftext|>


<commit_before>const getOptions = require('./getOptions')
const app = require('express')()
const worker = require('ddv-worker')
const http = require('http')
const fs = require('fs')
const path = require('path')
const {
  Nuxt
} = require('nuxt')
const logger = require('./logger')
const nuxts = Object.create(null)
const templates = Object.create(null)
const hostToTemplateId = Object.create(null)
const vhostOptions = Object.create(null)

// 创建http服务
worker.server = http.createServer(app)
module.exports = worker
app.use(function (req, res, next) {
  return vhostRender.apply(this, arguments)
})
app.use(function (req, res, next) {
  return vhostRender.apply(this, arguments)
})

// 渲染中间件
function vhostRender (req, res, next) {
  var host = req.hostname || req.headers.host

  getTemplateIdByHost(host, req, res)
    .then(templateId => {
      return getNuxtRender(templateId, req, res).then(render => {
        render.apply(this, arguments)
      })
    })
    .catch(e => {
      if (vhostOptions.onError && typeof vhostOptions.onError === 'function') {
        return vhostOptions.onError(e, req, res)
      } else {
        return Promise.reject(e)
      }
    })
    .catch(e => {
      echoErrorByRes(e, req, res)
    })
}

function echoErrorByRes (e, req, res) {
  // 响应头
  res.writeHead(200, {
    'Content-Type': 'application/json; charset=utf8',
    'Access-Control-Allow-Origin': '*',
    'Accept-Language': 'zh-CN'
  })
  res.write('错误-:' + e.message)
  res.write('错误stack:' + e.stack)
  res.end('错误body:' + e.body)
}
// 获取编译器的方法
function getNuxtRender (templateId, req, res) {
  if (nuxts[templateId]) {
    return Promise.resolve(nuxts[templateId])
  } else {
    return createNuxtRender(templateId, req, res).then(nuxtRender => {
      nuxts[templateId] = nuxtRender
      return nuxts[templateId]
    })
  }
}
// function closeNuxtRender (templateId) {
//   return getNuxtRender(templateId)
//     .then(render => {
//       delete nuxts[templateId]
//       return render.close()
//     })
// }
// 创建编译器的方法
function createNuxtRender (templateId, req, res) {
  return getTemplateInfo(templateId, req, res)
    .then(info => {
      return getOptions(info.configFile)
        .then(options => {
          options.rootDir = info.rootDir || options.rootDir
          return options
        })
    })
    .then(options => {
      var arr = options.rootDir.split('/')
      var program = arr[arr.length - 1]
      var rootDir = path.resolve('.')
      var templatPath = path.resolve(vhostOptions.rootTemplateDir, program)
      var buildTemplateDir = vhostOptions.buildTemplateDir || path.resolve(rootDir, '.nuxt-dists')

      options.buildDir = path.resolve(buildTemplateDir, program)
      options.rootDir = vhostOptions.rootDir || rootDir
      options.srcDir = options.srcDir ? path.resolve(templatPath, options.srcDir) : templatPath

      let distDir = path.resolve(
        options.rootDir,
        options.buildDir || '.nuxt',
        'dist'
      )
      arr = void 0

      if (vhostOptions.processPool[program]) {
        program = void 0
        var e = new Error('Please wait patiently while the project is in progress.')
        e.errorId = 'WEBSITE_UPGRADE'

        return Promise.reject(e)
      }
      program = void 0

      return new Promise((resolve, reject) => {
        fs.stat(distDir, (err, stats) => {
          var isError = false
          if (err) {
            isError = true
          } else if (!stats.isDirectory()) {
            isError = true
          }

          if (isError) {
            if (
              vhostOptions.loadBuildFiles &&
              typeof vhostOptions.loadBuildFiles === 'function'
            ) {
              vhostOptions
                .loadBuildFiles(options.srcDir, vhostOptions, req, {
                  mode: 'production',
                  cwd: options.rootDir
                })
                .catch(e => {
                  e =
                    e ||
                    new Error(
                      'No build files found, please run `nuxt build` before launching `nuxt start`'
                    )
                  reject(e)
                })
            } else {
              reject(
                new Error(
                  'No build files found, please run `nuxt build` before launching `nuxt start`'
                )
              )
            }
          } else {
            resolve(options)
          }
        })
      })
    })
    .then(options => {
      let nuxt = new Nuxt(options)
      return nuxt.render
    })
}
// 获取模板信息
function getTemplateInfo (templateId, req, res) {
  if (templates[templateId]) {
    return Promise.resolve(templates[templateId])
  }
  return loadTemplateByIdRun(templateId, req, res).then(res => {
    templates[templateId] = res
    return templates[templateId]
  })
}

function getTemplateIdByHost (host, req, res) {
  if (hostToTemplateId[host]) {
    return Promise.resolve(hostToTemplateId[host])
  }
  return loadTemplateIdByHost(host, req, res).then(templateId => {
    hostToTemplateId[host] = templateId
    return hostToTemplateId[host]
  })
}

function loadTemplateIdByHost (host, req, res) {
  if (
    vhostOptions.loadTemplateIdByHost &&
    typeof vhostOptions.loadTemplateIdByHost === 'function'
  ) {
    return vhostOptions.loadTemplateIdByHost(host, req, res)
  } else {
    return Promise.reject(
      new Error('vhostOptions not find loadTemplateIdByHost')
    )
  }
}

function loadTemplateByIdRun (templateId, req, res) {
  if (
    vhostOptions.loadTemplateById &&
    typeof vhostOptions.loadTemplateById === 'function'
  ) {
    return vhostOptions.loadTemplateById(templateId, vhostOptions, req, res)
  } else {
    return Promise.reject(new Error('vhostOptions not find loadTemplateById'))
  }
}

worker.serverStart = function serverStart (config) {
  config.getConfig().then(options => {
    Object.keys(vhostOptions).forEach(key => {
      if (options[key]) {
        vhostOptions[key] = options[key]
      } else {
        delete vhostOptions[key]
      }
    })
    Object.keys(options).forEach(key => {
      if (options[key]) {
        vhostOptions[key] = options[key]
      }
    })
    // 监听服务 - Listen the server
    worker
      .updateServerConf({
        defaultListen: options.defaultListen,
        listen: options.listen,
        cpuLen: options.cpuLen,
        notMasterListen: {
          port: config.argv.port || 3000,
          hostname: config.argv.hostname || void 0
        }
      })
      .then(
        () => {
          logger.log('监听配置参数 更新成功')
        },
        e => {
          logger.error('监听配置参数 更新失败')
          logger.error(e)
        }
      )
  })
}
<commit_msg>format<commit_after>const getOptions = require('./getOptions')
const app = require('express')()
const worker = require('ddv-worker')
const http = require('http')
const fs = require('fs')
const path = require('path')
const {
  Nuxt
} = require('nuxt')
const logger = require('./logger')
const nuxts = Object.create(null)
const templates = Object.create(null)
const hostToTemplateId = Object.create(null)
const vhostOptions = Object.create(null)

// 创建http服务
worker.server = http.createServer(app)
module.exports = worker
app.use(function (req, res, next) {
  return vhostRender.apply(this, arguments)
})
app.use(function (req, res, next) {
  return vhostRender.apply(this, arguments)
})

// 渲染中间件
function vhostRender (req, res, next) {
  var host = req.hostname || req.headers.host

  getTemplateIdByHost(host, req, res)
    .then(templateId => {
      return getNuxtRender(templateId, req, res).then(render => {
        render.apply(this, arguments)
      })
    })
    .catch(e => {
      if (vhostOptions.onError && typeof vhostOptions.onError === 'function') {
        return vhostOptions.onError(e, req, res)
      } else {
        return Promise.reject(e)
      }
    })
    .catch(e => {
      echoErrorByRes(e, req, res)
    })
}

function echoErrorByRes (e, req, res) {
  // 响应头
  res.writeHead(200, {
    'Content-Type': 'application/json; charset=utf8',
    'Access-Control-Allow-Origin': '*',
    'Accept-Language': 'zh-CN'
  })
  res.write('错误-:' + e.message)
  res.write('错误stack:' + e.stack)
  res.end('错误body:' + e.body)
}
// 获取编译器的方法
function getNuxtRender (templateId, req, res) {
  if (nuxts[templateId]) {
    return Promise.resolve(nuxts[templateId])
  } else {
    return createNuxtRender(templateId, req, res).then(nuxtRender => {
      nuxts[templateId] = nuxtRender
      return nuxts[templateId]
    })
  }
}
// function closeNuxtRender (templateId) {
//   return getNuxtRender(templateId)
//     .then(render => {
//       delete nuxts[templateId]
//       return render.close()
//     })
// }
// 创建编译器的方法
function createNuxtRender (templateId, req, res) {
  return getTemplateInfo(templateId, req, res)
    .then(info => {
      return getOptions(info.configFile)
        .then(options => {
          options.rootDir = info.rootDir || options.rootDir
          return options
        })
    })
    .then(options => {
      var arr = options.rootDir.split('/')
      var program = arr[arr.length - 1]
      var rootDir = path.resolve('.')
      var templatPath = path.resolve(vhostOptions.rootTemplateDir, program)
      var buildTemplateDir = vhostOptions.buildTemplateDir || path.resolve(rootDir, '.nuxt-dists')

      options.buildDir = path.resolve(buildTemplateDir, program)
      options.rootDir = vhostOptions.rootDir || rootDir
      options.srcDir = options.srcDir ? path.resolve(templatPath, options.srcDir) : templatPath

      let distDir = path.resolve(
        options.rootDir,
        options.buildDir || '.nuxt',
        'dist'
      )
      arr = void 0

      if (vhostOptions.processPool[program]) {
        program = void 0
        var e = new Error('Please wait patiently while the project is in progress.')
        e.errorId = 'WEBSITE_UPGRADE'

        return Promise.reject(e)
      }
      program = void 0

      return new Promise((resolve, reject) => {
        fs.stat(distDir, (err, stats) => {
          var isError = false
          if (err) {
            isError = true
          } else if (!stats.isDirectory()) {
            isError = true
          }

          if (isError) {
            if (
              vhostOptions.loadBuildFiles &&
              typeof vhostOptions.loadBuildFiles === 'function'
            ) {
              vhostOptions
                .loadBuildFiles(options.srcDir, vhostOptions, req, {
                  mode: 'production',
                  cwd: options.rootDir
                })
                .catch(e => {
                  e =
                    e ||
                    new Error(
                      'No build files found, please run `nuxt build` before launching `nuxt start`'
                    )
                  reject(e)
                })
            } else {
              reject(
                new Error(
                  'No build files found, please run `nuxt build` before launching `nuxt start`'
                )
              )
            }
          } else {
            resolve(options)
          }
        })
      })
    })
    .then(options => {
      let nuxt = new Nuxt(options)
      return nuxt.render
    })
}
// 获取模板信息
function getTemplateInfo (templateId, req, res) {
  if (templates[templateId]) {
    return Promise.resolve(templates[templateId])
  }
  return loadTemplateByIdRun(templateId, req, res).then(res => {
    templates[templateId] = res
    return templates[templateId]
  })
}

function getTemplateIdByHost (host, req, res) {
  if (hostToTemplateId[host]) {
    return Promise.resolve(hostToTemplateId[host])
  }
  return loadTemplateIdByHost(host, req, res).then(templateId => {
    hostToTemplateId[host] = templateId
    return hostToTemplateId[host]
  })
}

function loadTemplateIdByHost (host, req, res) {
  if (
    vhostOptions.loadTemplateIdByHost &&
    typeof vhostOptions.loadTemplateIdByHost === 'function'
  ) {
    return vhostOptions.loadTemplateIdByHost(host, req, res)
  } else {
    return Promise.reject(
      new Error('vhostOptions not find loadTemplateIdByHost')
    )
  }
}

function loadTemplateByIdRun (templateId, req, res) {
  if (
    vhostOptions.loadTemplateById &&
    typeof vhostOptions.loadTemplateById === 'function'
  ) {
    return vhostOptions.loadTemplateById(templateId, vhostOptions, req, res)
  } else {
    return Promise.reject(new Error('vhostOptions not find loadTemplateById'))
  }
}

worker.serverStart = function serverStart (config) {
  config.getConfig()
    .then(options => {
      Object.keys(vhostOptions).forEach(key => {
        if (options[key]) {
          vhostOptions[key] = options[key]
        } else {
          delete vhostOptions[key]
        }
      })
      Object.keys(options).forEach(key => {
        if (options[key]) {
          vhostOptions[key] = options[key]
        }
      })
      // 监听服务 - Listen the server
      worker
        .updateServerConf({
          defaultListen: options.defaultListen,
          listen: options.listen,
          cpuLen: options.cpuLen,
          notMasterListen: {
            port: config.argv.port || 3000,
            hostname: config.argv.hostname || void 0
          }
        })
        .then(
          () => {
            logger.log('监听配置参数 更新成功')
          },
          e => {
            logger.error('监听配置参数 更新失败')
            logger.error(e)
          }
        )
    })
}
<|endoftext|>


<commit_before>"use strict"

module.exports = vectorizeText
module.exports.processPixels = processPixels

var surfaceNets = require('surface-nets')
var ndarray = require('ndarray')
var simplify = require('simplify-planar-graph')
var cleanPSLG = require('clean-pslg')
var cdt2d = require('cdt2d')
var toPolygonCrappy = require('planar-graph-to-polyline')

var TAG_bold = "b"
var CHR_bold = 'b'

var TAG_italic = "i"
var CHR_italic = 'i'

var TAG_super = "sup"
var CHR_super = 'P'

var TAG_sub = "sub"
var CHR_sub = 'B'

function parseTag(tag, TAG_CHR, str, map) {

  var opnTag =  "<"  + tag + ">"
  var clsTag =  "</" + tag + ">"

  var nOPN = opnTag.length
  var nCLS = clsTag.length

  var nStr = str.length

  var a = 0
  var b = -nCLS
  while (a > -1) {
    a = str.indexOf(opnTag, b + nCLS)
    if(a === -1) break

    b = str.indexOf(clsTag, a + nOPN)
    if(b === -1) break

    if(b <= a) break

    for(var i = a; i < b + nCLS; ++i){
      if((i < a + nOPN) || (i >= b)) {
        map[i] = null
      } else {
        if(map[i] !== null) {
          if(map[i].indexOf(TAG_CHR) === -1) map[i] += TAG_CHR
        }
      }
    }
  }

  return map
}

function transformPositions(positions, options, size) {
  var align = options.textAlign || "start"
  var baseline = options.textBaseline || "alphabetic"

  var lo = [1<<30, 1<<30]
  var hi = [0,0]
  var n = positions.length
  for(var i=0; i<n; ++i) {
    var p = positions[i]
    for(var j=0; j<2; ++j) {
      lo[j] = Math.min(lo[j], p[j])|0
      hi[j] = Math.max(hi[j], p[j])|0
    }
  }

  var xShift = 0
  switch(align) {
    case "center":
      xShift = -0.5 * (lo[0] + hi[0])
    break

    case "right":
    case "end":
      xShift = -hi[0]
    break

    case "left":
    case "start":
      xShift = -lo[0]
    break

    default:
      throw new Error("vectorize-text: Unrecognized textAlign: '" + align + "'")
  }

  var yShift = 0
  switch(baseline) {
    case "hanging":
    case "top":
      yShift = -lo[1]
    break

    case "middle":
      yShift = -0.5 * (lo[1] + hi[1])
    break

    case "alphabetic":
    case "ideographic":
      yShift = -3 * size
    break

    case "bottom":
      yShift = -hi[1]
    break

    default:
      throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'")
  }

  var scale = 1.0 / size
  if("lineHeight" in options) {
    scale *= +options.lineHeight
  } else if("width" in options) {
    scale = options.width / (hi[0] - lo[0])
  } else if("height" in options) {
    scale = options.height / (hi[1] - lo[1])
  }

  return positions.map(function(p) {
    return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ]
  })
}

function getPixels(canvas, context, raw_str, fontSize, lineSpacing) {

  raw_str = raw_str.replace(/\<br\>/g, '\n')

  var activeStyle = ""
  var map = []
  for (j = 0; j < raw_str.length; ++j) {
    map[j] = activeStyle
  }
  map = parseTag(TAG_bold,
                 CHR_bold, raw_str, map)
  map = parseTag(TAG_italic,
                 CHR_italic, raw_str, map)
  map = parseTag(TAG_super,
                 CHR_super, raw_str, map)
  map = parseTag(TAG_sub,
                 CHR_sub, raw_str, map)

  var styleOptions = []
  var plainText = ""
  for(j = 0; j < raw_str.length; ++j) {
    if(map[j] !== null) {
      plainText += raw_str[j]
      styleOptions.push(map[j])
    }
  }

console.log("raw_str=", raw_str);
console.log("map=", map);
console.log("allText=", plainText);
console.log("styleOptions=", styleOptions);
console.log("raw_str.length=", raw_str.length);
console.log("map.length=", map.length);
console.log("allText.length=", plainText.length);
console.log("styleOptions.length=", styleOptions.length);

  var allText = plainText.split('\n')

  var numberOfLines = allText.length
  var lineHeight = Math.round(lineSpacing * fontSize)
  var offsetX = fontSize
  var offsetY = fontSize * 2
  var maxWidth = 0
  var minHeight = numberOfLines * lineHeight + offsetY

  if(canvas.height < minHeight) {
    canvas.height = minHeight
  }

  context.fillStyle = "#000"
  context.fillRect(0, 0, canvas.width, canvas.height)

  context.fillStyle = "#fff"
  var i, j, xPos, yPos, zPos
  var nDone = 0

  for(i = 0; i < numberOfLines; ++i) {

    var txt = allText[i]
    xPos = 0
    yPos = i * lineHeight
    zPos = fontSize

    var buffer = ""
    function writeBuffer() {
      if(buffer !== "") {
        var delta = context.measureText(buffer).width

        context.fillText(buffer, offsetX + xPos, offsetY + yPos)
        xPos += delta
      }
    }

    function changeStyle(oldStyle, newStyle) {

      function getTextFontSize() {
        return "" + Math.round(zPos) + "px ";
      }

      var ctxFont = "" + context.font;

      var wasSub = (oldStyle.indexOf(CHR_sub) > -1)
      var is_Sub = (newStyle.indexOf(CHR_sub) > -1)

      if(!wasSub && is_Sub) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos /= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      if(wasSub && !is_Sub) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }

      var wasSuper = (oldStyle.indexOf(CHR_super) > -1)
      var is_Super = (newStyle.indexOf(CHR_super) > -1)

      if(!wasSuper && is_Super) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos /= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      if(wasSuper && !is_Super) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }

      var wasBold = (oldStyle.indexOf(CHR_bold) > -1)
      var is_Bold = (newStyle.indexOf(CHR_bold) > -1)

      if(!wasBold && is_Bold) {
        if(wasItalic) {
          ctxFont = ctxFont.replace("italic ", "italic bold ")
        } else {
          ctxFont = "bold " + ctxFont
        }
      }
      if(wasBold && !is_Bold) {
        ctxFont = ctxFont.replace("bold ", '')
      }

      var wasItalic = (oldStyle.indexOf(CHR_italic) > -1)
      var is_Italic = (newStyle.indexOf(CHR_italic) > -1)

      if(!wasItalic && is_Italic) {
        ctxFont = "italic " + ctxFont
      }
      if(wasItalic && !is_Italic) {
        ctxFont = ctxFont.replace("italic ", '')
      }

      context.font = ctxFont
    }

    for(j = 0; j < txt.length; ++j) {
      var restyle = false
      var newStyle
      if(activeStyle === styleOptions[j + nDone]) {
        buffer += txt[j]

        if(j === txt.length - 1) {
          if(j + nDone + 2 < styleOptions.length) {
            if(activeStyle !== styleOptions[j + nDone + 2]) {
              restyle = true
              newStyle = styleOptions[j + nDone + 2]
            }
          }
        }
      } else {
        writeBuffer()
        buffer = txt[j]
        restyle = true
        newStyle = styleOptions[j + nDone]
      }

      if(restyle) {
        changeStyle(activeStyle, newStyle)
        activeStyle = newStyle
      }
    }
    writeBuffer()

    nDone += txt.length + 1 // added one for enter

    var width = Math.round(xPos + 2 * offsetX) | 0
    if(maxWidth < width) maxWidth = width
  }

  //Cut pixels from image
  var xCut = maxWidth
  var yCut = offsetY + lineHeight * numberOfLines
  var pixels = ndarray(context.getImageData(0, 0, xCut, yCut).data, [yCut, xCut, 4])
  return pixels.pick(-1, -1, 0).transpose(1, 0)
}

function getContour(pixels, doSimplify) {
  var contour = surfaceNets(pixels, 128)
  if(doSimplify) {
    return simplify(contour.cells, contour.positions, 0.25)
  }
  return {
    edges: contour.cells,
    positions: contour.positions
  }
}

function processPixelsImpl(pixels, options, size, simplify) {
  //Extract contour
  var contour = getContour(pixels, simplify)

  //Apply warp to positions
  var positions = transformPositions(contour.positions, options, size)
  var edges     = contour.edges
  var flip = "ccw" === options.orientation

  //Clean up the PSLG, resolve self intersections, etc.
  cleanPSLG(positions, edges)

  //If triangulate flag passed, triangulate the result
  if(options.polygons || options.polygon || options.polyline) {
    var result = toPolygonCrappy(edges, positions)
    var nresult = new Array(result.length)
    for(var i=0; i<result.length; ++i) {
      var loops = result[i]
      var nloops = new Array(loops.length)
      for(var j=0; j<loops.length; ++j) {
        var loop = loops[j]
        var nloop = new Array(loop.length)
        for(var k=0; k<loop.length; ++k) {
          nloop[k] = positions[loop[k]].slice()
        }
        if(flip) {
          nloop.reverse()
        }
        nloops[j] = nloop
      }
      nresult[i] = nloops
    }
    return nresult
  } else if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: cdt2d(positions, edges, {
        delaunay: false,
        exterior: false,
        interior: true
      }),
      positions: positions
    }
  } else {
    return {
      edges:     edges,
      positions: positions
    }
  }
}

function processPixels(pixels, options, size) {
  try {
    return processPixelsImpl(pixels, options, size, true)
  } catch(e) {}
  try {
    return processPixelsImpl(pixels, options, size, false)
  } catch(e) {}
  if(options.polygons || options.polyline || options.polygon) {
    return []
  }
  if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: [],
      positions: []
    }
  }
  return {
    edges: [],
    positions: []
  }
}

function vectorizeText(str, canvas, context, options) {
  var size = options.size || 64
  var lineSpacing = options.lineSpacing || 1.25

  context.font = [
    options.fontStyle,
    options.fontVariant,
    options.fontWeight,
    size + "px",
    options.font
  ].filter(function(d) {return d}).join(" ")
  context.textAlign = "start"
  context.textBaseline = "alphabetic"
  context.direction = "ltr"

  var pixels = getPixels(canvas, context, str, size, lineSpacing)

  return processPixels(pixels, options, size)
}
<commit_msg>italic bold and sub is now working well<commit_after>"use strict"

module.exports = vectorizeText
module.exports.processPixels = processPixels

var surfaceNets = require('surface-nets')
var ndarray = require('ndarray')
var simplify = require('simplify-planar-graph')
var cleanPSLG = require('clean-pslg')
var cdt2d = require('cdt2d')
var toPolygonCrappy = require('planar-graph-to-polyline')

var TAG_bold = "b"
var CHR_bold = 'b'

var TAG_italic = "i"
var CHR_italic = 'i'

var TAG_super = "sup"
var CHR_super = 'P'

var TAG_sub = "sub"
var CHR_sub = 'B'

function parseTag(tag, TAG_CHR, str, map) {

  var opnTag =  "<"  + tag + ">"
  var clsTag =  "</" + tag + ">"

  var nOPN = opnTag.length
  var nCLS = clsTag.length

  var nStr = str.length

  var a = 0
  var b = -nCLS
  while (a > -1) {
    a = str.indexOf(opnTag, b + nCLS)
    if(a === -1) break

    b = str.indexOf(clsTag, a + nOPN)
    if(b === -1) break

    if(b <= a) break

    for(var i = a; i < b + nCLS; ++i){
      if((i < a + nOPN) || (i >= b)) {
        map[i] = null
      } else {
        if(map[i] !== null) {
          if(map[i].indexOf(TAG_CHR) === -1) map[i] += TAG_CHR
        }
      }
    }
  }

  return map
}

function transformPositions(positions, options, size) {
  var align = options.textAlign || "start"
  var baseline = options.textBaseline || "alphabetic"

  var lo = [1<<30, 1<<30]
  var hi = [0,0]
  var n = positions.length
  for(var i=0; i<n; ++i) {
    var p = positions[i]
    for(var j=0; j<2; ++j) {
      lo[j] = Math.min(lo[j], p[j])|0
      hi[j] = Math.max(hi[j], p[j])|0
    }
  }

  var xShift = 0
  switch(align) {
    case "center":
      xShift = -0.5 * (lo[0] + hi[0])
    break

    case "right":
    case "end":
      xShift = -hi[0]
    break

    case "left":
    case "start":
      xShift = -lo[0]
    break

    default:
      throw new Error("vectorize-text: Unrecognized textAlign: '" + align + "'")
  }

  var yShift = 0
  switch(baseline) {
    case "hanging":
    case "top":
      yShift = -lo[1]
    break

    case "middle":
      yShift = -0.5 * (lo[1] + hi[1])
    break

    case "alphabetic":
    case "ideographic":
      yShift = -3 * size
    break

    case "bottom":
      yShift = -hi[1]
    break

    default:
      throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'")
  }

  var scale = 1.0 / size
  if("lineHeight" in options) {
    scale *= +options.lineHeight
  } else if("width" in options) {
    scale = options.width / (hi[0] - lo[0])
  } else if("height" in options) {
    scale = options.height / (hi[1] - lo[1])
  }

  return positions.map(function(p) {
    return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ]
  })
}

function getPixels(canvas, context, raw_str, fontSize, lineSpacing) {

  raw_str = raw_str.replace(/\<br\>/g, '\n')

  var activeStyle = ""
  var map = []
  for (j = 0; j < raw_str.length; ++j) {
    map[j] = activeStyle
  }
  map = parseTag(TAG_bold,
                 CHR_bold, raw_str, map)
  map = parseTag(TAG_italic,
                 CHR_italic, raw_str, map)
  map = parseTag(TAG_super,
                 CHR_super, raw_str, map)
  map = parseTag(TAG_sub,
                 CHR_sub, raw_str, map)

  var allStyles = []
  var plainText = ""
  for(j = 0; j < raw_str.length; ++j) {
    if(map[j] !== null) {
      plainText += raw_str[j]
      allStyles.push(map[j])
    }
  }

  var allTexts = plainText.split('\n')

  var numberOfLines = allTexts.length
  var lineHeight = Math.round(lineSpacing * fontSize)
  var offsetX = fontSize
  var offsetY = fontSize * 2
  var maxWidth = 0
  var minHeight = numberOfLines * lineHeight + offsetY

  if(canvas.height < minHeight) {
    canvas.height = minHeight
  }

  context.fillStyle = "#000"
  context.fillRect(0, 0, canvas.width, canvas.height)

  context.fillStyle = "#fff"
  var i, j, xPos, yPos, zPos
  var nDone = 0

  for(i = 0; i < numberOfLines; ++i) {

    var txt = allTexts[i] + '\n'
    xPos = 0
    yPos = i * lineHeight
    zPos = fontSize

    var buffer = ""
    function writeBuffer() {
      if(buffer !== "") {
        var delta = context.measureText(buffer).width

        context.fillText(buffer, offsetX + xPos, offsetY + yPos)
        xPos += delta
      }
    }

    function changeStyle(oldStyle, newStyle) {

      function getTextFontSize() {
        return "" + Math.round(zPos) + "px ";
      }

      var ctxFont = "" + context.font;

      var wasSub = (oldStyle.indexOf(CHR_sub) > -1)
      var is_Sub = (newStyle.indexOf(CHR_sub) > -1)

      if(!wasSub && is_Sub) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos /= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      if(wasSub && !is_Sub) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }

      var wasSuper = (oldStyle.indexOf(CHR_super) > -1)
      var is_Super = (newStyle.indexOf(CHR_super) > -1)

      if(!wasSuper && is_Super) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos /= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }
      if(wasSuper && !is_Super) {
        ctxFont = ctxFont.replace(getTextFontSize(), "?px ")
        zPos *= 2
        ctxFont = ctxFont.replace("?px ", getTextFontSize())
      }

      var wasBold = (oldStyle.indexOf(CHR_bold) > -1)
      var is_Bold = (newStyle.indexOf(CHR_bold) > -1)

      if(!wasBold && is_Bold) {
        if(wasItalic) {
          ctxFont = ctxFont.replace("italic ", "italic bold ")
        } else {
          ctxFont = "bold " + ctxFont
        }
      }
      if(wasBold && !is_Bold) {
        ctxFont = ctxFont.replace("bold ", '')
      }

      var wasItalic = (oldStyle.indexOf(CHR_italic) > -1)
      var is_Italic = (newStyle.indexOf(CHR_italic) > -1)

      if(!wasItalic && is_Italic) {
        ctxFont = "italic " + ctxFont
      }
      if(wasItalic && !is_Italic) {
        ctxFont = ctxFont.replace("italic ", '')
      }

      context.font = ctxFont
    }

    for(j = 0; j < txt.length; ++j) {
      var style = (j + nDone < allStyles.length) ? allStyles[j + nDone] : allStyles[allStyles.length - 1]
      if(activeStyle === style) {
        buffer += txt[j]
      } else {
        writeBuffer()
        buffer = txt[j]

        changeStyle(activeStyle, style)
        activeStyle = style
      }
    }
    writeBuffer()

    nDone += txt.length

    var width = Math.round(xPos + 2 * offsetX) | 0
    if(maxWidth < width) maxWidth = width
  }

  //Cut pixels from image
  var xCut = maxWidth
  var yCut = offsetY + lineHeight * numberOfLines
  var pixels = ndarray(context.getImageData(0, 0, xCut, yCut).data, [yCut, xCut, 4])
  return pixels.pick(-1, -1, 0).transpose(1, 0)
}

function getContour(pixels, doSimplify) {
  var contour = surfaceNets(pixels, 128)
  if(doSimplify) {
    return simplify(contour.cells, contour.positions, 0.25)
  }
  return {
    edges: contour.cells,
    positions: contour.positions
  }
}

function processPixelsImpl(pixels, options, size, simplify) {
  //Extract contour
  var contour = getContour(pixels, simplify)

  //Apply warp to positions
  var positions = transformPositions(contour.positions, options, size)
  var edges     = contour.edges
  var flip = "ccw" === options.orientation

  //Clean up the PSLG, resolve self intersections, etc.
  cleanPSLG(positions, edges)

  //If triangulate flag passed, triangulate the result
  if(options.polygons || options.polygon || options.polyline) {
    var result = toPolygonCrappy(edges, positions)
    var nresult = new Array(result.length)
    for(var i=0; i<result.length; ++i) {
      var loops = result[i]
      var nloops = new Array(loops.length)
      for(var j=0; j<loops.length; ++j) {
        var loop = loops[j]
        var nloop = new Array(loop.length)
        for(var k=0; k<loop.length; ++k) {
          nloop[k] = positions[loop[k]].slice()
        }
        if(flip) {
          nloop.reverse()
        }
        nloops[j] = nloop
      }
      nresult[i] = nloops
    }
    return nresult
  } else if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: cdt2d(positions, edges, {
        delaunay: false,
        exterior: false,
        interior: true
      }),
      positions: positions
    }
  } else {
    return {
      edges:     edges,
      positions: positions
    }
  }
}

function processPixels(pixels, options, size) {
  try {
    return processPixelsImpl(pixels, options, size, true)
  } catch(e) {}
  try {
    return processPixelsImpl(pixels, options, size, false)
  } catch(e) {}
  if(options.polygons || options.polyline || options.polygon) {
    return []
  }
  if(options.triangles || options.triangulate || options.triangle) {
    return {
      cells: [],
      positions: []
    }
  }
  return {
    edges: [],
    positions: []
  }
}

function vectorizeText(str, canvas, context, options) {
  var size = options.size || 64
  var lineSpacing = options.lineSpacing || 1.25

  context.font = [
    options.fontStyle,
    options.fontVariant,
    options.fontWeight,
    size + "px",
    options.font
  ].filter(function(d) {return d}).join(" ")
  context.textAlign = "start"
  context.textBaseline = "alphabetic"
  context.direction = "ltr"

  var pixels = getPixels(canvas, context, str, size, lineSpacing)

  return processPixels(pixels, options, size)
}
<|endoftext|>


<commit_before>const saucelabs = require('sauce-test-runner');
const testServer = require('./testServer.js');

const port = 9999;

let reportStatus = 1;

const config = {
  urls: [`localhost:${port}/test/sauce-tests.html`],
  testname: 'Elix tests',
  framework: 'mocha',
  // throttled: 3,
  sauceConfig: {
    'video-upload-on-pass': false
  },
  browsers: [
    {
      browserName: 'chrome',
      platform: 'OS X 10.13'
    },
    {
      browserName: 'chrome',
      platform: 'Windows 10'
    },
    {
      browserName: 'firefox',
      platform: 'OS X 10.13',
    },
    {
      browserName: 'firefox',
      platform: 'Windows 10'
    },
    {
      browserName: 'MicrosoftEdge',
      version: '17',
      platform: 'Windows 10'
    },
    {
      browserName: 'safari',
      platform: 'OS X 10.13',
    }
  ],
  onTestSuiteComplete: (status) => {
    if (status) {
      console.log('All tests passed!');
      reportStatus = 0;
    }
    else {
      console.log('One or more tests failed');
    }
  }
};

async function runTests() {
  try {
    const server = await testServer(port);
    await saucelabs(config);
    server.close();
    process.exit(reportStatus);
  } catch (e) {
    console.error(e);
    process.exit(1);
  }
}

runTests();
<commit_msg>Ask for latest version of Microsoft Edge.<commit_after>const saucelabs = require('sauce-test-runner');
const testServer = require('./testServer.js');

const port = 9999;

let reportStatus = 1;

const config = {
  urls: [`localhost:${port}/test/sauce-tests.html`],
  testname: 'Elix tests',
  framework: 'mocha',
  // throttled: 3,
  sauceConfig: {
    'video-upload-on-pass': false
  },
  browsers: [
    {
      browserName: 'chrome',
      platform: 'OS X 10.13'
    },
    {
      browserName: 'chrome',
      platform: 'Windows 10'
    },
    {
      browserName: 'firefox',
      platform: 'OS X 10.13',
    },
    {
      browserName: 'firefox',
      platform: 'Windows 10'
    },
    {
      browserName: 'MicrosoftEdge',
      platform: 'Windows 10'
    },
    {
      browserName: 'safari',
      platform: 'OS X 10.13',
    }
  ],
  onTestSuiteComplete: (status) => {
    if (status) {
      console.log('All tests passed!');
      reportStatus = 0;
    }
    else {
      console.log('One or more tests failed');
    }
  }
};

async function runTests() {
  try {
    const server = await testServer(port);
    await saucelabs(config);
    server.close();
    process.exit(reportStatus);
  } catch (e) {
    console.error(e);
    process.exit(1);
  }
}

runTests();
<|endoftext|>


<commit_before>/**
 * modified version of bin packing algorithm @ https://github.com/jakesgordon/bin-packing
 * Copyright (c) 2011, 2012, 2013 Jake Gordon and contributors
 *
 * pixi.js is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license.php
*/

define([], function() {

	var BinPacker = Class.extend({

		init: function() {
		},

		pack: function(frames, options) {

			this.frames = {};
			this.options = options;
			this.width = 0;
			this.height = 0;

			this.options.padding.border -= this.options.padding.inner;
			if(this.options.padding.border < 0) {
				this.options.padding.border = 0;
			}

			if(this.options.powerOfTwo) {
				this.options.maxsize.w = this.powerOfTwo(this.options.maxsize.w) || 2;
				this.options.maxsize.h = this.powerOfTwo(this.options.maxsize.h) || 2;
			}

			if(this.options.fixed.w >= 1) {
				this.options.maxsize.w = this.options.fixed.w;
			}

			if(this.options.fixed.h >= 1) {
				this.options.maxsize.h = this.options.fixed.h;
			}

			var blocks = this.toBlocks(frames).sort(function(a, b) {
				return this.maxside(a, b);
			}.bind(this));

			this.fit(blocks);

			for(var n = 0 ; n < blocks.length ; n++) {
				var block = blocks[n];
				if (block.fit) {
					this.frames[block.frame] = {
						x: block.fit.x + this.options.padding.border + this.options.padding.inner,
						y: block.fit.y + this.options.padding.border + this.options.padding.inner,
						w: block.fit.w,
						h: block.fit.h,
						trimmed: block.t
					};
					this.width = Math.max(this.width, this.frames[block.frame].x + block.w);
					this.height = Math.max(this.height, this.frames[block.frame].y + block.h);
				} else {
					this.frames[block.frame] = null;
				}
			}

			this.width += 2 * this.options.padding.border - this.options.padding.shape;
			this.height += 2 * this.options.padding.border - this.options.padding.shape;

			if(this.options.powerOfTwo) {
				this.width = this.powerOfTwo(this.width) || 2;
				this.height = this.powerOfTwo(this.height) || 2;
			}

			if(this.options.squared) {
				if(this.height > this.width) {
					this.width = this.height;
				} else {
					this.height = this.width;
				}
			}

			if(this.options.fixed.w >= 1) { this.width = this.options.fixed.w; }
			if(this.options.fixed.h >= 1) { this.height = this.options.fixed.h; }

			return { frames: this.frames, width: this.width, height: this.height };
		},

		powerOfTwo: function(n) {
			var i = 0, s = 0;
			while (s === 0) {
				if(n <= Math.pow(2,i)) {
					s = Math.pow(2,i);
				}
				i++;
			}
			return s;
		},

		toBlocks: function (frames) {
			var blocks = [];
			_.each(frames, function (frame, index) {
				var block = {
					frame: index,
					w: ((this.options.trim && frame.trimmedSize.trimmed) ? frame.trimmedSize.width : frame.width) + this.options.padding.shape + 2 * this.options.padding.inner,
					h: ((this.options.trim && frame.trimmedSize.trimmed) ? frame.trimmedSize.height : frame.height) + this.options.padding.shape + 2 * this.options.padding.inner,
					t: (this.options.trim && frame.trimmedSize.trimmed),
					num: 1
				};
				if((block.w + 2 * this.options.padding.border) <= this.options.maxsize.w && (block.h + 2 * this.options.padding.border) <= this.options.maxsize.h) {
					blocks.push(block);
				}
			}.bind(this));
			return blocks;
		},

		w: function (a, b) {
			return b.w - a.w;
		},

		h: function (a, b) {
			return b.h - a.h;
		},

		max: function (a, b) {
			return Math.max(b.w, b.h) - Math.max(a.w, a.h);
		},

		min: function (a, b) {
			return Math.min(b.w, b.h) - Math.min(a.w, a.h);
		},

		maxside: function (a,b) {
			return this.msort(a, b, ["max", "min", "h", "w"]);
		},

		msort: function(a, b, criteria) {
			var diff, n;
			for (n = 0 ; n < criteria.length ; n++) {
				if(criteria[n] === "max") {
					diff = this.max(a, b);
				} else if(criteria[n] === "min") {
					diff = this.min(a, b);
				} else if(criteria[n] === "h") {
					diff = this.h(a, b);
				} else if(criteria[n] === "w") {
					diff = this.w(a, b);
				}
				if (diff != 0) {
					return diff;
				}
			}
			return 0;
		},

		fit: function(blocks) {
			var n, node, block, len = blocks.length;
			var w = len > 0 ? blocks[0].w : 0;
			var h = len > 0 ? blocks[0].h : 0;
			this.root = { x: 0, y: 0, w: w, h: h };
			for (n = 0; n < len ; n++) {
				block = blocks[n];
				if (node = this.findNode(this.root, block.w, block.h)) {
					block.fit = this.splitNode(node, block.w, block.h);
				} else {
					block.fit = this.growNode(block.w, block.h);
				}
			}
		},

		findNode: function(root, w, h) {
			if (root.used) {
				return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);
			} else if ((w <= root.w) && (h <= root.h)) {
				return root;
			} else {
				return null;
			}
		},

		splitNode: function(node, w, h) {
			node.used = true;
			node.down  = { x: node.x,     y: node.y + h, w: node.w,     h: node.h - h };
			node.right = { x: node.x + w, y: node.y,     w: node.w - w, h: h          };
			return node;
		},

		growNode: function(w, h) {
			var canGrowDown  = (w <= this.root.w);
			var canGrowRight = (h <= this.root.h);

			var shouldGrowRight = canGrowRight && (this.root.h >= (this.root.w + w));
			var shouldGrowDown  = canGrowDown  && (this.root.w >= (this.root.h + h));

			// dirty
			if(this.options.powerOfTwo) {
				var pot = this.powerOfTwo(this.root.w) + 2 * this.options.padding.border - this.options.padding.shape;
				if((this.root.w + w + 2 * this.options.padding.border) > pot && (this.root.h + h + 2 * this.options.padding.border) <= (pot*2) && canGrowDown) {
					shouldGrowDown = true;
					shouldGrowRight = false;
				}
			}
			if((this.root.w + w + 2 * this.options.padding.border) > this.options.maxsize.w) {
				shouldGrowRight = false;
				canGrowRight = false;
			}
			if((this.root.h + h + 2 * this.options.padding.border) > this.options.maxsize.h) {
				shouldGrowDown = false;
				canGrowDown = false;
			}

			if (shouldGrowRight) {
				return this.growRight(w, h);
			} else if (shouldGrowDown) {
				return this.growDown(w, h);
			} else if (canGrowRight) {
				return this.growRight(w, h);
			} else if (canGrowDown) {
				return this.growDown(w, h);
			} else {
				return null;
			}
		},

		growRight: function(w, h) {
			this.root = {
				used: true,
				x: 0,
				y: 0,
				w: this.root.w + w,
				h: this.root.h,
				down: this.root,
				right: { x: this.root.w, y: 0, w: w, h: this.root.h }
			};
			if (node = this.findNode(this.root, w, h)) {
				return this.splitNode(node, w, h);
			} else {
				return null;
			}
		},

		growDown: function(w, h) {
			this.root = {
				used: true,
				x: 0,
				y: 0,
				w: this.root.w,
				h: this.root.h + h,
				down:  { x: 0, y: this.root.h, w: this.root.w, h: h },
				right: this.root
			};
			if (node = this.findNode(this.root, w, h)) {
				return this.splitNode(node, w, h);
			} else {
				return null;
			}
		}

	});

	return BinPacker;

});
<commit_msg>Update binpacker.js<commit_after>/**
 * modified version of bin packing algorithm @ https://github.com/jakesgordon/bin-packing
 * Copyright (c) 2011, 2012, 2013 Jake Gordon and contributors
 *
 * @MIT License.
 * http://www.opensource.org/licenses/mit-license.php
*/

define([], function() {

	var BinPacker = Class.extend({

		init: function() {
		},

		pack: function(frames, options) {

			this.frames = {};
			this.options = options;
			this.width = 0;
			this.height = 0;

			this.options.padding.border -= this.options.padding.inner;
			if(this.options.padding.border < 0) {
				this.options.padding.border = 0;
			}

			if(this.options.powerOfTwo) {
				this.options.maxsize.w = this.powerOfTwo(this.options.maxsize.w) || 2;
				this.options.maxsize.h = this.powerOfTwo(this.options.maxsize.h) || 2;
			}

			if(this.options.fixed.w >= 1) {
				this.options.maxsize.w = this.options.fixed.w;
			}

			if(this.options.fixed.h >= 1) {
				this.options.maxsize.h = this.options.fixed.h;
			}

			var blocks = this.toBlocks(frames).sort(function(a, b) {
				return this.maxside(a, b);
			}.bind(this));

			this.fit(blocks);

			for(var n = 0 ; n < blocks.length ; n++) {
				var block = blocks[n];
				if (block.fit) {
					this.frames[block.frame] = {
						x: block.fit.x + this.options.padding.border + this.options.padding.inner,
						y: block.fit.y + this.options.padding.border + this.options.padding.inner,
						w: block.fit.w,
						h: block.fit.h,
						trimmed: block.t
					};
					this.width = Math.max(this.width, this.frames[block.frame].x + block.w);
					this.height = Math.max(this.height, this.frames[block.frame].y + block.h);
				} else {
					this.frames[block.frame] = null;
				}
			}

			this.width += 2 * this.options.padding.border - this.options.padding.shape;
			this.height += 2 * this.options.padding.border - this.options.padding.shape;

			if(this.options.powerOfTwo) {
				this.width = this.powerOfTwo(this.width) || 2;
				this.height = this.powerOfTwo(this.height) || 2;
			}

			if(this.options.squared) {
				if(this.height > this.width) {
					this.width = this.height;
				} else {
					this.height = this.width;
				}
			}

			if(this.options.fixed.w >= 1) { this.width = this.options.fixed.w; }
			if(this.options.fixed.h >= 1) { this.height = this.options.fixed.h; }

			return { frames: this.frames, width: this.width, height: this.height };
		},

		powerOfTwo: function(n) {
			var i = 0, s = 0;
			while (s === 0) {
				if(n <= Math.pow(2,i)) {
					s = Math.pow(2,i);
				}
				i++;
			}
			return s;
		},

		toBlocks: function (frames) {
			var blocks = [];
			_.each(frames, function (frame, index) {
				var block = {
					frame: index,
					w: ((this.options.trim && frame.trimmedSize.trimmed) ? frame.trimmedSize.width : frame.width) + this.options.padding.shape + 2 * this.options.padding.inner,
					h: ((this.options.trim && frame.trimmedSize.trimmed) ? frame.trimmedSize.height : frame.height) + this.options.padding.shape + 2 * this.options.padding.inner,
					t: (this.options.trim && frame.trimmedSize.trimmed),
					num: 1
				};
				if((block.w + 2 * this.options.padding.border) <= this.options.maxsize.w && (block.h + 2 * this.options.padding.border) <= this.options.maxsize.h) {
					blocks.push(block);
				}
			}.bind(this));
			return blocks;
		},

		w: function (a, b) {
			return b.w - a.w;
		},

		h: function (a, b) {
			return b.h - a.h;
		},

		max: function (a, b) {
			return Math.max(b.w, b.h) - Math.max(a.w, a.h);
		},

		min: function (a, b) {
			return Math.min(b.w, b.h) - Math.min(a.w, a.h);
		},

		maxside: function (a,b) {
			return this.msort(a, b, ["max", "min", "h", "w"]);
		},

		msort: function(a, b, criteria) {
			var diff, n;
			for (n = 0 ; n < criteria.length ; n++) {
				if(criteria[n] === "max") {
					diff = this.max(a, b);
				} else if(criteria[n] === "min") {
					diff = this.min(a, b);
				} else if(criteria[n] === "h") {
					diff = this.h(a, b);
				} else if(criteria[n] === "w") {
					diff = this.w(a, b);
				}
				if (diff != 0) {
					return diff;
				}
			}
			return 0;
		},

		fit: function(blocks) {
			var n, node, block, len = blocks.length;
			var w = len > 0 ? blocks[0].w : 0;
			var h = len > 0 ? blocks[0].h : 0;
			this.root = { x: 0, y: 0, w: w, h: h };
			for (n = 0; n < len ; n++) {
				block = blocks[n];
				if (node = this.findNode(this.root, block.w, block.h)) {
					block.fit = this.splitNode(node, block.w, block.h);
				} else {
					block.fit = this.growNode(block.w, block.h);
				}
			}
		},

		findNode: function(root, w, h) {
			if (root.used) {
				return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);
			} else if ((w <= root.w) && (h <= root.h)) {
				return root;
			} else {
				return null;
			}
		},

		splitNode: function(node, w, h) {
			node.used = true;
			node.down  = { x: node.x,     y: node.y + h, w: node.w,     h: node.h - h };
			node.right = { x: node.x + w, y: node.y,     w: node.w - w, h: h          };
			return node;
		},

		growNode: function(w, h) {
			var canGrowDown  = (w <= this.root.w);
			var canGrowRight = (h <= this.root.h);

			var shouldGrowRight = canGrowRight && (this.root.h >= (this.root.w + w));
			var shouldGrowDown  = canGrowDown  && (this.root.w >= (this.root.h + h));

			// dirty
			if(this.options.powerOfTwo) {
				var pot = this.powerOfTwo(this.root.w) + 2 * this.options.padding.border - this.options.padding.shape;
				if((this.root.w + w + 2 * this.options.padding.border) > pot && (this.root.h + h + 2 * this.options.padding.border) <= (pot*2) && canGrowDown) {
					shouldGrowDown = true;
					shouldGrowRight = false;
				}
			}
			if((this.root.w + w + 2 * this.options.padding.border) > this.options.maxsize.w) {
				shouldGrowRight = false;
				canGrowRight = false;
			}
			if((this.root.h + h + 2 * this.options.padding.border) > this.options.maxsize.h) {
				shouldGrowDown = false;
				canGrowDown = false;
			}

			if (shouldGrowRight) {
				return this.growRight(w, h);
			} else if (shouldGrowDown) {
				return this.growDown(w, h);
			} else if (canGrowRight) {
				return this.growRight(w, h);
			} else if (canGrowDown) {
				return this.growDown(w, h);
			} else {
				return null;
			}
		},

		growRight: function(w, h) {
			this.root = {
				used: true,
				x: 0,
				y: 0,
				w: this.root.w + w,
				h: this.root.h,
				down: this.root,
				right: { x: this.root.w, y: 0, w: w, h: this.root.h }
			};
			if (node = this.findNode(this.root, w, h)) {
				return this.splitNode(node, w, h);
			} else {
				return null;
			}
		},

		growDown: function(w, h) {
			this.root = {
				used: true,
				x: 0,
				y: 0,
				w: this.root.w,
				h: this.root.h + h,
				down:  { x: 0, y: this.root.h, w: this.root.w, h: h },
				right: this.root
			};
			if (node = this.findNode(this.root, w, h)) {
				return this.splitNode(node, w, h);
			} else {
				return null;
			}
		}

	});

	return BinPacker;

});
<|endoftext|>


<commit_before>var http = require('https');

exports.version = '0.0.5';

exports.WEPAY = function(settings)
{
    for (key in settings) {
        if (!settings[key])
            settings[key] = null;
    }

    var _in_production = false,
        options = {
            headers : {
                'Authorization': 'Bearer ' + settings.access_token,
                'Content-Type': 'application/json',
                'User-Agent': 'WePay NodeJS SDK'
            },
            method  : 'POST',
            port    : 443,
        };

    var get_domain = function()
    {
        if (_in_production) {
            host = 'wepayapi.com';
        } else {
            host = 'stage.wepayapi.com';
        }
        options.host = host;
        return host;
    }

    return {
        use_production: function()
        {
            _in_production = true;
            get_domain();
            return this;
        },

        use_staging: function()
        {
            _in_production = false;
            get_domain();
            return this;
        },

        call: function(url, params, callbackFunction) {
            options.path = '/v2' + url;
            var _params = JSON.stringify(params);

            // adjust the content length
            options.headers['Content-Length'] = _params.length;

            // set API Version
            if (settings.api_version){
                options.headers['Api-Version'] = settings.api_version;
            }

            var request = http.request(options, function(response) {
                // setup a variable to hold all of the response info.
                // it's possible that the response is too larger for NodeJS to handle in a single request
                // this will appropriately chunk the incoming response so that we receive all of the info
                var body = "";
                response.on('data', function(chunk) {
                    body += chunk;
                });
                response.on("end", function() {
                    // check the callbackFunction and return the data we received
                    if (callbackFunction && typeof callbackFunction === 'function') {
                        // encode the chunked body and perform the callback
                        callbackFunction(JSON.parse(body.toString('utf8')));
                    }
                });
            });

            request.write(_params);

            request.on('error', function(e) {
                throw new Error(e.message);
            });

            request.end();
        },

        get_access_token: function()
        {
            return settings.access_token;
        },

        get_api_version: function()
        {
            return settings.api_version;
        },

        set_access_token: function(access_token)
        {
            settings.access_token = access_token;
        },

        set_api_version: function(api_version)
        {
            settings.api_version = api_version;
        }
    }
};
<commit_msg>Add support for risk headers<commit_after>var http = require('https');

exports.version = '0.0.5';

exports.WEPAY = function(settings)
{
    for (key in settings) {
        if (!settings[key])
            settings[key] = null;
    }

    var _in_production = false,
        options = {
            headers : {
                'Authorization': 'Bearer ' + settings.access_token,
                'Content-Type': 'application/json',
                'User-Agent': 'WePay NodeJS SDK'
            },
            method  : 'POST',
            port    : 443,
        };

    var get_domain = function()
    {
        if (_in_production) {
            host = 'wepayapi.com';
        } else {
            host = 'stage.wepayapi.com';
        }
        options.host = host;
        return host;
    }

    return {
        use_production: function()
        {
            _in_production = true;
            get_domain();
            return this;
        },

        use_staging: function()
        {
            _in_production = false;
            get_domain();
            return this;
        },

        call: function(url, params, callbackFunction, riskToken, clientIP) {
            options.path = '/v2' + url;
            var _params = JSON.stringify(params);

            // adjust the content length
            options.headers['Content-Length'] = _params.length;

            // set API Version
            if (settings.api_version){
                options.headers['Api-Version'] = settings.api_version;
            }

            // set risk tokens
            if (riskToken) {
                options.headers['WePay-Risk-Token'] = riskToken;
            }
            if (clientIP) {
                options.headers['Client-IP'] = clientIP;
            }

            var request = http.request(options, function(response) {
                // setup a variable to hold all of the response info.
                // it's possible that the response is too larger for NodeJS to handle in a single request
                // this will appropriately chunk the incoming response so that we receive all of the info
                var body = "";
                response.on('data', function(chunk) {
                    body += chunk;
                });
                response.on("end", function() {
                    // check the callbackFunction and return the data we received
                    if (callbackFunction && typeof callbackFunction === 'function') {
                        // encode the chunked body and perform the callback
                        callbackFunction(JSON.parse(body.toString('utf8')));
                    }
                });
            });

            request.write(_params);

            request.on('error', function(e) {
                throw new Error(e.message);
            });

            request.end();
        },

        get_access_token: function()
        {
            return settings.access_token;
        },

        get_api_version: function()
        {
            return settings.api_version;
        },

        set_access_token: function(access_token)
        {
            settings.access_token = access_token;
        },

        set_api_version: function(api_version)
        {
            settings.api_version = api_version;
        }
    }
};
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////////////////////////////////
function oid() {
    //Get Token Balance
    $("#tokenBal").html(allTokens.balanceTokens.totalEarned.toFixed(2) + " tokens");
    if (window.location.hash != undefined) {
        //check if hash is oid
        var type = window.location.hash.substr(1);
        // split the hash
        var fields = type.split('=');
        var htpe = fields[0];
        var hval = fields[1];
        if (htpe == "oid") {
            //get the shop and the oder details
            var shop = getBitsWinOpt('s')
            // oid
            $(".otitle").html("");
            $(".otitle").append("Your Order");
            $(".of").html("");
            //var uid = JSON.parseInt(hval)
            var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name"));
            od.onsuccess = function (event) {
                try {
                    var odData = JSON.parse(event.target.result);
                    for (var ii = 0; ii < odData.length; ++ii) {
                        var xx = odData[ii].items
                        var xid = odData[ii].id
                        //makeOrder(products)
                        // match oid to url id
                        var urloid = getBitsOpt("oid")
                        if (urloid == xid) {
                            makeOrder(JSON.parse(xx), odData[ii].location)
                        } else {
                            console.log("no match")
                        }
                    }
                } catch (err) {}
            };
            od.onerror = function () {};
            //makeOrder(hval)
        } else {
            console.log("we dont know this hash")
        }
    } else {}
}

function unlockWallet() {
    walletFunctions(90).then(function (e) {
        loadGdrive();
        $(".walletToast").remove();
    })
}

function getUserOders(f) {

    doFetch({
        action: 'getAllOrders',
        uid: localStorage.getItem("bits-user-name")
    }).then(function (e) {
        if (e.status == "ok") {
            xx = e.data;
            //var earnedPoints = 0;

            for (var ii in allTokens) {
                allTokens[ii].totalEarned = 0;
            }
            for (var ii in xx) {
                var items = xx[ii].points;
                try {
                    var typeofCoin = JSON.parse(items).coin;
                } catch (err) {
                    console.log(err);
                    continue;
                }
                try {
                    var purchasePoints = JSON.parse(items).purchase;
                    if (purchasePoints == undefined) {
                        var purchasePoints = 0;
                    }
                } catch (err) {
                    console.log('this order does not have any purchase rewards', err);
                    var purchasePoints = 0;
                }
                try {
                    var deliveryPoints = JSON.parse(items).delivery;
                    if (deliveryPoints == undefined) {
                        var deliveryPoints = 0;
                    }
                } catch (err) {
                    console.log('this order does not have any delivery rewards', err);
                    var deliveryPoints = 0;
                }
                try {
                    allTokens[typeofCoin].totalEarned = allTokens[typeofCoin].totalEarned + purchasePoints + deliveryPoints;

                } catch (err) {
                    console.log('this coin had not been included in the rewards since its currently inactive', typeofCoin);
                    continue;
                }

                console.log(typeofCoin, purchasePoints, deliveryPoints);

            };

            var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name"));
            setdb.onsuccess = function () {
                oid();
            }
            setTimeout(function () {
                updateEarnedTokens(f)
            }, 1500);

        } else {
            swal("Cancelled", "an error occcured", "error");
        }
    })

}
// 		var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name"));
//
function updateEarnedTokens(f) {

    $('.coinlist').html('');
    var at = allTokens['allContracts'];

    var i = 0;
    var tCe = 0;
    tBal = 0;

    for(var i in at) {

try{
    if(!(location.origin+'/').includes(allTokens[at[i]].webpage)){
   continue;
   }
        var rate = allTokens[at[i]].rate;
        var coinName = allTokens[at[i]].name;
        //if i have 1000 kobos
        //var koboBalance = 1000;
        //		console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES');
        var koboRate = Math.floor(rate * baseX);
        var qq = rate * baseX;
        var xx = qq.toFixed(2);
        var coinId = at[i];
        var tA = allTokens[coinId].totalEarned + (allTokens[coinId].balance / Math.pow(10, allTokens[coinId].decimals));
        if (tA > 0) {
            //only display the coin if the user has a balance
            $('.coinlist').append('

' + coinName + '')
            $('.coin-' + coinId + '-bal').html('').append(tA.toFixed(5));

        }
        $('.coin-' + coinId + '-xrate').html('').append('1 ' + coinName + ' = ' + xx + ' ' + baseCd);
        tBal = tBal + (tA * allTokens[coinId].rate * baseX);
    }catch(e){
        console.log(e)
    }
        i++;
    }

    $('.balance-coins').html('').append(numberify(tBal,2) + ' ' + baseCd);
}

//Check Bal Interval
var checkBal = window.setInterval(function () {
    if ($("#checkBal")[0].innerHTML == "") {
        updateEarnedTokens()
    } else {
        clearInterval(checkBal);
    }
}, 7000);
<commit_msg>check balance interval set to 10sec<commit_after>////////////////////////////////////////////////////////////////////////////////////////////////////////////
function oid() {
    //Get Token Balance
    $("#tokenBal").html(allTokens.balanceTokens.totalEarned.toFixed(2) + " tokens");
    if (window.location.hash != undefined) {
        //check if hash is oid
        var type = window.location.hash.substr(1);
        // split the hash
        var fields = type.split('=');
        var htpe = fields[0];
        var hval = fields[1];
        if (htpe == "oid") {
            //get the shop and the oder details
            var shop = getBitsWinOpt('s')
            // oid
            $(".otitle").html("");
            $(".otitle").append("Your Order");
            $(".of").html("");
            //var uid = JSON.parseInt(hval)
            var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name"));
            od.onsuccess = function (event) {
                try {
                    var odData = JSON.parse(event.target.result);
                    for (var ii = 0; ii < odData.length; ++ii) {
                        var xx = odData[ii].items
                        var xid = odData[ii].id
                        //makeOrder(products)
                        // match oid to url id
                        var urloid = getBitsOpt("oid")
                        if (urloid == xid) {
                            makeOrder(JSON.parse(xx), odData[ii].location)
                        } else {
                            console.log("no match")
                        }
                    }
                } catch (err) {}
            };
            od.onerror = function () {};
            //makeOrder(hval)
        } else {
            console.log("we dont know this hash")
        }
    } else {}
}

function unlockWallet() {
    walletFunctions(90).then(function (e) {
        loadGdrive();
        $(".walletToast").remove();
    })
}

function getUserOders(f) {

    doFetch({
        action: 'getAllOrders',
        uid: localStorage.getItem("bits-user-name")
    }).then(function (e) {
        if (e.status == "ok") {
            xx = e.data;
            //var earnedPoints = 0;

            for (var ii in allTokens) {
                allTokens[ii].totalEarned = 0;
            }
            for (var ii in xx) {
                var items = xx[ii].points;
                try {
                    var typeofCoin = JSON.parse(items).coin;
                } catch (err) {
                    console.log(err);
                    continue;
                }
                try {
                    var purchasePoints = JSON.parse(items).purchase;
                    if (purchasePoints == undefined) {
                        var purchasePoints = 0;
                    }
                } catch (err) {
                    console.log('this order does not have any purchase rewards', err);
                    var purchasePoints = 0;
                }
                try {
                    var deliveryPoints = JSON.parse(items).delivery;
                    if (deliveryPoints == undefined) {
                        var deliveryPoints = 0;
                    }
                } catch (err) {
                    console.log('this order does not have any delivery rewards', err);
                    var deliveryPoints = 0;
                }
                try {
                    allTokens[typeofCoin].totalEarned = allTokens[typeofCoin].totalEarned + purchasePoints + deliveryPoints;

                } catch (err) {
                    console.log('this coin had not been included in the rewards since its currently inactive', typeofCoin);
                    continue;
                }

                console.log(typeofCoin, purchasePoints, deliveryPoints);

            };

            var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name"));
            setdb.onsuccess = function () {
                oid();
            }
            setTimeout(function () {
                updateEarnedTokens(f)
            }, 1500);

        } else {
            swal("Cancelled", "an error occcured", "error");
        }
    })

}
// 		var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name"));
//
function updateEarnedTokens(f) {

    $('.coinlist').html('');
    var at = allTokens['allContracts'];

    var i = 0;
    var tCe = 0;
    tBal = 0;

    for (var i in at) {

        try {
            if (!(location.origin + '/').includes(allTokens[at[i]].webpage)) {
                continue;
            }
            var rate = allTokens[at[i]].rate;
            var coinName = allTokens[at[i]].name;
            //if i have 1000 kobos
            //var koboBalance = 1000;
            //		console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES');
            var koboRate = Math.floor(rate * baseX);
            var qq = rate * baseX;
            var xx = qq.toFixed(2);
            var coinId = at[i];
            var tA = allTokens[coinId].totalEarned + (allTokens[coinId].balance / Math.pow(10, allTokens[coinId].decimals));
            if (tA > 0) {
                //only display the coin if the user has a balance
                $('.coinlist').append('

' + coinName + '')
                $('.coin-' + coinId + '-bal').html('').append(tA.toFixed(5));

            }
            $('.coin-' + coinId + '-xrate').html('').append('1 ' + coinName + ' = ' + xx + ' ' + baseCd);
            tBal = tBal + (tA * allTokens[coinId].rate * baseX);
        } catch (e) {
            console.log(e)
        }
        i++;
    }

    $('.balance-coins').html('').append(numberify(tBal, 2) + ' ' + baseCd);
}

//Check Bal Interval
window.setInterval(function () {
    updateEarnedTokens();
    console.log("running")
}, 10000);
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////////////////////////////////
function oid() {
	if (window.location.hash != undefined) {
		//check if hash is oid
		var type = window.location.hash.substr(1);
		console.log(type)
			// split the hash
		var fields = type.split('=');
		var htpe = fields[0];
		var hval = fields[1];
		console.log(htpe)
		console.log(hval)
		if (htpe == "oid") {
			console.log("its an order")
				//get the shop and the oder details
			var shop = getBitsWinOpt('s')
				// oid
			console.log("this is shop id " + shop + " the oid is " + hval)
				//var uid = JSON.parseInt(hval)
			var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name"));
			od.onsuccess = function(event) {
				try {
					var odData = JSON.parse(event.target.result);
					console.log(odData)
					for (var ii = 0; ii < odData.length; ++ii) {
						var xx = odData[ii].items
						var xid = odData[ii].id
						console.log(xid, xx)
							//makeOrder(products)
							// match oid to url id
						var urloid = getBitsOpt("oid")
						if (urloid == xid) {
							console.log("match")
							makeOrder(JSON.parse(xx), odData[ii].location)
						} else {
							console.log("no match")
						}
					}
				} catch (err) {}
			};
			od.onerror = function() {};
			//makeOrder(hval)
		} else {
			console.log("we dont know this hash")
		}
	} else {}
}

function getUserOders() {
	 // convert points to KOBO

 fetchRates().then(function(e) {
	if (e.status == "ok") {
		coinList = e.data.data;
		for (var i in coinList) {
			var rate = coinList[i].coinRate;
//if i have 1000 kobos
//var koboBalance = 1000;
	//		console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES');
var koboRate = 	Math.floor(rate*e.data.baseEx)
var qq = rate*e.data.baseEx
var xx = qq.toFixed(2);
console.log('1 KOBO = '+xx+' KES');
$('.bitsoko-xrate').html('').append('1 KOBO = '+xx+' KES')
localStorage.setItem('kobo-current-rates', xx);
		}
	} else {
		console.log("error");
	}
});
///////////////////////////////////////////////////////////////////////////////////////////////////
	doFetch({
		action: 'getAllOrders',
		uid: localStorage.getItem("bits-user-name")
	}).then(function(e) {
		if (e.status == "ok") {
			console.log(e.data)
			xx = e.data;

var earnedPoints = 0;
			for (var ii in xx) {
				var items = xx[ii].points;
				try{
var typeofCoin = JSON.parse(items).coin;
				}catch(err){
				console.log('this order does not have any rewards');
				continue;
				}
							try{

var purchasePoints = JSON.parse(items).purchase;
				}catch(err){
				console.log('this order does not have any purchase rewards');

var purchasePoints = 0;
				}
							try{

var deliveryPoints = JSON.parse(items).delivery;
				}catch(err){
				console.log('this order does not have any delivery rewards');

var deliveryPoints = 0;
				}

				 earnedPoints = earnedPoints + purchasePoints + deliveryPoints;

			};

				// convert this to kenyan sh
				 var rate=JSON.parse(localStorage.getItem('kobo-current-rates'));
				  var totalearnedPoints = earnedPoints * rate
					var q = totalearnedPoints.toFixed(2);
				 console.log(q);
				 $('#balance-coins').html('').append(q+' KES');

			var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name"));
			setdb.onsuccess = function() {
				oid();
			}
		} else {
			swal("Cancelled", "an error occcured", "error");
		}
	})
}
// 		var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name"));
//
<commit_msg>Update bits-oder-functions.js<commit_after>////////////////////////////////////////////////////////////////////////////////////////////////////////////
function oid() {
	if (window.location.hash != undefined) {
		//check if hash is oid
		var type = window.location.hash.substr(1);
		console.log(type)
			// split the hash
		var fields = type.split('=');
		var htpe = fields[0];
		var hval = fields[1];
		console.log(htpe)
		console.log(hval)
		if (htpe == "oid") {
			console.log("its an order")
				//get the shop and the oder details
			var shop = getBitsWinOpt('s')
				// oid
			console.log("this is shop id " + shop + " the oid is " + hval)
				//var uid = JSON.parseInt(hval)
			var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name"));
			od.onsuccess = function(event) {
				try {
					var odData = JSON.parse(event.target.result);
					console.log(odData)
					for (var ii = 0; ii < odData.length; ++ii) {
						var xx = odData[ii].items
						var xid = odData[ii].id
						console.log(xid, xx)
							//makeOrder(products)
							// match oid to url id
						var urloid = getBitsOpt("oid")
						if (urloid == xid) {
							console.log("match")
							makeOrder(JSON.parse(xx), odData[ii].location)
						} else {
							console.log("no match")
						}
					}
				} catch (err) {}
			};
			od.onerror = function() {};
			//makeOrder(hval)
		} else {
			console.log("we dont know this hash")
		}
	} else {}
}

function getUserOders() {
	 // convert points to KOBO

 fetchRates().then(function(e) {
	if (e.status == "ok") {
		coinList = e.data.data;
		for (var i in coinList) {
			var rate = coinList[i].coinRate;
//if i have 1000 kobos
//var koboBalance = 1000;
	//		console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES');
var koboRate = 	Math.floor(rate*e.data.baseEx)
var qq = rate*e.data.baseEx
var xx = qq.toFixed(2);
console.log('1 KOBO = '+xx+' KES');
$('.bitsoko-xrate').html('').append('1 KOBO = '+xx+' KES')
localStorage.setItem('kobo-current-rates', xx);
		}
	} else {
		console.log("error");
	}
});
///////////////////////////////////////////////////////////////////////////////////////////////////
	doFetch({
		action: 'getAllOrders',
		uid: localStorage.getItem("bits-user-name")
	}).then(function(e) {
		if (e.status == "ok") {
			console.log(e.data)
			xx = e.data;

var earnedPoints = 0;
			for (var ii in xx) {
				var items = xx[ii].points;
				try{
var typeofCoin = JSON.parse(items).coin;
				}catch(err){
				console.log('this order does not have any rewards');
				continue;
				}
							try{

var purchasePoints = JSON.parse(items).purchase;
				}catch(err){
				console.log('this order does not have any purchase rewards');

var purchasePoints = 0;
				}
							try{

var deliveryPoints = JSON.parse(items).delivery;
				}catch(err){
				console.log('this order does not have any delivery rewards');

var deliveryPoints = 0;
				}

				 console.log(earnedPoints,purchasePoints,deliveryPoints);

				 earnedPoints = earnedPoints + purchasePoints + deliveryPoints;

			};

				// convert this to kenyan sh
				 var rate=JSON.parse(localStorage.getItem('kobo-current-rates'));
				  var totalearnedPoints = earnedPoints * rate
					var q = totalearnedPoints.toFixed(2);
				 console.log(q);
				 $('#balance-coins').html('').append(q+' KES');

			var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name"));
			setdb.onsuccess = function() {
				oid();
			}
		} else {
			swal("Cancelled", "an error occcured", "error");
		}
	})
}
// 		var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name"));
//
<|endoftext|>