-
Notifications
You must be signed in to change notification settings - Fork 12
/
builtin.js
1 lines (1 loc) · 208 KB
/
builtin.js
1
Sk.builtinFiles={"files": {"src/lib/pythonds/trees/binheap.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n\n# this heap takes key value pairs, we will assume that the keys are integers\nclass BinHeap:\n def __init__(self):\n self.heapList = [0]\n self.currentSize = 0\n\n\n def buildHeap(self,alist):\n i = len(alist) // 2\n self.currentSize = len(alist)\n self.heapList = [0] + alist[:]\n print(len(self.heapList), i)\n while (i > 0):\n print(self.heapList, i)\n self.percDown(i)\n i = i - 1\n print(self.heapList,i)\n \n def percDown(self,i):\n while (i * 2) <= self.currentSize:\n mc = self.minChild(i)\n if self.heapList[i] > self.heapList[mc]:\n tmp = self.heapList[i]\n self.heapList[i] = self.heapList[mc]\n self.heapList[mc] = tmp\n i = mc\n \n def minChild(self,i):\n if i * 2 + 1 > self.currentSize:\n return i * 2\n else:\n if self.heapList[i * 2] < self.heapList[i * 2 + 1]:\n return i * 2\n else:\n return i * 2 + 1\n\n def percUp(self,i):\n while i // 2 > 0:\n if self.heapList[i] < self.heapList[i//2]:\n tmp = self.heapList[i // 2]\n self.heapList[i // 2] = self.heapList[i]\n self.heapList[i] = tmp\n i = i // 2\n \n def insert(self,k):\n self.heapList.append(k)\n self.currentSize = self.currentSize + 1\n self.percUp(self.currentSize)\n\n def delMin(self):\n retval = self.heapList[1]\n self.heapList[1] = self.heapList[self.currentSize]\n self.currentSize = self.currentSize - 1\n self.heapList.pop()\n self.percDown(1)\n return retval\n \n def isEmpty(self):\n if currentSize == 0:\n return True\n else:\n return False\n", "src/lib/pythonds/basic/stack.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n#stack.py\r\n\r\nclass Stack:\r\n def __init__(self):\r\n self.items = []\r\n\r\n def isEmpty(self):\r\n return self.items == []\r\n\r\n def push(self, item):\r\n self.items.append(item)\r\n\r\n def pop(self):\r\n return self.items.pop()\r\n\r\n def peek(self):\r\n return self.items[len(self.items)-1]\r\n\r\n def size(self):\r\n return len(self.items)\r\n\r\n", "src/lib/pythonds/trees/bst.py": "#!/bin/env python3.1\n# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005, 2010\n# \n\nclass BinarySearchTree:\n '''\n Author: Brad Miller\n Date: 1/15/2005\n Description: Imlement a binary search tree with the following interface\n functions: \n __contains__(y) <==> y in x\n __getitem__(y) <==> x[y]\n __init__()\n __len__() <==> len(x)\n __setitem__(k,v) <==> x[k] = v\n clear()\n get(k)\n items() \n keys() \n values()\n put(k,v)\n in\n del <==> \n '''\n\n def __init__(self):\n self.root = None\n self.size = 0\n \n def put(self,key,val):\n if self.root:\n self._put(key,val,self.root)\n else:\n self.root = TreeNode(key,val)\n self.size = self.size + 1\n\n def _put(self,key,val,currentNode):\n if key < currentNode.key:\n if currentNode.hasLeftChild():\n self._put(key,val,currentNode.leftChild)\n else:\n currentNode.leftChild = TreeNode(key,val,parent=currentNode)\n else:\n if currentNode.hasRightChild():\n self._put(key,val,currentNode.rightChild)\n else:\n currentNode.rightChild = TreeNode(key,val,parent=currentNode)\n \n def __setitem__(self,k,v):\n self.put(k,v)\n\n def get(self,key):\n if self.root:\n res = self._get(key,self.root)\n if res:\n return res.payload\n else:\n return None\n else:\n return None\n \n def _get(self,key,currentNode):\n if not currentNode:\n return None\n elif currentNode.key == key:\n return currentNode\n elif key < currentNode.key:\n return self._get(key,currentNode.leftChild)\n else:\n return self._get(key,currentNode.rightChild)\n \n \n def __getitem__(self,key):\n res = self.get(key)\n if res:\n return res\n else:\n raise KeyError('Error, key not in tree')\n \n\n def __contains__(self,key):\n if self._get(key,self.root):\n return True\n else:\n return False\n \n def length(self):\n return self.size\n\n def __len__(self):\n return self.size\n\n def __iter__(self):\n return self.root.__iter__()\n \n def delete(self,key):\n if self.size > 1:\n nodeToRemove = self._get(key,self.root)\n if nodeToRemove:\n self.remove(nodeToRemove)\n self.size = self.size-1\n else:\n raise KeyError('Error, key not in tree')\n elif self.size == 1 and self.root.key == key:\n self.root = None\n self.size = self.size - 1\n else:\n raise KeyError('Error, key not in tree')\n\n def __delitem__(self,key):\n self.delete(key)\n \n def remove(self,currentNode):\n if currentNode.isLeaf(): #leaf\n if currentNode == currentNode.parent.leftChild:\n currentNode.parent.leftChild = None\n else:\n currentNode.parent.rightChild = None\n elif currentNode.hasBothChildren(): #interior\n succ = currentNode.findSuccessor()\n succ.spliceOut()\n currentNode.key = succ.key\n currentNode.payload = succ.payload\n else: # this node has one child\n if currentNode.hasLeftChild():\n if currentNode.isLeftChild():\n currentNode.leftChild.parent = currentNode.parent\n currentNode.parent.leftChild = currentNode.leftChild\n elif currentNode.isRightChild():\n currentNode.leftChild.parent = currentNode.parent\n currentNode.parent.rightChild = currentNode.leftChild\n else:\n currentNode.replaceNodeData(currentNode.leftChild.key,\n currentNode.leftChild.payload,\n currentNode.leftChild.leftChild,\n currentNode.leftChild.rightChild)\n else:\n if currentNode.isLeftChild():\n currentNode.rightChild.parent = currentNode.parent\n currentNode.parent.leftChild = currentNode.rightChild\n elif currentNode.isRightChild():\n currentNode.rightChild.parent = currentNode.parent\n currentNode.parent.rightChild = currentNode.rightChild\n else:\n currentNode.replaceNodeData(currentNode.rightChild.key,\n currentNode.rightChild.payload,\n currentNode.rightChild.leftChild,\n currentNode.rightChild.rightChild)\n\n def inorder(self):\n self._inorder(self.root)\n\n def _inorder(self,tree):\n if tree != None:\n self._inorder(tree.leftChild)\n print(tree.key)\n self._inorder(tree.rightChild)\n\n def postorder(self):\n self._postorder(self.root)\n\n def _postorder(self, tree):\n if tree:\n self._postorder(tree.rightChild)\n self._postorder(tree.leftChild)\n print(tree.key) \n\n def preorder(self):\n self._preorder(self,self.root)\n\n def _preorder(self,tree):\n if tree:\n print(tree.key) \n self._preorder(tree.leftChild)\n self._preorder(tree.rightChild)\n\n \nclass TreeNode:\n def __init__(self,key,val,left=None,right=None,parent=None):\n self.key = key\n self.payload = val\n self.leftChild = left\n self.rightChild = right\n self.parent = parent\n self.balanceFactor = 0\n \n def hasLeftChild(self):\n return self.leftChild\n\n def hasRightChild(self):\n return self.rightChild\n \n def isLeftChild(self):\n return self.parent and self.parent.leftChild == self\n\n def isRightChild(self):\n return self.parent and self.parent.rightChild == self\n\n def isRoot(self):\n return not self.parent\n\n def isLeaf(self):\n return not (self.rightChild or self.leftChild)\n\n def hasAnyChildren(self):\n return self.rightChild or self.leftChild\n\n def hasBothChildren(self):\n return self.rightChild and self.leftChild\n \n def replaceNodeData(self,key,value,lc,rc):\n self.key = key\n self.payload = value\n self.leftChild = lc\n self.rightChild = rc\n if self.hasLeftChild():\n self.leftChild.parent = self\n if self.hasRightChild():\n self.rightChild.parent = self\n \n def findSuccessor(self):\n succ = None\n if self.hasRightChild():\n succ = self.rightChild.findMin()\n else:\n if self.parent:\n if self.isLeftChild():\n succ = self.parent\n else:\n self.parent.rightChild = None\n succ = self.parent.findSuccessor()\n self.parent.rightChild = self\n return succ\n\n\n def spliceOut(self):\n if self.isLeaf():\n if self.isLeftChild():\n self.parent.leftChild = None\n else:\n self.parent.rightChild = None\n elif self.hasAnyChildren():\n if self.hasLeftChild():\n if self.isLeftChild():\n self.parent.leftChild = self.leftChild\n else:\n self.parent.rightChild = self.leftChild\n self.leftChild.parent = self.parent\n else:\n if self.isLeftChild():\n self.parent.leftChild = self.rightChild\n else:\n self.parent.rightChild = self.rightChild\n self.rightChild.parent = self.parent\n\n def findMin(self):\n current = self\n while current.hasLeftChild():\n current = current.leftChild\n return current\n\n def __iter__(self):\n \"\"\"The standard inorder traversal of a binary tree.\"\"\"\n if self:\n if self.hasLeftChild():\n for elem in self.leftChild:\n yield elem\n yield self.key\n if self.hasRightChild():\n for elem in self.rightChild:\n yield elem\n\n \n", "src/lib/time/__init__.js": "\n/*\n\tBarebones implementation of the Python time package.\n\n\tFor now, only the time() function is implemented.\n*/\n \nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n mod.time = new Sk.builtin.func(function() {\n\t return Sk.builtin.assk$(new Date().getTime() / 1000, undefined);\n });\n\n return mod;\n}\n", "src/lib/image/__init__.js": "var ImageMod; // the single identifier needed in the global scope\n\nif (! ImageMod) {\n ImageMod = { };\n ImageMod.canvasLib = [];\n}\n\n// todo create an empty image by reading image data from a blank canvas of the appropriate size\n\nvar $builtinmodule = function(name) {\n var mod = {};\n\n var image = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self,imageId) {\n self.image = document.getElementById(imageId.v);\n if (self.image == null) {\n throw \"There is no image on this page named: \" + imageId.v;\n }\n self.width = self.image.width;\n self.height = self.image.height;\n self.canvas = document.createElement(\"canvas\");\n self.canvas.height = self.height;\n self.canvas.width = self.width;\n self.ctx = self.canvas.getContext(\"2d\");\n self.ctx.drawImage(self.image,0,0)\n self.imagedata = self.ctx.getImageData(0,0,self.width,self.height);\n });\n\n $loc.getPixel = new Sk.builtin.func(function(self,x,y) {\n\t\t\tx = Sk.builtin.asnum$(x);\n\t\t\ty = Sk.builtin.asnum$(y);\n var index = (y*4)*self.width+(x*4);\n var red = self.imagedata.data[index]\n var green = self.imagedata.data[index+1]\n var blue = self.imagedata.data[index+2]\n return Sk.misceval.callsim(mod.Pixel,red,green,blue);\n });\n\n $loc.setPixel = new Sk.builtin.func(function(self, x, y, pix) {\n\t\t\tx = Sk.builtin.asnum$(x);\n\t\t\ty = Sk.builtin.asnum$(y);\n var index = (y*4)*self.width+(x*4);\n self.imagedata.data[index] = Sk.misceval.callsim(pix.getRed,pix);\n self.imagedata.data[index+1] = Sk.misceval.callsim(pix.getGreen,pix);\n self.imagedata.data[index+2] = Sk.misceval.callsim(pix.getBlue,pix);\n self.imagedata.data[index+3] = 255;\n });\n\n $loc.getHeight = new Sk.builtin.func(function(self) {\n return self.image.height;\n });\n\n $loc.getWidth = new Sk.builtin.func(function(self,titlestring) {\n return self.image.width;\n });\n\n $loc.draw = new Sk.builtin.func(function(self,win,ulx,uly) {\n\t\t\twin = Sk.builtin.asnum$(win);\n\t\t\tulx = Sk.builtin.asnum$(ulx);\n\t\t\tuly = Sk.builtin.asnum$(uly);\n var can = Sk.misceval.callsim(win.getWin,win);\n var ctx = can.getContext(\"2d\");\n //ctx.putImageData(self.imagedata,0,0,0,0,self.imagedata.width,self.imagedata.height);\n if (! ulx) {\n ulx = 0;\n uly = 0;\n }\n ctx.putImageData(self.imagedata,ulx,uly);\n });\n\n // toList\n\n }\n\n mod.Image = Sk.misceval.buildClass(mod, image, 'Image', []);\n\n var eImage = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self,width,height) {\n self.width = Sk.builtin.asnum$(width);\n self.height = Sk.builtin.asnum$(height);\n self.canvas = document.createElement(\"canvas\");\n self.ctx = self.canvas.getContext('2d');\n self.canvas.height = self.height;\n self.canvas.width = self.width;\n self.imagedata = self.ctx.getImageData(0,0,self.width,self.height);\n });\n\n }\n\n mod.EmptyImage = Sk.misceval.buildClass(mod, eImage, 'EmptyImage', [mod.Image]);\n\n // create a ListImage object\n\n \n var pixel = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self,r,g,b) {\n self.red = Sk.builtin.asnum$(r);\n self.green = Sk.builtin.asnum$(g);\n self.blue = Sk.builtin.asnum$(b);\n });\n\n $loc.getRed = new Sk.builtin.func(function(self) {\n return self.red;\n });\n\n $loc.getGreen = new Sk.builtin.func(function(self) {\n return self.green;\n });\n\n $loc.getBlue = new Sk.builtin.func(function(self) {\n return self.blue;\n });\n\n $loc.setRed = new Sk.builtin.func(function(self,r) {\n self.red = Sk.builtin.asnum$(r);\n });\n\n $loc.setGreen = new Sk.builtin.func(function(self,g) {\n self.green = Sk.builtin.asnum$(g);\n });\n\n $loc.setBlue = new Sk.builtin.func(function(self,b) {\n self.blue = Sk.builtin.asnum$(b);\n });\n\n $loc.__getitem__ = new Sk.builtin.func(function(self,k) {\n\t\t k = Sk.builtin.asnum$(k);\n if(k == 0) {\n return self.red;\n } else if (k == 1) {\n return self.green;\n } else if (k == 2) {\n return self.blue;\n }\n });\n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n return \"[\" + self.red + \",\" + self.green + \",\" + self.blue + \"]\"\n });\n \n //getColorTuple\n $loc.getColorTuple = new Sk.builtin.func(function(self,x,y) {\n\n });\n\n //setRange -- change from 0..255 to 0.0 .. 1.0\n $loc.setRange = new Sk.builtin.func(function(self,mx) {\n self.max = Sk.builtin.asnum$(mx);\n });\n\n }\n mod.Pixel = Sk.misceval.buildClass(mod, pixel, 'Pixel', []);\n\n\n\n var screen = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self,width,height) {\n var currentCanvas = ImageMod.canvasLib[Sk.canvas];\n if (currentCanvas === undefined) {\n self.theScreen = document.getElementById(Sk.canvas);\n if (width !== undefined) {\n self.theScreen.height = height;\n self.theScreen.width = width;\n }\n\n ImageMod.canvasLib[Sk.canvas] = self.theScreen;\n } else {\n self.theScreen = currentCanvas;\n self.theScreen.height = self.theScreen.height;\n }\n self.theScreen.style.display = \"block\";\n });\n\n $loc.getWin = new Sk.builtin.func(function(self) {\n return self.theScreen;\n });\n\n // exitonclick\n $loc.exitonclick = new Sk.builtin.func(function(self) {\n var canvas_id = self.theScreen.id;\n self.theScreen.onclick = function() {\n document.getElementById(canvas_id).style.display = 'none';\n document.getElementById(canvas_id).onclick = null;\n delete ImageMod.canvasLib[canvas_id];\n }\n\n });\n //getMouse\n }\n\n mod.ImageWin = Sk.misceval.buildClass(mod, screen, 'ImageWin', []);\n\n return mod\n}\n", "src/lib/pythonds/basic/__init__.py": "\n#__all__ = [\"stack\"]\n\n\n#from .stack import Stack\n#from .queue import Queue\n\n\n\n", "src/lib/webgl/matrix4.js": "// more from 'tdl'\nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n var temp0v3_ = new Float32Array(3);\n var temp1v3_ = new Float32Array(3);\n var temp2v3_ = new Float32Array(3);\n\n var temp0v4_ = new Float32Array(4);\n var temp1v4_ = new Float32Array(4);\n var temp2v4_ = new Float32Array(4);\n\n var temp0m4_ = new Float32Array(16);\n var temp1m4_ = new Float32Array(16);\n var temp2m4_ = new Float32Array(16);\n\n var normalize = function(dst, a) {\n var n = 0.0;\n var aLength = a.length;\n for (var i = 0; i < aLength; ++i)\n n += a[i] * a[i];\n n = Math.sqrt(n);\n if (n > 0.00001) {\n for (var i = 0; i < aLength; ++i)\n dst[i] = a[i] / n;\n } else {\n for (var i = 0; i < aLength; ++i)\n dst[i] = 0;\n }\n return dst;\n };\n\n var cross = function(dst, a, b) {\n dst[0] = a[1] * b[2] - a[2] * b[1];\n dst[1] = a[2] * b[0] - a[0] * b[2];\n dst[2] = a[0] * b[1] - a[1] * b[0];\n return dst;\n };\n\n var subVector = function(dst, a, b) {\n var aLength = a.length;\n for (var i = 0; i < aLength; ++i)\n dst[i] = a[i] - b[i];\n return dst;\n };\n\n var dot = function(a, b) {\n return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);\n };\n\n mod.lookAt = new Sk.builtin.func(function(view, eye, target, up)\n {\n var t0 = temp0v3_;\n var t1 = temp1v3_;\n var t2 = temp2v3_;\n\n var vz = normalize(t0, subVector(t0, eye.v, target.v));\n var vx = normalize(t1, cross(t1, up.v, vz));\n var vy = cross(t2, vz, vx);\n\n var dst = view.v;\n dst[ 0] = vx[0];\n dst[ 1] = vy[0];\n dst[ 2] = vz[0];\n dst[ 3] = 0;\n dst[ 4] = vx[1];\n dst[ 5] = vy[1];\n dst[ 6] = vz[1];\n dst[ 7] = 0;\n dst[ 8] = vx[2];\n dst[ 9] = vy[2];\n dst[10] = vz[2];\n dst[11] = 0;\n dst[12] = -dot(vx, eye.v);\n dst[13] = -dot(vy, eye.v);\n dst[14] = -dot(vz, eye.v);\n dst[15] = 1;\n\n return view;\n });\n\n mod.perspective = new Sk.builtin.func(function(proj, angle, aspect, near, far)\n {\n var f = Math.tan(Math.PI * 0.5 - 0.5 * (angle * Math.PI / 180));\n var rangeInv = 1.0 / (near - far);\n\n var dst = proj.v;\n\n dst[0] = f / aspect;\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = f;\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = (near + far) * rangeInv;\n dst[11] = -1;\n\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = near * far * rangeInv * 2;\n dst[15] = 0;\n\n return proj;\n });\n\n // builds, not appending\n mod.rotationY = new Sk.builtin.func(function(target, angle)\n {\n var dst = target.v;\n var c = Math.cos(angle * Math.PI / 180);\n var s = Math.sin(angle * Math.PI / 180);\n\n dst[ 0] = c;\n dst[ 1] = 0;\n dst[ 2] = -s;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = s;\n dst[ 9] = 0;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return target;\n });\n\n mod.identity = new Sk.builtin.func(function(target)\n {\n var dst = target.v;\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n return target;\n });\n\n // row major\n mod.mul = new Sk.builtin.func(function(target, x, y)\n {\n var dst = target.v;\n var a = x.v;\n var b = y.v;\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[ 4 + 0];\n var a11 = a[ 4 + 1];\n var a12 = a[ 4 + 2];\n var a13 = a[ 4 + 3];\n var a20 = a[ 8 + 0];\n var a21 = a[ 8 + 1];\n var a22 = a[ 8 + 2];\n var a23 = a[ 8 + 3];\n var a30 = a[12 + 0];\n var a31 = a[12 + 1];\n var a32 = a[12 + 2];\n var a33 = a[12 + 3];\n var b00 = b[0];\n var b01 = b[1];\n var b02 = b[2];\n var b03 = b[3];\n var b10 = b[ 4 + 0];\n var b11 = b[ 4 + 1];\n var b12 = b[ 4 + 2];\n var b13 = b[ 4 + 3];\n var b20 = b[ 8 + 0];\n var b21 = b[ 8 + 1];\n var b22 = b[ 8 + 2];\n var b23 = b[ 8 + 3];\n var b30 = b[12 + 0];\n var b31 = b[12 + 1];\n var b32 = b[12 + 2];\n var b33 = b[12 + 3];\n dst[ 0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;\n dst[ 1] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;\n dst[ 2] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;\n dst[ 3] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;\n dst[ 4] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;\n dst[ 5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;\n dst[ 6] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;\n dst[ 7] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;\n dst[ 8] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;\n dst[ 9] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;\n dst[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;\n dst[11] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;\n dst[12] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;\n dst[13] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;\n dst[14] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;\n dst[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;\n return target;\n });\n\n mod.invert = new Sk.builtin.func(function(target, mat)\n {\n var dst = target.v;\n var m = mat.v;\n var m00 = m[0 * 4 + 0];\n var m01 = m[0 * 4 + 1];\n var m02 = m[0 * 4 + 2];\n var m03 = m[0 * 4 + 3];\n var m10 = m[1 * 4 + 0];\n var m11 = m[1 * 4 + 1];\n var m12 = m[1 * 4 + 2];\n var m13 = m[1 * 4 + 3];\n var m20 = m[2 * 4 + 0];\n var m21 = m[2 * 4 + 1];\n var m22 = m[2 * 4 + 2];\n var m23 = m[2 * 4 + 3];\n var m30 = m[3 * 4 + 0];\n var m31 = m[3 * 4 + 1];\n var m32 = m[3 * 4 + 2];\n var m33 = m[3 * 4 + 3];\n var tmp_0 = m22 * m33;\n var tmp_1 = m32 * m23;\n var tmp_2 = m12 * m33;\n var tmp_3 = m32 * m13;\n var tmp_4 = m12 * m23;\n var tmp_5 = m22 * m13;\n var tmp_6 = m02 * m33;\n var tmp_7 = m32 * m03;\n var tmp_8 = m02 * m23;\n var tmp_9 = m22 * m03;\n var tmp_10 = m02 * m13;\n var tmp_11 = m12 * m03;\n var tmp_12 = m20 * m31;\n var tmp_13 = m30 * m21;\n var tmp_14 = m10 * m31;\n var tmp_15 = m30 * m11;\n var tmp_16 = m10 * m21;\n var tmp_17 = m20 * m11;\n var tmp_18 = m00 * m31;\n var tmp_19 = m30 * m01;\n var tmp_20 = m00 * m21;\n var tmp_21 = m20 * m01;\n var tmp_22 = m00 * m11;\n var tmp_23 = m10 * m01;\n\n var t0 = (tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31) -\n (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\n var t1 = (tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31) -\n (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\n var t2 = (tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31) -\n (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\n var t3 = (tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21) -\n (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\n\n var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\n\n dst[ 0] = d * t0;\n dst[ 1] = d * t1;\n dst[ 2] = d * t2;\n dst[ 3] = d * t3;\n dst[ 4] = d * ((tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30) -\n (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30));\n dst[ 5] = d * ((tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30) -\n (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30));\n dst[ 6] = d * ((tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30) -\n (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30));\n dst[ 7] = d * ((tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20) -\n (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20));\n dst[ 8] = d * ((tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33) -\n (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33));\n dst[ 9] = d * ((tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33) -\n (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33));\n dst[10] = d * ((tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33) -\n (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33));\n dst[11] = d * ((tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23) -\n (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23));\n dst[12] = d * ((tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12) -\n (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22));\n dst[13] = d * ((tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22) -\n (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02));\n dst[14] = d * ((tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02) -\n (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12));\n dst[15] = d * ((tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12) -\n (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02));\n return target;\n });\n\n mod.transpose = new Sk.builtin.func(function(target, mat)\n {\n var dst = target.v;\n var m = mat.v;\n for (var j = 0; j < 4; ++j) {\n for (var i = 0; i < 4; ++i)\n dst[j * 4 + i] = m[i * 4 + j];\n }\n return dst;\n });\n\n return mod;\n};\n", "src/lib/webgl/__init__.js": "var $builtinmodule = function(name)\n{\n var mod = {};\n\n // todo; won't work compressed\n mod.tp$name = \"webgl\";\n\n //\n // Setup code taken from 'tdl'. I tried to use more of it, but it's a bit\n // broken.\n //\n var makeFailHTML = function(msg) {\n return '' +\n '<table style=\"background-color: #8CE; width: 100%; height: 100%;\"><tr>' +\n '<td align=\"center\">' +\n '<div style=\"display: table-cell; vertical-align: middle;\">' +\n '<div style=\"\">' + msg + '</div>' +\n '</div>' +\n '</td></tr></table>';\n };\n\n var GET_A_WEBGL_BROWSER = '' +\n 'This page requires a browser that supports WebGL.<br/>' +\n '<a href=\"http://get.webgl.org\">Click here to upgrade your browser.</a>';\n\n var NEED_HARDWARE = '' +\n \"It doesn't appear your computer can support WebGL.<br/>\" +\n '<a href=\"http://get.webgl.org\">Click here for more information.</a>';\n \n var create3DContext = function(canvas) {\n var names = [\"webgl\", \"experimental-webgl\", \"webkit-3d\", \"moz-webgl\"];\n var context = null;\n for (var ii = 0; ii < names.length; ++ii) {\n try {\n context = canvas.getContext(names[ii]);\n } catch(e) {}\n if (context) {\n break;\n }\n }\n if (context) {\n // Disallow selection by default. This keeps the cursor from changing to an\n // I-beam when the user clicks and drags. It's easier on the eyes.\n function returnFalse() {\n return false;\n }\n\n canvas.onselectstart = returnFalse;\n canvas.onmousedown = returnFalse;\n }\n return context;\n };\n\n var setupWebGL = function(canvasContainerId, opt_canvas) {\n var container = document.getElementById(canvasContainerId);\n var context;\n if (!opt_canvas) {\n opt_canvas = container.getElementsByTagName(\"canvas\")[0];\n }\n if (!opt_canvas) {\n // this browser doesn't support the canvas tag at all. Not even 2d.\n container.innerHTML = makeFailHTML(\n GET_A_WEBGL_BROWSER);\n return;\n }\n\n var context = create3DContext(opt_canvas);\n if (!context) {\n // TODO(gman): fix to official way to detect that it's the user's machine, not the browser.\n var browserStrings = navigator.userAgent.match(/(\\w+\\/.*? )/g);\n var browsers = {};\n try {\n for (var b = 0; b < browserStrings.length; ++b) {\n var parts = browserStrings[b].match(/(\\w+)/g);\n var bb = [];\n for (var ii = 1; ii < parts.length; ++ii) {\n bb.push(parseInt(parts[ii]));\n }\n browsers[parts[0]] = bb;\n }\n } catch (e) {\n }\n if (browsers.Chrome &&\n (browsers.Chrome[0] > 7 ||\n (browsers.Chrome[0] == 7 && browsers.Chrome[1] > 0) ||\n (browsers.Chrome[0] == 7 && browsers.Chrome[1] == 0 && browsers.Chrome[2] >= 521))) {\n container.innerHTML = makeFailHTML(\n NEED_HARDWARE);\n } else {\n container.innerHTML = makeFailHTML(\n GET_A_WEBGL_BROWSER);\n }\n }\n return context;\n };\n\n mod.Context = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self, canvasid)\n {\n var canvas = document.getElementById(canvasid.v);\n // NB: purposefully leak this to global because\n // everything wants it (esp. for constants it's a pain\n // to have to pass it to utility functions)\n /*var*/ gl = setupWebGL(canvasid.v, canvas)\n if (!gl)\n throw \"couldn't get webgl context, unsupported browser?\";\n\n self.gl = gl;\n // all (?) browsers that have webgl support\n // __proto__ too so we cheese out and just rip\n // them out of there rather than manually\n // enumerating the entire webgl api. it wouldn't\n // be too difficult to do it \"properly\", just\n // long.\n for (var k in gl.__proto__)\n {\n if (typeof gl.__proto__[k] === \"number\")\n {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), gl.__proto__[k]);\n }\n else if (typeof gl.__proto__[k] === \"function\")\n {\n (function(key) {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), new Sk.builtin.func(function()\n {\n var f = gl.__proto__[key];\n // todo; assuming only basic\n // type returns?\n return f.apply(gl, arguments);\n }));\n }(k));\n }\n }\n\n console.log(\"gl initialized\", gl, canvas, canvas.width, canvas.height);\n\n // set to cornflower so we know we're init'd at least\n gl.clearColor(100/255.0,149/255.0,237/255.0,1);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(0, 0, canvas.width, canvas.height);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.flush();\n });\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n $loc.setDrawFunc = new Sk.builtin.func(function(self, func)\n {\n var startTime = (new Date()).getTime();\n var intervalId = setInterval(function() {\n Sk.misceval.callsim(func, self, (new Date()).getTime() - startTime);\n if (goog.global.shutdownGLContext)\n {\n clearInterval(intervalId);\n console.log(\"gl draw function shutting down\");\n return;\n }\n }, 1000.0 / 60.0);\n \n });\n },\n 'Context', []);\n\n mod.Shader = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self, gl, vertex, fragment)\n {\n self.gl = gl.gl;\n var gl = self.gl;\n self.program = gl.createProgram();\n var vs = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vs, vertex.v);\n gl.compileShader(vs);\n if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS))\n {\n console.log(gl.getShaderInfoLog(vs));\n throw new Sk.builtin.SyntaxError(\"Error compiling vertex shader:\" + gl.getShaderInfoLog(vs));\n }\n gl.attachShader(self.program, vs);\n gl.deleteShader(vs);\n \n var fs = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fs, fragment.v);\n gl.compileShader(fs);\n if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS))\n {\n console.log(gl.getShaderInfoLog(fs));\n throw new Sk.builtin.SyntaxError(\"Error compiling fragment shader:\" + gl.getShaderInfoLog(fs));\n }\n gl.attachShader(self.program, fs);\n gl.deleteShader(fs);\n\n gl.linkProgram(self.program);\n gl.useProgram(self.program);\n\n\n //\n //\n // Some more init code from 'tdl' (slightly\n // tweaked)\n //\n //\n\n var endsWith = function(haystack, needle) {\n return haystack.substr(haystack.length - needle.length) === needle;\n };\n\n // Look up attribs.\n var attribs = {\n };\n // Also make a plain table of the locs.\n var attribLocs = {\n };\n\n function createAttribSetter(info, index) {\n if (info.size != 1) {\n throw(\"arrays of attribs not handled\");\n }\n return function(b) {\n gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer());\n gl.enableVertexAttribArray(index);\n gl.vertexAttribPointer(\n index, b.numComponents(), b.type(), false, b.stride(), b.offset());\n };\n }\n\n var numAttribs = gl.getProgramParameter(self.program, gl.ACTIVE_ATTRIBUTES);\n for (var ii = 0; ii < numAttribs; ++ii) {\n var info = gl.getActiveAttrib(self.program, ii);\n name = info.name;\n if (endsWith(name, \"[0]\")) {\n name = name.substr(0, name.length - 3);\n }\n var index = gl.getAttribLocation(self.program, info.name);\n attribs[name] = createAttribSetter(info, index);\n attribLocs[name] = index\n }\n\n // Look up uniforms\n var numUniforms = gl.getProgramParameter(self.program, gl.ACTIVE_UNIFORMS);\n var uniforms = {\n };\n\n function createUniformSetter(info) {\n var loc = gl.getUniformLocation(self.program, info.name);\n var type = info.type;\n if (info.size > 1 && endsWith(info.name, \"[0]\")) {\n // It's an array.\n if (type == gl.FLOAT)\n return function(v) { gl.uniform1fv(loc, v); };\n if (type == gl.FLOAT_VEC2)\n return function(v) { gl.uniform2fv(loc, v); };\n if (type == gl.FLOAT_VEC3)\n return function(v) { gl.uniform3fv(loc, v); };\n if (type == gl.FLOAT_VEC4)\n return function(v) { gl.uniform4fv(loc, v); };\n if (type == gl.INT)\n return function(v) { gl.uniform1iv(loc, v); };\n if (type == gl.INT_VEC2)\n return function(v) { gl.uniform2iv(loc, v); };\n if (type == gl.INT_VEC3)\n return function(v) { gl.uniform3iv(loc, v); };\n if (type == gl.INT_VEC4)\n return function(v) { gl.uniform4iv(loc, v); };\n if (type == gl.BOOL)\n return function(v) { gl.uniform1iv(loc, v); };\n if (type == gl.BOOL_VEC2)\n return function(v) { gl.uniform2iv(loc, v); };\n if (type == gl.BOOL_VEC3)\n return function(v) { gl.uniform3iv(loc, v); };\n if (type == gl.BOOL_VEC4)\n return function(v) { gl.uniform4iv(loc, v); };\n if (type == gl.FLOAT_MAT2)\n return function(v) { gl.uniformMatrix2fv(loc, false, v); };\n if (type == gl.FLOAT_MAT3)\n return function(v) { gl.uniformMatrix3fv(loc, false, v); };\n if (type == gl.FLOAT_MAT4)\n return function(v) { gl.uniformMatrix4fv(loc, false, v); };\n if (type == gl.SAMPLER_2D)\n return function(v) { gl.uniform1iv(loc, v); };\n if (type == gl.SAMPLER_CUBE_MAP)\n return function(v) { gl.uniform1iv(loc, v); };\n throw (\"unknown type: 0x\" + type.toString(16));\n } else {\n if (type == gl.FLOAT)\n return function(v) { gl.uniform1f(loc, v); };\n if (type == gl.FLOAT_VEC2)\n return function(v) { gl.uniform2fv(loc, v); };\n if (type == gl.FLOAT_VEC3)\n return function(v) { gl.uniform3fv(loc, v); };\n if (type == gl.FLOAT_VEC4)\n return function(v) { gl.uniform4fv(loc, v); };\n if (type == gl.INT)\n return function(v) { gl.uniform1i(loc, v); };\n if (type == gl.INT_VEC2)\n return function(v) { gl.uniform2iv(loc, v); };\n if (type == gl.INT_VEC3)\n return function(v) { gl.uniform3iv(loc, v); };\n if (type == gl.INT_VEC4)\n return function(v) { gl.uniform4iv(loc, v); };\n if (type == gl.BOOL)\n return function(v) { gl.uniform1i(loc, v); };\n if (type == gl.BOOL_VEC2)\n return function(v) { gl.uniform2iv(loc, v); };\n if (type == gl.BOOL_VEC3)\n return function(v) { gl.uniform3iv(loc, v); };\n if (type == gl.BOOL_VEC4)\n return function(v) { gl.uniform4iv(loc, v); };\n if (type == gl.FLOAT_MAT2)\n return function(v) { gl.uniformMatrix2fv(loc, false, v); };\n if (type == gl.FLOAT_MAT3)\n return function(v) { gl.uniformMatrix3fv(loc, false, v); };\n if (type == gl.FLOAT_MAT4)\n return function(v) { gl.uniformMatrix4fv(loc, false, v); };\n if (type == gl.SAMPLER_2D)\n return function(v) { gl.uniform1i(loc, v); };\n if (type == gl.SAMPLER_CUBE)\n return function(v) { gl.uniform1i(loc, v); };\n throw (\"unknown type: 0x\" + type.toString(16));\n }\n }\n\n for (var ii = 0; ii < numUniforms; ++ii) {\n var info = gl.getActiveUniform(self.program, ii);\n name = info.name;\n if (endsWith(name, \"[0]\")) {\n name = name.substr(0, name.length - 3);\n }\n uniforms[name] = createUniformSetter(info);\n }\n\n self.attrib = attribs;\n self.attribLoc = attribLocs;\n self.uniform = uniforms;\n });\n\n $loc.setUniform = new Sk.builtin.func(function(self, uniform, value)\n {\n var func = self.uniform[uniform.v];\n if (func)\n {\n //console.log(\"SET UNI:\", uniform.v, value);\n func(Sk.ffi.remapToJs(value));\n }\n });\n\n $loc.setUniform$impl = function(self, uniform, value)\n {\n var func = self.uniform[uniform];\n if (func)\n {\n //console.log(\"SET UNI:\", uniform, value);\n func(value);\n }\n };\n\n $loc.use = new Sk.builtin.func(function(self)\n {\n self.gl.useProgram(self.program);\n });\n },\n 'Shader', []);\n\n\n mod.Float32Array = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self, data)\n {\n if (typeof data === \"number\")\n self.v = new Float32Array(data);\n else\n self.v = new Float32Array(Sk.ffi.remapToJs(data));\n });\n\n $loc.__repr__ = new Sk.builtin.func(function(self)\n {\n var copy = [];\n for (var i = 0; i < self.v.length; ++i)\n copy.push(self.v[i]);\n return new Sk.builtin.str(\"[\"+copy.join(', ')+\"]\");\n });\n\n },\n 'Float32Array', []);\n\n\n return mod;\n};\n", "src/builtin/sys.js": "var $builtinmodule = function(name)\n{\n var sys = {};\n\n var args = [];\n var argv = Sk.getSysArgv();\n for (var i = 0; i < argv.length; ++i)\n args.push(new Sk.builtin.str(argv[i]));\n sys.argv = new Sk.builtins['list'](args);\n\n sys.copyright = Sk.builtin['str'](\"Copyright 2009-2010 Scott Graham.\\nAll Rights Reserved.\\n\");\n\n sys.modules = Sk.sysmodules;\n\n sys.path = Sk.realsyspath;\n\n sys.getExecutionLimit = new Sk.builtin.func(function() {\n return Sk.execLimit\n });\n\n sys.setExecutionLimit = new Sk.builtin.func(function(t) {\n if (t !== undefined) {\n Sk.execLimit = t\n }\n });\n\n sys.debug = new Sk.builtin.func(function() {\n debugger;\n });\n\n return sys;\n};\n", "src/lib/pythonds/trees/balance.py": "#!/bin/env python3.1\n# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005, 2010\n# \n\nfrom .bst import BinarySearchTree, TreeNode\n\nclass AVLTree(BinarySearchTree):\n '''\n Author: Brad Miller\n Date: 1/15/2005\n Description: Imlement a binary search tree with the following interface\n functions: \n __contains__(y) <==> y in x\n __getitem__(y) <==> x[y]\n __init__()\n __len__() <==> len(x)\n __setitem__(k,v) <==> x[k] = v\n clear()\n get(k)\n has_key(k)\n items() \n keys() \n values()\n put(k,v)\n '''\n\n\n def _put(self,key,val,currentNode):\n if key < currentNode.key:\n if currentNode.hasLeftChild():\n self._put(key,val,currentNode.leftChild)\n else:\n currentNode.leftChild = TreeNode(key,val,parent=currentNode)\n self.updateBalance(currentNode.leftChild)\n else:\n if currentNode.hasRightChild():\n self._put(key,val,currentNode.rightChild)\n else:\n currentNode.rightChild = TreeNode(key,val,parent=currentNode)\n self.updateBalance(currentNode.rightChild) \n\n def updateBalance(self,node):\n if node.balanceFactor > 1 or node.balanceFactor < -1:\n self.rebalance(node)\n return\n if node.parent != None:\n if node.isLeftChild():\n node.parent.balanceFactor += 1\n elif node.isRightChild():\n node.parent.balanceFactor -= 1\n\n if node.parent.balanceFactor != 0:\n self.updateBalance(node.parent)\n\n def rebalance(self,node):\n if node.balanceFactor < 0:\n if node.rightChild.balanceFactor > 0:\n # Do an LR Rotation\n self.rotateRight(node.rightChild)\n self.rotateLeft(node)\n else:\n # single left\n self.rotateLeft(node)\n elif node.balanceFactor > 0:\n if node.leftChild.balanceFactor < 0:\n # Do an RL Rotation\n self.rotateLeft(node.leftChild)\n self.rotateRight(node)\n else:\n # single right\n self.rotateRight(node)\n\n def rotateLeft(self,rotRoot):\n newRoot = rotRoot.rightChild\n rotRoot.rightChild = newRoot.leftChild\n if newRoot.leftChild != None:\n newRoot.leftChild.parent = rotRoot\n newRoot.parent = rotRoot.parent\n if rotRoot.isRoot():\n self.root = newRoot\n else:\n if rotRoot.isLeftChild():\n rotRoot.parent.leftChild = newRoot\n else:\n rotRoot.parent.rightChild = newRoot\n newRoot.leftChild = rotRoot\n rotRoot.parent = newRoot\n rotRoot.balanceFactor = rotRoot.balanceFactor + 1 - min(newRoot.balanceFactor, 0)\n newRoot.balanceFactor = newRoot.balanceFactor + 1 + max(rotRoot.balanceFactor, 0)\n\n\n def rotateRight(self,rotRoot):\n newRoot = rotRoot.leftChild\n rotRoot.leftChild = newRoot.rightChild\n if newRoot.rightChild != None:\n newRoot.rightChild.parent = rotRoot\n newRoot.parent = rotRoot.parent\n if rotRoot.isRoot():\n self.root = newRoot\n else:\n if rotRoot.isRightChild():\n rotRoot.parent.rightChild = newRoot\n else:\n rotRoot.parent.leftChild = newRoot\n newRoot.rightChild = rotRoot\n rotRoot.parent = newRoot\n rotRoot.balanceFactor = rotRoot.balanceFactor - 1 - max(newRoot.balanceFactor, 0)\n newRoot.balanceFactor = newRoot.balanceFactor - 1 + min(rotRoot.balanceFactor, 0)\n \n", "src/lib/pythonds/basic/queue.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n#queue.py\r\n\r\nclass Queue:\r\n def __init__(self):\r\n self.items = []\r\n\r\n def isEmpty(self):\r\n return self.items == []\r\n\r\n def enqueue(self, item):\r\n self.items.insert(0,item)\r\n\r\n def dequeue(self):\r\n return self.items.pop()\r\n\r\n def size(self):\r\n return len(self.items)\r\n", "src/lib/pythonds/graphs/adjGraph.py": "#\n# adjGraph\n#\n# Created by Brad Miller on 2005-02-24.\n# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.\n#\n\nimport sys\nimport os\nimport unittest\n\nclass Graph:\n def __init__(self):\n self.vertices = {}\n self.numVertices = 0\n \n def addVertex(self,key):\n self.numVertices = self.numVertices + 1\n newVertex = Vertex(key)\n self.vertices[key] = newVertex\n return newVertex\n \n def getVertex(self,n):\n if n in self.vertices:\n return self.vertices[n]\n else:\n return None\n\n def __contains__(self,n):\n return n in self.vertices\n \n def addEdge(self,f,t,cost=0):\n if f not in self.vertices:\n nv = self.addVertex(f)\n if t not in self.vertices:\n nv = self.addVertex(t)\n self.vertices[f].addNeighbor(self.vertices[t],cost)\n \n def getVertices(self):\n return list(self.vertices.keys())\n \n def __iter__(self):\n return iter(self.vertices.values())\n \nclass Vertex:\n def __init__(self,num):\n self.id = num\n self.connectedTo = {}\n self.color = 'white'\n self.dist = sys.maxsize\n self.pred = None\n self.disc = 0\n self.fin = 0\n\n # def __lt__(self,o):\n # return self.id < o.id\n \n def addNeighbor(self,nbr,weight=0):\n self.connectedTo[nbr] = weight\n \n def setColor(self,color):\n self.color = color\n \n def setDistance(self,d):\n self.dist = d\n\n def setPred(self,p):\n self.pred = p\n\n def setDiscovery(self,dtime):\n self.disc = dtime\n \n def setFinish(self,ftime):\n self.fin = ftime\n \n def getFinish(self):\n return self.fin\n \n def getDiscovery(self):\n return self.disc\n \n def getPred(self):\n return self.pred\n \n def getDistance(self):\n return self.dist\n \n def getColor(self):\n return self.color\n \n def getConnections(self):\n return self.connectedTo.keys()\n \n def getWeight(self,nbr):\n return self.connectedTo[nbr]\n \n def __str__(self):\n return str(self.id) + \":color \" + self.color + \":disc \" + str(self.disc) + \":fin \" + str(self.fin) + \":dist \" + str(self.dist) + \":pred \\n\\t[\" + str(self.pred)+ \"]\\n\"\n \n def getId(self):\n return self.id\n\nclass adjGraphTests(unittest.TestCase):\n def setUp(self):\n self.tGraph = Graph()\n \n def testMakeGraph(self):\n gFile = open(\"test.dat\")\n for line in gFile:\n fVertex, tVertex = line.split('|')\n fVertex = int(fVertex)\n tVertex = int(tVertex)\n self.tGraph.addEdge(fVertex,tVertex)\n for i in self.tGraph:\n adj = i.getAdj()\n for k in adj:\n print(i, k)\n\n \nif __name__ == '__main__':\n unittest.main()\n \n", "src/lib/turtle/__init__.js": "//\n//\n// Turtle Graphics Module for Skulpt\n//\n// Brad Miller\n//\n//\n//\n\n\nvar TurtleGraphics; // the single identifier needed in the global scope\n\nif (! TurtleGraphics) {\n TurtleGraphics = { };\n}\n\n\n(function () {\n\n // Define private constants\n\n var Degree2Rad = Math.PI / 180.0; // conversion factor for degrees to radians\n var Rad2Degree = 180.0 / Math.PI\n\n //\n // Define TurtleCanvas\n // \n\n function TurtleCanvas(options) {\n this.canvasID = TurtleGraphics.defaults.canvasID;\n if (options.canvasID) {\n this.canvasID = options.canvasID;\n }\n\n this.canvas = document.getElementById(this.canvasID);\n this.context = this.canvas.getContext('2d');\n //this.canvas.style.display = 'block';\n $(this.canvas).fadeIn();\n\n this.lineScale = 1.0;\n this.xptscale = 1.0;\n this.yptscale = 1.0\n\n this.llx = -this.canvas.width / 2;\n this.lly = -this.canvas.height / 2;\n this.urx = this.canvas.width / 2;\n this.ury = this.canvas.height / 2;\n this.setup(this.canvas.width,this.canvas.height);\n TurtleGraphics.canvasInit = true;\n this.tlist = []\n\n\t\tthis.timeFactor = 5;\n if (TurtleGraphics.defaults.animate) {\n this.delay = 5 * this.timeFactor;\n } else {\n this.delay = 0;\n }\n this.segmentLength = 10;\n this.renderCounter = 1;\n this.clearPoint = 0;\n TurtleGraphics.canvasLib[this.canvasID] = this;\n\t\tSk.tg.fadeOnExit = true;\t//\tThis can be set to false AFTER the program completes to turn off the fade out on the canvas as a result of exitonclick\n }\n\n TurtleCanvas.prototype.setup = function(width, height) {\n this.canvas.width = width;\n this.canvas.height = height;\n this.lineScale = 1.0;\n this.xptscale = 1.0;\n this.yptscale = 1.0;\n\n this.llx = -this.canvas.width / 2;\n this.lly = -this.canvas.height / 2;\n this.urx = this.canvas.width / 2;\n this.ury = this.canvas.height / 2;\n this.renderCounter = 1;\n this.clearPoint = 0;\n\t\tthis.timeFactor = 5;\n if (TurtleGraphics.defaults.animate ) {\n this.delay = 5 * this.timeFactor;\n } else {\n this.delay = 0;\n }\n\n if (TurtleGraphics.canvasInit == false) {\n this.context.save();\n this.context.translate(this.canvas.width / 2, this.canvas.height / 2); // move 0,0 to center.\n this.context.scale(1, -1); // scaling like this flips the y axis the right way.\n TurtleGraphics.canvasInit = true;\n TurtleGraphics.eventCount = 0;\n TurtleGraphics.renderClock = 0;\n TurtleGraphics.renderTime = 0;\t// RNL\n } else {\n this.context.restore();\n this.context.translate(this.canvas.width / 2, this.canvas.height / 2); // move 0,0 to center.\n this.context.scale(1, -1); // scaling like this flips the y axis the right way.\n this.context.clearRect(-this.canvas.width / 2, -this.canvas.height / 2,\n this.canvas.width, this.canvas.height);\n }\n }\n TurtleCanvas.prototype.addToCanvas = function(t) {\n\t this.tlist.push(t);\n }\n\n TurtleCanvas.prototype.onCanvas = function(t) {\n return (this.tlist.indexOf(t) >= 0);\n }\n\n TurtleCanvas.prototype.isAnimating = function() {\n return (this.tlist.length > 0)\n }\n\n TurtleCanvas.prototype.startAnimating = function(t) {\n\t\tif (! this.isAnimating()) {\n \tthis.intervalId = setTimeout(render, this.delay);\t//\tsetInterval(render, this.delay);\n\t\t}\n \tif (!this.onCanvas(t))\t//\tAdded by RNL in case startAnimating is called after it's already been added\n \t\tthis.addToCanvas(t);\n Sk.isTurtleProgram = true;\n }\n\n TurtleCanvas.prototype.doneAnimating = function(t) {\n var idx = this.tlist.indexOf(t);\n if (idx > -1)\n this.tlist.splice(idx, 1);\n if (this.tlist.length == 0) {\n clearTimeout(this.intervalId)\t//\tclearInterval(this.intervalId);\n $(Sk.runButton).removeAttr('disabled');\n }\n\n }\n\n TurtleCanvas.prototype.cancelAnimation = function() {\n if (this.intervalId) {\n clearTimeout(this.intervalId)\t//\tclearInterval(this.intervalId);\n }\n\n for (var t in this.tlist) {\n this.tlist[t].aCount = this.tlist[t].drawingEvents.length - 1;\n }\n render();\n }\n\n TurtleCanvas.prototype.setSpeedDelay = function(s) {\t// RNL\n var df = 10 - (s % 11) + 1;\n this.delay = df * this.timeFactor;\t//\tRNL was 10;\n }\n\n TurtleCanvas.prototype.setDelay = function(d) {\n this.delay = d;\n }\n\n TurtleCanvas.prototype.getDelay = function(s) { // RNL\n return this.delay;\n }\n\n TurtleCanvas.prototype.setCounter = function(s) {\n\t\tif (!s || s <= 0)\t//\tDon't let this be less than 1\n\t\t\ts = 1;\n this.renderCounter = s;\n }\n\n TurtleCanvas.prototype.getCounter = function() {\n return this.renderCounter;\n }\n\n TurtleCanvas.prototype.setworldcoordinates = function(llx, lly, urx, ury) {\n this.context.restore();\n this.context.scale(this.canvas.width / (urx - llx), -this.canvas.height / (ury - lly));\n if (lly == 0)\n this.context.translate(-llx, lly - (ury - lly));\n else if (lly > 0)\n this.context.translate(-llx, -lly * 2);\n else\n this.context.translate(-llx, -ury);\n\n var xlinescale = (urx - llx) / this.canvas.width;\n var ylinescale = (ury - lly) / this.canvas.height;\n this.xptscale = xlinescale;\n this.yptscale = ylinescale;\n this.lineScale = Math.min(xlinescale,ylinescale)\n this.context.save();\n\n this.llx = llx;\n this.lly = lly;\n this.urx = urx;\n this.ury = ury;\n\n }\n\n TurtleCanvas.prototype.window_width = function() {\n return this.canvas.width;\n }\n\n TurtleCanvas.prototype.window_height = function() {\n return this.canvas.height;\n }\n\n TurtleCanvas.prototype.bgcolor = function(c) {\n this.background_color = c;\n //this.canvas.style.setProperty(\"background-color\", c.v);\n $(this.canvas).css(\"background-color\",c.v);\n }\n\n TurtleCanvas.prototype.setSegmentLength = function(s) {\n this.segmentLength = s;\n }\n\n TurtleCanvas.prototype.getSegmentLength = function() {\n return this.segmentLength;\n }\n \n // todo: if animating, this should be deferred until the proper time\n TurtleCanvas.prototype.exitonclick = function () {\n var canvas_id = this.canvasID;\n var theCanvas = this;\n $(this.canvas).click(function() {\n if (! theCanvas.isAnimating()) {\n\t\t\t\tif (Sk.tg.fadeOnExit)\t//\tLet's this be configurable\n \t$(\"#\"+canvas_id).hide();\n $(\"#\"+canvas_id).unbind('click');\n Sk.tg.canvasInit = false;\n delete Sk.tg.canvasLib[canvas_id];\n }\n });\n }\n\n TurtleCanvas.prototype.turtles = function() {\n return TurtleGraphics.turtleList;\n }\n\n\tTurtleCanvas.prototype.tracer = function(t, d) {\t//\tNew version NOT attached to a turtle (as per real turtle)\n this.setCounter(t);\n\t\tif (t == 0) {\n\t\t\tfor (var i in this.turtleList)\n\t\t\t\tthis.turtleList[i].animate = false;\n\t\t\tthis.cancelAnimation();\n\t\t}\n\t\tif (d !== undefined)\n\t\t\tthis.setDelay(d);\n\t}\n\n // check if all turtles are done\n allDone = function() {\n var allDone = true;\n for (var tix in TurtleGraphics.turtleList) {\n var theT = TurtleGraphics.turtleList[tix];\n allDone = allDone && (theT.aCount >= theT.drawingEvents.length);\n }\n return allDone;\n }\n //\n // This is the function that provides the animation\n //\n render = function () {\n var context = document.getElementById(TurtleGraphics.defaults.canvasID).getContext('2d');\n with (context) {\n with (TurtleGraphics.canvasLib[TurtleGraphics.defaults.canvasID]) {\n clearRect(llx, lly, (urx - llx), (ury - lly));\n //canvas.style.setProperty(\"background-color\",TurtleGraphics.turtleCanvas.bgcolor.v);\n }\n var incr = TurtleGraphics.canvasLib[TurtleGraphics.defaults.canvasID].getCounter();\n var lastCanvas = null\n\n TurtleGraphics.renderClock += incr;\n\n for (var tix in TurtleGraphics.turtleList) {\n var t = TurtleGraphics.turtleList[tix]\n lastCanvas = t.turtleCanvas \n if (t.aCount >= t.drawingEvents.length)\n t.aCount = t.drawingEvents.length - 1;\n moveTo(0, 0);\n var currentPos = new Vector(0,0,0);\n var currentHead = new Vector(1,0,0);\n lineWidth = t.get_pen_width();\n lineCap = 'round';\n lineJoin = 'round';\n strokeStyle = 'black';\n var filling = false;\n if (isNaN(t.turtleCanvas.delay))\n \tt.turtleCanvas.delay = 0\n//\t\t\t\tconsole.log(tix + \" : \" + t.clearPoint + \" to \" + t.aCount)\n for (var i = t.clearPoint; (i <= t.aCount || t.turtleCanvas.delay == 0) && i < t.drawingEvents.length; i++) {\n \tif (i > t.aCount)\t//\tIf se jump past aCount, jump it ahead\n \t\tt.aCount = i\n var oper = t.drawingEvents[i];\n var ts = oper[oper.length-1];\n//\t\t\t\t\tconsole.log(i + \"/\" + ts + oper [0] + \"{\" + oper [1] + \"}\" + t.turtleCanvas.delay)\n if (ts <= TurtleGraphics.renderClock || t.turtleCanvas.delay == 0) {\n \tif (ts > TurtleGraphics.renderClock)\t//\tIf we go past the render clock, jump it ahead\n \t\tTurtleGraphics.renderClock = ts\n//\t\t\t\t\t\tconsole.log(\"<==\")\n if (oper[0] == \"LT\") { // line to\n if (! filling) {\n beginPath();\n moveTo(oper[1], oper[2]);\n }\n lineTo(oper[3], oper[4]);\n strokeStyle = oper[5];\n stroke();\n currentPos = new Vector(oper[3],oper[4],0);\n if (! filling)\n closePath();\n }\n else if (oper[0] == \"MT\") { // move to\n moveTo(oper[3], oper[4]);\n currentPos = new Vector(oper[3],oper[4],0);\n }\n else if (oper[0] == \"BF\") { // begin fill\n beginPath();\n moveTo(oper[1], oper[2]);\n filling = true;\n }\n else if (oper[0] == \"EF\") { // end fill\n fillStyle = oper[3];\n stroke();\n fill();\n closePath();\n filling = false;\n }\n else if (oper[0] == \"FC\") { // fill color\n fillStyle = oper[1];\n }\n else if (oper[0] == \"TC\") { // turtle color\n strokeStyle = oper[1];\n }\n else if (oper[0] == \"PW\") { // Pen width\n lineWidth = oper[1];\n }\n else if (oper[0] == \"DT\") { // Dot\n var col = fillStyle;\n fillStyle = oper[2];\n var size = oper[1];\n fillRect(oper[3] - size / 2, oper[4] - size / 2, size, size);\n fillStyle = col;\n }\n else if (oper[0] == \"CI\") { // Circle\n if (!filling)\n\t\t\t\t\t\t\t\tbeginPath();\n arc(oper[1], oper[2], oper[3], oper[4], oper[5], oper[6]);\n currentPos = new Vector(oper[1]+Math.cos(oper[5])*oper[3],\n oper[2]+Math.sin(oper[5])*oper[3],0);\n stroke();\n if (! filling) {\n closePath();\n }\n }\n else if (oper[0] == \"WT\") { // write\n if (font)\n font = oper[2];\n scale(1, -1);\n fillText(oper[1], oper[3], -oper[4]);\n scale(1, -1);\n } else if (oper[0] == \"ST\") { // stamp\n t.drawturtle(oper[3], new Vector(oper[1], oper[2], 0));\n } else if (oper[0] == \"HT\") { // hide turtle\n t.visible = false;\n } else if (oper[0] == \"SH\") { // show turtle\n t.visible = true;\n } else if (oper[0] == \"TT\") {\n currentHead = oper[1];\n } else if (oper[0] == \"CL\") { // RNL clear\n \tclear_canvas(t.canvasID);\n \tt.clearPoint = i;\t// Different from reset that calls clear because it leaves the turtles where they are\n } else if (oper[0] == \"DL\") { // RNL delay\n \tvar df = oper[1]\n// \tconsole.log(\"animated delay set \" + df)\n \tt.turtleCanvas.delay = df\n } else if (oper[0] == \"SC\") { // RNL speed change\n \tvar s = oper[1]\n \tif (s < 0)\n \t\ts = 0\n \tif (s > 10)\n \t\ts = 10\n \t\t\t\t\t\tvar df = (10 - (s % 11) + 1) * t.turtleCanvas.timeFactor\t//\t10\n \t\t\t\t\t\tif (s == 0) {\n \t\t\t\t\t\t\tdf = 0\n \t\t\t\t\t\t}\n\t //\tt.turtleCanvas.intervalId = clearInterval(t.turtleCanvas.intervalId);\n\t \t\t\t\t\tt.turtleCanvas.delay = df;\n\t \t\t\t\t\t//\tt.turtleCanvas.intervalId = setInterval(render, t.turtleCanvas.delay)\n \t\t\t\t\t\tif (oper[2]) {\n \t\t\t\t\t\t\tt.turtleCanvas.setSegmentLength(oper[2]);\n \t\t\t\t\t\t}\n \t\t\t\t\t} else if (oper[0] == \"NO\") { // RNL no op \t\n } else {\n\t\t\t\t\t\t\tconsole.log(\"unknown op: \" + oper[0]);\n } // end of oper[0] test\n } // end of if ts < render clock\n } // end of for\n//\t\t\t\tconsole.log(TurtleGraphics.renderClock + \" / \" + t.aCount)\n//\t\t\t\tconsole.log(\"------------------------------\")\n t.aCount += incr;\n if (t.visible) {\n // draw the turtle\n t.drawturtle(currentHead.toAngle(), currentPos); // just use currentHead\n }\n }\n //if (t.aCount >= t.drawingEvents.length) {\n if (TurtleGraphics.renderClock > TurtleGraphics.eventCount ){ // && allDone() ){\n// t.turtleCanvas.doneAnimating(t);\n//\t\t\t\tconsole.log(\"done animating\")\n if (lastCanvas) lastCanvas.doneAnimating(t);\n } else {\n// \t\t\tt.turtleCanvas.intervalId = setTimeout(render, t.turtleCanvas.delay)\n \t\t\tif (lastCanvas) {\n \t\t\t\tlastCanvas.intervalId = setTimeout(render, lastCanvas.delay)\n \t\t\t}\n }\n }\n }\n\n\n\n // Constructor for Turtle objects\n function Turtle() {\n if (arguments.length >= 1) {\n this.initialize(arguments[0]);\n }\n else {\n this.initialize();\n }\n TurtleGraphics.turtleList.push(this);\n }\n\n\n Turtle.prototype.go_home = function () {\n // Put turtle in initial state\n // turtle is headed to the right\n // with location 0,0,0 in the middle of the canvas.\n // x grows to the right\n // y grows towards the top of the canvas\n with (this) {\n position = home;\n context.moveTo(home[0], home[1]);\n heading = new Vector([1.0, 0.0, 0.0]); // to the right; in turtle space x+ direction\n normal = new Vector([0.0, 0.0, -1.0]); // in z- direction\n }\n };\n\n Turtle.prototype.initialize = function () {\n // Initialize the turtle.\n var options = { };\n\n if (arguments.length >= 1) {\n options = arguments[0];\n }\n\n this.canvasID = TurtleGraphics.defaults.canvasID;\n if (options.canvasID) {\n this.canvasID = options.canvasID;\n }\n this.context = document.getElementById(this.canvasID).getContext('2d');\n\n this.animate = TurtleGraphics.defaults.animate;\n\n with (this.context) {\n if (TurtleGraphics.canvasInit == false) { // This is a workaround until I understand skulpt re-running better\n // the downside is that this limits us to a single turtle...\n save();\n translate(canvas.width / 2, canvas.height / 2); // move 0,0 to center.\n scale(1, -1); // scaling like this flips the y axis the right way.\n if (! TurtleGraphics.canvasLib[this.canvasID]) {\n TurtleGraphics.canvasLib[this.canvasID] = new TurtleCanvas(options);\n }\n TurtleGraphics.canvasInit = true;\n } else {\n clear_canvas(this.canvasID);\n }\n\n this.turtleCanvas = TurtleGraphics.canvasLib[this.canvasID];\n this.home = new Vector([0.0, 0.0, 0.0]);\n this.visible = true;\n this.shapeStore = {};\n this.shapeStore['turtle'] = turtleShapePoints();\n this.shapeStore['arrow'] = defaultShapePoints();\n this.shapeStore['circle'] = circleShapePoints();\n this.shapeStore['classic'] = classicShapePoints();\n this.currentShape = 'classic';\n this.drawingEvents = [];\n\n this.filling = false;\n this.pen = true;\n this.penStyle = 'black';\n this.penWidth = 2;\n this.fillStyle = 'black';\n this.position = [ ];\n this.heading = [ ];\n this.normal = [ ];\n this.go_home();\n this.aCount = 0;\n this.clearPoint = 0;\t// RNL for clear/clearScreen\n }\n }\n function turtleShapePoints() {\n var pl = [\n [0,16],\n [-2,14],\n [-1,10],\n [-4,7],\n [-7,9],\n [-9,8],\n [-6,5],\n [-7,1],\n [-5,-3],\n [-8,-6],\n [-6,-8],\n [-4,-5],\n [0,-7],\n [4,-5],\n [6,-8],\n [8,-6],\n [5,-3],\n [7,1],\n [6,5],\n [9,8],\n [7,9],\n [4,7],\n [1,10],\n [2,14]\n ];\n res = [];\n for (p in pl) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n function defaultShapePoints() {\n var pl = [\n [-10,0],\n [10,0],\n [0,10]\n ];\n res = [];\n for (p in pl) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n function circleShapePoints() {\n var pl = [\n [10,0],\n [9.51,3.09],\n [8.09,5.88],\n [5.88,8.09],\n [3.09,9.51],\n [0,10],\n [-3.09,9.51],\n [-5.88,8.09],\n [-8.09,5.88],\n [-9.51,3.09],\n [-10,0],\n [-9.51,-3.09],\n [-8.09,-5.88],\n [-5.88,-8.09],\n [-3.09,-9.51],\n [-0.00,-10.00],\n [3.09,-9.51],\n [5.88,-8.09],\n [8.09,-5.88],\n [9.51,-3.09]\n ];\n res = [];\n for (p in pl) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n function classicShapePoints() {\n var pl = [\n [0,0],\n [-5,-9],\n [0,-7],\n [5,-9]\n ];\n\n res = [];\n for (p in pl) {\n res.push(new Vector(pl[p]));\n }\n return res;\n\n }\n\n Turtle.prototype.clean = function () {\n // Clean the canvas\n // Optional second argument is color\n with (this) {\n if (arguments.length >= 1) {\n clear_canvas(canvasID, arguments[0]);\n }\n else {\n clear_canvas(canvasID);\n }\n initialize();\n }\n }\n\n Turtle.prototype.addDrawingEvent = function(eventList) {\n TurtleGraphics.eventCount += 1;\n eventList.push(TurtleGraphics.eventCount);\n this.drawingEvents.push(eventList);\n }\n// \n// Drawing Functions\n//\n\n // break a line into segments\n // sp: Vector of starting position\n // ep: Vector of ending position\n // sl: int length of segments\n segmentLine = function(sp, ep, sL, pen) {\n var head = ep.sub(sp).normalize();\n var numSegs = Math.floor(ep.sub(sp).len() / sL);\n var res = [];\n var oldp = sp;\n var newp;\n var op = \"\"\n if (pen)\n op = \"LT\"\n else\n op = \"MT\"\n for (var i = 0; i < numSegs; i++) {\n newp = oldp.linear(1, sL, head);\n res.push([op,oldp[0],oldp[1],newp[0],newp[1]]);\n oldp = newp;\n }\n if (! ((oldp[0] == ep[0]) && (oldp[1] == ep[1])))\n res.push([op, oldp[0], oldp[1], ep[0], ep[1]]);\n return res;\n }\n\n Turtle.prototype.draw_line = function(newposition) {\n with (this) {\n with (context) {\n if (! animate) {\n if (! filling) {\n beginPath();\n moveTo(position[0], position[1]);\n }\n lineCap = 'round';\n lineJoin = 'round';\n lineWidth = get_pen_width();\n strokeStyle = penStyle;\n lineTo(newposition[0], newposition[1]);\n stroke();\n if (! filling)\n closePath();\n } else {\n var r = segmentLine(position, newposition, turtleCanvas.getSegmentLength(), pen);\n for (var s in r) {\n r[s].push(penStyle);\n addDrawingEvent(r[s]);\n }\n if (! turtleCanvas.isAnimating()) {\n turtleCanvas.startAnimating(this);\n } else {\n if (! turtleCanvas.onCanvas(this))\n turtleCanvas.addToCanvas(this);\n }\n }\n }\n }\n\n }\n\n\n Turtle.prototype.forward = function (d) {\n with (this) {\n var newposition = position.linear(1, d, heading);\n goto(newposition);\n }\n }\n\n Turtle.prototype.backward = function(d) {\n this.forward(-d);\n }\n\n//\tThis is an internal function that sets the position without doing any drawing\n Turtle.prototype.teleport_to = function(nx, ny) {\n if (nx instanceof Vector)\n var newposition = nx;\n else\n var newposition = new Vector([nx,ny,0]);\n this.context.moveTo(newposition[0], newposition[1]);\n\t\tthis.position = newposition;\n\t}\n\n Turtle.prototype.goto = function(nx, ny) {\n if (nx instanceof Vector)\n var newposition = nx;\n else\n var newposition = new Vector([nx,ny,0]);\n with (this) {\n if (pen) {\n draw_line(newposition);\n } else {\n if (! animate) {\n context.moveTo(newposition[0], newposition[1]);\n } else {\n var r = segmentLine(position, newposition, turtleCanvas.getSegmentLength(), pen);\n for (var s in r)\n addDrawingEvent(r[s]);\n if (! turtleCanvas.isAnimating()) {\n turtleCanvas.startAnimating(this);\n } else {\n if (! turtleCanvas.onCanvas(this))\n turtleCanvas.addToCanvas(this);\n }\n }\n }\n position = newposition;\n\n }\n }\n\n Turtle.prototype.delay = function(d) {\t// RNL\n \tif (d != null) {\n \t\tif (d < 0)\n \t\t\td = -d\n \t\tif (!this.animate) \n \t\t\tthis.turtleCanvas.setDelay(d)\n \t\telse {\n \t\t\tthis.turtleCanvas.setDelay(d)\n\t \t\tthis.addDrawingEvent([\"DL\", d])\n\t \t\tthis.addDrawingEvent([\"NO\"])\n \t\t}\n \t}\n return this.turtleCanvas.getDelay();\n }\n\n Turtle.prototype.speed = function(s,t) {\n if (s > 0 && !this.animate) {\n this.animate = true;\n this.turtleCanvas.setSpeedDelay(s)\n } else if (s == 0 && !this.animate) {\n \tthis.turtleCanvas.setSpeedDelay(s)\n } else {\n// this.animate = false;\n// this.turtleCanvas.cancelAnimation();\n\t\t\tthis.addDrawingEvent([\"SC\", s, t])\n\t\t\tthis.addDrawingEvent([\"NO\"])\n }\n if (t) {\n this.turtleCanvas.setSegmentLength(t);\n // set the number of units to divide a segment into\n } else {\n this.turtleCanvas.setSegmentLength(10);\n }\n }\n\n Turtle.prototype.tracer = function(t, d) {\n this.turtleCanvas.setCounter(t);\n\t\tif (t == 0) {\n\t\t\tthis.animate=false;\n\t\t\tthis.turtleCanvas.cancelAnimation();\n\t\t}\n\t\tif (d !== undefined)\n\t\t\tthis.turtleCanvas.setDelay(d);\n }\n\n Turtle.prototype.getRenderCounter = function() {\n return this.turtleCanvas.getCounter();\n }\n\n Turtle.prototype.turn = function (phi) {\n with (this) {\n var alpha = phi * Degree2Rad;\n var left = normal.cross(heading);\n var newheading = heading.rotateNormal(left, normal, alpha);\n heading = newheading;\n\n if (animate) {\n addDrawingEvent([\"TT\",heading]);\n }\n }\n }\n\n Turtle.prototype.right = Turtle.prototype.turn;\n\n Turtle.prototype.left = function(phi) {\n this.turn(-phi);\n }\n\n Turtle.prototype.get_heading = function () {\n if (TurtleGraphics.defaults.degrees)\n return this.heading.toAngle()\n else\n return this.heading\n }\n\n Turtle.prototype.get_position = function () {\n return this.position;\n }\n\n Turtle.prototype.getx = function () {\n return this.position[0];\n }\n\n Turtle.prototype.gety = function () {\n return this.position[1];\n }\n\n Turtle.prototype.set_heading = function(newhead) {\n if ((typeof(newhead)).toLowerCase() === 'number') {\n this.heading = Vector.angle2vec(newhead);\n } else {\n this.heading = newhead;\n }\n }\n\n Turtle.prototype.towards = function(to, y) {\n // set heading vector to point towards another point.\n if ((typeof(to)).toLowerCase() === 'number')\n to = new Vector(to, y, 0);\n else if (! (to instanceof Vector)) {\n to = new Vector(to);\n }\n var res = to.sub(this.position);\n res = res.normalize();\n if (TurtleGraphics.defaults.degrees)\n return res.toAngle();\n else\n return res;\n }\n\n Turtle.prototype.distance = function(to, y) {\n if ((typeof(to)).toLowerCase() === 'number')\n to = new Vector(to, y, 0);\n return this.position.sub(new Vector(to)).len();\n }\n\n Turtle.prototype.dot = function() {\n var size = 2;\n if (arguments.length >= 1) size = arguments[0];\n size = size * this.turtleCanvas.lineScale;\n with (this) {\n with (context) {\n var color = penStyle;\n var nc = arguments[1] || color;\n if (! animate) {\n fillStyle = nc;\n fillRect(position[0] - size / 2, position[1] - size / 2, size, size);\n fillStyle = color;\n } else {\n addDrawingEvent([\"DT\", size, nc, position[0], position[1]]);\n }\n }\n }\n\n }\n\n Turtle.prototype.circle = function(radius, extent) {\n if (extent === undefined) {\n extent = 360\n }\n\t\tif (this.animate) {\n\t\t\tvar arcLen = Math.abs(radius * Math.PI * 2.0 * extent / 360);\n\t\t\tvar segLen = this.turtleCanvas.getSegmentLength();\n\t\t\tif (arcLen <= segLen)\n\t\t\t\tthis.arc(radius,extent);\n\t\t\telse {\n\t\t\t\t//\tBreak the arc into segments for animation\n\t\t\t\tvar extentPart = (segLen / arcLen) * extent;\n\t\t\t\tvar extentLeft = extent;\n\t\t\t\twhile (Math.abs(extentLeft) > Math.abs(extentPart)) {\n\t\t\t\t\tthis.arc(radius, extentPart);\n\t\t\t\t\textentLeft = extentLeft - extentPart;\n\t\t\t\t}\n\t\t\t\tif (Math.abs(extentLeft) > 0.01)\n\t\t\t\t\tthis.arc(radius, extentLeft);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.arc(radius,extent);\n\t\t}\n\t}\n\t\n Turtle.prototype.arc = function(radius, extent) {\n\t\t//\tFigure out where the turtle is and which way it's facing\n\t\tvar turtleHeading = this.get_heading()\n\t\tvar tx = this.position[0]\n\t\tvar ty = this.position[1]\n\n\t\t//\tFigure out the circle center\n\t\tvar cx = tx + (radius * Math.cos((turtleHeading + 90) * Degree2Rad));\n\t\tvar cy = ty + (radius * Math.sin((turtleHeading + 90) * Degree2Rad));\n\n\t\t//\tCanvas arc angles go CLOCKWISE, not COUNTERCLOCKWISE like Turtle\n\n\t\t//\tFigure out our arc angles\n\t\tvar startAngleDeg;\n\t\tif (radius >= 0)\n\t\t\tstartAngleDeg = turtleHeading - 90;\n\t\telse\n\t\t\tstartAngleDeg = turtleHeading + 90;\n\n\t\tvar endAngleDeg;\n if (extent) {\n\t\t\tif (radius >= 0)\n\t endAngleDeg = startAngleDeg + extent;\n\t\t\telse\n\t endAngleDeg = startAngleDeg - extent;\n } else {\n\t\t\tif (radius >= 0)\n\t endAngleDeg = startAngleDeg + 360;\n\t\t\telse\n\t\t\t\tendAngleDeg = startAngleDeg - 360;\n\t\t}\n\n\t\t//\tCanvas angles are opposite\n\t\tstartAngleDeg = 360 - startAngleDeg\n\t\tendAngleDeg = 360 - endAngleDeg\n\n\t\t//\tBecuase the y axis has been flipped in HTML5 Canvas with a tanslation, we need to adjust the angles\n\t\tstartAngleDeg = -startAngleDeg\n\t\tendAngleDeg = -endAngleDeg\n\n\t\t//\tConvert to radians\n\t\tvar startAngle = startAngleDeg * Degree2Rad;\n\t\tvar endAngle = endAngleDeg * Degree2Rad;\n\n\n\t\t//\tDo the drawing\n if (! this.animate) {\n\t\t\tif (!this.filling)\n\t\t\t\tthis.context.beginPath();\n this.context.arc(cx, cy, Math.abs(radius), startAngle, endAngle, (radius * extent <= 0));\n this.context.stroke();\n\t\t\tif (!this.filling)\n\t\t\t\tthis.context.closePath();\n } else {\n this.addDrawingEvent([\"CI\", cx, cy, Math.abs(radius), startAngle, endAngle, (radius * extent <= 0)]);\n }\n\n\t\t//\tMove the turtle only if we have to\n\t\tif (extent && (extent % 360) != 0) {\n\t\t\tvar turtleArc;\n\t\t\tif (radius >= 0)\n\t\t\t\tturtleArc = extent;\n\t\t\telse \n\t\t\t\tturtleArc = -extent;\n\t\t\tvar newTurtleHeading = (turtleHeading + turtleArc) % 360;\n\t\t\tif (newTurtleHeading < 0)\n\t\t\t\tnewTurtleHeading = newTurtleHeading + 360;\n\n\t\t\tvar nx = cx + (radius * Math.cos((newTurtleHeading - 90) * Degree2Rad));\n\t\t\tvar ny = cy + (radius * Math.sin((newTurtleHeading - 90) * Degree2Rad));\t//\ty coord is inverted in turtle\n\n\t\t\t//\tMove it internally\n\t\t\tthis.set_heading(newTurtleHeading);\n\t\t\tthis.teleport_to(nx,ny);\n\n\t\t\t//\tIf we're animating the turtle, move it on the screen\n\t\t\tif (this.animate) {\n\t\t\t\tthis.addDrawingEvent([\"TT\", this.heading]);\n\t\t\t}\n\t\t}\n\n }\n\n Turtle.prototype.write = function(theText, move, align, font) {\n if (! this.animate) {\n if (font)\n this.context.font = font.v;\n this.context.scale(1, -1);\n this.context.fillText(theText, this.position[0], -this.position[1]);\n this.context.scale(1, -1);\n } else {\n var fontspec;\n if (font)\n fontspec = font.v\n this.addDrawingEvent([\"WT\", theText, fontspec, this.position[0], this.position[1]]);\n }\n }\n\n Turtle.prototype.setworldcoordinates = function(llx, lly, urx, ury) {\n this.turtleCanvas.setworldcoordinates(llx, lly, urx, ury);\n }\n\n//\n// Pen and Style functions\n//\n Turtle.prototype.pen_down = function () {\n this.pen = true;\n }\n\n Turtle.prototype.down = Turtle.prototype.pen_down;\n\n Turtle.prototype.pen_up = function () {\n this.pen = false;\n }\n\n Turtle.prototype.up = Turtle.prototype.pen_up;\n\n Turtle.prototype.get_pen = function () {\n return this.pen;\n }\n\n Turtle.prototype.set_pen_width = function (w) {\n if (this.animate)\n this.addDrawingEvent([\"PW\", w * this.turtleCanvas.lineScale]);\n else\n this.penWidth = w;\n }\n\n Turtle.prototype.get_pen_width = function() {\n return this.penWidth * this.turtleCanvas.lineScale;\n }\n\n Turtle.prototype.set_pen_color = function (c, g, b) {\n if (typeof(c) == \"string\") {\n this.penStyle = c;\n } else {\n \tvar rs\n \tvar gs\n \tvar bs\n \tif (typeof( c) == \"object\" && c.length == 3) {\n\t\t\t\tvar c0 = Sk.builtin.asnum$(c[0]);\n\t\t\t\tvar c1 = Sk.builtin.asnum$(c[1]);\n\t\t\t\tvar c2 = Sk.builtin.asnum$(c[2]);\n \t\trs = c0.toString(16)\n \t\tgs = c1.toString(16)\n \t\tbs = c2.toString(16)\n \t} else {\n \trs = c.toString(16);\n \tgs = g.toString(16);\n \tbs = b.toString(16);\n \t}\n while (rs.length < 2) rs = \"0\" + rs;\n while (gs.length < 2) gs = \"0\" + gs;\n while (bs.length < 2) bs = \"0\" + bs;\n c = \"#\" + rs + gs + bs;\n this.penStyle = c;\n }\n\n this.context.strokeStyle = c;\n if (this.animate)\n this.addDrawingEvent([\"TC\", c]);\n }\n\n Turtle.prototype.set_fill_color = function (c, g, b) {\n if (typeof(c) == \"string\") {\n this.fillStyle = c;\n } else {\n \tvar rs\n \tvar gs\n \tvar bs\n \tif (typeof( c) == \"object\" && c.length == 3) {\n\t\t\t\tvar c0 = Sk.builtin.asnum$(c[0]);\n\t\t\t\tvar c1 = Sk.builtin.asnum$(c[1]);\n\t\t\t\tvar c2 = Sk.builtin.asnum$(c[2]);\n \t\trs = c0.toString(16)\n \t\tgs = c1.toString(16)\n \t\tbs = c2.toString(16)\n \t} else {\n \trs = c.toString(16);\n \tgs = g.toString(16);\n \tbs = b.toString(16);\n \t}\n while (rs.length < 2) rs = \"0\" + rs;\n while (gs.length < 2) gs = \"0\" + gs;\n while (bs.length < 2) bs = \"0\" + bs;\n c = \"#\" + rs + gs + bs;\n this.fillStyle = c;\n }\n\n this.context.fillStyle = c;\n if (this.animate)\n this.addDrawingEvent([\"FC\", c]);\n }\n\n Turtle.prototype.begin_fill = function () {\n if (! this.animate) {\n this.filling = true;\n this.context.beginPath();\n this.context.moveTo(this.position[0], this.position[1]);\n } else\n this.addDrawingEvent([\"BF\", this.position[0], this.position[1]]);\n\n }\n\n Turtle.prototype.end_fill = function () {\n if (! this.animate) {\n this.context.stroke();\n this.context.fill();\n this.context.closePath();\n this.filling = false;\n } else\n this.addDrawingEvent([\"EF\", this.position[0], this.position[1], this.fillStyle]);\n }\n\n\n Turtle.prototype.showturtle = function() {\n if (this.animate) {\n this.addDrawingEvent([\"SH\"]);\n }\n this.visible = true;\n }\n\n Turtle.prototype.hideturtle = function() {\n if (this.animate) {\n this.addDrawingEvent([\"HT\"]);\n }\n this.visible = false;\n }\n\n Turtle.prototype.isvisible = function() {\n return this.visible;\n }\n\n // \n // Appearance\n //\n\n Turtle.prototype.shape = function(s) {\n if (this.shapeStore[s])\n this.currentShape = s;\n else {\n }\n }\n\n Turtle.prototype.drawturtle = function(heading, position) {\n var rtPoints = [];\n var plist = this.shapeStore[this.currentShape];\n var head;\n if (! (heading === undefined))\n head = heading - 90.0;\n else\n head = this.heading.toAngle() - 90.0;\n if (! position)\n position = this.position\n for (p in plist) {\n rtPoints.push(plist[p].scale(this.turtleCanvas.xptscale,this.turtleCanvas.yptscale).rotate(head).add(position));\n }\n this.context.beginPath();\n this.context.moveTo(rtPoints[0][0], rtPoints[0][1]);\n for (var i = 1; i < rtPoints.length; i++) {\n this.context.lineTo(rtPoints[i][0], rtPoints[i][1]);\n }\n this.context.closePath();\n this.context.stroke();\n if (this.fillStyle) {\n this.context.fill();\n }\n }\n\n Turtle.prototype.stamp = function() {\n // either call drawTurtle or just add a DT with current position and heading to the drawingEvents list.\n if (this.animate) {\n this.addDrawingEvent([\"ST\",this.position[0],this.position[1],this.heading.toAngle()]);\n } else\n this.drawturtle();\n }\n \n Turtle.prototype.clear = function () {\n \tif (this.animate) {\n \t\tthis.addDrawingEvent([\"CL\"])\n \t} else {\n \t\tclear_canvas(this.canvasID);\n \t}\n }\n\n function clear_canvas(canId) {\n with (document.getElementById(canId).getContext('2d')) {\n if (arguments.length >= 2) {\n//\t\tfillStyle = arguments[1];\n//\t\tfillRect(0, 0, canvas.width, canvas.height);\n }\n clearRect(-canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);\n }\n }\n\n\n // Create a 3d Vector class for manipulating turtle heading, and position.\n\n function Vector(x, y, z) {\n if ((typeof(x)).toLowerCase() === 'number') {\n Array.prototype.push.call(this, x);\n Array.prototype.push.call(this, y);\n Array.prototype.push.call(this, z);\n }\n else {\n for (var i in x) {\n Array.prototype.push.call(this, x[i]);\n }\n }\n }\n\n\n // Create a vector object given a direction as an angle.\n Vector.angle2vec = function(phi) {\n var res = new Vector([0.0,0.0,0.0]);\n phi = phi * Degree2Rad;\n res[0] = Math.cos(phi);\n res[1] = Math.sin(phi);\n return res.normalize();\n }\n\n // This trick allows you to access a Vector object like an array\n // myVec[0] == x\n // myVec[1] == y\n // myVec[2] == z\n // we really only need the z for the convenience of rotating\n Vector.prototype.addItem = function(item) {\n Array.prototype.push.call(this, item);\n }\n\n Vector.prototype.linear = function(a, b, v) {\n var result = [ ];\n for (var c = 0; c <= 2; ++c) {\n result[c] = a * this[c] + b * v[c];\n }\n return new Vector(result);\n }\n\n Vector.prototype.cross = function(v) {\n // Return cross product of this and v\n var result = [ ];\n for (var c = 0; c <= 2; ++c) {\n result[c] = this[(c + 1) % 3] * v[(c + 2) % 3] - this[(c + 2) % 3] * v[(c + 1) % 3];\n }\n return new Vector(result);\n }\n\n Vector.prototype.rotate = function(angle) {\n // Rotate this counter clockwise by angle.\n var perp = new Vector(-this[1], this[0], 0);\n angle = angle * Degree2Rad;\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n return new Vector(this[0] * c + perp[0] * s, this[1] * c + perp[1] * s, 0);\n }\n\n Vector.prototype.rotateNormal = function(v, w, alpha) {\n // Return rotation of this in direction of v about w over alpha\n // Requires: v, w are vectors; alpha is angle in radians\n // this, v, w are orthonormal\n return this.linear(Math.cos(alpha), Math.sin(alpha), v);\n }\n\n Vector.prototype.normalize = function() {\n var n = this.len();\n var res = this.div(n);\n return res;\n }\n\n Vector.prototype.toAngle = function() {\n // workaround for values getting set to +/i xxx e -16 fooling the +/- checks below\n if (Math.abs(this[1]) < 0.00001) this[1] = 0.0;\n if (Math.abs(this[0]) < 0.00001) this[0] = 0.0;\n var rads = Math.atan(Math.abs(this[1]) / Math.abs(this[0]));\n var deg = rads * Rad2Degree;\n if (this[0] < 0 && this[1] > 0) deg = 180 - deg;\n else if (this[0] < 0 && this[1] <= 0) deg = 180.0 + deg;\n else if (this[0] >= 0 && this[1] < 0) deg = 360 - deg;\n return deg;\n }\n\n // divide all vector components by the same value\n Vector.prototype.div = function(n) {\n res = []\n res[0] = this[0] / n;\n res[1] = this[1] / n;\n res[2] = this[2] / n;\n return new Vector(res);\n }\n\n // subtract one vector from another\n Vector.prototype.sub = function(v) {\n res = new Vector(0, 0, 0);\n res[0] = this[0] - v[0];\n res[1] = this[1] - v[1];\n res[2] = this[2] - v[2];\n return res;\n }\n\n Vector.prototype.add = function(v) {\n res = new Vector(0, 0, 0);\n res[0] = this[0] + v[0];\n res[1] = this[1] + v[1];\n res[2] = this[2] + v[2];\n return res;\n }\n\n Vector.prototype.smul = function(k) { // scalar multiplication\n res = new Vector(0, 0, 0);\n res[0] = this[0] * k;\n res[1] = this[1] * k;\n res[2] = this[2] * k;\n return res;\n }\n\n Vector.prototype.scale = function(xs,ys) {\n res = new Vector(0,0,0);\n res[0] = this[0] * ys;\n res[1] = this[1] * xs;\n res[2] = 1.0;\n return res;\n }\n\n Vector.prototype.len = function() {\n return Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);\n }\n\n\n TurtleGraphics.defaults = { canvasID: 'mycanvas', degrees: true, animate: true }\n TurtleGraphics.turtleList = [];\n TurtleGraphics.Turtle = Turtle;\n TurtleGraphics.TurtleCanvas = TurtleCanvas;\n TurtleGraphics.canvasLib = {}\n TurtleGraphics.clear_canvas = clear_canvas;\n TurtleGraphics.Vector = Vector;\n TurtleGraphics.canvasInit = false;\n TurtleGraphics.eventCount = 0;\n TurtleGraphics.renderClock = 0;\n TurtleGraphics.renderTime = 0; // RNL\n\n})();\n\n\n//\n// Wrapper around the Turtle Module starts here.\n//\n//\nvar $builtinmodule = function(name) {\n var mod = {};\n // First we create an object, this will end up being the class\n // class\n Sk.tg = TurtleGraphics;\n\n var checkArgs = function(expected, actual, func) {\n if (actual != expected ) {\n throw new Sk.builtin.TypeError(func + \" takes exactly \" + expected +\n \" positional argument (\" + actual + \" given)\")\n }\n }\n\n var turtle = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self) {\n TurtleGraphics.defaults = {canvasID: Sk.canvas, animate: true, degrees: true};\n self.theTurtle = new TurtleGraphics.Turtle();\n });\n\n//\n// Turtle Motion\n//\n //\n // Move and Draw\n //\n $loc.forward = new Sk.builtin.func(function(self, dist) {\n\t\t\tdist = Sk.builtin.asnum$(dist);\n checkArgs(2,arguments.length,\"forward()\");\n self.theTurtle.forward(dist);\n });\n\n $loc.fd = $loc.forward;\n\n $loc.backward = new Sk.builtin.func(function(self, dist) {\n\t\t\tdist = Sk.builtin.asnum$(dist);\n checkArgs(2,arguments.length,\"backward()\");\n self.theTurtle.forward(-dist);\n });\n\n $loc.back = $loc.backward;\n $loc.bk = $loc.backward;\n\n $loc.right = new Sk.builtin.func(function(self, angle) {\n\t\t\tangle = Sk.builtin.asnum$(angle);\n checkArgs(2,arguments.length,\"right()\");\n self.theTurtle.turn(angle);\n });\n\n $loc.rt = $loc.right;\n\n $loc.left = new Sk.builtin.func(function(self, angle) {\n\t\t\tangle = Sk.builtin.asnum$(angle);\n checkArgs(2,arguments.length,\"left()\");\n self.theTurtle.turn(-angle);\n });\n\n $loc.lt = $loc.left;\n\n $loc.goto = new Sk.builtin.func(function(self, nx, ny) {\n\t\t\tnx = Sk.builtin.asnum$(nx);\n\t\t\tny = Sk.builtin.asnum$(ny);\n checkArgs(3,arguments.length,\"goto()\");\n self.theTurtle.goto(nx, ny);\n });\n\n $loc.setposition = new Sk.builtin.func(function(self,nx,ny) {\n\t\t\tnx = Sk.builtin.asnum$(nx);\n\t\t\tny = Sk.builtin.asnum$(ny);\n checkArgs(3,arguments.length,\"setposition()\");\n self.theTurtle.up();\n self.theTurtle.goto(nx,ny);\n self.theTurtle.down();\n });\n $loc.setpos = $loc.setposition;\n\n $loc.setx = new Sk.builtin.func(function(self, nx) {\n\t\t\tnx = Sk.builtin.asnum$(nx);\n checkArgs(2,arguments.length,\"setx()\");\n self.theTurtle.goto(nx, self.theTurtle.GetY());\n });\n\n $loc.sety = new Sk.builtin.func(function(self, ny) {\n\t\t\tny = Sk.builtin.asnum$(ny);\n checkArgs(2,arguments.length,\"sety()\");\n self.theTurtle.goto(self.theTurtle.GetX(), ny);\n });\n\n $loc.setheading = new Sk.builtin.func(function(self, newhead) {\n\t\t\tnewhead = Sk.builtin.asnum$(newhead);\n checkArgs(2,arguments.length,\"setheading()\");\n return self.theTurtle.set_heading(newhead);\n });\n\n $loc.seth = $loc.setheading;\n\n $loc.home = new Sk.builtin.func(function(self) {\n self.theTurtle.go_home();\n });\n\n $loc.dot = new Sk.builtin.func(function(self, /*opt*/ size, color) {\n\t\t\tsize = Sk.builtin.asnum$(size);\n size = size || 1;\n if (color) {\n color = color.v || self.theTurtle.penStyle;\n }\n self.theTurtle.dot(size, color);\n });\n\n $loc.circle = new Sk.builtin.func(function(self, radius, extent) {\n\t\t\tradius = Sk.builtin.asnum$(radius);\n\t\t\textent = Sk.builtin.asnum$(extent);\n self.theTurtle.circle(radius, extent);\n });\n\n $loc.delay = new Sk.builtin.func(function(self, d) {\n\t\t\td = Sk.builtin.asnum$(d);\n return self.theTurtle.delay(d);\n });\n\n $loc.speed = new Sk.builtin.func(function(self, s, t) {\n\t\t\ts = Sk.builtin.asnum$(s);\n\t\t\tt = Sk.builtin.asnum$(t);\n self.theTurtle.speed(s,t);\n });\n\n $loc.tracer = new Sk.builtin.func(function(self, t, d) {\n\t\t\tt = Sk.builtin.asnum$(t);\n\t\t\td = Sk.builtin.asnum$(d);\n self.theTurtle.tracer(t, d);\n });\n\n\t\t$loc.update = new Sk.builtin.func(function(self) {\n\t\t\t//\tDummy function to emulate update... when not animating, we don't save the drawing operations, so this is pointless for us\n\t\t});\n\n // todo: stamp, clearstamp, clearstamps, undo, speed\n\n //\n // Tell Turtle's state\n //\n $loc.heading = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"heading()\");\n return self.theTurtle.get_heading();\n });\n\n $loc.position = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"position()\");\n var res = self.theTurtle.get_position();\n var x = new Sk.builtin.tuple([res[0],res[1]]);\n return x;\n });\n\n $loc.pos = $loc.position;\n\n $loc.xcor = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"xcor()\");\n var res = self.theTurtle.getx();\n return res;\n });\n\n $loc.ycor = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"ycor()\");\n var res = self.theTurtle.gety();\n return res;\n });\n\n $loc.towards = new Sk.builtin.func(function(self, tx, ty) {\n\t\t\ttx = Sk.builtin.asnum$(tx);\n\t\t\tty = Sk.builtin.asnum$(ty);\n if ((typeof(tx)).toLowerCase() === 'number')\n tx = [tx, ty, 0];\n return self.theTurtle.towards(tx);\n });\n\n // tx can be either a number or a vector position.\n // tx can not be a turtle at this time as multiple turtles have not been implemented yet.\n $loc.distance = new Sk.builtin.func(function(self, tx, ty) {\n\t\t\ttx = Sk.builtin.asnum$(tx);\n\t\t\tty = Sk.builtin.asnum$(ty);\n if ((typeof(tx)).toLowerCase() === 'number') {\n tx = [tx, ty, 0];\n } else {\n tx = [tx.theTurtle.getx(), tx.theTurtle.gety(), 0];\n }\n return self.theTurtle.distance(tx);\n });\n\n //\n // Setting and Measurement\n //\n\n // todo: degrees and radians...\n\n//\n// Pen Control\n//\n\n //\n // Drawing State\n //\n\n $loc.up = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"up()\");\n self.theTurtle.pen_up();\n });\n\n $loc.penup = $loc.up;\n $loc.pu = $loc.up;\n\n $loc.down = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"down()\");\n self.theTurtle.pen_down();\n });\n\n $loc.pendown = $loc.down;\n $loc.pd = $loc.down;\n\n $loc.width = new Sk.builtin.func(function(self, w) {\n\t\t\tw = Sk.builtin.asnum$(w);\n checkArgs(2,arguments.length,\"width()\");\n self.theTurtle.set_pen_width(w);\n });\n\n $loc.pensize = $loc.width;\n\n $loc.isdown = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"isdown()\");\n return self.theTurtle.get_pen();\n });\n\n // todo: pen -- return a dictionary full of pen stuff\n\n //\n // Color Control\n //\n\n $loc.fillcolor = new Sk.builtin.func(function(self, color, green, blue) {\n if (color) {\n if (blue) {\n self.theTurtle.set_fill_color(color, green, blue);\n } else {\n color = color.v || self.theTurtle.context.fillStyle;\n self.theTurtle.set_fill_color(color);\n }\n } else\n return self.theTurtle.fillStyle;\n });\n\n $loc.pencolor = new Sk.builtin.func(function(self, color, green, blue) {\n if (color) {\n if (blue) {\n\t\t\t\t\tcolor = Sk.builtin.asnum$(color);\n\t\t\t\t\tgreen = Sk.builtin.asnum$(green);\n\t\t\t\t\tblue = Sk.builtin.asnum$(blue);\n self.theTurtle.set_pen_color(color, green, blue);\n } else {\n color = color.v || self.theTurtle.context.fillStyle;\n self.theTurtle.set_pen_color(color);\n }\n } else\n return self.theTurtle.penStyle;\n });\n\n $loc.color = new Sk.builtin.func(function(self, color, green, blue) {\n if(color) {\n if (blue) {\n self.theTurtle.set_pen_color(color, green, blue);\n self.theTurtle.set_fill_color(color, green, blue);\n } else {\n color = color.v || self.theTurtle.context.fillStyle;\n self.theTurtle.set_pen_color(color);\n self.theTurtle.set_fill_color(color);\n }\n } else \n return [self.theTurtle.penStyle, self.theTurtle.fillStyle]; \n });\n\n //\n // Filling\n //\n\n $loc.begin_fill = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"begin_fill()\");\n self.theTurtle.begin_fill();\n });\n\n $loc.end_fill = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"end_fill()\");\n self.theTurtle.end_fill();\n });\n\n $loc.fill = new Sk.builtin.func(function(self, fillt) {\n\t\t\tif (fillt === undefined)\n\t\t\t\treturn self.theTurtle.filling;\n if (fillt)\n self.theTurtle.begin_fill();\n else\n self.theTurtle.end_fill();\n });\n\n //\n // More drawing control\n //\n\n $loc.reset = new Sk.builtin.func(function(self) {\n self.theTurtle.clean();\n });\n\n $loc.showturtle = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"showturtle()\");\n self.theTurtle.showturtle();\n });\n $loc.st = $loc.showturtle;\n\n $loc.hideturtle = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"hideturtle()\");\n self.theTurtle.hideturtle();\n });\n $loc.ht = $loc.hideturtle;\n\n $loc.isvisible = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"isvisible()\");\n self.theTurtle.isvisible()\n });\n\n $loc.stamp = new Sk.builtin.func(function(self) {\n checkArgs(1,arguments.length,\"stamp()\");\n self.theTurtle.stamp();\n });\n\n $loc.shape = new Sk.builtin.func(function(self, s) {\n checkArgs(2,arguments.length,\"shape()\");\n self.theTurtle.shape(s.v);\n });\n\n\n // todo the move, align, and font parameters should be kwargs...\n $loc.write = new Sk.builtin.func(function(self, mystr, move, align, font) {\n self.theTurtle.write(mystr.v, move, align, font);\n });\n\n // todo clean -- again multiple turtles\n\n $loc.setworldcoordinates = new Sk.builtin.func(function(self, llx, lly, urx, ury) {\n\t\t\tllx = Sk.builtin.asnum$(llx);\n\t\t\tlly = Sk.builtin.asnum$(lly);\n\t\t\turx = Sk.builtin.asnum$(urx);\n\t\t\tury = Sk.builtin.asnum$(ury);\n self.theTurtle.setworldcoordinates(llx, lly, urx, ury);\n });\n\n\t\t//\tAdded by RNL\n\n\t\t$loc.clear = new Sk.builtin.func(function(self) {\n\t\t\tself.theTurtle.clear()\n\t\t});\n\n }\n\n mod.Turtle = Sk.misceval.buildClass(mod, turtle, 'Turtle', []);\n\n var screen = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self) {\n TurtleGraphics.defaults = {canvasID: Sk.canvas, animate: true, degrees: true};\n var currentCanvas = TurtleGraphics.canvasLib[TurtleGraphics.defaults.canvasID];\n if (currentCanvas === undefined) {\n self.theScreen = new TurtleGraphics.TurtleCanvas(TurtleGraphics.defaults);\n } else {\n self.theScreen = currentCanvas;\n }\n });\n\n $loc.bgcolor = new Sk.builtin.func(function(self, c) {\n self.theScreen.bgcolor(c);\n });\n\n $loc.setworldcoordinates = new Sk.builtin.func(function(self, llx,lly,urx,ury) {\n\t\t\tllx = Sk.builtin.asnum$(llx);\n\t\t\tlly = Sk.builtin.asnum$(lly);\n\t\t\turx = Sk.builtin.asnum$(urx);\n\t\t\tury = Sk.builtin.asnum$(ury);\n self.theScreen.setworldcoordinates(llx,lly,urx,ury);\n });\n\n $loc.exitonclick = new Sk.builtin.func(function(self) {\n self.theScreen.exitonclick();\n });\n\n $loc.title = new Sk.builtin.func(function(self,titlestring) {\n // no op....\n });\n\n $loc.window_width = new Sk.builtin.func(function(self) {\n return self.theScreen.window_width();\n });\n\n $loc.window_height = new Sk.builtin.func(function(self) {\n return self.theScreen.window_height();\n });\n\n $loc.turtles = new Sk.builtin.func(function(self) {\n return self.theScreen.turtles();\n });\n\n\t\t$loc.colormode = new Sk.builtin.func(function(self) {\n\t\t\t//\tEmpty function to emulate compatibility\n\t\t});\n \n// $loc.clear = new Sk.builtin.func(function(self) {\n// \t\n// });\n\n var myfunc = function(self, width, height, startx, starty) {\n\t\t\twidth = Sk.builtin.asnum$(width);\n\t\t\theight = Sk.builtin.asnum$(height);\n self.theScreen.setup(width,height);\n }\n // this should allow for named parameters\n myfunc.co_varnames = ['self','width','height','startx','starty'];\n myfunc.$defaults = [null,500,500,0,0];\n $loc.setup = new Sk.builtin.func(myfunc);\n }\n\n mod.Screen = Sk.misceval.buildClass(mod, screen, 'Screen', []);\n\n mod.tracer = new Sk.builtin.func(function(t, d) {\n\t\tt = Sk.builtin.asnum$(t);\n\t\td = Sk.builtin.asnum$(d);\n\t\tfor (var i in Sk.tg.canvasLib)\n\t\t\tSk.tg.canvasLib[i].tracer(t, d);\n });\n\n\tmod.update = new Sk.builtin.func(function(self) {\n\t\t//\tDummy function to emulate update... when not animating, we don't save the drawing operations, so this is pointless for us\n\t});\n\n\n return mod\n}\n", "src/lib/webgl/math.js": "var $builtinmodule = function(name)\n{\n var mod = {};\n\n // todo; should probably put this in a math package\n mod.Mat44 = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self)\n {\n Sk.misceval.callsim($loc.loadIdentity, self);\n self.stack = [];\n });\n\n $loc.push = new Sk.builtin.func(function(self)\n {\n self.stack.push(self.elements.slice(0));\n });\n\n $loc.pop = new Sk.builtin.func(function(self)\n {\n self.elements = self.stack.pop();\n });\n\n $loc.loadIdentity = new Sk.builtin.func(function(self)\n {\n self.elements = [1.0, 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0];\n });\n\n $loc.transform3 = new Sk.builtin.func(function(self, v)\n {\n var e = self.elements;\n return Sk.misceval.callsim(mod.Vec3,\n e[0] * v.x + e[4] * v.y + e[8] * v.z,\n e[1] * v.x + e[5] * v.y + e[9] * v.z,\n e[2] * v.x + e[6] * v.y + e[10] * v.z);\n });\n\n $loc.scale = new Sk.builtin.func(function(self, sx, sy, sz)\n {\n self.elements[0*4+0] *= sx;\n self.elements[0*4+1] *= sx;\n self.elements[0*4+2] *= sx;\n self.elements[0*4+3] *= sx;\n\n self.elements[1*4+0] *= sy;\n self.elements[1*4+1] *= sy;\n self.elements[1*4+2] *= sy;\n self.elements[1*4+3] *= sy;\n\n self.elements[2*4+0] *= sz;\n self.elements[2*4+1] *= sz;\n self.elements[2*4+2] *= sz;\n self.elements[2*4+3] *= sz;\n\n return self;\n });\n\n $loc.translate = new Sk.builtin.func(function(self, tx, ty, tz)\n {\n self.elements[3*4+0] += self.elements[0*4+0] * tx + self.elements[1*4+0] * ty + self.elements[2*4+0] * tz;\n self.elements[3*4+1] += self.elements[0*4+1] * tx + self.elements[1*4+1] * ty + self.elements[2*4+1] * tz;\n self.elements[3*4+2] += self.elements[0*4+2] * tx + self.elements[1*4+2] * ty + self.elements[2*4+2] * tz;\n self.elements[3*4+3] += self.elements[0*4+3] * tx + self.elements[1*4+3] * ty + self.elements[2*4+3] * tz;\n return self;\n });\n\n $loc.rotate = new Sk.builtin.func(function(self, angle, x, y, z)\n {\n var mag = Math.sqrt(x*x + y*y + z*z);\n var sinAngle = Math.sin(angle * Math.PI / 180.0);\n var cosAngle = Math.cos(angle * Math.PI / 180.0);\n\n if (mag > 0)\n {\n var xx, yy, zz, xy, yz, zx, xs, ys, zs;\n var oneMinusCos;\n var rotMat;\n\n x /= mag;\n y /= mag;\n z /= mag;\n\n xx = x * x;\n yy = y * y;\n zz = z * z;\n xy = x * y;\n yz = y * z;\n zx = z * x;\n xs = x * sinAngle;\n ys = y * sinAngle;\n zs = z * sinAngle;\n oneMinusCos = 1.0 - cosAngle;\n\n rotMat = Sk.misceval.callsim(mod.Mat44);\n\n rotMat.elements[0*4+0] = (oneMinusCos * xx) + cosAngle;\n rotMat.elements[0*4+1] = (oneMinusCos * xy) - zs;\n rotMat.elements[0*4+2] = (oneMinusCos * zx) + ys;\n rotMat.elements[0*4+3] = 0.0;\n\n rotMat.elements[1*4+0] = (oneMinusCos * xy) + zs;\n rotMat.elements[1*4+1] = (oneMinusCos * yy) + cosAngle;\n rotMat.elements[1*4+2] = (oneMinusCos * yz) - xs;\n rotMat.elements[1*4+3] = 0.0;\n\n rotMat.elements[2*4+0] = (oneMinusCos * zx) - ys;\n rotMat.elements[2*4+1] = (oneMinusCos * yz) + xs;\n rotMat.elements[2*4+2] = (oneMinusCos * zz) + cosAngle;\n rotMat.elements[2*4+3] = 0.0;\n\n rotMat.elements[3*4+0] = 0.0;\n rotMat.elements[3*4+1] = 0.0;\n rotMat.elements[3*4+2] = 0.0;\n rotMat.elements[3*4+3] = 1.0;\n\n rotMat = rotMat.multiply(self);\n self.elements = rotMat.elements;\n }\n return self;\n });\n\n $loc.multiply = new Sk.builtin.func(function(self, right)\n {\n var tmp = Sk.misceval.callsim(mod.Mat44);\n\n for (var i = 0; i < 4; i++)\n {\n tmp.elements[i*4+0] =\n (self.elements[i*4+0] * right.elements[0*4+0]) +\n (self.elements[i*4+1] * right.elements[1*4+0]) +\n (self.elements[i*4+2] * right.elements[2*4+0]) +\n (self.elements[i*4+3] * right.elements[3*4+0]) ;\n\n tmp.elements[i*4+1] =\n (self.elements[i*4+0] * right.elements[0*4+1]) +\n (self.elements[i*4+1] * right.elements[1*4+1]) +\n (self.elements[i*4+2] * right.elements[2*4+1]) +\n (self.elements[i*4+3] * right.elements[3*4+1]) ;\n\n tmp.elements[i*4+2] =\n (self.elements[i*4+0] * right.elements[0*4+2]) +\n (self.elements[i*4+1] * right.elements[1*4+2]) +\n (self.elements[i*4+2] * right.elements[2*4+2]) +\n (self.elements[i*4+3] * right.elements[3*4+2]) ;\n\n tmp.elements[i*4+3] =\n (self.elements[i*4+0] * right.elements[0*4+3]) +\n (self.elements[i*4+1] * right.elements[1*4+3]) +\n (self.elements[i*4+2] * right.elements[2*4+3]) +\n (self.elements[i*4+3] * right.elements[3*4+3]) ;\n }\n\n self.elements = tmp.elements;\n return self;\n });\n\n /* Following gluLookAt implementation is adapted from\n * the Mesa 3D Graphics library. http://www.mesa3d.org\n */\n // todo; rewrite this with proper vec/mat ops\n $loc.lookAt = new Sk.builtin.func(function(self, eyeX, eyeY, eyeZ,\n centerX, centerY, centerZ,\n upX, upY, upZ)\n {\n /* Z vector */\n var z = [\n eyeX - centerX,\n eyeY - centerY,\n eyeZ - centerZ\n ];\n var mag = Math.sqrt(z[0] * z[0] + z[1] * z[1] + z[2] * z[2]);\n if (mag)\n {\n z[0] /= mag;\n z[1] /= mag;\n z[2] /= mag;\n }\n\n /* Y vector */\n var y = [ upX, upY, upZ ];\n\n /* X vector = Y cross Z */\n var x = [];\n x[0] = y[1] * z[2] - y[2] * z[1];\n x[1] = -y[0] * z[2] + y[2] * z[0];\n x[2] = y[0] * z[1] - y[1] * z[0];\n\n /* Recompute Y = Z cross X */\n y[0] = z[1] * x[2] - z[2] * x[1];\n y[1] = -z[0] * x[2] + z[2] * x[0];\n y[2] = z[0] * x[1] - z[1] * x[0];\n\n /* mpichler, 19950515 */\n /* cross product gives area of parallelogram, which is < 1.0 for\n * non-perpendicular unit-length vectors; so normalize x, y here\n */\n\n mag = Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);\n if (mag) {\n x[0] /= mag;\n x[1] /= mag;\n x[2] /= mag;\n }\n\n mag = Math.sqrt(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]);\n if (mag) {\n y[0] /= mag;\n y[1] /= mag;\n y[2] /= mag;\n }\n\n var lookAt = Sk.misceval.callsim(mod.Mat44);\n lookAt.elements[0 * 4 + 0] = x[0];\n lookAt.elements[1 * 4 + 0] = x[1];\n lookAt.elements[2 * 4 + 0] = x[2];\n lookAt.elements[3 * 4 + 0] = 0.;\n lookAt.elements[0 * 4 + 1] = y[0];\n lookAt.elements[1 * 4 + 1] = y[1];\n lookAt.elements[2 * 4 + 1] = y[2];\n lookAt.elements[3 * 4 + 1] = 0.;\n lookAt.elements[0 * 4 + 2] = z[0];\n lookAt.elements[1 * 4 + 2] = z[1];\n lookAt.elements[2 * 4 + 2] = z[2];\n lookAt.elements[3 * 4 + 2] = 0.;\n lookAt.elements[0 * 4 + 3] = 0.;\n lookAt.elements[1 * 4 + 3] = 0.;\n lookAt.elements[2 * 4 + 3] = 0.;\n lookAt.elements[3 * 4 + 3] = 1.;\n\n // log(lookAt.elements);\n\n lookAt = lookAt.multiply(self);\n self.elements = lookAt.elements;\n self.translate(-eyeX, -eyeY, -eyeZ);\n\n // log(this.elements);\n\n return self;\n });\n },\n 'Mat44', []);\n\n // todo; should probably put this in a math package\n mod.Mat33 = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self)\n {\n Sk.misceval.callsim($loc.loadIdentity, self);\n });\n\n $loc.loadIdentity = new Sk.builtin.func(function(self)\n {\n self.elements = [1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 1.0];\n });\n },\n 'Mat33', []);\n\n mod.Vec3 = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self, x, y, z)\n {\n self.x = x;\n self.y = y;\n self.z = z;\n });\n $loc.__sub__ = new Sk.builtin.func(function(self, other)\n {\n return Sk.misceval.callsim(mod.Vec3, self.x - other.x, self.y - other.y, self.z - other.z);\n });\n },\n 'Vec3', []);\n \n mod.cross = new Sk.builtin.func(function(v1, v2)\n {\n goog.asserts.assert(v1 instanceof mod.Vec3 && v2 instanceof mod.Vec3);\n return Sk.misceval.callsim(mod.Vec3,\n v1.y * v2.z - v1.z * v2.y,\n v1.z * v2.x - v1.x * v2.z,\n v1.x * v2.y - v1.y * v2.x);\n });\n\n return mod;\n};\n", "src/builtin/unittest.py": "#!/usr/bin/env python\n'''\nPython unit testing framework, based on Erich Gamma's JUnit and Kent Beck's\nSmalltalk testing framework.\n\nThis module contains the core framework classes that form the basis of\nspecific test cases and suites (TestCase, TestSuite etc.), and also a\ntext-based utility class for running the tests and reporting the results\n (TextTestRunner).\n\nSimple usage:\n\n import unittest\n\n class IntegerArithmenticTestCase(unittest.TestCase):\n def testAdd(self): ## test method names begin 'test*'\n self.assertEquals((1 + 2), 3)\n self.assertEquals(0 + 1, 1)\n def testMultiply(self):\n self.assertEquals((0 * 10), 0)\n self.assertEquals((5 * 8), 40)\n\n if __name__ == '__main__':\n unittest.main()\n\nFurther information is available in the bundled documentation, and from\n\n http://docs.python.org/lib/module-unittest.html\n\nCopyright (c) 1999-2003 Steve Purcell\nThis module is free software, and you may redistribute it and/or modify\nit under the same terms as Python itself, so long as this copyright message\nand disclaimer are retained in their original form.\n\nIN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\nSPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF\nTHIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\nDAMAGE.\n\nTHE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS,\nAND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,\nSUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n'''\n\n__author__ = \"Steve Purcell\"\n__email__ = \"stephen_purcell at yahoo dot com\"\n__version__ = \"#Revision: 1.63 $\"[11:-2]\n\nimport time\nimport sys\nimport traceback\nimport os\nimport types\n\n##############################################################################\n# Exported classes and functions\n##############################################################################\n__all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',\n 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']\n\n# Expose obsolete functions for backwards compatibility\n__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])\n\n\n##############################################################################\n# Backward compatibility\n##############################################################################\nif sys.version_info[:2] < (2, 2):\n def isinstance(obj, clsinfo):\n import __builtin__\n if type(clsinfo) in (tuple, list):\n for cls in clsinfo:\n if cls is type: cls = types.ClassType\n if __builtin__.isinstance(obj, cls):\n return 1\n return 0\n else: return __builtin__.isinstance(obj, clsinfo)\n\ndef _CmpToKey(mycmp):\n 'Convert a cmp= function into a key= function'\n class K(object):\n def __init__(self, obj):\n self.obj = obj\n def __lt__(self, other):\n return mycmp(self.obj, other.obj) == -1\n return K\n\n##############################################################################\n# Test framework core\n##############################################################################\n\n# All classes defined herein are 'new-style' classes, allowing use of 'super()'\n__metaclass__ = type\n\ndef _strclass(cls):\n return \"%s.%s\" % (cls.__module__, cls.__name__)\n\n__unittest = 1\n\nclass TestResult:\n \"\"\"Holder for test result information.\n\n Test results are automatically managed by the TestCase and TestSuite\n classes, and do not need to be explicitly manipulated by writers of tests.\n\n Each instance holds the total number of tests run, and collections of\n failures and errors that occurred among those test runs. The collections\n contain tuples of (testcase, exceptioninfo), where exceptioninfo is the\n formatted traceback of the error that occurred.\n \"\"\"\n def __init__(self):\n self.failures = []\n self.errors = []\n self.testsRun = 0\n self.shouldStop = False\n\n def startTest(self, test):\n \"Called when the given test is about to be run\"\n self.testsRun = self.testsRun + 1\n\n def stopTest(self, test):\n \"Called when the given test has been run\"\n pass\n\n def addError(self, test, err):\n \"\"\"Called when an error has occurred. 'err' is a tuple of values as\n returned by sys.exc_info().\n \"\"\"\n self.errors.append((test, self._exc_info_to_string(err, test)))\n\n def addFailure(self, test, err):\n \"\"\"Called when an error has occurred. 'err' is a tuple of values as\n returned by sys.exc_info().\"\"\"\n self.failures.append((test, self._exc_info_to_string(err, test)))\n\n def addSuccess(self, test):\n \"Called when a test has completed successfully\"\n pass\n\n def wasSuccessful(self):\n \"Tells whether or not this result was a success\"\n return len(self.failures) == len(self.errors) == 0\n\n def stop(self):\n \"Indicates that the tests should be aborted\"\n self.shouldStop = True\n\n def _exc_info_to_string(self, err, test):\n \"\"\"Converts a sys.exc_info()-style tuple of values into a string.\"\"\"\n exctype, value, tb = err\n # Skip test runner traceback levels\n while tb and self._is_relevant_tb_level(tb):\n tb = tb.tb_next\n if exctype is test.failureException:\n # Skip assert*() traceback levels\n length = self._count_relevant_tb_levels(tb)\n return ''.join(traceback.format_exception(exctype, value, tb, length))\n return ''.join(traceback.format_exception(exctype, value, tb))\n\n def _is_relevant_tb_level(self, tb):\n return '__unittest' in tb.tb_frame.f_globals\n\n def _count_relevant_tb_levels(self, tb):\n length = 0\n while tb and not self._is_relevant_tb_level(tb):\n length += 1\n tb = tb.tb_next\n return length\n\n def __repr__(self):\n return \"<%s run=%i errors=%i failures=%i>\" % \\\n (_strclass(self.__class__), self.testsRun, len(self.errors),\n len(self.failures))\n\nclass TestCase:\n \"\"\"A class whose instances are single test cases.\n\n By default, the test code itself should be placed in a method named\n 'runTest'.\n\n If the fixture may be used for many test cases, create as\n many test methods as are needed. When instantiating such a TestCase\n subclass, specify in the constructor arguments the name of the test method\n that the instance is to execute.\n\n Test authors should subclass TestCase for their own tests. Construction\n and deconstruction of the test's environment ('fixture') can be\n implemented by overriding the 'setUp' and 'tearDown' methods respectively.\n\n If it is necessary to override the __init__ method, the base class\n __init__ method must always be called. It is important that subclasses\n should not change the signature of their __init__ method, since instances\n of the classes are instantiated automatically by parts of the framework\n in order to be run.\n \"\"\"\n\n # This attribute determines which exception will be raised when\n # the instance's assertion methods fail; test methods raising this\n # exception will be deemed to have 'failed' rather than 'errored'\n\n failureException = AssertionError\n\n def __init__(self, methodName='runTest'):\n \"\"\"Create an instance of the class that will use the named test\n method when executed. Raises a ValueError if the instance does\n not have a method with the specified name.\n \"\"\"\n try:\n self._testMethodName = methodName\n testMethod = getattr(self, methodName)\n self._testMethodDoc = testMethod.__doc__\n except AttributeError:\n raise ValueError, \"no such test method in %s: %s\" % \\\n (self.__class__, methodName)\n\n def setUp(self):\n \"Hook method for setting up the test fixture before exercising it.\"\n pass\n\n def tearDown(self):\n \"Hook method for deconstructing the test fixture after testing it.\"\n pass\n\n def countTestCases(self):\n return 1\n\n def defaultTestResult(self):\n return TestResult()\n\n def shortDescription(self):\n \"\"\"Returns a one-line description of the test, or None if no\n description has been provided.\n\n The default implementation of this method returns the first line of\n the specified test method's docstring.\n \"\"\"\n doc = self._testMethodDoc\n return doc and doc.split(\"\\n\")[0].strip() or None\n\n def id(self):\n return \"%s.%s\" % (_strclass(self.__class__), self._testMethodName)\n\n def __eq__(self, other):\n if type(self) is not type(other):\n return False\n\n return self._testMethodName == other._testMethodName\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash((type(self), self._testMethodName))\n\n def __str__(self):\n return \"%s (%s)\" % (self._testMethodName, _strclass(self.__class__))\n\n def __repr__(self):\n return \"<%s testMethod=%s>\" % \\\n (_strclass(self.__class__), self._testMethodName)\n\n def run(self, result=None):\n if result is None: result = self.defaultTestResult()\n result.startTest(self)\n testMethod = getattr(self, self._testMethodName)\n try:\n try:\n self.setUp()\n except KeyboardInterrupt:\n raise\n except:\n result.addError(self, self._exc_info())\n return\n\n ok = False\n try:\n testMethod()\n ok = True\n except self.failureException:\n result.addFailure(self, self._exc_info())\n except KeyboardInterrupt:\n raise\n except:\n result.addError(self, self._exc_info())\n\n try:\n self.tearDown()\n except KeyboardInterrupt:\n raise\n except:\n result.addError(self, self._exc_info())\n ok = False\n if ok: result.addSuccess(self)\n finally:\n result.stopTest(self)\n\n def __call__(self, *args, **kwds):\n return self.run(*args, **kwds)\n\n def debug(self):\n \"\"\"Run the test without collecting errors in a TestResult\"\"\"\n self.setUp()\n getattr(self, self._testMethodName)()\n self.tearDown()\n\n def _exc_info(self):\n \"\"\"Return a version of sys.exc_info() with the traceback frame\n minimised; usually the top level of the traceback frame is not\n needed.\n \"\"\"\n return sys.exc_info()\n\n def fail(self, msg=None):\n \"\"\"Fail immediately, with the given message.\"\"\"\n raise self.failureException, msg\n\n def failIf(self, expr, msg=None):\n \"Fail the test if the expression is true.\"\n if expr: raise self.failureException, msg\n\n def failUnless(self, expr, msg=None):\n \"\"\"Fail the test unless the expression is true.\"\"\"\n if not expr: raise self.failureException, msg\n\n def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):\n \"\"\"Fail unless an exception of class excClass is thrown\n by callableObj when invoked with arguments args and keyword\n arguments kwargs. If a different type of exception is\n thrown, it will not be caught, and the test case will be\n deemed to have suffered an error, exactly as for an\n unexpected exception.\n \"\"\"\n try:\n callableObj(*args, **kwargs)\n except excClass:\n return\n else:\n if hasattr(excClass,'__name__'): excName = excClass.__name__\n else: excName = str(excClass)\n raise self.failureException, \"%s not raised\" % excName\n\n def failUnlessEqual(self, first, second, msg=None):\n \"\"\"Fail if the two objects are unequal as determined by the '=='\n operator.\n \"\"\"\n if not first == second:\n raise self.failureException, \\\n (msg or '%r != %r' % (first, second))\n\n def failIfEqual(self, first, second, msg=None):\n \"\"\"Fail if the two objects are equal as determined by the '=='\n operator.\n \"\"\"\n if first == second:\n raise self.failureException, \\\n (msg or '%r == %r' % (first, second))\n\n def failUnlessAlmostEqual(self, first, second, places=7, msg=None):\n \"\"\"Fail if the two objects are unequal as determined by their\n difference rounded to the given number of decimal places\n (default 7) and comparing to zero.\n\n Note that decimal places (from zero) are usually not the same\n as significant digits (measured from the most signficant digit).\n \"\"\"\n if round(abs(second-first), places) != 0:\n raise self.failureException, \\\n (msg or '%r != %r within %r places' % (first, second, places))\n\n def failIfAlmostEqual(self, first, second, places=7, msg=None):\n \"\"\"Fail if the two objects are equal as determined by their\n difference rounded to the given number of decimal places\n (default 7) and comparing to zero.\n\n Note that decimal places (from zero) are usually not the same\n as significant digits (measured from the most signficant digit).\n \"\"\"\n if round(abs(second-first), places) == 0:\n raise self.failureException, \\\n (msg or '%r == %r within %r places' % (first, second, places))\n\n # Synonyms for assertion methods\n\n assertEqual = assertEquals = failUnlessEqual\n\n assertNotEqual = assertNotEquals = failIfEqual\n\n assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual\n\n assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual\n\n assertRaises = failUnlessRaises\n\n assert_ = assertTrue = failUnless\n\n assertFalse = failIf\n\n\n\nclass TestSuite:\n \"\"\"A test suite is a composite test consisting of a number of TestCases.\n\n For use, create an instance of TestSuite, then add test case instances.\n When all tests have been added, the suite can be passed to a test\n runner, such as TextTestRunner. It will run the individual test cases\n in the order in which they were added, aggregating the results. When\n subclassing, do not forget to call the base class constructor.\n \"\"\"\n def __init__(self, tests=()):\n self._tests = []\n self.addTests(tests)\n\n def __repr__(self):\n return \"<%s tests=%s>\" % (_strclass(self.__class__), self._tests)\n\n __str__ = __repr__\n\n def __eq__(self, other):\n if type(self) is not type(other):\n return False\n return self._tests == other._tests\n\n def __ne__(self, other):\n return not self == other\n\n # Can't guarantee hash invariant, so flag as unhashable\n __hash__ = None\n\n def __iter__(self):\n return iter(self._tests)\n\n def countTestCases(self):\n cases = 0\n for test in self._tests:\n cases += test.countTestCases()\n return cases\n\n def addTest(self, test):\n # sanity checks\n if not hasattr(test, '__call__'):\n raise TypeError(\"the test to add must be callable\")\n if (isinstance(test, (type, types.ClassType)) and\n issubclass(test, (TestCase, TestSuite))):\n raise TypeError(\"TestCases and TestSuites must be instantiated \"\n \"before passing them to addTest()\")\n self._tests.append(test)\n\n def addTests(self, tests):\n if isinstance(tests, basestring):\n raise TypeError(\"tests must be an iterable of tests, not a string\")\n for test in tests:\n self.addTest(test)\n\n def run(self, result):\n for test in self._tests:\n if result.shouldStop:\n break\n test(result)\n return result\n\n def __call__(self, *args, **kwds):\n return self.run(*args, **kwds)\n\n def debug(self):\n \"\"\"Run the tests without collecting errors in a TestResult\"\"\"\n for test in self._tests: test.debug()\n\n\nclass FunctionTestCase(TestCase):\n \"\"\"A test case that wraps a test function.\n\n This is useful for slipping pre-existing test functions into the\n unittest framework. Optionally, set-up and tidy-up functions can be\n supplied. As with TestCase, the tidy-up ('tearDown') function will\n always be called if the set-up ('setUp') function ran successfully.\n \"\"\"\n\n def __init__(self, testFunc, setUp=None, tearDown=None,\n description=None):\n TestCase.__init__(self)\n self.__setUpFunc = setUp\n self.__tearDownFunc = tearDown\n self.__testFunc = testFunc\n self.__description = description\n\n def setUp(self):\n if self.__setUpFunc is not None:\n self.__setUpFunc()\n\n def tearDown(self):\n if self.__tearDownFunc is not None:\n self.__tearDownFunc()\n\n def runTest(self):\n self.__testFunc()\n\n def id(self):\n return self.__testFunc.__name__\n\n def __eq__(self, other):\n if type(self) is not type(other):\n return False\n\n return self.__setUpFunc == other.__setUpFunc and \\\n self.__tearDownFunc == other.__tearDownFunc and \\\n self.__testFunc == other.__testFunc and \\\n self.__description == other.__description\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash((type(self), self.__setUpFunc, self.__tearDownFunc,\n self.__testFunc, self.__description))\n\n def __str__(self):\n return \"%s (%s)\" % (_strclass(self.__class__), self.__testFunc.__name__)\n\n def __repr__(self):\n return \"<%s testFunc=%s>\" % (_strclass(self.__class__), self.__testFunc)\n\n def shortDescription(self):\n if self.__description is not None: return self.__description\n doc = self.__testFunc.__doc__\n return doc and doc.split(\"\\n\")[0].strip() or None\n\n\n\n##############################################################################\n# Locating and loading tests\n##############################################################################\n\nclass TestLoader:\n \"\"\"This class is responsible for loading tests according to various\n criteria and returning them wrapped in a TestSuite\n \"\"\"\n testMethodPrefix = 'test'\n sortTestMethodsUsing = cmp\n suiteClass = TestSuite\n\n def loadTestsFromTestCase(self, testCaseClass):\n \"\"\"Return a suite of all tests cases contained in testCaseClass\"\"\"\n if issubclass(testCaseClass, TestSuite):\n raise TypeError(\"Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?\")\n testCaseNames = self.getTestCaseNames(testCaseClass)\n if not testCaseNames and hasattr(testCaseClass, 'runTest'):\n testCaseNames = ['runTest']\n return self.suiteClass(map(testCaseClass, testCaseNames))\n\n def loadTestsFromModule(self, module):\n \"\"\"Return a suite of all tests cases contained in the given module\"\"\"\n tests = []\n for name in dir(module):\n obj = getattr(module, name)\n if (isinstance(obj, (type, types.ClassType)) and\n issubclass(obj, TestCase)):\n tests.append(self.loadTestsFromTestCase(obj))\n return self.suiteClass(tests)\n\n def loadTestsFromName(self, name, module=None):\n \"\"\"Return a suite of all tests cases given a string specifier.\n\n The name may resolve either to a module, a test case class, a\n test method within a test case class, or a callable object which\n returns a TestCase or TestSuite instance.\n\n The method optionally resolves the names relative to a given module.\n \"\"\"\n parts = name.split('.')\n if module is None:\n parts_copy = parts[:]\n while parts_copy:\n try:\n module = __import__('.'.join(parts_copy))\n break\n except ImportError:\n del parts_copy[-1]\n if not parts_copy: raise\n parts = parts[1:]\n obj = module\n for part in parts:\n parent, obj = obj, getattr(obj, part)\n\n if type(obj) == types.ModuleType:\n return self.loadTestsFromModule(obj)\n elif (isinstance(obj, (type, types.ClassType)) and\n issubclass(obj, TestCase)):\n return self.loadTestsFromTestCase(obj)\n elif (type(obj) == types.UnboundMethodType and\n isinstance(parent, (type, types.ClassType)) and\n issubclass(parent, TestCase)):\n return TestSuite([parent(obj.__name__)])\n elif isinstance(obj, TestSuite):\n return obj\n elif hasattr(obj, '__call__'):\n test = obj()\n if isinstance(test, TestSuite):\n return test\n elif isinstance(test, TestCase):\n return TestSuite([test])\n else:\n raise TypeError(\"calling %s returned %s, not a test\" %\n (obj, test))\n else:\n raise TypeError(\"don't know how to make test from: %s\" % obj)\n\n def loadTestsFromNames(self, names, module=None):\n \"\"\"Return a suite of all tests cases found using the given sequence\n of string specifiers. See 'loadTestsFromName()'.\n \"\"\"\n suites = [self.loadTestsFromName(name, module) for name in names]\n return self.suiteClass(suites)\n\n def getTestCaseNames(self, testCaseClass):\n \"\"\"Return a sorted sequence of method names found within testCaseClass\n \"\"\"\n def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):\n return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')\n testFnNames = filter(isTestMethod, dir(testCaseClass))\n if self.sortTestMethodsUsing:\n testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))\n return testFnNames\n\n\n\ndefaultTestLoader = TestLoader()\n\n\n##############################################################################\n# Patches for old functions: these functions should be considered obsolete\n##############################################################################\n\ndef _makeLoader(prefix, sortUsing, suiteClass=None):\n loader = TestLoader()\n loader.sortTestMethodsUsing = sortUsing\n loader.testMethodPrefix = prefix\n if suiteClass: loader.suiteClass = suiteClass\n return loader\n\ndef getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):\n return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)\n\ndef makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):\n return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)\n\ndef findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):\n return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)\n\n\n##############################################################################\n# Text UI\n##############################################################################\n\nclass _WritelnDecorator:\n \"\"\"Used to decorate file-like objects with a handy 'writeln' method\"\"\"\n def __init__(self,stream):\n self.stream = stream\n\n def __getattr__(self, attr):\n return getattr(self.stream,attr)\n\n def writeln(self, arg=None):\n if arg: self.write(arg)\n self.write('\\n') # text-mode streams translate to \\r\\n if needed\n\n\nclass _TextTestResult(TestResult):\n \"\"\"A test result class that can print formatted text results to a stream.\n\n Used by TextTestRunner.\n \"\"\"\n separator1 = '=' * 70\n separator2 = '-' * 70\n\n def __init__(self, stream, descriptions, verbosity):\n TestResult.__init__(self)\n self.stream = stream\n self.showAll = verbosity > 1\n self.dots = verbosity == 1\n self.descriptions = descriptions\n\n def getDescription(self, test):\n if self.descriptions:\n return test.shortDescription() or str(test)\n else:\n return str(test)\n\n def startTest(self, test):\n TestResult.startTest(self, test)\n if self.showAll:\n self.stream.write(self.getDescription(test))\n self.stream.write(\" ... \")\n self.stream.flush()\n\n def addSuccess(self, test):\n TestResult.addSuccess(self, test)\n if self.showAll:\n self.stream.writeln(\"ok\")\n elif self.dots:\n self.stream.write('.')\n self.stream.flush()\n\n def addError(self, test, err):\n TestResult.addError(self, test, err)\n if self.showAll:\n self.stream.writeln(\"ERROR\")\n elif self.dots:\n self.stream.write('E')\n self.stream.flush()\n\n def addFailure(self, test, err):\n TestResult.addFailure(self, test, err)\n if self.showAll:\n self.stream.writeln(\"FAIL\")\n elif self.dots:\n self.stream.write('F')\n self.stream.flush()\n\n def printErrors(self):\n if self.dots or self.showAll:\n self.stream.writeln()\n self.printErrorList('ERROR', self.errors)\n self.printErrorList('FAIL', self.failures)\n\n def printErrorList(self, flavour, errors):\n for test, err in errors:\n self.stream.writeln(self.separator1)\n self.stream.writeln(\"%s: %s\" % (flavour,self.getDescription(test)))\n self.stream.writeln(self.separator2)\n self.stream.writeln(\"%s\" % err)\n\n\nclass TextTestRunner:\n \"\"\"A test runner class that displays results in textual form.\n\n It prints out the names of tests as they are run, errors as they\n occur, and a summary of the results at the end of the test run.\n \"\"\"\n def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):\n self.stream = _WritelnDecorator(stream)\n self.descriptions = descriptions\n self.verbosity = verbosity\n\n def _makeResult(self):\n return _TextTestResult(self.stream, self.descriptions, self.verbosity)\n\n def run(self, test):\n \"Run the given test case or test suite.\"\n result = self._makeResult()\n startTime = time.time()\n test(result)\n stopTime = time.time()\n timeTaken = stopTime - startTime\n result.printErrors()\n self.stream.writeln(result.separator2)\n run = result.testsRun\n self.stream.writeln(\"Ran %d test%s in %.3fs\" %\n (run, run != 1 and \"s\" or \"\", timeTaken))\n self.stream.writeln()\n if not result.wasSuccessful():\n self.stream.write(\"FAILED (\")\n failed, errored = map(len, (result.failures, result.errors))\n if failed:\n self.stream.write(\"failures=%d\" % failed)\n if errored:\n if failed: self.stream.write(\", \")\n self.stream.write(\"errors=%d\" % errored)\n self.stream.writeln(\")\")\n else:\n self.stream.writeln(\"OK\")\n return result\n\n\n\n##############################################################################\n# Facilities for running tests from the command line\n##############################################################################\n\nclass TestProgram:\n \"\"\"A command-line program that runs a set of tests; this is primarily\n for making test modules conveniently executable.\n \"\"\"\n USAGE = \"\"\"\\\nUsage: %(progName)s [options] [test] [...]\n\nOptions:\n -h, --help Show this message\n -v, --verbose Verbose output\n -q, --quiet Minimal output\n\nExamples:\n %(progName)s - run default set of tests\n %(progName)s MyTestSuite - run suite 'MyTestSuite'\n %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething\n %(progName)s MyTestCase - run all 'test*' test methods\n in MyTestCase\n\"\"\"\n def __init__(self, module='__main__', defaultTest=None,\n argv=None, testRunner=None,\n testLoader=defaultTestLoader):\n if type(module) == type(''):\n self.module = __import__(module)\n for part in module.split('.')[1:]:\n self.module = getattr(self.module, part)\n else:\n self.module = module\n if argv is None:\n argv = sys.argv\n self.verbosity = 1\n self.defaultTest = defaultTest\n self.testRunner = testRunner\n self.testLoader = testLoader\n self.progName = os.path.basename(argv[0])\n self.parseArgs(argv)\n self.runTests()\n\n def usageExit(self, msg=None):\n if msg: print msg\n print self.USAGE % self.__dict__\n sys.exit(2)\n\n def parseArgs(self, argv):\n import getopt\n try:\n options, args = getopt.getopt(argv[1:], 'hHvq',\n ['help','verbose','quiet'])\n for opt, value in options:\n if opt in ('-h','-H','--help'):\n self.usageExit()\n if opt in ('-q','--quiet'):\n self.verbosity = 0\n if opt in ('-v','--verbose'):\n self.verbosity = 2\n if len(args) == 0 and self.defaultTest is None:\n self.test = self.testLoader.loadTestsFromModule(self.module)\n return\n if len(args) > 0:\n self.testNames = args\n else:\n self.testNames = (self.defaultTest,)\n self.createTests()\n except getopt.error, msg:\n self.usageExit(msg)\n\n def createTests(self):\n self.test = self.testLoader.loadTestsFromNames(self.testNames,\n self.module)\n\n def runTests(self):\n if self.testRunner is None:\n self.testRunner = TextTestRunner\n\n if isinstance(self.testRunner, (type, types.ClassType)):\n try:\n testRunner = self.testRunner(verbosity=self.verbosity)\n except TypeError:\n # didn't accept the verbosity argument\n testRunner = self.testRunner()\n else:\n # it is assumed to be a TestRunner instance\n testRunner = self.testRunner\n result = testRunner.run(self.test)\n sys.exit(not result.wasSuccessful())\n\nmain = TestProgram\n\n\n##############################################################################\n# Executing this module from the command line\n##############################################################################\n\nif __name__ == \"__main__\":\n main(module=None)\n", "src/lib/pythonds/graphs/__init__.py": "\n\nfrom .adjGraph import Graph\nfrom .adjGraph import Vertex\nfrom .priorityQueue import PriorityQueue\n", "src/lib/pythonds/graphs/priorityQueue.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \nimport unittest\n\n# this implementation of binary heap takes key value pairs,\n# we will assume that the keys are all comparable\n\nclass PriorityQueue:\n def __init__(self):\n self.heapArray = [(0,0)]\n self.currentSize = 0\n\n def buildHeap(self,alist):\n self.currentSize = len(alist)\n self.heapArray = [(0,0)]\n for i in alist:\n self.heapArray.append(i)\n i = len(alist) // 2 \n while (i > 0):\n self.percDown(i)\n i = i - 1\n \n def percDown(self,i):\n while (i * 2) <= self.currentSize:\n mc = self.minChild(i)\n if self.heapArray[i][0] > self.heapArray[mc][0]:\n tmp = self.heapArray[i]\n self.heapArray[i] = self.heapArray[mc]\n self.heapArray[mc] = tmp\n i = mc\n \n def minChild(self,i):\n if i*2 > self.currentSize:\n return -1\n else:\n if i*2 + 1 > self.currentSize:\n return i*2\n else:\n if self.heapArray[i*2][0] < self.heapArray[i*2+1][0]:\n return i*2\n else:\n return i*2+1\n\n def percUp(self,i):\n while i // 2 > 0:\n if self.heapArray[i][0] < self.heapArray[i//2][0]:\n tmp = self.heapArray[i//2]\n self.heapArray[i//2] = self.heapArray[i]\n self.heapArray[i] = tmp\n i = i//2\n \n def add(self,k):\n self.heapArray.append(k)\n self.currentSize = self.currentSize + 1\n self.percUp(self.currentSize)\n\n def delMin(self):\n retval = self.heapArray[1][1]\n self.heapArray[1] = self.heapArray[self.currentSize]\n self.currentSize = self.currentSize - 1\n self.heapArray.pop()\n self.percDown(1)\n return retval\n \n def isEmpty(self):\n if self.currentSize == 0:\n return True\n else:\n return False\n\n def decreaseKey(self,val,amt):\n # this is a little wierd, but we need to find the heap thing to decrease by\n # looking at its value\n done = False\n i = 1\n myKey = 0\n while not done and i <= self.currentSize:\n if self.heapArray[i][1] == val:\n done = True\n myKey = i\n else:\n i = i + 1\n if myKey > 0:\n self.heapArray[myKey] = (amt,self.heapArray[myKey][1])\n self.percUp(myKey)\n \n def __contains__(self,vtx):\n for pair in self.heapArray:\n if pair[1] == vtx:\n return True\n return False\n \nclass TestBinHeap(unittest.TestCase):\n def setUp(self):\n self.theHeap = PriorityQueue()\n self.theHeap.add((2,'x'))\n self.theHeap.add((3,'y'))\n self.theHeap.add((5,'z'))\n self.theHeap.add((6,'a'))\n self.theHeap.add((4,'d'))\n\n\n def testInsert(self):\n assert self.theHeap.currentSize == 5\n\n def testDelmin(self):\n assert self.theHeap.delMin() == 'x'\n assert self.theHeap.delMin() == 'y'\n \n def testDecKey(self):\n self.theHeap.decreaseKey('d',1)\n assert self.theHeap.delMin() == 'd'\n \nif __name__ == '__main__':\n unittest.main()\n", "src/lib/pythonds/__init__.py": "", "src/lib/icebuddha/__init__.py": "def intToHex(value, fill=8):\n if fill == 0:\n return \"%X\" % value\n if fill == 8:\n return \"%0.8X\" % value\n else:\n format = \"%s0.%dX\" % (\"%\", fill)\n return format % value\n\n\ndef getBinary(value, varsize):\n str = \"\"\n for i in range(varsize):\n if (value & (1 << ((varsize-1) - i))) != 0:\n str += \"1\"\n else:\n str += \"0\"\n return str\n\n\ndef getMask(value, varsize, mask):\n str = \"\"\n for i in range(varsize):\n if (mask & (1 << ((varsize-1) - i))) != 0:\n if (value & (1 << ((varsize-1) - i))) != 0:\n str += \"1\"\n else:\n str += \"0\"\n else:\n str += \".\"\n return str\n\n\ndef nbsp(count):\n str = \"\"\n for i in range(count):\n str += (\"%snbsp;\" % chr(0x26))\n return str\n\n\ndef getString(filedata, offset, length):\n displayableAscii = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",\n \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",\n \" \", \"!\", \"\", \"#\", \"$\", \"%\", \"\", \"\", \"(\", \")\", \"*\", \"+\", \",\", \"-\", \"\", \"\",\n \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \":\", \";\", \"\", \"=\", \"\", \"?\",\n \"@\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\",\n \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"[\", \"\", \"]\", \"^\", \"_\",\n \"\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\",\n \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"{\", \"|\", \"}\", \"~\", \"\"]\n str = \"\"\n for i in range(length):\n val = filedata[offset + i]\n if (val > 127):\n continue\n str += displayableAscii[val]\n return str\n\nclass IceBuddha:\n def __init__(self, filedata, root):\n self.filedata = filedata\n self.root = Node(self, root, 0, 0)\n self.endian = self.getConst(\"LITTLE_ENDIAN\")\n\n def getConst(self, name):\n # Hack due to skulpt not knowing about static variables\n if name == \"LITTLE_ENDIAN\":\n return 0\n elif name == \"BIG_ENDIAN\":\n return 1\n return 0\n\n def setBigEndian(self):\n self.endian = self.getConst(\"BIG_ENDIAN\")\n\n def setLittleEndian(self):\n self.endian = self.getConst(\"LITTLE_ENDIAN\")\n\n def getEndian(self):\n return self.endian\n\n def getParseTree(self):\n return [self.root.get()]\n\n def append(self, node):\n self.root.append(node)\n\n def isEqual(self, offset, arrayToCheck):\n for i in range(len(arrayToCheck)):\n if (self.filedata[offset + i] != arrayToCheck[i]):\n return False\n return True\n\n def parse(self, offset, structName, input, comment=\"\"):\n struct = Node(self, structName, offset)\n struct.setComment(comment)\n for l in input.split('\\n'):\n parts = l.split(';')\n if (len(parts) < 2):\n continue\n comment = parts[1]\n parts = parts[0].split()\n type = parts[0]\n ascii = False\n if (type == \"BYTE\"):\n size = 1\n if (type == \"CHAR\"):\n size = 1\n ascii = True\n elif (type == \"WORD\"):\n size = 2\n elif (type == \"DWORD\"):\n size = 4\n elif (type == \"ULONGLONG\"):\n size = 8\n else:\n size = 1\n\n name = parts[1]\n value = \"\"\n\n arrayParts = name.split('[')\n if len(arrayParts) > 1:\n arraySize = int((arrayParts[1].split(']'))[0])\n size *= arraySize\n if ascii:\n value = getString(self.filedata, offset, size)\n n = Node(self, name, offset, size, comment, value)\n offset += size\n struct.append(n)\n return struct\n\n\nclass Node:\n def __init__(self, ib, label=\"\", offset=0, size=0, comment=\"\", value=\"\"):\n self.ib = ib\n self.filedata = ib.filedata\n self.offset = offset\n self.size = size\n\n self.label = label\n self.comment = comment\n self.children = []\n self.value = value\n\n def setComment(self, comment):\n self.comment = comment\n\n def setValue(self, value):\n self.value = value\n\n def getValue(self):\n return self.value\n\n def getData(self):\n data = 0\n if self.ib.getEndian() == self.ib.getConst(\"LITTLE_ENDIAN\"):\n for i in range(self.size):\n data = data << 8\n data |= self.filedata[self.offset+(self.size-1-i)]\n else:\n for i in range(self.size):\n data = data << 8\n data |= self.filedata[self.offset+(i)]\n return data\n\n def getBytes(self):\n data = []\n if self.ib.getEndian() == self.ib.getConst(\"LITTLE_ENDIAN\"):\n for i in range(self.size):\n data.append(self.filedata[self.offset+(self.size-1-i)])\n else:\n for i in range(self.size):\n data.append(self.filedata[self.offset+(i)])\n return data\n\n def get(self):\n childData = []\n for c in self.children:\n childData.append(c.get())\n\n return [self.label, self.size, self.comment, self.offset,\n childData, self.value]\n\n def findChild(self, childName):\n for c in self.children:\n name = c.label.split('[')\n name = name[0]\n if name == childName:\n return c\n print \"Child %s not found\" % childName\n return None\n\n def getInt(self, valueName=None):\n size = self.size\n offset = self.offset\n if valueName != None:\n c = self.findChild(valueName)\n size = c.size\n offset = c.offset\n\n if c is None:\n return 0\n return c.getData()\n\n c.getData()\n\n def start(self):\n return self.offset\n\n def end(self):\n return self.offset + self.size\n\n def append(self, child):\n self.children.append(child)\n self.size += child.size\n\n # TODO Put this somewhere else\n def isMatch(self, a1, a2):\n if (len(a1) != len(a2)):\n return False\n\n for i in range(len(a1)):\n if a1[i] != a2[i]:\n return False\n return True\n\n def setMeaningFromConstants(self, input):\n for l in input.split('\\n'):\n parts = l.split('=')\n if (len(parts) < 2):\n continue\n name = parts[0].strip()\n value = int(parts[1].strip(), 0)\n\n # TODO Don't assume 4 bytes\n valueBytes = [value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff]\n selfBytes = self.getBytes()\n\n if self.isMatch(valueBytes, selfBytes):\n self.setValue(name)\n break\n\n\n def parseBitField(self, input):\n bitCount = 0\n varSize = self.size*8\n\n self.value = \"%s%s\" % (nbsp(2), getBinary(self.getData(), varSize))\n for l in input.split('\\n'):\n parts = l.split(';')\n if (len(parts) < 2):\n continue\n comment = parts[1]\n parts = parts[0].split(\":\")\n if (len(parts) < 2):\n continue\n size = int(parts[1])\n if bitCount + size > self.size * 8:\n print \"Bit field too large for %s\" % self.label\n\n parts = parts[0].split()\n\n varType = parts[0] # Ignored\n name = parts[1]\n\n bitmask = 0\n for i in range(bitCount, bitCount + size):\n bitmask |= (1 << i)\n\n data = (bitmask & self.getData())\n data = data >> bitCount\n\n value = \"<br>%s%s (%s) %s : %d %s\" % (nbsp(11),\n getMask(bitmask & self.getData(), varSize, bitmask),\n intToHex(data, 0),\n name,\n size,\n comment)\n self.value += value\n bitCount += size\n", "src/lib/pythonds/basic/deque.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n#deque.py\r\n\r\n\r\nclass Deque:\r\n def __init__(self):\r\n self.items = []\r\n\r\n def isEmpty(self):\r\n return self.items == []\r\n\r\n def addFront(self, item):\r\n self.items.append(item)\r\n\r\n def addRear(self, item):\r\n self.items.insert(0,item)\r\n\r\n def removeFront(self):\r\n return self.items.pop()\r\n\r\n def removeRear(self):\r\n return self.items.pop(0)\r\n\r\n def size(self):\r\n return len(self.items)\r\n", "src/lib/webgl/models.js": "// most of this file is from/based on 'tdl'\n\nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n var Buffer = function(array, opt_target) {\n var target = opt_target || gl.ARRAY_BUFFER;\n var buf = gl.createBuffer();\n this.target = target;\n this.buf = buf;\n this.set(array);\n this.numComponents_ = array.numComponents;\n this.numElements_ = array.numElements;\n this.totalComponents_ = this.numComponents_ * this.numElements_;\n if (array.buffer instanceof Float32Array) {\n this.type_ = gl.FLOAT;\n } else if (array.buffer instanceof Uint8Array) {\n this.type_ = gl.UNSIGNED_BYTE;\n } else if (array.buffer instanceof Int8Array) {\n this.type_ = gl._BYTE;\n } else if (array.buffer instanceof Uint16Array) {\n this.type_ = gl.UNSIGNED_SHORT;\n } else if (array.buffer instanceof Int16Array) {\n this.type_ = gl.SHORT;\n } else {\n throw(\"unhandled type:\" + (typeof array.buffer));\n }\n };\n\n Buffer.prototype.set = function(array) {\n gl.bindBuffer(this.target, this.buf);\n gl.bufferData(this.target, array.buffer, gl.STATIC_DRAW);\n }\n\n Buffer.prototype.type = function() {\n return this.type_;\n };\n\n Buffer.prototype.numComponents = function() {\n return this.numComponents_;\n };\n\n Buffer.prototype.numElements = function() {\n return this.numElements_;\n };\n\n Buffer.prototype.totalComponents = function() {\n return this.totalComponents_;\n };\n\n Buffer.prototype.buffer = function() {\n return this.buf;\n };\n\n Buffer.prototype.stride = function() {\n return 0;\n };\n\n Buffer.prototype.offset = function() {\n return 0;\n };\n\n\n\n mod.Model = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self, shader, arrays, textures)\n {\n self.buffers = {};\n var setBuffer = function(name, array)\n {\n var target = (name == 'indices') ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;\n b = self.buffers[name];\n if (!b)\n b = new Buffer(array, target);\n else\n b.set(array);\n self.buffers[name] = b;\n };\n for (name in arrays)\n setBuffer(name, arrays[name]);\n\n var textureUnits = {};\n var unit = 0;\n for (var texture in textures)\n {\n textureUnits[texture] = unit++;\n }\n\n self.mode = gl.TRIANGLES;\n self.textures = textures.v;\n self.textureUnits = textureUnits;\n self.shader = shader;\n });\n\n /**\n * Sets up the shared parts of drawing this model. Uses the\n * program, binds the buffers, sets the textures.\n *\n * @param {!Object.<string, *>} uniforms An object of names to\n * values to set on this models uniforms.\n */\n $loc.drawPrep = new Sk.builtin.func(function(self, uniforms)\n {\n var shader = self.shader;\n var buffers = self.buffers;\n var textures = self.textures;\n\n uniforms = Sk.ffi.remapToJs(uniforms);\n\n Sk.misceval.callsim(shader.use, shader);\n\n for (var buffer in buffers) {\n var b = buffers[buffer];\n if (buffer == 'indices') {\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b.buffer());\n } else {\n var attrib = shader.attrib[buffer];\n if (attrib) {\n attrib(b);\n }\n }\n }\n\n for (var texture in textures) {\n var unit = self.textureUnits[texture];\n shader.setUniform$impl(shader, textuer, unit);\n textures[texture].bindToUnit(unit);\n }\n\n for (var uniform in uniforms) {\n shader.setUniform$impl(shader, uniform, uniforms[uniform]);\n }\n });\n\n /**\n * Draws this model.\n *\n * After calling tdl.models.Model.drawPrep you can call this\n * function multiple times to draw this model.\n *\n * @param {!Object.<string, *>} uniforms An object of names to\n * values to set on this models uniforms.\n */\n $loc.draw = new Sk.builtin.func(function(self, uniforms, opt_textures)\n {\n var shader = self.shader;\n uniforms = Sk.ffi.remapToJs(uniforms);\n for (uniform in uniforms) {\n shader.setUniform$impl(shader, uniform, uniforms[uniform]);\n }\n\n if (opt_textures) {\n for (var texture in opt_textures) {\n var unit = self.textureUnits[texture];\n shader.setUniform$impl(shader, texture, unit);\n opt_textures[texture].bindToUnit(unit);\n }\n }\n\n var buffers = self.buffers;\n gl.drawElements(self.mode, buffers.indices.totalComponents(), gl.UNSIGNED_SHORT, 0);\n });\n },\n 'Model', []);\n\n return mod;\n};\n", "src/lib/pythonds/trees/__init__.py": "\n# from .binaryTree import BinaryTree\n# from .balance import AVLTree\n# from .bst import BinarySearchTree\n# from .binheap import BinHeap\n\n\n", "src/lib/pythonds/trees/binaryTree.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n\nclass BinaryTree:\n \"\"\"\n A recursive implementation of Binary Tree\n Using links and Nodes approach.\n \"\"\" \n def __init__(self,rootObj):\n self.key = rootObj\n self.leftChild = None\n self.rightChild = None\n\n def insertLeft(self,newNode):\n if self.leftChild == None:\n self.leftChild = BinaryTree(newNode)\n else:\n t = BinaryTree(newNode)\n t.left = self.leftChild\n self.leftChild = t\n \n def insertRight(self,newNode):\n if self.rightChild == None:\n self.rightChild = BinaryTree(newNode)\n else:\n t = BinaryTree(newNode)\n t.right = self.rightChild\n self.rightChild = t\n\n def isLeaf(self):\n return ((not self.leftChild) and (not self.rightChild))\n\n def getRightChild(self):\n return self.rightChild\n\n def getLeftChild(self):\n return self.leftChild\n\n def setRootVal(self,obj):\n self.key = obj\n\n def getRootVal(self,):\n return self.key\n\n def inorder(self):\n if self.leftChild:\n self.leftChild.inorder()\n print(self.key)\n if self.rightChild:\n self.rightChild.inorder()\n\n def postorder(self):\n if self.leftChild:\n self.leftChild.postorder()\n if self.rightChild:\n self.rightChild.postorder()\n print(self.key)\n\n\n def preorder(self):\n print(self.key)\n if self.leftChild:\n self.leftChild.preorder()\n if self.rightChild:\n self.rightChild.preorder()\n\n def printexp(self):\n if self.leftChild:\n print('(')\n self.leftChild.printexp()\n print(self.key)\n if self.rightChild:\n self.rightChild.printexp()\n print(')')\n\n def postordereval(self):\n opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}\n res1 = None\n res2 = None\n if self.leftChild:\n res1 = self.leftChild.postordereval() #// \\label{peleft}\n if self.rightChild:\n res2 = self.rightChild.postordereval() #// \\label{peright}\n if res1 and res2:\n return opers[self.key](res1,res2) #// \\label{peeval}\n else:\n return self.key\n\ndef inorder(tree):\n if tree != None:\n inorder(tree.getLeftChild())\n print(tree.getRootVal())\n inorder(tree.getRightChild())\n\ndef printexp(tree):\n if tree.leftChild:\n print('(')\n printexp(tree.getLeftChild())\n print(tree.getRootVal())\n if tree.rightChild:\n printexp(tree.getRightChild())\n print(')') \n\ndef printexp(tree):\n sVal = \"\"\n if tree:\n sVal = '(' + printexp(tree.getLeftChild())\n sVal = sVal + str(tree.getRootVal())\n sVal = sVal + printexp(tree.getRightChild()) + ')'\n return sVal\n\ndef postordereval(tree):\n opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}\n res1 = None\n res2 = None\n if tree:\n res1 = postordereval(tree.getLeftChild()) #// \\label{peleft}\n res2 = postordereval(tree.getRightChild()) #// \\label{peright}\n if res1 and res2:\n return opers[tree.getRootVal()](res1,res2) #// \\label{peeval}\n else:\n return tree.getRootVal()\n\ndef height(tree):\n if tree == None:\n return -1\n else:\n return 1 + max(height(tree.leftChild),height(tree.rightChild))\n\n# t = BinaryTree(7)\n# t.insertLeft(3)\n# t.insertRight(9)\n# inorder(t)\n# import operator\n# x = BinaryTree('*')\n# x.insertLeft('+')\n# l = x.getLeftChild()\n# l.insertLeft(4)\n# l.insertRight(5)\n# x.insertRight(7)\n# print(printexp(x))\n# print(postordereval(x))\n# print(height(x))\n", "src/lib/math/__init__.js": "var $builtinmodule = function(name)\n{\n var mod = {};\n mod.pi = Sk.builtin.assk$(Math.PI, Sk.builtin.nmber.float$);\n mod.e = Sk.builtin.assk$(Math.E, Sk.builtin.nmber.float$);\n\n mod.abs = new Sk.builtin.func(function(x) {\n\t\treturn Sk.builtin.assk$(Math.abs(Sk.builtin.asnum$(x)), undefined);\n });\n\n//\tRNL\tadded\n mod.fabs = new Sk.builtin.func(function(x) {\n\t\treturn Sk.builtin.assk$(Math.abs(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.asin = new Sk.builtin.func(function(rad) {\n\t\treturn Sk.builtin.assk$(Math.asin(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.acos = new Sk.builtin.func(function(rad) {\n\t\treturn Sk.builtin.assk$(Math.acos(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.atan = new Sk.builtin.func(function(rad) {\n\t\treturn Sk.builtin.assk$(Math.atan(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.atan2 = new Sk.builtin.func(function(x, y) {\n\t\treturn Sk.builtin.assk$(Math.atan2(Sk.builtin.asnum$(x), Sk.builtin.asnum$(y)), Sk.builtin.nmber.float$);\n });\n\n mod.sin = new Sk.builtin.func(function(rad) {\n\t\treturn Sk.builtin.assk$(Math.sin(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.cos = new Sk.builtin.func(function(rad) {\n\t\treturn Sk.builtin.assk$(Math.cos(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.tan = new Sk.builtin.func(function(rad) {\n\t\treturn Sk.builtin.assk$(Math.tan(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.ceil = new Sk.builtin.func(function(x) {\n\t\treturn Sk.builtin.assk$(Math.ceil(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.floor = new Sk.builtin.func(function(x) {\n\t\treturn Sk.builtin.assk$(Math.floor(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.sqrt = new Sk.builtin.func(function(x) {\n\t\treturn Sk.builtin.assk$(Math.sqrt(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.log = new Sk.builtin.func(function(x, b) {\n\t\tif (b) {\n\t\t\treturn Sk.builtin.assk$((Math.log(Sk.builtin.asnum$(x)) / Math.log(Sk.builtin.asnum$(b))), Sk.builtin.nmber.float$);\n\t\t}\n\t\treturn Sk.builtin.assk$(Math.log(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.log10 = new Sk.builtin.func(function(x, b) {\n\t\treturn Sk.builtin.assk$((Math.log(Sk.builtin.asnum$(x)) / Math.log(Sk.builtin.asnum$(10))), Sk.builtin.nmber.float$);\n\t});\n\n mod.exp = new Sk.builtin.func(function(x) {\n\t\treturn Sk.builtin.assk$(Math.exp(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.pow = new Sk.builtin.func(function(x,y) {\n\t\treturn Sk.builtin.assk$(Math.pow(Sk.builtin.asnum$(x),Sk.builtin.asnum$(y)), Sk.builtin.nmber.float$);\n });\n\n mod.radians = new Sk.builtin.func(function(deg) {\n\t\treturn Sk.builtin.assk$(Math.PI / 180.0 * Sk.builtin.asnum$(deg), Sk.builtin.nmber.float$);\n });\n\n mod.degrees = new Sk.builtin.func(function(rad) {\n\t\treturn Sk.builtin.assk$(180.0 / Math.PI * Sk.builtin.asnum$(rad), Sk.builtin.nmber.float$);\n });\n\n mod.trunc = new Sk.builtin.func(function(x) {\n\t\treturn Sk.builtin.assk$(Math.floor(Sk.builtin.asnum$(x)), Sk.builtin.nmber.int$);\n });\n\n mod.hypot = new Sk.builtin.func(function(x, y) {\n\t\tx = Sk.builtin.asnum$(x);\n\t\ty = Sk.builtin.asnum$(y);\n\t\treturn Sk.builtin.assk$(Math.sqrt((x*x)+(y*y)), Sk.builtin.nmber.float$);\n });\n\n\tmod.factorial = new Sk.builtin.func(function(x) {\n\t\tx = Math.floor(Sk.builtin.asnum$(x));\n\t\tvar r = 1;\n\t\tfor (var i = 2; i <= x; i++)\n\t\t\tr *= i;\n\t\treturn Sk.builtin.assk$(r, Sk.builtin.nmber.int$);\n\t});\n\n return mod;\n}\n", "src/lib/webgl/primitives.js": "// most of this file is from 'tdl'\n\nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n\n\n /**\n * AttribBuffer manages a TypedArray as an array of vectors.\n *\n * @param {number} numComponents Number of components per\n * vector.\n * @param {number|!Array.<number>} numElements Number of vectors or the data.\n * @param {string} opt_type The type of the TypedArray to\n * create. Default = 'Float32Array'.\n * @param {!Array.<number>} opt_data The data for the array.\n */\n var AttribBuffer = function(\n numComponents, numElements, opt_type) {\n opt_type = opt_type || 'Float32Array';\n var type = window[opt_type];\n if (numElements.length) {\n this.buffer = new type(numElements);\n numElements = this.buffer.length / numComponents;\n this.cursor = numElements;\n } else {\n this.buffer = new type(numComponents * numElements);\n this.cursor = 0;\n }\n this.numComponents = numComponents;\n this.numElements = numElements;\n this.type = opt_type;\n };\n\n AttribBuffer.prototype.stride = function() {\n return 0;\n };\n\n AttribBuffer.prototype.offset = function() {\n return 0;\n };\n\n AttribBuffer.prototype.getElement = function(index) {\n var offset = index * this.numComponents;\n var value = [];\n for (var ii = 0; ii < this.numComponents; ++ii) {\n value.push(this.buffer[offset + ii]);\n }\n return value;\n };\n\n AttribBuffer.prototype.setElement = function(index, value) {\n var offset = index * this.numComponents;\n for (var ii = 0; ii < this.numComponents; ++ii) {\n this.buffer[offset + ii] = value[ii];\n }\n };\n\n AttribBuffer.prototype.clone = function() {\n var copy = new AttribBuffer(\n this.numComponents, this.numElements, this.type);\n copy.pushArray(this);\n return copy;\n }\n\n AttribBuffer.prototype.push = function(value) {\n this.setElement(this.cursor++, value);\n };\n\n AttribBuffer.prototype.pushArray = function(array) {\n // this.buffer.set(array, this.cursor * this.numComponents);\n // this.cursor += array.numElements;\n for (var ii = 0; ii < array.numElements; ++ii) {\n this.push(array.getElement(ii));\n }\n };\n\n AttribBuffer.prototype.pushArrayWithOffset =\n function(array, offset) {\n for (var ii = 0; ii < array.numElements; ++ii) {\n var elem = array.getElement(ii);\n for (var jj = 0; jj < offset.length; ++jj) {\n elem[jj] += offset[jj];\n }\n this.push(elem);\n }\n };\n\n /**\n * Computes the extents\n * @param {!AttribBuffer} positions The positions\n * @return {!{min: !tdl.math.Vector3, max:!tdl.math.Vector3}}\n * The min and max extents.\n */\n AttribBuffer.prototype.computeExtents = function() {\n var numElements = this.numElements;\n var numComponents = this.numComponents;\n var minExtent = this.getElement(0);\n var maxExtent = this.getElement(0);\n for (var ii = 1; ii < numElements; ++ii) {\n var element = this.getElement(ii);\n for (var jj = 0; jj < numComponents; ++jj) {\n minExtent[jj] = Math.min(minExtent[jj], element[jj]);\n maxExtent[jj] = Math.max(maxExtent[jj], element[jj]);\n }\n }\n return {min: minExtent, max: maxExtent};\n };\n\n\n /**\n * Creates the vertices and indices for a cube. The\n * cube will be created around the origin. (-size / 2, size / 2)\n *\n * @param {number} size Width, height and depth of the cube.\n * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The\n * created plane vertices.\n */\n mod.createCube = new Sk.builtin.func(function(size)\n {\n var CUBE_FACE_INDICES_ = [\n [3, 7, 5, 1],\n [0, 4, 6, 2],\n [6, 7, 3, 2],\n [0, 1, 5, 4],\n [5, 7, 6, 4],\n [2, 3, 1, 0]\n ];\n\n var k = size / 2;\n\n var cornerVertices = [\n [-k, -k, -k],\n [+k, -k, -k],\n [-k, +k, -k],\n [+k, +k, -k],\n [-k, -k, +k],\n [+k, -k, +k],\n [-k, +k, +k],\n [+k, +k, +k]\n ];\n\n var faceNormals = [\n [+1, +0, +0],\n [-1, +0, +0],\n [+0, +1, +0],\n [+0, -1, +0],\n [+0, +0, +1],\n [+0, +0, -1]\n ];\n\n var uvCoords = [\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 1]\n ];\n\n var numVertices = 6 * 4;\n var positions = new AttribBuffer(3, numVertices);\n var normals = new AttribBuffer(3, numVertices);\n var texCoords = new AttribBuffer(2, numVertices);\n var indices = new AttribBuffer(3, 6 * 2, 'Uint16Array');\n\n for (var f = 0; f < 6; ++f) {\n var faceIndices = CUBE_FACE_INDICES_[f];\n for (var v = 0; v < 4; ++v) {\n var position = cornerVertices[faceIndices[v]];\n var normal = faceNormals[f];\n var uv = uvCoords[v];\n\n // Each face needs all four vertices because the normals and texture\n // coordinates are not all the same.\n positions.push(position);\n normals.push(normal);\n texCoords.push(uv);\n\n }\n // Two triangles make a square face.\n var offset = 4 * f;\n indices.push([offset + 0, offset + 1, offset + 2]);\n indices.push([offset + 0, offset + 2, offset + 3]);\n }\n\n return {\n position: positions,\n normal: normals,\n texCoord: texCoords,\n indices: indices\n };\n });\n\n return mod;\n};\n", "src/lib/re/__init__.js": "var $builtinmodule = function(name)\n{\n var mod = {};\n\n var matchobj = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self,thematch, pattern, string) {\n self.thematch = thematch;\n\t self.re = pattern;\n\t self.string = string;\n });\n\n\t$loc.groups = new Sk.builtin.func(function(self) {\n\t return new Sk.builtin.tuple(self.thematch.v.slice(1))\n\t});\n\n\t$loc.group = new Sk.builtin.func(function(self,grpnum) {\n\t\tgrpnum = Sk.builtin.asnum$(grpnum);\n\t if(grpnum >= self.thematch.v.length) {\n\t\tthrow new Sk.builtin.IndexError(\"Index out of range: \" + grpnum);\n\t\t}\n\t return self.thematch.v[grpnum]\n\t});\n\n }\n\n mod.MatchObject = Sk.misceval.buildClass(mod, matchobj, 'MatchObject', []);\n\n // Internal function to return a Python list of strings \n // From a JS regular expression string\n mod._findre = function(res, string) {\n var re = eval(res);\n var matches = string.v.match(re);\n retval = new Sk.builtin.list();\n if ( matches == null ) return retval;\n for (var i = 0; i < matches.length; ++i) {\n var sitem = new Sk.builtin.str(matches[i]);\n retval.v.push(sitem);\n }\n return retval;\n }\n \n mod.findall = new Sk.builtin.func(function(pattern, string, flags) {\n var res = \"/\"+pattern.v.replace(\"/\",\"\\\\/\")+\"/g\";\n var re = eval(res);\n var matches = string.v.match(re);\n retval = new Sk.builtin.list();\n if ( matches == null ) return retval;\n for (var i = 0; i < matches.length; ++i) {\n var sitem = new Sk.builtin.str(matches[i]);\n retval.v.push(sitem);\n }\n return retval;\n });\n\n mod.search = new Sk.builtin.func(function(pattern, string, flags) {\n var res = \"/\"+pattern.v.replace(\"/\",\"\\\\/\")+\"/\";\n lst = mod._findre(res,string);\n if ( lst.v.length < 1 ) return null;\n var mob = Sk.misceval.callsim(mod.MatchObject, lst, pattern, string);\n return mob;\n });\n\n mod.match = new Sk.builtin.func(function(pattern, string, flags) {\n var res = \"/^\"+pattern.v.replace(\"/\",\"\\\\/\")+\"/\";\n lst = mod._findre(res,string);\n if ( lst.v.length < 1 ) return null;\n var mob = Sk.misceval.callsim(mod.MatchObject, lst, pattern, string);\n return mob;\n });\n\n return mod;\n}\n", "src/lib/random/__init__.js": "\n/*\n I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace\n so it's better encapsulated. Now you can have multiple random number generators\n and they won't stomp all over eachother's state.\n \n If you want to use this as a substitute for Math.random(), use the random()\n method like so:\n \n var m = new MersenneTwister();\n var randomNumber = m.random();\n \n You can also call the other genrand_{foo}() methods on the instance.\n\n If you want to use a specific seed in order to get a repeatable random\n sequence, pass an integer into the constructor:\n\n var m = new MersenneTwister(123);\n\n and that will always produce the same random sequence.\n\n Sean McCullough ([email protected])\n*/\n\n/* \n A C-program for MT19937, with initialization improved 2002/1/26.\n Coded by Takuji Nishimura and Makoto Matsumoto.\n \n Before using, initialize the state by using init_genrand(seed) \n or init_by_array(init_key, key_length).\n \n Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,\n All rights reserved. \n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n \n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n \n 3. The names of its contributors may not be used to endorse or promote \n products derived from this software without specific prior written \n permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n \n \n Any feedback is very welcome.\n http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\n email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)\n*/\n\nvar MersenneTwister = function(seed) {\n if (seed == undefined) {\n seed = new Date().getTime();\n } \n /* Period parameters */ \n this.N = 624;\n this.M = 397;\n this.MATRIX_A = 0x9908b0df; /* constant vector a */\n this.UPPER_MASK = 0x80000000; /* most significant w-r bits */\n this.LOWER_MASK = 0x7fffffff; /* least significant r bits */\n \n this.mt = new Array(this.N); /* the array for the state vector */\n this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */\n\n this.init_genrand(seed);\n} \n \n/* initializes mt[N] with a seed */\nMersenneTwister.prototype.init_genrand = function(s) {\n this.mt[0] = s >>> 0;\n for (this.mti=1; this.mti<this.N; this.mti++) {\n var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);\n this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)\n + this.mti;\n /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n /* In the previous versions, MSBs of the seed affect */\n /* only MSBs of the array mt[]. */\n /* 2002/01/09 modified by Makoto Matsumoto */\n this.mt[this.mti] >>>= 0;\n /* for >32 bit machines */\n }\n}\n \n/* initialize by an array with array-length */\n/* init_key is the array for initializing keys */\n/* key_length is its length */\n/* slight change for C++, 2004/2/26 */\nMersenneTwister.prototype.init_by_array = function(init_key, key_length) {\n var i, j, k;\n this.init_genrand(19650218);\n i=1; j=0;\n k = (this.N>key_length ? this.N : key_length);\n for (; k; k--) {\n var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)\n this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))\n + init_key[j] + j; /* non linear */\n this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */\n i++; j++;\n if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }\n if (j>=key_length) j=0;\n }\n for (k=this.N-1; k; k--) {\n var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);\n this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))\n - i; /* non linear */\n this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */\n i++;\n if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }\n }\n\n this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ \n}\n \n/* generates a random number on [0,0xffffffff]-interval */\nMersenneTwister.prototype.genrand_int32 = function() {\n var y;\n var mag01 = new Array(0x0, this.MATRIX_A);\n /* mag01[x] = x * MATRIX_A for x=0,1 */\n\n if (this.mti >= this.N) { /* generate N words at one time */\n var kk;\n\n if (this.mti == this.N+1) /* if init_genrand() has not been called, */\n this.init_genrand(5489); /* a default initial seed is used */\n\n for (kk=0;kk<this.N-this.M;kk++) {\n y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);\n this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (;kk<this.N-1;kk++) {\n y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);\n this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);\n this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n this.mti = 0;\n }\n\n y = this.mt[this.mti++];\n\n /* Tempering */\n y ^= (y >>> 11);\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= (y >>> 18);\n\n return y >>> 0;\n}\n \n/* generates a random number on [0,0x7fffffff]-interval */\nMersenneTwister.prototype.genrand_int31 = function() {\n return (this.genrand_int32()>>>1);\n}\n \n/* generates a random number on [0,1]-real-interval */\nMersenneTwister.prototype.genrand_real1 = function() {\n return this.genrand_int32()*(1.0/4294967295.0); \n /* divided by 2^32-1 */ \n}\n\n/* generates a random number on [0,1)-real-interval */\nMersenneTwister.prototype.random = function() {\n return this.genrand_int32()*(1.0/4294967296.0); \n /* divided by 2^32 */\n}\n \n/* generates a random number on (0,1)-real-interval */\nMersenneTwister.prototype.genrand_real3 = function() {\n return (this.genrand_int32() + 0.5)*(1.0/4294967296.0); \n /* divided by 2^32 */\n}\n \n/* generates a random number on [0,1) with 53-bit resolution*/\nMersenneTwister.prototype.genrand_res53 = function() { \n var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6; \n return(a*67108864.0+b)*(1.0/9007199254740992.0); \n} \n\n/* These real versions are due to Isaku Wada, 2002/01/09 added */\n\nfunction fisherYates ( myArray ) {\n var i = myArray.length, j, tempi, tempj;\n if ( i == 0 ) return false;\n while ( --i ) {\n j = Math.floor( Math.random() * ( i + 1 ) );\n tempi = myArray[i];\n tempj = myArray[j];\n myArray[i] = tempj;\n myArray[j] = tempi;\n }\n}\n\nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n var myGenerator = new MersenneTwister();\n\n var checkArgs = function(expected, actual, func) {\n if (actual != expected ) {\n throw new Sk.builtin.TypeError(func + \" takes exactly \" + expected +\n \" positional argument (\" + actual + \" given)\")\n }\n }\n\n mod.seed = new Sk.builtin.func(function(x) {\n \t\tx = Sk.builtin.asnum$(x);\n if (arguments.length > 0)\n myGenerator = new MersenneTwister(x);\n else\n myGenerator = new MersenneTwister();\n });\n\n mod.random = new Sk.builtin.func(function() {\n\treturn Sk.builtin.assk$(myGenerator.genrand_res53(), undefined);\n });\n\n mod.randint = new Sk.builtin.func(function(low,high) {\n\t\tlow = Sk.builtin.asnum$(low);\n \t\thigh = Sk.builtin.asnum$(high);\n checkArgs(2,arguments.length,\"randint()\")\n return Sk.builtin.assk$(Math.round(myGenerator.genrand_res53()*(high-low))+low, undefined);\n });\n\n mod.randrange = new Sk.builtin.func(function(low,high) {\n\t\tlow = Sk.builtin.asnum$(low);\n \t\thigh = Sk.builtin.asnum$(high);\n if (high === undefined) {\n high = low;\n low = 0;\n }\n high = high - 1;\n return Sk.builtin.assk$(Math.round(myGenerator.genrand_res53()*(high-low))+low, undefined);\n });\n\n mod.shuffle = new Sk.builtin.func(function(myarray) {\n\tfisherYates(myarray.v)\n });\n\n return mod;\n\n}\n", "src/lib/test/__init__.py": "__author__ = 'bmiller'\n\ndef testEqual(actual, expected):\n if type(expected) == type(1):\n if actual == expected:\n print('Pass')\n return True\n elif type(expected) == type(1.11):\n if abs(actual-expected) < 0.00001:\n print('Pass')\n return True\n else:\n if actual == expected:\n print('Pass')\n return True\n print('Test Failed: expected ' + str(expected) + ' but got ' + str(actual))\n return False\n\ndef testNotEqual(actual, expected):\n pass\n\n", "src/builtin/this.py": "s = \"\"\"Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf orggre guna htyl.\nRkcyvpvg vf orggre guna vzcyvpvg.\nFvzcyr vf orggre guna pbzcyrk.\nPbzcyrk vf orggre guna pbzcyvpngrq.\nSyng vf orggre guna arfgrq.\nFcnefr vf orggre guna qrafr.\nErnqnovyvgl pbhagf.\nFcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.\nNygubhtu cenpgvpnyvgl orngf chevgl.\nReebef fubhyq arire cnff fvyragyl.\nHayrff rkcyvpvgyl fvyraprq.\nVa gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.\nGurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.\nNygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.\nAbj vf orggre guna arire.\nNygubhtu arire vf bsgra orggre guna *evtug* abj.\nVs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.\nVs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.\nAnzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!\"\"\"\n\nd = {}\nfor c in (65, 97):\n for i in range(26):\n d[chr(i+c)] = chr((i+13) % 26 + c)\n\nprint \"\".join([d.get(c, c) for c in s])\n"}}