text:
;(function($B){

eval($B.InjectBuiltins())

var $ObjectDict = object.$dict

var $StringDict = {__class__:$B.$type,
    __dir__:$ObjectDict.__dir__,
    __name__:'str',
    $native:true
}

$StringDict.__add__ = function(self,other){
    if(!(typeof other==="string")){
        try{return getattr(other,'__radd__')(self)}
        catch(err){throw _b_.TypeError(
            "Can't convert "+$B.get_class(other).__name__+" to str implicitely")}
    }
    return self+other
}

$StringDict.__contains__ = function(self,item){
    if(!(typeof item==="string")){throw _b_.TypeError(
         "'in <string>' requires string as left operand, not "+item.__class__)}
    var nbcar = item.length
    if(nbcar==0) return true // a string contains the empty string
    if(self.length==0) return nbcar==0
    for(var i=0, _len_i = self.length; i < _len_i;i++){
        if(self.substr(i,nbcar)==item) return true
    }
    return false
}

$StringDict.__delitem__ = function(){
    throw _b_.TypeError("'str' object doesn't support item deletion")
}

// __dir__must be assigned explicitely because attribute resolution for builtin
// classes doesn't use __mro__
$StringDict.__dir__ = $ObjectDict.__dir__

$StringDict.__eq__ = function(self,other){
    if(other===undefined){ // compare object "self" to class "str"
        return self===str
    }
    if (_b_.isinstance(other, _b_.str)) {
       return other.valueOf() == self.valueOf()
    }
    return other===self.valueOf()
}

$StringDict.__format__ = function(self,arg){
    var _fs = $FormattableString(self.valueOf())
    var args=[], pos=0
    // we don't need the first item (ie, self)
    for (var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]}
    return _fs.strformat(arg)
}

$StringDict.__getitem__ = function(self,arg){
    if(isinstance(arg,_b_.int)){
        var pos = arg
        if(arg<0) pos+=self.length
        if(pos>=0 && pos<self.length) return self.charAt(pos)
        throw _b_.IndexError('string index out of range')
    }
    if(isinstance(arg,slice)) {
        var step = arg.step===None ? 1 : arg.step
        if(step>0){
            var start = arg.start===None ? 0 : arg.start
            var stop = arg.stop===None ? getattr(self,'__len__')() : arg.stop
        }else{
            var start = arg.start===None ? getattr(self,'__len__')()-1 : arg.start
            var stop = arg.stop===None ? 0 : arg.stop
        }
        if(start<0) start+=self.length
        if(stop<0) stop+=self.length
        var res = '',i=null
        if(step>0){
            if(stop<=start) return ''
            for(var i=start;i<stop;i+=step) res += self.charAt(i)
        } else {
            if(stop>=start) return ''
            for(var i=start;i>=stop;i+=step) res += self.charAt(i)
        }
        return res
    }
    if(isinstance(arg,bool)) return self.__getitem__(_b_.int(arg))
}

$StringDict.__hash__ = function(self) {
  if (self === undefined) {
     return $StringDict.__hashvalue__ || $B.$py_next_hash--  // for hash of string type (not instance of string)
  }

  //http://stackoverflow.com/questions/2909106/python-whats-a-correct-and-good-way-to-implement-hash
  // this implementation for strings maybe good enough for us..

  var hash=1;
  for(var i=0, _len_i = self.length; i < _len_i; i++) {
      hash=(101*hash + self.charCodeAt(i)) & 0xFFFFFFFF
  }

  return hash
}

$StringDict.__init__ = function(self,arg){
    self.valueOf = function(){return arg}
    self.toString = function(){return arg}
    return _b_.None
}

var $str_iterator = $B.$iterator_class('str_iterator')
$StringDict.__iter__ = function(self){
    var items = self.split('') // list of all characters in string
    return $B.$iterator(items,$str_iterator)
}

$StringDict.__len__ = function(self){return self.length}

var kwarg_key = new RegExp('([^\\)]*)\\)')

var NotANumber = function() {
    this.name = 'NotANumber'
}

var number_check=function(s) {
    if(!isinstance(s,[_b_.int,_b_.float])){
        throw new NotANumber()
    }
}

var get_char_array = function(size, char) {
    if (size <= 0)
        return ''
    return new Array(size + 1).join(char)
}

var format_padding = function(s, flags, minus_one) {
    var padding = flags.padding
    if (!padding) {  // undefined
        return s
    }
    s = s.toString()
    padding = parseInt(padding, 10)
    if (minus_one) {  // numeric formatting where sign goes in front of padding
        padding -= 1
    }
    if (!flags.left) {
        return get_char_array(padding - s.length, flags.pad_char) + s
    } else {
        // left adjusted
        return s + get_char_array(padding - s.length, flags.pad_char)
    }
}

var format_int_precision = function(val, flags) {
    var precision = flags.precision
    if (!precision) {
        return val.toString()
    }
    precision = parseInt(precision, 10)
    var s
    if (val.__class__ === $B.LongInt.$dict) {
       s=$B.LongInt.$dict.to_base(val, 10)
    } else {
       s=val.toString()
    }
    var sign = s[0]
    if (s[0] === '-') {
        return '-' + get_char_array(precision - s.length + 1, '0') + s.slice(1)
    }
    return get_char_array(precision - s.length, '0') + s
}

var format_float_precision = function(val, upper, flags, modifier) {
    var precision = flags.precision
    // val is a float
    if (isFinite(val)) {
        val = modifier(val, precision, flags, upper)
        return val
    }
    if (val === Infinity) {
        val = 'inf'
    } else if (val === -Infinity) {
        val = '-inf'
    } else {
        val = 'nan'
    }
    if (upper) {
        return val.toUpperCase()
    }
    return val

}

var format_sign = function(val, flags) {
    if (flags.sign) {
        if (val >= 0) {
            return "+"
        }
    } else if (flags.space) {
        if (val >= 0) {
            return " "
        }
    }
    return ""
}

var str_format = function(val, flags) {
    // string format supports left and right padding
    flags.pad_char = " "  // even if 0 padding is defined, don't use it
    return format_padding(str(val), flags)
}

var num_format = function(val, flags) {
    number_check(val)
    if (val.__class__ === $B.LongInt.$dict) {
      val = $B.LongInt.$dict.to_base(val, 10)
    } else {
      val = parseInt(val)
    }

    var s = format_int_precision(val, flags)
    if (flags.pad_char === '0') {
        if (val < 0) {
            s = s.substring(1)
            return '-' + format_padding(s, flags, true)
        }
        var sign = format_sign(val, flags)
        if (sign !== '') {
            return sign + format_padding(s, flags, true)
        }
    }

    return format_padding(format_sign(val, flags) + s, flags)
}

var repr_format = function(val, flags) {
    flags.pad_char = " "  // even if 0 padding is defined, don't use it
    return format_padding(repr(val), flags)
}

var ascii_format = function(val, flags) {
    flags.pad_char = " "  // even if 0 padding is defined, don't use it
    return format_padding(ascii(val), flags)
}

// converts to val to float and sets precision if missing
var _float_helper = function(val, flags) {
    number_check(val)
    if (!flags.precision) {
        if (!flags.decimal_point) {
            flags.precision = 6
        } else {
            flags.precision = 0
        }
    } else {
        flags.precision = parseInt(flags.precision, 10)
        validate_precision(flags.precision)
    }
    return parseFloat(val)
}

// used to capture and remove trailing zeroes
var trailing_zeros = /(.*?)(0+)([eE].*)/
var leading_zeros = /\.(0*)/
var trailing_dot = /\.$/

var validate_precision = function(precision) {
    // force precision to limits of javascript
    if (precision > 20) {
        throw _b_.ValueError("precision too big")
    }
}

// gG
var floating_point_format = function(val, upper, flags) {
    val = _float_helper(val, flags)
    var v = val.toString()
    var v_len = v.length
    var dot_idx = v.indexOf('.')
    if (dot_idx < 0) {
        dot_idx = v_len
    }
    if (val < 1 && val > -1) {
        var zeros = leading_zeros.exec(v)
        var numzeros
        if (zeros) {
            numzeros = zeros[1].length
        } else {
            numzeros = 0
        }
        if (numzeros >= 4) {
            val = format_sign(val, flags) + format_float_precision(val, upper, flags, _floating_g_exp_helper)
            if (!flags.alternate) {
                var trl = trailing_zeros.exec(val)
                if (trl) {
                    val = trl[1].replace(trailing_dot, '') + trl[3]  // remove trailing
                }
            } else {
                if (flags.precision <= 1) {
                    val = val[0] + '.' + val.substring(1)
                }
            }
            return format_padding(val, flags)
        }
        flags.precision += numzeros
        return format_padding(format_sign(val, flags) + format_float_precision(val, upper, flags,
            function(val, precision) {
                val = val.toFixed(min(precision, v_len - dot_idx) + numzeros)
            }), flags)
    }

    if (dot_idx > flags.precision) {
        val = format_sign(val, flags) + format_float_precision(val, upper, flags, _floating_g_exp_helper)
        if (!flags.alternate) {
            var trl = trailing_zeros.exec(val)
            if (trl) {
                val = trl[1].replace(trailing_dot, '') + trl[3]  // remove trailing
            }
        } else {
            if (flags.precision <= 1) {
                val = val[0] + '.' + val.substring(1)
            }
        }
        return format_padding(val, flags)
    }
    return format_padding(format_sign(val, flags) + format_float_precision(val, upper, flags,
        function(val, precision) {
            if (!flags.decimal_point) {
                precision = min(v_len - 1, 6)
            } else if (precision > v_len) {
                if (!flags.alternate) {
                    precision = v_len
                }
            }
            if (precision < dot_idx) {
                precision = dot_idx
            }
            return val.toFixed(precision - dot_idx)
        }), flags)
}

var _floating_g_exp_helper = function(val, precision, flags, upper) {
    if (precision) {
        --precision
    }
    val = val.toExponential(precision)
    // pad exponent to two digits
    var e_idx = val.lastIndexOf('e')
    if (e_idx > val.length - 4) {
        val = val.substring(0, e_idx + 2) + '0' + val.substring(e_idx + 2)
    }
    if (upper) {
        return val.toUpperCase()
    }
    return val
}

// fF
var floating_point_decimal_format = function(val, upper, flags) {
    val = _float_helper(val, flags)
    return format_padding(format_sign(val, flags) + format_float_precision(val, upper, flags,
        function(val, precision, flags) {
            val = val.toFixed(precision)
            if (precision === 0 && flags.alternate) {
                val += '.'
            }
            return val
        }), flags)
}

var _floating_exp_helper = function(val, precision, flags, upper) {
    val = val.toExponential(precision)
    // pad exponent to two digits
    var e_idx = val.lastIndexOf('e')
    if (e_idx > val.length - 4) {
        val = val.substring(0, e_idx + 2) + '0' + val.substring(e_idx + 2)
    }
    if (upper) {
        return val.toUpperCase()
    }
    return val
}

// eE
var floating_point_exponential_format = function(val, upper, flags) {
    val = _float_helper(val, flags)

    return format_padding(format_sign(val, flags) + format_float_precision(val, upper, flags, _floating_exp_helper), flags)
}

var signed_hex_format = function(val, upper, flags) {
    var ret
    number_check(val)

    if (val.__class__ === $B.LongInt.$dict) {
       ret=$B.LongInt.$dict.to_base(val, 16)
    } else {
       ret = parseInt(val)
       ret = ret.toString(16)
    }
    ret = format_int_precision(ret, flags)
    if (upper) {
        ret = ret.toUpperCase()
    }
    if (flags.pad_char === '0') {
        if (val < 0) {
            ret = ret.substring(1)
            ret = '-' + format_padding(ret, flags, true)
        }
        var sign = format_sign(val, flags)
        if (sign !== '') {
            ret = sign + format_padding(ret, flags, true)
        }
    }

    if (flags.alternate) {
        if (ret.charAt(0) === '-') {
            if (upper) {
                ret = "-0X" + ret.slice(1)
            } else {
                ret = "-0x" + ret.slice(1)
            }
        } else {
            if (upper) {
                ret = "0X" + ret
            } else {
                ret = "0x" + ret
            }
        }
    }
    return format_padding(format_sign(val, flags) + ret, flags)
}

var octal_format = function(val, flags) {
    number_check(val)
    var ret

    if (val.__class__ === $B.LongInt.$dict) {
      ret = $B.LongInt.$dict.to_base(8)
    } else {
      ret = parseInt(val)
      ret = ret.toString(8)
    }

    ret = format_int_precision(ret, flags)

    if (flags.pad_char === '0') {
        if (val < 0) {
            ret = ret.substring(1)
            ret = '-' + format_padding(ret, flags, true)
        }
        var sign = format_sign(val, flags)
        if (sign !== '') {
            ret = sign + format_padding(ret, flags, true)
        }
    }

    if (flags.alternate) {
        if (ret.charAt(0) === '-') {
            ret = "-0o" + ret.slice(1)
        } else {
            ret = "0o" + ret
        }
    }
    return format_padding(ret, flags)
}

var single_char_format = function(val, flags) {
    if(isinstance(val,str) && val.length==1) return val
    try {
        val = _b_.int(val)  // yes, floats are valid (they are cast to int)
    } catch (err) {
        throw _b_.TypeError('%c requires int or char')
    }
    return format_padding(chr(val), flags)
}

var num_flag = function(c, flags) {
    if (c === '0' && !flags.padding && !flags.decimal_point && !flags.left) {
        flags.pad_char = '0'
        return
    }
    if (!flags.decimal_point) {
        flags.padding = (flags.padding || "") + c
    } else {
        flags.precision = (flags.precision || "") + c
    }
}

var decimal_point_flag = function(val, flags) {
    if (flags.decimal_point) {
        // can only have one decimal point
        throw new UnsupportedChar()
    }
    flags.decimal_point = true
}

var neg_flag = function(val, flags) {
    flags.pad_char = ' '  // overrides '0' flag
    flags.left = true
}

var space_flag = function(val, flags) {
    flags.space = true
}

var sign_flag = function(val, flags) {
    flags.sign = true
}

var alternate_flag = function(val, flags) {
    flags.alternate = true
}

var char_to_func_mapping = {
    's': str_format,
    'd': num_format,
    'i': num_format,
    'u': num_format,
    'o': octal_format,
    'r': repr_format,
    'a': ascii_format,
    'g': function(val, flags) {return floating_point_format(val, false, flags)},
    'G': function(val, flags) {return floating_point_format(val, true, flags)},
    'f': function(val, flags) {return floating_point_decimal_format(val, false, flags)},
    'F': function(val, flags) {return floating_point_decimal_format(val, true, flags)},
    'e': function(val, flags) {return floating_point_exponential_format(val, false, flags)},
    'E': function(val, flags) {return floating_point_exponential_format(val, true, flags)},
    'x': function(val, flags) {return signed_hex_format(val, false, flags)},
    'X': function(val, flags) {return signed_hex_format(val, true, flags)},
    'c': single_char_format,
    '0': function(val, flags) {return num_flag('0', flags)},
    '1': function(val, flags) {return num_flag('1', flags)},
    '2': function(val, flags) {return num_flag('2', flags)},
    '3': function(val, flags) {return num_flag('3', flags)},
    '4': function(val, flags) {return num_flag('4', flags)},
    '5': function(val, flags) {return num_flag('5', flags)},
    '6': function(val, flags) {return num_flag('6', flags)},
    '7': function(val, flags) {return num_flag('7', flags)},
    '8': function(val, flags) {return num_flag('8', flags)},
    '9': function(val, flags) {return num_flag('9', flags)},
    '-': neg_flag,
    ' ': space_flag,
    '+': sign_flag,
    '.': decimal_point_flag,
    '#': alternate_flag
}

// exception thrown when an unsupported char is encountered in legacy format
var UnsupportedChar = function() {
    this.name = "UnsupportedChar"
}

$StringDict.__mod__ = function(val, args) {
    return $legacy_format(val, args, char_to_func_mapping)
}

var $legacy_format = function(val, args, char_mapping) {
    var length = val.length
    var pos = 0 |0
    var argpos = null
    if (args && _b_.isinstance(args, _b_.tuple)) {
        argpos = 0 |0
    }
    var ret = ''
    var $get_kwarg_string = function(s) {
        // returns [val, newpos]
        ++pos
        var rslt = kwarg_key.exec(s.substring(newpos))
        if (!rslt) {
            throw _b_.ValueError("incomplete format key")
        }
        var key = rslt[1]
        newpos += rslt[0].length
        try {
            var val = _b_.getattr(args.__class__,'__getitem__')(args, key)
        } catch(err) {
            if (err.name === "KeyError") {
                throw err
            }
            throw _b_.TypeError("format requires a mapping")
        }
        return get_string_value(s, val)
    }

    var $get_arg_string = function(s) {
        // returns [val, newpos]
        var val

        // non-tuple args
        if (argpos === null) {
            // args is the value
            val = args
        } else {
            try {
                val = args[argpos++]
            }
            catch(err) {
                if (err.name === "IndexError") {
                    throw _b_.TypeError("not enough arguments for format string")
                } else {
                    throw err
                }
            }
        }
        return get_string_value(s, val)
    }
    var get_string_value = function(s, val) {
        // todo: get flags, type
        // todo: string value based on flags, type, value
        var flags = {'pad_char': ' '}
        do {
            var func = char_mapping[s[newpos]]
            try {
                if (func === undefined) {
                    throw new UnsupportedChar()
                } else {
                    var ret = func(val, flags)
                    if (ret !== undefined) {
                        return ret
                    }
                    ++newpos
                }
            } catch (err) {
                if (err.name === "UnsupportedChar") {
                    invalid_char = s[newpos]
                    if (invalid_char === undefined) {
                        throw _b_.ValueError("incomplete format")
                    }
                    throw _b_.ValueError("unsupported format character '" + invalid_char +
                        "' (0x" + invalid_char.charCodeAt(0).toString(16) + ") at index " + newpos)
                } else if (err.name === "NotANumber") {
                    var try_char = s[newpos]
                    var cls = val.__class__
                    if (!cls) {
                        if (typeof(val) === 'string') {
                            cls = 'str'
                        } else {
                            cls = typeof(val)
                        }
                    } else {
                        cls = cls.__name__
                    }
                    throw _b_.TypeError("%" + try_char + " format: a number is required, not " + cls)
                } else {
                    throw err
                }
            }
        } while (true)
    }
    do {
        var newpos = val.indexOf('%', pos)
        if (newpos < 0) {
            ret += val.substring(pos)
            break
        }
        ret += val.substring(pos, newpos)
        ++newpos
        if (newpos < length) {
            if (val[newpos] === '%') {
                ret += '%'
            } else {
                var tmp
                if (val[newpos] === '(') {
                    ++newpos
                    ret += $get_kwarg_string(val)
                } else {
                    ret += $get_arg_string(val)
                }
            }
        } else {
            // % at end of string
            throw _b_.ValueError("incomplete format")
        }
        pos = newpos + 1
    } while (pos < length)
    return ret
}

var char_to_new_format_mapping = {
    'b': function(val, flags) {
        number_check(val)
        val = val.toString(2)
        if (flags.alternate) {
            val = "0b" + val
        }
        return val
    },
    'n': function(val, flags) {return floating_point_format(val, false, flags)},
    'N': function(val, flags) {return floating_point_format(val, true, flags)}
}

for (k in char_to_func_mapping) {
    char_to_new_format_mapping[k] = char_to_func_mapping[k]
}

$format_to_legacy = function(val, args) {
    return $legacy_format(val, args, char_to_new_format_mapping)
}

$StringDict.__mro__ = [$StringDict,$ObjectDict]

$StringDict.__mul__ = function(self,other){
    if(!isinstance(other,_b_.int)){throw _b_.TypeError(
        "Can't multiply sequence by non-int of type '"+
            $B.get_class(other).__name__+"'")}
    $res = ''
    for(var i=0;i<other;i++){$res+=self.valueOf()}
    return $res
}

$StringDict.__ne__ = function(self,other){return other!==self.valueOf()}

$StringDict.__repr__ = function(self){
    if(self.search('"')==-1 && self.search("'")==-1){
        return "'"+self+"'"
    }else if(self.search('"')==-1){
        return '"'+self+'"'
    }
    var qesc = new RegExp("'","g") // to escape single quote
    var res = self.replace(/\n/g,'\\\\n')
    res = "'"+res.replace(qesc,"\\'")+"'"
    return res
}

$StringDict.__setattr__ = function(self,attr,value){return setattr(self,attr,value)}

$StringDict.__setitem__ = function(self,attr,value){
    throw _b_.TypeError("'str' object does not support item assignment")
}
$StringDict.__str__ = function(self){
    if(self===undefined) return "<class 'str'>"
    return self.toString()
}
$StringDict.toString = function(){return 'string!'}

// generate comparison methods
var $comp_func = function(self,other){
    if(typeof other !=="string"){throw _b_.TypeError(
        "unorderable types: 'str' > "+$B.get_class(other).__name__+"()")}
    return self > other
}
$comp_func += '' // source code
var $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
for(var $op in $comps){
    eval("$StringDict.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
}

// add "reflected" methods
$B.make_rmethods($StringDict)

// unsupported operations
var $notimplemented = function(self,other){
    throw NotImplementedError("OPERATOR not implemented for class str")
}

$StringDict.capitalize = function(self){
    if(self.length==0) return ''
    return self.charAt(0).toUpperCase()+self.substr(1).toLowerCase()
}

$StringDict.casefold = function(self) {
    throw _b_.NotImplementedError("function casefold not implemented yet");
}

$StringDict.center = function(self,width,fillchar){
    if(fillchar===undefined){fillchar=' '}else{fillchar=fillchar}
    if(width<=self.length) return self

    var pad = parseInt((width-self.length)/2)
    var res = Array(pad+1).join(fillchar) // is this statement faster than the for loop below?
    res += self + res
    if(res.length<width){res += fillchar}
    return res
}

$StringDict.count = function(self,elt){
    if(!(typeof elt==="string")){throw _b_.TypeError(
        "Can't convert '"+elt.__class__.__name__+"' object to str implicitly")}
    //needs to be non overlapping occurrences of substring in string.
    var n=0, pos=0
    while(1){
        pos=self.indexOf(elt,pos)
        if(pos>=0){ n++; pos+=elt.length} else break;
    }
    return n
}

$StringDict.encode = function(self, encoding) {
    if (encoding === undefined) encoding='utf-8'
    if(encoding=='rot13' || encoding=='rot_13'){
        // Special case : returns a string
        var res = ''
        for(var i=0, _len = self.length; i<_len ; i++){
            var char = self.charAt(i)
            if(('a'<=char && char<='m') || ('A'<=char && char<='M')){
                res += String.fromCharCode(String.charCodeAt(char)+13)
            }else if(('m'<char && char<='z') || ('M'<char && char<='Z')){
                res += String.fromCharCode(String.charCodeAt(char)-13)
            }else{res += char}
        }
        return res
    }
    return _b_.bytes(self, encoding)
}

$StringDict.endswith = function(self){
    // Return True if the string ends with the specified suffix, otherwise
    // return False. suffix can also be a tuple of suffixes to look for.
    // With optional start, test beginning at that position. With optional
    // end, stop comparing at that position.
    var $ns=$B.$MakeArgs1("$StringDict.endswith",4,
        {self:null, suffix:null, start:null, end:null},
        ['self', 'suffix', 'start', 'end'],
        arguments,{start:0, end:self.length-1},null,null)
    var suffixes = $ns['suffix']
    if(!isinstance(suffixes,_b_.tuple)){suffixes=[suffixes]}
    var start = $ns['start'],
        end = $ns['end']
    var s = self.substr(start,end+1)
    for(var i=0, _len_i = suffixes.length; i < _len_i;i++){
        suffix = suffixes[i]
        if(suffix.length<=s.length &&
            s.substr(s.length-suffix.length)==suffix) return true
    }
    return false
}

$StringDict.expandtabs = function(self, tabsize) {
    tabsize=tabsize || 8
    var _str=''
    for (var i=0; i < tabsize; i++) _str+=' '
    return self.valueOf().replace(/\t/g, _str)
}

$StringDict.find = function(self){
    // Return the lowest index in the string where substring sub is found,
    // such that sub is contained in the slice s[start:end]. Optional
    // arguments start and end are interpreted as in slice notation.
    // Return -1 if sub is not found.
    var start=0,end=self.length
    var $ns=$B.$MakeArgs1("$StringDict.find",4,
        {self:null, sub:null, start:null, end:null},
        ['self', 'sub', 'start','end'],
        arguments,{start:0, end:self.length},null,null)
    for(var attr in $ns){eval('var '+attr+'=$ns[attr]')}
    if(!isinstance(sub,str)){throw _b_.TypeError(
        "Can't convert '"+sub.__class__.__name__+"' object to str implicitly")}
    if(!isinstance(start,_b_.int)||!isinstance(end,_b_.int)){
        throw _b_.TypeError(
        "slice indices must be integers or None or have an __index__ method")}
    var s = self.substring(start,end)
    var esc_sub = ''
    for(var i=0, _len_i = sub.length; i < _len_i;i++){
        switch(sub.charAt(i)) {
          case '[':
          case '.':
          case '*':
          case '+':
          case '?':
          case '|':
          case '(':
          case ')':
          case '$':
          case '^':
            esc_sub += '\\'
        }
        esc_sub += sub.charAt(i)
    }
    var res = s.search(esc_sub)
    if(res==-1) return -1
    return start+res
}

var $FormattableString=function(format_string) {
    // inspired from
    // https://raw.github.com/florentx/stringformat/master/stringformat.py
    this.format_string=format_string

    this._prepare = function() {
       //console.log('prepare')
       var match = arguments[0]
       //console.log('match1', match)

       var p1 = '' + arguments[2]

       if (match == '%') return '%%'
       if (match.substring(0,1) == match.substring(match.length-1)) {
          // '{{' or '}}'
          return match.substring(0, Math.floor(match.length/2))
       }

       if (p1.charAt(0) == '{' && p1.charAt(match.length-1) == '}') {
          p1=match.substring(1, p1.length-1)
       }

       var _repl
       if (match.length >= 2) {
          _repl=''
       } else {
         _repl = match.substring(1)
       }

       var _i = p1.indexOf(':')
       var _out
       if (_i > -1) {
         _out = [p1.slice(0,_i), p1.slice(_i+1)]
       } else { _out=[p1]}

       var _field=_out[0] || ''
       var _format_spec=_out[1] || ''

       _out= _field.split('!')
       var _literal=_out[0] || ''
       var _sep=_field.indexOf('!') > -1?'!': undefined // _out[1]
       var _conv=_out[1]  //conversion

       if (_sep && _conv === undefined) {
          throw _b_.ValueError("end of format while looking for conversion specifier")
       }

       if (_conv !== undefined && _conv.length > 1) {
          throw _b_.ValueError("expected ':' after format specifier")
       }

       if (_conv !== undefined && 'rsa'.indexOf(_conv) == -1) {
          throw _b_.ValueError("Unknown conversion specifier " + _conv)
       }

       _name_parts=this.field_part.apply(null, [_literal])

       var _start=_literal.charAt(0)
       var _name=''
       if (_start=='' || _start=='.' || _start == '[') {
          // auto-numbering
          if (this._index === undefined) {
             throw _b_.ValueError("cannot switch from manual field specification to automatic field numbering")
          }

          _name = this._index.toString()
          this._index+=1

          if (! _literal ) {
             _name_parts.shift()
          }
       } else {
         _name = _name_parts.shift()[1]
         if (this._index !== undefined && !isNaN(_name)) {
            // manual specification
            if (this._index) {
               throw _b_.ValueError("cannot switch from automatic field " +
                                "numbering to manual field specification")
               this._index=undefined
            }
         }
       }

       var _empty_attribute=false

       var _k
       for (var i=0, _len_i = _name_parts.length; i < _len_i; i++) {
           _k = _name_parts[i][0]
           var _v = _name_parts[i][1]
           var _tail = _name_parts[i][2]
           if (_v === '') {_empty_attribute = true}
           if (_tail !== '') {
              throw _b_.ValueError("Only '.' or '[' may follow ']' " +
                               "in format field specifier")
           }
       }

       if (_name_parts && _k == '[' && !
          _literal.charAt(_literal.length) == ']') {
          throw _b_.ValueError("Missing ']' in format string")
       }

       if (_empty_attribute) {
          throw _b_.ValueError("Empty attribute in format string")
       }

       var _rv=''
       if (_format_spec.indexOf('{') != -1) {
          _format_spec = _format_spec.replace(this.format_sub_re, this._prepare)
          _rv = [_name_parts, _conv, _format_spec]
          if (this._nested[_name] === undefined) {
             this._nested[_name]=[]
             this._nested_array.push(_name)
          }
          this._nested[_name].push(_rv)
       } else {
          _rv = [_name_parts, _conv, _format_spec]
          if (this._kwords[_name] === undefined) {
             this._kwords[_name]=[]
             this._kwords_array.push(_name)
          }
          this._kwords[_name].push(_rv)
       }

       return '%(' + id(_rv) + ')s'
    }  // this._prepare

    this.format=function() {
       // same as str.format() and unicode.format in Python 2.6+

       var $ns=$B.$MakeArgs1('format',0,{},[],arguments,{},'args','kwargs')
       var args=$ns['args']
       var kwargs=$ns['kwargs']

       if (args.length>0) {
          for (var i=0, _len_i = args.length; i < _len_i; i++) {
              //kwargs[str(i)]=args.$dict[i]
              getattr(kwargs, '__setitem__')(str(i), args[i])
          }
       }

       //encode arguments to ASCII, if format string is bytes
       var _want_bytes = isinstance(this._string, str)
       var _params=_b_.dict()

       for (var i=0, _len_i = this._kwords_array.length; i < _len_i; i++) {
           var _name = this._kwords_array[i]
           var _items = this._kwords[_name]
           var _var = getattr(kwargs, '__getitem__')(_name)
           var _value;
           if (hasattr(_var, 'value')) {
              _value = getattr(_var, 'value')
           } else {
             _value=_var
           }

           for (var j=0, _len_j = _items.length; j < _len_j; j++) {
               var _parts = _items[j][0]
               var _conv = _items[j][1]
               var _spec = _items[j][2]

               var _f=this.format_field.apply(null, [_value, _parts,_conv,_spec,_want_bytes])
               getattr(_params,'__setitem__')(id(_items[j]).toString(), _f)
           }
       }

       for (var i=0, _len_i = this._nested_array.length; i < _len_i; i++) {
           var _name = this._nested_array[i]
           var _items = this._nested[i]

           var _var = getattr(kwargs, '__getitem__')(_name)
           var _value;
           if (hasattr(_var, 'value')) {
              _value = getattr(getattr(kwargs, '__getitem__')(_name), 'value')
           } else {
             _value=_var
           }

           for (var j=0, _len_j = _items.length; j < _len_j; j++) {
               var _parts = _items[j][0]
               var _conv = _items[j][1]
               var _spec = _items[j][2]

               _spec=$format_to_legacy(_spec, _params)

               var _f=this.format_field.apply(null, [_value, _parts,_conv,_spec,_want_bytes])
               getattr(_params,'__setitem__')(id(_items[j]).toString(), _f)
           }
       }
       return $format_to_legacy(this._string, _params)
    }  // this.format

    this.format_field=function(value,parts,conv,spec,want_bytes) {

       if (want_bytes === undefined) want_bytes = false

       for (var i=0, _len_i = parts.length; i < _len_i; i++) {
           var _k = parts[i][0]
           var _part = parts[i][1]

           if (_k) {
              if (!isNaN(_part)) {
                 value = value[parseInt(_part)]
              } else {
                 value = getattr(value, _part)
              }
           } else {
              value = value[_part]
           }
       }

       if (conv) {
          // fix me
          value = $format_to_legacy((conv == 'r') && '%r' || '%s', value)
       }

       value = this.strformat(value, spec)

       if (want_bytes) { return value.toString()}

       return value
    }

    this.strformat=function(value, format_spec) {
       if (format_spec === undefined) format_spec = ''
       if (!isinstance(value,[str,_b_.int]) && hasattr(value, '__format__')) {
          return getattr(value, '__format__')(format_spec)
       }
       var _m = this.format_spec_re.test(format_spec)

       if (!_m) throw _b_.ValueError('Invalid conversion specification')

       var _match=this.format_spec_re.exec(format_spec)
       var _align=_match[1]
       var _sign=_match[2]
       var _prefix=_match[3]
       var _width=_match[4]
       var _comma=_match[5]
       var _precision=_match[6]
       var _conversion=_match[7]

       var _is_float = isinstance(value, _b_.float)
       var _is_integer = isinstance(value, _b_.int)
       var _is_numeric = _is_float || _is_integer

       if (_prefix != '' && ! _is_numeric) {
          if (_is_numeric) {
             throw _b_.ValueError('Alternate form (#) not allowed in float format specifier')
          } else {
             throw _b_.ValueError('Alternate form (#) not allowed in string format specification')
          }
       }

       if (_is_numeric && _conversion == 'n') {
          _conversion = _is_integer && 'd' || 'g'
       } else {
          if (_sign) {
             if (! _is_numeric) {
                throw _b_.ValueError('Sign not allowed in string format specification');
             }
             if (_conversion == 'c') {
                throw("Sign not allowed with integer format specifier 'c'")
             }
          }
       }

       if (_comma !== '') {
          value += ''
          var x = value.split('.')
          var x1 = x[0];
          var x2 = x.length > 1 ? '.' + x[1] : '';
          var rgx = /(\d+)(\d{3})/;

          while (rgx.test(x1)) {
                 x1 = x1.replace(rgx, '$1' + ',' + '$2');
          }
          value=x1+x2
       }

       var _rv
       if (_conversion != '' && ((_is_numeric && _conversion == 's') ||
          (! _is_integer && 'coxX'.indexOf(_conversion) != -1))) {
          console.log(_conversion)
          throw _b_.ValueError('Fix me')
       }

       if (_conversion == 'c') _conversion = 's'

       // fix me
       _rv='%' + _prefix + _precision + (_conversion || 's')

       _rv = $format_to_legacy(_rv, value)

       if (_sign != '-' && value >= 0) _rv = _sign + _rv

       var _zero = false
       if (_width) {
          _zero = _width.charAt(0) == '0'
          _width = parseInt(_width)
       } else {
          _width = 0
       }

       // Fastpath when alignment is not required

       if (_width <= _rv.length) {
          if (! _is_float && (_align == '=' || (_zero && ! _align))) {
             throw _b_.ValueError("'=' alignment not allowed in string format specifier")
          }
          return _rv
       }

       _fill = _align.substr(0,_align.length-1)
       _align= _align.substr(_align.length-1)

       if (! _fill) {_fill = _zero && '0' || ' '}

       if (_align == '^') {
          _rv = getattr(_rv, 'center')(_width, _fill)
       } else if (_align == '=' || (_zero && ! _align)) {
          if (! _is_numeric) {
             throw _b_.ValueError("'=' alignment not allowed in string format specifier")
          }
          if (_value < 0 || _sign != '-') {
             _rv = _rv.substring(0,1) + getattr(_rv.substring(1),'rjust')(_width - 1, _fill)
          } else {
             _rv = getattr(_rv, 'rjust')(_width, _fill)
          }
       } else if ((_align == '>' || _align == '=') || (_is_numeric && ! _aligned)) {
         _rv = getattr(_rv, 'rjust')(_width, _fill)
       } else if (_align == '<') {
         _rv = getattr(_rv, 'ljust')(_width, _fill)
       } else {
         throw _b_.ValueError("'" + _align + "' alignment not valid")
       }

       return _rv
    }

    this.field_part=function(literal) {
       if (literal.length == 0) return [['','','']]

       var _matches=[]
       var _pos=0

       var _start='', _middle='', _end=''
       var arg_name=''

       // arg_name
       if (literal === undefined) console.log(literal)
       var _lit=literal.charAt(_pos)
       while (_pos < literal.length &&
              _lit !== '[' && _lit !== '.') {
              arg_name += _lit
              _pos++
              _lit=literal.charAt(_pos)
       }

       // todo.. need to work on code below, but this takes cares of most
       // common cases.
       if (arg_name != '') _matches.push(['', arg_name, ''])

       //return _matches

       var attribute_name=''
       var element_index=''

       //look for attribute_name and element_index
       while (_pos < literal.length) {
          var car = literal.charAt(_pos)

          if (car == '[') { // element_index
             _start=_middle=_end=''
             _pos++

             car = literal.charAt(_pos)
             while (_pos < literal.length && car !== ']') {
                _middle += car
                _pos++
                car = literal.charAt(_pos)
             }

             _pos++
             if (car == ']') {
                while (_pos < literal.length) {
                  _end+=literal.charAt(_pos)
                  _pos++
                }
             }

             _matches.push([_start, _middle, _end])

          } else if (car == '.') { // attribute_name
                  _middle=''
                  _pos++
                  car = literal.charAt(_pos)
                  while (_pos < literal.length &&
                         car !== '[' &&
                         car !== '.') {
                      //console.log(car)
                      _middle += car
                      _pos++
                      car = literal.charAt(_pos)
                  }

                  _matches.push(['.', _middle, ''])
          }
       }
       return _matches
    }

    this.format_str_re = new RegExp(
      '(%)' +
      '|((?!{)(?:{{)+' +
      '|(?:}})+(?!})' +
      '|{(?:[^{}](?:[^{}]+|{[^{}]*})*)?})', 'g'
    )

    this.format_sub_re = new RegExp('({[^{}]*})')  // nested replacement field

    this.format_spec_re = new RegExp(
      '((?:[^{}]?[<>=^])?)' +      // alignment
      '([\\-\\+ ]?)' +                // sign
      '(#?)' + '(\\d*)' + '(,?)' +    // base prefix, minimal width, thousands sep
      '((?:\.\\d+)?)' +             // precision
      '(.?)$'                      // type
    )

    this._index = 0
    this._kwords = {}
    this._kwords_array=[]
    this._nested = {}
    this._nested_array=[]

    this._string=format_string.replace(this.format_str_re, this._prepare)

    return this
}

$StringDict.format = function(self) {

    var _fs = $FormattableString(self.valueOf())
    var args=[], pos=0
    // we don't need the first item (ie, self)
    for (var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]}
    return _fs.format.apply(null, args)
}

$StringDict.format_map = function(self) {
  throw NotImplementedError("function format_map not implemented yet");
}

$StringDict.index = function(self){
    // Like find(), but raise ValueError when the substring is not found.
    var res = $StringDict.find.apply(self,arguments)
    if(res===-1) throw _b_.ValueError("substring not found")
    return res
}

$StringDict.isalnum = function(self) {return /^[a-z0-9]+$/i.test(self)}

$StringDict.isalpha = function(self) {return /^[a-z]+$/i.test(self)}

$StringDict.isdecimal = function(self) {
  // this is not 100% correct
  return /^[0-9]+$/.test(self)
}

$StringDict.isdigit = function(self) { return /^[0-9]+$/.test(self)}

$StringDict.isidentifier = function(self) {

  switch(self) {
    case 'False':
    case 'None':
    case 'True':
    case 'and':
    case 'as':
    case 'assert':
    case 'break':
    case 'class':
    case 'continue':
    case 'def':
    case 'del':
    case 'elif':
    case 'else':
    case 'except':
    case 'finally':
    case 'for':
    case 'from':
    case 'global':
    case 'if':
    case 'import':
    case 'in':
    case 'is':
    case 'lambda':
    case 'nonlocal':
    case 'not':
    case 'or':
    case 'pass':
    case 'raise':
    case 'return':
    case 'try':
    case 'while':
    case 'with':
    case 'yield':
      return true
  }

  // fixme..  this isn't complete but should be a good start
  return /^[a-z][0-9a-z_]+$/i.test(self)
}

$StringDict.islower = function(self) {return /^[a-z]+$/.test(self)}

// not sure how to handle unicode variables
$StringDict.isnumeric = function(self) {return /^[0-9]+$/.test(self)}

// inspired by http://www.codingforums.com/archive/index.php/t-17925.html
$StringDict.isprintable = function(self) {return !/[^ -~]/.test(self)}

$StringDict.isspace = function(self) {return /^\s+$/i.test(self)}

$StringDict.istitle = function(self) {return /^([A-Z][a-z]+)(\s[A-Z][a-z]+)$/i.test(self)}

$StringDict.isupper = function(self) {return /^[A-Z]+$/.test(self)}

$StringDict.join = function(self,obj){
    var iterable=iter(obj)
    var res = '',count=0
    while(1){
        try{
            var obj2 = next(iterable)
            if(!isinstance(obj2,str)){throw _b_.TypeError(
                "sequence item "+count+": expected str instance, "+$B.get_class(obj2).__name__+" found")}
            res += obj2+self
            count++
        }catch(err){
            if(err.__name__==='StopIteration'){break}
            else{throw err}
        }
    }
    if(count==0) return ''
    return res.substr(0,res.length-self.length)
}

$StringDict.ljust = function(self, width, fillchar) {
  if (width <= self.length) return self
  if (fillchar === undefined) fillchar=' '
  return self + Array(width - self.length + 1).join(fillchar)
}

$StringDict.lower = function(self){return self.toLowerCase()}

$StringDict.lstrip = function(self,x){
    var pattern = null
    if(x==undefined){pattern="\\s*"}
    else{pattern = "["+x+"]*"}
    var sp = new RegExp("^"+pattern)
    return self.replace(sp,"")
}

// note, maketrans should be a static function.
$StringDict.maketrans = function(from, to) {
   var _t=[]
   // make 'default' translate table
   for(var i=0; i < 256; i++) _t[i]=String.fromCharCode(i)

   // make substitution in the translation table
   for(var i=0, _len_i = from.source.length; i < _len_i; i++) {
      var _ndx=from.source[i].charCodeAt(0)     //retrieve ascii code of char
      _t[_ndx]=to.source[i]
   }

   // create a data structure that string.translate understands
   var _d=dict()
   for(var i=0; i < 256; i++) {
      _b_.dict.$dict.__setitem__(_d, i, _t[i])
   }
   return _d
}

$StringDict.partition = function(self,sep) {
  if (sep === undefined) {
     throw Error("sep argument is required");
     return
  }
  var i=self.indexOf(sep)
  if (i== -1) return _b_.tuple([self, '', ''])
  return _b_.tuple([self.substring(0,i), sep, self.substring(i+sep.length)])
}

function $re_escape(str)
{
  var specials = "[.*+?|()$^"
  for(var i=0, _len_i = specials.length; i < _len_i;i++){
      var re = new RegExp('\\'+specials.charAt(i),'g')
      str = str.replace(re, "\\"+specials.charAt(i))
  }
  return str
}

$StringDict.replace = function(self, old, _new, count) {
    // Replaces occurrences of 'old' by '_new'. Count references
    // the number of times to replace. In CPython, negative or undefined
    // values of count means replace all.
    if (count === undefined) {
        count = -1;
    } else {
        // Validate instance type of 'count'
        if (!isinstance(count,[_b_.int,_b_.float])) {
            throw _b_.TypeError("'" + str(count.__class__) + "' object cannot be interpreted as an integer");
        } else if (isinstance(count, _b_.float)) {
            throw _b_.TypeError("integer argument expected, got float");
        }
    }

    var res = self.valueOf();
    var pos = -1;
    if (count < 0) count = res.length;
    while (count > 0) {
        pos = res.indexOf(old, pos);
        if (pos < 0)
            break;
        res = res.substr(0, pos) + _new + res.substr(pos + old.length);
        pos = pos + _new.length;
        count--;
    }
    return res;
}

$StringDict.rfind = function(self){
    // Return the highest index in the string where substring sub is found,
    // such that sub is contained within s[start:end]. Optional arguments
    // start and end are interpreted as in slice notation. Return -1 on failure.
    var $ns=$B.$MakeArgs1("$StringDict.find",4,
        {self:null, sub:null, start:null, end:null},
        ['self', 'sub', 'start', 'end'],
        arguments,{start:0, end:self.length},null,null)
    for(var attr in $ns){eval('var '+attr+'=$ns[attr]')}
    if(!isinstance(sub,str)){throw _b_.TypeError(
        "Can't convert '"+sub.__class__.__name__+"' object to str implicitly")}
    if(!isinstance(start,_b_.int)||!isinstance(end,_b_.int)){throw _b_.TypeError(
        "slice indices must be integers or None or have an __index__ method")}

    var s = self.substring(start,end)

    // why not use lastIndexOf, which passes all brython tests..?
    return self.lastIndexOf(sub)
}

$StringDict.rindex = function(){
    // Like rfind() but raises ValueError when the substring sub is not found
    var res = $StringDict.rfind.apply(this,arguments)
    if(res==-1){throw _b_.ValueError("substring not found")}
    return res
}

$StringDict.rjust = function(self) {
    var $ns=$B.$MakeArgs1("$StringDict.rjust",3,
        {self:null, width:null, fillchar:null},
        ['self', 'width', 'fillchar'],
        arguments,{fillchar:' '},null,null)
    for(var attr in $ns){eval('var '+attr+'=$ns[attr]')}

    if (width <= self.length) return self

    return Array(width - self.length + 1).join(fillchar) + self
}

$StringDict.rpartition = function(self,sep) {
  if (sep === undefined) {
     throw Error("sep argument is required");
     return
  }
  var pos=self.length-sep.length
  while(1){
      if(self.substr(pos,sep.length)==sep){
          return _b_.tuple([self.substr(0,pos),sep,self.substr(pos+sep.length)])
      }else{
          pos--
          if(pos<0){return _b_.tuple(['','',self])}
      }
  }
}

$StringDict.rsplit = function(self) {
    var args = [], pos=0
    for(var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]}
    var $ns=$B.$MakeArgs1("$StringDict.rsplit",0,{},[],args,{},'args','kw')
    var sep=None,maxsplit=-1
    if($ns['args'].length>=1){sep=$ns['args'][0]}
    if($ns['args'].length==2){maxsplit=$ns['args'][1]}
    maxsplit = _b_.dict.$dict.get($ns['kw'],'maxsplit',maxsplit)

    //var array=$StringDict.split(self)

    var array=$StringDict.split(self, sep)

    if (array.length <= maxsplit || maxsplit == -1) return array

    var s=[]

    s = array.splice(array.length - maxsplit, array.length)
    s.splice(0, 0, array.join(sep))

    return s
}

