PageRenderTime 41ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 1ms

/brython.js

https://bitbucket.org/olemis/brython-git
JavaScript | 5400 lines | 5397 code | 0 blank | 3 comment | 721 complexity | 2b3b992a411831b336b4d525699e7589 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. // brython.js www.brython.info
  2. // version 1.1.20130319-232656
  3. // version compiled from commented, indented source files at http://code.google.com/p/brython/
  4. __BRYTHON__=new Object()
  5. __BRYTHON__.__getattr__=function(attr){return this[attr]}
  6. __BRYTHON__.date=function(){
  7. if(arguments.length===0){return JSObject(new Date())}
  8. else if(arguments.length===1){return JSObject(new Date(arguments[0]))}
  9. else if(arguments.length===7){return JSObject(new Date(arguments[0],
  10. arguments[1]-1,arguments[2],arguments[3],
  11. arguments[4],arguments[5],arguments[6]))}
  12. }
  13. __BRYTHON__.has_local_storage=typeof(Storage)!=="undefined"
  14. if(__BRYTHON__.has_local_storage){
  15. __BRYTHON__.local_storage=function(){return JSObject(localStorage)}
  16. }
  17. __BRYTHON__.has_json=typeof(JSON)!=="undefined"
  18. __BRYTHON__.version_info=[1,1,"20130319-232656"]
  19. __BRYTHON__.path=[]
  20. function abs(obj){
  21. if(isinstance(obj,int)){return int(Math.abs(obj))}
  22. else if(isinstance(obj,float)){return float(Math.abs(obj.value))}
  23. else if('__abs__' in obj){return obj.__abs__()}
  24. else{throw TypeError("Bad operand type for abs(): '"+str(obj.__class__)+"'")}
  25. }
  26. function $alert(src){alert(str(src))}
  27. function all(iterable){
  28. while(true){
  29. try{
  30. var elt=next(iterable)
  31. if(!bool(elt)){return False}
  32. }catch(err){return True}
  33. }
  34. }
  35. function any(iterable){
  36. if(iterable.__item__===undefined){
  37. throw TypeError("'"+iterable.__class__.__name__+"' object is not iterable")
  38. }
  39. while(true){
  40. try{
  41. var elt=next(iterable)
  42. if(bool(elt)){return True}
  43. }catch(err){return False}
  44. }
  45. }
  46. function assert_raises(){
  47. var $ns=$MakeArgs('assert_raises',arguments,['exc','func'],{},'args','kw')
  48. var args=$ns['args']
  49. try{$ns['func'].apply(this,args)}
  50. catch(err){
  51. if(err.name!==$ns['exc']){
  52. throw AssertionError(
  53. "exception raised '"+err.name+"', expected '"+$ns['exc']+"'")
  54. }
  55. return
  56. }
  57. throw AssertionError("no exception raised, expected '"+$ns['exc']+"'")
  58. }
  59. function bool(obj){
  60. if(obj===null){return False}
  61. else if(obj===undefined){return False}
  62. else if(isinstance(obj,dict)){return obj.keys.length>0}
  63. else if(isinstance(obj,tuple)){return obj.length>0}
  64. else if(typeof obj==="boolean"){return obj}
  65. else if(typeof obj==="number" || typeof obj==="string"){
  66. if(obj){return true}else{return false}
  67. }else if('__bool__' in obj){return obj.__bool__()}
  68. else if('__len__' in obj){return obj.__len__()>0}
  69. return true
  70. }
  71. bool.__class__=$type
  72. bool.__name__='bool'
  73. bool.__str__=function(){return "<class 'bool'>"}
  74. bool.toString=bool.__str__
  75. bool.__hash__=function(){
  76. if(this.valueOf())return 1
  77. return 0
  78. }
  79. function $class(obj,info){
  80. this.obj=obj
  81. this.info=info
  82. this.__class__=Object
  83. this.toString=function(){return "<class '"+info+"'>"}
  84. }
  85. function $confirm(src){return confirm(src)}
  86. function $DictClass($keys,$values){
  87. var x=null
  88. var i=null
  89. this.iter=null
  90. this.__class__=dict
  91. this.$keys=$keys
  92. this.$values=$values
  93. }
  94. function dict(){
  95. if(arguments.length==0){return new $DictClass([],[])}
  96. else if(arguments.length===1 && isinstance(arguments[0],dict)){
  97. return arguments[0]
  98. }
  99. var $ns=$MakeArgs('dict',arguments,[],{},'args','kw')
  100. var args=$ns['args']
  101. var kw=$ns['kw']
  102. if(args.length>0){
  103. var iterable=args[0]
  104. var obj=new $DictClass([],[])
  105. for(var i=0;i<iterable.__len__();i++){
  106. var elt=iterable.__item__(i)
  107. obj.__setitem__(elt.__item__(0),elt.__item__(1))
  108. }
  109. return obj
  110. }else if(kw.$keys.length>0){
  111. return kw
  112. }
  113. }
  114. dict.__name__='dict'
  115. dict.toString=function(){return "<class 'dict'>"}
  116. dict.__add__=function(self,other){
  117. var msg="unsupported operand types for +:'dict' and "
  118. throw TypeError(msg+"'"+(str(other.__class__)|| typeof other)+"'")
  119. }
  120. dict.__class__=$type
  121. dict.__contains__=function(self,item){
  122. return self.$keys.__contains__(item)
  123. }
  124. dict.__delitem__=function(self,arg){
  125. for(var i=0;i<self.$keys.length;i++){
  126. if(arg.__eq__(self.$keys[i])){
  127. self.$keys.splice(i,1)
  128. self.$values.splice(i,1)
  129. return
  130. }
  131. }
  132. throw KeyError(str(arg))
  133. }
  134. dict.__eq__=function(self,other){
  135. if(other===undefined){
  136. return self===dict
  137. }
  138. if(!isinstance(other,dict)){return False}
  139. if(other.$keys.length!==self.$keys.length){return False}
  140. for(var i=0;i<self.$keys.length;i++){
  141. var key=self.$keys[i]
  142. for(j=0;j<other.$keys.length;j++){
  143. try{
  144. if(other.$keys[j].__eq__(key)){
  145. if(!other.$values[j].__eq__(self.$values[i])){
  146. return False
  147. }
  148. }
  149. }catch(err){void(0)}
  150. }
  151. }
  152. return True
  153. }
  154. dict.__getattr__=function(attr){
  155. if(this[attr]!==undefined){return this[attr]}
  156. else{throw AttributeError("'dict' object has no attribute '"+attr+"'")}
  157. }
  158. dict.__getitem__=function(self,arg){
  159. for(var i=0;i<self.$keys.length;i++){
  160. if(arg.__eq__(self.$keys[i])){return self.$values[i]}
  161. }
  162. throw KeyError(str(arg))
  163. }
  164. dict.__hash__=function(self){throw TypeError("unhashable type: 'dict'");}
  165. dict.__in__=function(self,item){return item.__contains__(self)}
  166. dict.__item__=function(self,i){return self.$keys[i]}
  167. dict.__len__=function(self){return self.$keys.length}
  168. dict.__ne__=function(self,other){return !dict.__eq__(self,other)}
  169. dict.__next__=function(self){
  170. if(self.iter==null){self.iter==0}
  171. if(self.iter<self.$keys.length){
  172. self.iter++
  173. return self.$keys[self.iter-1]
  174. }else{
  175. self.iter=null
  176. throw StopIteration()
  177. }
  178. }
  179. dict.__not_in__=function(self,item){return !(item.__contains__(self))}
  180. dict.__setitem__=function(self,key,value){
  181. for(var i=0;i<self.$keys.length;i++){
  182. try{
  183. if(key.__eq__(self.$keys[i])){
  184. self.$values[i]=value
  185. return
  186. }
  187. }catch(err){
  188. void(0)
  189. }
  190. }
  191. self.$keys.push(key)
  192. self.$values.push(value)
  193. }
  194. dict.__str__=function(self){
  195. if(self===undefined){return "<class 'dict'>"}
  196. if(self.$keys.length==0){return '{}'}
  197. var res="{",key=null,value=null,i=null
  198. var qesc=new RegExp('"',"g")
  199. for(var i=0;i<self.$keys.length;i++){
  200. if(typeof self.$keys[i]==="string"){key='"'+$escape_dq(self.$keys[i])+'"'}
  201. else{key=str(self.$keys[i])}
  202. if(typeof self.$values[i]==="string"){value='"'+$escape_dq(self.$values[i])+'"'}
  203. else{value=str(self.$values[i])}
  204. res +=key+':'+value+','
  205. }
  206. return res.substr(0,res.length-1)+'}'
  207. }
  208. dict.items=function(self){
  209. return new $iterator(zip(self.$keys,self.$values),"dict_items")
  210. }
  211. dict.keys=function(self){
  212. return new $iterator(self.$keys,"dict keys")
  213. }
  214. dict.update=function(self){
  215. var params=[]
  216. for(var i=1;i<arguments.length;i++){params.push(arguments[i])}
  217. var $ns=$MakeArgs('dict.update',params,[],{},'args','kw')
  218. var args=$ns['args']
  219. if(args.length>0 && isinstance(args[0],dict)){
  220. var other=args[0]
  221. for(var i=0;i<other.$keys.length;i++){
  222. dict.__setitem__(self,other.$keys[i],other.$values[i])
  223. }
  224. }
  225. var kw=$ns['kw']
  226. console.log('kw '+kw.__class__)
  227. var keys=list(kw.keys())
  228. for(var i=0;i<keys.__len__();i++){
  229. dict.__setitem__(self,keys[i],kw.__getitem__(keys[i]))
  230. }
  231. }
  232. dict.values=function(self){
  233. return new $iterator(self.$values,"dict values")
  234. }
  235. $DictClass.prototype.__class__=dict
  236. $DictClass.prototype.__getattr__=function(attr){
  237. if(attr==='__class__'){return this.__class__}
  238. if(dict[attr]===undefined){throw AttributeError("'dict' object has no attribute '"+attr+"'")}
  239. var obj=this
  240. var res=function(){
  241. var args=[obj]
  242. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  243. return dict[attr].apply(obj,args)
  244. }
  245. res.__str__=function(){return "<built-in method "+attr+" of dict object>"}
  246. return res
  247. }
  248. for(var attr in dict){
  249. if($DictClass.prototype[attr]===undefined){
  250. $DictClass.prototype[attr]=(function(attr){
  251. return function(){
  252. var args=[this]
  253. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  254. return dict[attr].apply(this,args)
  255. }
  256. })(attr)
  257. }
  258. }
  259. function dir(obj){
  260. var res=[]
  261. for(var attr in obj){res.push(attr)}
  262. res.sort()
  263. return res
  264. }
  265. function enumerate(iterator){
  266. var res=[]
  267. for(var i=0;i<iterator.__len__();i++){
  268. res.push([i,iterator.__item__(i)])
  269. }
  270. return res
  271. }
  272. function $eval(src){
  273. if(src===""){throw SyntaxError("unexpected EOF while parsing")}
  274. try{return eval(__BRYTHON__.py2js(src).to_js())}
  275. catch(err){
  276. if(err.py_error===undefined){throw RuntimeError(err.message)}
  277. if(document.$stderr){document.$stderr.__getattr__('write')(document.$stderr_buff+'\n')}
  278. else{err.message +=err.info;throw(err)}
  279. }
  280. }
  281. function exec(src){
  282. try{eval(__BRYTHON__.py2js(src).to_js())}
  283. catch(err){
  284. console.log(err)
  285. if(err.py_error===undefined){err=RuntimeError(err+'')}
  286. var trace=err.__name__+': '+err.message
  287. if(err.__name__=='SyntaxError'||err.__name__==='IndentationError'){
  288. trace +=err.info
  289. }
  290. if(document.$stderr){document.$stderr.__getattr__('write')(trace)}
  291. else{err.message +=err.info}
  292. throw err
  293. }
  294. }
  295. function filter(){
  296. if(arguments.length!=2){throw TypeError(
  297. "filter expected 2 arguments, got "+arguments.length)}
  298. var func=arguments[0],iterable=arguments[1]
  299. var res=[]
  300. for(var i=0;i<iterable.__len__();i++){
  301. if(func(iterable.__item__(i))){
  302. res.push(iterable.__item__(i))
  303. }
  304. }
  305. return res
  306. }
  307. function float(value){
  308. if(value===undefined){return new $FloatClass(0.0)}
  309. if(typeof value=="number" ||(typeof value=="string" && !isNaN(value))){
  310. return new $FloatClass(parseFloat(value))
  311. }
  312. if(isinstance(value,float))return value
  313. if(value=='inf')return new $FloatClass(Infinity)
  314. if(value=='-inf')return new $FloatClass(-Infinity)
  315. if(typeof value=='string' && value.toLowerCase()=='nan')return new $FloatClass(Number.NaN)
  316. throw ValueError("Could not convert to float(): '"+str(value)+"'")
  317. }
  318. float.__class__=$type
  319. float.__name__='float'
  320. float.toString=function(){return "<class 'float'>"}
  321. float.__hash__=function(){
  322. frexp=function(re){
  323. var ex=Math.floor(Math.log(re)/ Math.log(2))+ 1
  324. var frac=re / Math.pow(2, ex)
  325. return[frac, ex]
  326. }
  327. if(this.value===Infinity || this.value===-Infinity){
  328. if(this.value < 0.0)return -271828
  329. return 314159
  330. }else if(isNaN(this.value)){
  331. return 0
  332. }
  333. var r=frexp(this.value)
  334. r[0]*=Math.pow(2,31)
  335. hipart=int(r[0])
  336. r[0]=(r[0]- hipart)* Math.pow(2,31)
  337. var x=hipart + int(r[0])+(r[1]<< 15)
  338. return x & 0xFFFFFFFF
  339. }
  340. function $FloatClass(value){
  341. this.value=value
  342. this.__class__=float
  343. this.__hash__=float.__hash__
  344. }
  345. $FloatClass.prototype.toString=function(){
  346. var res=this.value+''
  347. if(res.indexOf('.')==-1){res+='.0'}
  348. return str(res)
  349. }
  350. $FloatClass.prototype.__class__=float
  351. $FloatClass.prototype.__bool__=function(){return bool(this.value)}
  352. $FloatClass.prototype.__floordiv__=function(other){
  353. if(isinstance(other,int)){
  354. if(other===0){throw ZeroDivisionError('division by zero')}
  355. else{return float(Math.floor(this.value/other))}
  356. }else if(isinstance(other,float)){
  357. if(!other.value){throw ZeroDivisionError('division by zero')}
  358. else{return float(Math.floor(this.value/other.value))}
  359. }else{throw TypeError(
  360. "unsupported operand type(s) for //: 'int' and '"+other.__class__+"'")
  361. }
  362. }
  363. $FloatClass.prototype.__getattr__=function(attr){
  364. if(this[attr]!==undefined){return this[attr]}
  365. else{throw AttributeError("'float' object has no attribute '"+attr+"'")}
  366. }
  367. $FloatClass.prototype.__hash__=float.__hash__
  368. $FloatClass.prototype.__in__=function(item){return item.__contains__(this)}
  369. $FloatClass.prototype.__not_in__=function(item){return !(item.__contains__(this))}
  370. $FloatClass.prototype.__str__=$FloatClass.prototype.toString
  371. $FloatClass.prototype.__truediv__=function(other){
  372. if(isinstance(other,int)){
  373. if(other===0){throw ZeroDivisionError('division by zero')}
  374. else{return float(this.value/other)}
  375. }else if(isinstance(other,float)){
  376. if(!other.value){throw ZeroDivisionError('division by zero')}
  377. else{return float(this.value/other.value)}
  378. }else{throw TypeError(
  379. "unsupported operand type(s) for //: 'int' and '"+other.__class__+"'")
  380. }
  381. }
  382. var $op_func=function(other){
  383. if(isinstance(other,int)){return float(this.value-other)}
  384. else if(isinstance(other,float)){return float(this.value-other.value)}
  385. else if(isinstance(other,bool)){
  386. var bool_value=0;
  387. if(other.valueOf())bool_value=1
  388. return float(this.value-bool_value)}
  389. else{throw TypeError(
  390. "unsupported operand type(s) for -: "+this.value+" (float) and '"+other.__class__+"'")
  391. }
  392. }
  393. $op_func +=''
  394. var $ops={'+':'add','-':'sub','*':'mul','%':'mod'}
  395. for($op in $ops){
  396. eval('$FloatClass.prototype.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op))
  397. }
  398. var $comp_func=function(other){
  399. if(isinstance(other,int)){return this.value > other.valueOf()}
  400. else if(isinstance(other,float)){return this.value > other.value}
  401. else{throw TypeError(
  402. "unorderable types: "+this.__class__+'() > '+other.__class__+"()")
  403. }
  404. }
  405. $comp_func +=''
  406. var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le','==':'eq','!=':'ne'}
  407. for($op in $comps){
  408. eval("$FloatClass.prototype.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
  409. }
  410. var $notimplemented=function(other){
  411. throw TypeError(
  412. "unsupported operand types for OPERATOR: '"+this.__class__+"' and '"+other.__class__+"'")
  413. }
  414. $notimplemented +=''
  415. for($op in $operators){
  416. var $opfunc='__'+$operators[$op]+'__'
  417. if(!($opfunc in $FloatClass.prototype)){
  418. eval('$FloatClass.prototype.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
  419. }
  420. }
  421. function getattr(obj,attr,_default){
  422. if(obj.__getattr__!==undefined &&
  423. obj.__getattr__(attr)!==undefined){
  424. return obj.__getattr__(attr)
  425. }
  426. else if(_default !==undefined){return _default}
  427. else{throw AttributeError(
  428. "'"+str(obj.__class__)+"' object has no attribute '"+attr+"'")}
  429. }
  430. function hasattr(obj,attr){
  431. try{getattr(obj,attr);return True}
  432. catch(err){return False}
  433. }
  434. function hash(obj){
  435. if(isinstance(obj, int)){return obj.valueOf();}
  436. if(isinstance(obj, bool)){return int(obj);}
  437. if(obj.__hashvalue__ !==undefined){return obj.__hashvalue__;}
  438. if(obj.__hash__ !==undefined){
  439. obj.__hashvalue__=obj.__hash__()
  440. return obj.__hashvalue__
  441. }else{
  442. throw AttributeError(
  443. "'"+str(obj.__class__)+"' object has no attribute '__hash__'")
  444. }
  445. }
  446. function input(src){
  447. return prompt(src)
  448. }
  449. function int(value){
  450. if(value===undefined){return 0}
  451. else if(isinstance(value,int)){return value}
  452. else if(value===True){return 1}
  453. else if(value===False){return 0}
  454. else if(typeof value=="number" ||
  455. (typeof value=="string" && parseInt(value)!=NaN)){
  456. return parseInt(value)
  457. }else if(isinstance(value,float)){
  458. return parseInt(value.value)
  459. }else{throw ValueError(
  460. "Invalid literal for int() with base 10: '"+str(value)+"'"+value.__class__)
  461. }
  462. }
  463. int.__class__=$type
  464. int.__name__='int'
  465. int.toString=function(){return "<class 'int'>"}
  466. Number.prototype.__class__=int
  467. Number.prototype.__floordiv__=function(other){
  468. if(isinstance(other,int)){
  469. if(other==0){throw ZeroDivisionError('division by zero')}
  470. else{return Math.floor(this/other)}
  471. }else if(isinstance(other,float)){
  472. if(!other.value){throw ZeroDivisionError('division by zero')}
  473. else{return float(Math.floor(this/other.value))}
  474. }else{$UnsupportedOpType("//","int",other.__class__)}
  475. }
  476. Number.prototype.__getattr__=function(attr){
  477. if(this[attr]!==undefined){return this[attr]}
  478. throw AttributeError("'int' object has no attribute '"+attr+"'")
  479. }
  480. Number.prototype.__hash__=function(){return this.valueOf()}
  481. Number.prototype.__in__=function(item){return item.__contains__(this)}
  482. Number.prototype.__int__=function(){return this}
  483. Number.prototype.__mul__=function(other){
  484. var val=this.valueOf()
  485. if(isinstance(other,int)){return this*other}
  486. else if(isinstance(other,float)){return float(this*other.value)}
  487. else if(isinstance(other,bool)){
  488. var bool_value=0
  489. if(other.valueOf())bool_value=1
  490. return this*bool_value}
  491. else if(typeof other==="string"){
  492. var res=''
  493. for(var i=0;i<val;i++){res+=other}
  494. return res
  495. }else if(isinstance(other,[list,tuple])){
  496. var res=[]
  497. var $temp=other.slice(0,other.length)
  498. for(var i=0;i<val;i++){res=res.concat($temp)}
  499. if(isinstance(other,tuple)){res=tuple.apply(this,res)}
  500. return res
  501. }else{$UnsupportedOpType("*",int,other)}
  502. }
  503. Number.prototype.__not_in__=function(item){
  504. res=item.__contains__(this)
  505. return !res
  506. }
  507. Number.prototype.__pow__=function(other){
  508. if(typeof other==="number"){return int(Math.pow(this.valueOf(),other.valueOf()))}
  509. else{$UnsupportedOpType("//",int,other.__class__)}
  510. }
  511. Number.prototype.__setattr__=function(attr,value){throw AttributeError(
  512. "'int' object has no attribute "+attr+"'")}
  513. Number.prototype.__str__=function(){return this.toString()}
  514. Number.prototype.__truediv__=function(other){
  515. if(isinstance(other,int)){
  516. if(other==0){throw ZeroDivisionError('division by zero')}
  517. else{return float(this/other)}
  518. }else if(isinstance(other,float)){
  519. if(!other.value){throw ZeroDivisionError('division by zero')}
  520. else{return float(this/other.value)}
  521. }else{$UnsupportedOpType("//","int",other.__class__)}
  522. }
  523. var $op_func=function(other){
  524. if(isinstance(other,int)){
  525. var res=this.valueOf()-other.valueOf()
  526. if(isinstance(res,int)){return res}
  527. else{return float(res)}
  528. }
  529. else if(isinstance(other,float)){return float(this.valueOf()-other.value)}
  530. else if(isinstance(other,bool)){
  531. var bool_value=0
  532. if(other.valueOf())bool_value=1
  533. return this.valueOf()-bool_value}
  534. else{throw TypeError(
  535. "unsupported operand type(s) for -: "+this.value+" (float) and '"+str(other.__class__)+"'")
  536. }
  537. }
  538. $op_func +=''
  539. var $ops={'+':'add','-':'sub','%':'mod'}
  540. for($op in $ops){
  541. eval('Number.prototype.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op))
  542. }
  543. var $comp_func=function(other){
  544. if(isinstance(other,int)){return this.valueOf()> other.valueOf()}
  545. else if(isinstance(other,float)){return this.valueOf()> other.value}
  546. else{throw TypeError(
  547. "unorderable types: "+str(this.__class__)+'() > '+str(other.__class__)+"()")}
  548. }
  549. $comp_func +=''
  550. var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le','==':'eq','!=':'ne'}
  551. for($op in $comps){
  552. eval("Number.prototype.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
  553. }
  554. var $notimplemented=function(other){
  555. throw TypeError(
  556. "unsupported operand types for OPERATOR: '"+str(this.__class__)+"' and '"+str(other.__class__)+"'")
  557. }
  558. $notimplemented +=''
  559. for($op in $operators){
  560. var $opfunc='__'+$operators[$op]+'__'
  561. if(!($opfunc in Number.prototype)){
  562. eval('Number.prototype.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
  563. }
  564. }
  565. function isinstance(obj,arg){
  566. if(obj===null){return arg===None}
  567. if(obj===undefined){return false}
  568. if(arg.constructor===Array){
  569. for(var i=0;i<arg.length;i++){
  570. if(isinstance(obj,arg[i])){return true}
  571. }
  572. return false
  573. }else{
  574. if(arg===int){
  575. return((typeof obj)=="number"||obj.constructor===Number)&&(obj.valueOf()%1===0)
  576. }
  577. if(arg===float){
  578. return((typeof obj=="number" && obj.valueOf()%1!==0))||
  579. (obj.__class__===float)
  580. }
  581. if(arg===str){return(typeof obj=="string")}
  582. if(arg===list){return(obj.constructor===Array)}
  583. if(obj.__class__!==undefined){return obj.__class__===arg}
  584. return obj.constructor===arg
  585. }
  586. }
  587. function iter(obj){
  588. if('__item__' in obj){
  589. obj.__counter__=0
  590. return obj
  591. }
  592. throw TypeError("'"+str(obj.__class__)+"' object is not iterable")
  593. }
  594. function $iterator(obj,info){
  595. this.__getattr__=function(attr){
  596. var res=this[attr]
  597. if(res===undefined){throw AttributeError(
  598. "'"+info+"' object has no attribute '"+attr+"'")}
  599. else{return res}
  600. }
  601. this.__len__=function(){return obj.__len__()}
  602. this.__item__=function(i){return obj.__item__(i)}
  603. this.__class__=new $class(this,info)
  604. this.toString=function(){return info+'('+obj.toString()+')'}
  605. }
  606. function len(obj){
  607. try{return obj.__len__()}
  608. catch(err){
  609. try{return obj.__getattr__('__len__')()}
  610. catch(err){
  611. throw TypeError("object of type '"+obj.__class__.__name__+"' has no len()")}
  612. }
  613. }
  614. function map(){
  615. var func=arguments[0],res=[],rank=0
  616. while(true){
  617. var args=[],flag=true
  618. for(var i=1;i<arguments.length;i++){
  619. var x=arguments[i].__item__(rank)
  620. if(x===undefined){flag=false;break}
  621. args.push(x)
  622. }
  623. if(!flag){break}
  624. res.push(func.apply(null,args))
  625. rank++
  626. }
  627. return res
  628. }
  629. function $extreme(args,op){
  630. if(op==='__gt__'){var $op_name="max"}
  631. else{var $op_name="min"}
  632. if(args.length==0){throw TypeError($op_name+" expected 1 argument, got 0")}
  633. var last_arg=args[args.length-1]
  634. var last_i=args.length-1
  635. var has_key=false
  636. if(isinstance(last_arg,$Kw)){
  637. if(last_arg.name==='key'){
  638. var func=last_arg.value
  639. has_key=true
  640. last_i--
  641. }else{throw TypeError($op_name+"() got an unexpected keyword argument")}
  642. }else{var func=function(x){return x}}
  643. if((has_key && args.length==2)||(!has_key && args.length==1)){
  644. var arg=args[0]
  645. var $iter=iter(arg)
  646. var res=null
  647. while(true){
  648. try{
  649. var x=next($iter)
  650. if(res===null || bool(func(x)[op](func(res)))){res=x}
  651. }catch(err){
  652. if(err.__name__=="StopIteration"){return res}
  653. throw err
  654. }
  655. }
  656. }else{
  657. var res=null
  658. for(var i=0;i<=last_i;i++){
  659. var x=args[i]
  660. if(res===null || bool(func(x)[op](func(res)))){res=x}
  661. }
  662. return res
  663. }
  664. }
  665. function max(){
  666. var args=[]
  667. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  668. return $extreme(args,'__gt__')
  669. }
  670. function min(){
  671. var args=[]
  672. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  673. return $extreme(args,'__lt__')
  674. }
  675. function next(obj){
  676. if('__item__' in obj){
  677. if(obj.__counter__===undefined){obj.__counter__=0}
  678. var res=obj.__item__(obj.__counter__)
  679. if(res!==undefined){obj.__counter__++;return res}
  680. throw StopIteration('')
  681. }
  682. throw TypeError("'"+str(obj.__class__)+"' object is not iterable")
  683. }
  684. function $not(obj){return !bool(obj)}
  685. function $ObjectClass(){
  686. this.__class__="<class 'object'>"
  687. }
  688. $ObjectClass.prototype.__getattr__=function(attr){
  689. if(attr in this){return this[attr]}
  690. else{throw AttributeError("object has no attribute '"+attr+"'")}
  691. }
  692. $ObjectClass.prototype.__delattr__=function(attr){delete this[attr]}
  693. $ObjectClass.prototype.__setattr__=function(attr,value){this[attr]=value}
  694. function object(){
  695. return new $ObjectClass()
  696. }
  697. object.__class__=$type
  698. object.__name__='object'
  699. object.__str__="<class 'object'>"
  700. object.__hash__=function(){
  701. document.$py_next_hash+=1;
  702. return document.$py_next_hash
  703. }
  704. $ObjectClass.prototype.__hash__=object.__hash__
  705. function $open(){
  706. var $ns=$MakeArgs('open',arguments,['file'],{'mode':'r','encoding':'utf-8'},'args','kw')
  707. for(var attr in $ns){eval('var '+attr+'=$ns["'+attr+'"]')}
  708. if(args.length>0){var mode=args[0]}
  709. if(args.length>1){var encoding=args[1]}
  710. if(isinstance(file,JSObject)){return new $OpenFile(file.js,mode,encoding)}
  711. }
  712. function $print(){
  713. var $ns=$MakeArgs('print',arguments,[],{},'args','kw')
  714. var args=$ns['args']
  715. var kw=$ns['kw']
  716. var end='\n'
  717. var res=''
  718. if(kw['end']!==undefined){end=kw['end']}
  719. for(var i=0;i<args.length;i++){
  720. res +=str(args[i])
  721. if(i<args.length-1){res +=' '}
  722. }
  723. res +=end
  724. document.$stdout.__getattr__('write')(res)
  725. }
  726. log=function(arg){console.log(arg)}
  727. function $prompt(text,fill){return prompt(text,fill || '')}
  728. function range(){
  729. var $ns=$MakeArgs('range',arguments,[],{},'args',null)
  730. var args=$ns['args']
  731. if(args.length>3){throw TypeError(
  732. "range expected at most 3 arguments, got "+args.length)
  733. }
  734. var start=0
  735. var stop=0
  736. var step=1
  737. if(args.length==1){stop=args[0]}
  738. else if(args.length>=2){
  739. start=args[0]
  740. stop=args[1]
  741. }
  742. if(args.length>=3){step=args[2]}
  743. if(step==0){throw ValueError("range() arg 3 must not be zero")}
  744. var res=[]
  745. if(step>0){
  746. for(var i=start;i<stop;i+=step){res.push(i)}
  747. }else if(step<0){
  748. for(var i=start;i>stop;i+=step){res.push(i)}
  749. }
  750. return res
  751. }
  752. function repr(obj){return obj.toString()}
  753. function reversed(seq){
  754. if(isinstance(seq,list)){seq.reverse();return seq}
  755. else if(isinstance(seq,str)){
  756. var res=''
  757. for(var i=seq.length-1;i>=0;i--){res+=seq.charAt(i)}
  758. return res
  759. }else{throw TypeError(
  760. "argument to reversed() must be a sequence")}
  761. }
  762. function round(arg,n){
  763. if(!isinstance(arg,[int,float])){
  764. throw TypeError("type "+str(arg.__class__)+" doesn't define __round__ method")
  765. }
  766. if(n===undefined){n=0}
  767. if(!isinstance(n,int)){throw TypeError(
  768. "'"+n.__class__+"' object cannot be interpreted as an integer")}
  769. var mult=Math.pow(10,n)
  770. var res=Number(Math.round(arg*mult)).__truediv__(mult)
  771. if(n==0){return int(res)}else{return float(res)}
  772. }
  773. function set(){
  774. var i=0
  775. if(arguments.length==0){return new $SetClass()}
  776. else if(arguments.length==1){
  777. var arg=arguments[0]
  778. if(isinstance(arg,set)){return arg}
  779. var obj=new $SetClass()
  780. try{
  781. for(var i=0;i<arg.__len__();i++){
  782. obj.items.push(arg.__getitem__(i))
  783. }
  784. return obj
  785. }catch(err){
  786. throw TypeError("'"+arg.__class__.__name__+"' object is not iterable")
  787. }
  788. }else{
  789. throw TypeError("set expected at most 1 argument, got "+arguments.length)
  790. }
  791. }
  792. set.__class__=$type
  793. set.__name__='set'
  794. set.toString=function(){return "<class 'set'>"}
  795. set.__hash__=function(){throw TypeError("unhashable type: 'set'");}
  796. function $SetClass(){
  797. var x=null
  798. var i=null
  799. this.iter=null
  800. this.__class__=set
  801. this.items=[]
  802. }
  803. $SetClass.prototype.toString=function(){
  804. var res="{"
  805. for(var i=0;i<this.items.length;i++){
  806. var x=this.items[i]
  807. if(isinstance(x,str)){res +="'"+x+"'"}
  808. else{res +=x.toString()}
  809. if(i<this.items.length-1){res +=','}
  810. }
  811. return res+'}'
  812. }
  813. $SetClass.prototype.__add__=function(other){
  814. return set(this.items.concat(other.items))
  815. }
  816. $SetClass.prototype.__class__=set
  817. $SetClass.prototype.__contains__=function(item){
  818. for(var i=0;i<this.items.length;i++){
  819. try{if(this.items[i].__eq__(item)){return True}
  820. }catch(err){void(0)}
  821. }
  822. return False
  823. }
  824. $SetClass.prototype.__eq__=function(other){
  825. if(isinstance(other,set)){
  826. if(other.items.length==this.items.length){
  827. for(var i=0;i<this.items.length;i++){
  828. if(this.__contains__(other.items[i])===False){
  829. return False
  830. }
  831. }
  832. return True
  833. }
  834. }
  835. return False
  836. }
  837. $SetClass.prototype.__getattr__=function(attr){
  838. if(this[attr]!==undefined){return this[attr]}
  839. else{throw AttributeError("'set' object has no attribute '"+attr+"'")}
  840. }
  841. $SetClass.prototype.__hash__=set.__hash__
  842. $SetClass.prototype.__in__=function(item){return item.__contains__(this)}
  843. $SetClass.prototype.__len__=function(){return int(this.items.length)}
  844. $SetClass.prototype.__item__=function(i){return this.items[i]}
  845. $SetClass.prototype.__ne__=function(other){return !(this.__eq__(other))}
  846. $SetClass.prototype.__not_in__=function(item){return !(item.__contains__(this))}
  847. $SetClass.prototype.__str__=$SetClass.prototype.toString
  848. $SetClass.prototype.add=function(item){
  849. var i=0
  850. for(i=0;i<this.items.length;i++){
  851. try{if(item.__eq__(this.items[i])){return}}
  852. catch(err){void(0)}
  853. }
  854. this.items.push(item)
  855. }
  856. function setattr(obj,attr,value){
  857. if(!isinstance(attr,str)){throw TypeError("setattr(): attribute name must be string")}
  858. obj[attr]=value
  859. }
  860. function $SliceClass(start,stop,step){
  861. this.__class__=slice
  862. this.start=start
  863. this.stop=stop
  864. this.step=step
  865. }
  866. function slice(){
  867. var $ns=$MakeArgs('slice',arguments,[],{},'args',null)
  868. var args=$ns['args']
  869. if(args.length>3){throw TypeError(
  870. "slice expected at most 3 arguments, got "+args.length)
  871. }
  872. var start=0
  873. var stop=0
  874. var step=1
  875. if(args.length==1){stop=args[0]}
  876. else if(args.length>=2){
  877. start=args[0]
  878. stop=args[1]
  879. }
  880. if(args.length>=3){step=args[2]}
  881. if(step==0){throw ValueError("slice step must not be zero")}
  882. return new $SliceClass(start,stop,step)
  883. }
  884. function sum(iterable,start){
  885. if(start===undefined){start=0}
  886. var res=0
  887. for(var i=start;i<iterable.__len__();i++){
  888. res=res.__add__(iterable.__item__(i))
  889. }
  890. return res
  891. }
  892. function $tuple(arg){return arg}
  893. function tuple(){
  894. var args=new Array(),i=0
  895. for(i=0;i<arguments.length;i++){args.push(arguments[i])}
  896. var obj=list(args)
  897. obj.__class__=tuple
  898. obj.toString=function(){
  899. var res=args.__str__()
  900. res='('+res.substr(1,res.length-2)
  901. if(obj.length===1){res+=','}
  902. return res+')'
  903. }
  904. obj.__hash__=function(){
  905. var x=0x345678
  906. for(var i=0;i < args.length;i++){
  907. var y=args[i].__hash__()
  908. x=(1000003 * x)^ y & 0xFFFFFFFF
  909. }
  910. return x
  911. }
  912. obj.__str__=obj.toString
  913. return obj
  914. }
  915. tuple.__class__=$type
  916. tuple.__name__='tuple'
  917. tuple.__str__=function(){return "<class 'tuple'>"}
  918. tuple.toString=tuple.__str__
  919. function zip(){
  920. var $ns=$MakeArgs('zip',arguments,[],{},'args','kw')
  921. var args=$ns['args']
  922. var kw=$ns['kw']
  923. var rank=0,res=[]
  924. while(true){
  925. var line=[],flag=true
  926. for(var i=0;i<args.length;i++){
  927. var x=args[i].__item__(rank)
  928. if(x===undefined){flag=false;break}
  929. line.push(x)
  930. }
  931. if(!flag){return res}
  932. res.push(line)
  933. rank++
  934. }
  935. }
  936. True=true
  937. False=false
  938. Boolean.prototype.__class__=bool
  939. Boolean.prototype.__eq__=function(other){
  940. if(this.valueOf()){return !!other}else{return !other}
  941. }
  942. Boolean.prototype.__getattr__=function(attr){
  943. if(this[attr]!==undefined){return this[attr]}
  944. else{throw AttributeError("'bool' object has no attribute '"+attr+"'")}
  945. }
  946. Boolean.prototype.__hash__=function(){
  947. if(this.valueOf())return 1
  948. return 0
  949. }
  950. Boolean.prototype.__mul__=function(other){
  951. if(this.valueOf())return other
  952. return 0
  953. }
  954. Boolean.prototype.__add__=function(other){
  955. if(this.valueOf())return other + 1
  956. return other
  957. }
  958. Boolean.prototype.toString=function(){
  959. if(this.valueOf())return "True"
  960. return "False"
  961. }
  962. Boolean.prototype.__str__=Boolean.prototype.toString
  963. function $NoneClass(){
  964. this.__class__=new $class(this,"NoneType")
  965. this.value=null
  966. this.__bool__=function(){return False}
  967. this.__eq__=function(other){return other===None}
  968. this.__getattr__=function(attr){
  969. if(this[attr]!==undefined){return this[attr]}
  970. else{throw AttributeError("'NoneType' object has no attribute '"+attr+"'")}
  971. }
  972. this.__hash__=function(){return 0}
  973. this.__ne__=function(other){return other!==None}
  974. this.__str__=function(){return 'None'}
  975. var comp_ops=['ge','gt','le','lt']
  976. for(var key in $comps){
  977. if(comp_ops.indexOf($comps[key])>-1){
  978. this['__'+$comps[key]+'__']=(function(k){
  979. return function(other){
  980. throw TypeError("unorderable types: NoneType() "+$comps[k]+" "+
  981. other.__class__.__name__)}
  982. })(key)
  983. }
  984. }
  985. for(var func in this){
  986. if(typeof this[func]==='function'){
  987. this[func].__str__=(function(f){
  988. return function(){return "<mthod-wrapper "+f+" of NoneType object>"}
  989. })(func)
  990. }
  991. }
  992. }
  993. None=new $NoneClass()
  994. Exception=function(msg){
  995. var err=Error()
  996. err.info=''
  997. if(document.$debug && msg.split('\n').length==1){
  998. var module=document.$line_info[1]
  999. var line_num=document.$line_info[0]
  1000. var lines=document.$py_src[module].split('\n')
  1001. err.info +="\nmodule '"+module+"' line "+line_num
  1002. err.info +='\n'+lines[line_num-1]
  1003. }
  1004. err.message=msg + err.info
  1005. err.args=tuple(msg.split('\n')[0])
  1006. err.__str__=function(){return msg}
  1007. err.toString=err.__str__
  1008. err.__getattr__=function(attr){return this[attr]}
  1009. err.__name__='Exception'
  1010. err.__class__=Exception
  1011. err.py_error=true
  1012. __BRYTHON__.exception_stack.push(err)
  1013. return err
  1014. }
  1015. Exception.__str__=function(){return "<class 'Exception'>"}
  1016. Exception.__class__=$type
  1017. function $make_exc(name){
  1018. var $exc=(Exception+'').replace(/Exception/g,name)
  1019. eval(name+'='+$exc)
  1020. eval(name+'.__str__ = function(){return "<class '+"'"+name+"'"+'>"}')
  1021. eval(name+'.__class__=$type')
  1022. }
  1023. var $errors=['AssertionError','AttributeError','EOFError','FloatingPointError',
  1024. 'GeneratorExit','ImportError','IndexError','KeyError','KeyboardInterrupt',
  1025. 'NameError','NotImplementedError','OSError','OverflowError','ReferenceError',
  1026. 'RuntimeError','StopIteration','SyntaxError','IndentationError','TabError',
  1027. 'SystemError','SystemExit','TypeError','UnboundLocalError','ValueError',
  1028. 'ZeroDivisionError','IOError']
  1029. for(var i=0;i<$errors.length;i++){$make_exc($errors[i])}
  1030. list=function(){
  1031. function $list(){
  1032. var args=new Array()
  1033. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1034. return new $ListClass(args)
  1035. }
  1036. function list(){
  1037. if(arguments.length===0){return[]}
  1038. else if(arguments.length>1){
  1039. throw TypeError("list() takes at most 1 argument ("+arguments.length+" given)")
  1040. }
  1041. var res=[]
  1042. list.__init__(res,arguments[0])
  1043. return res
  1044. }
  1045. list.__add__=function(self,other){
  1046. var res=self.valueOf().concat(other.valueOf())
  1047. if(isinstance(self,tuple)){res=tuple.apply(self,res)}
  1048. return res
  1049. }
  1050. list.__class__=$type
  1051. list.__contains__=function(self,item){
  1052. for(var i=0;i<self.length;i++){
  1053. try{if(self[i].__eq__(item)){return true}
  1054. }catch(err){void(0)}
  1055. }
  1056. return false
  1057. }
  1058. list.__delitem__=function(self,arg){
  1059. if(isinstance(arg,int)){
  1060. var pos=arg
  1061. if(arg<0){pos=self.length+pos}
  1062. if(pos>=0 && pos<self.length){
  1063. self.splice(pos,1)
  1064. return
  1065. }
  1066. else{throw IndexError('list index out of range')}
  1067. }else if(isinstance(arg,slice)){
  1068. var start=arg.start || 0
  1069. var stop=arg.stop || self.length
  1070. var step=arg.step || 1
  1071. if(start<0){start=self.length+start}
  1072. if(stop<0){stop=self.length+stop}
  1073. var res=[],i=null
  1074. if(step>0){
  1075. if(stop>start){
  1076. for(i=start;i<stop;i+=step){
  1077. if(self[i]!==undefined){res.push(i)}
  1078. }
  1079. }
  1080. }else{
  1081. if(stop<start){
  1082. for(i=start;i>stop;i+=step.value){
  1083. if(self[i]!==undefined){res.push(i)}
  1084. }
  1085. res.reverse()
  1086. }
  1087. }
  1088. for(var i=res.length-1;i>=0;i--){
  1089. self.splice(res[i],1)
  1090. }
  1091. return
  1092. }else{
  1093. throw TypeError('list indices must be integer, not '+str(arg.__class__))
  1094. }
  1095. }
  1096. list.__eq__=function(self,other){
  1097. if(other===undefined){
  1098. return self===list
  1099. }
  1100. if(isinstance(other,self.__class__)){
  1101. if(other.length==self.length){
  1102. for(var i=0;i<self.length;i++){
  1103. if(!self[i].__eq__(other[i])){return False}
  1104. }
  1105. return True
  1106. }
  1107. }
  1108. return False
  1109. }
  1110. list.__getattr__=function(attr){
  1111. switch(attr){
  1112. case '__class__':
  1113. var res=function(){return list}
  1114. res.__str__=list.__str__
  1115. return res
  1116. case '__name__':
  1117. var res=function(){
  1118. throw AttributeError(" 'list' object has no attribute '__name__'")
  1119. }
  1120. res.__str__=function(){return 'list'}
  1121. return res
  1122. default:
  1123. return list[attr]
  1124. }
  1125. }
  1126. list.__getitem__=function(self,arg){
  1127. if(isinstance(arg,int)){
  1128. var items=self.valueOf()
  1129. var pos=arg
  1130. if(arg<0){pos=items.length+pos}
  1131. if(pos>=0 && pos<items.length){return items[pos]}
  1132. else{
  1133. throw IndexError('list index out of range')
  1134. }
  1135. }else if(isinstance(arg,slice)){
  1136. var step=arg.step===None ? 1 : arg.step
  1137. if(step>0){
  1138. var start=arg.start===None ? 0 : arg.start
  1139. var stop=arg.stop===None ? self.__len__(): arg.stop
  1140. }else{
  1141. var start=arg.start===None ? self.__len__()-1 : arg.start
  1142. var stop=arg.stop===None ? 0 : arg.stop
  1143. }
  1144. if(start<0){start=int(self.length+start)}
  1145. if(stop<0){stop=self.length+stop}
  1146. var res=[],i=null,items=self.valueOf()
  1147. if(step>0){
  1148. if(stop<=start){return res}
  1149. else{
  1150. for(i=start;i<stop;i+=step){
  1151. if(items[i]!==undefined){res.push(items[i])}
  1152. }
  1153. return res
  1154. }
  1155. }else{
  1156. if(stop>=start){return res}
  1157. else{
  1158. for(i=start;i>=stop;i+=step){
  1159. if(items[i]!==undefined){res.push(items[i])}
  1160. }
  1161. return res
  1162. }
  1163. }
  1164. }else if(isinstance(arg,bool)){
  1165. return self.__getitem__(int(arg))
  1166. }else{
  1167. throw TypeError('list indices must be integer, not '+str(arg.__class__))
  1168. }
  1169. }
  1170. list.__hash__=function(self){throw TypeError("unhashable type: 'list'")}
  1171. list.__in__=function(self,item){return item.__contains__(self)}
  1172. list.__init__=function(self){
  1173. while(self.__len__()>0){self.pop()}
  1174. if(arguments.length===1){return}
  1175. var arg=arguments[1]
  1176. for(var i=0;i<arg.__len__();i++){self.push(arg.__item__(i))}
  1177. }
  1178. list.__item__=function(self,i){return self[i]}
  1179. list.__len__=function(self){return self.length}
  1180. list.__mul__=function(self,other){
  1181. if(isinstance(other,int)){return other.__mul__(self)}
  1182. else{throw TypeError("can't multiply sequence by non-int of type '"+other.__name+"'")}
  1183. }
  1184. list.__name__='list'
  1185. list.__ne__=function(self,other){return !self.__eq__(other)}
  1186. list.__next__=function(self){
  1187. if(self.iter===null){self.iter=0}
  1188. if(self.iter<self.valueOf().length){
  1189. self.iter++
  1190. return self.valueOf()[self.iter-1]
  1191. }else{
  1192. self.iter=null
  1193. throw StopIteration('')
  1194. }
  1195. }
  1196. list.__not_in__=function(self,item){return !item.__contains__(self)}
  1197. list.__setitem__=function(self,arg,value){
  1198. if(isinstance(arg,int)){
  1199. var pos=arg
  1200. if(arg<0){pos=self.length+pos}
  1201. if(pos>=0 && pos<self.length){self[pos]=value}
  1202. else{throw IndexError('list index out of range')}
  1203. }else if(isinstance(arg,slice)){
  1204. var start=arg.start===None ? 0 : arg.start
  1205. var stop=arg.stop===None ? self.__len__(): arg.stop
  1206. var step=arg.step===None ? 1 : arg.step
  1207. if(start<0){start=self.length+start}
  1208. if(stop<0){stop=self.length+stop}
  1209. self.splice(start,stop-start)
  1210. if(hasattr(value,'__item__')){
  1211. var $temp=list(value)
  1212. for(var i=$temp.length-1;i>=0;i--){
  1213. self.splice(start,0,$temp[i])
  1214. }
  1215. }else{
  1216. throw TypeError("can only assign an iterable")
  1217. }
  1218. }else{
  1219. throw TypeError('list indices must be integer, not '+str(arg.__class__))
  1220. }
  1221. }
  1222. list.__str__=function(self){
  1223. if(self===undefined){return "<class 'list'>"}
  1224. var res="[",items=self.valueOf()
  1225. for(var i=0;i<self.length;i++){
  1226. var x=self[i]
  1227. if(isinstance(x,str)){res +="'"+x+"'"}
  1228. else if(x['__str__']!==undefined){res +=x.__str__()}
  1229. else{res +=x.toString()}
  1230. if(i<self.length-1){res +=','}
  1231. }
  1232. return res+']'
  1233. }
  1234. list.append=function(self,other){self.push(other)}
  1235. list.count=function(self,elt){
  1236. var res=0
  1237. for(var i=0;i<self.length;i++){
  1238. if(self[i].__eq__(elt)){res++}
  1239. }
  1240. return res
  1241. }
  1242. list.extend=function(self,other){
  1243. if(arguments.length!=2){throw TypeError(
  1244. "extend() takes exactly one argument ("+arguments.length+" given)")}
  1245. try{
  1246. for(var i=0;i<other.__len__();i++){self.push(other.__item__(i))}
  1247. }catch(err){
  1248. throw TypeError("object is not iterable")
  1249. }
  1250. }
  1251. list.index=function(self,elt){
  1252. for(var i=0;i<self.length;i++){
  1253. if(self[i].__eq__(elt)){return i}
  1254. }
  1255. throw ValueError(str(elt)+" is not in list")
  1256. }
  1257. list.insert=function(self,i,item){self.splice(i,0,item)}
  1258. list.remove=function(self,elt){
  1259. for(var i=0;i<self.length;i++){
  1260. if(self[i].__eq__(elt)){
  1261. self.splice(i,1)
  1262. return
  1263. }
  1264. }
  1265. throw ValueError(str(elt)+" is not in list")
  1266. }
  1267. list.pop=function(self,pos){
  1268. if(pos===undefined){
  1269. var res=self[self.length-1]
  1270. self.splice(self.length-1,1)
  1271. return res
  1272. }else if(arguments.length==2){
  1273. if(isinstance(pos,int)){
  1274. var res=self[pos]
  1275. self.splice(pos,1)
  1276. return res
  1277. }else{
  1278. throw TypeError(pos.__class__+" object cannot be interpreted as an integer")
  1279. }
  1280. }else{
  1281. throw TypeError("pop() takes at most 1 argument ("+(arguments.length-1)+' given)')
  1282. }
  1283. }
  1284. list.reverse=function(self){
  1285. for(var i=0;i<parseInt(self.length/2);i++){
  1286. var buf=self[i]
  1287. self[i]=self[self.length-i-1]
  1288. self[self.length-i-1]=buf
  1289. }
  1290. }
  1291. function $partition(arg,array,begin,end,pivot)
  1292. {
  1293. var piv=array[pivot]
  1294. array.swap(pivot, end-1)
  1295. var store=begin
  1296. for(var ix=begin;ix<end-1;++ix){
  1297. if(arg(array[ix]).__le__(arg(piv))){
  1298. array.swap(store, ix)
  1299. ++store
  1300. }
  1301. }
  1302. array.swap(end-1, store)
  1303. return store
  1304. }
  1305. Array.prototype.swap=function(a, b)
  1306. {
  1307. var tmp=this[a]
  1308. this[a]=this[b]
  1309. this[b]=tmp
  1310. }
  1311. function $qsort(arg,array, begin, end)
  1312. {
  1313. if(end-1>begin){
  1314. var pivot=begin+Math.floor(Math.random()*(end-begin))
  1315. pivot=$partition(arg,array, begin, end, pivot)
  1316. $qsort(arg,array, begin, pivot)
  1317. $qsort(arg,array, pivot+1, end)
  1318. }
  1319. }
  1320. list.sort=function(self){
  1321. var func=function(x){return x}
  1322. var reverse=false
  1323. for(var i=1;i<arguments.length;i++){
  1324. var arg=arguments[i]
  1325. if(isinstance(arg,$Kw)){
  1326. if(arg.name==='key'){func=arg.value}
  1327. else if(arg.name==='reverse'){reverse=arg.value}
  1328. }
  1329. }
  1330. if(self.length==0){return}
  1331. $qsort(func,self,0,self.length)
  1332. if(reverse){list.reverse(self)}
  1333. }
  1334. list.toString=list.__str__
  1335. function $ListClass(items){
  1336. var x=null,i=null
  1337. this.iter=null
  1338. this.__class__=list
  1339. this.items=items
  1340. }
  1341. for(var attr in list){
  1342. if(typeof list[attr]==='function'){list[attr].__str__=function(){return "<list method "+attr+">"}}
  1343. var func=(function(attr){
  1344. return function(){
  1345. var args=[this]
  1346. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1347. return list[attr].apply(this,args)
  1348. }
  1349. })(attr)
  1350. func.__str__=(function(attr){
  1351. return function(){return "<method-wrapper '"+attr+"' of list object>"}
  1352. })(attr)
  1353. Array.prototype[attr]=func
  1354. }
  1355. Array.prototype.__class__=list
  1356. Array.prototype.__getattr__=function(attr){
  1357. if(attr==='__class__'){return this.__class__}
  1358. if(list[attr]===undefined){
  1359. throw AttributeError("'"+this.__class__.__name__+"' object has no attribute '"+attr+"'")
  1360. }
  1361. var obj=this
  1362. var res=function(){
  1363. var args=[obj]
  1364. for(var i=0;i<arguments.length;i++){args.push(arguments[i])}
  1365. return list[attr].apply(obj,args)
  1366. }
  1367. res.__str__=function(){return "<built-in method "+attr+" of "+this.__class__.__name__+" object>"}
  1368. return res
  1369. }
  1370. return list
  1371. }()
  1372. str=function(){
  1373. function str(arg){
  1374. if(arg===undefined){return '<undefined>'}
  1375. else if(arg.__str__!==undefined){return arg.__str__()}
  1376. else if(arg.__getattr__('__str__')!==undefined){
  1377. return arg.__getattr__('__str__')()
  1378. }else{return arg.toString()}
  1379. }
  1380. str.__name__='str'
  1381. str.__str__=function(){return "<class 'str'>"}
  1382. str.toString=str.__str__
  1383. str.__add__=function(self,other){
  1384. if(!(typeof other==="string")){
  1385. try{return other.__radd__(self)}
  1386. catch(err){throw TypeError(
  1387. "Can't convert "+other.__class__+" to str implicitely")}
  1388. }else{
  1389. return self+other
  1390. }
  1391. }
  1392. str.__class__=$type
  1393. str.__contains__=function(self,item){
  1394. if(!(typeof item==="string")){throw TypeError(
  1395. "'in <string>' requires string as left operand, not "+item.__class__)}
  1396. var nbcar=item.length
  1397. for(var i=0;i<self.length;i++){
  1398. if(self.substr(i,nbcar)==item){return True}
  1399. }
  1400. return False
  1401. }
  1402. str.__eq__=function(self,other){
  1403. if(other===undefined){
  1404. return self===str
  1405. }
  1406. return other===self.valueOf()
  1407. }
  1408. str.__getattr__=function(attr){return this[attr]}
  1409. str.__getitem__=function(self,arg){
  1410. if(isinstance(arg,int)){
  1411. var pos=arg
  1412. if(arg<0){pos=self.length+pos}
  1413. if(pos>=0 && pos<self.length){return self.charAt(pos)}
  1414. else{throw IndexError('string index out of range')}
  1415. }else if(isinstance(arg,slice)){
  1416. var step=arg.step===None ? 1 : arg.step
  1417. if(step>0){
  1418. var start=arg.start===None ? 0 : arg.start
  1419. var stop=arg.stop===None ? self.__len__(): arg.stop
  1420. }else{
  1421. var start=arg.start===None ? self.__len__()-1 : arg.start
  1422. var stop=arg.stop===None ? 0 : arg.stop
  1423. }
  1424. if(start<0){start=self.length+start}
  1425. if(stop<0){stop=self.length+stop}
  1426. var res='',i=null
  1427. if(step>0){
  1428. if(stop<=start){return ''}
  1429. else{
  1430. for(i=start;i<stop;i+=step){
  1431. res +=self.charAt(i)
  1432. }
  1433. }
  1434. }else{
  1435. if(stop>=start){return ''}
  1436. else{
  1437. for(i=start;i>=stop;i+=step){
  1438. res +=self.charAt(i)
  1439. }
  1440. }
  1441. }
  1442. return res
  1443. }else if(isinstance(arg,bool)){
  1444. return self.__getitem__(int(arg))
  1445. }
  1446. }
  1447. str.__hash__=function(self){
  1448. var hash=1
  1449. for(var i=0;i < self.length;i++){
  1450. hash=(101*hash + self.charCodeAt(i))& 0xFFFFFFFF
  1451. }
  1452. return hash
  1453. }
  1454. str.__in__=function(self,item){return item.__contains__(self.valueOf())}
  1455. str.__item__=function(self,i){return self.charAt(i)}
  1456. str.__len__=function(self){return self.length}
  1457. str.__mod__=function(self,args){
  1458. var flags=$List2Dict('#','0','-',' ','+')
  1459. var ph=[]
  1460. function format(s){
  1461. var conv_flags='([#\\+\\- 0])*'
  1462. var conv_types='[diouxXeEfFgGcrsa%]'
  1463. var re=new RegExp('\\%(\\(.+\\))*'+conv_flags+'(\\*|\\d*)(\\.\\*|\\.\\d*)*(h|l|L)*('+conv_types+'){1}')
  1464. var res=re.exec(s)
  1465. this.is_format=true
  1466. if(!res){this.is_format=false;return}
  1467. this.src=res[0]
  1468. if(res[1]){this.mapping_key=str(res[1].substr(1,res[1].length-2))}
  1469. else{this.mapping_key=null}
  1470. this.flag=res[2]
  1471. this.min_width=res[3]
  1472. this.precision=res[4]
  1473. this.length_modifier=res[5]
  1474. this.type=res[6]
  1475. this.toString=function(){
  1476. var res='type '+this.type+' key '+this.mapping_key+' min width '+this.min_width
  1477. res +=' precision '+this.precision
  1478. return res
  1479. }
  1480. this.format=function(src){
  1481. if(this.mapping_key!==null){
  1482. if(!isinstance(src,dict)){throw TypeError("format requires a mapping")}
  1483. src=src.__getitem__(this.mapping_key)
  1484. }
  1485. if(this.type=="s"){return str(src)}
  1486. else if(this.type=="i" || this.type=="d"){
  1487. if(!isinstance(src,[int,float])){throw TypeError(
  1488. "%"+this.type+" format : a number is required, not "+str(src.__class__))}
  1489. return str(int(src))
  1490. }else if(this.type=="f" || this.type=="F"){
  1491. if(!isinstance(src,[int,float])){throw TypeError(
  1492. "%"+this.type+" format : a number is required, not "+str(src.__class__))}
  1493. return str(float(src))
  1494. }
  1495. }
  1496. }
  1497. var elts=[]
  1498. var pos=0, start=0, nb_repl=0
  1499. var val=self.valueOf()
  1500. while(pos<val.length){
  1501. if(val.charAt(pos)=='%'){
  1502. var f=new format(val.substr(pos))
  1503. if(f.is_format && f.type!=="%"){
  1504. elts.push(val.substring(start,pos))
  1505. elts.push(f)
  1506. start=pos+f.src.length
  1507. pos=start
  1508. nb_repl++
  1509. }else{pos++}
  1510. }else{pos++}
  1511. }
  1512. elts.push(val.substr(start))
  1513. if(!isinstance(args,tuple)){
  1514. if(nb_repl>1){throw TypeError('not enough arguments for format string')}
  1515. else{elts[1]=elts[1].format(args)}
  1516. }else{
  1517. if(nb_repl==args.length){
  1518. for(var i=0;i<args.length;i++){
  1519. var fmt=elts[1+2*i]
  1520. elts[1+2*i]=fmt.format(args[i])
  1521. }
  1522. }else if(nb_repl<args.length){throw TypeError(
  1523. "not all arguments converted during string formatting")
  1524. }else{throw TypeError('not enough arguments for format string')}
  1525. }
  1526. var res=''
  1527. for(var i=0;i<elts.length;i++){res+=elts[i]}
  1528. res=res.replace(/%%/g,'%')
  1529. return res
  1530. }
  1531. str.__mul__=function(self,other){
  1532. if(!isinstance(other,int)){throw TypeError(
  1533. "Can't multiply sequence by non-int of type '"+str(other.__class__)+"'")}
  1534. $res=''
  1535. for(var i=0;i<other;i++){$res+=self.valueOf()}
  1536. return $res
  1537. }
  1538. str.__ne__=function(self,other){return other!==self.valueOf()}
  1539. str.__next__=function(self){
  1540. if(self.iter==null){self.iter==0}
  1541. if(self.iter<self.value.length){
  1542. self.iter++
  1543. return str(self.value.charAt(self.iter-1))
  1544. }else{
  1545. self.iter=null
  1546. throw StopIteration()
  1547. }
  1548. }
  1549. str.__not_in__=function(self,item){return !item.__contains__(self.valueOf())}
  1550. str.__setattr__=function(self,attr,value){setattr(self,attr,value)}
  1551. self.__setitem__=function(self,attr,value){
  1552. throw TypeError("'str' object does not support item assignment")
  1553. }
  1554. str.__str__=function(self){
  1555. if(self===undefined){return "<class 'str'>"}
  1556. else{return self.toString()}
  1557. }
  1558. var $comp_func=function(self,other){
  1559. if(typeof other !=="string"){throw TypeError(
  1560. "unorderable types: 'str' > "+other.__class__+"()")}
  1561. return self > other
  1562. }
  1563. $comp_func +=''
  1564. var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le'}
  1565. for($op in $comps){
  1566. eval("str.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op))
  1567. }
  1568. var $notimplemented=function(self,other){
  1569. throw TypeError(
  1570. "unsupported operand types for OPERATOR: '"+str(self.__class__)+"' and '"+str(other.__class__)+"'")
  1571. }
  1572. $notimplemented +=''
  1573. for($op in $operators){
  1574. var $opfunc='__'+$operators[$op]+'__'
  1575. if(!($opfunc in str)){
  1576. eval('str.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op))
  1577. }
  1578. }
  1579. str.capitalize=function(self){
  1580. if(self.length==0){return ''}
  1581. return self.charAt(0).toUpperCase()+self.substr(1).toLowerCase()
  1582. }
  1583. str.center=function(self,width,fillchar){
  1584. if(fillchar===undefined){fillchar=' '}else{fillchar=fillchar}
  1585. if(width<=self.length){return self}
  1586. else{
  1587. var pad=parseInt((width-self.length)/2)
  1588. res=''
  1589. for(var i=0;i<pad;i++){res+=fillchar}
  1590. res +=self
  1591. for(var i=0;i<pad;i++){res+=fillchar}
  1592. if(res.length<width){res +=fillchar}
  1593. return res
  1594. }
  1595. }
  1596. str.count=function(self,elt){
  1597. if(!(typeof elt==="string")){throw TypeError(
  1598. "Can't convert '"+str(elt.__class__)+"' object to str implicitly")}
  1599. var res=0
  1600. for(var i=0;i<self.length-elt.length+1;i++){
  1601. if(self.substr(i,elt.length)===elt){res++}
  1602. }
  1603. return res
  1604. }
  1605. str.endswith=function(self){
  1606. var args=[]
  1607. for(var i=1;i<arguments.length;i++){args.push(arguments[i])}
  1608. var $ns=$MakeArgs("str.endswith",args,['suffix'],
  1609. {'start':null,'end':null},null,null)
  1610. var suffixes=$ns['suffix']
  1611. if(!isinstance(suffixes,tuple)){suffixes=[suffixes]}
  1612. var start=$ns['start']|| 0
  1613. var end=$ns['end']|| self.length-1
  1614. var s=self.substr(start,end+1)
  1615. for(var i=0;i<suffixes.length;i++){
  1616. suffix=suffixes[i]
  1617. if(suffix.length<=s.length &&
  1618. s.substr(s.length-suffix.length)==suffix){return True}
  1619. }
  1620. return False
  1621. }
  1622. str.find=function(self){
  1623. var $ns=$MakeArgs("str.find",arguments,['self','sub'],
  1624. {'start':0,'end':self.length},null,null)
  1625. var sub=$ns['sub'],start=$ns['start'],end=$ns['end']
  1626. if(!isinstance(sub,str)){throw TypeError(
  1627. "Can't convert '"+str(sub.__class__)+"' object to str implicitly")}
  1628. if(!isinstance(start,int)||!isinstance(end,int)){throw TypeError(
  1629. "slice indices must be integers or None or have an __index__ method")}
  1630. var s=self.substring(start,end)
  1631. var escaped=list("[.*+?|()$^")
  1632. var esc_sub=''
  1633. for(var i=0;i<sub.length;i++){
  1634. if(escaped.indexOf(sub.charAt(i))>-1){esc_sub +='\\'}
  1635. esc_sub +=sub.charAt(i)
  1636. }
  1637. var res=s.search(esc_sub)
  1638. if(res==-1){return -1}
  1639. else{return start+res}
  1640. }
  1641. str.index=function(self){
  1642. var res=str.find.apply(self,arguments)
  1643. if(res===-1){throw ValueError("substring not found")}
  1644. else{return res}
  1645. }
  1646. str.join=function(self,iterable){
  1647. if(!'__item__' in iterable){throw TypeError(
  1648. "'"+str(iterable.__class__)+"' object is not iterable")}
  1649. var res='',count=0
  1650. for(var i=0;i<iterable.length;i++){
  1651. var obj2=iterable.__getitem__(i)
  1652. if(!isinstance(obj2,str)){throw TypeError(
  1653. "sequence item "+count+": expected str instance, "+obj2.__class__+"found")}
  1654. res +=obj2+self
  1655. count++
  1656. }
  1657. if(count==0){return ''}
  1658. res=res.substr(0,res.length-self.length)
  1659. return res
  1660. }
  1661. str.lower=function(self){return self.toLowerCase()}
  1662. str.lstrip=function(self,x){
  1663. var pattern=null
  1664. if(x==undefined){pattern="\\s*"}
  1665. else{pattern="["+x+"]*"}
  1666. var sp=new RegExp("^"+pattern)
  1667. return self.replace(sp,"")
  1668. }
  1669. function $re_escape(str)
  1670. {
  1671. var specials="[.*+?|()$^"
  1672. for(var i=0;i<specials.length;i++){
  1673. var re=new RegExp('\\'+specials.charAt(i),'g')
  1674. str=str.replace(re, "\\"+specials.charAt(i))
  1675. }
  1676. return str
  1677. }
  1678. str.replace=function(self,old,_new,count){
  1679. if(count!==undefined){
  1680. if(!isinstance(count,[int,float])){throw TypeError(
  1681. "'"+str(count.__class__)+"' object cannot be interpreted as an integer")}
  1682. var re=new RegExp($re_escape(old),'g')
  1683. var res=self.valueOf()
  1684. while(count>0){
  1685. if(self.search(re)==-1){return res}
  1686. res=res.replace(re,_new)
  1687. count--
  1688. }
  1689. return res
  1690. }else{
  1691. var re=new RegExp($re_escape(old),"g")
  1692. return self.replace(re,_new)
  1693. }
  1694. }
  1695. str.rfind=function(self){
  1696. var $ns=$MakeArgs("str.find",arguments,['self','sub'],
  1697. {'start':0,'end':self.length},null,null)
  1698. var sub=$ns['sub'],start=$ns['start'],end=$ns['end']
  1699. if(!isinstance(sub,str)){throw TypeError(
  1700. "Can't convert '"+str(sub.__class__)+"' object to str implicitly")}
  1701. if(!isinstance(start,int)||!isinstance(end,int)){throw TypeError(
  1702. "slice indices must be integers or None or have an __index__ method")}
  1703. var s=self.substring(start,end)
  1704. var reversed=''
  1705. for(var i=s.length-1;i>=0;i--){reversed +=s.charAt(i)}
  1706. var res=reversed.search(sub)
  1707. if(res==-1){return -1}
  1708. else{return start+s.length

Large files files are truncated, but you can click here to view the full file