<commit_before>var $operators = {
    "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift",
    "**=":"ipow","**":"pow","//":"floordiv","<<":"lshift",">>":"rshift",
    "+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv",
    "%=":"imod","&=":"iand","|=":"ior",
    "^=":"ipow","+":"add","-":"sub","*":"mul",
    "/":"truediv","%":"mod","&":"and","|":"or",
    "^":"pow","<":"lt",">":"gt",
    "<=":"le",">=":"ge","==":"eq","!=":"ne",
    "or":"or","and":"and","in":"in","not":"not",
    "not_in":"not_in","is_not":"is_not" // fake
    }

var $first_op_letter = {}
for(op in $operators){$first_op_letter[op.charAt(0)]=0}

function $tokenize(src){
    var delimiters = [["#","\n","comment"],['"""','"""',"triple_string"],
        ["'","'","string"],['"','"',"string"],
        ["r'","'","raw_string"],['r"','"',"raw_string"]]
    var br_open = {"(":0,"[":0,"{":0}
    var br_close = {")":"(","]":"[","}":"{"}
    var br_stack = ""
    var br_pos = new Array()
    var kwdict = $List2Dict("False","class","finally","is","return",
        "None","continue","for","lambda","try","True","def","from",
        "nonlocal","while","del","global","with",
        "as","elif","if","yield","assert","else","import","pass",
        "break","except","raise")
    var unsupported = $List2Dict("class","is","from","nonlocal","with",
        "as","yield")
    // causes errors for some browsers
    // complete list at http://www.javascripter.net/faq/reserved.htm
    var forbidden = $List2Dict("item","status")

    var punctuation = {',':0,':':0} //,';':0}
    var int_pattern = new RegExp("^\\d+")
    var float_pattern = new RegExp("^\\d+\\.\\d*(e-?\\d+)?")
    var id_pattern = new RegExp("[\\$_a-zA-Z]\\w*")

    var stack = new Array()
    var name = ""
    var _type = null
    var pos = 0
    var indent_stack = [0]

    var pos2line = {}
    var lnum=1
    for(i=0;i<src.length;i++){
        pos2line[i]=lnum
        if(src.charAt(i)=='\n'){lnum+=1}
    }
    lnum = 0
    while(pos<src.length){
        document.line_num = pos2line[pos]
        var flag = false
        var car = src.charAt(pos)
        // check indentation
        if(stack.length==0 || $last(stack)[0]=='newline'){
            var indent = 0
            while(pos<src.length && src.charAt(pos)==" "){
                indent++;pos++
            }
            // ignore empty lines
            if(src.charAt(pos)=='\n'){pos++;lnum++;continue}
            // indentation must be equal to some value in indent_stack, or
            // greater if last line ended with :
            if(stack.length>1){
                if(indent>$last(indent_stack)){
                    if(stack[stack.length-2][0] != "delimiter" &&
                        stack[stack.length-2][1] != ":"){
                        $raise("IndentationError","unexpected indent")
                    }else{
                        indent_stack.push(indent)
                    }
                }else if(indent==$last(indent_stack)){
                    if(stack[stack.length-2][0]=="delimiter" &&
                        stack[stack.length-2][1]==":"){
                        $raise("IndentationError","expected an indented block")
                    }
                }else if(indent<$last(indent_stack)){
                    indent_stack.pop()
                    while(true){
                        if(indent_stack.length==0){
                            $raise('IndentationError','unexpected indent')
                        }
                        if(indent>$last(indent_stack)){
                            $raise('IndentationError','unexpected indent')
                        }else if(indent==$last(indent_stack)){break}
                        else{indent_stack.pop()}
                    }
                }
            }else if(indent>0){
                $raise("IndentationError","unexpected indent")
            }
            stack.push(["indent",indent,pos-indent])
            continue
        }
        // comment
        if(car=="#"){
            var end = src.substr(pos+1).search('\n')
            if(end==-1){end=src.length-1}
            stack.push(["newline",lnum,pos+1+end])
            lnum += 1
            pos += end+2;continue
        }
        // string
        if(car=='"' || car=="'"){
            var raw = false
            var end = null
            if(name.length>0 && name.toLowerCase()=="r"){
                // raw string
                raw = true;name=""
            }
            if(src.substr(pos,3)==car+car+car){_type="triple_string";end=pos+3}
            else{_type="string";end=pos+1}
            var escaped = false
            var zone = car
            var found = false
            while(end<src.length){
                if(escaped){zone+=src.charAt(end);escaped=false;end+=1}
                else if(src.charAt(end)=="\\"){
                    if(raw){
                        zone += '\\\\'
                        end++
                    } else {
                        if(src.charAt(end+1)=='\n'){
                            // explicit line joining inside strings
                            end += 2
                            lnum++
                        } else {
                            zone+=src.charAt(end);escaped=true;end+=1
                        }
                    }
                } else if(src.charAt(end)==car){
                    if(_type=="triple_string" && src.substr(end,3)!=car+car+car){
                        end++
                    } else {
                        found = true
                        // end of string
                        if(stack.length>0 && $last(stack)[0]=="str"){
                            // implicit string concatenation : insert a + sign
                            stack.push(['operator','+',end])
                        }
                        stack.push(["str",zone+car,pos])
                        pos = end+1
                        if(_type=="triple_string"){pos = end+3}
                        break
                    }
                } else {
                    zone += src.charAt(end)
                    if(src.charAt(end)=='\n'){lnum++}
                    end++
                }
            }
            if(!found){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"String end not found ")
            }
            continue
        }
        // identifier ?
        if(name==""){
            if(car.search(/[a-zA-Z_]/)!=-1){
                name=car // identifier start
                pos++;continue
            }
        } else {
            if(car.search(/\w/)!=-1){
                name+=car
                pos++;continue
            } else{
                if(name in kwdict){
                    if(name in unsupported){
                        document.line_num = pos2line[pos]
                        $raise('SyntaxError',"Unsupported Python keyword '"+name+"'")
                    }
                    stack.push(["keyword",name,pos-name.length])
                } else if(name in $operators) { // and, or
                    stack.push(["operator",name,pos-name.length])
                } else if(stack.length>1 && $last(stack)[0]=="point"
                    && (stack[stack.length-2][0] in $List2Dict('id','qualifier','bracket'))) {
                    stack.push(["qualifier",name,pos-name.length])
                } else if(name in forbidden) {
                    document.line_num = pos2line[pos]
                    $raise('SyntaxError',"Forbidden name '"+name+"' : might conflict with Javascript variables")
                } else {
                    stack.push(["id",name,pos-name.length])
                }
                name=""
                continue
            }
        }
        // qualified name ?
        if(car=="."){
            stack.push(["point",".",pos])
            pos++;continue
        }
        // number
        if(car.search(/\d/)>-1){
            // digit
            var res = float_pattern.exec(src.substr(pos))
            if(res){
                if(res[0].search('e')>-1){stack.push(["float",res[0],pos])}
                else{stack.push(["float",eval(res[0]),pos])}
            }else{
                res = int_pattern.exec(src.substr(pos))
                stack.push(["int",eval(res[0]),pos])
            }
            pos += res[0].length
            continue
        }
        if(car=="\n"){
            lnum++
            if(br_stack.length>0){
                // implicit line joining inside brackets
                pos++;continue
            } else {
                // ignore empty lines
                if(stack[stack.length-1][0]!="newline"){
                    stack.push(["newline",lnum,pos])
                } else {
                    stack[stack.length-1][1] = lnum // update line num
                }
                pos++;continue
            }
        }
        if(car in br_open){
            br_stack += car
            br_pos[br_stack.length-1] = pos
            stack.push(["bracket",car,pos])
            pos++;continue
        }
        if(car in br_close){
            if(br_stack==""){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unexpected closing bracket")
            } else if(br_close[car]!=$last(br_stack)){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unbalanced bracket ")
            } else {
                br_stack = br_stack.substr(0,br_stack.length-1)
                stack.push(["bracket",car,pos])
                pos++;continue
            }
        }
        if(car=="="){
            if(src.charAt(pos+1)!="="){
                // assignment if outside of brackets
                if(br_stack.length==0){
                    stack.push(["assign","=",pos])
                } else { // like in foo(bar=9)
                    stack.push(["delimiter","=",pos])
                }
                pos++;continue
            } else {
                stack.push(["operator","==",pos])
                pos+=2;continue
            }
        }
        if(car in punctuation){
            stack.push(["delimiter",car,pos])
            pos++;continue
        }
        // operators
        if(car in $first_op_letter){
            // find longest match
            var op_match = ""
            for(op_sign in $operators){
                if(op_sign==src.substr(pos,op_sign.length)
                    && op_sign.length>op_match.length){
                    op_match=op_sign
                }
            }
            if(op_match.length>0){
                stack.push(["operator",op_match,pos])
                pos += op_match.length
                continue
            }
        }
        if(car=='\\' && src.charAt(pos+1)=='\n'){
            lnum++;pos+=2;continue
        }
        if(car!=' '){$raise('SyntaxError','unknown token '+car)}
        pos += 1
    }

    if(br_stack.length!=0){
        pos = br_pos.pop()
        document.line_num = pos2line[pos]
        $raise('SyntaxError',"Unbalanced bracket "+br_stack.charAt(br_stack.length-1))
    }

    return stack

}
<commit_msg>Minor update<commit_after>var $operators = {
    "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift",
    "**=":"ipow","**":"pow","//":"floordiv","<<":"lshift",">>":"rshift",
    "+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv",
    "%=":"imod","&=":"iand","|=":"ior",
    "^=":"ipow","+":"add","-":"sub","*":"mul",
    "/":"truediv","%":"mod","&":"and","|":"or",
    "^":"pow","<":"lt",">":"gt",
    "<=":"le",">=":"ge","==":"eq","!=":"ne",
    "or":"or","and":"and","in":"in","not":"not",
    "not_in":"not_in","is_not":"is_not" // fake
    }