$StringDict.rstrip = function(self,x){
    if(x==undefined){var pattern="\\s*"}
    else{var pattern = "["+x+"]*"}
    sp = new RegExp(pattern+'$')
    return str(self.replace(sp,""))
}

$StringDict.split = function(self){
    var args = [], pos=0
    for(var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]}
    var $ns=$B.$MakeArgs1("$StringDict.split",0,{},[],args,{},'args','kw')
    var sep=None,maxsplit=-1
    if($ns['args'].length>=1){sep=$ns['args'][0]}
    if($ns['args'].length==2){maxsplit=$ns['args'][1]}
    maxsplit = _b_.dict.$dict.get($ns['kw'],'maxsplit',maxsplit)
    if(sep=='') throw _b_.ValueError('empty separator')
    if(sep===None){
        var res = []
        var pos = 0
        while(pos<self.length&&self.charAt(pos).search(/\s/)>-1){pos++}
        if(pos===self.length-1){return [self]}
        var name = ''
        while(1){
            if(self.charAt(pos).search(/\s/)===-1){
                if(name===''){name=self.charAt(pos)}
                else{name+=self.charAt(pos)}
            }else{
                if(name!==''){
                    res.push(name)
                    if(maxsplit!==-1&&res.length===maxsplit+1){
                        res.pop()
                        res.push(name+self.substr(pos))
                        return res
                    }
                    name=''
                }
            }
            pos++
            if(pos>self.length-1){
                if(name){res.push(name)}
                break
            }
        }
        return res
    }else{
        var esc_sep = ''
        for(var i=0, _len_i = sep.length; i < _len_i;i++){
            switch(sep.charAt(i)) {
              case '*':
              case '+':
              case '.':
              case '[':
              case ']':
              case '(':
              case ')':
              case '|':
              case '$':
              case '^':
                esc_sep += '\\'
            }
            esc_sep += sep.charAt(i)
        }
        var re = new RegExp(esc_sep)
        if (maxsplit==-1){
            // use native Javascript split on self
            return self.valueOf().split(re,maxsplit)
        }

        // javascript split behavior is different from python when
        // a maxsplit argument is supplied. (see javascript string split
        // function docs for details)
        var l=self.valueOf().split(re,-1)
        var a=l.slice(0, maxsplit)
        var b=l.slice(maxsplit, l.length)
        if (b.length > 0) a.push(b.join(sep))

        return a
    }
}

