diff --git a/game/end_to_end_tests/test_play_through.py b/game/end_to_end_tests/test_play_through.py index d9448b627..848fe214b 100644 --- a/game/end_to_end_tests/test_play_through.py +++ b/game/end_to_end_tests/test_play_through.py @@ -415,3 +415,152 @@ def test_level_121(self): def test_level_122(self): self._complete_level(122, check_algorithm_score=False, final_level=True) + def test_episode_13(self): + self._complete_episode(13, 1014) + + def test_level_1014(self): + self._complete_level(1014) + + def test_level_1015(self): + self._complete_level(1015) + + def test_level_1016(self): + self._complete_level(1016, check_algorithm_score=False) + + def test_level_1017(self): + self._complete_level(1017, check_algorithm_score=False) + + def test_level_1018(self): + self._complete_level(1018, check_algorithm_score=False) + + def test_level_1019(self): + self._complete_level(1019) + + def test_level_1020(self): + self._complete_level(1020, check_algorithm_score=False) + + def test_level_1021(self): + self._complete_level(1021, check_algorithm_score=False) + + def test_level_1022(self): + self._complete_level(1022) + + def test_level_1023(self): + self._complete_level(1023) + + def test_level_1024(self): + self._complete_level(1024, check_algorithm_score=False) + + def test_level_1025(self): + self._complete_level(1025, check_algorithm_score=False) + + def test_episode_14(self): + self._complete_episode(14, 1026) + + def test_level_1026(self): + self._complete_level(1026) + + def test_level_1027(self): + self._complete_level(1027) + + def test_level_1028(self): + self._complete_level(1028) + + def test_level_1029(self): + self._complete_level(1029) + + def test_level_1030(self): + self._complete_level(1030, check_algorithm_score=False) + + def test_level_1031(self): + self._complete_level(1031) + + def test_level_1032(self): + self._complete_level(1032) + + def test_level_1033(self): + self._complete_level(1033, check_algorithm_score=False) + + def test_level_1034(self): + self._complete_level(1034, check_algorithm_score=False) + + def test_level_1035(self): + self._complete_level(1035) + + def test_level_1036(self): + self._complete_level(1036) + + def test_level_1037(self): + self._complete_level(1037, check_algorithm_score=False) + + def test_level_1039(self): + self._complete_level(1039, check_algorithm_score=False) + + def test_level_1040(self): + self._complete_level(1040, check_algorithm_score=False) + + def test_episode_15(self): + self._complete_episode(15, 1041) + + def test_level_1041(self): + self._complete_level(1041) + + def test_level_1042(self): + self._complete_level(1042, check_algorithm_score=False) + + def test_level_1043(self): + self._complete_level(1043, check_algorithm_score=False) + + def test_level_1044(self): + self._complete_level(1044) + + def test_level_1045(self): + self._complete_level(1045, check_algorithm_score=False) + + def test_level_1046(self): + self._complete_level(1046, check_algorithm_score=False) + + def test_level_1047(self): + self._complete_level(1047, check_algorithm_score=False) + + def test_level_1048(self): + self._complete_level(1048, check_algorithm_score=False) + + def test_level_1049(self): + self._complete_level(1049, check_algorithm_score=False) + + def test_episode_22(self): + self._complete_episode(22, 1050) + + def test_level_1050(self): + self._complete_level(1050) + + def test_level_1051(self): + self._complete_level(1051) + + def test_level_1052(self): + self._complete_level(1052, check_algorithm_score=False) + + def test_level_1053(self): + self._complete_level(1053, check_algorithm_score=False) + + def test_level_1054(self): + self._complete_level(1054, check_algorithm_score=False) + + def test_level_1055(self): + self._complete_level(1055, check_algorithm_score=False) + + def test_level_1056(self): + self._complete_level(1056, check_algorithm_score=False) + + def test_level_1057(self): + self._complete_level(1057, check_algorithm_score=False) + + def test_level_1058(self): + self._complete_level(1058, check_algorithm_score=False) + + def test_level_1059(self): + self._complete_level(1059, check_algorithm_score=False) + + def test_level_1060(self): + self._complete_level(1060, check_algorithm_score=False, final_level=True) diff --git a/game/messages.py b/game/messages.py index c23ec648e..3543f1e60 100644 --- a/game/messages.py +++ b/game/messages.py @@ -36,9 +36,7 @@ def if_else_icon_url(): def if_else_example_url(): - return ( - 'If Else example' - ) + return 'If Else example' def not_shared_level(): @@ -1940,6 +1938,7 @@ def hint_level91(): "Beginner's Guide to Python." ) + def title_level92(): return "Start with the basics, forward, left and right" @@ -1952,13 +1951,16 @@ def description_level92(): ) return build_description(title_level92(), message) + def commands_level92(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level92(): return ( "Try using the following commands:
my_van.move_forwards()
my_van.turn_left()" @@ -1977,13 +1979,16 @@ def description_level93(): ) return build_description(title_level93(), message) + def commands_level93(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level93(): return ( """Try using the following commands: @@ -2005,13 +2010,16 @@ def description_level94(): ) return build_description(title_level94(), message) + def commands_level94(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level94(): return ( """Try using the following commands: @@ -2033,13 +2041,16 @@ def description_level95(): ) return build_description(title_level95(), message) + def commands_level95(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level95(): return ( """To repeat some statements a set number of times you can use something like the following: @@ -2063,11 +2074,10 @@ def description_level96(): ) return build_description(title_level96(), message) + def commands_level96(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' - ) + return "Movement" + "
my_van.move_forwards()" + "
my_van.turn_left()" + def hint_level96(): return ( @@ -2091,13 +2101,16 @@ def description_level97(): ) return build_description(title_level97(), message) + def commands_level97(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level97(): return ( """To repeat within a repeats a set number of times you can use something like the following: @@ -2123,19 +2136,22 @@ def description_level98(): ) return build_description(title_level98(), message) + def commands_level98(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()
'+ - '
' + - 'Position' + - '
my_van.at_destination()' + - '
my_van.is_road_forward()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()
" + + '
' + + "Position" + + "
my_van.at_destination()" + + "
my_van.is_road_forward()
" + + '
' ) + def hint_level98(): return ( """To repeat while a condition is met you can use something like the following: @@ -2161,22 +2177,25 @@ def description_level99(): ) return build_description(title_level99(), message) + def commands_level99(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()
'+ - '
' + - 'Position' + - '
my_van.at_destination()' + - '
my_van.is_road_right()' + - '
my_van.is_road_left()' + - '
my_van.is_road_forward()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.at_destination()" + + "
my_van.is_road_right()" + + "
my_van.is_road_left()" + + "
my_van.is_road_forward()
" + + '
' ) + def hint_level99(): return ( """To repeat while a condition is met you can use something like the following: @@ -2201,22 +2220,25 @@ def description_level100(): ) return build_description(title_level100(), message) + def commands_level100(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()
'+ - '
' + - 'Position'+ - '
my_van.at_destination()' + - '
my_van.is_road_forward()' + - '
my_van.is_road_right()' + - '
my_van.is_road_left()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.at_destination()" + + "
my_van.is_road_forward()" + + "
my_van.is_road_right()" + + "
my_van.is_road_left()
" + + '
' ) + def hint_level100(): return ( "Try using
if my_van.at_dead_end():

to check if the van is at a dead end." @@ -2236,13 +2258,16 @@ def description_level101(): ) return build_description(title_level101(), message) + def commands_level101(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level101(): return ( """To define a function in Python you could do something like: @@ -2266,13 +2291,16 @@ def description_level102(): ) return build_description(title_level102(), message) + def commands_level102(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level102(): return ( """To define a function in Python you could do something like: @@ -2295,13 +2323,16 @@ def description_level103(): ) return build_description(title_level103(), message) + def commands_level103(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level103(): return ( """To define a function that calls another function you could do something like: @@ -2328,13 +2359,16 @@ def description_level104(): ) return build_description(title_level104(), message) + def commands_level104(): - return ('Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()' + return ( + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" ) + def hint_level104(): return ( """To define a function that calls another function you could do something like: @@ -2361,23 +2395,26 @@ def description_level105(): ) return build_description(title_level105(), message) + def commands_level105(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()' + - '
my_van.turn_right()'+ - '
my_van.wait()
' + - '
' + - 'Position' + - '
my_van.is_road_forward()' + - '
my_van.is_road_left()' + - '
my_van.at_red_traffic_light()' + - '
my_van.at_destination()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" + + "
my_van.wait()
" + + '
' + + "Position" + + "
my_van.is_road_forward()" + + "
my_van.is_road_left()" + + "
my_van.at_red_traffic_light()" + + "
my_van.at_destination()
" + + '
' ) + def hint_level105(): return ( "For this you will have to use a combination of the while and if statements." @@ -2398,26 +2435,30 @@ def description_level106(): ) return build_description(title_level106(), message) + def commands_level106(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_right()
'+ - '
' + - 'Position' + - '
my_van.at_destination()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.at_destination()
" + + '
' ) + def hint_level106(): return ( """To use a variable to store the number of grid squares the van has to move you can do something like the following: -
number = 1
+
count = 1
 while not my_van.at_destination():
-    print number
-    number += 1
-Variables can be used in place of constants when calling functions. For example to repeat something number times you can do something like the following: + # Do something + print(count) + count = count + 1
+Variables can be used in place of fixed values when calling functions. For example to repeat something number times you can do something like the following:
for count in range(number):
""" + PYTHON_HINT ) @@ -2434,18 +2475,21 @@ def description_level107(): ) return build_description(title_level107(), message) + def commands_level107(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()
'+ - '
' + - 'Position' + - '
my_van.at_destination()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()
" + + '
' + + "Position" + + "
my_van.at_destination()
" + + '
' ) + def hint_level107(): return ( "To double the value of a variable you can do something like the following:
number *= 2
" @@ -2461,22 +2505,25 @@ def description_level108(): message = "This time the straight sections of road decrease in length by 2 after each turn." return build_description(title_level108(), message) + def commands_level108(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_left()
'+ - '
' + - 'Position' + - '
my_van.at_destination()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()
" + + '
' + + "Position" + + "
my_van.at_destination()
" + + '
' ) + def hint_level108(): return ( "To decrease the value of a variable by an amount you can do something like the " - "following:
number -= 5
" + PYTHON_HINT + "following:
count = count - 5
" + PYTHON_HINT ) @@ -2491,17 +2538,19 @@ def description_level109(): ) return build_description(title_level109(), message) + def commands_level109(): - return ('
' + - '
' + - 'Movement'+ - '
my_van.move_forwards()' + - '
my_van.turn_right()'+ - '
my_van.turn_left()
'+ - '
' + - 'Position' + - '
my_van.at_destination()
' + - '
' + return ( + '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_right()" + + "
my_van.turn_left()
" + + '
' + + "Position" + + "
my_van.at_destination()
" + + '
' ) @@ -2566,7 +2615,10 @@ def hint_level109(): "Can you remember how the Python was formed under the blocks in the previous levels? Take a look in the Py Commands for a quick reminder.", ), lambda: "Now it is your turn, you can click on the Py commands button for a reminder of the Python commands that you can use.", - lambda: 'Movement'+ '
my_van.move_forwards()' +'
my_van.turn_left()' +'
my_van.turn_right()', + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", ) ( @@ -2581,7 +2633,10 @@ def hint_level109(): "This route is just a bit longer. Make sure you type the Python code accurately!", ), lambda: "The most common errors here are missing the round brackets at the end of the commands or mistyping the commands, e.g. use my_van.move_fowards() and not my_van.move_foward()", - lambda: 'Movement'+ '
my_van.move_forwards()' +'
my_van.turn_left()' +'
my_van.turn_right()', + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", ) ( @@ -2596,7 +2651,10 @@ def hint_level109(): "Try to find the shortest route using Python code only. You are getting really good at this!", ), lambda: "If you are stuck on this one, check that you are using the Python commands accurately. Click the Py Commands button to help you.", - lambda: 'Movement'+ '
my_van.move_forwards()' +'
my_van.turn_left()' +'
my_van.turn_right()', + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", ) ( @@ -2607,9 +2665,7 @@ def hint_level109(): lambda: "In a while, crocodile!", lambda: build_description( title_level116(), - "This level may look easy, but this time you need to use a While Loop to deliver to the house." - "
" - "Can you do it? Name your variables wisely.", + "Try to build up the blocks using a while loop to solve this one. Make sure that you count carefully.", ), lambda: "Make sure that you are using the right blocks here. You must use the pink block for variables and the dark blue number block for values. Watch the video if you are unsure.", ) @@ -2622,11 +2678,7 @@ def hint_level109(): lambda: "Wiggle while you work", lambda: build_description( title_level117(), - "This time it's a little harder. We've added the directions back in." - "
" - "Can you put them in the right place?" - "

" - "Notice how the Python looks in the console.", + "Now look at the Python code for that while loop you created. Can you match the blocks to the Python? What do you notice about the Python code?", ), lambda: "If you cannot solve this one, try creating a solution without a while loop and then looking for what is repeated...", ) @@ -2639,9 +2691,7 @@ def hint_level109(): lambda: "This way, that way, forwards...", lambda: build_description( title_level118(), - "Now all three directions are back!" - "
" - "Use what you have learned so far to get your delivery completed.", + "Think carefully about this one. It might be that some code is inside a loop and some code is not…", ), lambda: "You can solve this in stages. Try moving to the start of the repeated section, then adding the loop and then finishing it off.", ) @@ -2655,12 +2705,13 @@ def hint_level109(): lambda: "Four leaf clover", lambda: build_description( title_level119(), - "Now let's try what you've learned without blocks." - "
" - "Click on the Py Commands button to remind yourself of the syntax you need.", + "Look for a pattern and then count how many times it repeats. Good luck!", ), lambda: "If you cannot solve this one, try creating a solution without a while loop and then looking for what is repeated...", - lambda: 'Movement'+ '
my_van.move_forwards()' +'
my_van.turn_left()' +'
my_van.turn_right()', + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", ) ( @@ -2672,10 +2723,13 @@ def hint_level109(): lambda: "Pond life", lambda: build_description( title_level120(), - "So many routes but only one that is efficient. Can you work out which one it is?", + "There is a pattern of moves in this one too. Can you spot it?", ), lambda: "What if you go down the middle section?", - lambda: 'Movement'+ '
my_van.move_forwards()' +'
my_van.turn_left()' +'
my_van.turn_right()', + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", ) ( @@ -2687,10 +2741,13 @@ def hint_level109(): lambda: "Farmyard overdrive", lambda: build_description( title_level121(), - "Maybe including a loop is the answer here?", + "Look for a pattern before you type any code. You can solve this one with a counted loop…", ), lambda: "Try that middle route...", - lambda: 'Movement'+ '
my_van.move_forwards()' +'
my_van.turn_left()' +'
my_van.turn_right()', + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", ) ( @@ -2702,10 +2759,13 @@ def hint_level109(): lambda: "Snnnaaaake reflection", lambda: build_description( title_level122(), - "Can you see some patterns? Looks like those loops will come in handy again for this tricky route.", + "The solution to this one is just a bit longer. Build it up slowly. Good luck!", ), lambda: "Don't try to solve this in one go. Work out the pattern for the top route and check that works. Then move on to the next part...", - lambda: 'Movement'+ '
my_van.move_forwards()' +'
my_van.turn_left()' +'
my_van.turn_right()', + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", ) @@ -3024,6 +3084,552 @@ def hint_level109(): lambda: "TODO", ) +( + title_level1014, + description_level1014, + hint_level1014, +) = ( + lambda: "Too many cows", + lambda: build_description( + title_level1014(), + "This is a nice long straight road, but there are cows about!", + ), + lambda: "Make sure you sound the horn to get the cows off the road.", +) + +( + title_level1015, + description_level1015, + hint_level1015, +) = ( + lambda: "Stepping it up", + lambda: build_description( + title_level1015(), "There are some bends in this road. Be careful!" + ), + lambda: "What do you need to count, how many times you move or how many times you move forwards?", +) + +(title_level1016, description_level1016, hint_level1016, commands_level1016) = ( + lambda: "Cows on the stairs", + lambda: build_description( + title_level1016(), + "Oh no! The farmer seems to have let their cows out again. Be careful.", + ), + lambda: "Look for a pattern here...", + lambda: '
' + + '
' + + "Movement" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + "
" + + '
' + + '
' + + "

Animals" + + "
my_van.is_animal_crossing()" + + "
my_van.sound_horn()

" + + "
", +) + +(title_level1017, description_level1017, hint_level1017, commands_level1017) = ( + lambda: "Try stepping in Python!", + lambda: build_description( + title_level1017(), "Keep going, you're getting the hang of the Python code." + ), + lambda: "So you are going forward unless...?", + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.is_road_left()
" + + '
', +) + +(title_level1018, description_level1018, hint_level1018, commands_level1018) = ( + lambda: "A long and winding road", + lambda: build_description(title_level1018(), "Oh dear, you might get a bit dizzy!"), + lambda: "What are you counting here, straight roads or bends?", + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()
" + + '
' + + "Position" + + "
my_van.is_road_left()
" + + '
', +) + +( + title_level1019, + description_level1019, + hint_level1019, +) = ( + lambda: "Try this level... or else!", + lambda: build_description( + title_level1019(), + "Have you noticed that there are more roads ahead than turns? Try checking if there is a road ahead and then otherwise making the turns you need...", + ), + lambda: "Remember to use if..else", +) + +(title_level1020, description_level1020, hint_level1020, commands_level1020) = ( + lambda: "Now try one in Python!", + lambda: build_description( + title_level1020(), "Use if..else in Python for this level" + ), + lambda: "Don't get distracted by the other roads. Look for a pattern you can repeat.", + lambda: '
' + + '
' + + "Movement" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.is_road_left()
" + + '
', +) + +(title_level1021, description_level1021, hint_level1021, commands_level1021) = ( + lambda: "What if there are multiple houses?", + lambda: build_description( + title_level1021(), + "This is a really busy road. Make sure that you don't miss any of the houses.", + ), + lambda: "Did you get the last house? Think about what value the loop counter will have at that point in your code...", + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" + + "
my_van.deliver()
" + + '
' + + "Position" + + "
my_van.is_road_left()
" + + '
', +) + +( + title_level1022, + description_level1022, + hint_level1022, +) = ( + lambda: "Count and check", + lambda: build_description( + title_level1022(), "There are lots of turns here, don't get distracted." + ), + lambda: "Think about the order of the questions you ask using your if and elif statements.", +) + +( + title_level1023, + description_level1023, + hint_level1023, +) = ( + lambda: "Another twisty trip", + lambda: build_description(title_level1023(), "Don't go the long way around!"), + lambda: "Think carefully about the order in which you ask questions in your if..else if block", +) + +(title_level1024, description_level1024, hint_level1024, commands_level1024) = ( + lambda: "Give Python a go!", + lambda: build_description( + title_level1024(), "Look carefully for the shortest route." + ), + lambda: "Think carefully about the order in which you ask questions in your if..elif statements.", + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.is_road_forward()" + + "
my_van.is_road_left()
" + + '
', +) + +(title_level1025, description_level1025, hint_level1025, commands_level1025) = ( + lambda: "Now we've added a traffic light", + lambda: build_description( + title_level1025(), "Look carefully for the shortest route." + ), + lambda: "Think carefully about the order in which you ask questions in your if..elif statements. Don't forget the traffic lights.", + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" + + "
my_van.wait()
" + + '
' + + "Position" + + "
my_van.is_road_forward()" + + "
my_van.is_road_left()" + + "
my_van.at_red_traffic_light()
" + + '
', +) + +( + title_level1026, + description_level1026, + hint_level1026, +) = (lambda: title_level85(), lambda: description_level85(), lambda: hint_level85()) + +( + title_level1027, + description_level1027, + hint_level1027, +) = ( + lambda: "Full steam ahead", + lambda: build_description( + title_level1027(), "Just keep going until you get there..." + ), + lambda: "You might find that the solution to this level is quite familiar...", +) + +( + title_level1028, + description_level1028, + hint_level1028, +) = ( + lambda: "Another staircase...", + lambda: build_description( + title_level1028(), + "Well done, you did it! Now have a go at using the Repeat until block on a road with lots of turns.", + ), + lambda: "This is another route you have seen before. Last time you counted how many times your instructions were repeated. This time, your program is going to repeat your commands until you reach the destination. What do you need to repeat?", +) + +( + title_level1029, + description_level1029, + hint_level1029, +) = (lambda: title_level119(), lambda: description_level119(), lambda: hint_level119()) + +(title_level1030, description_level1030, hint_level1030, commands_level1030) = ( + lambda: title_level84(), + lambda: description_level84(), + lambda: hint_level84(), + lambda: '
' + + '
' + + "Movement" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.at_destination()
" + + '
', +) + +( + title_level1031, + description_level1031, + hint_level1031, +) = (lambda: title_level34(), lambda: description_level34(), lambda: hint_level34()) + +( + title_level1032, + description_level1032, + hint_level1032, +) = ( + lambda: "Something isn't right", + lambda: build_description( + title_level1032(), + "You don't have a right turn block here, so plan your route carefully.", + ), + lambda: "Think carefully about the order in which you ask questions in your if-statement here...", +) + +(title_level1033, description_level1033, hint_level1033, commands_level1033) = ( + lambda: "Looking both ways", + lambda: build_description(title_level1033(), "Can you find the shortest route?"), + lambda: "In this level, you want to check for a left turn first. If there is no left turn, turn right. Keep in mind what that looks like in Python.", + lambda: '
' + + '
' + + "Movement" + + "
my_van.turn_left()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.is_road_left()" + + "
my_van.at_destination()
" + + '
', +) + +(title_level1034, description_level1034, hint_level1034, commands_level1034) = ( + lambda: "The pond is nice but out of the way", + lambda: build_description( + title_level1034(), + "Can you find the shortest route? Don't take the scenic route.", + ), + lambda: "Just look for the simplest route to the house.", + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.is_road_right()" + + "
my_van.at_destination()
" + + '
', +) + +( + title_level1035, + description_level1035, + hint_level1035, +) = (lambda: title_level99(), lambda: description_level99(), lambda: hint_level99()) + +( + title_level1036, + description_level1036, + hint_level1036, +) = (lambda: title_level38(), lambda: description_level38(), lambda: hint_level38()) + +(title_level1037, description_level1037, hint_level1037, commands_level1037) = ( + lambda: title_level100(), + lambda: description_level100(), + lambda: hint_level100(), + lambda: commands_level100(), +) + +(title_level1038, description_level1038, hint_level1038, commands_level1038) = ( + lambda: title_level39(), + lambda: description_level39(), + lambda: hint_level39(), + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_around()" + + "
my_van.turn_right()
" + + '
' + + "Position" + + "
my_van.at_destination()" + + "
my_van.is_road_forward()" + + "
my_van.at_dead_end()
" + + '
' + + '
' + + '
' + + "

Animals" + + "
my_van.is_animal_crossing()" + + "
my_van.sound_horn()

" + + "
", +) + +(title_level1039, description_level1039, hint_level1039, commands_level1039) = ( + lambda: title_level47(), + lambda: description_level47(), + lambda: hint_level47(), + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()
" + + '
' + + "Position" + + "
my_van.at_destination()" + + "
my_van.is_road_forward()
" + + '
' + + '
' + + '
' + + "

Animals" + + "
my_van.is_animal_crossing()" + + "
my_van.sound_horn()

" + + "
", +) + +(title_level1040, description_level1040, hint_level1040, commands_level1040) = ( + lambda: title_level48(), + lambda: description_level48(), + lambda: hint_level48(), + lambda: '
' + + '
' + + "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_around()" + + "
my_van.turn_left()" + + "
my_van.turn_right()" + + "
my_van.wait()
" + + '
' + + "Position" + + "
my_van.at_red_traffic_light()" + + "
my_van.at_destination()" + + "
my_van.is_road_forward()" + + "
my_van.is_road_left()" + + "
my_van.is_road_right()" + + "
my_van.at_dead_end()
" + + '
', +) + +( + title_level1041, + description_level1041, + hint_level1041, +) = (lambda: title_level83(), lambda: description_level83(), lambda: hint_level83()) + +(title_level1042, description_level1042, hint_level1042, commands_level1042) = ( + lambda: title_level95(), + lambda: description_level95(), + lambda: hint_level95(), + lambda: commands_level95(), +) + +(title_level1043, description_level1043, hint_level1043, commands_level1043) = ( + lambda: title_level96(), + lambda: description_level96(), + lambda: hint_level96(), + lambda: commands_level96(), +) + +( + title_level1044, + description_level1044, + hint_level1044, +) = ( + lambda: title_level84(), + lambda: description_level84(), + lambda: hint_level84(), +) + +(title_level1045, description_level1045, hint_level1045, commands_level1045) = ( + lambda: title_level97(), + lambda: description_level97(), + lambda: hint_level97(), + lambda: commands_level97(), +) + +(title_level1046, description_level1046, hint_level1046, commands_level1046) = ( + lambda: title_level106(), + lambda: description_level106(), + lambda: hint_level106(), + lambda: commands_level106(), +) + +(title_level1047, description_level1047, hint_level1047, commands_level1047) = ( + lambda: title_level107(), + lambda: description_level107(), + lambda: hint_level107(), + lambda: commands_level107(), +) + +(title_level1048, description_level1048, hint_level1048, commands_level1048) = ( + lambda: title_level108(), + lambda: description_level108(), + lambda: hint_level108(), + lambda: commands_level108(), +) + +(title_level1049, description_level1049, hint_level1049, commands_level1049) = ( + lambda: title_level109(), + lambda: description_level109(), + lambda: hint_level109(), + lambda: commands_level109(), +) + +( + title_level1050, + description_level1050, + hint_level1050, +) = (lambda: title_level61(), lambda: description_level61(), lambda: hint_level61()) + +( + title_level1051, + description_level1051, + hint_level1051, +) = (lambda: title_level62(), lambda: description_level62(), lambda: hint_level62()) + +(title_level1052, description_level1052, hint_level1052, commands_level1052) = ( + lambda: title_level63(), + lambda: description_level63(), + lambda: hint_level63(), + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", +) + +(title_level1053, description_level1053, hint_level1053, commands_level1053) = ( + lambda: title_level64(), + lambda: description_level64(), + lambda: hint_level64(), + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", +) + +(title_level1054, description_level1054, hint_level1054, commands_level1054) = ( + lambda: title_level65(), + lambda: description_level65(), + lambda: hint_level65(), + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", +) + +(title_level1055, description_level1055, hint_level1055, commands_level1055) = ( + lambda: title_level66(), + lambda: description_level66(), + lambda: hint_level66(), + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", +) + +(title_level1056, description_level1056, hint_level1056, commands_level1056) = ( + lambda: title_level67(), + lambda: description_level67(), + lambda: hint_level67(), + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", +) + +(title_level1057, description_level1057, hint_level1057, commands_level1057) = ( + lambda: "Have a go at procedures", + lambda: build_description(title_level1057(), "Try adding a procedure and watch what happens in Python."), + lambda: hint_level90(), + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", +) + +(title_level1058, description_level1058, hint_level1058, commands_level1058) = ( + lambda: title_level91(), + lambda: build_description(title_level1058(), "Try adding a procedure and watch what happens in Python."), + lambda: hint_level91(), + lambda: "Movement" + + "
my_van.move_forwards()" + + "
my_van.turn_left()" + + "
my_van.turn_right()", +) + +(title_level1059, description_level1059, hint_level1059, commands_level1059) = ( + lambda: title_level101(), + lambda: description_level101(), + lambda: hint_level101(), + lambda: commands_level101(), +) + +(title_level1060, description_level1060, hint_level1060, commands_level1060) = ( + lambda: title_level102(), + lambda: description_level102(), + lambda: hint_level102(), + lambda: commands_level102(), +) + # Episode titles def get_episode_title(episode_id): @@ -3040,9 +3646,16 @@ def get_episode_title(episode_id): 10: "Introduction to Python", 11: "Python", 12: "Counted Loops Using While", - 13: "Indeterminate While Loops - coming soon", + 13: "Indeterminate Loops - coming soon", 14: "Selection in a Loop - coming soon", 15: "For Loops - coming soon", + 16: "Output, Operators, and Data", + 17: "Variables, Input, and Casting", + 18: "Selection", + 19: "Complex Selection", + 20: "String Manipulation", + 21: "Lists", + 22: "Procedures", } return episode_titles[episode_id] diff --git a/game/migrations/0097_add_python_den_levels.py b/game/migrations/0097_add_python_den_levels.py new file mode 100644 index 000000000..3d74a00a0 --- /dev/null +++ b/game/migrations/0097_add_python_den_levels.py @@ -0,0 +1,1512 @@ +import json + +from django.apps.registry import Apps +from django.db import migrations, models +from game.level_management import set_decor_inner, set_blocks_inner + + +def add_python_den_levels(apps, schema_editor): + Level = apps.get_model("game", "Level") + Episode = apps.get_model("game", "Episode") + + episode13 = Episode.objects.get(pk=13) + episode14 = Episode.objects.get(pk=14) + episode15 = Episode.objects.get(pk=15) + episode20 = Episode.objects.get(pk=20) + episode21 = Episode.objects.get(pk=21) + episode22 = Episode.objects.get(pk=22) + + level1014 = Level( + name="1014", + episode=episode13, + character_name="Van", + default=True, + destinations="[[9,4]]", + model_solution="[10]", + origin='{"coordinate":[0,4],"direction":"E"}', + path='[{"coordinate":[0,4],"connectedNodes":[1]},{"coordinate":[1,4],"connectedNodes":[0,2]},{"coordinate":[2,4],"connectedNodes":[1,3]},{"coordinate":[3,4],"connectedNodes":[2,4]},{"coordinate":[4,4],"connectedNodes":[3,5]},{"coordinate":[5,4],"connectedNodes":[4,6]},{"coordinate":[6,4],"connectedNodes":[5,7]},{"coordinate":[7,4],"connectedNodes":[6,8]},{"coordinate":[8,4],"connectedNodes":[7,9]},{"coordinate":[9,4],"connectedNodes":[8]}]', + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="farm", + cows='[{"minCows":1,"maxCows":1,"potentialCoordinates":[{"x":2,"y":4},{"x":5,"y":4},{"x":7,"y":4}],"type":"WHITE"}]', + lesson="This is a nice long straight road, but there are cows about!", + hint="Make sure you sound the horn to get the cows off the road.", + ) + + level1015 = Level( + name="1015", + episode=episode13, + path='[{"coordinate":[5,0],"connectedNodes":[1]},{"coordinate":[5,1],"connectedNodes":[2,0]},{"coordinate":[4,1],"connectedNodes":[3,1]},{"coordinate":[4,2],"connectedNodes":[4,2]},{"coordinate":[4,3],"connectedNodes":[5,3]},{"coordinate":[4,4],"connectedNodes":[6,4]},{"coordinate":[3,4],"connectedNodes":[7,5]},{"coordinate":[3,5],"connectedNodes":[8,6]},{"coordinate":[3,6],"connectedNodes":[9,7]},{"coordinate":[3,7],"connectedNodes":[8]}]', + origin='{"coordinate":[5,0],"direction":"N"}', + destinations="[[3,7]]", + default=True, + model_solution="[11]", + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="farm", + character_name="Van", + lesson="There are some bends in this road. Be careful!", + hint="What do you need to count, how many times you move or how many times you move forwards?", + ) + + level1016 = Level( + name="1016", + episode=episode13, + path='[{"coordinate":[1,1],"connectedNodes":[1]},{"coordinate":[1,2],"connectedNodes":[2,0]},{"coordinate":[2,2],"connectedNodes":[1,3]},{"coordinate":[2,3],"connectedNodes":[4,2]},{"coordinate":[3,3],"connectedNodes":[3,5]},{"coordinate":[3,4],"connectedNodes":[6,4]},{"coordinate":[4,4],"connectedNodes":[5,7]},{"coordinate":[4,5],"connectedNodes":[8,6]},{"coordinate":[5,5],"connectedNodes":[7,9]},{"coordinate":[5,6],"connectedNodes":[10,8]},{"coordinate":[6,6],"connectedNodes":[9,11]},{"coordinate":[6,7],"connectedNodes":[12,10]},{"coordinate":[7,7],"connectedNodes":[11]}]', + cows='[{"minCows":1,"maxCows":1,"potentialCoordinates":[{"x":3,"y":3},{"x":5,"y":5},{"x":4,"y":4}],"type":"WHITE"}]', + origin='{"coordinate":[1,1],"direction":"N"}', + destinations="[[7,7]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="farm", + character_name="Van", + lesson="Oh no! The farmer seems to have let their cows out again. Be careful.", + hint="Look for a pattern here...", + ) + + level1017 = Level( + name="1017", + episode=episode13, + path='[{"coordinate":[7,0],"connectedNodes":[1]},{"coordinate":[7,1],"connectedNodes":[2,0]},{"coordinate":[6,1],"connectedNodes":[3,1]},{"coordinate":[6,2],"connectedNodes":[4,2]},{"coordinate":[6,3],"connectedNodes":[5,3]},{"coordinate":[6,4],"connectedNodes":[6,4]},{"coordinate":[5,4],"connectedNodes":[7,5]},{"coordinate":[5,5],"connectedNodes":[8,6]},{"coordinate":[5,6],"connectedNodes":[7]}]', + origin='{"coordinate":[7,0],"direction":"N"}', + destinations="[[5,6]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="grass", + character_name="Van", + lesson="Keep going, you're getting the hang of the Python code.", + hint="So you are going forward unless...?", + ) + + level1018 = Level( + name="1018", + episode=episode13, + path='[{"coordinate":[7,1],"connectedNodes":[1]},{"coordinate":[7,2],"connectedNodes":[2,0]},{"coordinate":[7,3],"connectedNodes":[3,1]},{"coordinate":[7,4],"connectedNodes":[4,2]},{"coordinate":[7,5],"connectedNodes":[5,3]},{"coordinate":[6,5],"connectedNodes":[6,4]},{"coordinate":[5,5],"connectedNodes":[7,5]},{"coordinate":[4,5],"connectedNodes":[8,6]},{"coordinate":[3,5],"connectedNodes":[9,7]},{"coordinate":[2,5],"connectedNodes":[8,10]},{"coordinate":[2,4],"connectedNodes":[9,11]},{"coordinate":[2,3],"connectedNodes":[10,12]},{"coordinate":[2,2],"connectedNodes":[11,13]},{"coordinate":[2,1],"connectedNodes":[12,14]},{"coordinate":[3,1],"connectedNodes":[13,15]},{"coordinate":[4,1],"connectedNodes":[14,16]},{"coordinate":[5,1],"connectedNodes":[15,17]},{"coordinate":[6,1],"connectedNodes":[16,18]},{"coordinate":[6,2],"connectedNodes":[19,17]},{"coordinate":[6,3],"connectedNodes":[20,18]},{"coordinate":[6,4],"connectedNodes":[21,19]},{"coordinate":[5,4],"connectedNodes":[22,20]},{"coordinate":[4,4],"connectedNodes":[23,21]},{"coordinate":[3,4],"connectedNodes":[22,24]},{"coordinate":[3,3],"connectedNodes":[23,25]},{"coordinate":[3,2],"connectedNodes":[24,26]},{"coordinate":[4,2],"connectedNodes":[25,27]},{"coordinate":[5,2],"connectedNodes":[26]}]', + origin='{"coordinate":[7,1],"direction":"N"}', + destinations="[[5,2]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="snow", + character_name="Van", + lesson="Oh dear, you might get a bit dizzy!", + hint="What are you counting here, straight roads or bends?", + ) + + level1019 = Level( + name="1019", + episode=episode13, + path='[{"coordinate":[9,3],"connectedNodes":[1]},{"coordinate":[8,3],"connectedNodes":[2,0]},{"coordinate":[7,3],"connectedNodes":[3,1,15]},{"coordinate":[7,4],"connectedNodes":[4,2]},{"coordinate":[6,4],"connectedNodes":[5,3]},{"coordinate":[5,4],"connectedNodes":[6,4,12]},{"coordinate":[4,4],"connectedNodes":[7,5]},{"coordinate":[3,4],"connectedNodes":[8,6]},{"coordinate":[3,5],"connectedNodes":[9,7]},{"coordinate":[2,5],"connectedNodes":[10,8,17]},{"coordinate":[1,5],"connectedNodes":[11,9]},{"coordinate":[0,5],"connectedNodes":[10]},{"coordinate":[5,3],"connectedNodes":[5,13]},{"coordinate":[5,2],"connectedNodes":[21,12,14]},{"coordinate":[6,2],"connectedNodes":[13,15]},{"coordinate":[7,2],"connectedNodes":[14,2,16]},{"coordinate":[7,1],"connectedNodes":[15]},{"coordinate":[2,4],"connectedNodes":[9,18]},{"coordinate":[2,3],"connectedNodes":[17,19]},{"coordinate":[2,2],"connectedNodes":[18,20]},{"coordinate":[3,2],"connectedNodes":[19,21]},{"coordinate":[4,2],"connectedNodes":[20,13]}]', + origin='{"coordinate":[9,3],"direction":"W"}', + destinations="[[0,5]]", + default=True, + model_solution="[11]", + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="grass", + character_name="Van", + lesson="Have you noticed that there are more roads ahead than turns? Try checking if there is a road ahead and then otherwise making the turns you need...", + hint="Remember to use if..else", + ) + + level1020 = Level( + name="1020", + episode=episode13, + path='[{"coordinate":[2,2],"connectedNodes":[1]},{"coordinate":[3,2],"connectedNodes":[0,2,19]},{"coordinate":[3,3],"connectedNodes":[10,3,1]},{"coordinate":[4,3],"connectedNodes":[2,4]},{"coordinate":[4,4],"connectedNodes":[5,3]},{"coordinate":[5,4],"connectedNodes":[4,6,17]},{"coordinate":[5,5],"connectedNodes":[7,5]},{"coordinate":[6,5],"connectedNodes":[6,8]},{"coordinate":[6,6],"connectedNodes":[9,7]},{"coordinate":[7,6],"connectedNodes":[8]},{"coordinate":[3,4],"connectedNodes":[11,2]},{"coordinate":[3,5],"connectedNodes":[12,10]},{"coordinate":[3,6],"connectedNodes":[13,11]},{"coordinate":[3,7],"connectedNodes":[14,12]},{"coordinate":[4,7],"connectedNodes":[13,15]},{"coordinate":[5,7],"connectedNodes":[14,16]},{"coordinate":[6,7],"connectedNodes":[15]},{"coordinate":[5,3],"connectedNodes":[5,18]},{"coordinate":[5,2],"connectedNodes":[19,17]},{"coordinate":[4,2],"connectedNodes":[1,18]}]', + origin='{"coordinate":[2,2],"direction":"E"}', + destinations="[[7,6]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="snow", + character_name="Van", + lesson="Use if..else in Python for this level", + hint="Don't get distracted by the other roads. Look for a pattern you can repeat.", + ) + + level1021 = Level( + name="1021", + episode=episode13, + path='[{"coordinate":[4,0],"connectedNodes":[1]},{"coordinate":[4,1],"connectedNodes":[2,0]},{"coordinate":[3,1],"connectedNodes":[3,1]},{"coordinate":[3,2],"connectedNodes":[4,2]},{"coordinate":[3,3],"connectedNodes":[5,3]},{"coordinate":[3,4],"connectedNodes":[6,4]},{"coordinate":[2,4],"connectedNodes":[7,5]},{"coordinate":[2,5],"connectedNodes":[8,6]},{"coordinate":[2,6],"connectedNodes":[9,7]},{"coordinate":[1,6],"connectedNodes":[10,8]},{"coordinate":[1,7],"connectedNodes":[9]}]', + origin='{"coordinate":[4,0],"direction":"N"}', + destinations="[[3,1],[2,4],[1,6],[1,7]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="grass", + character_name="Van", + lesson="This is a really busy road. Make sure that you don't miss any of the houses.", + hint="Did you get the last house? Think about what value the loop counter will have at that point in your code...", + ) + + level1022 = Level( + name="1022", + episode=episode13, + path='[{"coordinate":[2,3],"connectedNodes":[1]},{"coordinate":[2,2],"connectedNodes":[0,2,16]},{"coordinate":[3,2],"connectedNodes":[1,3]},{"coordinate":[3,1],"connectedNodes":[2,4,14]},{"coordinate":[4,1],"connectedNodes":[3,5]},{"coordinate":[5,1],"connectedNodes":[4,6,22]},{"coordinate":[5,2],"connectedNodes":[7,5]},{"coordinate":[6,2],"connectedNodes":[6,8]},{"coordinate":[6,3],"connectedNodes":[9,17,7]},{"coordinate":[6,4],"connectedNodes":[10,8]},{"coordinate":[5,4],"connectedNodes":[11,9]},{"coordinate":[5,5],"connectedNodes":[12,10]},{"coordinate":[4,5],"connectedNodes":[13,11]},{"coordinate":[3,5],"connectedNodes":[12]},{"coordinate":[3,0],"connectedNodes":[15,3]},{"coordinate":[2,0],"connectedNodes":[16,14]},{"coordinate":[2,1],"connectedNodes":[1,15]},{"coordinate":[7,3],"connectedNodes":[8,18]},{"coordinate":[8,3],"connectedNodes":[17,19]},{"coordinate":[8,2],"connectedNodes":[18,20]},{"coordinate":[8,1],"connectedNodes":[21,19]},{"coordinate":[7,1],"connectedNodes":[22,20]},{"coordinate":[6,1],"connectedNodes":[5,21]}]', + origin='{"coordinate":[2,3],"direction":"S"}', + destinations="[[3,5]]", + default=True, + model_solution="[12]", + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="grass", + character_name="Van", + lesson="There are lots of turns here, don't get distracted.", + hint="Think about the order of the questions you ask using your if and elif statements.", + ) + + level1023 = Level( + name="1023", + episode=episode13, + path='[{"coordinate":[2,7],"connectedNodes":[1]},{"coordinate":[2,6],"connectedNodes":[0,2]},{"coordinate":[2,5],"connectedNodes":[1,28,3]},{"coordinate":[2,4],"connectedNodes":[2,4]},{"coordinate":[2,3],"connectedNodes":[3,5]},{"coordinate":[2,2],"connectedNodes":[4,6]},{"coordinate":[2,1],"connectedNodes":[5,7]},{"coordinate":[3,1],"connectedNodes":[6,8]},{"coordinate":[4,1],"connectedNodes":[7,9]},{"coordinate":[5,1],"connectedNodes":[8,10]},{"coordinate":[6,1],"connectedNodes":[9,11]},{"coordinate":[7,1],"connectedNodes":[10,12]},{"coordinate":[8,1],"connectedNodes":[11,13]},{"coordinate":[9,1],"connectedNodes":[12,14]},{"coordinate":[9,2],"connectedNodes":[15,13]},{"coordinate":[9,3],"connectedNodes":[16,14]},{"coordinate":[9,4],"connectedNodes":[17,15]},{"coordinate":[9,5],"connectedNodes":[18,16]},{"coordinate":[9,6],"connectedNodes":[19,17]},{"coordinate":[8,6],"connectedNodes":[20,18]},{"coordinate":[7,6],"connectedNodes":[21,19]},{"coordinate":[6,6],"connectedNodes":[22,20]},{"coordinate":[5,6],"connectedNodes":[23,21]},{"coordinate":[4,6],"connectedNodes":[22,24]},{"coordinate":[4,5],"connectedNodes":[28,23,25]},{"coordinate":[4,4],"connectedNodes":[24,26]},{"coordinate":[4,3],"connectedNodes":[25,27]},{"coordinate":[4,2],"connectedNodes":[26]},{"coordinate":[3,5],"connectedNodes":[2,24]}]', + origin='{"coordinate":[2,7],"direction":"S"}', + destinations="[[4,2]]", + default=True, + model_solution="[12]", + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="farm", + character_name="Van", + lesson="Don't go the long way around!", + hint="Think carefully about the order in which you ask questions in your if..else if block", + ) + + level1024 = Level( + name="1024", + episode=episode13, + path='[{"coordinate":[7,0],"connectedNodes":[1]},{"coordinate":[7,1],"connectedNodes":[10,2,0]},{"coordinate":[7,2],"connectedNodes":[3,24,1]},{"coordinate":[7,3],"connectedNodes":[4,2]},{"coordinate":[6,3],"connectedNodes":[5,3]},{"coordinate":[6,4],"connectedNodes":[23,6,33,4]},{"coordinate":[6,5],"connectedNodes":[7,5]},{"coordinate":[6,6],"connectedNodes":[8,6]},{"coordinate":[5,6],"connectedNodes":[9,7]},{"coordinate":[5,7],"connectedNodes":[8]},{"coordinate":[6,1],"connectedNodes":[11,1]},{"coordinate":[5,1],"connectedNodes":[12,10]},{"coordinate":[4,1],"connectedNodes":[13,11]},{"coordinate":[3,1],"connectedNodes":[14,12]},{"coordinate":[2,1],"connectedNodes":[15,13]},{"coordinate":[1,1],"connectedNodes":[16,17,14]},{"coordinate":[0,1],"connectedNodes":[15]},{"coordinate":[1,2],"connectedNodes":[18,15]},{"coordinate":[1,3],"connectedNodes":[19,17]},{"coordinate":[1,4],"connectedNodes":[20,18]},{"coordinate":[2,4],"connectedNodes":[19,21]},{"coordinate":[3,4],"connectedNodes":[20,22]},{"coordinate":[4,4],"connectedNodes":[21,23]},{"coordinate":[5,4],"connectedNodes":[22,5]},{"coordinate":[8,2],"connectedNodes":[2,25]},{"coordinate":[9,2],"connectedNodes":[24,26]},{"coordinate":[9,3],"connectedNodes":[27,25]},{"coordinate":[9,4],"connectedNodes":[28,26]},{"coordinate":[9,5],"connectedNodes":[29,27]},{"coordinate":[9,6],"connectedNodes":[30,28]},{"coordinate":[8,6],"connectedNodes":[29,31]},{"coordinate":[8,5],"connectedNodes":[30,32]},{"coordinate":[8,4],"connectedNodes":[33,31]},{"coordinate":[7,4],"connectedNodes":[5,32]}]', + origin='{"coordinate":[7,0],"direction":"N"}', + destinations="[[5,7]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="farm", + character_name="Van", + lesson="Look carefully for the shortest route.", + hint="Think carefully about the order in which you ask questions in your if..elif statements.", + ) + + level1025 = Level( + name="1025", + episode=episode13, + path='[{"coordinate":[8,0],"connectedNodes":[1]},{"coordinate":[8,1],"connectedNodes":[2,0]},{"coordinate":[8,2],"connectedNodes":[3,1]},{"coordinate":[7,2],"connectedNodes":[4,2]},{"coordinate":[6,2],"connectedNodes":[12,5,3]},{"coordinate":[6,3],"connectedNodes":[25,4]},{"coordinate":[4,5],"connectedNodes":[7,19]},{"coordinate":[3,5],"connectedNodes":[8,6]},{"coordinate":[2,5],"connectedNodes":[9,7]},{"coordinate":[1,5],"connectedNodes":[10,8,18]},{"coordinate":[1,6],"connectedNodes":[11,9]},{"coordinate":[1,7],"connectedNodes":[10]},{"coordinate":[5,2],"connectedNodes":[13,4]},{"coordinate":[4,2],"connectedNodes":[14,12]},{"coordinate":[3,2],"connectedNodes":[15,13]},{"coordinate":[2,2],"connectedNodes":[16,14]},{"coordinate":[1,2],"connectedNodes":[17,15]},{"coordinate":[1,3],"connectedNodes":[18,16]},{"coordinate":[1,4],"connectedNodes":[9,17]},{"coordinate":[5,5],"connectedNodes":[6,20]},{"coordinate":[6,5],"connectedNodes":[19,21]},{"coordinate":[7,5],"connectedNodes":[20,22]},{"coordinate":[8,5],"connectedNodes":[21,23]},{"coordinate":[8,4],"connectedNodes":[24,22]},{"coordinate":[7,4],"connectedNodes":[25,23]},{"coordinate":[6,4],"connectedNodes":[24,5]}]', + traffic_lights='[{"redDuration":3,"greenDuration":3,"sourceCoordinate":{"x":4,"y":5},"direction":"W","startTime":0,"startingState":"RED"},{"redDuration":3,"greenDuration":3,"sourceCoordinate":{"x":1,"y":5},"direction":"N","startTime":0,"startingState":"RED"}]', + origin='{"coordinate":[8,0],"direction":"N"}', + destinations="[[1,7]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="grass", + character_name="Van", + lesson="Look carefully for the shortest route.", + hint="Think carefully about the order in which you ask questions in your if..elif statements. Don't forget the traffic lights.", + ) + + level1026 = Level.objects.get(name="85", default=True) + level1026.pk = None + level1026._state.adding = True + level1026.name = "1026" + level1026.model_solution = "[4]" + level1026.disable_algorithm_score = False + level1026.episode = episode14 + + level1027 = Level( + name="1027", + episode=episode14, + path='[{"coordinate":[0,3],"connectedNodes":[1]},{"coordinate":[1,3],"connectedNodes":[0,2]},{"coordinate":[2,3],"connectedNodes":[1,3]},{"coordinate":[3,3],"connectedNodes":[2,4]},{"coordinate":[4,3],"connectedNodes":[3,5]},{"coordinate":[5,3],"connectedNodes":[4,6]},{"coordinate":[6,3],"connectedNodes":[5,7]},{"coordinate":[7,3],"connectedNodes":[6,8]},{"coordinate":[8,3],"connectedNodes":[7]}]', + origin='{"coordinate":[0,3],"direction":"E"}', + destinations="[[8,3]]", + default=True, + model_solution="[4]", + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="grass", + character_name="Van", + lesson="Just keep going until you get there...", + hint="You might find that the solution to this level is quite familiar...", + ) + + level1028 = Level( + name="1028", + episode=episode14, + path='[{"coordinate":[2,2],"connectedNodes":[1]},{"coordinate":[3,2],"connectedNodes":[0,2]},{"coordinate":[3,3],"connectedNodes":[3,1]},{"coordinate":[4,3],"connectedNodes":[2,4]},{"coordinate":[4,4],"connectedNodes":[5,3]},{"coordinate":[5,4],"connectedNodes":[4,6]},{"coordinate":[5,5],"connectedNodes":[7,5]},{"coordinate":[6,5],"connectedNodes":[6,8]},{"coordinate":[6,6],"connectedNodes":[9,7]},{"coordinate":[7,6],"connectedNodes":[8]}]', + origin='{"coordinate":[2,2],"direction":"E"}', + destinations="[[7,6]]", + default=True, + model_solution="[5]", + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="grass", + character_name="Van", + lesson="Well done, you did it! Now have a go at using the Repeat until block on a road with lots of turns.", + hint="This is another route you have seen before. Last time you counted how many times your instructions were repeated. This time, your program is going to repeat your commands until you reach the destination. What do you need to repeat?", + ) + + level1029 = Level.objects.get(name="119", default=True) + level1029.pk = None + level1029._state.adding = True + level1029.name = "1029" + level1029.blocklyEnabled = True + level1029.pythonEnabled = False + level1029.pythonViewEnabled = True + level1029.model_solution = "[7]" + level1029.disable_algorithm_score = False + level1029.episode = episode14 + + level1030 = Level.objects.get(name="84", default=True) + level1030.pk = None + level1030._state.adding = True + level1030.name = "1030" + level1030.blocklyEnabled = False + level1030.pythonEnabled = True + level1030.pythonViewEnabled = False + level1030.model_solution = "[]" + level1030.disable_algorithm_score = True + level1030.episode = episode14 + + level1031 = Level.objects.get(name="34", default=True) + level1031.pk = None + level1031._state.adding = True + level1031.name = "1031" + level1031.blocklyEnabled = True + level1031.pythonEnabled = False + level1031.pythonViewEnabled = True + level1031.model_solution = "[7]" + level1031.disable_algorithm_score = False + level1031.episode = episode14 + + level1032 = Level( + name="1032", + episode=episode14, + path='[{"coordinate":[5,0],"connectedNodes":[1]},{"coordinate":[5,1],"connectedNodes":[2,0]},{"coordinate":[5,2],"connectedNodes":[3,23,1]},{"coordinate":[5,3],"connectedNodes":[4,2]},{"coordinate":[5,4],"connectedNodes":[17,3]},{"coordinate":[4,5],"connectedNodes":[6,17]},{"coordinate":[3,5],"connectedNodes":[7,5]},{"coordinate":[2,5],"connectedNodes":[24,6,8]},{"coordinate":[2,4],"connectedNodes":[7,9]},{"coordinate":[2,3],"connectedNodes":[8,10]},{"coordinate":[2,2],"connectedNodes":[9,11]},{"coordinate":[2,1],"connectedNodes":[10,12]},{"coordinate":[3,1],"connectedNodes":[11,13]},{"coordinate":[4,1],"connectedNodes":[12,14]},{"coordinate":[4,2],"connectedNodes":[15,13]},{"coordinate":[4,3],"connectedNodes":[16,14]},{"coordinate":[4,4],"connectedNodes":[15]},{"coordinate":[5,5],"connectedNodes":[5,29,18,4]},{"coordinate":[6,5],"connectedNodes":[17,19]},{"coordinate":[7,5],"connectedNodes":[18,20]},{"coordinate":[7,4],"connectedNodes":[19,21]},{"coordinate":[7,3],"connectedNodes":[20,22]},{"coordinate":[7,2],"connectedNodes":[23,21,36]},{"coordinate":[6,2],"connectedNodes":[2,22]},{"coordinate":[1,5],"connectedNodes":[25,7]},{"coordinate":[1,6],"connectedNodes":[26,24]},{"coordinate":[2,6],"connectedNodes":[25,27]},{"coordinate":[3,6],"connectedNodes":[26,28]},{"coordinate":[4,6],"connectedNodes":[27,29]},{"coordinate":[5,6],"connectedNodes":[28,30,17]},{"coordinate":[6,6],"connectedNodes":[29,31]},{"coordinate":[7,6],"connectedNodes":[30,32]},{"coordinate":[8,6],"connectedNodes":[31,33]},{"coordinate":[8,5],"connectedNodes":[32,34]},{"coordinate":[8,4],"connectedNodes":[33,35]},{"coordinate":[8,3],"connectedNodes":[34,36]},{"coordinate":[8,2],"connectedNodes":[22,35]}]', + origin='{"coordinate":[5,0],"direction":"N"}', + destinations="[[4,4]]", + default=True, + model_solution="[7]", + pythonEnabled=False, + pythonViewEnabled=True, + theme_name="grass", + character_name="Van", + lesson="You don't have a right turn block here, so plan your route carefully.", + hint="Think carefully about the order in which you ask questions in your if-statement here...", + ) + + level1033 = Level( + name="1033", + episode=episode14, + path='[{"coordinate":[7,1],"connectedNodes":[1]},{"coordinate":[7,2],"connectedNodes":[2,0]},{"coordinate":[6,2],"connectedNodes":[3,1]},{"coordinate":[6,3],"connectedNodes":[4,13,2]},{"coordinate":[5,3],"connectedNodes":[5,3]},{"coordinate":[5,4],"connectedNodes":[6,16,15,4]},{"coordinate":[4,4],"connectedNodes":[7,5]},{"coordinate":[4,5],"connectedNodes":[8,16,6]},{"coordinate":[3,5],"connectedNodes":[9,7]},{"coordinate":[3,6],"connectedNodes":[10,8]},{"coordinate":[2,6],"connectedNodes":[11,9]},{"coordinate":[2,7],"connectedNodes":[12,17,10]},{"coordinate":[1,7],"connectedNodes":[11]},{"coordinate":[7,3],"connectedNodes":[3,14]},{"coordinate":[7,4],"connectedNodes":[15,13]},{"coordinate":[6,4],"connectedNodes":[5,22,14]},{"coordinate":[5,5],"connectedNodes":[7,5]},{"coordinate":[3,7],"connectedNodes":[11,18]},{"coordinate":[4,7],"connectedNodes":[17,19]},{"coordinate":[5,7],"connectedNodes":[18,20]},{"coordinate":[6,7],"connectedNodes":[19,21]},{"coordinate":[6,6],"connectedNodes":[20,22]},{"coordinate":[6,5],"connectedNodes":[21,15]}]', + origin='{"coordinate":[7,1],"direction":"N"}', + destinations="[[1,7]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="snow", + character_name="Van", + lesson="Can you find the shortest route?", + hint="In this level, you want to check for a left turn first. If there is no left turn, turn right. Keep in mind what that looks like in Python.", + ) + + level1034 = Level( + name="1034", + episode=episode14, + path='[{"coordinate":[0,6],"connectedNodes":[1]},{"coordinate":[1,6],"connectedNodes":[0,2]},{"coordinate":[2,6],"connectedNodes":[1,3]},{"coordinate":[3,6],"connectedNodes":[2,4]},{"coordinate":[4,6],"connectedNodes":[3,5]},{"coordinate":[5,6],"connectedNodes":[4,6]},{"coordinate":[5,5],"connectedNodes":[5,23,7]},{"coordinate":[5,4],"connectedNodes":[6,8]},{"coordinate":[5,3],"connectedNodes":[7,29,9]},{"coordinate":[5,2],"connectedNodes":[8,10]},{"coordinate":[5,1],"connectedNodes":[11,9]},{"coordinate":[4,1],"connectedNodes":[12,10]},{"coordinate":[3,1],"connectedNodes":[13,11]},{"coordinate":[2,1],"connectedNodes":[14,12]},{"coordinate":[1,1],"connectedNodes":[15,13]},{"coordinate":[1,2],"connectedNodes":[34,16,14]},{"coordinate":[1,3],"connectedNodes":[17,15]},{"coordinate":[1,4],"connectedNodes":[30,16]},{"coordinate":[2,5],"connectedNodes":[30,19]},{"coordinate":[3,5],"connectedNodes":[18,20]},{"coordinate":[3,4],"connectedNodes":[19,21]},{"coordinate":[3,3],"connectedNodes":[20,22]},{"coordinate":[3,2],"connectedNodes":[21]},{"coordinate":[6,5],"connectedNodes":[6,24]},{"coordinate":[7,5],"connectedNodes":[23,25]},{"coordinate":[8,5],"connectedNodes":[24,26]},{"coordinate":[8,4],"connectedNodes":[25,27]},{"coordinate":[8,3],"connectedNodes":[28,26]},{"coordinate":[7,3],"connectedNodes":[29,27]},{"coordinate":[6,3],"connectedNodes":[8,28]},{"coordinate":[1,5],"connectedNodes":[31,18,17]},{"coordinate":[0,5],"connectedNodes":[30,32]},{"coordinate":[0,4],"connectedNodes":[31,33]},{"coordinate":[0,3],"connectedNodes":[32,34]},{"coordinate":[0,2],"connectedNodes":[33,15]}]', + origin='{"coordinate":[0,6],"direction":"E"}', + destinations="[[3,2]]", + default=True, + disable_algorithm_score=True, + blocklyEnabled=False, + theme_name="grass", + character_name="Van", + lesson="Can you find the shortest route? Don't take the scenic route.", + hint="Just look for the simplest route to the house.", + ) + + level1035 = Level.objects.get(name="99", default=True) + level1035.pk = None + level1035._state.adding = True + level1035.name = "1035" + level1035.blocklyEnabled = True + level1035.pythonEnabled = False + level1035.pythonViewEnabled = True + level1035.model_solution = "[9]" + level1035.disable_algorithm_score = False + level1035.episode = episode14 + + level1036 = Level.objects.get(name="38", default=True) + level1036.pk = None + level1036._state.adding = True + level1036.name = "1036" + level1036.pythonViewEnabled = True + level1036.model_solution = "[11]" + level1036.disable_algorithm_score = False + level1036.episode = episode14 + + level1037 = Level.objects.get(name="100", default=True) + level1037.pk = None + level1037._state.adding = True + level1037.name = "1037" + level1037.episode = episode14 + + level1038 = Level.objects.get(name="39", default=True) + level1038.pk = None + level1038._state.adding = True + level1038.name = "1038" + level1038.blocklyEnabled = False + level1038.pythonEnabled = True + level1038.model_solution = "[]" + level1038.disable_route_score = False + level1038.disable_algorithm_score = True + level1038.episode = episode14 + + level1039 = Level.objects.get(name="47", default=True) + level1039.pk = None + level1039._state.adding = True + level1039.name = "1039" + level1039.blocklyEnabled = False + level1039.pythonEnabled = True + level1039.model_solution = "[]" + level1039.disable_algorithm_score = True + level1039.episode = episode14 + + level1040 = Level.objects.get(name="48", default=True) + level1040.pk = None + level1040._state.adding = True + level1040.name = "1040" + level1040.blocklyEnabled = False + level1040.pythonEnabled = True + level1040.model_solution = "[]" + level1040.disable_algorithm_score = True + level1040.episode = episode14 + + level1041 = Level.objects.get(name="83", default=True) + level1041.pk = None + level1041._state.adding = True + level1041.name = "1041" + level1041.disable_algorithm_score = False + level1041.episode = episode15 + + level1042 = Level.objects.get(name="95", default=True) + level1042.pk = None + level1042._state.adding = True + level1042.name = "1042" + level1042.episode = episode15 + + level1043 = Level.objects.get(name="96", default=True) + level1043.pk = None + level1043._state.adding = True + level1043.name = "1043" + level1043.episode = episode15 + + level1044 = Level.objects.get(name="84", default=True) + level1044.pk = None + level1044._state.adding = True + level1044.name = "1044" + level1044.disable_algorithm_score = False + level1044.episode = episode15 + + level1045 = Level.objects.get(name="97", default=True) + level1045.pk = None + level1045._state.adding = True + level1045.name = "1045" + level1045.episode = episode15 + + level1046 = Level.objects.get(name="106", default=True) + level1046.pk = None + level1046._state.adding = True + level1046.name = "1046" + level1046.episode = episode15 + + level1047 = Level.objects.get(name="107", default=True) + level1047.pk = None + level1047._state.adding = True + level1047.name = "1047" + level1047.episode = episode15 + + level1048 = Level.objects.get(name="108", default=True) + level1048.pk = None + level1048._state.adding = True + level1048.name = "1048" + level1048.episode = episode15 + + level1049 = Level.objects.get(name="109", default=True) + level1049.pk = None + level1049._state.adding = True + level1049.name = "1049" + level1049.episode = episode15 + + level1050 = Level.objects.get(name="61", default=True) + level1050.pk = None + level1050._state.adding = True + level1050.name = "1050" + level1050.pythonViewEnabled = True + level1050.disable_algorithm_score = False + level1050.episode = episode22 + + level1051 = Level.objects.get(name="62", default=True) + level1051.pk = None + level1051._state.adding = True + level1051.name = "1051" + level1051.pythonViewEnabled = True + level1051.disable_algorithm_score = False + level1051.episode = episode22 + + level1052 = Level.objects.get(name="63", default=True) + level1052.pk = None + level1052._state.adding = True + level1052.name = "1052" + level1052.blocklyEnabled = False + level1052.pythonEnabled = True + level1052.model_solution = "[]" + level1052.disable_algorithm_score = True + level1052.episode = episode22 + + level1053 = Level.objects.get(name="64", default=True) + level1053.pk = None + level1053._state.adding = True + level1053.name = "1053" + level1053.blocklyEnabled = False + level1053.pythonEnabled = True + level1053.model_solution = "[]" + level1053.disable_algorithm_score = True + level1053.episode = episode22 + + level1054 = Level.objects.get(name="65", default=True) + level1054.pk = None + level1054._state.adding = True + level1054.name = "1054" + level1054.blocklyEnabled = False + level1054.pythonEnabled = True + level1054.model_solution = "[]" + level1054.disable_algorithm_score = True + level1054.episode = episode22 + + level1055 = Level.objects.get(name="66", default=True) + level1055.pk = None + level1055._state.adding = True + level1055.name = "1055" + level1055.blocklyEnabled = False + level1055.pythonEnabled = True + level1055.model_solution = "[]" + level1055.disable_algorithm_score = True + level1055.episode = episode22 + + level1056 = Level.objects.get(name="67", default=True) + level1056.pk = None + level1056._state.adding = True + level1056.name = "1056" + level1056.blocklyEnabled = False + level1056.pythonEnabled = True + level1056.model_solution = "[]" + level1056.disable_algorithm_score = True + level1056.episode = episode22 + + level1057 = Level.objects.get(name="90", default=True) + level1057.pk = None + level1057._state.adding = True + level1057.name = "1057" + level1057.blocklyEnabled = False + level1057.pythonViewEnabled = False + level1057.pythonEnabled = True + level1057.disable_algorithm_score = True + level1057.episode = episode22 + + level1058 = Level.objects.get(name="91", default=True) + level1058.pk = None + level1058._state.adding = True + level1058.name = "1058" + level1058.blocklyEnabled = False + level1058.pythonViewEnabled = False + level1058.pythonEnabled = True + level1058.disable_algorithm_score = True + level1058.episode = episode22 + + level1059 = Level.objects.get(name="101", default=True) + level1059.pk = None + level1059._state.adding = True + level1059.name = "1059" + level1059.episode = episode22 + + level1060 = Level.objects.get(name="102", default=True) + level1060.pk = None + level1060._state.adding = True + level1060.name = "1060" + level1060.episode = episode22 + + def save_all_levels(): + level1014.save() + level1015.save() + level1016.save() + level1017.save() + level1018.save() + level1019.save() + level1020.save() + level1021.save() + level1022.save() + level1023.save() + level1024.save() + level1025.save() + level1026.save() + level1027.save() + level1028.save() + level1029.save() + level1030.save() + level1031.save() + level1032.save() + level1033.save() + level1034.save() + level1035.save() + level1036.save() + level1037.save() + level1038.save() + level1039.save() + level1040.save() + level1041.save() + level1042.save() + level1043.save() + level1044.save() + level1045.save() + level1046.save() + level1047.save() + level1048.save() + level1049.save() + level1050.save() + level1051.save() + level1052.save() + level1053.save() + level1054.save() + level1055.save() + level1056.save() + level1057.save() + level1058.save() + level1059.save() + level1060.save() + + save_all_levels() + level1014.next_level = level1015 + level1015.next_level = level1016 + level1016.next_level = level1017 + level1017.next_level = level1018 + level1018.next_level = level1019 + level1019.next_level = level1020 + level1020.next_level = level1021 + level1021.next_level = level1022 + level1022.next_level = level1023 + level1023.next_level = level1024 + level1024.next_level = level1025 + level1025.next_level = level1026 + level1026.next_level = level1027 + level1027.next_level = level1028 + level1028.next_level = level1029 + level1029.next_level = level1030 + level1030.next_level = level1031 + level1031.next_level = level1032 + level1032.next_level = level1033 + level1033.next_level = level1034 + level1034.next_level = level1035 + level1035.next_level = level1036 + level1036.next_level = level1037 + level1037.next_level = level1038 + level1038.next_level = level1039 + level1039.next_level = level1040 + level1040.next_level = level1041 + level1041.next_level = level1042 + level1042.next_level = level1043 + level1043.next_level = level1044 + level1044.next_level = level1045 + level1045.next_level = level1046 + level1046.next_level = level1047 + level1047.next_level = level1048 + level1048.next_level = level1049 + level1049.next_level = level1050 + level1050.next_level = level1051 + level1051.next_level = level1052 + level1052.next_level = level1053 + level1053.next_level = level1054 + level1054.next_level = level1055 + level1055.next_level = level1056 + level1056.next_level = level1057 + level1057.next_level = level1058 + level1058.next_level = level1059 + level1059.next_level = level1060 + level1060.next_level = None + + save_all_levels() + + +def delete_python_den_levels(apps, schema_editor): + Level = apps.get_model("game", "Level") + Level.objects.filter(name__in=range(1014, 1061)).delete() + + +def add_python_den_blocks(apps, schema_editor): + Level = apps.get_model("game", "Level") + LevelBlock = apps.get_model("game", "LevelBlock") + Block = apps.get_model("game", "Block") + + def set_blocks(level, blocks): + set_blocks_inner(level, blocks, LevelBlock, Block) + + level1014 = Level.objects.get(name="1014", default=True) + level1015 = Level.objects.get(name="1015", default=True) + level1019 = Level.objects.get(name="1019", default=True) + level1022 = Level.objects.get(name="1022", default=True) + level1023 = Level.objects.get(name="1023", default=True) + level1026 = Level.objects.get(name="1026", default=True) + level1027 = Level.objects.get(name="1027", default=True) + level1028 = Level.objects.get(name="1028", default=True) + level1029 = Level.objects.get(name="1029", default=True) + level1031 = Level.objects.get(name="1031", default=True) + level1032 = Level.objects.get(name="1032", default=True) + level1035 = Level.objects.get(name="1035", default=True) + level1036 = Level.objects.get(name="1036", default=True) + level1041 = Level.objects.get(name="1041", default=True) + level1044 = Level.objects.get(name="1044", default=True) + level1050 = Level.objects.get(name="1050", default=True) + level1051 = Level.objects.get(name="1051", default=True) + level1057 = Level.objects.get(name="1057", default=True) + level1058 = Level.objects.get(name="1058", default=True) + + set_blocks( + level1014, + json.loads( + '[{"type": "variables_numeric_set"},' + + '{"type": "controls_repeat_while"},' + + '{"type": "variables_get"},' + + '{"type": "math_number"},' + + '{"type": "logic_compare"},' + + '{"type": "controls_if"},' + + '{"type": "cow_crossing"},' + + '{"type": "sound_horn"},' + + '{"type": "move_forwards"},' + + '{"type": "variables_increment"}]' + ), + ) + + set_blocks( + level1015, + json.loads( + '[{"type": "variables_numeric_set"},' + + '{"type": "controls_repeat_while"},' + + '{"type": "variables_get"},' + + '{"type": "math_number"},' + + '{"type": "logic_compare"},' + + '{"type": "controls_if"},' + + '{"type": "road_exists"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "move_forwards"},' + + '{"type": "variables_increment"}]' + ), + ) + + set_blocks( + level1019, + json.loads( + '[{"type": "variables_numeric_set"},' + + '{"type": "controls_repeat_while"},' + + '{"type": "variables_get"},' + + '{"type": "math_number"},' + + '{"type": "logic_compare"},' + + '{"type": "controls_if"},' + + '{"type": "road_exists"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "move_forwards"},' + + '{"type": "variables_increment"}]' + ), + ) + + set_blocks( + level1022, + json.loads( + '[{"type": "variables_numeric_set"},' + + '{"type": "controls_repeat_while"},' + + '{"type": "variables_get"},' + + '{"type": "math_number"},' + + '{"type": "logic_compare"},' + + '{"type": "controls_if"},' + + '{"type": "road_exists"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "move_forwards"},' + + '{"type": "variables_increment"}]' + ), + ) + + set_blocks( + level1023, + json.loads( + '[{"type": "variables_numeric_set"},' + + '{"type": "controls_repeat_while"},' + + '{"type": "variables_get"},' + + '{"type": "math_number"},' + + '{"type": "logic_compare"},' + + '{"type": "controls_if"},' + + '{"type": "road_exists"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "move_forwards"},' + + '{"type": "variables_increment"}]' + ), + ) + + set_blocks( + level1026, + json.loads( + '[{"type": "move_forwards"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "at_destination"},' + + '{"type": "logic_negate"},' + + '{"type": "controls_repeat_while"}]' + ), + ) + + set_blocks( + level1027, + json.loads( + '[{"type": "controls_repeat_while"},' + + '{"type": "logic_negate"},' + + '{"type": "at_destination"},' + + '{"type": "move_forwards"}]' + ), + ) + + set_blocks( + level1028, + json.loads( + '[{"type": "controls_repeat_while"},' + + '{"type": "logic_negate"},' + + '{"type": "at_destination"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"}]' + ), + ) + + set_blocks( + level1029, + json.loads( + '[{"type": "controls_repeat_while"},' + + '{"type": "logic_negate"},' + + '{"type": "at_destination"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "move_forwards"}]' + ), + ) + + set_blocks( + level1031, + json.loads( + '[{"type": "controls_repeat_while"},' + + '{"type": "logic_negate"},' + + '{"type": "at_destination"},' + + '{"type": "controls_if"},' + + '{"type": "road_exists"},' + + '{"type": "turn_left"},' + + '{"type": "move_forwards"}]' + ), + ) + + set_blocks( + level1032, + json.loads( + '[{"type": "controls_repeat_while"},' + + '{"type": "logic_negate"},' + + '{"type": "at_destination"},' + + '{"type": "controls_if"},' + + '{"type": "road_exists"},' + + '{"type": "turn_left"},' + + '{"type": "move_forwards"}]' + ), + ) + + set_blocks( + level1035, + json.loads( + '[{"type": "controls_repeat_while"},' + + '{"type": "logic_negate"},' + + '{"type": "at_destination"},' + + '{"type": "controls_if"},' + + '{"type": "road_exists"},' + + '{"type": "move_forwards"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"}]' + ), + ) + + set_blocks( + level1036, + json.loads( + '[{"type": "controls_repeat_while"},' + + '{"type": "logic_negate"},' + + '{"type": "at_destination"},' + + '{"type": "controls_if"},' + + '{"type": "cow_crossing"},' + + '{"type": "sound_horn"},' + + '{"type": "road_exists"},' + + '{"type": "move_forwards"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"}]' + ), + ) + + set_blocks( + level1041, + json.loads( + '[{"type": "move_forwards"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "controls_repeat"}]' + ), + ) + + set_blocks( + level1044, + json.loads( + '[{"type": "move_forwards"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "controls_repeat"}]' + ), + ) + + set_blocks( + level1050, + json.loads( + '[{"type": "call_proc"},' + + '{"type": "declare_proc"},' + + '{"type": "move_forwards"},' + + '{"type": "turn_left"},' + + '{"type": "turn_right"},' + + '{"type": "controls_repeat"}]' + ), + ) + + set_blocks( + level1051, + json.loads( + '[{"type": "call_proc"},' + + '{"type": "declare_proc"},' + + '{"type": "move_forwards"},' + + '{"type": "turn_right"},' + + '{"type": "wait"},' + + '{"type": "controls_repeat_until"},' + + '{"type": "traffic_light"}]' + ), + ) + + set_blocks( + level1057, + json.loads( + '[{"type":"move_forwards"},' + + '{"type":"turn_left"},' + + '{"type":"turn_right"},' + + '{"type":"controls_repeat"},' + + '{"type":"call_proc"},' + + '{"type":"declare_proc"}]' + ), + ) + + set_blocks( + level1058, + json.loads( + '[{"type":"move_forwards"},' + + '{"type":"turn_left"},' + + '{"type":"turn_right"},' + + '{"type":"controls_repeat"},' + + '{"type":"call_proc"},' + + '{"type":"declare_proc"}]' + ), + ) + + +def delete_python_den_blocks(apps, schema_editor): + Level = apps.get_model("game", "Level") + LevelBlock = apps.get_model("game", "LevelBlock") + LevelBlock.objects.filter(level_id__in=range(1014, 1061)).delete() + + +def add_python_den_decor(apps, schema_editor): + Level = apps.get_model("game", "Level") + LevelDecor = apps.get_model("game", "LevelDecor") + + def set_decor(level, decor): + set_decor_inner(level, decor, LevelDecor) + + def bulk_copy_decor(old_level_name, new_level_name): + old_level = Level.objects.get(name=old_level_name, default=True) + decor_to_copy = LevelDecor.objects.filter(level_id=old_level.id).values() + new_level = Level.objects.get(name=new_level_name, default=True) + + new_level_decor = [] + for decor in decor_to_copy: + new_level_decor.append( + LevelDecor( + level_id=new_level.pk, + x=decor["x"], + y=decor["y"], + decorName=decor["decorName"], + ) + ) + LevelDecor.objects.bulk_create(new_level_decor) + + level1014 = Level.objects.get(name="1014", default=True) + level1015 = Level.objects.get(name="1015", default=True) + level1016 = Level.objects.get(name="1016", default=True) + level1017 = Level.objects.get(name="1017", default=True) + level1018 = Level.objects.get(name="1018", default=True) + level1019 = Level.objects.get(name="1019", default=True) + level1020 = Level.objects.get(name="1020", default=True) + level1021 = Level.objects.get(name="1021", default=True) + level1022 = Level.objects.get(name="1022", default=True) + level1023 = Level.objects.get(name="1023", default=True) + level1024 = Level.objects.get(name="1024", default=True) + level1027 = Level.objects.get(name="1027", default=True) + level1028 = Level.objects.get(name="1028", default=True) + level1033 = Level.objects.get(name="1033", default=True) + level1034 = Level.objects.get(name="1034", default=True) + + set_decor( + level1014, + json.loads( + '[{"x": 149, "y": 299, "decorName": "pond"},' + + '{"x": 398, "y": 354, "decorName": "bush"},' + + '{"x": 399, "y": 318, "decorName": "bush"},' + + '{"x": 311, "y": 309, "decorName": "tree2"},' + + '{"x": 568, "y": 516, "decorName": "tree1"},' + + '{"x": 654, "y": 512, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1015, + json.loads( + '[{"x": 404, "y": 602, "decorName": "pond"},' + + '{"x": 563, "y": 600, "decorName": "pond"},' + + '{"x": 501, "y": 503, "decorName": "pond"},' + + '{"x": 254, "y": 655, "decorName": "bush"},' + + '{"x": 253, "y": 617, "decorName": "bush"},' + + '{"x": 407, "y": 512, "decorName": "tree2"},' + + '{"x": 494, "y": 391, "decorName": "tree1"},' + + '{"x": 486, "y": 318, "decorName": "tree1"},' + + '{"x": 286, "y": 327, "decorName": "tree1"},' + + '{"x": 252, "y": 256, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1016, + json.loads( + '[{"x": 699, "y": 499, "decorName": "pond"},' + + '{"x": 700, "y": 402, "decorName": "pond"},' + + '{"x": 611, "y": 469, "decorName": "bush"},' + + '{"x": 610, "y": 427, "decorName": "bush"},' + + '{"x": 613, "y": 505, "decorName": "tree2"}]' + ), + ) + + set_decor( + level1017, + json.loads( + '[{"x": 461, "y": 314, "decorName": "pond"},' + + '{"x": 428, "y": 371, "decorName": "tree1"},' + + '{"x": 500, "y": 179, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1018, + json.loads( + '[{"x": 301, "y": 594, "decorName": "tree1"},' + + '{"x": 421, "y": 598, "decorName": "tree1"},' + + '{"x": 529, "y": 600, "decorName": "tree1"},' + + '{"x": 120, "y": 415, "decorName": "tree2"},' + + '{"x": 93, "y": 300, "decorName": "tree2"}]' + ), + ) + + set_decor( + level1019, + json.loads( + '[{"x": 562, "y": 42, "decorName": "pond"},' + + '{"x": 551, "y": 501, "decorName": "bush"},' + + '{"x": 551, "y": 562, "decorName": "bush"},' + + '{"x": 602, "y": 299, "decorName": "tree2"},' + + '{"x": 618, "y": 500, "decorName": "tree1"},' + + '{"x": 460, "y": 495, "decorName": "tree1"},' + + '{"x": 145, "y": 364, "decorName": "tree1"},' + + '{"x": 145, "y": 269, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1020, + json.loads( + '[{"x": 443, "y": 578, "decorName": "pond"},' + + '{"x": 640, "y": 434, "decorName": "tree2"},' + + '{"x": 623, "y": 362, "decorName": "tree1"},' + + '{"x": 647, "y": 292, "decorName": "tree2"},' + + '{"x": 694, "y": 341, "decorName": "tree1"},' + + '{"x": 516, "y": 651, "decorName": "tree2"},' + + '{"x": 412, "y": 648, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1021, + json.loads( + '[{"x": 149, "y": 292, "decorName": "pond"},' + + '{"x": 300, "y": 507, "decorName": "tree1"},' + + '{"x": 308, "y": 583, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1022, + json.loads( + '[{"x": 663, "y": 191, "decorName": "pond"},' + + '{"x": 364, "y": 395, "decorName": "tree1"},' + + '{"x": 463, "y": 317, "decorName": "tree2"},' + + '{"x": 367, "y": 237, "decorName": "tree1"},' + + '{"x": 250, "y": 391, "decorName": "tree2"}]' + ), + ) + + set_decor( + level1023, + json.loads( + '[{"x": 599, "y": 310, "decorName": "pond"},' + + '{"x": 599, "y": 208, "decorName": "pond"},' + + '{"x": 754, "y": 337, "decorName": "bush"},' + + '{"x": 755, "y": 370, "decorName": "bush"},' + + '{"x": 754, "y": 302, "decorName": "bush"},' + + '{"x": 809, "y": 370, "decorName": "bush"},' + + '{"x": 810, "y": 334, "decorName": "bush"},' + + '{"x": 810, "y": 298, "decorName": "bush"},' + + '{"x": 602, "y": 418, "decorName": "tree2"},' + + '{"x": 646, "y": 483, "decorName": "tree1"},' + + '{"x": 678, "y": 426, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1024, + json.loads( + '[{"x": 316, "y": 302, "decorName": "pond"},' + + '{"x": 207, "y": 198, "decorName": "pond"},' + + '{"x": 371, "y": 198, "decorName": "pond"},' + + '{"x": 533, "y": 195, "decorName": "pond"},' + + '{"x": 491, "y": 367, "decorName": "bush"},' + + '{"x": 498, "y": 330, "decorName": "bush"},' + + '{"x": 553, "y": 354, "decorName": "bush"},' + + '{"x": 546, "y": 318, "decorName": "bush"},' + + '{"x": 230, "y": 317, "decorName": "tree2"}]' + ), + ) + + set_decor( + level1027, + json.loads( + '[{"x": 147, "y": 214, "decorName": "pond"},' + + '{"x": 434, "y": 255, "decorName": "bush"},' + + '{"x": 489, "y": 259, "decorName": "bush"},' + + '{"x": 298, "y": 188, "decorName": "tree2"},' + + '{"x": 158, "y": 398, "decorName": "tree2"},' + + '{"x": 220, "y": 410, "decorName": "tree1"},' + + '{"x": 548, "y": 411, "decorName": "tree1"},' + + '{"x": 617, "y": 407, "decorName": "tree2"},' + + '{"x": 669, "y": 199, "decorName": "tree2"}]' + ), + ) + + set_decor( + level1028, + json.loads( + '[{"x": 443, "y": 578, "decorName": "pond"},' + + '{"x": 640, "y": 434, "decorName": "tree2"},' + + '{"x": 623, "y": 362, "decorName": "tree1"},' + + '{"x": 647, "y": 292, "decorName": "tree2"},' + + '{"x": 694, "y": 341, "decorName": "tree1"},' + + '{"x": 516, "y": 651, "decorName": "tree2"},' + + '{"x": 412, "y": 648, "decorName": "tree1"}]' + ), + ) + + set_decor( + level1033, + json.loads( + '[{"x": 459, "y": 602, "decorName": "pond"},' + + '{"x": 381, "y": 606, "decorName": "tree2"},' + + '{"x": 692, "y": 688, "decorName": "tree1"},' + + '{"x": 717, "y": 620, "decorName": "tree1"},' + + '{"x": 686, "y": 530, "decorName": "tree2"}]' + ), + ) + + set_decor( + level1034, + json.loads( + '[{"x": 625, "y": 408, "decorName": "pond"},' + + '{"x": 201, "y": 411, "decorName": "tree2"},' + + '{"x": 200, "y": 342, "decorName": "tree1"},' + + '{"x": 405, "y": 443, "decorName": "tree2"},' + + '{"x": 400, "y": 514, "decorName": "tree1"}]' + ), + ) + + bulk_copy_decor("85", "1026") + bulk_copy_decor("119", "1029") + bulk_copy_decor("84", "1030") + bulk_copy_decor("34", "1031") + bulk_copy_decor("99", "1035") + bulk_copy_decor("38", "1036") + bulk_copy_decor("100", "1037") + bulk_copy_decor("39", "1038") + bulk_copy_decor("47", "1039") + bulk_copy_decor("48", "1040") + bulk_copy_decor("83", "1041") + bulk_copy_decor("95", "1042") + bulk_copy_decor("96", "1043") + bulk_copy_decor("84", "1044") + bulk_copy_decor("97", "1045") + bulk_copy_decor("106", "1046") + bulk_copy_decor("107", "1047") + bulk_copy_decor("108", "1048") + bulk_copy_decor("109", "1049") + bulk_copy_decor("61", "1050") + bulk_copy_decor("62", "1051") + bulk_copy_decor("63", "1052") + bulk_copy_decor("64", "1053") + bulk_copy_decor("65", "1054") + bulk_copy_decor("66", "1055") + bulk_copy_decor("67", "1056") + bulk_copy_decor("90", "1057") + bulk_copy_decor("91", "1058") + bulk_copy_decor("101", "1059") + bulk_copy_decor("102", "1060") + + +def delete_python_den_decor(apps, schema_editor): + Level = apps.get_model("game", "Level") + LevelDecor = apps.get_model("game", "LevelDecor") + LevelDecor.objects.filter(level_id__in=range(1014, 1061)).delete() + + +def create_python_den_episodes(apps, schema_editor): + Episode = apps.get_model("game", "Episode") + + episode16 = Episode.objects.create( + pk=16, + name="Output, Operators, and Data", + ) + + episode17 = Episode.objects.create( + pk=17, + name="Variables, Input, and Casting", + ) + + episode18 = Episode.objects.create( + pk=18, + name="Selection", + ) + + episode19 = Episode.objects.create( + pk=19, + name="Complex Selection", + ) + + episode20 = Episode.objects.create( + pk=20, + name="String Manipulation", + ) + + episode21 = Episode.objects.create( + pk=21, + name="Lists", + ) + + episode22 = Episode.objects.create( + pk=22, + name="Procedures", + ) + + episode12 = Episode.objects.get(pk=12) + episode13 = Episode.objects.get(pk=13) + episode14 = Episode.objects.get(pk=14) + episode15 = Episode.objects.get(pk=15) + episode16.next_episode = episode17 + episode17.next_episode = episode18 + episode18.next_episode = episode19 + episode19.next_episode = episode12 + episode12.next_episode = episode13 + episode13.next_episode = episode14 + episode14.next_episode = episode20 + episode20.next_episode = episode21 + episode21.next_episode = episode15 + episode15.next_episode = episode22 + + episode12.save() + episode13.save() + episode14.save() + episode15.save() + episode16.save() + episode17.save() + episode18.save() + episode19.save() + episode20.save() + episode21.save() + + +def delete_python_den_episodes(apps, schema_editor): + Episode = apps.get_model("game", "Episode") + Episode.objects.filter(pk__in=range(16, 23)).delete() + + episode14 = Episode.objects.get(pk=14) + episode15 = Episode.objects.get(pk=15) + episode14.next_episode = episode15 + episode15.next_episode = None + + episode14.save() + episode15.save() + + +def set_first_and_last_levels(apps, schema_editor): + Episode = apps.get_model("game", "Episode") + Level = apps.get_model("game", "Level") + + episode13 = Episode.objects.get(pk=13) + episode13.first_level = Level.objects.get(name="1014", default=True) + episode13.save() + + episode14 = Episode.objects.get(pk=14) + episode14.first_level = Level.objects.get(name="1026", default=True) + episode14.save() + + episode15 = Episode.objects.get(pk=15) + episode15.first_level = Level.objects.get(name="1041", default=True) + episode15.save() + + episode22 = Episode.objects.get(pk=22) + episode22.first_level = Level.objects.get(name="1050", default=True) + episode22.save() + + +def reset_first_and_last_levels(apps, schema_editor): + Episode = apps.get_model("game", "Episode") + + episode13 = Episode.objects.get(pk=13) + episode13.first_level = None + episode13.save() + + episode14 = Episode.objects.get(pk=14) + episode14.first_level = None + episode14.save() + + episode15 = Episode.objects.get(pk=15) + episode15.first_level = None + episode15.save() + + episode22 = Episode.objects.get(pk=22) + episode22.first_level = None + episode22.save() + + +def delete_old_loop_levels(apps, schema_editor): + Level = apps.get_model("game", "Level") + Level.objects.filter(name__in=range(123, 154)).delete() + + +def recreate_old_loop_levels(apps, schema_editor): + Episode = apps.get_model("game", "Episode") + Level = apps.get_model("game", "Level") + + episode_15 = Episode.objects.get(pk=15) + episode_14 = Episode.objects.get(pk=14) + episode_13 = Episode.objects.get(pk=13) + + level_153 = Level.objects.create( + name="153", + episode=episode_15, + ) + level_152 = Level.objects.create( + name="152", + episode=episode_15, + next_level=level_153, + ) + level_151 = Level.objects.create( + name="151", + episode=episode_15, + next_level=level_152, + ) + level_150 = Level.objects.create( + name="150", + episode=episode_15, + next_level=level_151, + ) + level_149 = Level.objects.create( + name="149", + episode=episode_15, + next_level=level_150, + ) + + # Episode 14, Levels 141 - 148 + level_148 = Level.objects.create( + name="148", + episode=episode_14, + next_level=level_149, + ) + level_147 = Level.objects.create( + name="147", + episode=episode_14, + next_level=level_148, + ) + level_146 = Level.objects.create( + name="146", + episode=episode_14, + next_level=level_147, + ) + level_145 = Level.objects.create( + name="145", + episode=episode_14, + next_level=level_146, + ) + level_144 = Level.objects.create( + name="144", + episode=episode_14, + next_level=level_145, + ) + level_143 = Level.objects.create( + name="143", + episode=episode_14, + next_level=level_144, + ) + level_142 = Level.objects.create( + name="142", + episode=episode_14, + next_level=level_143, + ) + level_141 = Level.objects.create( + name="141", + episode=episode_14, + next_level=level_142, + ) + + # Episode 13, Levels 123 - 140 + level_140 = Level.objects.create( + name="140", + episode=episode_13, + next_level=level_141, + ) + level_139 = Level.objects.create( + name="139", + episode=episode_13, + next_level=level_140, + ) + level_138 = Level.objects.create( + name="138", + episode=episode_13, + next_level=level_139, + ) + level_137 = Level.objects.create( + name="137", + episode=episode_13, + next_level=level_138, + ) + level_136 = Level.objects.create( + name="136", + episode=episode_13, + next_level=level_137, + ) + level_135 = Level.objects.create( + name="135", + episode=episode_13, + next_level=level_136, + ) + level_134 = Level.objects.create( + name="134", + episode=episode_13, + next_level=level_135, + ) + level_133 = Level.objects.create( + name="133", + episode=episode_13, + next_level=level_134, + ) + level_132 = Level.objects.create( + name="132", + episode=episode_13, + next_level=level_133, + ) + level_131 = Level.objects.create( + name="131", + episode=episode_13, + next_level=level_132, + ) + level_130 = Level.objects.create( + name="130", + episode=episode_13, + next_level=level_131, + ) + level_129 = Level.objects.create( + name="129", + episode=episode_13, + next_level=level_130, + ) + level_128 = Level.objects.create( + name="128", + episode=episode_13, + next_level=level_129, + ) + level_127 = Level.objects.create( + name="127", + episode=episode_13, + next_level=level_128, + ) + level_126 = Level.objects.create( + name="126", + episode=episode_13, + next_level=level_127, + ) + level_125 = Level.objects.create( + name="125", + episode=episode_13, + next_level=level_126, + ) + level_124 = Level.objects.create( + name="124", + episode=episode_13, + next_level=level_125, + ) + level_123 = Level.objects.create( + name="123", + episode=episode_13, + next_level=level_124, + ) + + +class Migration(migrations.Migration): + dependencies = [("game", "0096_alter_level_commands")] + + operations = [ + migrations.RunPython( + code=delete_old_loop_levels, reverse_code=recreate_old_loop_levels + ), + migrations.RunPython( + code=create_python_den_episodes, reverse_code=delete_python_den_episodes + ), + migrations.RunPython( + code=add_python_den_levels, reverse_code=delete_python_den_levels + ), + migrations.RunPython( + code=add_python_den_blocks, reverse_code=delete_python_den_blocks + ), + migrations.RunPython( + code=add_python_den_decor, reverse_code=delete_python_den_decor + ), + migrations.RunPython( + code=set_first_and_last_levels, reverse_code=reset_first_and_last_levels + ), + ] diff --git a/game/static/game/js/game.js b/game/static/game/js/game.js index 1bef35bf5..f760b80df 100644 --- a/game/static/game/js/game.js +++ b/game/static/game/js/game.js @@ -113,8 +113,16 @@ ocargo.Game.prototype.setup = function () { } else if (DEFAULT_LEVEL) { titlePrefix = gettext('Level %(level_name)s') } + + let adjusted_level_name = '' + if (LEVEL_NAME > 1000) { + adjusted_level_name = LEVEL_NAME - 1000 + } else { + adjusted_level_name = LEVEL_NAME; + } + if (titlePrefix) { - title = interpolate(titlePrefix, { level_name: LEVEL_NAME }, true) + title = interpolate(titlePrefix, { level_name: adjusted_level_name }, true) } else { title = LEVEL_NAME } diff --git a/game/static/game/js/skulpt/skulpt-stdlib.js b/game/static/game/js/skulpt/skulpt-stdlib.js index 24fc6df2f..73154ddea 100644 --- a/game/static/game/js/skulpt/skulpt-stdlib.js +++ b/game/static/game/js/skulpt/skulpt-stdlib.js @@ -1 +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:\ndef __init__(self):\nself.heapList = [0]\nself.currentSize = 0\n\n\ndef buildHeap(self,alist):\ni = len(alist) // 2\nself.currentSize = len(alist)\nself.heapList = [0] + alist[:]\nprint(len(self.heapList), i)\nwhile (i > 0):\nprint(self.heapList, i)\nself.percDown(i)\ni = i - 1\nprint(self.heapList,i)\n\ndef percDown(self,i):\nwhile (i * 2) <= self.currentSize:\nmc = self.minChild(i)\nif self.heapList[i] > self.heapList[mc]:\ntmp = self.heapList[i]\nself.heapList[i] = self.heapList[mc]\nself.heapList[mc] = tmp\ni = mc\n\ndef minChild(self,i):\nif i * 2 + 1 > self.currentSize:\nreturn i * 2\nelse:\nif self.heapList[i * 2] < self.heapList[i * 2 + 1]:\nreturn i * 2\nelse:\nreturn i * 2 + 1\n\ndef percUp(self,i):\nwhile i // 2 > 0:\n if self.heapList[i] < self.heapList[i//2]:\n tmp = self.heapList[i // 2]\nself.heapList[i // 2] = self.heapList[i]\nself.heapList[i] = tmp\ni = i // 2\n\ndef insert(self,k):\nself.heapList.append(k)\nself.currentSize = self.currentSize + 1\nself.percUp(self.currentSize)\n\ndef delMin(self):\nretval = self.heapList[1]\nself.heapList[1] = self.heapList[self.currentSize]\nself.currentSize = self.currentSize - 1\nself.heapList.pop()\nself.percDown(1)\nreturn retval\n\ndef isEmpty(self):\nif currentSize == 0:\nreturn True\nelse:\nreturn 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\n\nclass Stack:\ndef __init__(self):\nself.items = []\n\ndef isEmpty(self):\nreturn self.items == []\n\ndef push(self, item):\nself.items.append(item)\n\ndef pop(self):\nreturn self.items.pop()\n\ndef peek(self):\nreturn self.items[len(self.items)-1]\n\ndef size(self):\nreturn len(self.items)\n\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'''\nAuthor: Brad Miller\nDate: 1/15/2005\nDescription: Imlement a binary search tree with the following interface\nfunctions:\n __contains__(y) <==> y in x\n__getitem__(y) <==> x[y]\n__init__()\n__len__() <==> len(x)\n__setitem__(k,v) <==> x[k] = v\nclear()\nget(k)\nitems()\nkeys()\nvalues()\nput(k,v)\nin\ndel <==>\n'''\n\ndef __init__(self):\nself.root = None\nself.size = 0\n\ndef put(self,key,val):\nif self.root:\nself._put(key,val,self.root)\nelse:\nself.root = TreeNode(key,val)\nself.size = self.size + 1\n\ndef _put(self,key,val,currentNode):\nif key < currentNode.key:\nif currentNode.hasLeftChild():\nself._put(key,val,currentNode.leftChild)\nelse:\ncurrentNode.leftChild = TreeNode(key,val,parent=currentNode)\nelse:\nif currentNode.hasRightChild():\nself._put(key,val,currentNode.rightChild)\nelse:\ncurrentNode.rightChild = TreeNode(key,val,parent=currentNode)\n\ndef __setitem__(self,k,v):\nself.put(k,v)\n\ndef get(self,key):\nif self.root:\nres = self._get(key,self.root)\nif res:\nreturn res.payload\nelse:\nreturn None\nelse:\nreturn None\n\ndef _get(self,key,currentNode):\nif not currentNode:\n return None\nelif currentNode.key == key:\nreturn currentNode\nelif key < currentNode.key:\nreturn self._get(key,currentNode.leftChild)\nelse:\nreturn self._get(key,currentNode.rightChild)\n\n\ndef __getitem__(self,key):\nres = self.get(key)\nif res:\nreturn res\nelse:\nraise KeyError('Error, key not in tree')\n\n\ndef __contains__(self,key):\nif self._get(key,self.root):\nreturn True\nelse:\nreturn False\n\ndef length(self):\nreturn self.size\n\ndef __len__(self):\nreturn self.size\n\ndef __iter__(self):\nreturn self.root.__iter__()\n\ndef delete(self,key):\nif self.size > 1:\nnodeToRemove = self._get(key,self.root)\nif nodeToRemove:\nself.remove(nodeToRemove)\nself.size = self.size-1\nelse:\nraise KeyError('Error, key not in tree')\nelif self.size == 1 and self.root.key == key:\nself.root = None\nself.size = self.size - 1\nelse:\nraise KeyError('Error, key not in tree')\n\ndef __delitem__(self,key):\nself.delete(key)\n\ndef remove(self,currentNode):\nif currentNode.isLeaf(): #leaf\nif currentNode == currentNode.parent.leftChild:\ncurrentNode.parent.leftChild = None\nelse:\ncurrentNode.parent.rightChild = None\nelif currentNode.hasBothChildren(): #interior\nsucc = currentNode.findSuccessor()\nsucc.spliceOut()\ncurrentNode.key = succ.key\ncurrentNode.payload = succ.payload\nelse: # this node has one child\nif currentNode.hasLeftChild():\nif currentNode.isLeftChild():\ncurrentNode.leftChild.parent = currentNode.parent\ncurrentNode.parent.leftChild = currentNode.leftChild\nelif currentNode.isRightChild():\ncurrentNode.leftChild.parent = currentNode.parent\ncurrentNode.parent.rightChild = currentNode.leftChild\nelse:\ncurrentNode.replaceNodeData(currentNode.leftChild.key,\n currentNode.leftChild.payload,\n currentNode.leftChild.leftChild,\n currentNode.leftChild.rightChild)\nelse:\nif currentNode.isLeftChild():\ncurrentNode.rightChild.parent = currentNode.parent\ncurrentNode.parent.leftChild = currentNode.rightChild\nelif currentNode.isRightChild():\ncurrentNode.rightChild.parent = currentNode.parent\ncurrentNode.parent.rightChild = currentNode.rightChild\nelse:\ncurrentNode.replaceNodeData(currentNode.rightChild.key,\n currentNode.rightChild.payload,\n currentNode.rightChild.leftChild,\n currentNode.rightChild.rightChild)\n\ndef inorder(self):\nself._inorder(self.root)\n\ndef _inorder(self,tree):\nif tree != None:\nself._inorder(tree.leftChild)\nprint(tree.key)\nself._inorder(tree.rightChild)\n\ndef postorder(self):\nself._postorder(self.root)\n\ndef _postorder(self, tree):\nif tree:\nself._postorder(tree.rightChild)\nself._postorder(tree.leftChild)\nprint(tree.key)\n\ndef preorder(self):\nself._preorder(self,self.root)\n\ndef _preorder(self,tree):\nif tree:\nprint(tree.key)\nself._preorder(tree.leftChild)\nself._preorder(tree.rightChild)\n\n\nclass TreeNode:\ndef __init__(self,key,val,left=None,right=None,parent=None):\nself.key = key\nself.payload = val\nself.leftChild = left\nself.rightChild = right\nself.parent = parent\nself.balanceFactor = 0\n\ndef hasLeftChild(self):\nreturn self.leftChild\n\ndef hasRightChild(self):\nreturn self.rightChild\n\ndef isLeftChild(self):\nreturn self.parent and self.parent.leftChild == self\n\ndef isRightChild(self):\nreturn self.parent and self.parent.rightChild == self\n\ndef isRoot(self):\nreturn not self.parent\n\ndef isLeaf(self):\nreturn not (self.rightChild or self.leftChild)\n\ndef hasAnyChildren(self):\nreturn self.rightChild or self.leftChild\n\ndef hasBothChildren(self):\nreturn self.rightChild and self.leftChild\n\ndef replaceNodeData(self,key,value,lc,rc):\nself.key = key\nself.payload = value\nself.leftChild = lc\nself.rightChild = rc\nif self.hasLeftChild():\nself.leftChild.parent = self\nif self.hasRightChild():\nself.rightChild.parent = self\n\ndef findSuccessor(self):\nsucc = None\nif self.hasRightChild():\nsucc = self.rightChild.findMin()\nelse:\nif self.parent:\nif self.isLeftChild():\nsucc = self.parent\nelse:\nself.parent.rightChild = None\nsucc = self.parent.findSuccessor()\nself.parent.rightChild = self\nreturn succ\n\n\ndef spliceOut(self):\nif self.isLeaf():\nif self.isLeftChild():\nself.parent.leftChild = None\nelse:\nself.parent.rightChild = None\nelif self.hasAnyChildren():\nif self.hasLeftChild():\nif self.isLeftChild():\nself.parent.leftChild = self.leftChild\nelse:\nself.parent.rightChild = self.leftChild\nself.leftChild.parent = self.parent\nelse:\nif self.isLeftChild():\nself.parent.leftChild = self.rightChild\nelse:\nself.parent.rightChild = self.rightChild\nself.rightChild.parent = self.parent\n\ndef findMin(self):\ncurrent = self\nwhile current.hasLeftChild():\ncurrent = current.leftChild\nreturn current\n\ndef __iter__(self):\n\"\"\"The standard inorder traversal of a binary tree.\"\"\"\nif self:\nif self.hasLeftChild():\nfor elem in self.leftChild:\nyield elem\nyield self.key\nif self.hasRightChild():\nfor elem in self.rightChild:\nyield 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/operator/__init__.js": "/*\n * __author__: Isaac Dontje Lindell (i@isaacdontjelindell.com)\n *\n * Implementation of the Python operator module.\n */\n\nvar $builtinmodule = function(name) {\n var mod = {};\n\n mod.lt = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Lt')); });\n mod.__lt__ = mod.lt;\n\n mod.le = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'LtE')); });\n mod.__le__ = mod.le;\n\n mod.eq = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Eq')); });\n mod.__eq__ = mod.eq;\n\n mod.ne = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'NotEq')); });\n mod.__ne__ = mod.ne;\n\n mod.ge = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'GtE')); });\n mod.__ge__ = mod.ge;\n\n mod.gt = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Gt')); });\n mod.__gt__ = mod.gt;\n\n mod.not_ = new Sk.builtin.func(function (obj) { throw new Sk.builtin.NotImplementedError(\"operator.not_() is not yet implemented in Skulpt\"); });\n\n mod.truth = new Sk.builtin.func(function(obj) { return Sk.builtin.bool(obj); });\n\n mod.is_ = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Is')); });\n\n mod.is_not = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'IsNot')); });\n\n mod.abs = new Sk.builtin.func(function(obj) { return Sk.misceval.callsim(Sk.builtin.abs, obj); });\n mod.__abs__ = mod.abs;\n\n // The documentation says that operator.add() is defined for a and b numbers, but\n // CPython (2.6) allows a and b to be other types (e.g. str)\n mod.add = new Sk.builtin.func(function (a, b) { return Sk.abstr.objectAdd(a, b); });\n mod.__add__ = mod.add;\n\n mod.and_ = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$and'].call(a, b); });\n mod.__and__ = mod.and_;\n\n mod.div = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$divide'].call(a, b); });\n mod.__div__ = mod.div;\n\n mod.floordiv = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$floor_divide'].call(a, b); });\n mod.__floordiv__ = mod.floordiv;\n\n // Doesn't look like anything has the __index__ magic function anyway\n mod.index = new Sk.builtin.func(function (a) { throw new Sk.builtin.NotImplementedError(\"operator.index() is not yet implemented in Skulpt\"); });\n mod.__index__ = mod.index;\n\n // Note: Sk.abstr.numberUnaryOp(obj, 'Invert') looks for the function nb$invert() on obj.\n // However, it doesn't look like that function has been implemented for any existing object types.\n // I've gone ahead and created this function for completeness' sake, but expect any use of it to\n // result in an error.\n mod.inv = new Sk.builtin.func(function (obj) { return Sk.abstr.numberUnaryOp(obj, 'Invert'); });\n mod.__inv__ = mod.inv;\n mod.invert = mod.inv;\n mod.__invert__ = mod.inv;\n\n mod.lshift = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$lshift'].call(a, b); });\n mod.__lshift__ = mod.lshift;\n\n mod.mod = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$remainder'].call(a, b); });\n mod.__mod__ = mod.mod;\n\n mod.mul = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$multiply'].call(a, b); });\n mod.__mul__ = mod.mul;\n\n mod.neg = new Sk.builtin.func(function (obj) { return Sk.abstr.objectNegative(obj); });\n mod.__neg__ = mod.neg;\n\n mod.or_ = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$or'].call(a, b); });\n mod.__or__ = mod.or_;\n\n mod.pos = new Sk.builtin.func(function (obj) { return Sk.abstr.objectPositive(obj); });\n mod.__pos__ = mod.pos;\n\n mod.pow = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$power'].call(a, b); });\n mod.__pow__ = mod.pow;\n\n mod.rshift = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$rshift'].call(a, b); });\n mod.__rshift__ = mod.rshift;\n\n mod.sub = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$subtract'].call(a, b); });\n mod.__sub__ = mod.sub;\n\n mod.truediv = mod.div;\n mod.__truediv__ = mod.div;\n\n mod.xor = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$xor'].call(a, b); });\n mod.__xor__ = mod.xor;\n\n mod.concat = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceConcat(a, b); });\n mod.__concat__ = mod.concat;\n\n mod.contains = new Sk.builtin.func(function (a, b) { return Sk.builtin.bool(Sk.abstr.sequenceContains(a, b)); });\n mod.__contains__ = mod.contains;\n\n mod.countOf = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceGetCountOf(a, b); });\n\n mod.delitem = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceDelItem(a, b); });\n mod.__delitem__ = mod.delitem;\n\n mod.getitem = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceGetItem(a, b); });\n mod.__getitem__ = mod.getitem;\n\n mod.indexOf = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceGetIndexOf(a, b); });\n\n mod.setitem = new Sk.builtin.func(function (a, b, c) { return Sk.abstr.sequenceSetItem(a, b, c); });\n mod.__setitem__ = mod.setitem;\n\n return mod;\n };\n ", "src/lib/image/__init__.js": "var ImageMod; // the single identifier needed in the global scope\n\n if (! 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\n var $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/unittest/__init__.py": "__author__ = 'bmiller'\n '''\n This is the start of something that behaves like\n the unittest module from cpython.\n\n '''\n\n\n class TestCase:\n def __init__(self):\n self.numPassed = 0\n self.numFailed = 0\n\n self.tlist = []\n testNames = {}\n for name in dir(self):\n if name[:4] == 'test' and name not in testNames:\n self.tlist.append(getattr(self,name))\n testNames[name]=True\n\n def setup(self):\n pass\n\n def tearDown(self):\n pass\n\n def main(self):\n\n for func in self.tlist:\n try:\n self.setup()\n func()\n self.tearDown()\n except:\n self.appendResult('Error',None,None,None)\n self.numFailed += 1\n self.showSummary()\n\n def assertEqual(self, actual, expected, feedback=\"\"):\n res = actual==expected\n self.appendResult(res,str(actual)+' to be equal to ',expected, feedback)\n\n def assertNotEqual(actual, expected, feedback=\"\"):\n res = actual != expected\n self.appendResult(res,str(actual)+' to not equal ',expected,feedback)\n\n def assertTrue(self,x, feedback=\"\"):\n res = x\n self.appendResult(res,str(x)+' to be ',True,feedback)\n\n def assertFalse(self,x, feedback=\"\"):\n res = not x\n self.appendResult(res,str(x)+' to be ',False,feedback)\n\n def assertIs(self,a,b, feedback=\"\"):\n res = a is b\n self.appendResult(res,str(a)+' to be the same object as ',b,feedback)\n\n def assertIsNot(self,a,b, feedback=\"\"):\n res = a is not b\n self.appendResult(res,str(a)+' to not be the same object as ',b,feedback)\n\n def assertIsNone(self,x, feedback=\"\"):\n res = x is None\n self.appendResult(res,x,None,feedback)\n\n def assertIsNotNone(self,x, feedback=\"\"):\n res = x is not None\n self.appendResult(res,str(x)+' to not be ',None,feedback)\n\n def assertIn(self,a,b, feedback=\"\"):\n res = a in b\n self.appendResult(res,str(a)+' to be in ',b,feedback)\n\n def assertNotIn(self,a,b, feedback=\"\"):\n res = a not in b\n self.appendResult(res,str(a)+' to not be in ',b,feedback)\n\n def assertIsInstance(self,a,b, feedback=\"\"):\n res = isinstance(a,b)\n self.appendResult(res,str(a)+' to be an instance of ',b,feedback)\n\n def assertNotIsInstance(self,a,b, feedback=\"\"):\n res = not isinstance(a,b)\n self.appendResult(res,str(a)+' to not be an instance of ',b,feedback)\n\n def assertAlmostEqual(self,a,b, feedback=\"\"):\n res = round(a-b,7) == 0\n self.appendResult(res,str(a)+' to equal ',b,feedback)\n\n def assertNotAlmostEqual(self,a,b, feedback=\"\"):\n res = round(a-b,7) != 0\n self.appendResult(res,str(a)+' to not equal ',b,feedback)\n\n def assertGreater(self,a,b, feedback=\"\"):\n res = a > b\n self.appendResult(res,str(a)+' to be greater than ',b,feedback)\n\n def assertGreaterEqual(self,a,b, feedback=\"\"):\n res = a >= b\n self.appendResult(res,str(a)+' to be greater than or equal to ',b,feedback)\n\n def assertLess(self,a,b, feedback=\"\"):\n res = a < b\n self.appendResult(res,str(a)+' to be less than ',b,feedback)\n\n def assertLessEqual(self,a,b, feedback=\"\"):\n res = a <= b\n self.appendResult(res,str(a)+' to be less than or equal to ',b,feedback)\n\n def appendResult(self,res,actual,expected,feedback):\n if res == 'Error':\n msg = 'Error'\n elif res:\n msg = 'Pass'\n self.numPassed += 1\n else:\n msg = 'Fail: expected %s %s ' % (str(actual),str(expected)) + feedback\n self.numFailed += 1\n\n def showSummary(self):\n pct = self.numPassed / (self.numPassed+self.numFailed) * 100\n print \"ran %d tests, passed %d \\n\" % (self.numPassed+self.numFailed, self.numPassed)\n\n\n\n def main():\n glob = globals() # globals() still needs work\n for name in glob:\n if issubclass(glob[name],TestCase):\n glob[name]().main()\n\n ", "src/lib/test/__init__.py": "__author__ = 'bmiller'\n\n def 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\n def testNotEqual(actual, expected):\n pass\n\n ", "src/lib/string/__init__.js": "/*\n * __author__: Isaac Dontje Lindell (i@isaacdontjelindell.com)\n *\n * Implementation of the Python string module.\n */\n\n\n var $builtinmodule = function(name) {\n var mod = {};\n\n mod.ascii_lowercase = Sk.builtin.str('abcdefghijklmnopqrstuvwxyz');\n mod.ascii_uppercase = Sk.builtin.str('ABCDEFGHIJKLMNOPQRSTUVWXYZ');\n mod.ascii_letters = Sk.builtin.str(mod.ascii_lowercase.v + mod.ascii_uppercase.v);\n\n mod.lowercase = Sk.builtin.str('abcdefghijklmnopqrstuvwxyz');\n mod.uppercase = Sk.builtin.str('ABCDEFGHIJKLMNOPQRSTUVWXYZ');\n mod.letters = Sk.builtin.str(mod.lowercase.v + mod.uppercase.v);\n\n mod.digits = Sk.builtin.str('0123456789', Sk.builtin.str);\n mod.hexdigits = Sk.builtin.str('0123456789abcdefABCDEF');\n mod.octdigits = Sk.builtin.str('01234567');\n\n mod.punctuation = Sk.builtin.str('!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~');\n mod.whitespace = Sk.builtin.str('\\t\\n\\x0b\\x0c\\r ');\n\n /* Note: The docs for string.printable say that it's the concatenation of string.digits,\n * string.letters, string.punctuation, and string.whitespace. The CPython interpreter\n * outputs the whitespace characters in one order when string.whitespace is used, and a\n * slightly different order when string.printable is used. I've elected to follow the\n * behavior of CPython here rather than the spec. */\n mod.printable = Sk.builtin.str(mod.digits.v + mod.letters.v + mod.punctuation.v + \" \\t\\n\\r\\x0b\\x0c\");\n\n\n mod.split = new Sk.builtin.func(function(s, sep, maxsplit) {\n return Sk.misceval.callsim(Sk.builtin.str.prototype['split'], s, sep, maxsplit);\n });\n\n /* Return a copy of word with only its first character capitalized. */\n mod.capitalize = new Sk.builtin.func(function(word) {\n return Sk.misceval.callsim(Sk.builtin.str.prototype['capitalize'], word);\n });\n\n /* Concatenate a list or tuple of words with intervening occurrences\n * of sep. The default value for sep is a single space character. */\n mod.join = new Sk.builtin.func(function(words, sep) {\n if (sep === undefined) {\n sep = Sk.builtin.str(' ');\n }\n return Sk.misceval.callsim(Sk.builtin.str.prototype['join'], sep, words);\n });\n\n\n /* Split the argument into words using split(), capitalize each word\n * using capitalize(), and join the capitalized words using join().\n * Note that this replaces runs of whitespace characters by a single\n * space, and removes leading and trailing whitespace. */\n mod.capwords = new Sk.builtin.func(function(s, sep) {\n Sk.builtin.pyCheckArgs('capwords', arguments, 1, 2);\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"s must be a string\");\n }\n if (sep === undefined) {\n sep = Sk.builtin.str(' ');\n }\n if(!Sk.builtin.checkString(sep)) {\n throw new Sk.builtin.TypeError(\"sep must be a string\");\n }\n\n var words = Sk.misceval.callsim(mod.split, s, sep);\n var capWords = [];\n for (var i=0; i 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/urllib/request/__init__.js": "var $builtinmodule = function(name)\n {\n var request = {};\n\n\n //~ Classes .................................................................\n\n // Response class\n //\n // Response objects are returned by the request, get, post, etc.\n // methods, allowing the user to access the response text, status\n // code, and other information.\n\n // ------------------------------------------------------------\n var response = function($gbl, $loc) {\n\n // ------------------------------------------------------------\n $loc.__init__ = new Sk.builtin.func(function(self, xhr) {\n self.data$ = xhr.responseText;\n self.lineList = self.data$.split(\"\\n\");\n self.lineList = self.lineList.slice(0,-1);\n for(var i =0 ; i < self.lineList.length; i++) {\n self.lineList[i] = self.lineList[i]+'\\n';\n }\n self.currentLine = 0;\n self.pos$ = 0;\n });\n\n\n // ------------------------------------------------------------\n $loc.__str__ = new Sk.builtin.func(function(self) {\n return Sk.ffi.remapToPy('');\n });\n\n\n // ------------------------------------------------------------\n $loc.__iter__ = new Sk.builtin.func(function(self) {\n var allLines = self.lineList;\n\n return Sk.builtin.makeGenerator(function() {\n if (this.$index >= this.$lines.length) return undefined;\n return new Sk.builtin.str(this.$lines[this.$index++]);\n }, {\n $obj: self,\n $index: 0,\n $lines: allLines\n });\n });\n\n\n // ------------------------------------------------------------\n $loc.read = new Sk.builtin.func(function(self, size) {\n if (self.closed) throw new Sk.builtin.ValueError(\"I/O operation on closed file\");\n var len = self.data$.length;\n if (size === undefined) size = len;\n var ret = new Sk.builtin.str(self.data$.substr(self.pos$, size));\n self.pos$ += size;\n if (self.pos$ >= len) self.pos$ = len;\n return ret;\n });\n\n\n // ------------------------------------------------------------\n $loc.readline = new Sk.builtin.func(function(self, size) {\n var line = \"\";\n if (self.currentLine < self.lineList.length) {\n line = self.lineList[self.currentLine];\n self.currentLine++;\n }\n return new Sk.builtin.str(line);\n });\n\n\n // ------------------------------------------------------------\n $loc.readlines = new Sk.builtin.func(function(self, sizehint) {\n var arr = [];\n for(var i = self.currentLine; i < self.lineList.length; i++) {\n arr.push(new Sk.builtin.str(self.lineList[i]));\n }\n return new Sk.builtin.list(arr);\n });\n\n };\n\n request.Response =\n Sk.misceval.buildClass(request, response, 'Response', []);\n\n\n //~ Module functions ........................................................\n\n // ------------------------------------------------------------\n /**\n * Constructs and sends a Request. Returns Response object.\n *\n * http://docs.python-requests.org/en/latest/api/#requests.request\n *\n * For now, this implementation doesn't actually construct a Request\n * object; it just makes the request through jQuery.ajax and then\n * constructs a Response.\n */\n request.urlopen = new Sk.builtin.func(function(url, data, timeout) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\",url.v,false);\n xmlhttp.send(null);\n\n return Sk.misceval.callsim(request.Response,xmlhttp)\n });\n\n\n return request;\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\n\n class Queue:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def enqueue(self, item):\n self.items.insert(0,item)\n\n def dequeue(self):\n return self.items.pop()\n\n def size(self):\n return len(self.items)\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\n import sys\n import os\n import unittest\n\n class 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\n class 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\n class 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\n if __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 var TurtleGraphics;\n// the single identifier needed in the global scope\n if (!TurtleGraphics) {\n TurtleGraphics = {\n doneDelegates: [],\n fadeOnExit: true,\n\t\tdefaults: {\n \t\t\tcanvasID: 'mycanvas',\n\t\t\tdegrees: true,\n\t\t\tanimate: true\n\t\t}\n };\n }\n (function () {\n 'use strict';\n // Define private constants\n var Degree2Rad = Math.PI / 180,\n // conversion factor for degrees to radians\n Rad2Degree = 180 / Math.PI,\n render,\n allDone,\n segmentLine,\n clear_canvas;\n\n // Create a 3d Vector class for manipulating turtle heading, and position.\n function Vector(x, y, z) {\n var i;\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 } else {\n for (i = 0; i < x.length; i = i + 1) {\n Array.prototype.push.call(this, x[i]);\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]);\n phi = phi * Degree2Rad;\n res[0] = Math.cos(phi);\n res[1] = Math.sin(phi);\n return res.normalize();\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 Vector.prototype.linear = function (a, b, v) {\n if (this.length !== 3 || v.length !== 3) {\n return;\n }\n return new Vector([a * this[0] + b * v[0],\n a * this[1] + b * v[1],\n a * this[2] + b * v[2]]);\n\n\n };\n Vector.prototype.cross = function (v) {\n if (this.length !== 3 || v.length !== 3) {\n return;\n }\n\n return new Vector([this[1] * v[2] - this[2] * v[1],\n this[2] * v[0] - this[0] * v[2],\n this[0] * v[1] - this[1] * v[0]]);\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 c,\n s;\n angle = angle * Degree2Rad;\n c = Math.cos(angle);\n s = Math.sin(angle);\n return new Vector(this[0] * c + perp[0] * s, this[1] * c + perp[1] * s, 0);\n };\n Vector.prototype.rotateNormal = function (v, 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 Vector.prototype.normalize = function () {\n var n = this.len(),\n res = this.div(n);\n return res;\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) {\n this[1] = 0;\n }\n if (Math.abs(this[0]) < 0.00001) {\n this[0] = 0;\n }\n var rads = Math.atan(Math.abs(this[1]) / Math.abs(this[0])),\n deg = rads * Rad2Degree;\n if (this[0] < 0 && this[1] > 0) {\n deg = 180 - deg;\n } else if (this[0] < 0 && this[1] <= 0) {\n deg = 180 + deg;\n } else if (this[0] >= 0 && this[1] < 0) {\n deg = 360 - deg;\n }\n return deg;\n };\n // divide all vector components by the same value\n Vector.prototype.div = function (n) {\n var 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 // subtract one vector from another\n Vector.prototype.sub = function (v) {\n var 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 Vector.prototype.add = function (v) {\n var 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 Vector.prototype.smul = function (k) {\n // scalar multiplication\n var 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 Vector.prototype.scale = function (xs, ys) {\n var res = new Vector(0, 0, 0);\n res[0] = this[0] * ys;\n res[1] = this[1] * xs;\n res[2] = 1;\n return res;\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 allDone = function () {\n var done = true, tix, theT;\n for (tix = 0; tix < TurtleGraphics.turtleList.length; tix = tix + 1) {\n theT = TurtleGraphics.turtleList[tix];\n done = done && theT.aCount >= theT.drawingEvents.length;\n }\n return done;\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 canvasLib = TurtleGraphics.canvasLib[TurtleGraphics.defaults.canvasID],\n incr = TurtleGraphics.canvasLib[TurtleGraphics.defaults.canvasID].getCounter(),\n t,\n tix,\n i,\n \t\t\tcurrentPos,\n currentHead,\n filling,\n oper,\n ts,\n tmpColor,\n size,\n speed;\n\n\t\tcontext.moveTo(0, 0);\n\t\tcontext.lineCap = 'round';\n\t\tcontext.lineJoin = 'round';\n context.clearRect(canvasLib.llx, canvasLib.lly, canvasLib.urx - canvasLib.llx, canvasLib.ury - canvasLib.lly); //canvas.style.setProperty(\"background-color\",TurtleGraphics.turtleCanvas.bgcolor.v);\n TurtleGraphics.renderClock += incr;\n for (tix = 0; tix < TurtleGraphics.turtleList.length; tix = tix + 1) {\n currentPos = new Vector(0, 0, 0);\n currentHead = new Vector(1, 0, 0);\n context.fillStyle = 'black';\n context.strokeStyle = 'black';\n t = TurtleGraphics.turtleList[tix];\n\t\t\tcurrentHead = t.heading;\n context.lastCanvas = t.turtleCanvas;\n if (t.aCount >= t.drawingEvents.length) {\n t.aCount = t.drawingEvents.length - 1;\n }\n\n\t\t\tcontext.lineWidth = t.get_pen_width();\n\n filling = false;\n if (isNaN(t.turtleCanvas.delay)) {\n t.turtleCanvas.delay = 0;\n }\n //console.log(tix + \" : \" + t.clearPoint + \" to \" + t.aCount)\n for (i = t.clearPoint; (i <= t.aCount || t.turtleCanvas.delay === 0) && i < t.drawingEvents.length; i = i + 1) {\n if (i > t.aCount) {\n //If se jump past aCount, jump it ahead\n t.aCount = i;\n }\n oper = t.drawingEvents[i];\n ts = oper[oper.length - 1];\n //console.log(i + \"/\" + ts + oper [0] + \"{\" + oper [1] + \"}\" + t.turtleCanvas.delay)\n if (ts <= TurtleGraphics.renderClock || t.turtleCanvas.delay === 0) {\n if (ts > TurtleGraphics.renderClock) {\n //If we go past the render clock, jump it ahead\n TurtleGraphics.renderClock = ts;\n }\n //console.log(\"<==\")\n switch (oper[0]) {\n case 'LT': //line To\n if (!filling) {\n context.beginPath();\n context.moveTo(oper[1], oper[2]);\n }\n context.lineTo(oper[3], oper[4]);\n context.strokeStyle = oper[5];\n context.stroke();\n currentPos = new Vector(oper[3], oper[4], 0);\n if (!filling) {\n context.closePath();\n }\n break;\n case 'MT': //move to\n context.moveTo(oper[3], oper[4]);\n currentPos = new Vector(oper[3], oper[4], 0);\n break;\n case 'BF': //begin fill\n context.beginPath();\n context.moveTo(oper[1], oper[2]);\n filling = true;\n break;\n case 'EF': //end fill\n context.fillStyle = oper[3];\n context.stroke();\n context.fill();\n context.closePath();\n filling = false;\n break;\n case 'FC': // fill color\n \t\t\t\t\t\tcontext.fillStyle = oper[1];\n break;\n case 'TC': // turtle color\n context.strokeStyle = oper[1];\n break;\n case 'PW': // Pen width\n context.lineWidth = oper[1];\n break;\n case 'DT': // Dot\n tmpColor = context.fillStyle;\n context.fillStyle = oper[2];\n size = oper[1];\n context.fillRect(oper[3] - size / 2, oper[4] - size / 2, size, size);\n context.fillStyle = tmpColor;\n break;\n case 'CI': // Circle\n if (!filling) {\n context.beginPath();\n }\n context.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], oper[2] + Math.sin(oper[5]) * oper[3], 0);\n context.stroke();\n if (!filling) {\n context.closePath();\n }\n break;\n case 'WT':\n // write\n if (context.font) {\n context.font = oper[2];\n }\n context.scale(1, -1);\n context.fillText(oper[1], oper[3], -oper[4]);\n context.scale(1, -1);\n break;\n case 'ST':\n // stamp\n t.drawturtle(oper[3], new Vector(oper[1], oper[2], 0));\n break;\n case 'HT': // hide turtle\n t.visible = false;\n break;\n case 'SH': // show turtle\n t.visible = true;\n break;\n case 'TT': // turn\n currentHead = oper[1];\n break;\n case 'CL': // clear\n clear_canvas(t.canvasID);\n t.clearPoint = i; // Different from reset that calls clear because it leaves the turtles where they are\n break;\n case 'DL': // delay\n t.turtleCanvas.delay = oper[1];\n break;\n case 'SC': // speed change\n speed = oper[1];\n\n if (speed < 0) {\n t.turtleCanvas.delay = 0;\n } else {\n if (speed > 10) {\n speed = 10;\n }\n t.turtleCanvas.delay = (10 - speed % 11 + 1) * t.turtleCanvas.timeFactor; //10\n }\n\n //t.turtleCanvas.intervalId = clearInterval(t.turtleCanvas.intervalId);\n //t.turtleCanvas.intervalId = setInterval(render, t.turtleCanvas.delay)\n if (oper[2]) {\n t.turtleCanvas.setSegmentLength(oper[2]);\n }\n break;\n case 'CS': // change shape\n t.currentShape = oper[1];\n break;\n case 'NO':\n break;\n } //else {\n //console.log('unknown op: ' + oper[0]);\n //} // end of oper[0] test\n } // end of if ts < render clock\n }\n // end of for\n // console.log(TurtleGraphics.renderClock + \" / \" + t.aCount)\n // console.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) {\n // && allDone() ){\n // t.turtleCanvas.doneAnimating(t);\n // console.log(\"done animating\")\n if (context.lastCanvas) {\n context.lastCanvas.doneAnimating(t);\n }\n } else {\n //t.turtleCanvas.intervalId = setTimeout(render, t.turtleCanvas.delay)\n if (context.lastCanvas) {\n context.lastCanvas.intervalId = setTimeout(render, context.lastCanvas.delay);\n }\n }\n };\n //\n // Drawing Functions\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 numSegs = Math.floor(ep.sub(sp).len() / sL),\n res = [],\n oldp = sp,\n newp,\n op = '',\n i;\n if (pen) {\n op = 'LT';\n } else {\n op = 'MT';\n }\n for (i = 0; i < numSegs; i = i + 1) {\n newp = oldp.linear(1, sL, head);\n res.push([\n op,\n oldp[0],\n oldp[1],\n newp[0],\n newp[1]\n ]);\n oldp = newp;\n }\n if (!(oldp[0] === ep[0] && oldp[1] === ep[1])) {\n res.push([\n op,\n oldp[0],\n oldp[1],\n ep[0],\n ep[1]\n ]);\n }\n return res;\n };\n\n clear_canvas = function (canId) {\n var ctx = document.getElementById(canId).getContext('2d');\n //if (arguments.length >= 2) {\n // fillStyle = arguments[1];\n // fillRect(0, 0, canvas.width, canvas.height);\n //}\n ctx.clearRect(-ctx.canvas.width / 2, -ctx.canvas.height / 2, ctx.canvas.width, ctx.canvas.height);\n };\n //\n // Define TurtleCanvas\n //\n function TurtleCanvas(options) {\n this.canvasID = TurtleGraphics.defaults.canvasID;\n if (options.canvasID) {\n this.canvasID = options.canvasID;\n }\n this.canvas = document.getElementById(this.canvasID);\n this.context = this.canvas.getContext('2d');\n this.canvas.style.display = 'block';\n this.canvas.style.opacity = 1;\n //$(this.canvas).fadeIn();\n this.lineScale = 1;\n this.xptscale = 1;\n this.yptscale = 1;\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 this.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 }\n TurtleCanvas.prototype.setup = function (width, height) {\n this.canvas.width = width;\n this.canvas.height = height;\n this.lineScale = 1;\n this.xptscale = 1;\n this.yptscale = 1;\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 this.timeFactor = 5;\n if (TurtleGraphics.defaults.animate) {\n this.delay = 5 * this.timeFactor;\n } else {\n this.delay = 0;\n }\n if (TurtleGraphics.canvasInit === false) {\n this.context.save();\n this.context.translate(this.canvas.width / 2, this.canvas.height / 2);\n // move 0,0 to center.\n this.context.scale(1, -1);\n // 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; // RNL\n } else {\n this.context.restore();\n this.context.translate(this.canvas.width / 2, this.canvas.height / 2);\n // move 0,0 to center.\n this.context.scale(1, -1);\n // scaling like this flips the y axis the right way.\n this.context.clearRect(-this.canvas.width / 2, -this.canvas.height / 2, this.canvas.width, this.canvas.height);\n }\n };\n TurtleCanvas.prototype.addToCanvas = function (t) {\n this.tlist.push(t);\n };\n TurtleCanvas.prototype.onCanvas = function (t) {\n return this.tlist.indexOf(t) >= 0;\n };\n TurtleCanvas.prototype.isAnimating = function () {\n return this.tlist.length > 0;\n };\n TurtleCanvas.prototype.startAnimating = function (t) {\n if (!this.isAnimating()) {\n this.intervalId = setTimeout(render, this.delay); //setInterval(render, this.delay);\n }\n if (!this.onCanvas(t)) {\n //Added by RNL in case startAnimating is called after it's already been added\n this.addToCanvas(t);\n }\n\t\ttry {\n \t\t\tSk.isTurtleProgram = true;\n\t\t} catch (ReferenceEror) {\n \t\t}\n };\n TurtleCanvas.prototype.doneAnimating = function () {\n var i;\n this.tlist.splice(0, this.tlist.length);\n clearTimeout(this.intervalId);\n if (TurtleGraphics.doneDelegates) {\n for (i = 0; i < TurtleGraphics.doneDelegates.length; i = i + 1) {\n TurtleGraphics.doneDelegates[i]();\n }\n }\n };\n TurtleCanvas.prototype.cancelAnimation = function () {\n var t;\n if (this.intervalId) {\n clearTimeout(this.intervalId);\n }\n for (t = 0; t < this.tlist.length; t = t + 1) {\n this.tlist[t].aCount = this.tlist[t].drawingEvents.length - 1;\n }\n render();\n };\n TurtleCanvas.prototype.setSpeedDelay = function (s) {\n // RNL\n var df = 10 - s % 11 + 1;\n this.delay = df * this.timeFactor; //RNL was 10;\n };\n TurtleCanvas.prototype.setDelay = function (d) {\n this.delay = d;\n };\n TurtleCanvas.prototype.getDelay = function () {\n //RNL\n return this.delay;\n };\n TurtleCanvas.prototype.setCounter = function (s) {\n if (!s || s <= 0) {\n //Don't let this be less than 1\n s = 1;\n }\n this.renderCounter = s;\n };\n TurtleCanvas.prototype.getCounter = function () {\n return this.renderCounter;\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 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 this.llx = llx;\n this.lly = lly;\n this.urx = urx;\n this.ury = ury;\n };\n TurtleCanvas.prototype.window_width = function () {\n return this.canvas.width;\n };\n TurtleCanvas.prototype.window_height = function () {\n return this.canvas.height;\n };\n TurtleCanvas.prototype.bgcolor = function (c) {\n this.background_color = c;\n this.canvas.style.setProperty('background-color', c.v); //$(this.canvas).css(\"background-color\",c.v);\n };\n TurtleCanvas.prototype.setSegmentLength = function (s) {\n this.segmentLength = s;\n };\n TurtleCanvas.prototype.getSegmentLength = function () {\n return this.segmentLength;\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 theCanvas = this,\n eventHandler = function () {\n if (!theCanvas.isAnimating()) {\n if (TurtleGraphics.fadeOnExit) {\n //Let's this be configurable\n document.getElementById(canvas_id).style.display = 'none'; //$(\"#\"+canvas_id).hide();\n }\n document.getElementById(canvas_id).removeEventListener('click', eventHandler);\n //$(\"#\"+canvas_id).unbind('click');\n TurtleGraphics.canvasInit = false;\n delete TurtleGraphics.canvasLib[canvas_id];\n }\n };\n this.canvas.addEventListener('click', eventHandler, false);\n };\n TurtleCanvas.prototype.turtles = function () {\n return TurtleGraphics.turtleList;\n };\n TurtleCanvas.prototype.tracer = function (t, d) {\n var i;\n //New version NOT attached to a turtle (as per real turtle)\n this.setCounter(t);\n if (t === 0) {\n for (i = 0; i < this.turtleList; i = i + 1) {\n this.turtleList[i].animate = false;\n }\n this.cancelAnimation();\n }\n if (d !== undefined) {\n this.setDelay(d);\n }\n };\n // Constructor for Turtle objects\n function Turtle(opt) {\n this.initialize(opt);\n TurtleGraphics.turtleList.push(this);\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 this.position = this.home;\n this.context.moveTo(this.home[0], this.home[1]);\n this.heading = new Vector([1, 0, 0]);\n // to the right; in turtle space x+ direction\n this.normal = new Vector([0, 0, -1]); // in z- direction\n };\n Turtle.prototype.initialize = function (opt) {\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 p;\n for (p = 0; p < pl.length; p = p + 1) {\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 p;\n for (p = 0; p < pl.length; p = p + 1) {\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, -10 ],\n [ 3.09, -9.51 ],\n [ 5.88, -8.09 ],\n [ 8.09, -5.88 ],\n [ 9.51, -3.09 ]\n ],\n res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n function triangleShapePoints() {\n var pl = [\n [ 10, -5.77 ],\n [ 0, 11.55 ],\n [ -10, -5.77 ]\n ],\n res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n function squareShapePoints() {\n var pl = [\n [ 10, -10 ],\n [ 10, 10 ],\n [ -10, 10 ],\n [ -10, -10 ]\n ],\n res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\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 res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n // Initialize the turtle.\n var options = {}, ctx = null;\n if (opt) {\n options = opt;\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 this.animate = TurtleGraphics.defaults.animate;\n ctx = this.context;\n if (TurtleGraphics.canvasInit === false) {\n // This is a workaround until I understand skulpt re-running better\n // the downside is that this limits us to a single turtle...\n ctx.save();\n ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);\n // move 0,0 to center.\n ctx.scale(1, -1);\n // 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 this.turtleCanvas = TurtleGraphics.canvasLib[this.canvasID];\n this.home = new Vector([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.square = squareShapePoints();\n this.shapeStore.triangle = triangleShapePoints();\n this.shapeStore.blank = [new Vector(0, 0)];\n this.shapeStore.classic = classicShapePoints();\n this.currentShape = 'classic';\n this.drawingEvents = [];\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; // RNL for clear/clearScreen\n };\n Turtle.prototype.clean = function (color) {\n // Clean the canvas\n // Optional second argument is color\n if (arguments.length >= 1) {\n clear_canvas(this.canvasID, color);\n } else {\n clear_canvas(this.canvasID);\n }\n this.initialize();\n };\n Turtle.prototype.addDrawingEvent = function (eventList) {\n TurtleGraphics.eventCount += 1;\n eventList.push(TurtleGraphics.eventCount);\n this.drawingEvents.push(eventList);\n };\n Turtle.prototype.draw_line = function (newposition) {\n var ctx = this.context,\n r,\n s;\n if (!this.animate) {\n if (!this.filling) {\n ctx.beginPath();\n ctx.moveTo(this.position[0], this.position[1]);\n }\n ctx.lineCap = 'round';\n ctx.lineJoin = 'round';\n ctx.lineWidth = this.get_pen_width();\n ctx.strokeStyle = this.penStyle;\n ctx.lineTo(newposition[0], newposition[1]);\n\t\t\t//ctx.moveTo(newposition[0], newposition[1]);\n \t\t\tthis.position = newposition;\n ctx.stroke();\n if (!this.filling) {\n ctx.closePath();\n }\n } else {\n r = segmentLine(this.position, newposition, this.turtleCanvas.getSegmentLength(), this.pen);\n for (s = 0; s < r.length; s = s + 1) {\n r[s].push(this.penStyle);\n this.addDrawingEvent(r[s]);\n }\n if (!this.turtleCanvas.isAnimating()) {\n this.turtleCanvas.startAnimating(this);\n } else {\n if (!this.turtleCanvas.onCanvas(this)) {\n this.turtleCanvas.addToCanvas(this);\n }\n }\n }\n };\n Turtle.prototype.forward = function (d) {\n var newposition = this.position.linear(1, d, this.heading);\n this.goto(newposition);\n };\n Turtle.prototype.backward = function (d) {\n this.forward(-d);\n };\n //This is an internal function that sets the position without doing any drawing\n Turtle.prototype.teleport_to = function (nx, ny) {\n var newposition;\n if (nx instanceof Vector) {\n newposition = nx;\n } else {\n newposition = new Vector([nx, ny, 0]);\n }\n this.context.moveTo(newposition[0], newposition[1]);\n this.position = newposition;\n };\n Turtle.prototype.goto = function (nx, ny) {\n var newposition, r, s;\n if (nx instanceof Vector) {\n newposition = nx;\n } else {\n newposition = new Vector([nx, ny, 0]);\n }\n\t\tif (this.pen) {\n this.draw_line(newposition);\n } else {\n if (!this.animate) {\n this.context.moveTo(newposition[0], newposition[1]);\n } else {\n r = segmentLine(this.position, newposition, this.turtleCanvas.getSegmentLength(), this.pen);\n for (s = 0; s < r.length; s = s + 1) {\n this.addDrawingEvent(r[s]);\n }\n if (!this.turtleCanvas.isAnimating()) {\n this.turtleCanvas.startAnimating(this);\n } else {\n if (!this.turtleCanvas.onCanvas(this)) {\n this.turtleCanvas.addToCanvas(this);\n }\n }\n }\n }\n this.position = newposition;\n };\n Turtle.prototype.delay = function (d) {\n // RNL\n if (d !== null) {\n if (d < 0) {\n d = -d;\n }\n if (!this.animate) {\n this.turtleCanvas.setDelay(d);\n } else {\n this.turtleCanvas.setDelay(d);\n this.addDrawingEvent([ 'DL', d ]);\n this.addDrawingEvent(['NO']);\n }\n }\n return this.turtleCanvas.getDelay();\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 ) {\n this.animate = false;\n this.turtleCanvas.cancelAnimation();\n } else {\n this.turtleCanvas.setSpeedDelay(s);\n this.addDrawingEvent([ 'SC', s, t ]);\n this.addDrawingEvent(['NO']);\n }\n if (t) {\n this.turtleCanvas.setSegmentLength(t); // set the number of units to divide a segment into\n } else {\n this.turtleCanvas.setSegmentLength(10);\n }\n };\n Turtle.prototype.tracer = function (t, d) {\n this.turtleCanvas.setCounter(t);\n if (t === 0) {\n this.animate = false;\n this.turtleCanvas.cancelAnimation();\n }\n if (d !== undefined) {\n this.turtleCanvas.setDelay(d);\n }\n };\n Turtle.prototype.getRenderCounter = function () {\n return this.turtleCanvas.getCounter();\n };\n Turtle.prototype.turn = function (phi) {\n var alpha = phi * Degree2Rad,\n left = this.normal.cross(this.heading),\n newheading = this.heading.rotateNormal(left, alpha);\n this.heading = newheading;\n if (this.animate) {\n this.addDrawingEvent([ 'TT', this.heading ]);\n }\n };\n Turtle.prototype.right = Turtle.prototype.turn;\n Turtle.prototype.left = function (phi) {\n this.turn(-phi);\n };\n Turtle.prototype.get_heading = function () {\n if (TurtleGraphics.defaults.degrees) {\n return this.heading.toAngle();\n }\n return this.heading;\n };\n Turtle.prototype.get_position = function () {\n return this.position;\n };\n Turtle.prototype.getx = function () {\n return this.position[0];\n };\n Turtle.prototype.gety = function () {\n return this.position[1];\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 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 }\n return res;\n };\n Turtle.prototype.distance = function (to, y) {\n if ((typeof to).toLowerCase() === 'number') {\n to = new Vector(to, y, 0);\n }\n return this.position.sub(new Vector(to)).len();\n };\n Turtle.prototype.dot = function (psize, pcolor) {\n var size = 2,\n ctx = this.context,\n curPenStyle = this.penStyle,\n \t\t\tcurFillStyle = this.fillStyle;\n\n if (arguments.length >= 1) {\n size = psize;\n }\n size = size * this.turtleCanvas.lineScale;\n\n if (!this.animate) {\n \t\t\tif (pcolor) {\n \t\t\t\tctx.fillStyle = pcolor;\n\t\t\t\tctx.strokeStyle = pcolor;\n\t\t\t}\n ctx.fillRect(this.position[0] - size / 2, this.position[1] - size / 2, size, size);\n\t\t\tif (pcolor) {\n \t\t\t\tctx.fillStyle = curFillStyle;\n\t\t\t\tctx.strokeStyle = curPenStyle;\n\t\t\t}\n } else {\n this.addDrawingEvent([\n 'DT',\n size,\n pcolor || ctx.strokeStyle,\n this.position[0],\n this.position[1]\n ]);\n }\n };\n Turtle.prototype.circle = function (radius, extent) {\n var arcLen, segLen, extentPart, extentLeft;\n if (extent === undefined) {\n extent = 360;\n }\n if (this.animate) {\n arcLen = Math.abs(radius * Math.PI * 2 * extent / 360);\n segLen = this.turtleCanvas.getSegmentLength();\n if (arcLen <= segLen) {\n this.arc(radius, extent);\n } else {\n //Break the arc into segments for animation\n extentPart = segLen / arcLen * extent;\n extentLeft = extent;\n while (Math.abs(extentLeft) > Math.abs(extentPart)) {\n this.arc(radius, extentPart);\n extentLeft = extentLeft - extentPart;\n }\n if (Math.abs(extentLeft) > 0.01) {\n this.arc(radius, extentLeft);\n }\n }\n if (!this.turtleCanvas.isAnimating()) {\n this.turtleCanvas.startAnimating(this);\n } else {\n if (!this.turtleCanvas.onCanvas(this)) {\n this.turtleCanvas.addToCanvas(this);\n }\n }\n } else {\n this.arc(radius, extent);\n }\n };\n Turtle.prototype.arc = function (radius, extent) {\n //Figure out where the turtle is and which way it's facing\n var turtleHeading = this.get_heading(),\n tx = this.position[0],\n ty = this.position[1],\n //Figure out the circle center\n cx = tx + radius * Math.cos((turtleHeading + 90) * Degree2Rad),\n cy = ty + radius * Math.sin((turtleHeading + 90) * Degree2Rad),\n //Canvas arc angles go CLOCKWISE, not COUNTERCLOCKWISE like Turtle\n //Figure out our arc angles\n startAngleDeg,\n endAngleDeg,\n startAngle,\n endAngle,\n turtleArc,\n newTurtleHeading,\n nx,\n ny;\n\n if (radius >= 0) {\n startAngleDeg = turtleHeading - 90;\n } else {\n startAngleDeg = turtleHeading + 90;\n }\n\n if (extent) {\n if (radius >= 0) {\n endAngleDeg = startAngleDeg + extent;\n } else {\n endAngleDeg = startAngleDeg - extent;\n }\n } else {\n if (radius >= 0) {\n endAngleDeg = startAngleDeg + 360;\n } else {\n endAngleDeg = startAngleDeg - 360;\n }\n }\n //Canvas angles are opposite\n startAngleDeg = 360 - startAngleDeg;\n endAngleDeg = 360 - endAngleDeg;\n //Becuase the y axis has been flipped in HTML5 Canvas with a tanslation, we need to adjust the angles\n startAngleDeg = -startAngleDeg;\n endAngleDeg = -endAngleDeg;\n //Convert to radians\n startAngle = startAngleDeg * Degree2Rad;\n endAngle = endAngleDeg * Degree2Rad;\n //Do the drawing\n if (!this.animate) {\n if (!this.filling) {\n this.context.beginPath();\n }\n this.context.arc(cx, cy, Math.abs(radius), startAngle, endAngle, radius * extent <= 0);\n this.context.stroke();\n if (!this.filling) {\n this.context.closePath();\n }\n } else {\n this.addDrawingEvent([\n 'CI',\n cx,\n cy,\n Math.abs(radius),\n startAngle,\n endAngle,\n radius * extent <= 0\n ]);\n }\n //Move the turtle only if we have to\n if (extent && extent % 360 !== 0) {\n if (radius >= 0) {\n turtleArc = extent;\n } else {\n turtleArc = -extent;\n }\n newTurtleHeading = (turtleHeading + turtleArc) % 360;\n if (newTurtleHeading < 0) {\n newTurtleHeading = newTurtleHeading + 360;\n }\n nx = cx + radius * Math.cos((newTurtleHeading - 90) * Degree2Rad);\n ny = cy + radius * Math.sin((newTurtleHeading - 90) * Degree2Rad);\n //y coord is inverted in turtle\n //Move it internally\n this.set_heading(newTurtleHeading);\n this.teleport_to(nx, ny);\n //If we're animating the turtle, move it on the screen\n if (this.animate) {\n this.addDrawingEvent([\n 'TT',\n this.heading\n ]);\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 }\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 }\n this.addDrawingEvent([\n 'WT',\n theText,\n fontspec,\n this.position[0],\n 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 // Pen and Style functions\n //\n Turtle.prototype.pen_down = function () {\n this.pen = true;\n };\n Turtle.prototype.down = Turtle.prototype.pen_down;\n Turtle.prototype.pen_up = function () {\n this.pen = false;\n };\n Turtle.prototype.up = Turtle.prototype.pen_up;\n Turtle.prototype.get_pen = function () {\n return this.pen;\n };\n Turtle.prototype.set_pen_width = function (w) {\n if (this.animate) {\n this.addDrawingEvent([\n 'PW',\n w * this.turtleCanvas.lineScale\n ]);\n } else {\n this.penWidth = w;\n }\n };\n Turtle.prototype.get_pen_width = function () {\n return this.penWidth * this.turtleCanvas.lineScale;\n };\n Turtle.prototype.set_pen_color = function (c, g, b) {\n if (typeof c === 'string') {\n this.penStyle = c;\n } else {\n var rs, gs, bs, c0, c1, c2;\n if (Array.isArray(c)) {\n c0 = c[0];\n c1 = c[1];\n c2 = c[2];\n } else {\n c0 = c;\n c1 = g;\n c2 = b;\n }\n rs = Math.abs(c0).toString(16);\n gs = Math.abs(c1).toString(16);\n bs = Math.abs(c2).toString(16);\n while (rs.length < 2) {\n rs = '0' + rs;\n }\n while (gs.length < 2) {\n gs = '0' + gs;\n }\n while (bs.length < 2) {\n bs = '0' + bs;\n }\n c = '#' + rs + gs + bs;\n this.penStyle = c;\n }\n this.context.strokeStyle = c;\n if (this.animate) {\n this.addDrawingEvent([\n 'TC',\n c\n ]);\n }\n };\n Turtle.prototype.set_fill_color = function (c, g, b) {\n if (typeof c === 'string') {\n this.fillStyle = c;\n } else {\n var rs, gs, bs, c0, c1, c2;\n if (Array.isArray(c)) {\n c0 = c[0];\n c1 = c[1];\n c2 = c[2];\n } else {\n c0 = c;\n c1 = g;\n c2 = b;\n }\n rs = Math.abs(c0).toString(16);\n gs = Math.abs(c1).toString(16);\n bs = Math.abs(c2).toString(16);\n while (rs.length < 2) {\n rs = '0' + rs;\n }\n while (gs.length < 2) {\n gs = '0' + gs;\n }\n while (bs.length < 2) {\n bs = '0' + bs;\n }\n c = '#' + rs + gs + bs;\n this.fillStyle = c;\n }\n this.context.fillStyle = c;\n if (this.animate) {\n this.addDrawingEvent([\n 'FC',\n c\n ]);\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([\n 'BF',\n this.position[0],\n 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([\n 'EF',\n this.position[0],\n this.position[1],\n 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 Turtle.prototype.hideturtle = function () {\n if (this.animate) {\n this.addDrawingEvent(['HT']);\n }\n this.visible = false;\n };\n Turtle.prototype.isvisible = function () {\n return this.visible;\n };\n //\n // Appearance\n //\n Turtle.prototype.shape = function (s) {\n if (this.shapeStore[s]) {\n this.addDrawingEvent(['CS', s]); // add a Change Shape event\n }\n };\n Turtle.prototype.drawturtle = function (pHeading, pos) {\n var rtPoints = [],\n plist = this.shapeStore[this.currentShape],\n head,\n p,\n i;\n\n if (pHeading !== undefined) {\n head = pHeading - 90;\n } else {\n head = this.heading.toAngle() - 90;\n }\n\n if (!pos) {\n pos = this.position;\n }\n\n for (p = 0; p < plist.length; p = p + 1) {\n rtPoints.push(plist[p]\n .scale(this.turtleCanvas.xptscale, this.turtleCanvas.yptscale)\n .rotate(head)\n .add(pos));\n }\n this.context.beginPath();\n this.context.moveTo(rtPoints[0][0], rtPoints[0][1]);\n for (i = 1; i < rtPoints.length; i = i + 1) {\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 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([\n 'ST',\n this.position[0],\n this.position[1],\n this.heading.toAngle()\n ]);\n } else {\n this.drawturtle();\n }\n };\n Turtle.prototype.clear = function () {\n if (this.animate) {\n this.addDrawingEvent(['CL']);\n } else {\n \t\t\tclear_canvas(this.canvasID);\n\t\t\tthis.penStyle = 'black';\n\t\t\tthis.penWidth = 2;\n\t\t\tthis.fillStyle = 'black';\n }\n };\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// Wrapper around the Turtle Module starts here.\n//\n var $builtinmodule = function (name) {\n 'use strict';\n var mod = {},\n \t\tinitializeTurtlegraphics = function() {\n \t\t\tif (!TurtleGraphics) { TurtleGraphics = {}; }\n\t\t\tif (!TurtleGraphics.defaults) {\n \t\t\t\tTurtleGraphics.defaults = {\n\t\t\t\t\tanimate: true,\n\t\t\t\t\tcanvasID: Sk.canvas,\n\t\t\t\t\tdegrees: true\n\t\t\t\t}\n \t\t\t} else if (Sk.canvas) {\n \t\t\t\tTurtleGraphics.defaults.canvasID = Sk.canvas;\n\t\t\t}\n\t\t\tif (!TurtleGraphics.doneDelegates) { TurtleGraphics.doneDelegates = []; }\n\t\t},\n\t\tremoveDisabled = function () {\n \t\t\tif (Sk.runButton) {\n \t\t\t\tSk.runButton.removeAttribute('disabled');\n\t\t\t}\n\t\t},\n checkArgs = function (expected, actual, func) {\n if (actual !== expected) {\n throw new Sk.builtin.TypeError(func + ' takes exactly ' + expected + ' positional argument (' + actual + ' given)');\n }\n },\n turtle = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n \t\t\t\tinitializeTurtlegraphics();\n\t\t\t\tif (TurtleGraphics.doneDelegates.indexOf(removeDisabled) === -1){\n \t\t\t\t\tTurtleGraphics.doneDelegates.push(removeDisabled);\n\t\t\t\t}\n self.theTurtle = new TurtleGraphics.Turtle();\n });\n //\n // Turtle Motion\n //\n //\n // Move and Draw\n //\n $loc.forward = new Sk.builtin.func(function (self, dist) {\n dist = Sk.builtin.asnum$(dist);\n checkArgs(2, arguments.length, 'forward()');\n self.theTurtle.forward(dist);\n });\n $loc.fd = $loc.forward;\n $loc.backward = new Sk.builtin.func(function (self, dist) {\n dist = Sk.builtin.asnum$(dist);\n checkArgs(2, arguments.length, 'backward()');\n self.theTurtle.forward(-dist);\n });\n $loc.back = $loc.backward;\n $loc.bk = $loc.backward;\n $loc.right = new Sk.builtin.func(function (self, angle) {\n angle = Sk.builtin.asnum$(angle);\n checkArgs(2, arguments.length, 'right()');\n self.theTurtle.turn(angle);\n });\n $loc.rt = $loc.right;\n $loc.left = new Sk.builtin.func(function (self, angle) {\n angle = Sk.builtin.asnum$(angle);\n checkArgs(2, arguments.length, 'left()');\n self.theTurtle.turn(-angle);\n });\n $loc.lt = $loc.left;\n $loc.goto_$rw$ = new Sk.builtin.func(function (self, nx, ny) {\n nx = Sk.builtin.asnum$(nx);\n ny = Sk.builtin.asnum$(ny);\n checkArgs(3, arguments.length, 'goto()');\n self.theTurtle.goto(nx, ny);\n });\n $loc.setposition = new Sk.builtin.func(function (self, nx, ny) {\n nx = Sk.builtin.asnum$(nx);\n ny = 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 $loc.setx = new Sk.builtin.func(function (self, nx) {\n nx = Sk.builtin.asnum$(nx);\n checkArgs(2, arguments.length, 'setx()');\n self.theTurtle.goto(nx, self.theTurtle.GetY());\n });\n $loc.sety = new Sk.builtin.func(function (self, ny) {\n ny = Sk.builtin.asnum$(ny);\n checkArgs(2, arguments.length, 'sety()');\n self.theTurtle.goto(self.theTurtle.GetX(), ny);\n });\n $loc.setheading = new Sk.builtin.func(function (self, newhead) {\n newhead = Sk.builtin.asnum$(newhead);\n checkArgs(2, arguments.length, 'setheading()');\n return self.theTurtle.set_heading(newhead);\n });\n $loc.seth = $loc.setheading;\n $loc.home = new Sk.builtin.func(function (self) {\n self.theTurtle.go_home();\n });\n $loc.dot = new Sk.builtin.func(function (self, size, color) {\n size = 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 $loc.circle = new Sk.builtin.func(function (self, radius, extent) {\n radius = Sk.builtin.asnum$(radius);\n extent = Sk.builtin.asnum$(extent);\n self.theTurtle.circle(radius, extent);\n });\n $loc.delay = new Sk.builtin.func(function (self, d) {\n d = Sk.builtin.asnum$(d);\n return self.theTurtle.delay(d);\n });\n $loc.speed = new Sk.builtin.func(function (self, s, t) {\n s = Sk.builtin.asnum$(s);\n t = Sk.builtin.asnum$(t);\n self.theTurtle.speed(s, t);\n });\n $loc.tracer = new Sk.builtin.func(function (self, t, d) {\n t = Sk.builtin.asnum$(t);\n d = Sk.builtin.asnum$(d);\n self.theTurtle.tracer(t, d);\n });\n $loc.update = new Sk.builtin.func(function (self) {});\n // todo: stamp, clearstamp, clearstamps, undo, speed\n //\n // Tell Turtle's state\n //\n $loc.heading = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'heading()');\n return Sk.builtin.assk$(self.theTurtle.get_heading(), Sk.builtin.nmber.float$);\n });\n $loc.position = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'position()');\n var res = self.theTurtle.get_position(),\n x = new Sk.builtin.tuple([\n Sk.builtin.assk$(res[0], Sk.builtin.nmber.float$),\n Sk.builtin.assk$(res[1], Sk.builtin.nmber.float$)\n ]);\n return x;\n });\n $loc.pos = $loc.position;\n $loc.xcor = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'xcor()');\n var res = self.theTurtle.getx();\n return Sk.builtin.assk$(res, Sk.builtin.nmber.float$);\n });\n $loc.ycor = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'ycor()');\n var res = self.theTurtle.gety();\n return Sk.builtin.assk$(res, Sk.builtin.nmber.float$);\n });\n $loc.towards = new Sk.builtin.func(function (self, tx, ty) {\n tx = Sk.builtin.asnum$(tx);\n ty = Sk.builtin.asnum$(ty);\n if ((typeof tx).toLowerCase() === 'number') {\n tx = [ tx, ty, 0 ];\n } else {\n tx = [\n Sk.builtin.asnum$(tx.theTurtle.getx()),\n Sk.builtin.asnum$(tx.theTurtle.gety()),\n Sk.builtin.asnum$(0)\n ];\n }\n return Sk.builtin.assk$(self.theTurtle.towards(tx), Sk.builtin.nmber.float$);\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 tx = Sk.builtin.asnum$(tx);\n ty = Sk.builtin.asnum$(ty);\n if ((typeof tx).toLowerCase() === 'number') {\n tx = [\n tx,\n ty,\n 0\n ];\n } else {\n tx = [\n tx.theTurtle.getx(),\n tx.theTurtle.gety(),\n 0\n ];\n }\n return Sk.builtin.assk$(self.theTurtle.distance(tx), Sk.builtin.nmber.float$);\n });\n //\n // Setting and Measurement\n //\n // todo: degrees and radians...\n //\n // Pen Control\n //\n //\n // Drawing State\n //\n $loc.up = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'up()');\n self.theTurtle.pen_up();\n });\n $loc.penup = $loc.up;\n $loc.pu = $loc.up;\n $loc.down = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'down()');\n self.theTurtle.pen_down();\n });\n $loc.pendown = $loc.down;\n $loc.pd = $loc.down;\n $loc.width = new Sk.builtin.func(function (self, w) {\n w = Sk.builtin.asnum$(w);\n checkArgs(2, arguments.length, 'width()');\n self.theTurtle.set_pen_width(w);\n });\n $loc.pensize = $loc.width;\n $loc.isdown = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'isdown()');\n return self.theTurtle.get_pen();\n });\n // todo: pen -- return a dictionary full of pen stuff\n //\n // Color Control\n //\n $loc.fillcolor = new Sk.builtin.func(function (self, color, green, blue) {\n if (color) {\n if (blue) {\n color = Sk.builtin.asnum$(color);\n green = Sk.builtin.asnum$(green);\n blue = Sk.builtin.asnum$(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 color = Sk.builtin.asnum$(color);\n green = Sk.builtin.asnum$(green);\n blue = 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 color = Sk.builtin.asnum$(color);\n green = Sk.builtin.asnum$(green);\n blue = Sk.builtin.asnum$(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 [\n self.theTurtle.penStyle,\n self.theTurtle.fillStyle\n ];\n }\n });\n //\n // Filling\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 $loc.end_fill = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'end_fill()');\n self.theTurtle.end_fill();\n });\n $loc.fill = new Sk.builtin.func(function (self, fillt) {\n if (fillt === undefined) {\n return self.theTurtle.filling;\n }\n if (fillt) {\n self.theTurtle.begin_fill();\n } else {\n self.theTurtle.end_fill();\n }\n });\n //\n // More drawing control\n //\n $loc.reset = new Sk.builtin.func(function (self) {\n self.theTurtle.clean();\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 $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 $loc.isvisible = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'isvisible()');\n self.theTurtle.isvisible();\n });\n $loc.stamp = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'stamp()');\n self.theTurtle.stamp();\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 //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 //todo clean -- again multiple turtles\n $loc.setworldcoordinates = new Sk.builtin.func(function (self, llx, lly, urx, ury) {\n llx = Sk.builtin.asnum$(llx);\n lly = Sk.builtin.asnum$(lly);\n urx = Sk.builtin.asnum$(urx);\n ury = Sk.builtin.asnum$(ury);\n self.theTurtle.setworldcoordinates(llx, lly, urx, ury);\n });\n //Added by RNL\n $loc.clear = new Sk.builtin.func(function (self) {\n self.theTurtle.clear();\n });\n },\n screen = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n \t\t\t\tinitializeTurtlegraphics();\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 $loc.bgcolor = new Sk.builtin.func(function (self, c) {\n self.theScreen.bgcolor(c);\n });\n $loc.setworldcoordinates = new Sk.builtin.func(function (self, llx, lly, urx, ury) {\n llx = Sk.builtin.asnum$(llx);\n lly = Sk.builtin.asnum$(lly);\n urx = Sk.builtin.asnum$(urx);\n ury = Sk.builtin.asnum$(ury);\n self.theScreen.setworldcoordinates(llx, lly, urx, ury);\n });\n $loc.exitonclick = new Sk.builtin.func(function (self) {\n self.theScreen.exitonclick();\n });\n $loc.title = new Sk.builtin.func(function (self, titlestring) {});\n $loc.window_width = new Sk.builtin.func(function (self) {\n return Sk.builtin.assk$(self.theScreen.window_width(), Sk.builtin.nmber.int$);\n });\n $loc.window_height = new Sk.builtin.func(function (self) {\n return Sk.builtin.assk$(self.theScreen.window_height(), Sk.builtin.nmber.int$);\n });\n $loc.turtles = new Sk.builtin.func(function (self) {\n return self.theScreen.turtles();\n });\n $loc.colormode = new Sk.builtin.func(function (self) {});\n // $loc.clear = new Sk.builtin.func(function(self) {\n //\n // });\n var myfunc = function (self, width, height, startx, starty) {\n width = Sk.builtin.asnum$(width);\n height = Sk.builtin.asnum$(height);\n self.theScreen.setup(width, height);\n };\n // this should allow for named parameters\n myfunc.co_varnames = [\n 'self',\n 'width',\n 'height',\n 'startx',\n 'starty'\n ];\n myfunc.$defaults = [\n null,\n 500,\n 500,\n 0,\n 0\n ];\n $loc.setup = new Sk.builtin.func(myfunc);\n };\n // First we create an object, this will end up being the class\n // class\n Sk.tg = TurtleGraphics;\n mod.Turtle = Sk.misceval.buildClass(mod, turtle, 'Turtle', []);\n mod.Screen = Sk.misceval.buildClass(mod, screen, 'Screen', []);\n mod.tracer = new Sk.builtin.func(function (t, d) {\n var i;\n t = Sk.builtin.asnum$(t);\n d = Sk.builtin.asnum$(d);\n for (i = 0; i < Sk.tg.canvasLib.length; i = i + 1) {\n Sk.tg.canvasLib[i].tracer(t, d);\n }\n });\n mod.update = new Sk.builtin.func(function (self) {});\n return mod;\n };\n ", "src/lib/van/__init__.js": "//\n// Controller for a van\n//\n function VanController() {\n this.initialize();\n }\n VanController.prototype.initialize = function () {\n\n };\n VanController.prototype.highlightLineCallable = function(lineIndex, colour) {\n var lines = $('#editor .CodeMirror-code')[0].children;\n // unhighlight all lines\n var i;\n for (i = 0; i < lines.length; i++) {\n lines[i].style.background = \"\";\n }\n // highlight desired line\n lines[lineIndex].style.background = colour;\n };\n VanController.prototype.queueHighlight = function(colour) {\n var self = this;\n var lineIndex = Sk.currLineNo - 1;\n ocargo.animation.appendAnimation({\n type: 'callable',\n functionCall: function () { self.highlightLineCallable(lineIndex, colour); },\n description: 'highlight python callable',\n });\n };\n//\n// Movement and condition functions delegated appropriately\n//\n VanController.prototype.move_forwards = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.moveForwards();\n };\n VanController.prototype.turn_left = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed |= Sk.failed || !ocargo.model.turnLeft();\n };\n VanController.prototype.turn_right = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.turnRight();\n };\n VanController.prototype.turn_around = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.turnAround();\n };\n VanController.prototype.wait = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.wait();\n };\n VanController.prototype.deliver = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.deliver();\n };\n VanController.prototype.sound_horn = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n return ocargo.model.sound_horn();\n }\n return false;\n };\n VanController.prototype.at_dead_end = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isDeadEnd();\n }\n return false;\n };\n VanController.prototype.at_destination = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isAtADestination();\n }\n return false;\n };\n VanController.prototype.at_traffic_light = function (c) {\n switch(c) {\n case \"GREEN\":\n return this.at_green_traffic_light();\n break;\n case \"RED\":\n return this.at_red_traffic_light();\n break;\n default:\n return false;\n }\n };\n VanController.prototype.at_red_traffic_light = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isTrafficLightRed();\n }\n return false;\n };\n VanController.prototype.at_green_traffic_light = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isTrafficLightGreen();\n }\n return false;\n };\n VanController.prototype.is_road = function (d) {\n switch(d) {\n case \"FORWARD\":\n return this.is_road_forward();\n break;\n case \"LEFT\":\n return this.is_road_left();\n break;\n case \"RIGHT\":\n return this.is_road_right();\n break;\n default:\n return false;\n }\n };\n VanController.prototype.is_road_forward = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isRoadForward();\n }\n return false;\n\n };\n VanController.prototype.is_road_left = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isRoadLeft();\n }\n return false;\n };\n VanController.prototype.is_road_right = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isRoadRight();\n }\n return false;\n };\n VanController.prototype.is_animal_crossing = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isCowCrossing();\n }\n return false;\n };\n VanController.prototype.get_current_coordinate = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n var coordinate = ocargo.model.getCurrentCoordinate();\n return [coordinate.x, coordinate.y];\n }\n return null;\n };\n VanController.prototype.get_previous_coordinate = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n var coordinate = ocargo.model.getPreviousCoordinate();\n return [coordinate.x, coordinate.y];\n }\n return null;\n };\n\n var $builtinmodule = function (name) {\n 'use strict';\n var mod = {},\n checkArgs = function (expected, actual, func) {\n if (actual !== expected) {\n throw new Sk.builtin.TypeError(func + ' takes exactly ' + expected + ' positional argument (' + actual + ' given)');\n }\n },\n van = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n self.theVan = new VanController();\n });\n //\n // Van Action/Motion\n //\n $loc.move_forwards = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'move_forwards()');\n self.theVan.move_forwards();\n });\n $loc.turn_left = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'turn_left()');\n self.theVan.turn_left();\n });\n $loc.turn_right = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'turn_right()');\n self.theVan.turn_right();\n });\n $loc.turn_around = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'turn_around()');\n self.theVan.turn_around();\n });\n $loc.wait = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'wait()');\n self.theVan.wait();\n });\n $loc.deliver = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'deliver()');\n self.theVan.deliver();\n });\n $loc.sound_horn = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'sound_horn()');\n self.theVan.sound_horn();\n });\n //\n // Van state\n //\n $loc.at_dead_end = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_dead_end()');\n return Sk.builtin.bool(self.theVan.at_dead_end());\n });\n $loc.at_destination = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_destination()');\n return Sk.builtin.bool(self.theVan.at_destination());\n });\n $loc.at_traffic_light = new Sk.builtin.func(function (self, c) {\n checkArgs(2, arguments.length, 'at_traffic_light()');\n return Sk.builtin.bool(self.theVan.at_traffic_light(new Sk.builtin.str(c).v));\n });\n $loc.at_red_traffic_light = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_red_traffic_light()');\n return Sk.builtin.bool(self.theVan.at_red_traffic_light());\n });\n $loc.at_green_traffic_light = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_green_traffic_light()');\n return Sk.builtin.bool(self.theVan.at_green_traffic_light());\n });\n $loc.is_road = new Sk.builtin.func(function (self, d) {\n checkArgs(2, arguments.length, 'is_road()');\n return Sk.builtin.bool(self.theVan.is_road(new Sk.builtin.str(d).v));\n });\n $loc.is_road_forward = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_road_forward()');\n return Sk.builtin.bool(self.theVan.is_road_forward());\n });\n $loc.is_road_left = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_road_left()');\n return Sk.builtin.bool(self.theVan.is_road_left());\n });\n $loc.is_road_right = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_road_right()');\n return Sk.builtin.bool(self.theVan.is_road_right());\n });\n $loc.is_animal_crossing = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_animal_crossing()');\n return Sk.builtin.bool(self.theVan.is_animal_crossing());\n });\n $loc.get_current_coordinate = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'get_current_coordinate()');\n var coordinate = self.theVan.get_current_coordinate();\n if (coordinate) {\n return Sk.builtin.tuple(coordinate);\n } else {\n return Sk.builtin.none;\n }\n });\n $loc.get_previous_coordinate = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'get_previous_coordinate()');\n var coordinate = self.theVan.get_previous_coordinate();\n if (coordinate) {\n return Sk.builtin.tuple(coordinate);\n } else {\n return Sk.builtin.none;\n }\n });\n };\n\n mod.Van = Sk.misceval.buildClass(mod, van, 'Van', []);\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/lib/pythonds/graphs/__init__.py": "\n\n from .adjGraph import Graph\n from .adjGraph import Vertex\n from .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 #\n import unittest\n\n # this implementation of binary heap takes key value pairs,\n # we will assume that the keys are all comparable\n\n class 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\n class 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\n if __name__ == '__main__':\n unittest.main()\n ", "src/lib/pythonds/__init__.py": "", "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\n\n\n class Deque:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def addFront(self, item):\n self.items.append(item)\n\n def addRear(self, item):\n self.items.insert(0,item)\n\n def removeFront(self):\n return self.items.pop()\n\n def removeRear(self):\n return self.items.pop(0)\n\n def size(self):\n return len(self.items)\n ", "src/lib/processing/__init__.js": "var $builtinmodule = function(name)\n {\n var mod = {};\n var imList = [];\n var looping = true;\n\n // We need this to store a reference to the actual processing object which is not created\n // until the run function is called. Even then the processing object is passed by the\n // processing-js sytem as a parameter to the sketchProc function. Why not set it to None here\n //\n\n // See: http://processingjs.org/reference/\n\n mod.processing = null\n mod.p = null\n\n mod.CENTER = Sk.builtin.assk$(3, Sk.builtin.nmber.int$);\n mod.RADIUS = Sk.builtin.assk$(2, Sk.builtin.nmber.int$);\n mod.CORNERS = Sk.builtin.assk$(1, Sk.builtin.nmber.int$);\n mod.CORNER = Sk.builtin.assk$(0, Sk.builtin.nmber.int$);\n mod.RGB = Sk.builtin.assk$(1, Sk.builtin.nmber.int$);\n mod.HSB = Sk.builtin.assk$(3, Sk.builtin.nmber.int$);\n mod.CMYK = Sk.builtin.assk$(5, Sk.builtin.nmber.int$);\n mod.MITER = new Sk.builtin.str('miter');\n mod.BEVEL = new Sk.builtin.str('bevel');\n mod.ROUND = new Sk.builtin.str('round');\n mod.SQUARE = new Sk.builtin.str('butt');\n mod.PROJECT = new Sk.builtin.str('square');\n\n// 2D - Primitives\n mod.line = new Sk.builtin.func(function(x1, y1, x2, y2) {\n mod.processing.line(x1.v, y1.v, x2.v, y2.v);\n });\n\n mod.ellipse = new Sk.builtin.func(function(x,y,r1,r2) {\n mod.processing.ellipse(x.v,y.v,r1.v,r2.v)\n\n });\n\n mod.text = new Sk.builtin.func(function(theText, x, y) {\n mod.processing.text(theText.v, x.v, y.v);\n });\n\n mod.point = new Sk.builtin.func(function(x1,y1) {\n mod.processing.point(x1.v,y1.v)\n });\n\n mod.arc = new Sk.builtin.func(function(x, y, width, height, start, stop) {\n mod.processing.arc(x.v, y.v, width.v, height.v, start.v, stop.v)\n });\n\n mod.quad = new Sk.builtin.func(function(x1, y1, x2, y2, x3, y3, x4, y4) {\n mod.processing.quad(x1.v, y1.v, x2.v, y2.v, x3.v, y3.v, x4.v, y4.v)\n });\n\n mod.rect = new Sk.builtin.func(function(x, y, width, height, radius) {\n if (typeof(radius) == 'undefined') {\n var rad = 0\n } else {\n var rad = radius.v\n }\n mod.processing.rect(x.v, y.v, width.v, height.v, rad)\n });\n\n mod.triangle = new Sk.builtin.func(function(x1, y1, x2, y2, x3, y3) {\n mod.processing.triangle(x1.v, y1.v, x2.v, y2.v, x3.v, y3.v)\n });\n\n\n // 3D Primitives\n\n // todo: box, sphere, sphereDetail\n\n // Color\n mod.background = new Sk.builtin.func(function(r,g,b) {\n\n if (typeof(g) !== 'undefined')\n g = g.v\n if (typeof(b) !== 'undefined')\n b = b.v\n\n mod.processing.background(r.v,g,b)\n\n });\n\n mod.fill = new Sk.builtin.func(function(r,g,b) {\n // r will be either:\n // a number in which case the fill will be grayscale\n // a color object\n // g, and b may be undefined. If they hold values it will\n // be assumed that we have an r,g,b color tuple\n if (typeof(g) !== 'undefined')\n g = g.v\n if (typeof(b) !== 'undefined')\n b = b.v\n\n mod.processing.fill(r.v,g,b)\n\n });\n\n\n mod.stroke = new Sk.builtin.func(function(r,g,b) {\n\n if (typeof(g) !== 'undefined')\n g = g.v\n if (typeof(b) !== 'undefined')\n b = b.v\n\n mod.processing.stroke(r.v,g,b)\n\n });\n\n mod.noStroke = new Sk.builtin.func(function() {\n mod.processing.noStroke()\n });\n\n\n mod.colorMode = new Sk.builtin.func(function(model, maxV) {\n if (typeof(maxV) === 'undefined')\n maxV = 255\n else\n maxV = maxV.v\n mod.processing.colorMode(model.v, maxV)\n });\n\n mod.noFill = new Sk.builtin.func(function() {\n mod.processing.noFill()\n });\n\n\n // Environment\n\n mod.loop = new Sk.builtin.func(function() {\n if (mod.processing === null) {\n throw new Sk.builtin.Exception(\"Loop should be called in setup\")\n }\n looping = true;\n mod.processing.loop()\n });\n\n mod.noLoop = new Sk.builtin.func(function() {\n if (mod.processing === null) {\n throw new Sk.builtin.Exception(\"noLoop should be called in setup\")\n }\n looping = false;\n mod.processing.noLoop()\n });\n\n mod.frameRate = new Sk.builtin.func(function(fr) {\n mod.processing.frameRate(fr.v)\n\n });\n\n mod.size = new Sk.builtin.func(function(h,w) {\n mod.processing.size(h.v,w.v)\n\n });\n\n mod.exitp = new Sk.builtin.func(function(h,w) {\n mod.processing.exit()\n });\n\n\n mod.mouseX = new Sk.builtin.func(function() {\n return Sk.builtin.assk$(mod.processing.mouseX, Sk.builtin.nmber.int$);\n\n });\n\n mod.mouseY = new Sk.builtin.func(function() {\n return Sk.builtin.assk$(mod.processing.mouseY, Sk.builtin.nmber.int$);\n\n });\n\n // Attributes\n mod.rectMode = new Sk.builtin.func(function(mode) {\n mod.processing.rectMode(mode.v)\n });\n\n mod.strokeWeight = new Sk.builtin.func(function(wt) {\n mod.processing.strokeWeight(wt.v)\n\n });\n\n mod.smooth = new Sk.builtin.func(function() {\n mod.processing.smooth()\n });\n\n mod.noSmooth = new Sk.builtin.func(function() {\n mod.processing.noSmooth()\n });\n\n mod.ellipseMode = new Sk.builtin.func(function(mode) {\n mod.processing.ellipseMode(mode.v)\n });\n\n mod.strokeCap = new Sk.builtin.func(function(mode) {\n mod.processing.strokeCap(mode.v)\n });\n\n mod.strokeJoin = new Sk.builtin.func(function(mode) {\n mod.processing.strokeJoin(mode.v)\n });\n\n\n\n // Transforms\n\n mod.rotate = new Sk.builtin.func(function(rads) {\n // rotation in radians\n mod.processing.rotate(rads.v)\n\n });\n\n mod.scale = new Sk.builtin.func(function(sx, sy, sz) {\n if (typeof(sy) == 'undefined') {\n sy = 1.0\n } else\n sy = sy.v\n if (typeof(sz) == 'undefined') {\n sz = 1.0\n } else\n sz = sz.v\n mod.processing.scale(sx.v, sy, sz)\n });\n\n mod.translate = new Sk.builtin.func(function(sx, sy, sz) {\n if (typeof(sy) == 'undefined') {\n sy = 1.0\n } else\n sy = sy.v\n if (typeof(sz) == 'undefined') {\n sz = 1.0\n } else\n sz = sz.v\n mod.processing.translate(sx.v, sy, sz)\n });\n\n // todo: applyMatrix, popMatrix, printMatrix??, pushMatrix, resetMatrix, rotate{X,Y,Z}\n\n\n // //////////////////////////////////////////////////////////////////////\n // Run\n //\n // Create the processing context and setup of calls to setup, draw etc.\n //\n //\n // //////////////////////////////////////////////////////////////////////\n mod.run = new Sk.builtin.func(function() {\n function sketchProc(processing) {\n mod.processing = processing\n\n // processing.setup = function() {\n // if Sk.globals['setup']\n // Sk.misceval.callsim(Sk.globals['setup'])\n // }\n\n\n processing.draw = function() {\n // if there are pending image loads then just use the natural looping calls to\n // retry until all the images are loaded. If noLoop was called in setup then make\n // sure to revert to that after all the images in hand.\n var wait = false\n for (var i in imList) {\n if (imList[i].width == 0) {\n wait = true\n }\n }\n if (wait == true) {\n if (looping == true)\n return\n else {\n processing.loop()\n return\n }\n\n } else {\n if (looping == false)\n processing.noLoop()\n }\n\n mod.frameCount = processing.frameCount\n if (Sk.globals['draw'])\n Sk.misceval.callsim(Sk.globals['draw'])\n }\n\n var callBacks = ['setup', 'mouseMoved','mouseClicked', 'mouseDragged', 'mouseMoved', 'mouseOut',\n 'mouseOver', 'mousePressed', 'mouseReleased', 'keyPressed', 'keyReleased', 'keyTyped'\n ];\n\n for(var cb in callBacks) {\n if (Sk.globals[callBacks[cb]]) {\n console.log('defining ' + callBacks[cb])\n processing[callBacks[cb]] = new Function(\"Sk.misceval.callsim(Sk.globals['\"+callBacks[cb]+\"']);\")\n }\n }\n }\n\n var canvas = document.getElementById(Sk.canvas)\n $(canvas).show()\n mod.p = new Processing(canvas, sketchProc)\n\n\n });\n\n var mouseClass = function($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'x')\n return mod.processing.mouseX;\n else if (key == 'y')\n return mod.processing.mouseY;\n else if (key == 'px')\n return mod.processing.pmouseX;\n else if (key == 'py')\n return mod.processing.pmouseY;\n else if (key == 'pressed')\n return mod.processing.mousePressed;\n else if (key == 'button')\n return mod.processing.mouseButton\n });\n\n\n }\n\n\n mod.Mouse = Sk.misceval.buildClass(mod, mouseClass, 'Mouse', []);\n\n mod.mouse = Sk.misceval.callsim(mod.Mouse)\n\n var keyboardClass = function($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'key') {\n console.log(mod.processing.key)\n return new Sk.builtin.str(mod.processing.key.toString())\n }\n else if (key == 'keyCode')\n return mod.processing.keyCode\n else if (key == 'keyPressed')\n return new Sk.builtin.str(mod.processing.keyPressed) // todo bool\n });\n\n\n }\n\n mod.Keyboard = Sk.misceval.buildClass(mod,keyboardClass,'Keyboard', [])\n\n mod.keyboard = Sk.misceval.callsim(mod.Keyboard)\n\n\n\n var environmentClass = function($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'frameCount')\n return mod.processing.frameCount\n else if (key == 'frameRate')\n return mod.processing.frameRate\n else if (key == 'height')\n return mod.processing.height\n else if (key == 'width')\n return mod.processing.width\n else if (key == 'online')\n return mod.processing.online\n else if (key == 'focused')\n return mod.processing.focused\n });\n\n\n }\n\n mod.Environment = Sk.misceval.buildClass(mod,environmentClass,'Environment', [])\n\n mod.environment = Sk.misceval.callsim(mod.Environment)\n\n var screenClass = function($gbl, $loc) {\n\n $loc.__init__ = new Sk.builtin.func(function(self) {\n self.pixels = null;\n });\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'height')\n return mod.processing.height\n else if (key == 'width')\n return mod.processing.width\n else if (key == 'pixels')\n if (self.pixels == null) {\n self.pixels = new Sk.builtin.list(mod.processing.pixels.toArray())\n }\n return self.pixels\n });\n\n }\n\n mod.Screen = Sk.misceval.buildClass(mod,screenClass,'Screen', [])\n\n mod.screen = Sk.misceval.callsim(mod.Screen)\n\n mod.loadPixels = new Sk.builtin.func(function() {\n mod.processing.loadPixels()\n console.log(mod.processing.pixels)\n });\n\n\n var colorClass = function($gbl, $loc) {\n /* images are loaded async.. so its best to preload them */\n $loc.__init__ = new Sk.builtin.func(function(self, val1, val2, val3, alpha) {\n if (typeof(val2) !== 'undefined')\n val2 = val2.v\n if (typeof(val3) !== 'undefined')\n val3 = val3.v\n if (typeof(alpha) !== 'undefined')\n alpha = alpha.v\n self.v = mod.processing.color(val1.v, val2, val3, alpha)\n })\n\n }\n\n mod.color = Sk.misceval.buildClass(mod,colorClass,'color', [])\n\n mod.red = new Sk.builtin.func(function(clr) {\n return Sk.builtin.assk$(mod.processing.red(clr.v), Sk.builtin.nmber.int$);\n });\n\n mod.green = new Sk.builtin.func(function(clr) {\n return Sk.builtin.assk$(mod.processing.green(clr.v), Sk.builtin.nmber.int$);\n });\n\n mod.blue = new Sk.builtin.func(function(clr) {\n return Sk.builtin.assk$(mod.processing.blue(clr.v), Sk.builtin.nmber.int$);\n });\n\n // Image class and functions\n //\n var imageClass = function($gbl, $loc) {\n /* images are loaded async.. so its best to preload them */\n $loc.__init__ = new Sk.builtin.func(function(self,im) {\n self.v = im\n self.width = Sk.builtin.assk$(im.width, Sk.builtin.nmber.int$);\n self.height = Sk.builtin.assk$(im.height, Sk.builtin.nmber.int$);\n })\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'width') return self.v.width;\n if (key == 'height') return self.v.height;\n });\n\n }\n\n mod.PImage = Sk.misceval.buildClass(mod,imageClass,'PImage', [])\n\n mod.loadImage = new Sk.builtin.func(function(imfile) {\n var i = mod.processing.loadImage(imfile.v);\n imList.push(i);\n return Sk.misceval.callsim(mod.PImage,i);\n });\n\n\n mod.image = new Sk.builtin.func(function(im,x,y) {\n if (im.v.width > 0)\n mod.processing.image(im.v,x.v,y.v,im.v.width,im.v.height)\n });\n\n mod.get = new Sk.builtin.func(function(x,y) {\n var clr = mod.processing.get(x.v,y.v)\n return Sk.misceval.callsim(mod.color,\n Sk.builtin.assk$(mod.processing.red(clr), Sk.builtin.nmber.int$),\n Sk.builtin.assk$(mod.processing.green(clr), Sk.builtin.nmber.int$),\n Sk.builtin.assk$(mod.processing.blue(clr), Sk.builtin.nmber.int$));\n });\n\n mod.set = new Sk.builtin.func(function(x, y, color) {\n mod.processing.set(x.v, y.v, color.v)\n });\n\n// todo -- add a color class for creating color objects.\n\n\n return mod;\n }\n ", "src/lib/webgl/models.js": "// most of this file is from/based on 'tdl'\n\n var $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.} 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.} 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\n class 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\n def inorder(tree):\n if tree != None:\n inorder(tree.getLeftChild())\n print(tree.getRootVal())\n inorder(tree.getRightChild())\n\n def 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\n def 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\n def 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\n def 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/builtin/this.py": "s = \"\"\"Gur Mra bs Clguba, ol Gvz Crgref\n\n Ornhgvshy vf orggre guna htyl.\n Rkcyvpvg vf orggre guna vzcyvpvg.\n Fvzcyr vf orggre guna pbzcyrk.\n Pbzcyrk vf orggre guna pbzcyvpngrq.\n Syng vf orggre guna arfgrq.\n Fcnefr vf orggre guna qrafr.\n Ernqnovyvgl pbhagf.\n Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.\n Nygubhtu cenpgvpnyvgl orngf chevgl.\n Reebef fubhyq arire cnff fvyragyl.\n Hayrff rkcyvpvgyl fvyraprq.\n Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.\n Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.\n Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.\n Abj vf orggre guna arire.\n Nygubhtu arire vf bsgra orggre guna *evtug* abj.\n Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.\n Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.\n Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!\"\"\"\n\n d = {}\n for c in (65, 97):\n for i in range(26):\n d[chr(i+c)] = chr((i+13) % 26 + c)\n\n print \"\".join([d.get(c, c) for c in s])\n ", "src/lib/webgl/primitives.js": "// most of this file is from 'tdl'\n\n var $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.} 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.} 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.} 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/document/__init__.js": "var $builtinmodule = function(name) {\n var mod = {};\n\n mod.getElementById = new Sk.builtin.func(function(id) {\n var result = document.getElementById(id.v);\n if (result) {\n return Sk.misceval.callsim(mod.Element,result);\n }\n return Sk.builtin.none.none$;\n });\n\n mod.createElement = new Sk.builtin.func(function(eName) {\n var r = document.createElement(eName.v);\n if (r) {\n return Sk.misceval.callsim(mod.Element,r);\n }\n });\n\n\n mod.getElementsByTagName = new Sk.builtin.func(function(tag) {\n var r = document.getElementsByTagName(tag.v)\n var reslist = [];\n for (var i = r.length - 1; i >= 0; i--) {\n reslist.push(Sk.misceval.callsim(mod.Element,r[i]))\n }\n return new Sk.builtin.list(reslist)\n });\n\n mod.getElementsByClassName = new Sk.builtin.func(function(cname) {\n var r = document.getElementsByClassName(cname.v);\n var reslist = [];\n for (var i = 0; i < r.length; i++) {\n reslist.push(Sk.misceval.callsim(mod.Element,r[i]));\n };\n return new Sk.builtin.list(reslist);\n });\n\n mod.getElementsByName = new Sk.builtin.func(function(cname) {\n var r = document.getElementsByName(cname.v);\n var reslist = [];\n for (var i = 0; i < r.length; i++) {\n reslist.push(Sk.misceval.callsim(mod.Element,r[i]));\n };\n return new Sk.builtin.list(reslist);\n });\n\n mod.currentDiv = new Sk.builtin.func(function() {\n if (Sk.divid !== undefined) {\n return new Sk.builtin.str(Sk.divid)\n }\n else {\n throw new Sk.builtin.AttributeError(\"There is no value set for divid\");\n }\n })\n var elementClass = function($gbl, $loc) {\n /*\n Notes: self['$d'] is the dictionary used by the GenericGetAttr mechanism for an object.\n for various reasons if you create a class in Javascript and have self.xxxx instance\n variables, you cannot say instance.xxx and get the value of the instance variable unless\n it is stored in the self['$d'] object. This seems like a duplication of storage to me\n but that is how it works right now (5/2013)\n\n Writing your own __getattr__ is also an option but this gets very tricky when an attr is\n a method...\n */\n $loc.__init__ = new Sk.builtin.func(function(self,elem) {\n self.v = elem\n self.innerHTML = elem.innerHTML\n self.innerText = elem.innerText\n if (elem.value !== undefined) {\n self.value = elem.value\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('value'), new Sk.builtin.str(self.value))\n }\n\n if (elem.checked !== undefined) {\n self.checked = elem.checked\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('checked'), new Sk.builtin.str(self.checked))\n }\n\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerHTML'), new Sk.builtin.str(self.innerHTML))\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerText'), new Sk.builtin.str(self.innerText))\n\n })\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n $loc.__setattr__ = new Sk.builtin.func(function(self,key,value) {\n if (key === 'innerHTML') {\n self.innerHTML = value\n self.v.innerHTML = value.v\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerHTML'), value)\n }\n if (key === 'innerText') {\n self.innerText = value\n self.v.innerText = value.v\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerText'), value)\n }\n });\n\n\n $loc.appendChild = new Sk.builtin.func(function(self,ch) {\n self.v.appendChild(ch.v);\n });\n\n $loc.removeChild = new Sk.builtin.func(function(self,node) {\n self.v.removeChild(node.v)\n })\n\n // getCSS\n\n $loc.getCSS = new Sk.builtin.func(function(self,key) {\n return new Sk.builtin.str(self.v.style[key.v]);\n });\n\n\n $loc.setCSS = new Sk.builtin.func(function(self,attr,value) {\n self.v.style[attr.v] = value.v\n\n })\n\n $loc.getAttribute = new Sk.builtin.func(function(self,key) {\n var res = self.v.getAttribute(key.v)\n if (res) {\n return new Sk.builtin.str(res)\n } else {\n return Sk.builtin.none.none$;\n }\n });\n\n $loc.setAttribute = new Sk.builtin.func(function(self,attr,value) {\n self.v.setAttribute(attr.v,value.v)\n });\n\n $loc.getProperty = new Sk.builtin.func(function(self,key) {\n var res = self.v[key.v]\n if (res) {\n return new Sk.builtin.str(res)\n } else {\n return Sk.builtin.none.none$;\n }\n });\n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n console.log(self.v.tagName);\n return new Sk.builtin.str(self.v.tagName)\n })\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n return new Sk.builtin.str('[DOM Element]')\n })\n\n\n };\n\n mod.Element = Sk.misceval.buildClass(mod,elementClass,'Element', []);\n\n return mod;\n\n } ", "src/lib/webgl/matrix4.js": "// more from 'tdl'\n var $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/re/__init__.js": "var $builtinmodule = function(name)\n {\n var mod = {};\n\n // Constants (mostly unsupported)\n mod.I = 2;\n mod.IGNORECASE = 2;\n // mod.L = 4;\n // mod.LOCALE = 4;\n mod.M = 8;\n mod.MULTILINE = 8;\n // mod.S = 16;\n // mod.DOTALL = 16;\n // mod.U = 32;\n // mod.UNICODE = 32;\n // mod.X = 64;\n // mod.VERBOSE = 64;\n\n var validGroups = [\"(?:\", \"(?=\", \"(?!\"];\n\n var convert = function(pattern) {\n var newpattern;\n var match;\n var i;\n\n // Look for disallowed constructs\n match = pattern.match(/\\(\\?./g);\n if (match) {\n for (i=0; i= maxsplit)) {\n break;\n };\n };\n result.push(new Sk.builtin.str(str.substring(index)));\n\n return new Sk.builtin.list(result);\n });\n\n mod.findall = Sk.nativejs.func(function findall(pattern, string, flags) {\n Sk.builtin.pyCheckArgs(\"findall\", arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n };\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n };\n if (flags === undefined) {\n flags = 0;\n };\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n };\n\n var pat = Sk.ffi.unwrapo(pattern);\n var str = Sk.ffi.unwrapo(string);\n\n // Convert pat from Python to Javascript regex syntax\n pat = convert(pat);\n //print(\"Pat: \" + pat);\n //print(\"Str: \" + str);\n\n var jsflags = getFlags(flags);\n //print(\"Flags: \", jsflags);\n\n var regex = new RegExp(pat, jsflags);\n\n if (pat.match(/\\$/)) {\n \t var newline_at_end = new RegExp(/\\n$/);\n\t if (str.match(newline_at_end)) {\n \t str = str.slice(0,-1);\n\t }\n }\n\n var result = [];\n var match;\n while ((match = regex.exec(str)) != null) {\n //print(\"Matched '\" + match[0] + \"' at position \" + match.index +\n // \"; next search at \" + regex.lastIndex);\n // print(\"match: \" + JSON.stringify(match));\n if (match.length < 2) {\n result.push(new Sk.builtin.str(match[0]));\n } else if (match.length == 2) {\n result.push(new Sk.builtin.str(match[1]));\n } else {\n var groups = [];\n for (var i=1; i= 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 \tres = res.replace(/([^\\\\]){,(?![^\\[]*\\])/g, '$1{0,');\n var re = eval(res);\n\tvar patt = new RegExp('\\n$');\n\tif (string.v.match(patt))\n\t var matches = string.v.slice(0,-1).match(re);\n\telse\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 \tSk.builtin.pyCheckArgs('search', arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n };\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n };\n\tif (flags === undefined) {\n flags = 0;\n };\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n };\n var res = \"/\"+pattern.v.replace(/\\//g,\"\\\\/\")+\"/\";\n lst = mod._findre(res,string);\n if ( lst.v.length < 1 ) return Sk.builtin.none.none$;\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 \tSk.builtin.pyCheckArgs('match', arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n };\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n };\n\tif (flags === undefined) {\n flags = 0;\n };\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n };\n var res = \"/^\"+pattern.v.replace(/\\//g,\"\\\\/\")+\"/\";\n lst = mod._findre(res,string);\n if ( lst.v.length < 1 ) return Sk.builtin.none.none$;\n var mob = Sk.misceval.callsim(mod.MatchObject, lst, pattern, string);\n return mob;\n });\n\n return mod;\n }\n ", "src/lib/unittest/gui.py": "import document\n from unittest import TestCase\n\n class TestCaseGui(TestCase):\n \tdef __init__(self):\n \t\tTestCase.__init__(self)\n\n\t\tself.divid = document.currentDiv()\n\t\tself.mydiv = document.getElementById(self.divid)\n\t\tres = document.getElementById(self.divid+'_unit_results')\n\t\tif res:\n \t\t\tself.resdiv = res\n\t\t\tres.innerHTML = ''\n\t\telse:\n \t\t\tself.resdiv = document.createElement('div')\n\t\t\tself.resdiv.setAttribute('id',self.divid+'_unit_results')\n\t\t\tself.resdiv.setAttribute('class','unittest-results')\n\t\tself.mydiv.appendChild(self.resdiv)\n\n\n\tdef main(self):\n \t\tl = document.createElement('ul')\n\t\tself.resdiv.appendChild(l)\n\t\tself.resList = l\n\n\t\tfor func in self.tlist:\n \t\t\ttry:\n \t\t\t\tself.setup()\n\t\t\t\tfunc()\n\t\t\t\tself.tearDown()\n\t\t\texcept:\n \t\t\t\tself.appendResult('Error')\n\t\t\t\tself.numFailed += 1\n\t\tself.showSummary()\n\n\tdef appendResult(self,res,actual,expected,feedback):\n \t\tif res == 'Error':\n \t\t\tmsg = 'Error'\n\t\telif res:\n \t\t\tmsg = 'Pass'\n\t\t\tself.numPassed += 1\n\t\telse:\n \t\t\tmsg = 'Fail: expected %s %s ' % (str(actual),str(expected)) + feedback\n\t\t\tself.numFailed += 1\n\n\t\tpTag = document.createElement('li')\n\t\tpTag.innerHTML = msg\n\t\tself.resList.appendChild(pTag)\n\n\n\n\tdef showSummary(self):\n \t\tpct = self.numPassed / (self.numPassed+self.numFailed) * 100\n\t\tpTag = document.createElement('p')\n\t\tpTag.innerHTML = \"You passed: \" + str(pct) + \"% of the tests\"\n\t\tself.resdiv.appendChild(pTag)\n\t\tif pct < 90:\n \t\t\tself.resdiv.setCSS('background-color','#de8e96')\n\t\telse:\n \t\t\tself.resdiv.setCSS('background-color','#83d382')\n ", "src/lib/urllib/__init__.js": "var $builtinmodule = function(name)\n {\n var urllib = {};\n\n return urllib;\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 (banksean@gmail.com)\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\n var 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 */\n MersenneTwister.prototype.init_genrand = function(s) {\n this.mt[0] = s >>> 0;\n for (this.mti=1; this.mti>> 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 */\n MersenneTwister.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 */\n MersenneTwister.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>> 1) ^ mag01[y & 0x1];\n }\n for (;kk>> 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 */\n MersenneTwister.prototype.genrand_int31 = function() {\n return (this.genrand_int32()>>>1);\n }\n\n /* generates a random number on [0,1]-real-interval */\n MersenneTwister.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 */\n MersenneTwister.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 */\n MersenneTwister.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*/\n MersenneTwister.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\n\n\n var $builtinmodule = function(name)\n {\n\n var mod = {};\n\n var myGenerator = new MersenneTwister();\n\n mod.seed = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"seed\", arguments, 0, 1);\n\tx = Sk.builtin.asnum$(x);\n\n if (arguments.length > 0)\n myGenerator = new MersenneTwister(x);\n else\n myGenerator = new MersenneTwister();\n\n\treturn Sk.builtin.none.none$;\n });\n\n mod.random = new Sk.builtin.func(function() {\n Sk.builtin.pyCheckArgs(\"random\", arguments, 0, 0);\n\n\treturn new Sk.builtin.nmber(myGenerator.genrand_res53(), Sk.builtin.nmber.float$);\n });\n\n var toInt = function(num) {\n return num | 0;\n };\n\n var randrange = function(start, stop, step) {\n // Ported from CPython 2.7\n var width, n, ret;\n\n if (!Sk.builtin.checkInt(start)) {\n throw new Sk.builtin.ValueError(\"non-integer first argument for randrange()\");\n };\n\n if (stop === undefined) {\n // Random in [0, start)\n ret = toInt(myGenerator.genrand_res53() * start);\n\t return new Sk.builtin.nmber(ret, Sk.builtin.nmber.int$);\n };\n\n if (!Sk.builtin.checkInt(stop)) {\n throw new Sk.builtin.ValueError(\"non-integer stop for randrange()\");\n };\n\n if (step === undefined) {\n step = 1;\n };\n\n width = stop - start;\n\n if ((step == 1) && (width > 0)) {\n // Random in [start, stop), must use toInt on product for correct results with negative ranges\n ret = start + toInt(myGenerator.genrand_res53() * width);\n\t return new Sk.builtin.nmber(ret, Sk.builtin.nmber.int$);\n };\n\n if (step == 1) {\n throw new Sk.builtin.ValueError(\"empty range for randrange() (\" + start + \", \" + stop + \", \" + width + \")\");\n };\n\n if (!Sk.builtin.checkInt(step)) {\n throw new Sk.builtin.ValueError(\"non-integer step for randrange()\");\n };\n\n if (step > 0) {\n n = toInt((width + step - 1) / step);\n } else if (step < 0) {\n n = toInt((width + step + 1) / step);\n } else {\n throw new Sk.builtin.ValueError(\"zero step for randrange()\");\n };\n\n if (n <= 0) {\n throw new Sk.builtin.ValueError(\"empty range for randrange()\");\n };\n\n // Random in range(start, stop, step)\n ret = start + (step * toInt(myGenerator.genrand_res53() * n));\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.int$);\n };\n\n mod.randint = new Sk.builtin.func(function(a, b) {\n Sk.builtin.pyCheckArgs(\"randint\", arguments, 2, 2);\n\n\ta = Sk.builtin.asnum$(a);\n\tb = Sk.builtin.asnum$(b);\n return randrange(a, b+1);\n });\n\n mod.randrange = new Sk.builtin.func(function(start, stop, step) {\n Sk.builtin.pyCheckArgs(\"randrange\", arguments, 1, 3);\n\n\tstart = Sk.builtin.asnum$(start);\n\tstop = Sk.builtin.asnum$(stop);\n\tstep = Sk.builtin.asnum$(step);\n return randrange(start, stop, step);\n });\n\n mod.choice = new Sk.builtin.func(function(seq) {\n Sk.builtin.pyCheckArgs(\"choice\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"seq\", \"sequence\", Sk.builtin.checkSequence(seq));\n\n if (seq.sq$length !== undefined) {\n var r = toInt(myGenerator.genrand_res53() * seq.sq$length());\n return seq.mp$subscript(r);\n } else {\n throw new Sk.builtin.TypeError(\"object has no length\");\n }\n });\n\n mod.shuffle = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"shuffle\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"sequence\", Sk.builtin.checkSequence(x));\n\n if (x.sq$length !== undefined) {\n if (x.mp$ass_subscript !== undefined) {\n for (var i = x.sq$length() - 1; i > 0; i -= 1) {\n var r = toInt(myGenerator.genrand_res53() * (i + 1));\n var tmp = x.mp$subscript(r);\n x.mp$ass_subscript(r, x.mp$subscript(i));\n x.mp$ass_subscript(i, tmp);\n };\n } else {\n throw new Sk.builtin.TypeError(\"object is immutable\");\n };\n } else {\n throw new Sk.builtin.TypeError(\"object has no length\");\n };\n\n\treturn Sk.builtin.none.none$;\n });\n\n return mod;\n }\n ", "src/lib/webgl/__init__.js": "var $builtinmodule = function(name)\n {\n var mod = {};\n\n var makeFailHTML = function(msg) {\n return '' +\n '' +\n '
' +\n '
' +\n '
' + msg + '
' +\n '
' +\n '
';\n };\n\n var GET_A_WEBGL_BROWSER = '' +\n 'This page requires a browser that supports WebGL.
' +\n 'Click here to upgrade your browser.';\n\n var NEED_HARDWARE = '' +\n \"It doesn't appear your computer can support WebGL.
\" +\n 'Click here for more information.';\n\n var create3DContext = function(canvas) {\n var names = [\"webgl\", \"experimental-webgl\", \"webkit-3d\", \"moz-webgl\"];\n var gl = null;\n for (var ii = 0; ii < names.length; ++ii) {\n try {\n gl = canvas.getContext(names[ii]);\n }\n catch(e) {\n }\n if (gl) {\n break;\n }\n }\n if (gl) {\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 gl;\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(GET_A_WEBGL_BROWSER);\n return;\n }\n\n var gl = create3DContext(opt_canvas);\n if (!gl) {\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 }\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(NEED_HARDWARE);\n }\n else {\n container.innerHTML = makeFailHTML(GET_A_WEBGL_BROWSER);\n }\n }\n return gl;\n };\n\n /**\n * The Context encapsulates the underlying WebGL native JavaScript API.\n */\n mod.Context = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(\n function(self, canvasid) {\n var canvas = document.getElementById(canvasid.v);\n var gl = setupWebGL(canvasid.v, canvas)\n if (!gl) {\n throw new Error(\"Your browser does not appear to support WebGL.\");\n }\n\n self.gl = gl;\n\n // Copy symbolic constants and functions from native WebGL, encapsulating where necessary.\n for (var k in gl.__proto__) {\n if (typeof gl.__proto__[k] === 'number') {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), gl.__proto__[k]);\n }\n else if (typeof gl.__proto__[k] === \"function\") {\n switch(k) {\n case 'bufferData': {\n }\n break;\n case 'clearColor': {\n }\n break;\n case 'drawArrays': {\n }\n break;\n case 'getAttribLocation': {\n }\n break;\n case 'getUniformLocation': {\n }\n break;\n case 'shaderSource': {\n }\n break;\n case 'uniformMatrix4fv': {\n }\n break;\n case 'vertexAttribPointer': {\n }\n break;\n case 'viewport': {\n }\n break;\n default: {\n (function(key) {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), new Sk.builtin.func(function() {\n var f = gl.__proto__[key];\n return f.apply(gl, arguments);\n }));\n }(k));\n }\n }\n }\n }\n\n gl.clearColor(100.0/255.0, 149.0/255.0, 237.0/255.0, 1.0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n }\n );\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n $loc.bufferData = new Sk.builtin.func(\n function(self, target, data, usage) {\n self.gl.bufferData(target, data.v, usage);\n }\n );\n\n $loc.clearColor = new Sk.builtin.func(\n function(self, red, green, blue, alpha) {\n self.gl.clearColor(Sk.builtin.asnum$(red), Sk.builtin.asnum$(green), Sk.builtin.asnum$(blue), Sk.builtin.asnum$(alpha));\n }\n );\n\n $loc.getAttribLocation = new Sk.builtin.func(\n function(self, program, name) {\n return self.gl.getAttribLocation(program, name.v);\n }\n );\n\n $loc.getUniformLocation = new Sk.builtin.func(\n function(self, program, name) {\n return self.gl.getUniformLocation(program, name.v);\n }\n );\n\n $loc.shaderSource = new Sk.builtin.func(\n function(self, shader, src) {\n self.gl.shaderSource(shader, src.v);\n }\n );\n\n $loc.drawArrays = new Sk.builtin.func(\n function(self, mode, first, count) {\n self.gl.drawArrays(Sk.builtin.asnum$(mode), Sk.builtin.asnum$(first), Sk.builtin.asnum$(count));\n }\n );\n\n $loc.vertexAttribPointer = new Sk.builtin.func(\n function(self, index, size, type, normalized, stride, dunno) {\n self.gl.vertexAttribPointer(index, Sk.builtin.asnum$(size), Sk.builtin.asnum$(type), normalized, Sk.builtin.asnum$(stride), Sk.builtin.asnum$(dunno));\n }\n );\n\n $loc.viewport = new Sk.builtin.func(\n function(self, x, y, width, height) {\n self.gl.viewport(Sk.builtin.asnum$(x), Sk.builtin.asnum$(y), Sk.builtin.asnum$(width), Sk.builtin.asnum$(height));\n }\n );\n\n $loc.uniformMatrix4fv = new Sk.builtin.func(\n function(self, location, transpose, values) {\n// console.log(\"location \" + (typeof location));\n// console.log(\"transpose \" + (typeof transpose));\n// console.log(\"values.v \" + (typeof values.v));\n self.gl.uniformMatrix4fv(Sk.builtin.asnum$(location), transpose, values.v);\n }\n );\n\n $loc.setDrawFunc = new Sk.builtin.func(function(self, func) {\n var startTime = (new Date()).getTime();\n var intervalId = setInterval(\n function() {\n Sk.misceval.callsim(func, self, (new Date()).getTime() - startTime);\n }, 1000.0 / 60.0); // 60 fps\n });\n\n }, 'Context', []);\n\n mod.Float32Array = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, data) {\n if (typeof data === \"number\") {\n self.v = new Float32Array(data);\n }\n else {\n self.v = new Float32Array(Sk.ffi.remapToJs(data));\n }\n });\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n var copy = [];\n for (var i = 0; i < self.v.length; ++i) {\n copy.push(self.v[i]);\n }\n return new Sk.builtin.str(\"[\" + copy.join(', ') + \"]\");\n });\n }, 'Float32Array', []);\n\n /**\n * A 4x4 (mutable) matrix suitable for OpenGL.\n *\n * Mutability is chosen for performance.\n * The inderlying implementation is Float32Array.\n * The indexing of the elements is\n * 0 4 8 12\n * 1 5 9 13\n * 2 6 10 14\n * 3 7 11 15\n */\n mod.Matrix4x4 = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, data) {\n self.v = new Float32Array(Sk.ffi.remapToJs(data));\n });\n\n $loc.identity = new Sk.builtin.func(\n function(self) {\n\n var m = self.v;\n\n m[0] = 1;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = 1;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = 1;\n m[11] = 0;\n\n m[12] = 0;\n m[13] = 0;\n m[14] = 0;\n m[15] = 1;\n }\n );\n\n $loc.perspective = new Sk.builtin.func(\n function(self, fov, aspect, near, far) {\n\n var t = Math.tan(Math.PI * 0.5 - 0.5 * (Sk.builtin.asnum$(fov) * Math.PI / 180));\n var a = Sk.builtin.asnum$(aspect)\n var n = Sk.builtin.asnum$(near)\n var f = Sk.builtin.asnum$(far)\n var k = 1.0 / (n - f);\n\n var m = self.v;\n\n m[0] = t / a;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = t;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = (n + f) * k;\n m[11] = -1;\n\n m[12] = 0;\n m[13] = 0;\n m[14] = n * f * k * 2;\n m[15] = 0;\n }\n );\n\n $loc.translate = new Sk.builtin.func(\n function(self, translation) {\n\n var m = self.v;\n var t = Sk.ffi.remapToJs(translation);\n\n m[0] = 1;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = 1;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = 1;\n m[11] = 0;\n\n m[12] = t[0];\n m[13] = t[1];\n m[14] = t[2];\n m[15] = 1;\n }\n );\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n var copy = [];\n for (var i = 0; i < self.v.length; ++i) {\n copy.push(self.v[i]);\n }\n return new Sk.builtin.str(\"[\" + copy.join(', ') + \"]\");\n });\n }, 'Matrix4x4', []);\n\n return mod;\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//\tRNL\tadded\n mod.fabs = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"fabs\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.abs(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.asin = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"asin\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.asin(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.acos = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"acos\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.acos(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.atan = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"atan\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.atan(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.atan2 = new Sk.builtin.func(function(y, x) {\n Sk.builtin.pyCheckArgs(\"atan2\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.atan2(Sk.builtin.asnum$(y), Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.sin = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"sin\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.sin(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.cos = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"cos\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.cos(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.tan = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"tan\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.tan(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.asinh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"asinh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar L = x + Math.sqrt(x*x+1);\n\n\treturn new Sk.builtin.nmber(Math.log(L), Sk.builtin.nmber.float$);\n });\n\n mod.acosh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"acosh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar L = x + Math.sqrt(x*x-1);\n\n\treturn new Sk.builtin.nmber(Math.log(L), Sk.builtin.nmber.float$);\n });\n\n mod.atanh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"atanh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar L = (1+x)/(1-x);\n\n\treturn new Sk.builtin.nmber(Math.log(L)/2, Sk.builtin.nmber.float$);\n });\n\n mod.sinh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"sinh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar e = Math.E;\n\tvar p = Math.pow(e, x);\n\tvar n = 1/p;\n\tvar result = (p-n)/2;\n\n\treturn new Sk.builtin.nmber(result, Sk.builtin.nmber.float$);\n });\n\n mod.cosh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"cosh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar e = Math.E;\n\tvar p = Math.pow(e, x);\n\tvar n = 1/p;\n\tvar result = (p+n)/2;\n\n\treturn new Sk.builtin.nmber(result, Sk.builtin.nmber.float$);\n });\n\n mod.tanh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"tanh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar e = Math.E;\n\tvar p = Math.pow(e, x);\n\tvar n = 1/p;\n\tvar result = ((p-n)/2)/((p+n)/2);\n\n\treturn new Sk.builtin.nmber(result, Sk.builtin.nmber.float$);\n });\n\n mod.ceil = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"ceil\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.ceil(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.floor = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"floor\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.floor(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.sqrt = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"sqrt\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.sqrt(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.trunc = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"trunc\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.nmber(Sk.builtin.asnum$(x)|0, Sk.builtin.nmber.int$);\n });\n\n mod.log = new Sk.builtin.func(function(x, base) {\n Sk.builtin.pyCheckArgs(\"log\", arguments, 1, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n if (base === undefined) {\n \t return new Sk.builtin.nmber(Math.log(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n } else {\n Sk.builtin.pyCheckType(\"base\", \"number\", Sk.builtin.checkNumber(base));\n var ret = Math.log(Sk.builtin.asnum$(x)) / Math.log(Sk.builtin.asnum$(base));\n\t return new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n }\n });\n\n mod.log10 = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"log10\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n var ret = Math.log(Sk.builtin.asnum$(x)) / Math.log(10);\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n });\n\n mod.exp = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"exp\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.exp(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.pow = new Sk.builtin.func(function(x,y) {\n Sk.builtin.pyCheckArgs(\"pow\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n\n\treturn new Sk.builtin.nmber(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 Sk.builtin.pyCheckArgs(\"radians\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"deg\", \"number\", Sk.builtin.checkNumber(deg));\n\n\tvar ret = Math.PI / 180.0 * Sk.builtin.asnum$(deg);\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n });\n\n mod.degrees = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"degrees\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\tvar ret = 180.0 / Math.PI * Sk.builtin.asnum$(rad);\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n });\n\n mod.hypot = new Sk.builtin.func(function(x, y) {\n \tSk.builtin.pyCheckArgs(\"hypot\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\tSk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n\n\t\tx = Sk.builtin.asnum$(x);\n\t\ty = Sk.builtin.asnum$(y);\n\treturn new Sk.builtin.nmber(Math.sqrt((x*x)+(y*y)), Sk.builtin.nmber.float$);\n });\n\n\tmod.factorial = new Sk.builtin.func(function(x) {\n\t Sk.builtin.pyCheckArgs(\"factorial\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\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 new Sk.builtin.nmber(r, Sk.builtin.nmber.int$);\n\t});\n\n return mod;\n}"}} +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:\ndef __init__(self):\nself.heapList = [0]\nself.currentSize = 0\n\n\ndef buildHeap(self,alist):\ni = len(alist) // 2\nself.currentSize = len(alist)\nself.heapList = [0] + alist[:]\nprint(len(self.heapList), i)\nwhile (i > 0):\nprint(self.heapList, i)\nself.percDown(i)\ni = i - 1\nprint(self.heapList,i)\n\ndef percDown(self,i):\nwhile (i * 2) <= self.currentSize:\nmc = self.minChild(i)\nif self.heapList[i] > self.heapList[mc]:\ntmp = self.heapList[i]\nself.heapList[i] = self.heapList[mc]\nself.heapList[mc] = tmp\ni = mc\n\ndef minChild(self,i):\nif i * 2 + 1 > self.currentSize:\nreturn i * 2\nelse:\nif self.heapList[i * 2] < self.heapList[i * 2 + 1]:\nreturn i * 2\nelse:\nreturn i * 2 + 1\n\ndef percUp(self,i):\nwhile i // 2 > 0:\n if self.heapList[i] < self.heapList[i//2]:\n tmp = self.heapList[i // 2]\nself.heapList[i // 2] = self.heapList[i]\nself.heapList[i] = tmp\ni = i // 2\n\ndef insert(self,k):\nself.heapList.append(k)\nself.currentSize = self.currentSize + 1\nself.percUp(self.currentSize)\n\ndef delMin(self):\nretval = self.heapList[1]\nself.heapList[1] = self.heapList[self.currentSize]\nself.currentSize = self.currentSize - 1\nself.heapList.pop()\nself.percDown(1)\nreturn retval\n\ndef isEmpty(self):\nif currentSize == 0:\nreturn True\nelse:\nreturn 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\n\nclass Stack:\ndef __init__(self):\nself.items = []\n\ndef isEmpty(self):\nreturn self.items == []\n\ndef push(self, item):\nself.items.append(item)\n\ndef pop(self):\nreturn self.items.pop()\n\ndef peek(self):\nreturn self.items[len(self.items)-1]\n\ndef size(self):\nreturn len(self.items)\n\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'''\nAuthor: Brad Miller\nDate: 1/15/2005\nDescription: Imlement a binary search tree with the following interface\nfunctions:\n __contains__(y) <==> y in x\n__getitem__(y) <==> x[y]\n__init__()\n__len__() <==> len(x)\n__setitem__(k,v) <==> x[k] = v\nclear()\nget(k)\nitems()\nkeys()\nvalues()\nput(k,v)\nin\ndel <==>\n'''\n\ndef __init__(self):\nself.root = None\nself.size = 0\n\ndef put(self,key,val):\nif self.root:\nself._put(key,val,self.root)\nelse:\nself.root = TreeNode(key,val)\nself.size = self.size + 1\n\ndef _put(self,key,val,currentNode):\nif key < currentNode.key:\nif currentNode.hasLeftChild():\nself._put(key,val,currentNode.leftChild)\nelse:\ncurrentNode.leftChild = TreeNode(key,val,parent=currentNode)\nelse:\nif currentNode.hasRightChild():\nself._put(key,val,currentNode.rightChild)\nelse:\ncurrentNode.rightChild = TreeNode(key,val,parent=currentNode)\n\ndef __setitem__(self,k,v):\nself.put(k,v)\n\ndef get(self,key):\nif self.root:\nres = self._get(key,self.root)\nif res:\nreturn res.payload\nelse:\nreturn None\nelse:\nreturn None\n\ndef _get(self,key,currentNode):\nif not currentNode:\n return None\nelif currentNode.key == key:\nreturn currentNode\nelif key < currentNode.key:\nreturn self._get(key,currentNode.leftChild)\nelse:\nreturn self._get(key,currentNode.rightChild)\n\n\ndef __getitem__(self,key):\nres = self.get(key)\nif res:\nreturn res\nelse:\nraise KeyError('Error, key not in tree')\n\n\ndef __contains__(self,key):\nif self._get(key,self.root):\nreturn True\nelse:\nreturn False\n\ndef length(self):\nreturn self.size\n\ndef __len__(self):\nreturn self.size\n\ndef __iter__(self):\nreturn self.root.__iter__()\n\ndef delete(self,key):\nif self.size > 1:\nnodeToRemove = self._get(key,self.root)\nif nodeToRemove:\nself.remove(nodeToRemove)\nself.size = self.size-1\nelse:\nraise KeyError('Error, key not in tree')\nelif self.size == 1 and self.root.key == key:\nself.root = None\nself.size = self.size - 1\nelse:\nraise KeyError('Error, key not in tree')\n\ndef __delitem__(self,key):\nself.delete(key)\n\ndef remove(self,currentNode):\nif currentNode.isLeaf(): #leaf\nif currentNode == currentNode.parent.leftChild:\ncurrentNode.parent.leftChild = None\nelse:\ncurrentNode.parent.rightChild = None\nelif currentNode.hasBothChildren(): #interior\nsucc = currentNode.findSuccessor()\nsucc.spliceOut()\ncurrentNode.key = succ.key\ncurrentNode.payload = succ.payload\nelse: # this node has one child\nif currentNode.hasLeftChild():\nif currentNode.isLeftChild():\ncurrentNode.leftChild.parent = currentNode.parent\ncurrentNode.parent.leftChild = currentNode.leftChild\nelif currentNode.isRightChild():\ncurrentNode.leftChild.parent = currentNode.parent\ncurrentNode.parent.rightChild = currentNode.leftChild\nelse:\ncurrentNode.replaceNodeData(currentNode.leftChild.key,\n currentNode.leftChild.payload,\n currentNode.leftChild.leftChild,\n currentNode.leftChild.rightChild)\nelse:\nif currentNode.isLeftChild():\ncurrentNode.rightChild.parent = currentNode.parent\ncurrentNode.parent.leftChild = currentNode.rightChild\nelif currentNode.isRightChild():\ncurrentNode.rightChild.parent = currentNode.parent\ncurrentNode.parent.rightChild = currentNode.rightChild\nelse:\ncurrentNode.replaceNodeData(currentNode.rightChild.key,\n currentNode.rightChild.payload,\n currentNode.rightChild.leftChild,\n currentNode.rightChild.rightChild)\n\ndef inorder(self):\nself._inorder(self.root)\n\ndef _inorder(self,tree):\nif tree != None:\nself._inorder(tree.leftChild)\nprint(tree.key)\nself._inorder(tree.rightChild)\n\ndef postorder(self):\nself._postorder(self.root)\n\ndef _postorder(self, tree):\nif tree:\nself._postorder(tree.rightChild)\nself._postorder(tree.leftChild)\nprint(tree.key)\n\ndef preorder(self):\nself._preorder(self,self.root)\n\ndef _preorder(self,tree):\nif tree:\nprint(tree.key)\nself._preorder(tree.leftChild)\nself._preorder(tree.rightChild)\n\n\nclass TreeNode:\ndef __init__(self,key,val,left=None,right=None,parent=None):\nself.key = key\nself.payload = val\nself.leftChild = left\nself.rightChild = right\nself.parent = parent\nself.balanceFactor = 0\n\ndef hasLeftChild(self):\nreturn self.leftChild\n\ndef hasRightChild(self):\nreturn self.rightChild\n\ndef isLeftChild(self):\nreturn self.parent and self.parent.leftChild == self\n\ndef isRightChild(self):\nreturn self.parent and self.parent.rightChild == self\n\ndef isRoot(self):\nreturn not self.parent\n\ndef isLeaf(self):\nreturn not (self.rightChild or self.leftChild)\n\ndef hasAnyChildren(self):\nreturn self.rightChild or self.leftChild\n\ndef hasBothChildren(self):\nreturn self.rightChild and self.leftChild\n\ndef replaceNodeData(self,key,value,lc,rc):\nself.key = key\nself.payload = value\nself.leftChild = lc\nself.rightChild = rc\nif self.hasLeftChild():\nself.leftChild.parent = self\nif self.hasRightChild():\nself.rightChild.parent = self\n\ndef findSuccessor(self):\nsucc = None\nif self.hasRightChild():\nsucc = self.rightChild.findMin()\nelse:\nif self.parent:\nif self.isLeftChild():\nsucc = self.parent\nelse:\nself.parent.rightChild = None\nsucc = self.parent.findSuccessor()\nself.parent.rightChild = self\nreturn succ\n\n\ndef spliceOut(self):\nif self.isLeaf():\nif self.isLeftChild():\nself.parent.leftChild = None\nelse:\nself.parent.rightChild = None\nelif self.hasAnyChildren():\nif self.hasLeftChild():\nif self.isLeftChild():\nself.parent.leftChild = self.leftChild\nelse:\nself.parent.rightChild = self.leftChild\nself.leftChild.parent = self.parent\nelse:\nif self.isLeftChild():\nself.parent.leftChild = self.rightChild\nelse:\nself.parent.rightChild = self.rightChild\nself.rightChild.parent = self.parent\n\ndef findMin(self):\ncurrent = self\nwhile current.hasLeftChild():\ncurrent = current.leftChild\nreturn current\n\ndef __iter__(self):\n\"\"\"The standard inorder traversal of a binary tree.\"\"\"\nif self:\nif self.hasLeftChild():\nfor elem in self.leftChild:\nyield elem\nyield self.key\nif self.hasRightChild():\nfor elem in self.rightChild:\nyield 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/operator/__init__.js": "/*\n * __author__: Isaac Dontje Lindell (i@isaacdontjelindell.com)\n *\n * Implementation of the Python operator module.\n */\n\nvar $builtinmodule = function(name) {\n var mod = {};\n\n mod.lt = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Lt')); });\n mod.__lt__ = mod.lt;\n\n mod.le = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'LtE')); });\n mod.__le__ = mod.le;\n\n mod.eq = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Eq')); });\n mod.__eq__ = mod.eq;\n\n mod.ne = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'NotEq')); });\n mod.__ne__ = mod.ne;\n\n mod.ge = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'GtE')); });\n mod.__ge__ = mod.ge;\n\n mod.gt = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Gt')); });\n mod.__gt__ = mod.gt;\n\n mod.not_ = new Sk.builtin.func(function (obj) { throw new Sk.builtin.NotImplementedError(\"operator.not_() is not yet implemented in Skulpt\"); });\n\n mod.truth = new Sk.builtin.func(function(obj) { return Sk.builtin.bool(obj); });\n\n mod.is_ = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Is')); });\n\n mod.is_not = new Sk.builtin.func(function(a, b) { return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'IsNot')); });\n\n mod.abs = new Sk.builtin.func(function(obj) { return Sk.misceval.callsim(Sk.builtin.abs, obj); });\n mod.__abs__ = mod.abs;\n\n // The documentation says that operator.add() is defined for a and b numbers, but\n // CPython (2.6) allows a and b to be other types (e.g. str)\n mod.add = new Sk.builtin.func(function (a, b) { return Sk.abstr.objectAdd(a, b); });\n mod.__add__ = mod.add;\n\n mod.and_ = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$and'].call(a, b); });\n mod.__and__ = mod.and_;\n\n mod.div = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$divide'].call(a, b); });\n mod.__div__ = mod.div;\n\n mod.floordiv = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$floor_divide'].call(a, b); });\n mod.__floordiv__ = mod.floordiv;\n\n // Doesn't look like anything has the __index__ magic function anyway\n mod.index = new Sk.builtin.func(function (a) { throw new Sk.builtin.NotImplementedError(\"operator.index() is not yet implemented in Skulpt\"); });\n mod.__index__ = mod.index;\n\n // Note: Sk.abstr.numberUnaryOp(obj, 'Invert') looks for the function nb$invert() on obj.\n // However, it doesn't look like that function has been implemented for any existing object types.\n // I've gone ahead and created this function for completeness' sake, but expect any use of it to\n // result in an error.\n mod.inv = new Sk.builtin.func(function (obj) { return Sk.abstr.numberUnaryOp(obj, 'Invert'); });\n mod.__inv__ = mod.inv;\n mod.invert = mod.inv;\n mod.__invert__ = mod.inv;\n\n mod.lshift = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$lshift'].call(a, b); });\n mod.__lshift__ = mod.lshift;\n\n mod.mod = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$remainder'].call(a, b); });\n mod.__mod__ = mod.mod;\n\n mod.mul = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$multiply'].call(a, b); });\n mod.__mul__ = mod.mul;\n\n mod.neg = new Sk.builtin.func(function (obj) { return Sk.abstr.objectNegative(obj); });\n mod.__neg__ = mod.neg;\n\n mod.or_ = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$or'].call(a, b); });\n mod.__or__ = mod.or_;\n\n mod.pos = new Sk.builtin.func(function (obj) { return Sk.abstr.objectPositive(obj); });\n mod.__pos__ = mod.pos;\n\n mod.pow = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$power'].call(a, b); });\n mod.__pow__ = mod.pow;\n\n mod.rshift = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$rshift'].call(a, b); });\n mod.__rshift__ = mod.rshift;\n\n mod.sub = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$subtract'].call(a, b); });\n mod.__sub__ = mod.sub;\n\n mod.truediv = mod.div;\n mod.__truediv__ = mod.div;\n\n mod.xor = new Sk.builtin.func(function (a, b) { return Sk.builtin.nmber.prototype['nb$xor'].call(a, b); });\n mod.__xor__ = mod.xor;\n\n mod.concat = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceConcat(a, b); });\n mod.__concat__ = mod.concat;\n\n mod.contains = new Sk.builtin.func(function (a, b) { return Sk.builtin.bool(Sk.abstr.sequenceContains(a, b)); });\n mod.__contains__ = mod.contains;\n\n mod.countOf = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceGetCountOf(a, b); });\n\n mod.delitem = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceDelItem(a, b); });\n mod.__delitem__ = mod.delitem;\n\n mod.getitem = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceGetItem(a, b); });\n mod.__getitem__ = mod.getitem;\n\n mod.indexOf = new Sk.builtin.func(function (a, b) { return Sk.abstr.sequenceGetIndexOf(a, b); });\n\n mod.setitem = new Sk.builtin.func(function (a, b, c) { return Sk.abstr.sequenceSetItem(a, b, c); });\n mod.__setitem__ = mod.setitem;\n\n return mod;\n };\n ", "src/lib/image/__init__.js": "var ImageMod; // the single identifier needed in the global scope\n\n if (! 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\n var $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/unittest/__init__.py": "__author__ = 'bmiller'\n '''\n This is the start of something that behaves like\n the unittest module from cpython.\n\n '''\n\n\n class TestCase:\n def __init__(self):\n self.numPassed = 0\n self.numFailed = 0\n\n self.tlist = []\n testNames = {}\n for name in dir(self):\n if name[:4] == 'test' and name not in testNames:\n self.tlist.append(getattr(self,name))\n testNames[name]=True\n\n def setup(self):\n pass\n\n def tearDown(self):\n pass\n\n def main(self):\n\n for func in self.tlist:\n try:\n self.setup()\n func()\n self.tearDown()\n except:\n self.appendResult('Error',None,None,None)\n self.numFailed += 1\n self.showSummary()\n\n def assertEqual(self, actual, expected, feedback=\"\"):\n res = actual==expected\n self.appendResult(res,str(actual)+' to be equal to ',expected, feedback)\n\n def assertNotEqual(actual, expected, feedback=\"\"):\n res = actual != expected\n self.appendResult(res,str(actual)+' to not equal ',expected,feedback)\n\n def assertTrue(self,x, feedback=\"\"):\n res = x\n self.appendResult(res,str(x)+' to be ',True,feedback)\n\n def assertFalse(self,x, feedback=\"\"):\n res = not x\n self.appendResult(res,str(x)+' to be ',False,feedback)\n\n def assertIs(self,a,b, feedback=\"\"):\n res = a is b\n self.appendResult(res,str(a)+' to be the same object as ',b,feedback)\n\n def assertIsNot(self,a,b, feedback=\"\"):\n res = a is not b\n self.appendResult(res,str(a)+' to not be the same object as ',b,feedback)\n\n def assertIsNone(self,x, feedback=\"\"):\n res = x is None\n self.appendResult(res,x,None,feedback)\n\n def assertIsNotNone(self,x, feedback=\"\"):\n res = x is not None\n self.appendResult(res,str(x)+' to not be ',None,feedback)\n\n def assertIn(self,a,b, feedback=\"\"):\n res = a in b\n self.appendResult(res,str(a)+' to be in ',b,feedback)\n\n def assertNotIn(self,a,b, feedback=\"\"):\n res = a not in b\n self.appendResult(res,str(a)+' to not be in ',b,feedback)\n\n def assertIsInstance(self,a,b, feedback=\"\"):\n res = isinstance(a,b)\n self.appendResult(res,str(a)+' to be an instance of ',b,feedback)\n\n def assertNotIsInstance(self,a,b, feedback=\"\"):\n res = not isinstance(a,b)\n self.appendResult(res,str(a)+' to not be an instance of ',b,feedback)\n\n def assertAlmostEqual(self,a,b, feedback=\"\"):\n res = round(a-b,7) == 0\n self.appendResult(res,str(a)+' to equal ',b,feedback)\n\n def assertNotAlmostEqual(self,a,b, feedback=\"\"):\n res = round(a-b,7) != 0\n self.appendResult(res,str(a)+' to not equal ',b,feedback)\n\n def assertGreater(self,a,b, feedback=\"\"):\n res = a > b\n self.appendResult(res,str(a)+' to be greater than ',b,feedback)\n\n def assertGreaterEqual(self,a,b, feedback=\"\"):\n res = a >= b\n self.appendResult(res,str(a)+' to be greater than or equal to ',b,feedback)\n\n def assertLess(self,a,b, feedback=\"\"):\n res = a < b\n self.appendResult(res,str(a)+' to be less than ',b,feedback)\n\n def assertLessEqual(self,a,b, feedback=\"\"):\n res = a <= b\n self.appendResult(res,str(a)+' to be less than or equal to ',b,feedback)\n\n def appendResult(self,res,actual,expected,feedback):\n if res == 'Error':\n msg = 'Error'\n elif res:\n msg = 'Pass'\n self.numPassed += 1\n else:\n msg = 'Fail: expected %s %s ' % (str(actual),str(expected)) + feedback\n self.numFailed += 1\n\n def showSummary(self):\n pct = self.numPassed / (self.numPassed+self.numFailed) * 100\n print \"ran %d tests, passed %d \\n\" % (self.numPassed+self.numFailed, self.numPassed)\n\n\n\n def main():\n glob = globals() # globals() still needs work\n for name in glob:\n if issubclass(glob[name],TestCase):\n glob[name]().main()\n\n ", "src/lib/test/__init__.py": "__author__ = 'bmiller'\n\n def 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\n def testNotEqual(actual, expected):\n pass\n\n ", "src/lib/string/__init__.js": "/*\n * __author__: Isaac Dontje Lindell (i@isaacdontjelindell.com)\n *\n * Implementation of the Python string module.\n */\n\n\n var $builtinmodule = function(name) {\n var mod = {};\n\n mod.ascii_lowercase = Sk.builtin.str('abcdefghijklmnopqrstuvwxyz');\n mod.ascii_uppercase = Sk.builtin.str('ABCDEFGHIJKLMNOPQRSTUVWXYZ');\n mod.ascii_letters = Sk.builtin.str(mod.ascii_lowercase.v + mod.ascii_uppercase.v);\n\n mod.lowercase = Sk.builtin.str('abcdefghijklmnopqrstuvwxyz');\n mod.uppercase = Sk.builtin.str('ABCDEFGHIJKLMNOPQRSTUVWXYZ');\n mod.letters = Sk.builtin.str(mod.lowercase.v + mod.uppercase.v);\n\n mod.digits = Sk.builtin.str('0123456789', Sk.builtin.str);\n mod.hexdigits = Sk.builtin.str('0123456789abcdefABCDEF');\n mod.octdigits = Sk.builtin.str('01234567');\n\n mod.punctuation = Sk.builtin.str('!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~');\n mod.whitespace = Sk.builtin.str('\\t\\n\\x0b\\x0c\\r ');\n\n /* Note: The docs for string.printable say that it's the concatenation of string.digits,\n * string.letters, string.punctuation, and string.whitespace. The CPython interpreter\n * outputs the whitespace characters in one order when string.whitespace is used, and a\n * slightly different order when string.printable is used. I've elected to follow the\n * behavior of CPython here rather than the spec. */\n mod.printable = Sk.builtin.str(mod.digits.v + mod.letters.v + mod.punctuation.v + \" \\t\\n\\r\\x0b\\x0c\");\n\n\n mod.split = new Sk.builtin.func(function(s, sep, maxsplit) {\n return Sk.misceval.callsim(Sk.builtin.str.prototype['split'], s, sep, maxsplit);\n });\n\n /* Return a copy of word with only its first character capitalized. */\n mod.capitalize = new Sk.builtin.func(function(word) {\n return Sk.misceval.callsim(Sk.builtin.str.prototype['capitalize'], word);\n });\n\n /* Concatenate a list or tuple of words with intervening occurrences\n * of sep. The default value for sep is a single space character. */\n mod.join = new Sk.builtin.func(function(words, sep) {\n if (sep === undefined) {\n sep = Sk.builtin.str(' ');\n }\n return Sk.misceval.callsim(Sk.builtin.str.prototype['join'], sep, words);\n });\n\n\n /* Split the argument into words using split(), capitalize each word\n * using capitalize(), and join the capitalized words using join().\n * Note that this replaces runs of whitespace characters by a single\n * space, and removes leading and trailing whitespace. */\n mod.capwords = new Sk.builtin.func(function(s, sep) {\n Sk.builtin.pyCheckArgs('capwords', arguments, 1, 2);\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"s must be a string\");\n }\n if (sep === undefined) {\n sep = Sk.builtin.str(' ');\n }\n if(!Sk.builtin.checkString(sep)) {\n throw new Sk.builtin.TypeError(\"sep must be a string\");\n }\n\n var words = Sk.misceval.callsim(mod.split, s, sep);\n var capWords = [];\n for (var i=0; i 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/urllib/request/__init__.js": "var $builtinmodule = function(name)\n {\n var request = {};\n\n\n //~ Classes .................................................................\n\n // Response class\n //\n // Response objects are returned by the request, get, post, etc.\n // methods, allowing the user to access the response text, status\n // code, and other information.\n\n // ------------------------------------------------------------\n var response = function($gbl, $loc) {\n\n // ------------------------------------------------------------\n $loc.__init__ = new Sk.builtin.func(function(self, xhr) {\n self.data$ = xhr.responseText;\n self.lineList = self.data$.split(\"\\n\");\n self.lineList = self.lineList.slice(0,-1);\n for(var i =0 ; i < self.lineList.length; i++) {\n self.lineList[i] = self.lineList[i]+'\\n';\n }\n self.currentLine = 0;\n self.pos$ = 0;\n });\n\n\n // ------------------------------------------------------------\n $loc.__str__ = new Sk.builtin.func(function(self) {\n return Sk.ffi.remapToPy('');\n });\n\n\n // ------------------------------------------------------------\n $loc.__iter__ = new Sk.builtin.func(function(self) {\n var allLines = self.lineList;\n\n return Sk.builtin.makeGenerator(function() {\n if (this.$index >= this.$lines.length) return undefined;\n return new Sk.builtin.str(this.$lines[this.$index++]);\n }, {\n $obj: self,\n $index: 0,\n $lines: allLines\n });\n });\n\n\n // ------------------------------------------------------------\n $loc.read = new Sk.builtin.func(function(self, size) {\n if (self.closed) throw new Sk.builtin.ValueError(\"I/O operation on closed file\");\n var len = self.data$.length;\n if (size === undefined) size = len;\n var ret = new Sk.builtin.str(self.data$.substr(self.pos$, size));\n self.pos$ += size;\n if (self.pos$ >= len) self.pos$ = len;\n return ret;\n });\n\n\n // ------------------------------------------------------------\n $loc.readline = new Sk.builtin.func(function(self, size) {\n var line = \"\";\n if (self.currentLine < self.lineList.length) {\n line = self.lineList[self.currentLine];\n self.currentLine++;\n }\n return new Sk.builtin.str(line);\n });\n\n\n // ------------------------------------------------------------\n $loc.readlines = new Sk.builtin.func(function(self, sizehint) {\n var arr = [];\n for(var i = self.currentLine; i < self.lineList.length; i++) {\n arr.push(new Sk.builtin.str(self.lineList[i]));\n }\n return new Sk.builtin.list(arr);\n });\n\n };\n\n request.Response =\n Sk.misceval.buildClass(request, response, 'Response', []);\n\n\n //~ Module functions ........................................................\n\n // ------------------------------------------------------------\n /**\n * Constructs and sends a Request. Returns Response object.\n *\n * http://docs.python-requests.org/en/latest/api/#requests.request\n *\n * For now, this implementation doesn't actually construct a Request\n * object; it just makes the request through jQuery.ajax and then\n * constructs a Response.\n */\n request.urlopen = new Sk.builtin.func(function(url, data, timeout) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\",url.v,false);\n xmlhttp.send(null);\n\n return Sk.misceval.callsim(request.Response,xmlhttp)\n });\n\n\n return request;\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\n\n class Queue:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def enqueue(self, item):\n self.items.insert(0,item)\n\n def dequeue(self):\n return self.items.pop()\n\n def size(self):\n return len(self.items)\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\n import sys\n import os\n import unittest\n\n class 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\n class 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\n class 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\n if __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 var TurtleGraphics;\n// the single identifier needed in the global scope\n if (!TurtleGraphics) {\n TurtleGraphics = {\n doneDelegates: [],\n fadeOnExit: true,\n\t\tdefaults: {\n \t\t\tcanvasID: 'mycanvas',\n\t\t\tdegrees: true,\n\t\t\tanimate: true\n\t\t}\n };\n }\n (function () {\n 'use strict';\n // Define private constants\n var Degree2Rad = Math.PI / 180,\n // conversion factor for degrees to radians\n Rad2Degree = 180 / Math.PI,\n render,\n allDone,\n segmentLine,\n clear_canvas;\n\n // Create a 3d Vector class for manipulating turtle heading, and position.\n function Vector(x, y, z) {\n var i;\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 } else {\n for (i = 0; i < x.length; i = i + 1) {\n Array.prototype.push.call(this, x[i]);\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]);\n phi = phi * Degree2Rad;\n res[0] = Math.cos(phi);\n res[1] = Math.sin(phi);\n return res.normalize();\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 Vector.prototype.linear = function (a, b, v) {\n if (this.length !== 3 || v.length !== 3) {\n return;\n }\n return new Vector([a * this[0] + b * v[0],\n a * this[1] + b * v[1],\n a * this[2] + b * v[2]]);\n\n\n };\n Vector.prototype.cross = function (v) {\n if (this.length !== 3 || v.length !== 3) {\n return;\n }\n\n return new Vector([this[1] * v[2] - this[2] * v[1],\n this[2] * v[0] - this[0] * v[2],\n this[0] * v[1] - this[1] * v[0]]);\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 c,\n s;\n angle = angle * Degree2Rad;\n c = Math.cos(angle);\n s = Math.sin(angle);\n return new Vector(this[0] * c + perp[0] * s, this[1] * c + perp[1] * s, 0);\n };\n Vector.prototype.rotateNormal = function (v, 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 Vector.prototype.normalize = function () {\n var n = this.len(),\n res = this.div(n);\n return res;\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) {\n this[1] = 0;\n }\n if (Math.abs(this[0]) < 0.00001) {\n this[0] = 0;\n }\n var rads = Math.atan(Math.abs(this[1]) / Math.abs(this[0])),\n deg = rads * Rad2Degree;\n if (this[0] < 0 && this[1] > 0) {\n deg = 180 - deg;\n } else if (this[0] < 0 && this[1] <= 0) {\n deg = 180 + deg;\n } else if (this[0] >= 0 && this[1] < 0) {\n deg = 360 - deg;\n }\n return deg;\n };\n // divide all vector components by the same value\n Vector.prototype.div = function (n) {\n var 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 // subtract one vector from another\n Vector.prototype.sub = function (v) {\n var 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 Vector.prototype.add = function (v) {\n var 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 Vector.prototype.smul = function (k) {\n // scalar multiplication\n var 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 Vector.prototype.scale = function (xs, ys) {\n var res = new Vector(0, 0, 0);\n res[0] = this[0] * ys;\n res[1] = this[1] * xs;\n res[2] = 1;\n return res;\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 allDone = function () {\n var done = true, tix, theT;\n for (tix = 0; tix < TurtleGraphics.turtleList.length; tix = tix + 1) {\n theT = TurtleGraphics.turtleList[tix];\n done = done && theT.aCount >= theT.drawingEvents.length;\n }\n return done;\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 canvasLib = TurtleGraphics.canvasLib[TurtleGraphics.defaults.canvasID],\n incr = TurtleGraphics.canvasLib[TurtleGraphics.defaults.canvasID].getCounter(),\n t,\n tix,\n i,\n \t\t\tcurrentPos,\n currentHead,\n filling,\n oper,\n ts,\n tmpColor,\n size,\n speed;\n\n\t\tcontext.moveTo(0, 0);\n\t\tcontext.lineCap = 'round';\n\t\tcontext.lineJoin = 'round';\n context.clearRect(canvasLib.llx, canvasLib.lly, canvasLib.urx - canvasLib.llx, canvasLib.ury - canvasLib.lly); //canvas.style.setProperty(\"background-color\",TurtleGraphics.turtleCanvas.bgcolor.v);\n TurtleGraphics.renderClock += incr;\n for (tix = 0; tix < TurtleGraphics.turtleList.length; tix = tix + 1) {\n currentPos = new Vector(0, 0, 0);\n currentHead = new Vector(1, 0, 0);\n context.fillStyle = 'black';\n context.strokeStyle = 'black';\n t = TurtleGraphics.turtleList[tix];\n\t\t\tcurrentHead = t.heading;\n context.lastCanvas = t.turtleCanvas;\n if (t.aCount >= t.drawingEvents.length) {\n t.aCount = t.drawingEvents.length - 1;\n }\n\n\t\t\tcontext.lineWidth = t.get_pen_width();\n\n filling = false;\n if (isNaN(t.turtleCanvas.delay)) {\n t.turtleCanvas.delay = 0;\n }\n //console.log(tix + \" : \" + t.clearPoint + \" to \" + t.aCount)\n for (i = t.clearPoint; (i <= t.aCount || t.turtleCanvas.delay === 0) && i < t.drawingEvents.length; i = i + 1) {\n if (i > t.aCount) {\n //If se jump past aCount, jump it ahead\n t.aCount = i;\n }\n oper = t.drawingEvents[i];\n ts = oper[oper.length - 1];\n //console.log(i + \"/\" + ts + oper [0] + \"{\" + oper [1] + \"}\" + t.turtleCanvas.delay)\n if (ts <= TurtleGraphics.renderClock || t.turtleCanvas.delay === 0) {\n if (ts > TurtleGraphics.renderClock) {\n //If we go past the render clock, jump it ahead\n TurtleGraphics.renderClock = ts;\n }\n //console.log(\"<==\")\n switch (oper[0]) {\n case 'LT': //line To\n if (!filling) {\n context.beginPath();\n context.moveTo(oper[1], oper[2]);\n }\n context.lineTo(oper[3], oper[4]);\n context.strokeStyle = oper[5];\n context.stroke();\n currentPos = new Vector(oper[3], oper[4], 0);\n if (!filling) {\n context.closePath();\n }\n break;\n case 'MT': //move to\n context.moveTo(oper[3], oper[4]);\n currentPos = new Vector(oper[3], oper[4], 0);\n break;\n case 'BF': //begin fill\n context.beginPath();\n context.moveTo(oper[1], oper[2]);\n filling = true;\n break;\n case 'EF': //end fill\n context.fillStyle = oper[3];\n context.stroke();\n context.fill();\n context.closePath();\n filling = false;\n break;\n case 'FC': // fill color\n \t\t\t\t\t\tcontext.fillStyle = oper[1];\n break;\n case 'TC': // turtle color\n context.strokeStyle = oper[1];\n break;\n case 'PW': // Pen width\n context.lineWidth = oper[1];\n break;\n case 'DT': // Dot\n tmpColor = context.fillStyle;\n context.fillStyle = oper[2];\n size = oper[1];\n context.fillRect(oper[3] - size / 2, oper[4] - size / 2, size, size);\n context.fillStyle = tmpColor;\n break;\n case 'CI': // Circle\n if (!filling) {\n context.beginPath();\n }\n context.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], oper[2] + Math.sin(oper[5]) * oper[3], 0);\n context.stroke();\n if (!filling) {\n context.closePath();\n }\n break;\n case 'WT':\n // write\n if (context.font) {\n context.font = oper[2];\n }\n context.scale(1, -1);\n context.fillText(oper[1], oper[3], -oper[4]);\n context.scale(1, -1);\n break;\n case 'ST':\n // stamp\n t.drawturtle(oper[3], new Vector(oper[1], oper[2], 0));\n break;\n case 'HT': // hide turtle\n t.visible = false;\n break;\n case 'SH': // show turtle\n t.visible = true;\n break;\n case 'TT': // turn\n currentHead = oper[1];\n break;\n case 'CL': // clear\n clear_canvas(t.canvasID);\n t.clearPoint = i; // Different from reset that calls clear because it leaves the turtles where they are\n break;\n case 'DL': // delay\n t.turtleCanvas.delay = oper[1];\n break;\n case 'SC': // speed change\n speed = oper[1];\n\n if (speed < 0) {\n t.turtleCanvas.delay = 0;\n } else {\n if (speed > 10) {\n speed = 10;\n }\n t.turtleCanvas.delay = (10 - speed % 11 + 1) * t.turtleCanvas.timeFactor; //10\n }\n\n //t.turtleCanvas.intervalId = clearInterval(t.turtleCanvas.intervalId);\n //t.turtleCanvas.intervalId = setInterval(render, t.turtleCanvas.delay)\n if (oper[2]) {\n t.turtleCanvas.setSegmentLength(oper[2]);\n }\n break;\n case 'CS': // change shape\n t.currentShape = oper[1];\n break;\n case 'NO':\n break;\n } //else {\n //console.log('unknown op: ' + oper[0]);\n //} // end of oper[0] test\n } // end of if ts < render clock\n }\n // end of for\n // console.log(TurtleGraphics.renderClock + \" / \" + t.aCount)\n // console.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) {\n // && allDone() ){\n // t.turtleCanvas.doneAnimating(t);\n // console.log(\"done animating\")\n if (context.lastCanvas) {\n context.lastCanvas.doneAnimating(t);\n }\n } else {\n //t.turtleCanvas.intervalId = setTimeout(render, t.turtleCanvas.delay)\n if (context.lastCanvas) {\n context.lastCanvas.intervalId = setTimeout(render, context.lastCanvas.delay);\n }\n }\n };\n //\n // Drawing Functions\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 numSegs = Math.floor(ep.sub(sp).len() / sL),\n res = [],\n oldp = sp,\n newp,\n op = '',\n i;\n if (pen) {\n op = 'LT';\n } else {\n op = 'MT';\n }\n for (i = 0; i < numSegs; i = i + 1) {\n newp = oldp.linear(1, sL, head);\n res.push([\n op,\n oldp[0],\n oldp[1],\n newp[0],\n newp[1]\n ]);\n oldp = newp;\n }\n if (!(oldp[0] === ep[0] && oldp[1] === ep[1])) {\n res.push([\n op,\n oldp[0],\n oldp[1],\n ep[0],\n ep[1]\n ]);\n }\n return res;\n };\n\n clear_canvas = function (canId) {\n var ctx = document.getElementById(canId).getContext('2d');\n //if (arguments.length >= 2) {\n // fillStyle = arguments[1];\n // fillRect(0, 0, canvas.width, canvas.height);\n //}\n ctx.clearRect(-ctx.canvas.width / 2, -ctx.canvas.height / 2, ctx.canvas.width, ctx.canvas.height);\n };\n //\n // Define TurtleCanvas\n //\n function TurtleCanvas(options) {\n this.canvasID = TurtleGraphics.defaults.canvasID;\n if (options.canvasID) {\n this.canvasID = options.canvasID;\n }\n this.canvas = document.getElementById(this.canvasID);\n this.context = this.canvas.getContext('2d');\n this.canvas.style.display = 'block';\n this.canvas.style.opacity = 1;\n //$(this.canvas).fadeIn();\n this.lineScale = 1;\n this.xptscale = 1;\n this.yptscale = 1;\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 this.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 }\n TurtleCanvas.prototype.setup = function (width, height) {\n this.canvas.width = width;\n this.canvas.height = height;\n this.lineScale = 1;\n this.xptscale = 1;\n this.yptscale = 1;\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 this.timeFactor = 5;\n if (TurtleGraphics.defaults.animate) {\n this.delay = 5 * this.timeFactor;\n } else {\n this.delay = 0;\n }\n if (TurtleGraphics.canvasInit === false) {\n this.context.save();\n this.context.translate(this.canvas.width / 2, this.canvas.height / 2);\n // move 0,0 to center.\n this.context.scale(1, -1);\n // 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; // RNL\n } else {\n this.context.restore();\n this.context.translate(this.canvas.width / 2, this.canvas.height / 2);\n // move 0,0 to center.\n this.context.scale(1, -1);\n // scaling like this flips the y axis the right way.\n this.context.clearRect(-this.canvas.width / 2, -this.canvas.height / 2, this.canvas.width, this.canvas.height);\n }\n };\n TurtleCanvas.prototype.addToCanvas = function (t) {\n this.tlist.push(t);\n };\n TurtleCanvas.prototype.onCanvas = function (t) {\n return this.tlist.indexOf(t) >= 0;\n };\n TurtleCanvas.prototype.isAnimating = function () {\n return this.tlist.length > 0;\n };\n TurtleCanvas.prototype.startAnimating = function (t) {\n if (!this.isAnimating()) {\n this.intervalId = setTimeout(render, this.delay); //setInterval(render, this.delay);\n }\n if (!this.onCanvas(t)) {\n //Added by RNL in case startAnimating is called after it's already been added\n this.addToCanvas(t);\n }\n\t\ttry {\n \t\t\tSk.isTurtleProgram = true;\n\t\t} catch (ReferenceEror) {\n \t\t}\n };\n TurtleCanvas.prototype.doneAnimating = function () {\n var i;\n this.tlist.splice(0, this.tlist.length);\n clearTimeout(this.intervalId);\n if (TurtleGraphics.doneDelegates) {\n for (i = 0; i < TurtleGraphics.doneDelegates.length; i = i + 1) {\n TurtleGraphics.doneDelegates[i]();\n }\n }\n };\n TurtleCanvas.prototype.cancelAnimation = function () {\n var t;\n if (this.intervalId) {\n clearTimeout(this.intervalId);\n }\n for (t = 0; t < this.tlist.length; t = t + 1) {\n this.tlist[t].aCount = this.tlist[t].drawingEvents.length - 1;\n }\n render();\n };\n TurtleCanvas.prototype.setSpeedDelay = function (s) {\n // RNL\n var df = 10 - s % 11 + 1;\n this.delay = df * this.timeFactor; //RNL was 10;\n };\n TurtleCanvas.prototype.setDelay = function (d) {\n this.delay = d;\n };\n TurtleCanvas.prototype.getDelay = function () {\n //RNL\n return this.delay;\n };\n TurtleCanvas.prototype.setCounter = function (s) {\n if (!s || s <= 0) {\n //Don't let this be less than 1\n s = 1;\n }\n this.renderCounter = s;\n };\n TurtleCanvas.prototype.getCounter = function () {\n return this.renderCounter;\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 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 this.llx = llx;\n this.lly = lly;\n this.urx = urx;\n this.ury = ury;\n };\n TurtleCanvas.prototype.window_width = function () {\n return this.canvas.width;\n };\n TurtleCanvas.prototype.window_height = function () {\n return this.canvas.height;\n };\n TurtleCanvas.prototype.bgcolor = function (c) {\n this.background_color = c;\n this.canvas.style.setProperty('background-color', c.v); //$(this.canvas).css(\"background-color\",c.v);\n };\n TurtleCanvas.prototype.setSegmentLength = function (s) {\n this.segmentLength = s;\n };\n TurtleCanvas.prototype.getSegmentLength = function () {\n return this.segmentLength;\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 theCanvas = this,\n eventHandler = function () {\n if (!theCanvas.isAnimating()) {\n if (TurtleGraphics.fadeOnExit) {\n //Let's this be configurable\n document.getElementById(canvas_id).style.display = 'none'; //$(\"#\"+canvas_id).hide();\n }\n document.getElementById(canvas_id).removeEventListener('click', eventHandler);\n //$(\"#\"+canvas_id).unbind('click');\n TurtleGraphics.canvasInit = false;\n delete TurtleGraphics.canvasLib[canvas_id];\n }\n };\n this.canvas.addEventListener('click', eventHandler, false);\n };\n TurtleCanvas.prototype.turtles = function () {\n return TurtleGraphics.turtleList;\n };\n TurtleCanvas.prototype.tracer = function (t, d) {\n var i;\n //New version NOT attached to a turtle (as per real turtle)\n this.setCounter(t);\n if (t === 0) {\n for (i = 0; i < this.turtleList; i = i + 1) {\n this.turtleList[i].animate = false;\n }\n this.cancelAnimation();\n }\n if (d !== undefined) {\n this.setDelay(d);\n }\n };\n // Constructor for Turtle objects\n function Turtle(opt) {\n this.initialize(opt);\n TurtleGraphics.turtleList.push(this);\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 this.position = this.home;\n this.context.moveTo(this.home[0], this.home[1]);\n this.heading = new Vector([1, 0, 0]);\n // to the right; in turtle space x+ direction\n this.normal = new Vector([0, 0, -1]); // in z- direction\n };\n Turtle.prototype.initialize = function (opt) {\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 p;\n for (p = 0; p < pl.length; p = p + 1) {\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 p;\n for (p = 0; p < pl.length; p = p + 1) {\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, -10 ],\n [ 3.09, -9.51 ],\n [ 5.88, -8.09 ],\n [ 8.09, -5.88 ],\n [ 9.51, -3.09 ]\n ],\n res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n function triangleShapePoints() {\n var pl = [\n [ 10, -5.77 ],\n [ 0, 11.55 ],\n [ -10, -5.77 ]\n ],\n res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n function squareShapePoints() {\n var pl = [\n [ 10, -10 ],\n [ 10, 10 ],\n [ -10, 10 ],\n [ -10, -10 ]\n ],\n res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\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 res = [],\n p;\n for (p = 0; p < pl.length; p = p + 1) {\n res.push(new Vector(pl[p]));\n }\n return res;\n }\n\n // Initialize the turtle.\n var options = {}, ctx = null;\n if (opt) {\n options = opt;\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 this.animate = TurtleGraphics.defaults.animate;\n ctx = this.context;\n if (TurtleGraphics.canvasInit === false) {\n // This is a workaround until I understand skulpt re-running better\n // the downside is that this limits us to a single turtle...\n ctx.save();\n ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);\n // move 0,0 to center.\n ctx.scale(1, -1);\n // 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 this.turtleCanvas = TurtleGraphics.canvasLib[this.canvasID];\n this.home = new Vector([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.square = squareShapePoints();\n this.shapeStore.triangle = triangleShapePoints();\n this.shapeStore.blank = [new Vector(0, 0)];\n this.shapeStore.classic = classicShapePoints();\n this.currentShape = 'classic';\n this.drawingEvents = [];\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; // RNL for clear/clearScreen\n };\n Turtle.prototype.clean = function (color) {\n // Clean the canvas\n // Optional second argument is color\n if (arguments.length >= 1) {\n clear_canvas(this.canvasID, color);\n } else {\n clear_canvas(this.canvasID);\n }\n this.initialize();\n };\n Turtle.prototype.addDrawingEvent = function (eventList) {\n TurtleGraphics.eventCount += 1;\n eventList.push(TurtleGraphics.eventCount);\n this.drawingEvents.push(eventList);\n };\n Turtle.prototype.draw_line = function (newposition) {\n var ctx = this.context,\n r,\n s;\n if (!this.animate) {\n if (!this.filling) {\n ctx.beginPath();\n ctx.moveTo(this.position[0], this.position[1]);\n }\n ctx.lineCap = 'round';\n ctx.lineJoin = 'round';\n ctx.lineWidth = this.get_pen_width();\n ctx.strokeStyle = this.penStyle;\n ctx.lineTo(newposition[0], newposition[1]);\n\t\t\t//ctx.moveTo(newposition[0], newposition[1]);\n \t\t\tthis.position = newposition;\n ctx.stroke();\n if (!this.filling) {\n ctx.closePath();\n }\n } else {\n r = segmentLine(this.position, newposition, this.turtleCanvas.getSegmentLength(), this.pen);\n for (s = 0; s < r.length; s = s + 1) {\n r[s].push(this.penStyle);\n this.addDrawingEvent(r[s]);\n }\n if (!this.turtleCanvas.isAnimating()) {\n this.turtleCanvas.startAnimating(this);\n } else {\n if (!this.turtleCanvas.onCanvas(this)) {\n this.turtleCanvas.addToCanvas(this);\n }\n }\n }\n };\n Turtle.prototype.forward = function (d) {\n var newposition = this.position.linear(1, d, this.heading);\n this.goto(newposition);\n };\n Turtle.prototype.backward = function (d) {\n this.forward(-d);\n };\n //This is an internal function that sets the position without doing any drawing\n Turtle.prototype.teleport_to = function (nx, ny) {\n var newposition;\n if (nx instanceof Vector) {\n newposition = nx;\n } else {\n newposition = new Vector([nx, ny, 0]);\n }\n this.context.moveTo(newposition[0], newposition[1]);\n this.position = newposition;\n };\n Turtle.prototype.goto = function (nx, ny) {\n var newposition, r, s;\n if (nx instanceof Vector) {\n newposition = nx;\n } else {\n newposition = new Vector([nx, ny, 0]);\n }\n\t\tif (this.pen) {\n this.draw_line(newposition);\n } else {\n if (!this.animate) {\n this.context.moveTo(newposition[0], newposition[1]);\n } else {\n r = segmentLine(this.position, newposition, this.turtleCanvas.getSegmentLength(), this.pen);\n for (s = 0; s < r.length; s = s + 1) {\n this.addDrawingEvent(r[s]);\n }\n if (!this.turtleCanvas.isAnimating()) {\n this.turtleCanvas.startAnimating(this);\n } else {\n if (!this.turtleCanvas.onCanvas(this)) {\n this.turtleCanvas.addToCanvas(this);\n }\n }\n }\n }\n this.position = newposition;\n };\n Turtle.prototype.delay = function (d) {\n // RNL\n if (d !== null) {\n if (d < 0) {\n d = -d;\n }\n if (!this.animate) {\n this.turtleCanvas.setDelay(d);\n } else {\n this.turtleCanvas.setDelay(d);\n this.addDrawingEvent([ 'DL', d ]);\n this.addDrawingEvent(['NO']);\n }\n }\n return this.turtleCanvas.getDelay();\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 ) {\n this.animate = false;\n this.turtleCanvas.cancelAnimation();\n } else {\n this.turtleCanvas.setSpeedDelay(s);\n this.addDrawingEvent([ 'SC', s, t ]);\n this.addDrawingEvent(['NO']);\n }\n if (t) {\n this.turtleCanvas.setSegmentLength(t); // set the number of units to divide a segment into\n } else {\n this.turtleCanvas.setSegmentLength(10);\n }\n };\n Turtle.prototype.tracer = function (t, d) {\n this.turtleCanvas.setCounter(t);\n if (t === 0) {\n this.animate = false;\n this.turtleCanvas.cancelAnimation();\n }\n if (d !== undefined) {\n this.turtleCanvas.setDelay(d);\n }\n };\n Turtle.prototype.getRenderCounter = function () {\n return this.turtleCanvas.getCounter();\n };\n Turtle.prototype.turn = function (phi) {\n var alpha = phi * Degree2Rad,\n left = this.normal.cross(this.heading),\n newheading = this.heading.rotateNormal(left, alpha);\n this.heading = newheading;\n if (this.animate) {\n this.addDrawingEvent([ 'TT', this.heading ]);\n }\n };\n Turtle.prototype.right = Turtle.prototype.turn;\n Turtle.prototype.left = function (phi) {\n this.turn(-phi);\n };\n Turtle.prototype.get_heading = function () {\n if (TurtleGraphics.defaults.degrees) {\n return this.heading.toAngle();\n }\n return this.heading;\n };\n Turtle.prototype.get_position = function () {\n return this.position;\n };\n Turtle.prototype.getx = function () {\n return this.position[0];\n };\n Turtle.prototype.gety = function () {\n return this.position[1];\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 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 }\n return res;\n };\n Turtle.prototype.distance = function (to, y) {\n if ((typeof to).toLowerCase() === 'number') {\n to = new Vector(to, y, 0);\n }\n return this.position.sub(new Vector(to)).len();\n };\n Turtle.prototype.dot = function (psize, pcolor) {\n var size = 2,\n ctx = this.context,\n curPenStyle = this.penStyle,\n \t\t\tcurFillStyle = this.fillStyle;\n\n if (arguments.length >= 1) {\n size = psize;\n }\n size = size * this.turtleCanvas.lineScale;\n\n if (!this.animate) {\n \t\t\tif (pcolor) {\n \t\t\t\tctx.fillStyle = pcolor;\n\t\t\t\tctx.strokeStyle = pcolor;\n\t\t\t}\n ctx.fillRect(this.position[0] - size / 2, this.position[1] - size / 2, size, size);\n\t\t\tif (pcolor) {\n \t\t\t\tctx.fillStyle = curFillStyle;\n\t\t\t\tctx.strokeStyle = curPenStyle;\n\t\t\t}\n } else {\n this.addDrawingEvent([\n 'DT',\n size,\n pcolor || ctx.strokeStyle,\n this.position[0],\n this.position[1]\n ]);\n }\n };\n Turtle.prototype.circle = function (radius, extent) {\n var arcLen, segLen, extentPart, extentLeft;\n if (extent === undefined) {\n extent = 360;\n }\n if (this.animate) {\n arcLen = Math.abs(radius * Math.PI * 2 * extent / 360);\n segLen = this.turtleCanvas.getSegmentLength();\n if (arcLen <= segLen) {\n this.arc(radius, extent);\n } else {\n //Break the arc into segments for animation\n extentPart = segLen / arcLen * extent;\n extentLeft = extent;\n while (Math.abs(extentLeft) > Math.abs(extentPart)) {\n this.arc(radius, extentPart);\n extentLeft = extentLeft - extentPart;\n }\n if (Math.abs(extentLeft) > 0.01) {\n this.arc(radius, extentLeft);\n }\n }\n if (!this.turtleCanvas.isAnimating()) {\n this.turtleCanvas.startAnimating(this);\n } else {\n if (!this.turtleCanvas.onCanvas(this)) {\n this.turtleCanvas.addToCanvas(this);\n }\n }\n } else {\n this.arc(radius, extent);\n }\n };\n Turtle.prototype.arc = function (radius, extent) {\n //Figure out where the turtle is and which way it's facing\n var turtleHeading = this.get_heading(),\n tx = this.position[0],\n ty = this.position[1],\n //Figure out the circle center\n cx = tx + radius * Math.cos((turtleHeading + 90) * Degree2Rad),\n cy = ty + radius * Math.sin((turtleHeading + 90) * Degree2Rad),\n //Canvas arc angles go CLOCKWISE, not COUNTERCLOCKWISE like Turtle\n //Figure out our arc angles\n startAngleDeg,\n endAngleDeg,\n startAngle,\n endAngle,\n turtleArc,\n newTurtleHeading,\n nx,\n ny;\n\n if (radius >= 0) {\n startAngleDeg = turtleHeading - 90;\n } else {\n startAngleDeg = turtleHeading + 90;\n }\n\n if (extent) {\n if (radius >= 0) {\n endAngleDeg = startAngleDeg + extent;\n } else {\n endAngleDeg = startAngleDeg - extent;\n }\n } else {\n if (radius >= 0) {\n endAngleDeg = startAngleDeg + 360;\n } else {\n endAngleDeg = startAngleDeg - 360;\n }\n }\n //Canvas angles are opposite\n startAngleDeg = 360 - startAngleDeg;\n endAngleDeg = 360 - endAngleDeg;\n //Becuase the y axis has been flipped in HTML5 Canvas with a tanslation, we need to adjust the angles\n startAngleDeg = -startAngleDeg;\n endAngleDeg = -endAngleDeg;\n //Convert to radians\n startAngle = startAngleDeg * Degree2Rad;\n endAngle = endAngleDeg * Degree2Rad;\n //Do the drawing\n if (!this.animate) {\n if (!this.filling) {\n this.context.beginPath();\n }\n this.context.arc(cx, cy, Math.abs(radius), startAngle, endAngle, radius * extent <= 0);\n this.context.stroke();\n if (!this.filling) {\n this.context.closePath();\n }\n } else {\n this.addDrawingEvent([\n 'CI',\n cx,\n cy,\n Math.abs(radius),\n startAngle,\n endAngle,\n radius * extent <= 0\n ]);\n }\n //Move the turtle only if we have to\n if (extent && extent % 360 !== 0) {\n if (radius >= 0) {\n turtleArc = extent;\n } else {\n turtleArc = -extent;\n }\n newTurtleHeading = (turtleHeading + turtleArc) % 360;\n if (newTurtleHeading < 0) {\n newTurtleHeading = newTurtleHeading + 360;\n }\n nx = cx + radius * Math.cos((newTurtleHeading - 90) * Degree2Rad);\n ny = cy + radius * Math.sin((newTurtleHeading - 90) * Degree2Rad);\n //y coord is inverted in turtle\n //Move it internally\n this.set_heading(newTurtleHeading);\n this.teleport_to(nx, ny);\n //If we're animating the turtle, move it on the screen\n if (this.animate) {\n this.addDrawingEvent([\n 'TT',\n this.heading\n ]);\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 }\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 }\n this.addDrawingEvent([\n 'WT',\n theText,\n fontspec,\n this.position[0],\n 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 // Pen and Style functions\n //\n Turtle.prototype.pen_down = function () {\n this.pen = true;\n };\n Turtle.prototype.down = Turtle.prototype.pen_down;\n Turtle.prototype.pen_up = function () {\n this.pen = false;\n };\n Turtle.prototype.up = Turtle.prototype.pen_up;\n Turtle.prototype.get_pen = function () {\n return this.pen;\n };\n Turtle.prototype.set_pen_width = function (w) {\n if (this.animate) {\n this.addDrawingEvent([\n 'PW',\n w * this.turtleCanvas.lineScale\n ]);\n } else {\n this.penWidth = w;\n }\n };\n Turtle.prototype.get_pen_width = function () {\n return this.penWidth * this.turtleCanvas.lineScale;\n };\n Turtle.prototype.set_pen_color = function (c, g, b) {\n if (typeof c === 'string') {\n this.penStyle = c;\n } else {\n var rs, gs, bs, c0, c1, c2;\n if (Array.isArray(c)) {\n c0 = c[0];\n c1 = c[1];\n c2 = c[2];\n } else {\n c0 = c;\n c1 = g;\n c2 = b;\n }\n rs = Math.abs(c0).toString(16);\n gs = Math.abs(c1).toString(16);\n bs = Math.abs(c2).toString(16);\n while (rs.length < 2) {\n rs = '0' + rs;\n }\n while (gs.length < 2) {\n gs = '0' + gs;\n }\n while (bs.length < 2) {\n bs = '0' + bs;\n }\n c = '#' + rs + gs + bs;\n this.penStyle = c;\n }\n this.context.strokeStyle = c;\n if (this.animate) {\n this.addDrawingEvent([\n 'TC',\n c\n ]);\n }\n };\n Turtle.prototype.set_fill_color = function (c, g, b) {\n if (typeof c === 'string') {\n this.fillStyle = c;\n } else {\n var rs, gs, bs, c0, c1, c2;\n if (Array.isArray(c)) {\n c0 = c[0];\n c1 = c[1];\n c2 = c[2];\n } else {\n c0 = c;\n c1 = g;\n c2 = b;\n }\n rs = Math.abs(c0).toString(16);\n gs = Math.abs(c1).toString(16);\n bs = Math.abs(c2).toString(16);\n while (rs.length < 2) {\n rs = '0' + rs;\n }\n while (gs.length < 2) {\n gs = '0' + gs;\n }\n while (bs.length < 2) {\n bs = '0' + bs;\n }\n c = '#' + rs + gs + bs;\n this.fillStyle = c;\n }\n this.context.fillStyle = c;\n if (this.animate) {\n this.addDrawingEvent([\n 'FC',\n c\n ]);\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([\n 'BF',\n this.position[0],\n 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([\n 'EF',\n this.position[0],\n this.position[1],\n 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 Turtle.prototype.hideturtle = function () {\n if (this.animate) {\n this.addDrawingEvent(['HT']);\n }\n this.visible = false;\n };\n Turtle.prototype.isvisible = function () {\n return this.visible;\n };\n //\n // Appearance\n //\n Turtle.prototype.shape = function (s) {\n if (this.shapeStore[s]) {\n this.addDrawingEvent(['CS', s]); // add a Change Shape event\n }\n };\n Turtle.prototype.drawturtle = function (pHeading, pos) {\n var rtPoints = [],\n plist = this.shapeStore[this.currentShape],\n head,\n p,\n i;\n\n if (pHeading !== undefined) {\n head = pHeading - 90;\n } else {\n head = this.heading.toAngle() - 90;\n }\n\n if (!pos) {\n pos = this.position;\n }\n\n for (p = 0; p < plist.length; p = p + 1) {\n rtPoints.push(plist[p]\n .scale(this.turtleCanvas.xptscale, this.turtleCanvas.yptscale)\n .rotate(head)\n .add(pos));\n }\n this.context.beginPath();\n this.context.moveTo(rtPoints[0][0], rtPoints[0][1]);\n for (i = 1; i < rtPoints.length; i = i + 1) {\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 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([\n 'ST',\n this.position[0],\n this.position[1],\n this.heading.toAngle()\n ]);\n } else {\n this.drawturtle();\n }\n };\n Turtle.prototype.clear = function () {\n if (this.animate) {\n this.addDrawingEvent(['CL']);\n } else {\n \t\t\tclear_canvas(this.canvasID);\n\t\t\tthis.penStyle = 'black';\n\t\t\tthis.penWidth = 2;\n\t\t\tthis.fillStyle = 'black';\n }\n };\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// Wrapper around the Turtle Module starts here.\n//\n var $builtinmodule = function (name) {\n 'use strict';\n var mod = {},\n \t\tinitializeTurtlegraphics = function() {\n \t\t\tif (!TurtleGraphics) { TurtleGraphics = {}; }\n\t\t\tif (!TurtleGraphics.defaults) {\n \t\t\t\tTurtleGraphics.defaults = {\n\t\t\t\t\tanimate: true,\n\t\t\t\t\tcanvasID: Sk.canvas,\n\t\t\t\t\tdegrees: true\n\t\t\t\t}\n \t\t\t} else if (Sk.canvas) {\n \t\t\t\tTurtleGraphics.defaults.canvasID = Sk.canvas;\n\t\t\t}\n\t\t\tif (!TurtleGraphics.doneDelegates) { TurtleGraphics.doneDelegates = []; }\n\t\t},\n\t\tremoveDisabled = function () {\n \t\t\tif (Sk.runButton) {\n \t\t\t\tSk.runButton.removeAttribute('disabled');\n\t\t\t}\n\t\t},\n checkArgs = function (expected, actual, func) {\n if (actual !== expected) {\n throw new Sk.builtin.TypeError(func + ' takes exactly ' + expected + ' positional argument (' + actual + ' given)');\n }\n },\n turtle = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n \t\t\t\tinitializeTurtlegraphics();\n\t\t\t\tif (TurtleGraphics.doneDelegates.indexOf(removeDisabled) === -1){\n \t\t\t\t\tTurtleGraphics.doneDelegates.push(removeDisabled);\n\t\t\t\t}\n self.theTurtle = new TurtleGraphics.Turtle();\n });\n //\n // Turtle Motion\n //\n //\n // Move and Draw\n //\n $loc.forward = new Sk.builtin.func(function (self, dist) {\n dist = Sk.builtin.asnum$(dist);\n checkArgs(2, arguments.length, 'forward()');\n self.theTurtle.forward(dist);\n });\n $loc.fd = $loc.forward;\n $loc.backward = new Sk.builtin.func(function (self, dist) {\n dist = Sk.builtin.asnum$(dist);\n checkArgs(2, arguments.length, 'backward()');\n self.theTurtle.forward(-dist);\n });\n $loc.back = $loc.backward;\n $loc.bk = $loc.backward;\n $loc.right = new Sk.builtin.func(function (self, angle) {\n angle = Sk.builtin.asnum$(angle);\n checkArgs(2, arguments.length, 'right()');\n self.theTurtle.turn(angle);\n });\n $loc.rt = $loc.right;\n $loc.left = new Sk.builtin.func(function (self, angle) {\n angle = Sk.builtin.asnum$(angle);\n checkArgs(2, arguments.length, 'left()');\n self.theTurtle.turn(-angle);\n });\n $loc.lt = $loc.left;\n $loc.goto_$rw$ = new Sk.builtin.func(function (self, nx, ny) {\n nx = Sk.builtin.asnum$(nx);\n ny = Sk.builtin.asnum$(ny);\n checkArgs(3, arguments.length, 'goto()');\n self.theTurtle.goto(nx, ny);\n });\n $loc.setposition = new Sk.builtin.func(function (self, nx, ny) {\n nx = Sk.builtin.asnum$(nx);\n ny = 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 $loc.setx = new Sk.builtin.func(function (self, nx) {\n nx = Sk.builtin.asnum$(nx);\n checkArgs(2, arguments.length, 'setx()');\n self.theTurtle.goto(nx, self.theTurtle.GetY());\n });\n $loc.sety = new Sk.builtin.func(function (self, ny) {\n ny = Sk.builtin.asnum$(ny);\n checkArgs(2, arguments.length, 'sety()');\n self.theTurtle.goto(self.theTurtle.GetX(), ny);\n });\n $loc.setheading = new Sk.builtin.func(function (self, newhead) {\n newhead = Sk.builtin.asnum$(newhead);\n checkArgs(2, arguments.length, 'setheading()');\n return self.theTurtle.set_heading(newhead);\n });\n $loc.seth = $loc.setheading;\n $loc.home = new Sk.builtin.func(function (self) {\n self.theTurtle.go_home();\n });\n $loc.dot = new Sk.builtin.func(function (self, size, color) {\n size = 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 $loc.circle = new Sk.builtin.func(function (self, radius, extent) {\n radius = Sk.builtin.asnum$(radius);\n extent = Sk.builtin.asnum$(extent);\n self.theTurtle.circle(radius, extent);\n });\n $loc.delay = new Sk.builtin.func(function (self, d) {\n d = Sk.builtin.asnum$(d);\n return self.theTurtle.delay(d);\n });\n $loc.speed = new Sk.builtin.func(function (self, s, t) {\n s = Sk.builtin.asnum$(s);\n t = Sk.builtin.asnum$(t);\n self.theTurtle.speed(s, t);\n });\n $loc.tracer = new Sk.builtin.func(function (self, t, d) {\n t = Sk.builtin.asnum$(t);\n d = Sk.builtin.asnum$(d);\n self.theTurtle.tracer(t, d);\n });\n $loc.update = new Sk.builtin.func(function (self) {});\n // todo: stamp, clearstamp, clearstamps, undo, speed\n //\n // Tell Turtle's state\n //\n $loc.heading = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'heading()');\n return Sk.builtin.assk$(self.theTurtle.get_heading(), Sk.builtin.nmber.float$);\n });\n $loc.position = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'position()');\n var res = self.theTurtle.get_position(),\n x = new Sk.builtin.tuple([\n Sk.builtin.assk$(res[0], Sk.builtin.nmber.float$),\n Sk.builtin.assk$(res[1], Sk.builtin.nmber.float$)\n ]);\n return x;\n });\n $loc.pos = $loc.position;\n $loc.xcor = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'xcor()');\n var res = self.theTurtle.getx();\n return Sk.builtin.assk$(res, Sk.builtin.nmber.float$);\n });\n $loc.ycor = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'ycor()');\n var res = self.theTurtle.gety();\n return Sk.builtin.assk$(res, Sk.builtin.nmber.float$);\n });\n $loc.towards = new Sk.builtin.func(function (self, tx, ty) {\n tx = Sk.builtin.asnum$(tx);\n ty = Sk.builtin.asnum$(ty);\n if ((typeof tx).toLowerCase() === 'number') {\n tx = [ tx, ty, 0 ];\n } else {\n tx = [\n Sk.builtin.asnum$(tx.theTurtle.getx()),\n Sk.builtin.asnum$(tx.theTurtle.gety()),\n Sk.builtin.asnum$(0)\n ];\n }\n return Sk.builtin.assk$(self.theTurtle.towards(tx), Sk.builtin.nmber.float$);\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 tx = Sk.builtin.asnum$(tx);\n ty = Sk.builtin.asnum$(ty);\n if ((typeof tx).toLowerCase() === 'number') {\n tx = [\n tx,\n ty,\n 0\n ];\n } else {\n tx = [\n tx.theTurtle.getx(),\n tx.theTurtle.gety(),\n 0\n ];\n }\n return Sk.builtin.assk$(self.theTurtle.distance(tx), Sk.builtin.nmber.float$);\n });\n //\n // Setting and Measurement\n //\n // todo: degrees and radians...\n //\n // Pen Control\n //\n //\n // Drawing State\n //\n $loc.up = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'up()');\n self.theTurtle.pen_up();\n });\n $loc.penup = $loc.up;\n $loc.pu = $loc.up;\n $loc.down = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'down()');\n self.theTurtle.pen_down();\n });\n $loc.pendown = $loc.down;\n $loc.pd = $loc.down;\n $loc.width = new Sk.builtin.func(function (self, w) {\n w = Sk.builtin.asnum$(w);\n checkArgs(2, arguments.length, 'width()');\n self.theTurtle.set_pen_width(w);\n });\n $loc.pensize = $loc.width;\n $loc.isdown = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'isdown()');\n return self.theTurtle.get_pen();\n });\n // todo: pen -- return a dictionary full of pen stuff\n //\n // Color Control\n //\n $loc.fillcolor = new Sk.builtin.func(function (self, color, green, blue) {\n if (color) {\n if (blue) {\n color = Sk.builtin.asnum$(color);\n green = Sk.builtin.asnum$(green);\n blue = Sk.builtin.asnum$(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 color = Sk.builtin.asnum$(color);\n green = Sk.builtin.asnum$(green);\n blue = 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 color = Sk.builtin.asnum$(color);\n green = Sk.builtin.asnum$(green);\n blue = Sk.builtin.asnum$(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 [\n self.theTurtle.penStyle,\n self.theTurtle.fillStyle\n ];\n }\n });\n //\n // Filling\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 $loc.end_fill = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'end_fill()');\n self.theTurtle.end_fill();\n });\n $loc.fill = new Sk.builtin.func(function (self, fillt) {\n if (fillt === undefined) {\n return self.theTurtle.filling;\n }\n if (fillt) {\n self.theTurtle.begin_fill();\n } else {\n self.theTurtle.end_fill();\n }\n });\n //\n // More drawing control\n //\n $loc.reset = new Sk.builtin.func(function (self) {\n self.theTurtle.clean();\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 $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 $loc.isvisible = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'isvisible()');\n self.theTurtle.isvisible();\n });\n $loc.stamp = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'stamp()');\n self.theTurtle.stamp();\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 //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 //todo clean -- again multiple turtles\n $loc.setworldcoordinates = new Sk.builtin.func(function (self, llx, lly, urx, ury) {\n llx = Sk.builtin.asnum$(llx);\n lly = Sk.builtin.asnum$(lly);\n urx = Sk.builtin.asnum$(urx);\n ury = Sk.builtin.asnum$(ury);\n self.theTurtle.setworldcoordinates(llx, lly, urx, ury);\n });\n //Added by RNL\n $loc.clear = new Sk.builtin.func(function (self) {\n self.theTurtle.clear();\n });\n },\n screen = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n \t\t\t\tinitializeTurtlegraphics();\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 $loc.bgcolor = new Sk.builtin.func(function (self, c) {\n self.theScreen.bgcolor(c);\n });\n $loc.setworldcoordinates = new Sk.builtin.func(function (self, llx, lly, urx, ury) {\n llx = Sk.builtin.asnum$(llx);\n lly = Sk.builtin.asnum$(lly);\n urx = Sk.builtin.asnum$(urx);\n ury = Sk.builtin.asnum$(ury);\n self.theScreen.setworldcoordinates(llx, lly, urx, ury);\n });\n $loc.exitonclick = new Sk.builtin.func(function (self) {\n self.theScreen.exitonclick();\n });\n $loc.title = new Sk.builtin.func(function (self, titlestring) {});\n $loc.window_width = new Sk.builtin.func(function (self) {\n return Sk.builtin.assk$(self.theScreen.window_width(), Sk.builtin.nmber.int$);\n });\n $loc.window_height = new Sk.builtin.func(function (self) {\n return Sk.builtin.assk$(self.theScreen.window_height(), Sk.builtin.nmber.int$);\n });\n $loc.turtles = new Sk.builtin.func(function (self) {\n return self.theScreen.turtles();\n });\n $loc.colormode = new Sk.builtin.func(function (self) {});\n // $loc.clear = new Sk.builtin.func(function(self) {\n //\n // });\n var myfunc = function (self, width, height, startx, starty) {\n width = Sk.builtin.asnum$(width);\n height = Sk.builtin.asnum$(height);\n self.theScreen.setup(width, height);\n };\n // this should allow for named parameters\n myfunc.co_varnames = [\n 'self',\n 'width',\n 'height',\n 'startx',\n 'starty'\n ];\n myfunc.$defaults = [\n null,\n 500,\n 500,\n 0,\n 0\n ];\n $loc.setup = new Sk.builtin.func(myfunc);\n };\n // First we create an object, this will end up being the class\n // class\n Sk.tg = TurtleGraphics;\n mod.Turtle = Sk.misceval.buildClass(mod, turtle, 'Turtle', []);\n mod.Screen = Sk.misceval.buildClass(mod, screen, 'Screen', []);\n mod.tracer = new Sk.builtin.func(function (t, d) {\n var i;\n t = Sk.builtin.asnum$(t);\n d = Sk.builtin.asnum$(d);\n for (i = 0; i < Sk.tg.canvasLib.length; i = i + 1) {\n Sk.tg.canvasLib[i].tracer(t, d);\n }\n });\n mod.update = new Sk.builtin.func(function (self) {});\n return mod;\n };\n ", "src/lib/van/__init__.js": "//\n// Controller for a van\n//\n function VanController() {\n this.initialize();\n }\n VanController.prototype.initialize = function () {\n\n };\n VanController.prototype.highlightLineCallable = function(lineIndex, colour) {\n var lines = $('#editor .CodeMirror-code')[0].children;\n // unhighlight all lines\n var i;\n for (i = 0; i < lines.length; i++) {\n lines[i].style.background = \"\";\n }\n // highlight desired line\n if (typeof lines[lineIndex] != \"undefined\") {\n lines[lineIndex].style.background = colour;\n }\n };\n VanController.prototype.queueHighlight = function(colour) {\n var self = this;\n var lineIndex = Sk.currLineNo - 1;\n ocargo.animation.appendAnimation({\n type: 'callable',\n functionCall: function () { self.highlightLineCallable(lineIndex, colour); },\n description: 'highlight python callable',\n });\n };\n//\n// Movement and condition functions delegated appropriately\n//\n VanController.prototype.move_forwards = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.moveForwards();\n };\n VanController.prototype.turn_left = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed |= Sk.failed || !ocargo.model.turnLeft();\n };\n VanController.prototype.turn_right = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.turnRight();\n };\n VanController.prototype.turn_around = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.turnAround();\n };\n VanController.prototype.wait = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.wait();\n };\n VanController.prototype.deliver = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n }\n Sk.failed = Sk.failed || !ocargo.model.deliver();\n };\n VanController.prototype.sound_horn = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellowgreen\");\n return ocargo.model.sound_horn();\n }\n return false;\n };\n VanController.prototype.at_dead_end = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isDeadEnd();\n }\n return false;\n };\n VanController.prototype.at_destination = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isAtADestination();\n }\n return false;\n };\n VanController.prototype.at_traffic_light = function (c) {\n switch(c) {\n case \"GREEN\":\n return this.at_green_traffic_light();\n break;\n case \"RED\":\n return this.at_red_traffic_light();\n break;\n default:\n return false;\n }\n };\n VanController.prototype.at_red_traffic_light = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isTrafficLightRed();\n }\n return false;\n };\n VanController.prototype.at_green_traffic_light = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isTrafficLightGreen();\n }\n return false;\n };\n VanController.prototype.is_road = function (d) {\n switch(d) {\n case \"FORWARD\":\n return this.is_road_forward();\n break;\n case \"LEFT\":\n return this.is_road_left();\n break;\n case \"RIGHT\":\n return this.is_road_right();\n break;\n default:\n return false;\n }\n };\n VanController.prototype.is_road_forward = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isRoadForward();\n }\n return false;\n\n };\n VanController.prototype.is_road_left = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isRoadLeft();\n }\n return false;\n };\n VanController.prototype.is_road_right = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isRoadRight();\n }\n return false;\n };\n VanController.prototype.is_animal_crossing = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n return ocargo.model.isCowCrossing();\n }\n return false;\n };\n VanController.prototype.get_current_coordinate = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n var coordinate = ocargo.model.getCurrentCoordinate();\n return [coordinate.x, coordinate.y];\n }\n return null;\n };\n VanController.prototype.get_previous_coordinate = function () {\n if (!Sk.failed) {\n this.queueHighlight(\"yellow\");\n var coordinate = ocargo.model.getPreviousCoordinate();\n return [coordinate.x, coordinate.y];\n }\n return null;\n };\n\n var $builtinmodule = function (name) {\n 'use strict';\n var mod = {},\n checkArgs = function (expected, actual, func) {\n if (actual !== expected) {\n throw new Sk.builtin.TypeError(func + ' takes exactly ' + expected + ' positional argument (' + actual + ' given)');\n }\n },\n van = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n self.theVan = new VanController();\n });\n //\n // Van Action/Motion\n //\n $loc.move_forwards = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'move_forwards()');\n self.theVan.move_forwards();\n });\n $loc.turn_left = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'turn_left()');\n self.theVan.turn_left();\n });\n $loc.turn_right = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'turn_right()');\n self.theVan.turn_right();\n });\n $loc.turn_around = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'turn_around()');\n self.theVan.turn_around();\n });\n $loc.wait = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'wait()');\n self.theVan.wait();\n });\n $loc.deliver = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'deliver()');\n self.theVan.deliver();\n });\n $loc.sound_horn = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'sound_horn()');\n self.theVan.sound_horn();\n });\n //\n // Van state\n //\n $loc.at_dead_end = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_dead_end()');\n return Sk.builtin.bool(self.theVan.at_dead_end());\n });\n $loc.at_destination = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_destination()');\n return Sk.builtin.bool(self.theVan.at_destination());\n });\n $loc.at_traffic_light = new Sk.builtin.func(function (self, c) {\n checkArgs(2, arguments.length, 'at_traffic_light()');\n return Sk.builtin.bool(self.theVan.at_traffic_light(new Sk.builtin.str(c).v));\n });\n $loc.at_red_traffic_light = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_red_traffic_light()');\n return Sk.builtin.bool(self.theVan.at_red_traffic_light());\n });\n $loc.at_green_traffic_light = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'at_green_traffic_light()');\n return Sk.builtin.bool(self.theVan.at_green_traffic_light());\n });\n $loc.is_road = new Sk.builtin.func(function (self, d) {\n checkArgs(2, arguments.length, 'is_road()');\n return Sk.builtin.bool(self.theVan.is_road(new Sk.builtin.str(d).v));\n });\n $loc.is_road_forward = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_road_forward()');\n return Sk.builtin.bool(self.theVan.is_road_forward());\n });\n $loc.is_road_left = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_road_left()');\n return Sk.builtin.bool(self.theVan.is_road_left());\n });\n $loc.is_road_right = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_road_right()');\n return Sk.builtin.bool(self.theVan.is_road_right());\n });\n $loc.is_animal_crossing = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'is_animal_crossing()');\n return Sk.builtin.bool(self.theVan.is_animal_crossing());\n });\n $loc.get_current_coordinate = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'get_current_coordinate()');\n var coordinate = self.theVan.get_current_coordinate();\n if (coordinate) {\n return Sk.builtin.tuple(coordinate);\n } else {\n return Sk.builtin.none;\n }\n });\n $loc.get_previous_coordinate = new Sk.builtin.func(function (self) {\n checkArgs(1, arguments.length, 'get_previous_coordinate()');\n var coordinate = self.theVan.get_previous_coordinate();\n if (coordinate) {\n return Sk.builtin.tuple(coordinate);\n } else {\n return Sk.builtin.none;\n }\n });\n };\n\n mod.Van = Sk.misceval.buildClass(mod, van, 'Van', []);\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/lib/pythonds/graphs/__init__.py": "\n\n from .adjGraph import Graph\n from .adjGraph import Vertex\n from .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 #\n import unittest\n\n # this implementation of binary heap takes key value pairs,\n # we will assume that the keys are all comparable\n\n class 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\n class 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\n if __name__ == '__main__':\n unittest.main()\n ", "src/lib/pythonds/__init__.py": "", "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\n\n\n class Deque:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def addFront(self, item):\n self.items.append(item)\n\n def addRear(self, item):\n self.items.insert(0,item)\n\n def removeFront(self):\n return self.items.pop()\n\n def removeRear(self):\n return self.items.pop(0)\n\n def size(self):\n return len(self.items)\n ", "src/lib/processing/__init__.js": "var $builtinmodule = function(name)\n {\n var mod = {};\n var imList = [];\n var looping = true;\n\n // We need this to store a reference to the actual processing object which is not created\n // until the run function is called. Even then the processing object is passed by the\n // processing-js sytem as a parameter to the sketchProc function. Why not set it to None here\n //\n\n // See: http://processingjs.org/reference/\n\n mod.processing = null\n mod.p = null\n\n mod.CENTER = Sk.builtin.assk$(3, Sk.builtin.nmber.int$);\n mod.RADIUS = Sk.builtin.assk$(2, Sk.builtin.nmber.int$);\n mod.CORNERS = Sk.builtin.assk$(1, Sk.builtin.nmber.int$);\n mod.CORNER = Sk.builtin.assk$(0, Sk.builtin.nmber.int$);\n mod.RGB = Sk.builtin.assk$(1, Sk.builtin.nmber.int$);\n mod.HSB = Sk.builtin.assk$(3, Sk.builtin.nmber.int$);\n mod.CMYK = Sk.builtin.assk$(5, Sk.builtin.nmber.int$);\n mod.MITER = new Sk.builtin.str('miter');\n mod.BEVEL = new Sk.builtin.str('bevel');\n mod.ROUND = new Sk.builtin.str('round');\n mod.SQUARE = new Sk.builtin.str('butt');\n mod.PROJECT = new Sk.builtin.str('square');\n\n// 2D - Primitives\n mod.line = new Sk.builtin.func(function(x1, y1, x2, y2) {\n mod.processing.line(x1.v, y1.v, x2.v, y2.v);\n });\n\n mod.ellipse = new Sk.builtin.func(function(x,y,r1,r2) {\n mod.processing.ellipse(x.v,y.v,r1.v,r2.v)\n\n });\n\n mod.text = new Sk.builtin.func(function(theText, x, y) {\n mod.processing.text(theText.v, x.v, y.v);\n });\n\n mod.point = new Sk.builtin.func(function(x1,y1) {\n mod.processing.point(x1.v,y1.v)\n });\n\n mod.arc = new Sk.builtin.func(function(x, y, width, height, start, stop) {\n mod.processing.arc(x.v, y.v, width.v, height.v, start.v, stop.v)\n });\n\n mod.quad = new Sk.builtin.func(function(x1, y1, x2, y2, x3, y3, x4, y4) {\n mod.processing.quad(x1.v, y1.v, x2.v, y2.v, x3.v, y3.v, x4.v, y4.v)\n });\n\n mod.rect = new Sk.builtin.func(function(x, y, width, height, radius) {\n if (typeof(radius) == 'undefined') {\n var rad = 0\n } else {\n var rad = radius.v\n }\n mod.processing.rect(x.v, y.v, width.v, height.v, rad)\n });\n\n mod.triangle = new Sk.builtin.func(function(x1, y1, x2, y2, x3, y3) {\n mod.processing.triangle(x1.v, y1.v, x2.v, y2.v, x3.v, y3.v)\n });\n\n\n // 3D Primitives\n\n // todo: box, sphere, sphereDetail\n\n // Color\n mod.background = new Sk.builtin.func(function(r,g,b) {\n\n if (typeof(g) !== 'undefined')\n g = g.v\n if (typeof(b) !== 'undefined')\n b = b.v\n\n mod.processing.background(r.v,g,b)\n\n });\n\n mod.fill = new Sk.builtin.func(function(r,g,b) {\n // r will be either:\n // a number in which case the fill will be grayscale\n // a color object\n // g, and b may be undefined. If they hold values it will\n // be assumed that we have an r,g,b color tuple\n if (typeof(g) !== 'undefined')\n g = g.v\n if (typeof(b) !== 'undefined')\n b = b.v\n\n mod.processing.fill(r.v,g,b)\n\n });\n\n\n mod.stroke = new Sk.builtin.func(function(r,g,b) {\n\n if (typeof(g) !== 'undefined')\n g = g.v\n if (typeof(b) !== 'undefined')\n b = b.v\n\n mod.processing.stroke(r.v,g,b)\n\n });\n\n mod.noStroke = new Sk.builtin.func(function() {\n mod.processing.noStroke()\n });\n\n\n mod.colorMode = new Sk.builtin.func(function(model, maxV) {\n if (typeof(maxV) === 'undefined')\n maxV = 255\n else\n maxV = maxV.v\n mod.processing.colorMode(model.v, maxV)\n });\n\n mod.noFill = new Sk.builtin.func(function() {\n mod.processing.noFill()\n });\n\n\n // Environment\n\n mod.loop = new Sk.builtin.func(function() {\n if (mod.processing === null) {\n throw new Sk.builtin.Exception(\"Loop should be called in setup\")\n }\n looping = true;\n mod.processing.loop()\n });\n\n mod.noLoop = new Sk.builtin.func(function() {\n if (mod.processing === null) {\n throw new Sk.builtin.Exception(\"noLoop should be called in setup\")\n }\n looping = false;\n mod.processing.noLoop()\n });\n\n mod.frameRate = new Sk.builtin.func(function(fr) {\n mod.processing.frameRate(fr.v)\n\n });\n\n mod.size = new Sk.builtin.func(function(h,w) {\n mod.processing.size(h.v,w.v)\n\n });\n\n mod.exitp = new Sk.builtin.func(function(h,w) {\n mod.processing.exit()\n });\n\n\n mod.mouseX = new Sk.builtin.func(function() {\n return Sk.builtin.assk$(mod.processing.mouseX, Sk.builtin.nmber.int$);\n\n });\n\n mod.mouseY = new Sk.builtin.func(function() {\n return Sk.builtin.assk$(mod.processing.mouseY, Sk.builtin.nmber.int$);\n\n });\n\n // Attributes\n mod.rectMode = new Sk.builtin.func(function(mode) {\n mod.processing.rectMode(mode.v)\n });\n\n mod.strokeWeight = new Sk.builtin.func(function(wt) {\n mod.processing.strokeWeight(wt.v)\n\n });\n\n mod.smooth = new Sk.builtin.func(function() {\n mod.processing.smooth()\n });\n\n mod.noSmooth = new Sk.builtin.func(function() {\n mod.processing.noSmooth()\n });\n\n mod.ellipseMode = new Sk.builtin.func(function(mode) {\n mod.processing.ellipseMode(mode.v)\n });\n\n mod.strokeCap = new Sk.builtin.func(function(mode) {\n mod.processing.strokeCap(mode.v)\n });\n\n mod.strokeJoin = new Sk.builtin.func(function(mode) {\n mod.processing.strokeJoin(mode.v)\n });\n\n\n\n // Transforms\n\n mod.rotate = new Sk.builtin.func(function(rads) {\n // rotation in radians\n mod.processing.rotate(rads.v)\n\n });\n\n mod.scale = new Sk.builtin.func(function(sx, sy, sz) {\n if (typeof(sy) == 'undefined') {\n sy = 1.0\n } else\n sy = sy.v\n if (typeof(sz) == 'undefined') {\n sz = 1.0\n } else\n sz = sz.v\n mod.processing.scale(sx.v, sy, sz)\n });\n\n mod.translate = new Sk.builtin.func(function(sx, sy, sz) {\n if (typeof(sy) == 'undefined') {\n sy = 1.0\n } else\n sy = sy.v\n if (typeof(sz) == 'undefined') {\n sz = 1.0\n } else\n sz = sz.v\n mod.processing.translate(sx.v, sy, sz)\n });\n\n // todo: applyMatrix, popMatrix, printMatrix??, pushMatrix, resetMatrix, rotate{X,Y,Z}\n\n\n // //////////////////////////////////////////////////////////////////////\n // Run\n //\n // Create the processing context and setup of calls to setup, draw etc.\n //\n //\n // //////////////////////////////////////////////////////////////////////\n mod.run = new Sk.builtin.func(function() {\n function sketchProc(processing) {\n mod.processing = processing\n\n // processing.setup = function() {\n // if Sk.globals['setup']\n // Sk.misceval.callsim(Sk.globals['setup'])\n // }\n\n\n processing.draw = function() {\n // if there are pending image loads then just use the natural looping calls to\n // retry until all the images are loaded. If noLoop was called in setup then make\n // sure to revert to that after all the images in hand.\n var wait = false\n for (var i in imList) {\n if (imList[i].width == 0) {\n wait = true\n }\n }\n if (wait == true) {\n if (looping == true)\n return\n else {\n processing.loop()\n return\n }\n\n } else {\n if (looping == false)\n processing.noLoop()\n }\n\n mod.frameCount = processing.frameCount\n if (Sk.globals['draw'])\n Sk.misceval.callsim(Sk.globals['draw'])\n }\n\n var callBacks = ['setup', 'mouseMoved','mouseClicked', 'mouseDragged', 'mouseMoved', 'mouseOut',\n 'mouseOver', 'mousePressed', 'mouseReleased', 'keyPressed', 'keyReleased', 'keyTyped'\n ];\n\n for(var cb in callBacks) {\n if (Sk.globals[callBacks[cb]]) {\n console.log('defining ' + callBacks[cb])\n processing[callBacks[cb]] = new Function(\"Sk.misceval.callsim(Sk.globals['\"+callBacks[cb]+\"']);\")\n }\n }\n }\n\n var canvas = document.getElementById(Sk.canvas)\n $(canvas).show()\n mod.p = new Processing(canvas, sketchProc)\n\n\n });\n\n var mouseClass = function($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'x')\n return mod.processing.mouseX;\n else if (key == 'y')\n return mod.processing.mouseY;\n else if (key == 'px')\n return mod.processing.pmouseX;\n else if (key == 'py')\n return mod.processing.pmouseY;\n else if (key == 'pressed')\n return mod.processing.mousePressed;\n else if (key == 'button')\n return mod.processing.mouseButton\n });\n\n\n }\n\n\n mod.Mouse = Sk.misceval.buildClass(mod, mouseClass, 'Mouse', []);\n\n mod.mouse = Sk.misceval.callsim(mod.Mouse)\n\n var keyboardClass = function($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'key') {\n console.log(mod.processing.key)\n return new Sk.builtin.str(mod.processing.key.toString())\n }\n else if (key == 'keyCode')\n return mod.processing.keyCode\n else if (key == 'keyPressed')\n return new Sk.builtin.str(mod.processing.keyPressed) // todo bool\n });\n\n\n }\n\n mod.Keyboard = Sk.misceval.buildClass(mod,keyboardClass,'Keyboard', [])\n\n mod.keyboard = Sk.misceval.callsim(mod.Keyboard)\n\n\n\n var environmentClass = function($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'frameCount')\n return mod.processing.frameCount\n else if (key == 'frameRate')\n return mod.processing.frameRate\n else if (key == 'height')\n return mod.processing.height\n else if (key == 'width')\n return mod.processing.width\n else if (key == 'online')\n return mod.processing.online\n else if (key == 'focused')\n return mod.processing.focused\n });\n\n\n }\n\n mod.Environment = Sk.misceval.buildClass(mod,environmentClass,'Environment', [])\n\n mod.environment = Sk.misceval.callsim(mod.Environment)\n\n var screenClass = function($gbl, $loc) {\n\n $loc.__init__ = new Sk.builtin.func(function(self) {\n self.pixels = null;\n });\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'height')\n return mod.processing.height\n else if (key == 'width')\n return mod.processing.width\n else if (key == 'pixels')\n if (self.pixels == null) {\n self.pixels = new Sk.builtin.list(mod.processing.pixels.toArray())\n }\n return self.pixels\n });\n\n }\n\n mod.Screen = Sk.misceval.buildClass(mod,screenClass,'Screen', [])\n\n mod.screen = Sk.misceval.callsim(mod.Screen)\n\n mod.loadPixels = new Sk.builtin.func(function() {\n mod.processing.loadPixels()\n console.log(mod.processing.pixels)\n });\n\n\n var colorClass = function($gbl, $loc) {\n /* images are loaded async.. so its best to preload them */\n $loc.__init__ = new Sk.builtin.func(function(self, val1, val2, val3, alpha) {\n if (typeof(val2) !== 'undefined')\n val2 = val2.v\n if (typeof(val3) !== 'undefined')\n val3 = val3.v\n if (typeof(alpha) !== 'undefined')\n alpha = alpha.v\n self.v = mod.processing.color(val1.v, val2, val3, alpha)\n })\n\n }\n\n mod.color = Sk.misceval.buildClass(mod,colorClass,'color', [])\n\n mod.red = new Sk.builtin.func(function(clr) {\n return Sk.builtin.assk$(mod.processing.red(clr.v), Sk.builtin.nmber.int$);\n });\n\n mod.green = new Sk.builtin.func(function(clr) {\n return Sk.builtin.assk$(mod.processing.green(clr.v), Sk.builtin.nmber.int$);\n });\n\n mod.blue = new Sk.builtin.func(function(clr) {\n return Sk.builtin.assk$(mod.processing.blue(clr.v), Sk.builtin.nmber.int$);\n });\n\n // Image class and functions\n //\n var imageClass = function($gbl, $loc) {\n /* images are loaded async.. so its best to preload them */\n $loc.__init__ = new Sk.builtin.func(function(self,im) {\n self.v = im\n self.width = Sk.builtin.assk$(im.width, Sk.builtin.nmber.int$);\n self.height = Sk.builtin.assk$(im.height, Sk.builtin.nmber.int$);\n })\n\n $loc.__getattr__ = new Sk.builtin.func(function(self,key) {\n if (key == 'width') return self.v.width;\n if (key == 'height') return self.v.height;\n });\n\n }\n\n mod.PImage = Sk.misceval.buildClass(mod,imageClass,'PImage', [])\n\n mod.loadImage = new Sk.builtin.func(function(imfile) {\n var i = mod.processing.loadImage(imfile.v);\n imList.push(i);\n return Sk.misceval.callsim(mod.PImage,i);\n });\n\n\n mod.image = new Sk.builtin.func(function(im,x,y) {\n if (im.v.width > 0)\n mod.processing.image(im.v,x.v,y.v,im.v.width,im.v.height)\n });\n\n mod.get = new Sk.builtin.func(function(x,y) {\n var clr = mod.processing.get(x.v,y.v)\n return Sk.misceval.callsim(mod.color,\n Sk.builtin.assk$(mod.processing.red(clr), Sk.builtin.nmber.int$),\n Sk.builtin.assk$(mod.processing.green(clr), Sk.builtin.nmber.int$),\n Sk.builtin.assk$(mod.processing.blue(clr), Sk.builtin.nmber.int$));\n });\n\n mod.set = new Sk.builtin.func(function(x, y, color) {\n mod.processing.set(x.v, y.v, color.v)\n });\n\n// todo -- add a color class for creating color objects.\n\n\n return mod;\n }\n ", "src/lib/webgl/models.js": "// most of this file is from/based on 'tdl'\n\n var $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.} 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.} 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\n class 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\n def inorder(tree):\n if tree != None:\n inorder(tree.getLeftChild())\n print(tree.getRootVal())\n inorder(tree.getRightChild())\n\n def 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\n def 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\n def 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\n def 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/builtin/this.py": "s = \"\"\"Gur Mra bs Clguba, ol Gvz Crgref\n\n Ornhgvshy vf orggre guna htyl.\n Rkcyvpvg vf orggre guna vzcyvpvg.\n Fvzcyr vf orggre guna pbzcyrk.\n Pbzcyrk vf orggre guna pbzcyvpngrq.\n Syng vf orggre guna arfgrq.\n Fcnefr vf orggre guna qrafr.\n Ernqnovyvgl pbhagf.\n Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.\n Nygubhtu cenpgvpnyvgl orngf chevgl.\n Reebef fubhyq arire cnff fvyragyl.\n Hayrff rkcyvpvgyl fvyraprq.\n Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.\n Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.\n Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.\n Abj vf orggre guna arire.\n Nygubhtu arire vf bsgra orggre guna *evtug* abj.\n Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.\n Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.\n Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!\"\"\"\n\n d = {}\n for c in (65, 97):\n for i in range(26):\n d[chr(i+c)] = chr((i+13) % 26 + c)\n\n print \"\".join([d.get(c, c) for c in s])\n ", "src/lib/webgl/primitives.js": "// most of this file is from 'tdl'\n\n var $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.} 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.} 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.} 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/document/__init__.js": "var $builtinmodule = function(name) {\n var mod = {};\n\n mod.getElementById = new Sk.builtin.func(function(id) {\n var result = document.getElementById(id.v);\n if (result) {\n return Sk.misceval.callsim(mod.Element,result);\n }\n return Sk.builtin.none.none$;\n });\n\n mod.createElement = new Sk.builtin.func(function(eName) {\n var r = document.createElement(eName.v);\n if (r) {\n return Sk.misceval.callsim(mod.Element,r);\n }\n });\n\n\n mod.getElementsByTagName = new Sk.builtin.func(function(tag) {\n var r = document.getElementsByTagName(tag.v)\n var reslist = [];\n for (var i = r.length - 1; i >= 0; i--) {\n reslist.push(Sk.misceval.callsim(mod.Element,r[i]))\n }\n return new Sk.builtin.list(reslist)\n });\n\n mod.getElementsByClassName = new Sk.builtin.func(function(cname) {\n var r = document.getElementsByClassName(cname.v);\n var reslist = [];\n for (var i = 0; i < r.length; i++) {\n reslist.push(Sk.misceval.callsim(mod.Element,r[i]));\n };\n return new Sk.builtin.list(reslist);\n });\n\n mod.getElementsByName = new Sk.builtin.func(function(cname) {\n var r = document.getElementsByName(cname.v);\n var reslist = [];\n for (var i = 0; i < r.length; i++) {\n reslist.push(Sk.misceval.callsim(mod.Element,r[i]));\n };\n return new Sk.builtin.list(reslist);\n });\n\n mod.currentDiv = new Sk.builtin.func(function() {\n if (Sk.divid !== undefined) {\n return new Sk.builtin.str(Sk.divid)\n }\n else {\n throw new Sk.builtin.AttributeError(\"There is no value set for divid\");\n }\n })\n var elementClass = function($gbl, $loc) {\n /*\n Notes: self['$d'] is the dictionary used by the GenericGetAttr mechanism for an object.\n for various reasons if you create a class in Javascript and have self.xxxx instance\n variables, you cannot say instance.xxx and get the value of the instance variable unless\n it is stored in the self['$d'] object. This seems like a duplication of storage to me\n but that is how it works right now (5/2013)\n\n Writing your own __getattr__ is also an option but this gets very tricky when an attr is\n a method...\n */\n $loc.__init__ = new Sk.builtin.func(function(self,elem) {\n self.v = elem\n self.innerHTML = elem.innerHTML\n self.innerText = elem.innerText\n if (elem.value !== undefined) {\n self.value = elem.value\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('value'), new Sk.builtin.str(self.value))\n }\n\n if (elem.checked !== undefined) {\n self.checked = elem.checked\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('checked'), new Sk.builtin.str(self.checked))\n }\n\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerHTML'), new Sk.builtin.str(self.innerHTML))\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerText'), new Sk.builtin.str(self.innerText))\n\n })\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n $loc.__setattr__ = new Sk.builtin.func(function(self,key,value) {\n if (key === 'innerHTML') {\n self.innerHTML = value\n self.v.innerHTML = value.v\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerHTML'), value)\n }\n if (key === 'innerText') {\n self.innerText = value\n self.v.innerText = value.v\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerText'), value)\n }\n });\n\n\n $loc.appendChild = new Sk.builtin.func(function(self,ch) {\n self.v.appendChild(ch.v);\n });\n\n $loc.removeChild = new Sk.builtin.func(function(self,node) {\n self.v.removeChild(node.v)\n })\n\n // getCSS\n\n $loc.getCSS = new Sk.builtin.func(function(self,key) {\n return new Sk.builtin.str(self.v.style[key.v]);\n });\n\n\n $loc.setCSS = new Sk.builtin.func(function(self,attr,value) {\n self.v.style[attr.v] = value.v\n\n })\n\n $loc.getAttribute = new Sk.builtin.func(function(self,key) {\n var res = self.v.getAttribute(key.v)\n if (res) {\n return new Sk.builtin.str(res)\n } else {\n return Sk.builtin.none.none$;\n }\n });\n\n $loc.setAttribute = new Sk.builtin.func(function(self,attr,value) {\n self.v.setAttribute(attr.v,value.v)\n });\n\n $loc.getProperty = new Sk.builtin.func(function(self,key) {\n var res = self.v[key.v]\n if (res) {\n return new Sk.builtin.str(res)\n } else {\n return Sk.builtin.none.none$;\n }\n });\n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n console.log(self.v.tagName);\n return new Sk.builtin.str(self.v.tagName)\n })\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n return new Sk.builtin.str('[DOM Element]')\n })\n\n\n };\n\n mod.Element = Sk.misceval.buildClass(mod,elementClass,'Element', []);\n\n return mod;\n\n } ", "src/lib/webgl/matrix4.js": "// more from 'tdl'\n var $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/re/__init__.js": "var $builtinmodule = function(name)\n {\n var mod = {};\n\n // Constants (mostly unsupported)\n mod.I = 2;\n mod.IGNORECASE = 2;\n // mod.L = 4;\n // mod.LOCALE = 4;\n mod.M = 8;\n mod.MULTILINE = 8;\n // mod.S = 16;\n // mod.DOTALL = 16;\n // mod.U = 32;\n // mod.UNICODE = 32;\n // mod.X = 64;\n // mod.VERBOSE = 64;\n\n var validGroups = [\"(?:\", \"(?=\", \"(?!\"];\n\n var convert = function(pattern) {\n var newpattern;\n var match;\n var i;\n\n // Look for disallowed constructs\n match = pattern.match(/\\(\\?./g);\n if (match) {\n for (i=0; i= maxsplit)) {\n break;\n };\n };\n result.push(new Sk.builtin.str(str.substring(index)));\n\n return new Sk.builtin.list(result);\n });\n\n mod.findall = Sk.nativejs.func(function findall(pattern, string, flags) {\n Sk.builtin.pyCheckArgs(\"findall\", arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n };\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n };\n if (flags === undefined) {\n flags = 0;\n };\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n };\n\n var pat = Sk.ffi.unwrapo(pattern);\n var str = Sk.ffi.unwrapo(string);\n\n // Convert pat from Python to Javascript regex syntax\n pat = convert(pat);\n //print(\"Pat: \" + pat);\n //print(\"Str: \" + str);\n\n var jsflags = getFlags(flags);\n //print(\"Flags: \", jsflags);\n\n var regex = new RegExp(pat, jsflags);\n\n if (pat.match(/\\$/)) {\n \t var newline_at_end = new RegExp(/\\n$/);\n\t if (str.match(newline_at_end)) {\n \t str = str.slice(0,-1);\n\t }\n }\n\n var result = [];\n var match;\n while ((match = regex.exec(str)) != null) {\n //print(\"Matched '\" + match[0] + \"' at position \" + match.index +\n // \"; next search at \" + regex.lastIndex);\n // print(\"match: \" + JSON.stringify(match));\n if (match.length < 2) {\n result.push(new Sk.builtin.str(match[0]));\n } else if (match.length == 2) {\n result.push(new Sk.builtin.str(match[1]));\n } else {\n var groups = [];\n for (var i=1; i= 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 \tres = res.replace(/([^\\\\]){,(?![^\\[]*\\])/g, '$1{0,');\n var re = eval(res);\n\tvar patt = new RegExp('\\n$');\n\tif (string.v.match(patt))\n\t var matches = string.v.slice(0,-1).match(re);\n\telse\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 \tSk.builtin.pyCheckArgs('search', arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n };\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n };\n\tif (flags === undefined) {\n flags = 0;\n };\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n };\n var res = \"/\"+pattern.v.replace(/\\//g,\"\\\\/\")+\"/\";\n lst = mod._findre(res,string);\n if ( lst.v.length < 1 ) return Sk.builtin.none.none$;\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 \tSk.builtin.pyCheckArgs('match', arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n };\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n };\n\tif (flags === undefined) {\n flags = 0;\n };\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n };\n var res = \"/^\"+pattern.v.replace(/\\//g,\"\\\\/\")+\"/\";\n lst = mod._findre(res,string);\n if ( lst.v.length < 1 ) return Sk.builtin.none.none$;\n var mob = Sk.misceval.callsim(mod.MatchObject, lst, pattern, string);\n return mob;\n });\n\n return mod;\n }\n ", "src/lib/unittest/gui.py": "import document\n from unittest import TestCase\n\n class TestCaseGui(TestCase):\n \tdef __init__(self):\n \t\tTestCase.__init__(self)\n\n\t\tself.divid = document.currentDiv()\n\t\tself.mydiv = document.getElementById(self.divid)\n\t\tres = document.getElementById(self.divid+'_unit_results')\n\t\tif res:\n \t\t\tself.resdiv = res\n\t\t\tres.innerHTML = ''\n\t\telse:\n \t\t\tself.resdiv = document.createElement('div')\n\t\t\tself.resdiv.setAttribute('id',self.divid+'_unit_results')\n\t\t\tself.resdiv.setAttribute('class','unittest-results')\n\t\tself.mydiv.appendChild(self.resdiv)\n\n\n\tdef main(self):\n \t\tl = document.createElement('ul')\n\t\tself.resdiv.appendChild(l)\n\t\tself.resList = l\n\n\t\tfor func in self.tlist:\n \t\t\ttry:\n \t\t\t\tself.setup()\n\t\t\t\tfunc()\n\t\t\t\tself.tearDown()\n\t\t\texcept:\n \t\t\t\tself.appendResult('Error')\n\t\t\t\tself.numFailed += 1\n\t\tself.showSummary()\n\n\tdef appendResult(self,res,actual,expected,feedback):\n \t\tif res == 'Error':\n \t\t\tmsg = 'Error'\n\t\telif res:\n \t\t\tmsg = 'Pass'\n\t\t\tself.numPassed += 1\n\t\telse:\n \t\t\tmsg = 'Fail: expected %s %s ' % (str(actual),str(expected)) + feedback\n\t\t\tself.numFailed += 1\n\n\t\tpTag = document.createElement('li')\n\t\tpTag.innerHTML = msg\n\t\tself.resList.appendChild(pTag)\n\n\n\n\tdef showSummary(self):\n \t\tpct = self.numPassed / (self.numPassed+self.numFailed) * 100\n\t\tpTag = document.createElement('p')\n\t\tpTag.innerHTML = \"You passed: \" + str(pct) + \"% of the tests\"\n\t\tself.resdiv.appendChild(pTag)\n\t\tif pct < 90:\n \t\t\tself.resdiv.setCSS('background-color','#de8e96')\n\t\telse:\n \t\t\tself.resdiv.setCSS('background-color','#83d382')\n ", "src/lib/urllib/__init__.js": "var $builtinmodule = function(name)\n {\n var urllib = {};\n\n return urllib;\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 (banksean@gmail.com)\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\n var 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 */\n MersenneTwister.prototype.init_genrand = function(s) {\n this.mt[0] = s >>> 0;\n for (this.mti=1; this.mti>> 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 */\n MersenneTwister.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 */\n MersenneTwister.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>> 1) ^ mag01[y & 0x1];\n }\n for (;kk>> 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 */\n MersenneTwister.prototype.genrand_int31 = function() {\n return (this.genrand_int32()>>>1);\n }\n\n /* generates a random number on [0,1]-real-interval */\n MersenneTwister.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 */\n MersenneTwister.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 */\n MersenneTwister.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*/\n MersenneTwister.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\n\n\n var $builtinmodule = function(name)\n {\n\n var mod = {};\n\n var myGenerator = new MersenneTwister();\n\n mod.seed = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"seed\", arguments, 0, 1);\n\tx = Sk.builtin.asnum$(x);\n\n if (arguments.length > 0)\n myGenerator = new MersenneTwister(x);\n else\n myGenerator = new MersenneTwister();\n\n\treturn Sk.builtin.none.none$;\n });\n\n mod.random = new Sk.builtin.func(function() {\n Sk.builtin.pyCheckArgs(\"random\", arguments, 0, 0);\n\n\treturn new Sk.builtin.nmber(myGenerator.genrand_res53(), Sk.builtin.nmber.float$);\n });\n\n var toInt = function(num) {\n return num | 0;\n };\n\n var randrange = function(start, stop, step) {\n // Ported from CPython 2.7\n var width, n, ret;\n\n if (!Sk.builtin.checkInt(start)) {\n throw new Sk.builtin.ValueError(\"non-integer first argument for randrange()\");\n };\n\n if (stop === undefined) {\n // Random in [0, start)\n ret = toInt(myGenerator.genrand_res53() * start);\n\t return new Sk.builtin.nmber(ret, Sk.builtin.nmber.int$);\n };\n\n if (!Sk.builtin.checkInt(stop)) {\n throw new Sk.builtin.ValueError(\"non-integer stop for randrange()\");\n };\n\n if (step === undefined) {\n step = 1;\n };\n\n width = stop - start;\n\n if ((step == 1) && (width > 0)) {\n // Random in [start, stop), must use toInt on product for correct results with negative ranges\n ret = start + toInt(myGenerator.genrand_res53() * width);\n\t return new Sk.builtin.nmber(ret, Sk.builtin.nmber.int$);\n };\n\n if (step == 1) {\n throw new Sk.builtin.ValueError(\"empty range for randrange() (\" + start + \", \" + stop + \", \" + width + \")\");\n };\n\n if (!Sk.builtin.checkInt(step)) {\n throw new Sk.builtin.ValueError(\"non-integer step for randrange()\");\n };\n\n if (step > 0) {\n n = toInt((width + step - 1) / step);\n } else if (step < 0) {\n n = toInt((width + step + 1) / step);\n } else {\n throw new Sk.builtin.ValueError(\"zero step for randrange()\");\n };\n\n if (n <= 0) {\n throw new Sk.builtin.ValueError(\"empty range for randrange()\");\n };\n\n // Random in range(start, stop, step)\n ret = start + (step * toInt(myGenerator.genrand_res53() * n));\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.int$);\n };\n\n mod.randint = new Sk.builtin.func(function(a, b) {\n Sk.builtin.pyCheckArgs(\"randint\", arguments, 2, 2);\n\n\ta = Sk.builtin.asnum$(a);\n\tb = Sk.builtin.asnum$(b);\n return randrange(a, b+1);\n });\n\n mod.randrange = new Sk.builtin.func(function(start, stop, step) {\n Sk.builtin.pyCheckArgs(\"randrange\", arguments, 1, 3);\n\n\tstart = Sk.builtin.asnum$(start);\n\tstop = Sk.builtin.asnum$(stop);\n\tstep = Sk.builtin.asnum$(step);\n return randrange(start, stop, step);\n });\n\n mod.choice = new Sk.builtin.func(function(seq) {\n Sk.builtin.pyCheckArgs(\"choice\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"seq\", \"sequence\", Sk.builtin.checkSequence(seq));\n\n if (seq.sq$length !== undefined) {\n var r = toInt(myGenerator.genrand_res53() * seq.sq$length());\n return seq.mp$subscript(r);\n } else {\n throw new Sk.builtin.TypeError(\"object has no length\");\n }\n });\n\n mod.shuffle = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"shuffle\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"sequence\", Sk.builtin.checkSequence(x));\n\n if (x.sq$length !== undefined) {\n if (x.mp$ass_subscript !== undefined) {\n for (var i = x.sq$length() - 1; i > 0; i -= 1) {\n var r = toInt(myGenerator.genrand_res53() * (i + 1));\n var tmp = x.mp$subscript(r);\n x.mp$ass_subscript(r, x.mp$subscript(i));\n x.mp$ass_subscript(i, tmp);\n };\n } else {\n throw new Sk.builtin.TypeError(\"object is immutable\");\n };\n } else {\n throw new Sk.builtin.TypeError(\"object has no length\");\n };\n\n\treturn Sk.builtin.none.none$;\n });\n\n return mod;\n }\n ", "src/lib/webgl/__init__.js": "var $builtinmodule = function(name)\n {\n var mod = {};\n\n var makeFailHTML = function(msg) {\n return '' +\n '' +\n '
' +\n '
' +\n '
' + msg + '
' +\n '
' +\n '
';\n };\n\n var GET_A_WEBGL_BROWSER = '' +\n 'This page requires a browser that supports WebGL.
' +\n 'Click here to upgrade your browser.';\n\n var NEED_HARDWARE = '' +\n \"It doesn't appear your computer can support WebGL.
\" +\n 'Click here for more information.';\n\n var create3DContext = function(canvas) {\n var names = [\"webgl\", \"experimental-webgl\", \"webkit-3d\", \"moz-webgl\"];\n var gl = null;\n for (var ii = 0; ii < names.length; ++ii) {\n try {\n gl = canvas.getContext(names[ii]);\n }\n catch(e) {\n }\n if (gl) {\n break;\n }\n }\n if (gl) {\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 gl;\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(GET_A_WEBGL_BROWSER);\n return;\n }\n\n var gl = create3DContext(opt_canvas);\n if (!gl) {\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 }\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(NEED_HARDWARE);\n }\n else {\n container.innerHTML = makeFailHTML(GET_A_WEBGL_BROWSER);\n }\n }\n return gl;\n };\n\n /**\n * The Context encapsulates the underlying WebGL native JavaScript API.\n */\n mod.Context = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(\n function(self, canvasid) {\n var canvas = document.getElementById(canvasid.v);\n var gl = setupWebGL(canvasid.v, canvas)\n if (!gl) {\n throw new Error(\"Your browser does not appear to support WebGL.\");\n }\n\n self.gl = gl;\n\n // Copy symbolic constants and functions from native WebGL, encapsulating where necessary.\n for (var k in gl.__proto__) {\n if (typeof gl.__proto__[k] === 'number') {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), gl.__proto__[k]);\n }\n else if (typeof gl.__proto__[k] === \"function\") {\n switch(k) {\n case 'bufferData': {\n }\n break;\n case 'clearColor': {\n }\n break;\n case 'drawArrays': {\n }\n break;\n case 'getAttribLocation': {\n }\n break;\n case 'getUniformLocation': {\n }\n break;\n case 'shaderSource': {\n }\n break;\n case 'uniformMatrix4fv': {\n }\n break;\n case 'vertexAttribPointer': {\n }\n break;\n case 'viewport': {\n }\n break;\n default: {\n (function(key) {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), new Sk.builtin.func(function() {\n var f = gl.__proto__[key];\n return f.apply(gl, arguments);\n }));\n }(k));\n }\n }\n }\n }\n\n gl.clearColor(100.0/255.0, 149.0/255.0, 237.0/255.0, 1.0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n }\n );\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n $loc.bufferData = new Sk.builtin.func(\n function(self, target, data, usage) {\n self.gl.bufferData(target, data.v, usage);\n }\n );\n\n $loc.clearColor = new Sk.builtin.func(\n function(self, red, green, blue, alpha) {\n self.gl.clearColor(Sk.builtin.asnum$(red), Sk.builtin.asnum$(green), Sk.builtin.asnum$(blue), Sk.builtin.asnum$(alpha));\n }\n );\n\n $loc.getAttribLocation = new Sk.builtin.func(\n function(self, program, name) {\n return self.gl.getAttribLocation(program, name.v);\n }\n );\n\n $loc.getUniformLocation = new Sk.builtin.func(\n function(self, program, name) {\n return self.gl.getUniformLocation(program, name.v);\n }\n );\n\n $loc.shaderSource = new Sk.builtin.func(\n function(self, shader, src) {\n self.gl.shaderSource(shader, src.v);\n }\n );\n\n $loc.drawArrays = new Sk.builtin.func(\n function(self, mode, first, count) {\n self.gl.drawArrays(Sk.builtin.asnum$(mode), Sk.builtin.asnum$(first), Sk.builtin.asnum$(count));\n }\n );\n\n $loc.vertexAttribPointer = new Sk.builtin.func(\n function(self, index, size, type, normalized, stride, dunno) {\n self.gl.vertexAttribPointer(index, Sk.builtin.asnum$(size), Sk.builtin.asnum$(type), normalized, Sk.builtin.asnum$(stride), Sk.builtin.asnum$(dunno));\n }\n );\n\n $loc.viewport = new Sk.builtin.func(\n function(self, x, y, width, height) {\n self.gl.viewport(Sk.builtin.asnum$(x), Sk.builtin.asnum$(y), Sk.builtin.asnum$(width), Sk.builtin.asnum$(height));\n }\n );\n\n $loc.uniformMatrix4fv = new Sk.builtin.func(\n function(self, location, transpose, values) {\n// console.log(\"location \" + (typeof location));\n// console.log(\"transpose \" + (typeof transpose));\n// console.log(\"values.v \" + (typeof values.v));\n self.gl.uniformMatrix4fv(Sk.builtin.asnum$(location), transpose, values.v);\n }\n );\n\n $loc.setDrawFunc = new Sk.builtin.func(function(self, func) {\n var startTime = (new Date()).getTime();\n var intervalId = setInterval(\n function() {\n Sk.misceval.callsim(func, self, (new Date()).getTime() - startTime);\n }, 1000.0 / 60.0); // 60 fps\n });\n\n }, 'Context', []);\n\n mod.Float32Array = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, data) {\n if (typeof data === \"number\") {\n self.v = new Float32Array(data);\n }\n else {\n self.v = new Float32Array(Sk.ffi.remapToJs(data));\n }\n });\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n var copy = [];\n for (var i = 0; i < self.v.length; ++i) {\n copy.push(self.v[i]);\n }\n return new Sk.builtin.str(\"[\" + copy.join(', ') + \"]\");\n });\n }, 'Float32Array', []);\n\n /**\n * A 4x4 (mutable) matrix suitable for OpenGL.\n *\n * Mutability is chosen for performance.\n * The inderlying implementation is Float32Array.\n * The indexing of the elements is\n * 0 4 8 12\n * 1 5 9 13\n * 2 6 10 14\n * 3 7 11 15\n */\n mod.Matrix4x4 = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, data) {\n self.v = new Float32Array(Sk.ffi.remapToJs(data));\n });\n\n $loc.identity = new Sk.builtin.func(\n function(self) {\n\n var m = self.v;\n\n m[0] = 1;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = 1;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = 1;\n m[11] = 0;\n\n m[12] = 0;\n m[13] = 0;\n m[14] = 0;\n m[15] = 1;\n }\n );\n\n $loc.perspective = new Sk.builtin.func(\n function(self, fov, aspect, near, far) {\n\n var t = Math.tan(Math.PI * 0.5 - 0.5 * (Sk.builtin.asnum$(fov) * Math.PI / 180));\n var a = Sk.builtin.asnum$(aspect)\n var n = Sk.builtin.asnum$(near)\n var f = Sk.builtin.asnum$(far)\n var k = 1.0 / (n - f);\n\n var m = self.v;\n\n m[0] = t / a;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = t;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = (n + f) * k;\n m[11] = -1;\n\n m[12] = 0;\n m[13] = 0;\n m[14] = n * f * k * 2;\n m[15] = 0;\n }\n );\n\n $loc.translate = new Sk.builtin.func(\n function(self, translation) {\n\n var m = self.v;\n var t = Sk.ffi.remapToJs(translation);\n\n m[0] = 1;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = 1;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = 1;\n m[11] = 0;\n\n m[12] = t[0];\n m[13] = t[1];\n m[14] = t[2];\n m[15] = 1;\n }\n );\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n var copy = [];\n for (var i = 0; i < self.v.length; ++i) {\n copy.push(self.v[i]);\n }\n return new Sk.builtin.str(\"[\" + copy.join(', ') + \"]\");\n });\n }, 'Matrix4x4', []);\n\n return mod;\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//\tRNL\tadded\n mod.fabs = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"fabs\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.abs(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.asin = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"asin\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.asin(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.acos = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"acos\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.acos(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.atan = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"atan\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.atan(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.atan2 = new Sk.builtin.func(function(y, x) {\n Sk.builtin.pyCheckArgs(\"atan2\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.atan2(Sk.builtin.asnum$(y), Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.sin = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"sin\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.sin(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.cos = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"cos\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.cos(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.tan = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"tan\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\treturn new Sk.builtin.nmber(Math.tan(Sk.builtin.asnum$(rad)), Sk.builtin.nmber.float$);\n });\n\n mod.asinh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"asinh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar L = x + Math.sqrt(x*x+1);\n\n\treturn new Sk.builtin.nmber(Math.log(L), Sk.builtin.nmber.float$);\n });\n\n mod.acosh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"acosh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar L = x + Math.sqrt(x*x-1);\n\n\treturn new Sk.builtin.nmber(Math.log(L), Sk.builtin.nmber.float$);\n });\n\n mod.atanh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"atanh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar L = (1+x)/(1-x);\n\n\treturn new Sk.builtin.nmber(Math.log(L)/2, Sk.builtin.nmber.float$);\n });\n\n mod.sinh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"sinh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar e = Math.E;\n\tvar p = Math.pow(e, x);\n\tvar n = 1/p;\n\tvar result = (p-n)/2;\n\n\treturn new Sk.builtin.nmber(result, Sk.builtin.nmber.float$);\n });\n\n mod.cosh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"cosh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar e = Math.E;\n\tvar p = Math.pow(e, x);\n\tvar n = 1/p;\n\tvar result = (p+n)/2;\n\n\treturn new Sk.builtin.nmber(result, Sk.builtin.nmber.float$);\n });\n\n mod.tanh = new Sk.builtin.func(function(x) {\n \tSk.builtin.pyCheckArgs(\"tanh\", arguments, 1, 1);\n\tSk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\tx = Sk.builtin.asnum$(x);\n\n\tvar e = Math.E;\n\tvar p = Math.pow(e, x);\n\tvar n = 1/p;\n\tvar result = ((p-n)/2)/((p+n)/2);\n\n\treturn new Sk.builtin.nmber(result, Sk.builtin.nmber.float$);\n });\n\n mod.ceil = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"ceil\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.ceil(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.floor = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"floor\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.floor(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.sqrt = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"sqrt\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.sqrt(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.trunc = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"trunc\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.nmber(Sk.builtin.asnum$(x)|0, Sk.builtin.nmber.int$);\n });\n\n mod.log = new Sk.builtin.func(function(x, base) {\n Sk.builtin.pyCheckArgs(\"log\", arguments, 1, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n if (base === undefined) {\n \t return new Sk.builtin.nmber(Math.log(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n } else {\n Sk.builtin.pyCheckType(\"base\", \"number\", Sk.builtin.checkNumber(base));\n var ret = Math.log(Sk.builtin.asnum$(x)) / Math.log(Sk.builtin.asnum$(base));\n\t return new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n }\n });\n\n mod.log10 = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"log10\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n var ret = Math.log(Sk.builtin.asnum$(x)) / Math.log(10);\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n });\n\n mod.exp = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"exp\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n\treturn new Sk.builtin.nmber(Math.exp(Sk.builtin.asnum$(x)), Sk.builtin.nmber.float$);\n });\n\n mod.pow = new Sk.builtin.func(function(x,y) {\n Sk.builtin.pyCheckArgs(\"pow\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n\n\treturn new Sk.builtin.nmber(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 Sk.builtin.pyCheckArgs(\"radians\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"deg\", \"number\", Sk.builtin.checkNumber(deg));\n\n\tvar ret = Math.PI / 180.0 * Sk.builtin.asnum$(deg);\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n });\n\n mod.degrees = new Sk.builtin.func(function(rad) {\n Sk.builtin.pyCheckArgs(\"degrees\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n\tvar ret = 180.0 / Math.PI * Sk.builtin.asnum$(rad);\n\treturn new Sk.builtin.nmber(ret, Sk.builtin.nmber.float$);\n });\n\n mod.hypot = new Sk.builtin.func(function(x, y) {\n \tSk.builtin.pyCheckArgs(\"hypot\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\tSk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n\n\t\tx = Sk.builtin.asnum$(x);\n\t\ty = Sk.builtin.asnum$(y);\n\treturn new Sk.builtin.nmber(Math.sqrt((x*x)+(y*y)), Sk.builtin.nmber.float$);\n });\n\n\tmod.factorial = new Sk.builtin.func(function(x) {\n\t Sk.builtin.pyCheckArgs(\"factorial\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\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 new Sk.builtin.nmber(r, Sk.builtin.nmber.int$);\n\t});\n\n return mod;\n}"}} diff --git a/game/templates/game/level_selection.html b/game/templates/game/level_selection.html index e455f5905..431f3e0a3 100644 --- a/game/templates/game/level_selection.html +++ b/game/templates/game/level_selection.html @@ -173,18 +173,8 @@

Python levels

{% for episode in pythonEpisodes %} {% if episode.difficulty == "loops" %} -
-
+
+