var $first_op_letter = {}
for(op in $operators){$first_op_letter[op.charAt(0)]=0}

function $tokenize(src){
    var delimiters = [["#","\n","comment"],['"""','"""',"triple_string"],
        ["'","'","string"],['"','"',"string"],
        ["r'","'","raw_string"],['r"','"',"raw_string"]]
    var br_open = {"(":0,"[":0,"{":0}
    var br_close = {")":"(","]":"[","}":"{"}
    var br_stack = ""
    var br_pos = new Array()
    var kwdict = $List2Dict("False","class","finally","is","return",
        "None","continue","for","lambda","try","True","def","from",
        "nonlocal","while","del","global","with",
        "as","elif","if","yield","assert","else","import","pass",
        "break","except","raise")
    var unsupported = $List2Dict("class","is","from","nonlocal","with",
        "as","yield")
    // causes errors for some browsers
    // complete list at http://www.javascripter.net/faq/reserved.htm
    var forbidden = $List2Dict("item","status")

    var punctuation = {',':0,':':0} //,';':0}
    var int_pattern = new RegExp("^\\d+")
    var float_pattern = new RegExp("^\\d+\\.\\d*(e-?\\d+)?")
    var id_pattern = new RegExp("[\\$_a-zA-Z]\\w*")

    var stack = new Array()
    var name = ""
    var _type = null
    var pos = 0
    var indent_stack = [0]

    var pos2line = {}
    var lnum=1
    for(i=0;i<src.length;i++){
        pos2line[i]=lnum
        if(src.charAt(i)=='\n'){lnum+=1}
    }
    lnum = 0
    while(pos<src.length){
        document.line_num = pos2line[pos]
        var flag = false
        var car = src.charAt(pos)
        // check indentation
        if(stack.length==0 || $last(stack)[0]=='newline'){
            var indent = 0
            while(pos<src.length && src.charAt(pos)==" "){
                indent++;pos++
            }
            // ignore empty lines
            if(src.charAt(pos)=='\n'){pos++;lnum++;continue}
            // indentation must be equal to some value in indent_stack, or
            // greater if last line ended with :
            if(stack.length>1){
                if(indent>$last(indent_stack)){
                    if(stack[stack.length-2][0] != "delimiter" &&
                        stack[stack.length-2][1] != ":"){
                        $raise("IndentationError","unexpected indent")
                    }else{
                        indent_stack.push(indent)
                    }
                }else if(indent==$last(indent_stack)){
                    if(stack[stack.length-2][0]=="delimiter" &&
                        stack[stack.length-2][1]==":"){
                        $raise("IndentationError","expected an indented block")
                    }
                }else if(indent<$last(indent_stack)){
                    indent_stack.pop()
                    while(true){
                        if(indent_stack.length==0){
                            $raise('IndentationError','unexpected indent')
                        }
                        if(indent>$last(indent_stack)){
                            $raise('IndentationError','unexpected indent')
                        }else if(indent==$last(indent_stack)){break}
                        else{indent_stack.pop()}
                    }
                }
            }else if(indent>0){
                $raise("IndentationError","unexpected indent")
            }
            stack.push(["indent",indent,pos-indent])
            continue
        }
        // comment
        if(car=="#"){
            var end = src.substr(pos+1).search('\n')
            if(end==-1){end=src.length-1}
            stack.push(["newline",lnum,pos+1+end])
            lnum += 1
            pos += end+2;continue
        }
        // string
        if(car=='"' || car=="'"){
            var raw = false
            var end = null
            if(name.length>0 && name.toLowerCase()=="r"){
                // raw string
                raw = true;name=""
            }
            if(src.substr(pos,3)==car+car+car){_type="triple_string";end=pos+3}
            else{_type="string";end=pos+1}
            var escaped = false
            var zone = car
            var found = false
            while(end<src.length){
                if(escaped){zone+=src.charAt(end);escaped=false;end+=1}
                else if(src.charAt(end)=="\\"){
                    if(raw){
                        zone += '\\\\'
                        end++
                    } else {
                        if(src.charAt(end+1)=='\n'){
                            // explicit line joining inside strings
                            end += 2
                            lnum++
                        } else {
                            zone+=src.charAt(end);escaped=true;end+=1
                        }
                    }
                } else if(src.charAt(end)==car){
                    if(_type=="triple_string" && src.substr(end,3)!=car+car+car){
                        end++
                    } else {
                        found = true
                        // end of string
                        if(stack.length>0 && $last(stack)[0]=="str"){
                            // implicit string concatenation : insert a + sign
                            stack.push(['operator','+',end])
                        }
                        stack.push(["str",zone+car,pos])
                        pos = end+1
                        if(_type=="triple_string"){pos = end+3}
                        break
                    }
                } else {
                    zone += src.charAt(end)
                    if(src.charAt(end)=='\n'){lnum++}
                    end++
                }
            }
            if(!found){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"String end not found ")
            }
            continue
        }
        // identifier ?
        if(name==""){
            if(car.search(/[a-zA-Z_]/)!=-1){
                name=car // identifier start
                pos++;continue
            }
        } else {
            if(car.search(/\w/)!=-1){
                name+=car
                pos++;continue
            } else{
                if(name in kwdict){
                    if(name in unsupported){
                        document.line_num = pos2line[pos]
                        $raise('SyntaxError',"Unsupported Python keyword '"+name+"'")
                    }
                    stack.push(["keyword",name,pos-name.length])
                } else if(name in $operators) { // and, or
                    stack.push(["operator",name,pos-name.length])
                } else if(stack.length>1 && $last(stack)[0]=="point"
                    && (stack[stack.length-2][0] in $List2Dict('id','qualifier','bracket'))) {
                    stack.push(["qualifier",name,pos-name.length])
                } else if(name in forbidden) {
                    document.line_num = pos2line[pos]
                    $raise('SyntaxError',"Forbidden name '"+name+"' : might conflict with Javascript variables")
                } else {
                    stack.push(["id",name,pos-name.length])
                }
                name=""
                continue
            }
        }
        // qualified name ?
        if(car=="."){
            stack.push(["point",".",pos])
            pos++;continue
        }
        // number
        if(car.search(/\d/)>-1){
            // digit
            var res = float_pattern.exec(src.substr(pos))
            if(res){
                if(res[0].search('e')>-1){stack.push(["float",res[0],pos])}
                else{stack.push(["float",eval(res[0]),pos])}
            }else{
                res = int_pattern.exec(src.substr(pos))
                stack.push(["int",eval(res[0]),pos])
            }
            pos += res[0].length
            continue
        }
        if(car=="\n"){
            lnum++
            if(br_stack.length>0){
                // implicit line joining inside brackets
                pos++;continue
            } else {
                // ignore empty lines
                if(stack[stack.length-1][0]!="newline"){
                    stack.push(["newline",lnum,pos])
                } else {
                    stack[stack.length-1][1] = lnum // update line num
                }
                pos++;continue
            }
        }
        if(car in br_open){
            br_stack += car
            br_pos[br_stack.length-1] = pos
            stack.push(["bracket",car,pos])
            pos++;continue
        }
        if(car in br_close){
            if(br_stack==""){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unexpected closing bracket")
            } else if(br_close[car]!=$last(br_stack)){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unbalanced bracket ")
            } else {
                br_stack = br_stack.substr(0,br_stack.length-1)
                stack.push(["bracket",car,pos])
                pos++;continue
            }
        }
        if(car=="="){
            if(src.charAt(pos+1)!="="){
                // assignment if outside of brackets
                if(br_stack.length==0){
                    stack.push(["assign","=",pos])
                } else { // like in foo(bar=9)
                    stack.push(["delimiter","=",pos])
                }
                pos++;continue
            } else {
                stack.push(["operator","==",pos])
                pos+=2;continue
            }
        }
        if(car in punctuation){
            stack.push(["delimiter",car,pos])
            pos++;continue
        }
        // operators
        if(car in $first_op_letter){
            // find longest match
            var op_match = ""
            for(op_sign in $operators){
                if(op_sign==src.substr(pos,op_sign.length)
                    && op_sign.length>op_match.length){
                    op_match=op_sign
                }
            }
            if(op_match.length>0){
                stack.push(["operator",op_match,pos])
                pos += op_match.length
                continue
            }
        }
        if(car=='\\' && src.charAt(pos+1)=='\n'){
            lnum++;pos+=2;continue
        }
        if(car!=' '){$raise('SyntaxError','unknown token ['+car+']')}
        pos += 1
    }

    if(br_stack.length!=0){
        pos = br_pos.pop()
        document.line_num = pos2line[pos]
        $raise('SyntaxError',"Unbalanced bracket "+br_stack.charAt(br_stack.length-1))
    }

    return stack

}
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import EventEmitter from 'events';
import {createHash} from 'crypto';
import mkdirp from 'mkdirp';
import {isString, isObject} from 'lodash/lang';