$StringDict.splitlines = function(self){return $StringDict.split(self,'\n')}

$StringDict.startswith = function(self){
    // Return True if string starts with the prefix, otherwise return False.
    // prefix can also be a tuple of prefixes to look for. With optional
    // start, test string beginning at that position. With optional end,
    // stop comparing string at that position.
    var $ns=$B.$MakeArgs1("$StringDict.startswith",4,
        {self:null, prefix:null, start:null, end:null},
        ['self', 'prefix', 'start', 'end'],
        arguments,{start:0, end:self.length-1},null,null)
    var prefixes = $ns['prefix']
    if(!isinstance(prefixes,_b_.tuple)){prefixes=[prefixes]}
    var start = $ns['start']
    var end = $ns['end']
    var s = self.substr(start,end+1)

    for (var i=0, _len_i = prefixes.length; i < _len_i; i++) {
        if (s.indexOf(prefixes[i]) == 0) return true
    }
    return false
}

$StringDict.strip = function(self,x){
    if(x==undefined){x = "\\s"}
    return $StringDict.rstrip($StringDict.lstrip(self,x),x)
}

$StringDict.swapcase = function(self) {
    //inspired by http://www.geekpedia.com/code69_Swap-string-case-using-JavaScript.html
    return self.replace(/([a-z])|([A-Z])/g, function($0,$1,$2)
        { return ($1) ? $0.toUpperCase() : $0.toLowerCase()
    })
}