export function generateFilenameFromCacheKey(cacheKey) {
  const hash = createHash('md5').update(cacheKey).digest('hex');
  return hash + '.json';
}

export function createKVFileCache(options={}) {
  const {dirname} = options;
  if (!isString(dirname)) {
    throw new Error(`A \`dirname\` option must be provided`);
  }

  mkdirp.sync(dirname);

  const emitter = new EventEmitter();
  const cache = Object.create(null);

  return {
    cache,
    get(key, cb) {
      const filename = path.join(dirname, generateFilenameFromCacheKey(key));

      if (cache[filename]) {
        let data;
        try {
          data = JSON.parse(cache[filename]);
        } catch(err) {
          emitter.emit('error', err);
          return cb(err);
        }
        return cb(null, data);
      }

      fs.readFile(filename, 'utf8', (err, json) => {
        if (err) {
          // Cache misses are represented by missing files
          if (err.code === 'ENOENT') {
            return cb(null, null);
          }

          emitter.emit('error', err);
          return cb(err);
        }

        cache[filename] = json;

        let data;
        try {
          data = JSON.parse(json);
        } catch(err) {
          emitter.emit('error', err);
          return cb(err);
        }

        cb(null, data);
      });
    },
    set(key, value, cb) {
      const filename = path.join(dirname, generateFilenameFromCacheKey(key));

      // We serialize the data as late as possible to avoid blocking the event loop
      let json;
      try {
        json = JSON.stringify(value);
      } catch(err) {
        emitter.emit('error', err);
        if (cb) {
          return cb(err);
        } else {
          return;
        }
      }

      cache[filename] = json;

      fs.writeFile(filename, json, (err) => {
        if (err) {
          emitter.emit('error', err);
        }

        if (cb) {
          cb(err);
        }
      });
    },
    invalidate(key, cb) {
      const filename = path.join(dirname, generateFilenameFromCacheKey(key));
      cache[filename] = undefined;

      fs.unlink(filename, (err) => {
        if (err) {
          // Cache misses are represented by missing files, so we can ignore this
          if (err.code === 'ENOENT') {
            if (cb) {
              return cb(null);
            }
            return;
          }
          emitter.emit('error', err);
        }

        if (cb) {
          cb(err);
        }
      });
    },
    on: emitter.on.bind(emitter),
    once: emitter.once.bind(emitter),
    off: emitter.removeListener.bind(emitter)
  }
}<commit_msg>Code cleanup<commit_after>import fs from 'fs';
import path from 'path';
import EventEmitter from 'events';
import {createHash} from 'crypto';
import mkdirp from 'mkdirp';
import {isString, isObject} from 'lodash/lang';

export function generateFilenameFromCacheKey(cacheKey) {
  const hash = createHash('md5').update(cacheKey).digest('hex');
  return hash + '.json';
}

export function createKVFileCache(options={}) {
  const {dirname} = options;
  if (!isString(dirname)) {
    throw new Error(`A \`dirname\` option must be provided`);
  }

  mkdirp.sync(dirname);

  const emitter = new EventEmitter();
  const cache = Object.create(null);

  return {
    cache,
    get(key, cb) {
      const filename = path.join(dirname, generateFilenameFromCacheKey(key));

      if (cache[filename]) {
        let data;
        try {
          data = JSON.parse(cache[filename]);
        } catch(err) {
          emitter.emit('error', err);
          return cb(err);
        }
        return cb(null, data);
      }

      fs.readFile(filename, 'utf8', (err, json) => {
        if (err) {
          // Cache misses are represented by missing files
          if (err.code === 'ENOENT') {
            return cb(null, null);
          }

          emitter.emit('error', err);
          return cb(err);
        }

        cache[filename] = json;

        let data;
        try {
          data = JSON.parse(json);
        } catch(err) {
          emitter.emit('error', err);
          return cb(err);
        }

        cb(null, data);
      });
    },
    set(key, value, cb) {
      const filename = path.join(dirname, generateFilenameFromCacheKey(key));

      // We serialize the data as late as possible to avoid blocking the event loop
      let json;
      try {
        json = JSON.stringify(value);
      } catch(err) {
        emitter.emit('error', err);
        if (cb) {
          return cb(err);
        } else {
          return;
        }
      }

      cache[filename] = json;

      fs.writeFile(filename, json, (err) => {
        if (err) {
          emitter.emit('error', err);
        }

        if (cb) {
          cb(err);
        }
      });
    },
    invalidate(key, cb) {
      const filename = path.join(dirname, generateFilenameFromCacheKey(key));
      cache[filename] = undefined;

      fs.unlink(filename, (err) => {
        if (err) {
          // Cache misses are represented by missing files, so we can ignore this
          if (err.code === 'ENOENT') {
            if (cb) {
              return cb(null);
            }
            return;
          }

          emitter.emit('error', err);
          if (cb) {
            return cb(err);
          }
        }

        if (cb) {
          cb(null);
        }
      });
    },
    on: emitter.on.bind(emitter),
    once: emitter.once.bind(emitter),
    off: emitter.removeListener.bind(emitter)
  }
}<|endoftext|>


<commit_before>module.exports = {
  serviceName: 'Apply for BC Health Care',
  progressStep1: 'Prepare',
  progressStep2: 'Personal Info',
  progressStep3: 'Contact Info',
  progressStep4: 'Review & Submit'
}<commit_msg>Changed service name to "Apply for MSP" <commit_after>module.exports = {
  serviceName: 'Apply for MSP',
  progressStep1: 'Prepare',
  progressStep2: 'Personal Info',
  progressStep3: 'Contact Info',
  progressStep4: 'Review & Submit'
}
<|endoftext|>


<commit_before>(function(describe){
    "use strict";
    describe("chu controllers test suite", function(){
        var createController, $scope, $stateParams, $httpBackend, $state, adminApi;
        var formService, SERVER_URL;

        beforeEach(function(){
            module("mflAdminApp");
            inject(["$rootScope", "$controller", "$stateParams", "$httpBackend",
                   "$state", "adminApi","mfl.common.forms.changes","SERVER_URL",
                   function($rootScope, $controller,_$stateParams,
                    _$httpBackend, _$state, _adminApi, frm, _SERVER_URL){
                $scope = $rootScope.$new();
                SERVER_URL = _SERVER_URL;
                $httpBackend = _$httpBackend;
                $stateParams = _$stateParams;
                $state = _$state;
                adminApi = _adminApi;
                formService = frm;
                var data = {
                    $scope: $scope
                };
                createController = function(ctrl, params){
                    return $controller(ctrl, _.extend(data, params));

                };
            }]);
        });

        afterEach(function(){
            $httpBackend.verifyNoOutstandingRequest();
        });

        it("should have `mfl.setup.controller.chuStatus.list` defined",
           function(){
                var ctrl = createController("mfl.setup.controller.chuStatus.list", {});
                expect(ctrl).toBeDefined();
            });

        it("should have `mfl.setup.controller.chuStatus.view` defined",
           function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var ctrl = createController("mfl.setup.controller.chuStatus.view", dt);
                expect(ctrl).toBeDefined();
            });
        it("should view a chuStatus: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $httpBackend.flush();
                expect($scope.chuStatus).toEqual(res);
            });

        it("should view a chuStatus: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should delete chuStatus: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                spyOn($state, "go");
                var res = {mgs: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.deleteChuStatus(1);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_status");
            });

        it("should delete chuStatus: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.deleteChuStatus(1);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuStatus: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "Ok"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.updateChuStatus(1, form);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_status");
            });

        it("should update chuStatus: fail",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.updateChuStatus(1, form);
                $httpBackend.flush();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_status");
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuStatus: no changes",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.updateChuStatus(1, form);
                expect($httpBackend.flush).toThrow();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_status");
            });
        it("should have `mfl.setup.controller.chuStatus.create` defined",
           function(){
                var ctrl = createController("mfl.setup.controller.chuStatus.create");
                expect(ctrl).toBeDefined();
            });

        it("should create chuStatus: success",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/statuses/").respond(
                200, {});
                createController("mfl.setup.controller.chuStatus.create", {});
                $scope.createChuStatus({name: "Testing"});
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_status");
            });

        it("should create chuStatus: fail",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/statuses/").respond(
                500, {error: "error"});
                createController("mfl.setup.controller.chuStatus.create", {});
                $scope.createChuStatus({name: "Testing"});
                $httpBackend.flush();
                expect($scope.alert).toEqual("error");
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_status");
            });

        it("should have `mfl.setup.controller.chuApprover.list` defined",
           function(){
                var ctrl = createController("mfl.setup.controller.chuApprover.list", {});
                expect(ctrl).toBeDefined();
            });

        it("should have `mfl.setup.controller.chuApprover.view` defined",
           function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var ctrl = createController("mfl.setup.controller.chuApprover.view", dt);
                expect(ctrl).toBeDefined();
            });
        it("should view a chuApprover: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $httpBackend.flush();
                expect($scope.chuApprovers).toEqual(res);
            });

        it("should view a chuApprover: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should delete chuApprover: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                spyOn($state, "go");
                var res = {mgs: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.deleteChuApprovers(1);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_approvers");
            });

        it("should delete chuApprover: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.deleteChuApprovers(1);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuApprover: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "Ok"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.updateChuApprovers(1, form);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_approvers");
            });

        it("should update chuApprover: fail",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.updateChuApprovers(1, form);
                $httpBackend.flush();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_approvers");
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuApprover: no changes",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.updateChuApprovers(1, form);
                expect($httpBackend.flush).toThrow();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_approvers");
            });
        it("should have `mfl.setup.controller.chuApprover.create` defined",
           function(){
                var ctrl = createController("mfl.setup.controller.chuApprover.create");
                expect(ctrl).toBeDefined();
            });

        it("should create chuApprover: success",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/approvers/").respond(
                200, {});
                createController("mfl.setup.controller.chuApprover.create", {});
                $scope.createChuApprovers({name: "Testing"});
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_approvers");
            });

        it("should create chuApprover: fail",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/approvers/").respond(
                500, {error: "error"});
                createController("mfl.setup.controller.chuApprover.create", {});
                $scope.createChuApprovers({name: "Testing"});
                $httpBackend.flush();
                expect($scope.alert).toEqual("error");
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_approvers");
            });
    });
})(describe);
<commit_msg>CHU Approvers and Statuses tests<commit_after>(function(describe){
    "use strict";
    describe("chu controllers test suite", function(){
        var createController, $scope, $stateParams, $httpBackend, $state, adminApi;
        var formService, SERVER_URL;

        beforeEach(function(){
            module("mflAdminApp");
            inject(["$rootScope", "$controller", "$stateParams", "$httpBackend",
                   "$state", "adminApi","mfl.common.forms.changes","SERVER_URL",
                   function($rootScope, $controller,_$stateParams,
                    _$httpBackend, _$state, _adminApi, frm, _SERVER_URL){
                $scope = $rootScope.$new();
                SERVER_URL = _SERVER_URL;
                $httpBackend = _$httpBackend;
                $stateParams = _$stateParams;
                $state = _$state;
                adminApi = _adminApi;
                formService = frm;
                var data = {
                    $scope: $scope
                };
                createController = function(ctrl, params){
                    return $controller(ctrl, _.extend(data, params));

                };
            }]);
        });

        afterEach(function(){
            $httpBackend.verifyNoOutstandingRequest();
        });

        it("should have `mfl.setup.controller.chuStatus.list` defined",
           function(){
                var ctrl = createController("mfl.setup.controller.chuStatus.list", {});
                expect(ctrl).toBeDefined();
            });

        it("should have `mfl.setup.controller.chuStatus.view` defined",
           function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var ctrl = createController("mfl.setup.controller.chuStatus.view", dt);
                expect(ctrl).toBeDefined();
            });
        it("should view a chuStatus: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $httpBackend.flush();
                expect($scope.chuStatus).toEqual(res);
            });

        it("should view a chuStatus: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should delete chuStatus: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                spyOn($state, "go");
                var res = {mgs: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.deleteChuStatus(1);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_status");
            });

        it("should delete chuStatus: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.deleteChuStatus(1);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuStatus: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "Ok"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.updateChuStatus(1, form);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_status");
            });

        it("should update chuStatus: fail",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.updateChuStatus(1, form);
                $httpBackend.flush();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_status");
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuStatus: no changes",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/statuses/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/statuses/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuStatus.view", dt);
                $scope.updateChuStatus(1, form);
                expect($httpBackend.flush).toThrow();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_status");
            });

        it("should create chuStatus: success",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/statuses/").respond(
                200, {});
                createController("mfl.setup.controller.chuStatus.view", {});
                $scope.createChuStatus({name: "Testing"});
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_status");
            });

        it("should create chuStatus: fail",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/statuses/").respond(
                500, {error: "error"});
                createController("mfl.setup.controller.chuStatus.view", {});
                $scope.createChuStatus({name: "Testing"});
                $httpBackend.flush();
                expect($scope.alert).toEqual("error");
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_status");
            });

        it("should have `mfl.setup.controller.chuApprover.list` defined",
           function(){
                var ctrl = createController("mfl.setup.controller.chuApprover.list", {});
                expect(ctrl).toBeDefined();
            });

        it("should have `mfl.setup.controller.chuApprover.view` defined",
           function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var ctrl = createController("mfl.setup.controller.chuApprover.view", dt);
                expect(ctrl).toBeDefined();
            });
        it("should view a chuApprover: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $httpBackend.flush();
                expect($scope.chuApprovers).toEqual(res);
            });

        it("should view a chuApprover: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should delete chuApprover: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                spyOn($state, "go");
                var res = {mgs: "ok"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.deleteChuApprovers(1);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_approvers");
            });

        it("should delete chuApprover: error",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectDELETE(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.deleteChuApprovers(1);
                $httpBackend.flush();
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuApprover: success",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {msg: "Ok"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.updateChuApprovers(1, form);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_approvers");
            });

        it("should update chuApprover: fail",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {name : "Antony"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.updateChuApprovers(1, form);
                $httpBackend.flush();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_approvers");
                expect($scope.alert).toEqual(res.error);
            });

        it("should update chuApprover: no changes",function(){
                var dt = {
                    $stateParams: {id: 1}
                };
                var res = {error: "error"};
                var form = {};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/chul/approvers/1/").respond(
                200, res);
                $httpBackend.expectPATCH(SERVER_URL+"api/chul/approvers/1/").respond(
                500, res);
                createController("mfl.setup.controller.chuApprover.view", dt);
                $scope.updateChuApprovers(1, form);
                expect($httpBackend.flush).toThrow();
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_approvers");
            });

        it("should create chuApprover: success",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/approvers/").respond(
                200, {});
                createController("mfl.setup.controller.chuApprover.view", {});
                $scope.createChuApprovers({name: "Testing"});
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("setup.chu_approvers");
            });

        it("should create chuApprover: fail",function(){
                spyOn($state, "go");
                $httpBackend.expectPOST(SERVER_URL+"api/chul/approvers/").respond(
                500, {error: "error"});
                createController("mfl.setup.controller.chuApprover.view", {});
                $scope.createChuApprovers({name: "Testing"});
                $httpBackend.flush();
                expect($scope.alert).toEqual("error");
                expect($state.go).not.toHaveBeenCalledWith("setup.chu_approvers");
            });
    });
})(describe);
<|endoftext|>