$StringDict.title = function(self) {
    //inspired from http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript
    return self.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

$StringDict.translate = function(self,table) {
    var res = [], pos=0
    if (isinstance(table, _b_.dict)) {
       for (var i=0, _len_i = self.length; i < _len_i; i++) {
           var repl = _b_.dict.$dict.get(table,self.charCodeAt(i),-1)
           if(repl==-1){res[pos++]=self.charAt(i)}
           else if(repl!==None){res[pos++]=repl}
       }
    }
    return res.join('')
}

$StringDict.upper = function(self){return self.toUpperCase()}

$StringDict.zfill = function(self, width) {
  if (width === undefined || width <= self.length || !self.isnumeric()) {
     return self
  }

  return Array(width - self.length +1).join('0');
}

function str(arg){
    if(arg===undefined) return ''
    switch(typeof arg) {
      case 'string': return arg
      case 'number': return arg.toString()
    }

    try{
        if(arg.__class__===$B.$factory){
            // arg is a class (the factory function)
            // In this case, str() doesn't use the attribute __str__ of the
            // class or its subclasses, but the attribute __str__ of the
            // class metaclass (usually "type") or its subclasses (usually
            // "object")
            // The metaclass is the attribute __class__ of the class dictionary
            var func = $B.$type.__getattribute__(arg.$dict.__class__,'__str__')
            if(func.__func__===_b_.object.$dict.__str__){return func(arg)}
            return func()
        }

        var f = getattr(arg,'__str__')
        // XXX fix : if not better than object.__str__, try __repr__
        return f()
    }
    catch(err){
        //console.log('err '+err)
        try{ // try __repr__
             var f = getattr(arg,'__repr__')
             return getattr(f,'__call__')()
        }catch(err){
             if($B.debug>1){console.log(err)}
             console.log('Warning - no method __str__ or __repr__, default to toString', arg)
             return arg.toString()
        }
    }
}
str.__class__ = $B.$factory
str.$dict = $StringDict
$StringDict.$factory = str
$StringDict.__new__ = function(cls){
    if(cls===undefined){
        throw _b_.TypeError('str.__new__(): not enough arguments')
    }
    return {__class__:cls.$dict}
}

$B.set_func_names($StringDict)

// dictionary and factory for subclasses of string
var $StringSubclassDict = {
    __class__:$B.$type,
    __name__:'str'
}

// the methods in subclass apply the methods in $StringDict to the
// result of instance.valueOf(), which is a Javascript string
for(var $attr in $StringDict){
    if(typeof $StringDict[$attr]=='function'){
        $StringSubclassDict[$attr]=(function(attr){
            return function(){
                var args = [], pos=0
                if(arguments.length>0){
                    var args = [arguments[0].valueOf()], pos=1
                    for(var i=1, _len_i = arguments.length; i < _len_i;i++){
                        args[pos++]=arguments[i]
                    }
                }
                return $StringDict[attr].apply(null,args)
            }
        })($attr)
    }
}
$StringSubclassDict.__mro__ = [$StringSubclassDict,$ObjectDict]

// factory for str subclasses
$B.$StringSubclassFactory = {
    __class__:$B.$factory,
    $dict:$StringSubclassDict
}

_b_.str = str

// Function to parse the 2nd argument of format()
$B.parse_format_spec = function(spec){
    if(spec==''){this.empty=true;return}
    var pos=0,
        aligns = '<>=^',
        digits = '0123456789',
        types = 'bcdeEfFgGnosxX%'
    var align_pos = aligns.indexOf(spec.charAt(0))
    if(align_pos!=-1){this.align=aligns[align_pos];this.fill=' ';pos++}
    else{
        align_pos = aligns.indexOf(spec.charAt(1))
        if(spec.charAt(1) && align_pos!=-1){
            this.align=aligns[align_pos]
            this.fill=spec.charAt(0)
            pos = 2
        }
    }
    this.fill = this.fill || ' '
    var car = spec.charAt(pos)
    if(car=='+'||car=='-'||car==' '){this.sign=car;pos++;car=spec.charAt(pos)}
    if(car=='#'){this.alternate=true;pos++;car=spec.charAt(pos)}
    if(car=='0'){this.sign_aware=true;pos++;car=spec.charAt(pos)}
    while(car && digits.indexOf(car)>-1){
        if(this.width===undefined){this.width=car}
        else{this.width+=car}
        pos++;car=spec.charAt(pos)
    }
    if(this.width!==undefined){this.width=parseInt(this.width)}
    if(car==','){this.comma=true;pos++;car=spec.charAt(pos)}
    if(car=='.'){
        if(digits.indexOf(spec.charAt(pos+1))==-1){
            throw _b_.ValueError("Missing precision in format spec")
        }
        this.precision = spec.charAt(pos+1)
        pos+=2;car=spec.charAt(pos)
        while(car && digits.indexOf(car)>-1){
            this.precision+=car;pos++;car=spec.charAt(pos)
        }
        this.precision = parseInt(this.precision)
    }
    if(car && types.indexOf(car)>-1){this.type=car;pos++;car=spec.charAt(pos)}
    if(pos!==spec.length){
        //console.log('error', spec, this, pos, spec.charAt(pos))
        throw _b_.ValueError("Invalid format specifier")
    }
}

$B.format_width = function(s, fmt){
    if(fmt.width && s.length<fmt.width){
        var fill=fmt.fill || ' ', align = fmt.align || '<',
            missing = fmt.width-s.length
        switch(align){
            case '<':
                return s+fill.repeat(missing)
            case '>':
                return fill.repeat(missing)+s
            case '=':
                if('+-'.indexOf(s.charAt(0))==0){
                    return s.charAt(0)+fill.repeat(missing-1)+s
                }else{
                    return fill.repeat(missing)+s
                }
            case '^':
                left = parseInt(missing/2)
                return fill.repeat(left)+s+(missing-left).repeat(fill)
        }
    }
    return s
}

})(__BRYTHON__)


text:
import { UIPanel, UIRow, UIInput, UICheckbox, UIText, UISpan } from './libs/ui.js';

/* import { SidebarProjectMaterials } from './Sidebar.Project.Materials.js'; */
import { SidebarProjectRenderer } from './Sidebar.Project.Renderer.js';
import { SidebarProjectVideo } from './Sidebar.Project.Video.js';

function SidebarProject( editor ) {

	var config = editor.config;
	var strings = editor.strings;

	var container = new UISpan();

	var settings = new UIPanel();
	settings.setBorderTop( '0' );
	settings.setPaddingTop( '20px' );
	container.add( settings );

	// Title

	var titleRow = new UIRow();
	var title = new UIInput( config.getKey( 'project/title' ) ).setLeft( '100px' ).setWidth( '150px' ).onChange( function () {

		config.setKey( 'project/title', this.getValue() );

	} );

	titleRow.add( new UIText( strings.getKey( 'sidebar/project/title' ) ).setWidth( '90px' ) );
	titleRow.add( title );

	settings.add( titleRow );

	// Editable

	var editableRow = new UIRow();
	var editable = new UICheckbox( config.getKey( 'project/editable' ) ).setLeft( '100px' ).onChange( function () {

		config.setKey( 'project/editable', this.getValue() );

	} );

	editableRow.add( new UIText( strings.getKey( 'sidebar/project/editable' ) ).setWidth( '90px' ) );
	editableRow.add( editable );

	settings.add( editableRow );

	// WebVR

	var vrRow = new UIRow();
	var vr = new UICheckbox( config.getKey( 'project/vr' ) ).setLeft( '100px' ).onChange( function () {

		config.setKey( 'project/vr', this.getValue() );

	} );

	vrRow.add( new UIText( strings.getKey( 'sidebar/project/vr' ) ).setWidth( '90px' ) );
	vrRow.add( vr );

	settings.add( vrRow );

	// container.add( vrRow );
	//

	/* container.add( new SidebarProjectMaterials( editor ) ); */
	container.add( new SidebarProjectRenderer( editor ) );
	container.add( new SidebarProjectVideo( editor ) );

	return container;

}

export { SidebarProject };

redpajama_set_name: RedPajamaGithub


text:
using NUnit.Framework;
using SharpTestsEx;
using Toggle.Net.Configuration;
using Toggle.Net.Providers.TextFile;
using Toggle.Net.Tests.Stubs;

namespace Toggle.Net.Tests.TextFile
{
	public class TrueTest
	{
		[Test]
		public void ShouldBeEnabled()
		{
			var content = new[] { "someflag=true" };
			var toggleChecker = new ToggleConfiguration(new FileParser(new FileReaderStub(content), new DefaultSpecificationMappings())).Create();
			toggleChecker.IsEnabled("someflag")
				.Should().Be.True();
		}
	}
}


text:
import requests

try:
	requests.packages.urllib3.disable_warnings()
except:
	pass