<commit_before>/*
---

name: Scroller.Engine.scroller

description: Provides a wrapper for the scroller scroller.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Scroller.Engine

provides:
	- Scroller.Engine.scroller

...
*/

(function() {

iScroll.prototype._currentSize = {x: 0, y: 0};

var _checkDOMChanges = iScroll.prototype._checkDOMChanges;

iScroll.prototype._checkDOMChanges = function() {

	_checkDOMChanges.call(this);

	var size = this.wrapper.getSize();
	if (this._currentSize.x != size.x || this._currentSize.y != size.y) {
		this._currentSize = size;
		this.refresh();
	}
};

})();

/**
 * @name  Scroller.Engine.Native
 * @class Provides an engine that uses the iScroll scroller.
 *
 * @classdesc
 *
 * [TODO: Introduction]
 * [TODO: Events]
 * [TODO: Options]
 *
 * @author  Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
 * @version 0.1
 */
Moobile.Scroller.Engine.IScroll = new Class( /** @lends Scroller.Engine.scroller.prototype */ {

	Extends: Moobile.Scroller.Engine,

	scroller: null,

	scrolling: false,

	/**
	 * Initializes this scroller engine.
	 *
	 * This method will creates a `wrapper` element and wrap it around the
	 * given `content` element.
	 *
	 * @param {Element}	[content] The Element, element id or string.
	 * @param {Object}  [options] The options.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	initialize: function(content, options) {

		this.parent(content, options);

		this.wrapper.addClass('scroll-engine-scroller');

		var options = {
			hScroll: this.options.scrollX,
			vScroll: this.options.scrollY,
			momentum: this.options.momentum,
			bounce: this.options.momentum,
			hScrollbar: this.options.momentum,
			vScrollbar: this.options.momentum,
			useTransform: true,
			useTransition: true,
			hideScrollbar: true,
			fadeScrollbar: true,
			checkDOMChanges: true,
			snap: false,
			onScrollStart: this.bound('onStart'),
			onScrollMove: this.bound('onMove'),
			onTouchEnd: this.bound('onEnd')
		};

		this.scroller = new iScroll(this.wrapper, options);

		window.addEvent('orientationchange', this.bound('onOrientationChange'));

		return this;
	},

	/**
	 * Destroys this scroller engine.
	 *
	 * This method will remove the wrapper without removing the content
	 * element.
	 *
	 * @return {Scroller.Engine} This scroller engine.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	destroy: function() {
		this.scroller.destroy();
		this.parent();
		return this;
	},

	/**
	 * Scrolls to a set of coordinates.
	 *
	 * @param {Number} x      The x coordinate.
	 * @param {Number} y      The y coordinate.
	 * @param {Number} [time] The duration of the scroll.
	 *
	 * @return {Scroller.Engine} This scroller engine.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	scrollTo: function(x, y, time, relative) {
		(function() { this.scroller.scrollTo(x, -y, time, relative); }).delay(5, this);
		return this;
	},

	/**
	 * Scrolls to an element.
	 *
	 * @param {Element} element The element to scroll to.
	 * @param {Number}  [time]  The duration of the scroll.
	 *
	 * @return {Scroller.Engine} This scroller engine.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	scrollToElement: function(element, time) {
		(function() { this.scroller.scrollToElement(element, time); }).delay(5, this);
		return this;
	},

	/**
	 * Refreshes this scroller engine.
	 *
	 * @return {Scroller} This scroller.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	refresh: function() {
		this.scroller.refresh();
		return this;
	},

	/**
	 * Returns the size.
	 *
	 * This method will return the wrapper's size as an object with two keys,
	 * `x` which indicates the width and `y` which indicates the height.
	 *
	 * @return {Object} The size.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	getSize: function() {
		return this.wrapper.getSize();
	},

	/**
	 * Returns the current scroll position.
	 *
	 * This method will return the current scroll position as an object
	 * with two keys, `x` which indicates the horizontal scroll and `y` which
	 * indicates the vertical scroll of this entity.
	 *
	 * @return {Object} The scroll position.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	getScroll: function() {
		return {x: this.scroller.x, y: this.scroller.y};
	},

	/**
	 * Returns size including the scrolling area.
	 *
	 * This method will return the content's size as an object with two keys,
	 * `x` which indicates the width and `y` which indicates the height.
	 *
	 * @return {Object} The size including the scrolling area.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	getScrollSize: function() {
		return this.content.getScrollSize();
	},

	onStart: function() {
		this.scrolling = true;
		this.fireEvent('start');
	},

	onMove: function() {
		if (this.scrolling) {
			this.fireEvent('move');
		}
	},

	onEnd: function() {
		if (this.scrolling) {
			this.scrolling = false;
			this.fireEvent('end');
		}
	},

	onOrientationChange: function() {
		this.refresh();
	}

});

Moobile.Scroller.Engine.IScroll.supportsCurrentPlatform = function() {
	return true;
};
<commit_msg>Fixed engine name in css class<commit_after>/*
---

name: Scroller.Engine.scroller

description: Provides a wrapper for the scroller scroller.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Scroller.Engine

provides:
	- Scroller.Engine.scroller

...
*/

(function() {

iScroll.prototype._currentSize = {x: 0, y: 0};

var _checkDOMChanges = iScroll.prototype._checkDOMChanges;

iScroll.prototype._checkDOMChanges = function() {

	_checkDOMChanges.call(this);

	var size = this.wrapper.getSize();
	if (this._currentSize.x != size.x || this._currentSize.y != size.y) {
		this._currentSize = size;
		this.refresh();
	}
};

})();

/**
 * @name  Scroller.Engine.Native
 * @class Provides an engine that uses the iScroll scroller.
 *
 * @classdesc
 *
 * [TODO: Introduction]
 * [TODO: Events]
 * [TODO: Options]
 *
 * @author  Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
 * @version 0.1
 */
Moobile.Scroller.Engine.IScroll = new Class( /** @lends Scroller.Engine.scroller.prototype */ {

	Extends: Moobile.Scroller.Engine,

	scroller: null,

	scrolling: false,

	/**
	 * Initializes this scroller engine.
	 *
	 * This method will creates a `wrapper` element and wrap it around the
	 * given `content` element.
	 *
	 * @param {Element}	[content] The Element, element id or string.
	 * @param {Object}  [options] The options.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	initialize: function(content, options) {

		this.parent(content, options);

		this.wrapper.addClass('scroll-engine-iscroll');

		var options = {
			hScroll: this.options.scrollX,
			vScroll: this.options.scrollY,
			momentum: this.options.momentum,
			bounce: this.options.momentum,
			hScrollbar: this.options.momentum,
			vScrollbar: this.options.momentum,
			useTransform: true,
			useTransition: true,
			hideScrollbar: true,
			fadeScrollbar: true,
			checkDOMChanges: true,
			snap: false,
			onScrollStart: this.bound('onStart'),
			onScrollMove: this.bound('onMove'),
			onTouchEnd: this.bound('onEnd')
		};

		this.scroller = new iScroll(this.wrapper, options);

		window.addEvent('orientationchange', this.bound('onOrientationChange'));

		return this;
	},

	/**
	 * Destroys this scroller engine.
	 *
	 * This method will remove the wrapper without removing the content
	 * element.
	 *
	 * @return {Scroller.Engine} This scroller engine.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	destroy: function() {
		this.scroller.destroy();
		this.parent();
		return this;
	},

	/**
	 * Scrolls to a set of coordinates.
	 *
	 * @param {Number} x      The x coordinate.
	 * @param {Number} y      The y coordinate.
	 * @param {Number} [time] The duration of the scroll.
	 *
	 * @return {Scroller.Engine} This scroller engine.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	scrollTo: function(x, y, time, relative) {
		(function() { this.scroller.scrollTo(x, -y, time, relative); }).delay(5, this);
		return this;
	},

	/**
	 * Scrolls to an element.
	 *
	 * @param {Element} element The element to scroll to.
	 * @param {Number}  [time]  The duration of the scroll.
	 *
	 * @return {Scroller.Engine} This scroller engine.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	scrollToElement: function(element, time) {
		(function() { this.scroller.scrollToElement(element, time); }).delay(5, this);
		return this;
	},

	/**
	 * Refreshes this scroller engine.
	 *
	 * @return {Scroller} This scroller.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	refresh: function() {
		this.scroller.refresh();
		return this;
	},

	/**
	 * Returns the size.
	 *
	 * This method will return the wrapper's size as an object with two keys,
	 * `x` which indicates the width and `y` which indicates the height.
	 *
	 * @return {Object} The size.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	getSize: function() {
		return this.wrapper.getSize();
	},

	/**
	 * Returns the current scroll position.
	 *
	 * This method will return the current scroll position as an object
	 * with two keys, `x` which indicates the horizontal scroll and `y` which
	 * indicates the vertical scroll of this entity.
	 *
	 * @return {Object} The scroll position.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	getScroll: function() {
		return {x: this.scroller.x, y: this.scroller.y};
	},

	/**
	 * Returns size including the scrolling area.
	 *
	 * This method will return the content's size as an object with two keys,
	 * `x` which indicates the width and `y` which indicates the height.
	 *
	 * @return {Object} The size including the scrolling area.
	 *
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	getScrollSize: function() {
		return this.content.getScrollSize();
	},

	onStart: function() {
		this.scrolling = true;
		this.fireEvent('start');
	},

	onMove: function() {
		if (this.scrolling) {
			this.fireEvent('move');
		}
	},

	onEnd: function() {
		if (this.scrolling) {
			this.scrolling = false;
			this.fireEvent('end');
		}
	},

	onOrientationChange: function() {
		this.refresh();
	}

});

Moobile.Scroller.Engine.IScroll.supportsCurrentPlatform = function() {
	return true;
};
<|endoftext|>


<commit_before>import { translate } from '../../../../../common/i18n';

Blockly.Blocks.notify_telegram = {
    init() {
        this.jsonInit({
            message0: translate('Notify Telegram %1 Access Token: %2 Chat ID: %3 Message: %4'),
            args0   : [
                {
                    type: 'input_dummy',
                },
                {
                    type: 'input_value',
                    name: 'TELEGRAM_ACCESS_TOKEN',
                },
                {
                    type: 'input_value',
                    name: 'TELEGRAM_CHAT_ID',
                },
                {
                    type: 'input_value',
                    name: 'TELEGRAM_MESSAGE',
                },
            ],
            colour           : '#dedede',
            inputsInline     : true,
            previousStatement: null,
            nextStatement    : null,
            tooltip          : translate('Sends a message to Telegram'),
        });
    },
};

Blockly.JavaScript.notify_telegram = block => {
    const accessToken = Blockly.JavaScript.valueToCode(block, 'TELEGRAM_ACCESS_TOKEN') || '';
    const chatId = Blockly.JavaScript.valueToCode(block, 'TELEGRAM_CHAT_ID') || '';
    const message = Blockly.JavaScript.valueToCode(block, 'TELEGRAM_MESSAGE') || '';

    if (!accessToken || !chatId || !message) {
        return '';
    }

    const code = `Bot.notifyTelegram(${accessToken}, ${chatId}, ${message});\n`;
    return code;
};
<commit_msg>Return ORDER_ATOMIC for valueToCode<commit_after>import { translate } from '../../../../../common/i18n';
import { notify } from '../../../../bot/broadcast';

Blockly.Blocks.notify_telegram = {
    init() {
        this.jsonInit({
            message0: translate('Notify Telegram %1 Access Token: %2 Chat ID: %3 Message: %4'),
            args0   : [
                {
                    type: 'input_dummy',
                },
                {
                    type: 'input_value',
                    name: 'TELEGRAM_ACCESS_TOKEN',
                },
                {
                    type: 'input_value',
                    name: 'TELEGRAM_CHAT_ID',
                },
                {
                    type: 'input_value',
                    name: 'TELEGRAM_MESSAGE',
                },
            ],
            colour           : '#dedede',
            inputsInline     : true,
            previousStatement: null,
            nextStatement    : null,
            tooltip          : translate('Sends a message to Telegram'),
        });
    },
};

Blockly.JavaScript.notify_telegram = block => {
    const accessToken =
        Blockly.JavaScript.valueToCode(block, 'TELEGRAM_ACCESS_TOKEN', Blockly.JavaScript.ORDER_ATOMIC) || '';
    const chatId = Blockly.JavaScript.valueToCode(block, 'TELEGRAM_CHAT_ID', Blockly.JavaScript.ORDER_ATOMIC) || '';
    const message = Blockly.JavaScript.valueToCode(block, 'TELEGRAM_MESSAGE', Blockly.JavaScript.ORDER_ATOMIC) || '';

    if (!accessToken || !chatId || !message) {
        return '';
    }

    const code = `Bot.notifyTelegram(${accessToken}, ${chatId}, ${message});\n`;
    return code;
};
<|endoftext|>


<commit_before>'use strict';

goog.provide('Blockly.Python.hedgehog');

goog.require('Blockly.Python');

// set indentaion to 4 spaces
Blockly.Python.INDENT = '    ';

Blockly.Python['hedgehog_scope'] = function(block) {
    var statements = Blockly.Python.statementToCode(block, 'IN');
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'with connect(emergency=15) as hedgehog:\n' + statements;
    return code;
};

Blockly.Python['hedgehog_turn'] = function(block) {
    var port1 = block.getFieldValue('MOTOR1');
    var port2 = block.getFieldValue('MOTOR2');
    var dir = block.getFieldValue('DIR');
    var time = Blockly.Python.valueToCode(block, 'TIME', Blockly.Python.ORDER_ATOMIC);

    // imports
    Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'hedgehog.move(' + port1 + ', ' + (dir === 'RIGHT' ? '' : '-') + '1000)\n';
    code += 'hedgehog.move(' + port2 + ', ' + (dir === 'LEFT' ? '' : '-') + '1000)\n';
    code += 'sleep(' + time + ')\n\n';

    return code;
};

Blockly.Python['hedgehog_move'] = function(block) {
    var port = block.getFieldValue('PORT');
    var speed = Blockly.Python.valueToCode(block, 'SPEED', Blockly.Python.ORDER_NONE);
    var time = Blockly.Python.valueToCode(block, 'TIME', Blockly.Python.ORDER_ATOMIC);

    // imports
    Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'hedgehog.move(' + port + ', ' + speed + ')' + '\nsleep(' + time + ')\n\n';
    return code;
};

Blockly.Python['hedgehog_speed'] = function(block) {
    var speed = block.getFieldValue('SPEED');
    return [speed, Blockly.Python.ORDER_NONE];
};

Blockly.Python['hedgehog_servo'] = function(block) {
    var port = block.getFieldValue('PORT');
    var angle = Blockly.Python.valueToCode(block, 'ANGLE', Blockly.Python.ORDER_NONE);

    // imports
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'hedgehog.set_servo(' + port + ', ' + angle + '*22' + ')\n';
    return code;
};

Blockly.Python['hedgehog_degrees'] = function(block) {
    var angle = block.getFieldValue('ANGLE');

    // imports
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    return [angle, Blockly.Python.ORDER_NONE];
};

Blockly.Python['hedgehog_read_analog'] = function(block) {
    var port = block.getFieldValue('PORT');

    var code = 'hedgehog.get_analog(' + port + ')';
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Python['hedgehog_read_digital'] = function(block) {
    var port = block.getFieldValue('PORT');

    var code = 'hedgeho.get_digital(' + port + ')';
    return [code, Blockly.Python.ORDER_NONE];
};
<commit_msg>fix servo block<commit_after>'use strict';

goog.provide('Blockly.Python.hedgehog');

goog.require('Blockly.Python');

// set indentaion to 4 spaces
Blockly.Python.INDENT = '    ';

Blockly.Python['hedgehog_scope'] = function(block) {
    var statements = Blockly.Python.statementToCode(block, 'IN');
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'with connect(emergency=15) as hedgehog:\n' + statements;
    return code;
};

Blockly.Python['hedgehog_turn'] = function(block) {
    var port1 = block.getFieldValue('MOTOR1');
    var port2 = block.getFieldValue('MOTOR2');
    var dir = block.getFieldValue('DIR');
    var time = Blockly.Python.valueToCode(block, 'TIME', Blockly.Python.ORDER_ATOMIC);

    // imports
    Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'hedgehog.move(' + port1 + ', ' + (dir === 'RIGHT' ? '' : '-') + '1000)\n';
    code += 'hedgehog.move(' + port2 + ', ' + (dir === 'LEFT' ? '' : '-') + '1000)\n';
    code += 'sleep(' + time + ')\n\n';

    return code;
};

Blockly.Python['hedgehog_move'] = function(block) {
    var port = block.getFieldValue('PORT');
    var speed = Blockly.Python.valueToCode(block, 'SPEED', Blockly.Python.ORDER_NONE);
    var time = Blockly.Python.valueToCode(block, 'TIME', Blockly.Python.ORDER_ATOMIC);

    // imports
    Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'hedgehog.move(' + port + ', ' + speed + ')' + '\nsleep(' + time + ')\n\n';
    return code;
};

Blockly.Python['hedgehog_speed'] = function(block) {
    var speed = block.getFieldValue('SPEED');
    return [speed, Blockly.Python.ORDER_NONE];
};

Blockly.Python['hedgehog_servo'] = function(block) {
    var port = block.getFieldValue('PORT');
    var angle = Blockly.Python.valueToCode(block, 'ANGLE', Blockly.Python.ORDER_NONE);

    // imports
    Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    var code = 'hedgehog.set_servo(' + port + ', True, ' + angle + '*22' + ')\n';
    code += 'sleep(0.1)\n\n';
    return code;
};

Blockly.Python['hedgehog_degrees'] = function(block) {
    var angle = block.getFieldValue('ANGLE');

    // imports
    Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';

    return [angle, Blockly.Python.ORDER_NONE];
};

Blockly.Python['hedgehog_read_analog'] = function(block) {
    var port = block.getFieldValue('PORT');

    var code = 'hedgehog.get_analog(' + port + ')';
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Python['hedgehog_read_digital'] = function(block) {
    var port = block.getFieldValue('PORT');

    var code = 'hedgeho.get_digital(' + port + ')';
    return [code, Blockly.Python.ORDER_NONE];
};
<|endoftext|>


<commit_before>var apigeetool 		= require('apigeetool')
var lib				= require('../../lib')
var async           = require('async')
var lodash         = require('lodash')

var sdk 			= apigeetool.getPromiseSDK()

var adapter = function () {
	this.clean 			= clean
	this.build 			= build
	this.deploy 		= deploy
}

function build(context, resourceName, subResourceName, params, cb) {
	lib.print('meta','building app resources')
	cb()
}

function deploy(context, resourceName, subResourceName, params, cb) {
	lib.print('meta','deploying app resources')

	var config          = context.getConfig(resourceName, subResourceName)

	var items           = lib.filter_items(config.items, params)

	var deploy_info     = context.getDeploymentInfo()

	for (var i=0; i< items.length; i++) {
		lodash.merge(items[i], deploy_info)
		items[i].context = context
	}

	async.each(items, create_app, function(err){
		if(err){
			lib.print('ERROR', err)
			cb()
		} else {
			cb()
		}

	})
}

function create_app(item, callback) {
	var opts 			= item
	var context			= item.context
	delete item.context

	lodash.merge(opts, lib.normalize_data(JSON.parse(item.payload)))

	sdk.createApp(opts)
		.then(function(result){
			//cache create success
			lib.print('info', 'created app ' + item.name)
			if(item.assignResponse && item.assignResponse.length > 0){
				lib.extract_response(context, item.assignResponse, result)
			}
			callback()
		},function(err){
			//cache create failed
			lib.print('error', 'error creating app ' + item.name)
			lib.print('ERROR', err)
			callback()
		}) ;
}

function clean(context, resourceName, subResourceName, params, cb) {
	//opts = lib.build_opts(context, resourceName, subResourceName)
	lib.print('meta','cleaning app resources')

	var config          = context.getConfig(resourceName, subResourceName)

    var items           = lib.filter_items(config.items, params)

	var deploy_info     = context.getDeploymentInfo()

	for (var i=0; i< items.length; i++) {
		lodash.merge(items[i], deploy_info)
	}

	async.each(items, delete_app, function(err){
		if(err){
			lib.print('ERROR', err)
			cb()
		} else {
			cb()
		}

	})
}

function delete_app(item, callback) {
	var opts 			= item

	lodash.merge(opts, lib.normalize_data(JSON.parse(item.payload)))

	sdk.deleteApp(opts)
		.then(function(result){
			//cache create success
			lib.print('info', 'deleted app  ' + item.name)
			callback()
		},function(err){
			//cache create failed
			lib.print('error', 'error deleting app ' + item.name)
			lib.print('ERROR', err)
			callback()
		}) ;
}

exports.adapter 			= adapter
<commit_msg>update app.js , each -> eachSeries , deploy app<commit_after>var apigeetool 			= require('apigeetool')
var lib				= require('../../lib')
var async           		= require('async')
var lodash         		= require('lodash')

var sdk 			= apigeetool.getPromiseSDK()

var adapter = function () {
	this.clean 			= clean
	this.build 			= build
	this.deploy 			= deploy
}

function build(context, resourceName, subResourceName, params, cb) {
	lib.print('meta','building app resources')
	cb()
}

function deploy(context, resourceName, subResourceName, params, cb) {
	lib.print('meta','deploying app resources')

	var config          = context.getConfig(resourceName, subResourceName)

	var items           = lib.filter_items(config.items, params)

	var deploy_info     = context.getDeploymentInfo()

	for (var i=0; i< items.length; i++) {
		lodash.merge(items[i], deploy_info)
		items[i].context = context
	}

	async.eachSeries(items, create_app, function(err){
		if(err){
			lib.print('ERROR', err)
			cb()
		} else {
			cb()
		}

	})
}

function create_app(item, callback) {
	var opts 			= item
	var context			= item.context
	delete item.context

	lodash.merge(opts, lib.normalize_data(JSON.parse(item.payload)))

	sdk.createApp(opts)
		.then(function(result){
			//cache create success
			lib.print('info', 'created app ' + item.name)
			if(item.assignResponse && item.assignResponse.length > 0){
				lib.extract_response(context, item.assignResponse, result)
			}
			callback()
		},function(err){
			//cache create failed
			lib.print('error', 'error creating app ' + item.name)
			lib.print('ERROR', err)
			callback()
		}) ;
}

function clean(context, resourceName, subResourceName, params, cb) {
	//opts = lib.build_opts(context, resourceName, subResourceName)
	lib.print('meta','cleaning app resources')

	var config          = context.getConfig(resourceName, subResourceName)

    var items           = lib.filter_items(config.items, params)

	var deploy_info     = context.getDeploymentInfo()

	for (var i=0; i< items.length; i++) {
		lodash.merge(items[i], deploy_info)
	}

	async.each(items, delete_app, function(err){
		if(err){
			lib.print('ERROR', err)
			cb()
		} else {
			cb()
		}

	})
}

function delete_app(item, callback) {
	var opts 			= item

	lodash.merge(opts, lib.normalize_data(JSON.parse(item.payload)))

	sdk.deleteApp(opts)
		.then(function(result){
			//cache create success
			lib.print('info', 'deleted app  ' + item.name)
			callback()
		},function(err){
			//cache create failed
			lib.print('error', 'error deleting app ' + item.name)
			lib.print('ERROR', err)
			callback()
		}) ;
}

exports.adapter 			= adapter
<|endoftext|>


<commit_before>const SchemaFolder = require('./SchemaFolder');
const { join } = require('path');
const fs = require('fs-nextra');

class GatewayStorage {

	/**
	 * <warning>You should never create an instance of this class as it's abstract.</warning>
	 * @since 0.5.0
	 * @param {KlasaClient} client The client this GatewayStorage was created with
	 * @param {string} type The name of this GatewayStorage
	 * @param {string} [provider] The provider's name
	 * @private
	 */
	constructor(client, type, provider) {
		/**
		 * The client this GatewayStorage was created with.
		 * @since 0.5.0
		 * @name GatewayStorage#client
		 * @type {KlasaClient}
		 * @readonly
		 */
		Object.defineProperty(this, 'client', { value: client });

		/**
		 * The type of this GatewayStorage.
		 * @since 0.5.0
		 * @name GatewayStorage#type
		 * @type {string}
		 * @readonly
		 */
		Object.defineProperty(this, 'type', { value: type });

		/**
		 * The name of this instance's provider.
		 * @since 0.5.0
		 * @name GatewayStorage#providerName
		 * @type {string}
		 * @readonly
		 */
		Object.defineProperty(this, 'providerName', { value: provider || this.client.options.providers.default });

		/**
		 * @since 0.5.0
		 * @type {SchemaFolder}
		 */
		this.schema = null;

		/**
		 * @since 0.5.0
		 * @type {boolean}
		 */
		this.ready = false;
	}

	/**
	 * Where the bwd folder is located at.
	 * @since 0.5.0
	 * @type {string}
	 * @readonly
	 */
	get baseDir() {
		return join(this.client.clientBaseDir, 'bwd');
	}

	/**
	 * Where the file schema is located at.
	 * @since 0.5.0
	 * @type {string}
	 * @readonly
	 */
	get filePath() {
		return join(this.client.clientBaseDir, 'bwd', `${this.type}.schema.json`);
	}

	/**
	 * Get the provider that manages the persistent data.
	 * @since 0.5.0
	 * @type {?Provider}
	 * @readonly
	 */
	get provider() {
		return this.client.providers.get(this.providerName) || null;
	}

	/**
	 * Get this gateway's defaults.
	 * @since 0.5.0
	 * @type {Object}
	 * @readonly
	 */
	get defaults() {
		return { ...this.schema.defaults, default: true };
	}

	/**
	 * Inits the current Gateway.
	 * @since 0.5.0
	 * @param {Object} defaultSchema The default schema
	 */
	async init(defaultSchema) {
		if (this.ready) throw new Error(`[INIT] ${this} has already initialized.`);
		if (!this.provider) throw new Error(`This provider (${this.providerName}) does not exist in your system.`);
		this.ready = true;

		// Init the Schema
		await fs.ensureDir(this.baseDir);
		let schema;
		try {
			schema = await fs.readJSON(this.filePath);
		} catch (error) {
			// Make the schema the default one
			schema = defaultSchema;

			// Check if the file exists
			const fileWritten = await fs.pathExists(this.filePath);

			// If the file is written, there must be an issue with the file, emit an
			// error instead of overwritting it (which would result to data loss). If
			// the file does not exist, write the default schema.
			if (fileWritten) this.client.emit('error', error);
			else await fs.outputJSONAtomic(this.filePath, defaultSchema);
		}

		this.schema = new SchemaFolder(this.client, this, schema, null, '');

		// Init the table
		const hasTable = await this.provider.hasTable(this.type);
		if (!hasTable) await this.provider.createTable(this.type);
	}

}

module.exports = GatewayStorage;
<commit_msg>make init more performant<commit_after>const SchemaFolder = require('./SchemaFolder');
const { join } = require('path');
const fs = require('fs-nextra');

class GatewayStorage {

	/**
	 * <warning>You should never create an instance of this class as it's abstract.</warning>
	 * @since 0.5.0
	 * @param {KlasaClient} client The client this GatewayStorage was created with
	 * @param {string} type The name of this GatewayStorage
	 * @param {string} [provider] The provider's name
	 * @private
	 */
	constructor(client, type, provider) {
		/**
		 * The client this GatewayStorage was created with.
		 * @since 0.5.0
		 * @name GatewayStorage#client
		 * @type {KlasaClient}
		 * @readonly
		 */
		Object.defineProperty(this, 'client', { value: client });

		/**
		 * The type of this GatewayStorage.
		 * @since 0.5.0
		 * @name GatewayStorage#type
		 * @type {string}
		 * @readonly
		 */
		Object.defineProperty(this, 'type', { value: type });

		/**
		 * The name of this instance's provider.
		 * @since 0.5.0
		 * @name GatewayStorage#providerName
		 * @type {string}
		 * @readonly
		 */
		Object.defineProperty(this, 'providerName', { value: provider || this.client.options.providers.default });

		/**
		 * @since 0.5.0
		 * @type {SchemaFolder}
		 */
		this.schema = null;

		/**
		 * @since 0.5.0
		 * @type {boolean}
		 */
		this.ready = false;
	}

	/**
	 * Where the bwd folder is located at.
	 * @since 0.5.0
	 * @type {string}
	 * @readonly
	 */
	get baseDir() {
		return join(this.client.clientBaseDir, 'bwd');
	}

	/**
	 * Where the file schema is located at.
	 * @since 0.5.0
	 * @type {string}
	 * @readonly
	 */
	get filePath() {
		return join(this.client.clientBaseDir, 'bwd', `${this.type}.schema.json`);
	}

	/**
	 * Get the provider that manages the persistent data.
	 * @since 0.5.0
	 * @type {?Provider}
	 * @readonly
	 */
	get provider() {
		return this.client.providers.get(this.providerName) || null;
	}

	/**
	 * Get this gateway's defaults.
	 * @since 0.5.0
	 * @type {Object}
	 * @readonly
	 */
	get defaults() {
		return { ...this.schema.defaults, default: true };
	}

	/**
	 * Inits the current Gateway.
	 * @since 0.5.0
	 * @param {Object} defaultSchema The default schema
	 */
	async init(defaultSchema) {
		if (this.ready) throw new Error(`[INIT] ${this} has already initialized.`);
		const { provider } = this;
		if (!provider) throw new Error(`This provider (${this.providerName}) does not exist in your system.`);
		this.ready = true;

		// Init the Schema
		await fs.ensureDir(this.baseDir);
		let schema;
		try {
			schema = await fs.readJSON(this.filePath);
		} catch (error) {
			// Make the schema the default one
			schema = defaultSchema;

			// Check if the file exists
			const fileWritten = await fs.pathExists(this.filePath);

			// If the file is written, there must be an issue with the file, emit an
			// error instead of overwritting it (which would result to data loss). If
			// the file does not exist, write the default schema.
			if (fileWritten) this.client.emit('error', error);
			else await fs.outputJSONAtomic(this.filePath, defaultSchema);
		}

		this.schema = new SchemaFolder(this.client, this, schema, null, '');

		// Init the table
		const hasTable = await provider.hasTable(this.type);
		if (!hasTable) await provider.createTable(this.type);
	}

}

module.exports = GatewayStorage;
<|endoftext|>


<commit_before>import {F, C} from '../../parsec/index';

// resolve meanningles characters as an empty string
// also accept an empty string
function blank() {
    return C.charIn(' \t').rep().thenReturns(' ');
}

//todo: escape characters
function rawTextUntilChar(charList, allowVoid = false) {
    if (allowVoid) {
        return C.charNotIn(charList).optrep().map(chars => chars.join(''));
    } else {
        return C.charNotIn(charList).rep().map(chars => chars.join(''));
    }
}

function rawTextUntil(stop) {
    return F.not(stop).rep().map(chars => chars.join(''));
}

function eol() {
    return C.char('\n').or(C.string('\r\n'));
}

//A blank line in the code(that is 2 consecutive \n) is a single end of line (lineFeed) in the rendition
function lineFeed() {
    return eol().then(blank()).then(eol()).thenReturns({
        linefeed: undefined,
    });
}

//accept 1 tab or 4 spaces. Space may be unbreakable
function fourSpacesBlock() {
    return C.char('\t').or(C.charIn(' \u00A0').occurrence(4));
}

export default {
    blank,
    rawTextUntilChar,
    rawTextUntil,
    eol,
    lineFeed,
    fourSpacesBlock,
};
<commit_msg>Reverting a355d4715a3e5ba424cfe665dad38fdf5ae11d12<commit_after>import {F, C} from '../../parsec/index';

// resolve meanningles characters as an empty string
// also accept an empty string
function blank() {
    // TODO: why not return C.charIn(' \t').rep().thenReturns(' ');
    return C.charIn(' \t').optrep().thenReturns('');
}

//todo: escape characters
function rawTextUntilChar(charList, allowVoid = false) {
    if (allowVoid) {
        return C.charNotIn(charList).optrep().map(chars => chars.join(''));
    } else {
        return C.charNotIn(charList).rep().map(chars => chars.join(''));
    }
}

function rawTextUntil(stop) {
    return F.not(stop).rep().map(chars => chars.join(''));
}

function eol() {
    return C.char('\n').or(C.string('\r\n'));
}

//A blank line in the code(that is 2 consecutive \n) is a single end of line (lineFeed) in the rendition
function lineFeed() {
    return eol().then(blank()).then(eol()).thenReturns({
        linefeed: undefined,
    });
}

//accept 1 tab or 4 spaces. Space may be unbreakable
function fourSpacesBlock() {
    return C.char('\t').or(C.charIn(' \u00A0').occurrence(4));
}

export default {
    blank,
    rawTextUntilChar,
    rawTextUntil,
    eol,
    lineFeed,
    fourSpacesBlock,
};
<|endoftext|>