import json
import argparse
import os
import sys
import pprint
import time
pp = pprint.PrettyPrinter(indent=2)

'''
Recursively process a JSON object.
Parent files are specified by the 'parent' key in the JSON object
Values in the 'child' file take precedence
'''
def process_file(parent, child, indent):
	print "[info] %sprocessing parent file \"%s\"" % (indent, parent)

	try:
		parent_file = open(parent)
	except IOError as error:
		print "[error] Open of parent JSON template \"%s\" failed: %s" % (parent, error)
		sys.exit(1)

	try:
		parentdict = json.load(parent_file)
	except (ValueError, NameError) as error:
		print "[error] JSON format error in template \"%s\": %s" % (parent, error)
		sys.exit(1)

	parent_file.close()

	# Recursion happens here
	if 'parent' in parentdict:
		parentdict = process_file(parentdict["parent"], parentdict, indent + " ")

	# Process the child objects 'strings' and 'tables' keys.
	child_strings = {}
	child_tables = {}
	debug("[%s] starting merge" % (parent))
	if 'strings' in child:
		for string in child["strings"]:
			k, v = string.popitem()
			debug("[%s] child: %s" % (parent, k))
			child_strings[k] = v

	if 'tables' in child:
		i = 0
		for table in child["tables"]:
			debug("[%s] iapptable %s" % (parent, table["name"]))
			child_tables[table["name"]] = i
			i += 1

	# Merge with the parent dictionary giving precedence to the child's values
	if 'strings' in parentdict:
		for string in parentdict["strings"]:
			k, v = string.popitem()
			if k in child_strings.keys():
				string[k] = child_strings[k]
			 	debug("[%s] OVERRIDE: %s: %s" % (parent, k, string[k]))
			else:
			 	string[k] = v

	if 'tables' in parentdict:
		i = 0
		for table in parentdict["tables"]:
			if table["name"] in child_tables.keys():
				debug("[%s] OVERRIDE TABLE: %s" % (parent, table["name"]))
				parentdict["tables"][i] = child["tables"][child_tables[table["name"]]]
			i += 1

	if 'lists' in parentdict:
		i = 0
		for alist in parentdict["lists"]:
			if alist["name"] in child_tables.keys():
				debug("[%s] OVERRIDE LIST: %s" % (parent, alist["name"]))
				parentdict["lists"][i] = child["lists"][child_tables[alist["name"]]]
			i += 1

	# Inherit any other top level keys
	for topitem in child.keys():
		debug("topitem=%s" % topitem)
		if not topitem in ["tables", "strings"]:
			parentdict[topitem] = child[topitem]

	return parentdict

def debug(msg):
	if args.debug:
		print "DEBUG: %s" % (msg)

def check_final_deploy(istat_key):
	if args.nocheck:
		return(1)

	current_time = int(time.time())
	bashurl   = "https://%s/mgmt/tm/util/bash" % (args.host)
	istat_payload = { "command":"run",
					 "utilCmdArgs":"-c 'tmsh run cli script appsvcs_get_istat \"%s\"'" % (istat_key)
	               }

	for i in range(args.checknum):
		print "[info] checking for deployment completion (%s/%s)..." % ((i+1), args.checknum)
		resp = s.post(bashurl, data=json.dumps(istat_payload))
		if resp.status_code != requests.codes.ok:
			print "ERROR: %s" % (resp.json())
			sys.exit(1)

		respdict = json.loads(resp.text)

		result = respdict.get('commandResult')
		result = result.replace('\n','')
		debug("[check_deploy] current_time=%s result=%s" % (current_time, result))
		if result.startswith("FINISHED_"):
			parts = result.split('_')
			fin_time = int(parts[1])
			if fin_time > current_time:
				return(1)
		time.sleep(args.checkwait)

	return(0)

# Setup and process arguments
parser = argparse.ArgumentParser(description='Script to deploy an iApp to a BIG-IP device')
parser.add_argument("host",             help="The IP/Hostname of the BIG-IP device")
parser.add_argument("json_template",    help="The JSON iApp definition file")
parser.add_argument("-u", "--username", help="The BIG-IP username")
parser.add_argument("-p", "--password", help="The BIG-IP password")
parser.add_argument("-d", "--dontsave", help="Don't automatically save the config", action="store_true")
parser.add_argument("-r", "--redeploy", help="Redeploy an existing iApp", action="store_true")
parser.add_argument("-D", "--debug",    help="Enable debug output", action="store_true")
parser.add_argument("-n", "--nocheck",  help="Don't check for deployment completion", action="store_true")
parser.add_argument("-c", "--checknum", help="Number of times to check for deployment completion", default=10, type=int)
parser.add_argument("-w", "--checkwait",help="Delay in seconds between each deployment completion check", default=6, type=int)

args = parser.parse_args()

print "[info] processing template \"%s\"" % (args.json_template)

try:
	iapp_file = open(args.json_template)
except IOError as error:
	print "[error] Open of JSON template \"%s\" failed: %s" % (args.json_template, error)
	sys.exit(1)

try:
	iapp = json.load(iapp_file)
except (ValueError, NameError) as error:
	print "[error] JSON format error in template \"%s\": %s" % (args.json_template, error)
	sys.exit(1)

iapp_file.close()

if 'parent' in iapp:
	final = process_file(iapp["parent"], iapp, " ")
else:
	final = iapp

if args.username:
	if 'username' in final:
		print "[info] Username found in JSON but specified on CLI, using CLI value"
	final["username"] = args.username

if args.password:
	if 'password' in final:
		print "[info] Password found in JSON but specified on CLI, using CLI value"
	final["password"] = args.password

# Required fields
required = ['name','template_name','partition','username','password','inheritedDevicegroup','inheritedTrafficGroup','deviceGroup','trafficGroup']

for item in required:
	if not item in final:
		print "[error] The required key \"%s\" was not found in the JSON template (or it's parent(s))" % (item)
		sys.exit(1)

debug("final=%s" % pp.pformat(final))

# Set our REST urls
iapp_url       = "https://%s/mgmt/tm/sys/application/service" % (args.host)
save_url       = "https://%s/mgmt/tm/sys/config" % (args.host)
template_url   = "https://%s/mgmt/tm/sys/application/template?$select=name" % (args.host)
iapp_exist_url = "%s/~%s~%s.app~%s" % (iapp_url, final["partition"], final["name"], final["name"])
bash_url       = "https://%s/mgmt/tm/util/bash" % (args.host)

# Create request session, set credentials, allow self-signed SSL cert
s = requests.session()
s.auth = (final["username"], final["password"])
s.verify = False

time_payload = {
    "command":"run",
    "utilCmdArgs":"-c 'date +%s'"
}

resp = s.post(bash_url, data=json.dumps(time_payload))

if resp.status_code == 401:
    print "[error] Authentication to %s failed" % (args.host)
    sys.exit(1)

systimejson = json.loads(resp.text)
systime = systimejson.get('commandResult')
systime = systime.replace('\n','')

debug("[check_time] %s" % systime)

delta = time.time() - int(systime)
debug("[check_time] delta=%s" % delta)

if delta > 10:
    print "[error] Time delta between local system and BIG-IP is %s.  Limit is 10 seconds.  Please ensure time is synced" % delta
    sys.exit(1)

resp = s.get(template_url)
templates = resp.json();

tmpllist = []
for item in templates["items"]:
	if item["name"].startswith("appsvcs_integration_"):
		debug("[template_list] found template named %s" % (item["name"]))
		tmpllist.append(item["name"])

debug("[template_select] specified=%s" % (final["template_name"]))
if final["template_name"] == "latest":
	tmpllist.sort()
	final["template_name"] = tmpllist.pop()
	debug("[template_select] selected=%s" % (final["template_name"]))
else:
	if not final["template_name"] in tmpllist:
		print "[error] iApp template \"%s\" is not installed on BIG-IP host %s" % (final["template_name"], args.host)
		sys.exit(1)

deploy_payload = {
    "inheritedDevicegroup": final["inheritedDevicegroup"],
    "inheritedTrafficGroup": final["inheritedTrafficGroup"],
    "deviceGroup": final["deviceGroup"],
    "trafficGroup": final["trafficGroup"],
    "template": final["template_name"],
    "partition": final["partition"],
    "name": final["name"],
    "variables": [],
    "tables": [],
    "lists":[]
}

for string in final["strings"]:
	k, v = string.popitem()
	deploy_payload["variables"].append({"name":k, "value":v})

deploy_payload["tables"] = final["tables"]
deploy_payload["lists"] = final["lists"]

# Check to see if the template with the name specified in the arguments exists on the BIG-IP device
debug("exist_url=%s" % iapp_exist_url)
resp = s.get(iapp_exist_url)

# The template exists and the -o argument (overwrite) was not specified.  Print error and exit
if resp.status_code == 200 and not args.redeploy:
	print "[error] An iApp deployment named \"%s\" already exists on BIG-IP \"%s\".  To redeploy please specify the '-r' flag" % (final["name"], args.host)
	sys.exit(1)

istat_key = "sys.application.service /%s/%s.app/%s string deploy.postdeploy_final" % (deploy_payload.get('partition'), deploy_payload.get('name'), deploy_payload.get('name'))
# iApp deployment does not already exist, create it
if resp.status_code == 404:
 	# Send the REST call to create the template and print outcome
	debug("deploy_payload=%s" % json.dumps(deploy_payload))
	resp = s.post(iapp_url, data=json.dumps(deploy_payload))
	debug("deploy resp=%s" % (pp.pformat(json.loads(resp.text))))
	if resp.status_code != requests.codes.ok:
		print "[error] iApp deployment failed: %s" % (resp.json())
		sys.exit(1)
	if check_final_deploy(istat_key):
		print "[success] iApp \"%s\" deployed on BIG-IP \"%s\"" % (final["name"], args.host)
	else:
		print "[error] iApp deployment might have failed.  Please check /var/tmp/scriptd.out on the device"
		sys.exit(1)

# iApp deployment exists and args.redeploy (-r) is TRUE so we will redeploy
else:
	del deploy_payload["inheritedDevicegroup"]
	del deploy_payload["inheritedTrafficGroup"]
	del deploy_payload["deviceGroup"]
	del deploy_payload["trafficGroup"]
	deploy_payload["execute-action"] = "definition"

	debug("redeploy_payload=%s" % json.dumps(deploy_payload))
	resp = s.put(iapp_exist_url, data=json.dumps(deploy_payload))
	debug("redeploy resp=%s" % (pp.pformat(json.loads(resp.text))))
	if resp.status_code != requests.codes.ok:
		print "[error] iApp re-deployment failed: %s" % (resp.json())
		sys.exit(1)

	if check_final_deploy(istat_key):
		print "[success] iApp \"%s\" re-deployed on BIG-IP \"%s\"" % (final["name"], args.host)
	else:
		print "[error] iApp deployment might have failed.  Please check /var/tmp/scriptd.out on the device"
		sys.exit(1)

# Save the config (unless -d option was specified)
save_payload = { "command":"save" }
if not args.dontsave:
	resp = s.post(save_url, data=json.dumps(save_payload))
	if resp.status_code != requests.codes.ok:
		print "[error] save failed: %s" % (resp.json())
		sys.exit(1)
	else:
		print "[success] Config saved"

sys.exit(0)


text:
import argparse
import json
import os
import logging

from c7n.credentials import SessionFactory
from c7n.policy import load as policy_load
from c7n import mu, resources

from botocore.exceptions import ClientError

log = logging.getLogger('resources')

def load_policies(options):
    policies = []
    for f in options.config_files:
        collection = policy_load(options, f)
        policies.extend(collection.filter(options.policy_filter))
    return policies

def resources_gc_prefix(options, policy_collection):
    """Garbage collect old custodian policies based on prefix.

    We attempt to introspect to find the event sources for a policy
    but without the old configuration this is implicit.
    """
    session_factory = SessionFactory(
        options.region, options.profile, options.assume_role)

    manager = mu.LambdaManager(session_factory)
    funcs = list(manager.list_functions('custodian-'))

    client = session_factory().client('lambda')

    remove = []
    current_policies = [p.name for p in policy_collection]
    for f in funcs:
        pn = f['FunctionName'].split('-', 1)[1]
        if pn not in current_policies:
            remove.append(f)

    for n in remove:
        events = []
        try:
            result = client.get_policy(FunctionName=n['FunctionName'])
        except ClientError as e:
            if e.response['Error']['Code'] == 'ResourceNotFoundException':
                log.warn("Lambda Function or Access Policy Statement missing: {}".
                    format(n['FunctionName']))
            else:
                log.warn("Unexpected error: {} for function {}".
                    format(e, n['FunctionName']))

            # Continue on with next function instead of raising an exception
            continue

        if 'Policy' not in result:
            pass
        else:
            p = json.loads(result['Policy'])
            for s in p['Statement']:
                principal = s.get('Principal')
                if not isinstance(principal, dict):
                    log.info("Skipping function %s" % n['FunctionName'])
                    continue
                if principal == {'Service': 'events.amazonaws.com'}:
                    events.append(
                        mu.CloudWatchEventSource({}, session_factory))

        f = mu.LambdaFunction({
            'name': n['FunctionName'],
            'role': n['Role'],
            'handler': n['Handler'],
            'timeout': n['Timeout'],
            'memory_size': n['MemorySize'],
            'description': n['Description'],
            'runtime': n['Runtime'],
            'events': events}, None)

        log.info("Removing %s" % n['FunctionName'])
        if options.dryrun:
            log.info("Dryrun skipping removal")
            continue
        manager.remove(f)
        log.info("Removed %s" % n['FunctionName'])

def setup_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-c', '--config',
        required=True, dest="config_files", action="append")
    parser.add_argument(
        '-r', '--region', default=os.environ.get(
            'AWS_DEFAULT_REGION', 'us-east-1'))
    parser.add_argument('--dryrun', action="store_true", default=False)
    parser.add_argument(
        "--profile", default=os.environ.get('AWS_PROFILE'),
        help="AWS Account Config File Profile to utilize")
    parser.add_argument(
        "--assume", default=None, dest="assume_role",
        help="Role to assume")
    parser.add_argument(
        "-v", dest="verbose", action="store_true", default=False,
        help='toggle verbose logging')
    return parser

def main():
    parser = setup_parser()
    options = parser.parse_args()
    options.policy_filter = None
    options.log_group = None
    options.external_id = None
    options.cache_period = 0
    options.cache = None
    log_level = logging.INFO
    if options.verbose:
        log_level = logging.DEBUG
    logging.basicConfig(
        level=log_level,
        format="%(asctime)s: %(name)s:%(levelname)s %(message)s")
    logging.getLogger('botocore').setLevel(logging.ERROR)
    logging.getLogger('c7n.cache').setLevel(logging.WARNING)
    resources.load_resources()

    policies = load_policies(options)
    resources_gc_prefix(options, policies)

if __name__ == '__main__':
    main()


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Progr. 4(4): 334 (2005)

#### Original name
Desmosorus oncidii Ritschel, Oberw. & Berndt, 2005

### Remarks
null


text:
package rx.internal.util;

import rx.plugins.RxJavaPlugins;

public final class RxJavaPluginUtils {

    public static void handleException(Throwable e) {
        try {
            RxJavaPlugins.getInstance().getErrorHandler().handleError(e);
        } catch (Throwable pluginException) {
            handlePluginException(pluginException);
        }
    }

    private static void handlePluginException(Throwable pluginException) {
        /*
         * We don't want errors from the plugin to affect normal flow.
         * Since the plugin should never throw this is a safety net
         * and will complain loudly to System.err so it gets fixed.
         */
        System.err.println("RxJavaErrorHandler threw an Exception. It shouldn't. => " + pluginException.getMessage());
        pluginException.printStackTrace();
    }

}


text:
<?
/**
 *
 */

// #######################
require_once "core/environment_init.php";
$boostack->renderOpenHtmlHeadTags("Profile");
$boostack->registerAbsoluteCssFile("//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css");
// #######################

require_once $boostack->registerTemplateFile("boostack/header.phtml");

if($config['session_on'] && $objSession->IsLoggedIn()){
if ( isset ( $_POST['submit'] ) ) {

// Checking null values in message.
try{
    //Validate the form
    //sanitize
    $id = sanitizeInput($_POST["id"]);
    $first_name = sanitizeInput($_POST["first_name"]);
    $last_name = sanitizeInput($_POST["last_name"]);
    $locale = sanitizeInput($_POST["locale"]);
    $city = sanitizeInput($_POST["city"]);
    $state = sanitizeInput($_POST["state"]);
    $country = sanitizeInput($_POST["country"]);
    $zip = sanitizeInput($_POST["zip"]);
    $about_me = sanitizeInput($_POST["about_me"]);
    $tel = sanitizeInput($_POST["tel"]);
    $cell = sanitizeInput($_POST["cell"]);
    $profession = sanitizeInput($_POST["profession"]);
    $birthday = sanitizeInput($_POST["birthday"]);
    $movies = sanitizeInput($_POST["movies"]);
    $music = sanitizeInput($_POST["music"]);
    $political = sanitizeInput($_POST["political"]);
    $interests = sanitizeInput($_POST["interests"]);
    $tv = sanitizeInput($_POST["tv"]);
    $religion = sanitizeInput($_POST["religion"]);
    $sex = sanitizeInput($_POST["sex"]);

    if(inputcheck($first_name) && inputcheck($last_name) && checkphone($cell) && checkphone($tel)){
        //check and validate the form
        $userprofile = new User_Info($id);
        //put data in the variable
        $arr["first_name"] = $first_name;
        $arr["last_name"] = $last_name;
        $arr["locale"] = $locale;
        $arr["city"] = $city;
        $arr["state"] = $state;
        $arr["country"] = $country;
        $arr["zip"] = $zip;
        $arr["about_me"] = $about_me;
        $arr["tel"] = $tel;
        $arr["cell"] = $cell;
        $arr["profession"] = $profession;
        $arr["birthday"] = $birthday;
        $arr["movies"] = $movies;
        $arr["music"] = $music;
        $arr["political"] = $political;
        $arr["interests"] = $interests;
        $arr["tv"] = $tv;
        $arr["religion"] = $religion;
        $arr["sex"] = $sex;
        $userprofile -> update($arr);
        $result= "Success";
    }

}catch (Exception $e) {
    $error = $e->getMessage();
}

}
    $userInfo = new User_Info($CURRENTUSER->id);
    require_once $boostack->registerTemplateFile("boostack/content_profile_edit.phtml");
}else
    require_once $boostack->registerTemplateFile("boostack/content_login.phtml");

require_once $boostack->registerTemplateFile("boostack/footer.phtml");

/**
if($config['session_on'] && $objSession->IsLoggedIn()){
    if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $id = sanitizeInput($_POST["id"]);
    $first_name = sanitizeInput($_POST["first_name"]);
    $last_name = sanitizeInput($_POST["last_name"]);
    $locale = sanitizeInput($_POST["locale"]);
    $city = sanitizeInput($_POST["city"]);
    $state = sanitizeInput($_POST["state"]);
    $country = sanitizeInput($_POST["country"]);
    $zip = sanitizeInput($_POST["zip"]);
    $about_me = sanitizeInput($_POST["about_me"]);
    $tel = sanitizeInput($_POST["tel"]);
    $cell = sanitizeInput($_POST["cell"]);
    $profession = sanitizeInput($_POST["profession"]);
    $birthday = sanitizeInput($_POST["birthday"]);
    $movies = sanitizeInput($_POST["movies"]);
    $music = sanitizeInput($_POST["music"]);
    $political = sanitizeInput($_POST["political"]);
    $interests = sanitizeInput($_POST["interests"]);
    $tv = sanitizeInput($_POST["tv"]);
    $religion = sanitizeInput($_POST["religion"]);

    $sex = sanitizeInput($_POST["sex"]);

    if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
        $err_first_name = "Only letters and white space allowed";
    }

    $userprofile = new User_Info($id);
    $arr["first_name"] = $first_name;
    $arr["last_name"] = $last_name;
    $arr["locale"] = $locale;
    $arr["city"] = $city;
    $arr["state"] = $state;
    $arr["country"] = $country;
    $arr["zip"] = $zip;
    $arr["about_me"] = $about_me;
    $arr["tel"] = $tel;
    $arr["cell"] = $cell;
    $arr["profession"] = $profession;
    $arr["birthday"] = $birthday;
    $arr["movies"] = $movies;
    $arr["music"] = $music;
    $arr["political"] = $political;
    $arr["interests"] = $interests;
    $arr["tv"] = $tv;
    $arr["religion"] = $religion;

    $arr["sex"] = $sex;
    $userprofile -> update($arr);

}

    $userInfo = new User_Info($CURRENTUSER->id);
    require_once $boostack->registerTemplateFile("boostack/content_profile_edit.phtml");

}else
    require_once $boostack->registerTemplateFile("boostack/content_login.phtml");

require_once $boostack->registerTemplateFile("boostack/footer.phtml");
**/
// #######################

$boostack->renderCloseHtmlTag();
//import jquery ui .js
$boostack->registerAbsoluteScriptFile("//code.jquery.com/ui/1.11.4/jquery-ui.js");
$boostack->registerScriptFile("validator.js");
$boostack->writeLog("Homepage Page");
// #######################
?>


text:
require File.join(File.dirname(__FILE__), "mixins", "web_controller")
module Merb

  # A Merb::PartController is a light weight way to share logic and templates
  # amongst controllers.
  # Merb::PartControllers work just like Merb::controller.
  # There is a filter stack, layouts (if needed) all the render functions,
  # and url generation.
  #
  # Cookies, params, and even the request object are shared with the web controller
  class PartController < AbstractController
    include Merb::Mixins::WebController

    attr_reader :params

    cattr_accessor :_subclasses
    self._subclasses = Set.new

    # ==== Returns
    # Array[Class]:: Classes that inherit from Merb::PartController.
    def self.subclasses_list() _subclasses end

    # ==== Parameters
    # action<~to_s>:: The name of the action that will be rendered.
    # type<~to_s>::
    #    The mime-type of the template that will be rendered. Defaults to html.
    # controller<~to_s>::
    #   The name of the controller that will be rendered. Defaults to
    #   controller_name.
    #
    # ==== Returns
    # String:: The template location, i.e. ":controller/:action.:type".
    def _template_location(action, type = :html, controller = controller_name)
      "#{controller}/#{action}.#{type}"
    end

    # The location to look for a template and mime-type. This is overridden
    # from AbstractController, which defines a version of this that does not
    # involve mime-types.
    #
    # ==== Parameters
    # template<String>::
    #    The absolute path to a template - without mime and template extension.
    #    The mime-type extension is optional - it will be appended from the
    #    current content type if it hasn't been added already.
    # type<~to_s>::
    #    The mime-type of the template that will be rendered. Defaults to nil.
    #
    # @public
    def _absolute_template_location(template, type)
      template.match(/\.#{type.to_s.escape_regexp}$/) ? template : "#{template}.#{type}"
    end

    # Sets the template root to the default parts view directory.
    #
    # ==== Parameters
    # klass<Class>::
    #   The Merb::PartController inheriting from the base class.
    def self.inherited(klass)
      _subclasses << klass.to_s
      super
      klass._template_root = Merb.dir_for(:part) / "views" unless self._template_root
    end

    # ==== Parameters
    # web_controller<Merb::Controller>:: The controller calling this part.
    # opts<Hash>:: Additional options for this part.
    def initialize(web_controller, opts = {})
      @web_controller = web_controller
      @params = @web_controller.params.dup
      @params.merge!(opts) unless opts.empty?
      super
      @content_type = @web_controller.content_type
    end

    # ==== Parameters
    # action<~to_s>:: An action to dispatch to. Defaults to :to_s.
    #
    # ==== Returns
    # String:: The part body.
    def _dispatch(action=:to_s)
      action = action.to_s
      self.action_name = action
      super(action)
      @body
    end

    # Send any methods that are missing back up to the web controller
    # Patched to set partial locals on the web controller
    def method_missing(sym, *args, &blk)
      @web_controller.instance_variable_set(:@_merb_partial_locals, @_merb_partial_locals)
      @web_controller.send(sym, *args, &blk)
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">

  <meta name="generator" content=
  "HTML Tidy for Linux (vers 25 March 2009), see www.w3.org">

  <title>MATHO-PRIMES(1) manual page</title>

  Table of Contents

Name
matho-primes -
  generate consecutive prime numbers

Synopsis
matho-primes [start [stop] or
  "all"] ["twin"] ["pal" [base]]

  matho-primes [-htuv] [-c count] [-m number] [-p base]
  [start [stop]]

Description
This
  command-line utility is optionally part of the mathomatic(1) package. It quickly
  computes any number of consecutive prime numbers using a
  windowing, memory efficient sieve of Eratosthenes algorithm,
  dumping them to standard output. They are displayed one prime per
  line in ascending order, unless the "twin" option is specified,
  which displays only twin primes, two primes per line.

Generates up to 18 decimal digit primes, or whatever is the
  number of digits of precision for a floating point long
  double in the C compiler used to compile this utility. Note
  that this utility might be compiled to use only double precision
  floating point, if long double precision is not fully supported
  by the C compiler or hardware, allowing at most 15 decimal digit
  primes in that case.

Ways to verify that this utility is working are to pipe the
  output into the Unix "factor" utility, or compare the output with
  the BSD Games "primes" utility, using the supplied shell script:
  examples/testprimes.

All numbers displayed by this utility are decimal (base 10)
  prime numbers. A prime number is an integer that cannot be
  factored.

A range may be specified on the command line, otherwise the
  starting number and the number of primes to output is prompted
  for. The range is start to stop inclusive, and
  stop must be greater than or equal to start.

If the -c option is specified, the number of lines of
  primes displayed is limited to the decimal count that follows
  this option.

If the -t or "twin" option is specified on the command
  line, only twin primes will be displayed. Twin primes are
  two primes that differ in value by 2. Each twin pair is displayed
  together on the same line separated by a space character.

If the -p or "pal" option is specified on the command
  line, only palindromic primes are displayed. Palindromes
  are symmetrical, they read exactly the same forward and backward.
  The palindromic number base may be specified, the default
  is base 10. The base can be any integer greater than 1.
  Primes are always displayed in decimal (base 10).

The version number and short help on the allowed command-line
  parameters and usage information are displayed when given the
  -h option.

With the -u option, all output (standard output and
  standard error output) is set to be unbuffered, making all output
  happen immediately, instead of when the output buffer is full or
  when the program terminates or waits for input.

The -m option changes the memory size of the prime
  number sieve window. It is followed by a decimal, floating point
  number which is a multiplier of the default window size (2
  megabytes). It is possible that changing the memory size may
  speed up the total run time a bit; otherwise there is no reason
  to use this option, and its use is not recommended.

The -v option simply displays the program name and
  version number, and then exits successfully.

Author
George Gesslein
  II (gesslein@mathomatic.org) at "http://www.mathomatic.org ".

Reporting Bugs
If you
  find a bug, please report it to the author or at "https://launchpad.net/mathomatic
  ".

See Also
rmath(1) , mathomatic(1) , primorial(1) , matho-mult(1) , matho-sum(1) , matho-pascal(1) , matho-sumsq(1)

Table of Contents

Name

Synopsis

Description

Author

Reporting Bugs

See Also


text:
"""Extension package for the Ecpy application.

"""
from __future__ import (division, unicode_literals, print_function,
                        absolute_import)

import enaml

def list_manifests():
    """List the manifest that should be regsitered when the main Ecpy app is
    started.

    """
    with enaml.imports():
        from .manifest import ExtDemoManifest
    return [ExtDemoManifest]


text:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using MinimalisticCQRS.Infrastructure;

namespace MinimalisticCQRS.Specs
{
    public class SpecBus : MiniVan
    {
        public readonly List<Message> ResultingEvents = new List<Message>();

        protected Verifier verifier;

        public override void Apply(Message msg)
        {
            ResultingEvents.Add(msg);
            base.Apply(msg);
        }

        public SpecBus(MiniVanRegistry mvr)
            : base(mvr)
        {
            verifier = new Verifier(ResultingEvents);
        }

        public void GivenEvent(Action<dynamic> a)
        {
            a(this as dynamic);
            ResultingEvents.Clear();
        }

        public void WhenCommand(Action<dynamic> a)
        {
            ResultingEvents.Clear();
            try
            {
                verifier.Except = null;
                a(this as dynamic);
            }
            catch (Exception e)
            {
                if (e is System.Reflection.TargetInvocationException)
                    e = e.InnerException;
                verifier.Except = e;
            }
            ResultingEvents.RemoveAt(0);
        }

        public void ThenExpectEvent(Action<dynamic> a)
        {
            verifier.Then(a);
        }

        public void ThenDoNotExpectEvent(Action<dynamic> a)
        {
            verifier.ThenNot(a);
        }

        public void ThenExpectException<T>(Predicate<T> a = null) where T : Exception
        {
            verifier.ThenException<T>(a);
        }

        // support for message classes
        public void GivenEvent(object @event)
        {
            GivenEvent(x => x.Handle(@event));
        }

        public void WhenCommand(object command)
        {
            WhenCommand(x => x.Handle(command));
        }

        public void ThenExpectEvent(object @event)
        {
            verifier.Then(@event);
        }

        public void ThenDoNotExpectEvent(object @event)
        {
            verifier.ThenNot(@event);
        }

        protected class Verifier : DynamicObject
        {
            public Verifier(List<Message> input)
            {
                this.input = input;
            }

            Message msg = null;
            public Exception Except = null;
            private List<Message> input;

            public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
            {
                msg = new Message(binder, args);
                result = null;
                return true;
            }

            public void Then(Action<dynamic> a)
            {
                a(this);
                Then(msg);
            }

            public void Then(object o)
            {
                msg = (o as Message) ?? new Message(o);
                if (input.All(x => x != msg))
                {
                    var txt = MessageToText(msg);
                    var amsg = "Expected \n * " + txt + "\n but could not find it.";
                    var matches = input.Select(x => MessageToText(x))
                        .Select(x => new { distance = Levenshtein.Distance(txt, x), Event = x })
                        .OrderBy(x => x.distance)
                        .Take(5).Select(x => x.Event).ToArray();
                    amsg += "\nTop 5 of best possible matching events are:\n" + string.Join("\n * ", matches);
                    AssertFail(amsg);
                }
            }

            public void ThenNot(Action<dynamic> a)
            {
                a(this);
                ThenNot(msg);
            }

            public void ThenNot(object o)
            {
                msg = (o as Message) ?? new Message(o);
                if (input.Any(x => x == msg))
                {
                    AssertFail("Expected " + MessageToText(msg) + " but could not find it");
                }
            }

            public void ThenException<T>(Predicate<T> assertion = null) where T : Exception
            {
                if ((this.Except as T) == null)
                    AssertFail("Expected an exception of type " + typeof(T) + " but found none");
                if (assertion != null && !assertion(Except as T))
                {
                    AssertFail("Received an exception of type " + typeof(T) + " but the assertion did not match");
                }
            }

            private void AssertFail(string message)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(message);
            }
        }

        public static string MessageToText(Message msg)
        {
            var sb = new StringBuilder();
            sb.Append(msg.MethodName);
            sb.Append("(");
            foreach (var kv in msg.Parameters)
            {
                sb.Append(kv.Key);
                sb.Append("=");
                sb.Append((kv.Value ?? "").ToString());
                if (kv.Key != msg.Parameters.Last().Key)
                    sb.Append(",");
            }
            sb.Append(")");
            return sb.ToString();
        }
    }
}


text:
use consts::SAMPLES_PER_FRAME;

/// Represents the bit vectors u0, ..., u7, in that order.
pub type Chunks = [u32; 8];

/// Represents the number of detected Hamming/Golay bit errors, ϵ0, ...,
/// ϵ6, corresponding to the chunks u0, ..., u6.
pub type Errors = [usize; 7];

/// A received IMBE voice frame.
pub struct ReceivedFrame {
    /// Prioritized bit vector chunks, u0, ..., u7.
    pub chunks: Chunks,
    /// Error correction counts, ϵ0, ..., ϵ6.
    pub errors: Errors,
}

impl ReceivedFrame {
    /// Create a new `ReceivedFrame` from the given chunks u0, ...,
    /// u7 and error counts ϵ0, ..., ϵ6.
    pub fn new(chunks: Chunks, errors: Errors) -> ReceivedFrame {
        // First 4 chunks must have at most 12 bits.
        for i in 0..=3 {
            assert!(chunks[i] >> 12 == 0);
        }

        // Next 3 chunks must have at most 11 bits.
        for i in 4..=6 {
            assert!(chunks[i] >> 11 == 0);
        }

        // Final chunk must have at most 7 bits.
        assert!(chunks[7] >> 7 == 0);

        ReceivedFrame {
            chunks: chunks,
            errors: errors,
        }
    }
}

/// Audio samples in a decoded voice frame.
pub type AudioBuf = [f32; SAMPLES_PER_FRAME];


text:
body {
  padding-top: 0px;  /* Move body of page below navbar. */
  font-family: "Open Sans";
  color: #999;
  background-color: grey;

}

.page-content {
  padding: 10px;
  text-align: center;
}

.banner {
  padding-top: 0px;
  margin-top: 0px;
  height: 180px;
  background-image: url("../images/header.jpg");
  background-size: cover;
}

.navbar {
  background-color: darkred;
  font-family: "Open Sans";
}

.well {
  color: grey;
  background-color: darkred;
  border:none;
}

.menu{
  list-style-type: none;

}

.photo{
  background-image: url("../images/frontpage.jpg");
  height: 400px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center
}

.visible-xs-block{
  display:block;
}


text:
"""
=====================================================
Gaussian process classification (GPC) on iris dataset
=====================================================

This example illustrates the predicted probability of GPC for an isotropic
and anisotropic RBF kernel on a two-dimensional version for the iris-dataset.
The anisotropic RBF kernel obtains slightly higher log-marginal-likelihood by
assigning different length-scales to the two feature dimensions.
"""
print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF

# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2]  # we only take the first two features.
y = np.array(iris.target, dtype=int)

h = .02  # step size in the mesh

kernel = 1.0 * RBF([1.0])
gpc_rbf_isotropic = GaussianProcessClassifier(kernel=kernel).fit(X, y)
kernel = 1.0 * RBF([1.0, 1.0])
gpc_rbf_anisotropic = GaussianProcessClassifier(kernel=kernel).fit(X, y)

# create a mesh to plot in
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

titles = ["Isotropic RBF", "Anisotropic RBF"]
plt.figure(figsize=(10, 5))
for i, clf in enumerate((gpc_rbf_isotropic, gpc_rbf_anisotropic)):
    # Plot the predicted probabilities. For that, we will assign a color to
    # each point in the mesh [x_min, m_max]x[y_min, y_max].
    plt.subplot(1, 2, i + 1)

    Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape((xx.shape[0], xx.shape[1], 3))
    plt.imshow(Z, extent=(x_min, x_max, y_min, y_max), origin="lower")

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=np.array(["r", "g", "b"])[y],
                edgecolors=(0, 0, 0))
    plt.xlabel('Sepal length')
    plt.ylabel('Sepal width')
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())
    plt.title("%s, LML: %.3f" %
              (titles[i], clf.log_marginal_likelihood(clf.kernel_.theta)))

plt.tight_layout()
plt.show()