def install( self ): # Graphical representation of scoreboard are four labels and a separator line self.playerLabels = [ __new__( fabric.Text( 'Player {}'.format(name), { 'fill': 'white', 'fontFamily': 'arial', 'fontSize': '{}'.format(self.game.canvas.width / 30), 'left': self.game.orthoX(position * orthoWidth), 'top': self.game.orthoY(fieldHeight // 2 + self.nameShift) })) for name, position in (('AZ keys:', -7 / 16), ('KM keys:', 1 / 16)) ] self.hintLabel = __new__( fabric.Text( '[spacebar] starts game, [enter] resets score', { 'fill': 'white', 'fontFamily': 'arial', 'fontSize': '{}'.format(self.game.canvas.width / 70), 'left': self.game.orthoX(-7 / 16 * orthoWidth), 'top': self.game.orthoY(fieldHeight // 2 + self.hintShift) })) self.image = __new__( fabric.Line([ self.game.orthoX(-orthoWidth // 2), self.game.orthoY(fieldHeight // 2), self.game.orthoX(orthoWidth // 2), self.game.orthoY(fieldHeight // 2) ], {'stroke': 'white'}))
def __init__(self): self.keyCode = None self.pause = True self.canvasFrame = document.getElementById('canvas_frame') self.canvas = __new__( fabric.Canvas( 'canvas', { 'backgroundColor': 'black', 'originX': 'center', 'originY': 'center' })) self.canvas.onWindowDraw = self.draw # Install draw callback, will be called asynch self.canvas.lineWidth = 2 self.canvas.clear() set_size = 6 self.attributes = [] squares = [Square(self, index) for index in range(set_size)] self.squares = [Square.set(square) for square in squares] window.setInterval(self.update, 10) # Install update callback, time in ms window.setInterval(self.draw, 20) # Install draw callback, time in ms window.addEventListener('keydown', self.keydown) window.addEventListener('keyup', self.keyup) self.buttons = [] for key in ('F', 'J', 'space'): button = document.getElementById(key) button.addEventListener( 'mousedown', (lambda aKey: lambda: self.mouseOrTouch(aKey, True) )(key)) # Returns inner lambda button.addEventListener( 'touchstart', (lambda aKey: lambda: self.mouseOrTouch(aKey, True))(key)) button.addEventListener( 'mouseup', (lambda aKey: lambda: self.mouseOrTouch(aKey, False))(key)) button.addEventListener( 'touchend', (lambda aKey: lambda: self.mouseOrTouch(aKey, False))(key)) button.style.cursor = 'pointer' button.style.userSelect = 'none' self.buttons.append(button) self.time = +__new__(Date)
def startup(self): print("let's go!") self.resizing = 0 self.action = None self.worker = __new__(Worker("__javascript__/sample_worker.js")) self.worker.onmessage = self.on_message self.selector = document.getElementById("selector") self.container = document.getElementById("container") self.canvas = document.getElementById("mandelbrot") self.canvas.width = self.container.offsetWidth self.canvas.height = self.container.offsetHeight self.canvas.style.width = "{}px".format(self.canvas.width) self.canvas.style.height = "{}px".format(self.canvas.height) self.ctx = self.canvas.getContext("2d") self.reset() document.getElementById("container").onmousedown = self.on_mousedown document.getElementById("container").onmousemove = self.on_mousemove document.getElementById("container").onmouseup = self.on_mouseup document.getElementById("container").ontouchstart = self.on_touchstart document.getElementById("container").ontouchmove = self.on_touchmove document.getElementById("container").ontouchend = self.on_touchend
def __init__ (self): self.pause = True # Start experiment in paused state self.keyCode = None self.textFrame = document.getElementById ('text_frame') self.canvasFrame = document.getElementById ('canvas_frame') self.buttonsFrame = document.getElementById ('buttons_frame') self.canvas = __new__ (fabric.Canvas ('canvas', {'backgroundColor': 'grey', 'originX': 'center', 'originY': 'center'})) self.canvas.onWindowDraw = self.draw # Install draw callback, will be called asynch self.canvas.lineWidth = 2 self.canvas.clear () self.set_size = 6 self.attributes = [] # All attributes will insert themselves here self.stimuli = [Stimuli(self, index) for index in range (self.set_size)] # Pass game as parameter self self.fixation_point = Fixation(self) window.setInterval (self.update, 1) # Install update callback, time in ms window.setInterval (self.draw, 20) # Install draw callback, time in ms window.addEventListener ('keydown', self.keydown) window.addEventListener ('keyup', self.keyup) self.buttons = [] for key in ('F', 'J','space'): button = document.getElementById (key) button.addEventListener ('mousedown', (lambda aKey: lambda: self.mouseOrTouch (aKey, True)) (key)) # Returns inner lambda button.addEventListener ('touchstart', (lambda aKey: lambda: self.mouseOrTouch (aKey, True)) (key)) button.addEventListener ('mouseup', (lambda aKey: lambda: self.mouseOrTouch (aKey, False)) (key)) button.addEventListener ('touchend', (lambda aKey: lambda: self.mouseOrTouch (aKey, False)) (key)) button.style.cursor = 'pointer' button.style.userSelect = 'none' self.buttons.append (button) self.time = + __new__ (Date) self.start_exp_timer = self.time self.target_presented = bool self.isi_presented = bool self.all_presented = bool self.trial_set = bool self.target_color = [] window.onresize = self.resize self.resize ()
def __init__ (self): self.serviceIndex = 1 if Math.random () > 0.5 else 0 # Index of player that has initial service self.pause = True # Start game in paused state self.keyCode = None self.textFrame = document.getElementById ('text_frame') self.canvasFrame = document.getElementById ('canvas_frame') self.buttonsFrame = document.getElementById ('buttons_frame') self.canvas = __new__ (fabric.Canvas ('canvas', {'backgroundColor': 'black', 'originX': 'center', 'originY': 'center'})) self.canvas.onWindowDraw = self.draw # Install draw callback, will be called asynch self.canvas.lineWidth = 2 self.canvas.clear () self.attributes = [] # All attributes will insert themselves here self.paddles = [Paddle (self, index) for index in range (2)] # Pass game as parameter self self.ball = Ball (self) self.scoreboard = Scoreboard (self) window.setInterval (self.update, 10) # Install update callback, time in ms window.setInterval (self.draw, 20) # Install draw callback, time in ms window.addEventListener ('keydown', self.keydown) window.addEventListener ('keyup', self.keyup) self.buttons = [] for key in ('A', 'Z', 'K', 'M', 'space', 'enter'): button = document.getElementById (key) button.addEventListener ('mousedown', (lambda aKey: lambda: self.mouseOrTouch (aKey, True)) (key)) # Returns inner lambda button.addEventListener ('touchstart', (lambda aKey: lambda: self.mouseOrTouch (aKey, True)) (key)) button.addEventListener ('mouseup', (lambda aKey: lambda: self.mouseOrTouch (aKey, False)) (key)) button.addEventListener ('touchend', (lambda aKey: lambda: self.mouseOrTouch (aKey, False)) (key)) button.style.cursor = 'pointer' button.style.userSelect = 'none' self.buttons.append (button) self.time = + __new__ (Date) window.onresize = self.resize self.resize ()
def OLDgetFormData(self) -> dict: """Return a dict containing the current values of the form elements. This method reaches into the nether regions of javascript and uses a FormData element to retrieve the keys and values of any input elements in the form. See here for the specification of FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects NOTE: this should work, and it did use to; However now it returns an empty string. We work around this by extracting the data from the form ourselves. """ fd = __new__(FormData(self.form_el._el)) return dict([tt for tt in fd.entries()])
def commit(self): # Committing labels is adapting their texts self.scoreLabels = [ __new__( fabric.Text( '{}'.format(score), { 'fill': 'white', 'fontFamily': 'arial', 'fontSize': '{}'.format(self.game.canvas.width / 30), 'left': self.game.orthoX(position * orthoWidth), 'top': self.game.orthoY(fieldHeight // 2 + self.nameShift) })) for score, position in zip(self.scores, (-2 / 16, 6 / 16)) ]
def __init__(self, name="webclient", session="", namespace=""): self.clients.append(self) self.session_id = utils.storage.get("session_id") if not self.session_id: self.session_id = utils.random_string(10) utils.storage.set("session_id", self.session_id) self.socket_url = location.protocol + '//' + location.hostname + ':' + location.port + namespace self.socket = io(self.socket_url, {'transports': ['websocket']}) self.socket.on("command", self.on_command) self.socket.on("server_call", self.on_server_call) self.socket.on("exception", self.on_error) self.socket.on("connect", self.on_connect) self.socket.on("disconnect", self.on_disconnect) self.commands = { 'connect': 1, 'reconnect': 2, 'disconnect': 3, 'status': 4, 'handshake': 5, 'rehandshake': 6 } self.command_callbacks = {} self.namespace = namespace self.session = session self.name = name self._reconnecting = False self._connection_status = True self._disconnected_once = False self._initial_socket_connection = False self._socket_connection = False self._response_cb = {} self._first_connect = True self._msg_queue = [] self._last_msg = None self._cmd_status = {} self._cmd_status_c = 0 self._retries = None self._poll_interval = 5 self._poll_timeout = 1000 * 60 * 120 self._last_retry = __new__(Date()).getTime() self._prev_retry_interval = 0 self.polling = False if not Client.polling: utils.poll_func(self.connection, self._poll_timeout, self._poll_interval * 1000) self.polling = True Client.polling = True
def install(self): # The sprite holds an image that fabric can display red = 0 green = 255 blue = 0 color = (f'rbg({red},{green},{blue})') self.image = __new__( fabric.Rect({ 'width': self.game.scaleX(self.width), 'height': self.game.scaleY(self.height), 'originX': 'center', 'originY': 'center', 'fill': 'white' }))
def update(self): # Note that update and draw are not synchronized oldTime = self.time self.time = +__new__(Date) self.deltaT = (self.time - oldTime) / 1000. if self.pause: # If in paused state if self.keyCode == space: # If spacebar hit self.pause = False # Start playing else: # Else, so if in active state for attribute in self.attributes: # Compute predicted values attribute.predict() for attribute in self.attributes: # Correct values for bouncing and scoring attribute.interact() for attribute in self.attributes: # Commit them to pyglet for display attribute.commit()
def __init__(self, url: str, protocol_lst: list) -> None: """Initialise a raw web socket. The url is the name of the server to connect to. The protocol_lst is either a string or a list of strings. An empty list may be provided. """ BaseRawWebSocket.__init__(self) self._ws = __new__(WebSocket(url, 'json')) # self._ws = __new__(WebSocket(url)) # self._ws = __new__(WebSocket(url, protocol_lst)) __pragma__( 'js', '{}', 'self._ws.onopen = function(event){self._isopen = true; self.on_open_cb(event);}' ) __pragma__( 'js', '{}', 'self._ws.onerror = function(event){self.on_error_cb(event);}') __pragma__( 'js', '{}', 'self._ws.onmessage = function(event){self.on_message_cb(event);}') __pragma__( 'js', '{}', 'self._ws.onclose = function(event){self.on_close_cb(event);}')
def __init__(*args): return __new__(cls(*args))
def run(autoTester): autoTester.check( 'Issue 24') # Non keyword switch generates javascript SyntaxError switch = False autoTester.check(switch) autoTester.check( 'Issue 27') # Python list.index () not translated correctly autoTester.check(['zero', 'one', 'two', 'three', 'four'].index('three')) autoTester.check( 'Issue 36') # Bug in compiling lambda default argument values # Workaround for Python closures capturing variables rather than values # An extra enclosing scope is created to remember the value of the variable results = [] for i in range(10): # results.append (lambda: i) # Works nowhere # results.append (lambda j = i: j) # Works only in Python results.append( (lambda j: lambda: j)(i)) # Works in Python and Transcrypt autoTester.check([result() for result in results]) autoTester.check( 'Issue 37') # Python integer division not translated correctly autoTester.check(15 // 7) autoTester.check( 'Issue 40') # Python parentheses dropped during translation autoTester.check(65 / (5 * 2)) autoTester.check( 'Issue 50') # Wrong answer with parentheses moved during translation autoTester.check((240 + 30 - 1) // 30 * 30) autoTester.check('Issue 51') # Wrong answer with set() compare a = 1 b = 1 autoTester.check(a, b, {a, b} == {1, 2}) autoTester.check( 'Issue 52') # Non keyword 'default' generates javascript SyntaxError switch, case, default = 'switch', 'case', 'default' autoTester.check(switch, case, default) autoTester.check('Issue 54') # Type dict missing clear(), setdefault() aDict = {1: 11, 2: 22, 3: 33} autoTester.check(aDict) aDict.clear() autoTester.check(aDict) autoTester.check('Issue 60') # Python bool() not translated three = 3 one = three & 1 seven = three | 4 eight = one << 3 four = eight >> 1 aTrue = bool(three & one) aFalse = bool(three & four) autoTester.check(3, three, 1, one, 7, seven, 8, eight, 4, four, True, aTrue, False, aFalse) autoTester.check('Issue 65') # Adding two lists with + not supported __pragma__('opov') aList = [4, 5, 6] autoTester.check([ 1, 2, 3, ] + aList + [4, 5, 6]) autoTester.check(3 * [1, 2, 3]) autoTester.check([1, 2, 3] * 3) aString = 'Crocodile' autoTester.check('Tiger' + aString + 'Elephant') autoTester.check(3 * aString) autoTester.check(aString * 3) __pragma__('noopov') autoTester.check('Issue 76') # Python //= not translated correctly initially17 = 17 autoTester.check(initially17) initially17 //= 2 autoTester.check(initially17) initially17 //= 2 autoTester.check(initially17) autoTester.check( 'Issue 112' ) # When using -e6, iterating TypedArrays or other non-list Iterables doesn't work try: if __envir__.executor_name == __envir__.transpiler_name: # CPython doesn't know Int8Array x = __new__(Int8Array(2)) else: x = [None, None] x[0] = 3 x[1] = 2 for i in x: autoTester.check(i) # Since JavaScript 5 gives no exception for a loop over a non-iterable, following code must only be executed for JavaScript 6 # Since Transcrypt doesn't get to see all modules loaded by CPython, __ifdef__ cannot be made to do its thing for all modules in an efficient way for CPython # But a normal 'if' will work if '__esv6__' in __symbols__: y = 3 for j in y: autoTester.check(j) except: # No 'Exception' can be used behind this, since this is a JavaScript exception, and no subclass of Exception. ??? How desirable is this behaviour? pass # autoTester.check ('Detected iterating over non-iterable') # Minifier masks this exception, so we'll have to pass if '__esv6__' in __symbols__: # "if" rather than "__pragma__ ('ifdef')" because CPython doesn't understand pragma's autoTester.check( 'Issue 122' ) # Problem with yield (or rather with slicing beyond list end) def chunks(aList, chunkLength): for index in range(0, len(aList), chunkLength): yield aList[index:index + chunkLength] for chunk in chunks([chr(index + 97) for index in range(26)], 10): autoTester.check(chunk) autoTester.check('Issue 123') # Python % shouldn't behave like JS % autoTester.check(10 % 3, 10 % -3, -10 % 3, -10 % -3, 10 % 10, 10 % -10, -10 % 10, -10 % -10) autoTester.check('Issue 125') # Strings not iterable abc = 'abc' for index in abc: autoTester.check(abc) autoTester.check('Issue 127') # Can't use the key 'keys' in a dict autoTester.check({ "include_docs": "true", "keys": ["key1", "key2"], "limit": 50 }) autoTester.check('Issue 134') # Operator %= translated incorrectly x0, x1, x2, x3, x4, x5 = 5, 12, -5, -5, 0, 0 x0 %= 10 x1 %= 5 x2 %= 2 x3 %= -3 x4 %= 1 x5 %= -1000 autoTester.check(x0, x1, x2, x3, x4) autoTester.check( 'Issue 136') # Method dict.get(key[, default]) not implemented aDict = {'a': 'ape', 'b': 'banana'} autoTester.check(aDict.get('a', 'noApe'), aDict.get('b'), aDict.get('c', 'noCarot'), aDict.get('d')) autoTester.check('Issue 144') __pragma__('opov') aList = [x for x in [1, 2, 3]] autoTester.check(aList) __pragma__('noopov') autoTester.check('<br><br>Issue 145<br>' ) # List sorting incorrect in case of multiple columns class SortTest: def __init__(self): self.alphabet = 'abcdefghijklmnopqrstuvwxyz' self.nChars = 10 self.nCols = 10 self.nRows = 30 self.pseudoRandom = 0 def randomWord(): word = '' for iChar in range(self.nChars): self.pseudoRandom = (81212 * self.pseudoRandom + 28411) % 134456 # self.pseudoRandom = (1234 * self.pseudoRandom + 57) % 137 # Deliberately short period word += self.alphabet[self.pseudoRandom % 26] return word self.rows = [[randomWord() for iCol in range(self.nCols)] for iRow in range(self.nRows)] def sort(self): for iCol in reversed(range(self.nCols)): self.rows.sort(key=lambda row: row[iCol]) sortTest = SortTest() autoTester.check('<br>Unsorted:<br>') for row in sortTest.rows: autoTester.check('{}<br>'.format(','.join([word for word in row]))) sortTest.sort() autoTester.check('<br>Sorted:<br>') for row in sortTest.rows: autoTester.check('{}<br>'.format(','.join([word for word in row]))) autoTester.check( '<br><br>Issue 148<br>') # Allow key a.o. key 'items' in dict aDict = {'items': [4, 5, 6]} for aKey, aValue in aDict.items(): autoTester.check('{}: {}'.format(aKey, aValue)) autoTester.check('<br><br>Issue 169<br>' ) # Add support for float('inf') and float('-inf') autoTester.check(int(1 / float('inf')), int(1 / float('-inf'))) autoTester.check('<br><br>Issue 178<br>' ) # List Comprehensions / Operator Precedence Bug bitmaps = [(2, ''), (4, ''), (8, 'i'), (16, 'm'), (32, 'y'), (64, 'u'), (128, 'g')] for flags in (122, 233, 11, 55, 79, 201, 23, 111, 200, 100, 50, 25, 12, 6): autoTester.check(''.join([x[1] for x in bitmaps if (x[0] & flags) > 0]))
def run (autoTester): autoTester.check ('Issue 40') autoTester.check (65 / (5 * 2)) autoTester.check ('Issue 24') switch = False autoTester.check (switch) autoTester.check ('Issue 37') autoTester.check (15 // 7) autoTester.check ('Issue 27') autoTester.check (['zero', 'one', 'two', 'three', 'four'] .index ('three')) autoTester.check ('Issue 36') # Workaround for Python closures capturing variables rather than values # An extra enclosing scope is created to remember the value of the variable results = [] for i in range (10): # results.append (lambda: i) # Works nowhere # results.append (lambda j = i: j) # Works only in Python results.append ((lambda j: lambda: j) (i)) # Works in Python and Transcrypt autoTester.check ([result () for result in results]) autoTester.check ('Issue 50') autoTester.check ((240 + 30 - 1) // 30 * 30) autoTester.check ('Issue 51') a = 1 b = 1 autoTester.check (a, b, {a, b} == {1, 2}) autoTester.check ('Issue 52') switch, case, default = 'switch', 'case', 'default' autoTester.check (switch, case, default) autoTester.check ('Issue 54') aDict = {1: 11, 2: 22, 3: 33} autoTester.check (aDict) aDict.clear () autoTester.check (aDict) autoTester.check ('Issue 60') three = 3 one = three & 1 seven = three | 4 eight = one << 3 four = eight >> 1 aTrue = bool (three & one) aFalse = bool (three & four) autoTester.check (3, three, 1, one, 7, seven, 8, eight, 4, four, True, aTrue, False, aFalse) autoTester.check ('Issue 65') __pragma__ ('opov') aList = [4, 5, 6] autoTester.check ([1, 2, 3,] + aList + [4, 5, 6]) autoTester.check (3 * [1, 2, 3]) autoTester.check ([1, 2, 3] * 3) aString = 'Crocodile' autoTester.check ('Tiger' + aString + 'Elephant') autoTester.check (3 * aString) autoTester.check (aString * 3) __pragma__ ('noopov') autoTester.check ('Issue 76') initially17 = 17 autoTester.check (initially17) initially17 //= 2 autoTester.check (initially17) initially17 //= 2 autoTester.check (initially17) autoTester.check ('Issue 112') try: if __envir__.executor_name == __envir__.transpiler_name: # CPython doesn't know Int8Array x = __new__ (Int8Array (2)) else: x = [None, None] x [0] = 3 x [1] = 2 for i in x: autoTester.check (i) # Since JavaScript 5 gives no exception for for a loop over a non-iterable, following code must only be executed for JavaScript 6 # Since Transcrypt doesn't get to see all modules loaded by CPython, __ifdef__ cannot be made to do its thing for all modules in an efficient way for CPython # But a normal 'if' will work if '__esv6__' in __symbols__: y = 3 for j in y: autoTester.check (j) except Exception as exception: autoTester.check ('Detected iterating over non-iterable') if '__esv6__' in __symbols__: # "if" rather than "__pragma__ ('ifdef')" because CPython doesn't understand pragma's autoTester.check ('Issue 122') def chunks (aList, chunkLength): for index in range (0, len (aList), chunkLength): yield aList [index : index + chunkLength] for chunk in chunks ([chr (index + 97) for index in range (26)], 10): autoTester.check (chunk) autoTester.check ('Issue 123') autoTester.check (10 % 3, 10 % -3, -10 % 3, -10 % -3, 10 % 10, 10 % -10, -10 % 10, -10 % -10) autoTester.check ('Issue 125') abc = 'abc' for index in abc: autoTester.check (abc)
def run(autoTester): autoTester.check( 'Issue 24') # Non keyword switch generates javascript SyntaxError switch = False autoTester.check(switch) autoTester.check( 'Issue 27') # Python list.index () not translated correctly autoTester.check(['zero', 'one', 'two', 'three', 'four'].index('three')) autoTester.check( 'Issue 36') # Bug in compiling lambda default argument values # Workaround for Python closures capturing variables rather than values # An extra enclosing scope is created to remember the value of the variable results = [] for i in range(10): # results.append (lambda: i) # Works nowhere # results.append (lambda j = i: j) # Works only in Python results.append( (lambda j: lambda: j)(i)) # Works in Python and Transcrypt autoTester.check([result() for result in results]) autoTester.check( 'Issue 37') # Python integer division not translated correctly autoTester.check(15 // 7) autoTester.check( 'Issue 40') # Python parentheses dropped during translation autoTester.check(65 / (5 * 2)) autoTester.check( 'Issue 50') # Wrong answer with parentheses moved during translation autoTester.check((240 + 30 - 1) // 30 * 30) autoTester.check('Issue 51') # Wrong answer with set() compare a = 1 b = 1 autoTester.check(a, b, {a, b} == {1, 2}) autoTester.check( 'Issue 52') # Non keyword 'default' generates javascript SyntaxError switch, case, default = 'switch', 'case', 'default' autoTester.check(switch, case, default) autoTester.check('Issue 54') # Type dict missing clear(), setdefault() aDict = {1: 11, 2: 22, 3: 33} autoTester.check(aDict) aDict.clear() autoTester.check(aDict) autoTester.check('Issue 60') # Python bool() not translated three = 3 one = three & 1 seven = three | 4 eight = one << 3 four = eight >> 1 aTrue = bool(three & one) aFalse = bool(three & four) autoTester.check(3, three, 1, one, 7, seven, 8, eight, 4, four, True, aTrue, False, aFalse) autoTester.check('Issue 65') # Adding two lists with + not supported __pragma__('opov') aList = [4, 5, 6] autoTester.check([ 1, 2, 3, ] + aList + [4, 5, 6]) autoTester.check(3 * [1, 2, 3]) autoTester.check([1, 2, 3] * 3) aString = 'Crocodile' autoTester.check('Tiger' + aString + 'Elephant') autoTester.check(3 * aString) autoTester.check(aString * 3) __pragma__('noopov') autoTester.check('Issue 76') # Python //= not translated correctly initially17 = 17 autoTester.check(initially17) initially17 //= 2 autoTester.check(initially17) initially17 //= 2 autoTester.check(initially17) autoTester.check( 'Issue 112' ) # When using -e6, iterating TypedArrays or other non-list Iterables doesn't work try: if __envir__.executor_name == __envir__.transpiler_name: # CPython doesn't know Int8Array x = __new__(Int8Array(2)) else: x = [None, None] x[0] = 3 x[1] = 2 for i in x: autoTester.check(i) y = 3 for j in y: autoTester.check(j) except: # No 'Exception' can be used behind this, since this is a JavaScript exception, and no subclass of Exception. ??? How desirable is this behaviour? pass # autoTester.check ('Detected iterating over non-iterable') # Minifier masks this exception, so we'll have to pass autoTester.check( 'Issue 122' ) # Problem with yield (or rather with slicing beyond list end) def chunks(aList, chunkLength): for index in range(0, len(aList), chunkLength): yield aList[index:index + chunkLength] for chunk in chunks([chr(index + 97) for index in range(26)], 10): autoTester.check(chunk) autoTester.check('Issue 123') # Python % shouldn't behave like JS % autoTester.check(10 % 3, 10 % -3, -10 % 3, -10 % -3, 10 % 10, 10 % -10, -10 % 10, -10 % -10) autoTester.check('Issue 125') # Strings not iterable abc = 'abc' for index in abc: autoTester.check(abc) autoTester.check('Issue 127') # Can't use the key 'keys' in a dict autoTester.check({ "include_docs": "true", "keys": ["key1", "key2"], "limit": 50 }) autoTester.check('Issue 134') # Operator %= translated incorrectly x0, x1, x2, x3, x4, x5 = 5, 12, -5, -5, 0, 0 x0 %= 10 x1 %= 5 x2 %= 2 x3 %= -3 x4 %= 1 x5 %= -1000 autoTester.check(x0, x1, x2, x3, x4) autoTester.check( 'Issue 136') # Method dict.get(key[, default]) not implemented aDict = {'a': 'ape', 'b': 'banana'} autoTester.check(aDict.get('a', 'noApe'), aDict.get('b'), aDict.get('c', 'noCarot'), aDict.get('d')) autoTester.check('Issue 144') __pragma__('opov') aList = [x for x in [1, 2, 3]] autoTester.check(aList) __pragma__('noopov') autoTester.check('<br><br>Issue 145<br>' ) # List sorting incorrect in case of multiple columns class SortTest: def __init__(self): self.alphabet = 'abcdefghijklmnopqrstuvwxyz' self.nChars = 10 self.nCols = 10 self.nRows = 30 self.pseudoRandom = 0 def randomWord(): word = '' for iChar in range(self.nChars): self.pseudoRandom = (81212 * self.pseudoRandom + 28411) % 134456 # self.pseudoRandom = (1234 * self.pseudoRandom + 57) % 137 # Deliberately short period word += self.alphabet[self.pseudoRandom % 26] return word self.rows = [[randomWord() for iCol in range(self.nCols)] for iRow in range(self.nRows)] def sort(self): for iCol in reversed(range(self.nCols)): self.rows.sort(key=lambda row: row[iCol]) sortTest = SortTest() autoTester.check('<br>Unsorted:<br>') for row in sortTest.rows: autoTester.check('{}<br>'.format(','.join([word for word in row]))) sortTest.sort() autoTester.check('<br>Sorted:<br>') for row in sortTest.rows: autoTester.check('{}<br>'.format(','.join([word for word in row]))) autoTester.check( '<br><br>Issue 148<br>') # Allow key a.o. key 'items' in dict aDict = {'items': [4, 5, 6]} for aKey, aValue in aDict.items(): autoTester.check('{}: {}'.format(aKey, aValue)) autoTester.check('<br><br>Issue 169<br>' ) # Add support for float('inf') and float('-inf') autoTester.check(int(1 / float('inf')), int(1 / float('-inf'))) autoTester.check('<br><br>Issue 178<br>' ) # List Comprehensions / Operator Precedence Bug bitmaps = [(2, ''), (4, ''), (8, 'i'), (16, 'm'), (32, 'y'), (64, 'u'), (128, 'g')] for flags in (122, 233, 11, 55, 79, 201, 23, 111, 200, 100, 50, 25, 12, 6): autoTester.check(''.join([x[1] for x in bitmaps if (x[0] & flags) > 0])) def issue256(): autoTester.check('Issue 256') class C: def __init__(self, value): self.value = value def f1(value): # Generate parens after return return (C(value).value or 'second').capitalize() == 'First' def f2(value): # Generate parens after return return (C(value).value or 'second').capitalize() == 'Second' def f3(value): # Generate NO parens after return return C(value).value or 'second' def f4(value): # Generate NO parens after return return (C(value).value or 'second') autoTester.check(f1('first')) autoTester.check(f1('')) autoTester.check(f2('first')) autoTester.check(f2('')) autoTester.check(f3('first')) autoTester.check(f4('')) issue256() autoTester.check('Issue 274') a = 3 del a autoTester.check('Still alive') autoTester.check( 'Issue 276' ) # Partial, other part tested in testlet 'operator_overloading' a = 2 b = a**3 a **= 4 autoTester.check(a, b) autoTester.check('Issue 277') new = 3 autoTester.check(new) autoTester.check('Issue 279') class A: TypeError = 111 js_TypeError = 222 autoTester.check( A.TypeError, A.js_TypeError ) # ... Generated code should use py_TypeError and TypeError respectively autoTester.check('Still alive') autoTester.check('Issue 301') def filter_word(word0, word1): if len(word0) != len(word1): return False for char0, char1 in zip(word0, word1): if char0 != '_' and char0 != char1: return False return True autoTester.check(filter_word('bee', 'beer')) autoTester.check(filter_word('wine', 'wine')) autoTester.check(filter_word('win_', 'wind')) autoTester.check(filter_word('_in_', 'kind')) autoTester.check(filter_word('min_', 'kind')) autoTester.check('Issue 306') dict_306 = { 'Abraham': 'Lincoln', 'Barack': 'O\'Bama', 'Thomas': 'Jefferson' } results = [] try: while True: results.append(dict_306.popitem()) except Exception as exception: autoTester.check(sorted(results)) autoTester.check('That\'s it') autoTester.check('Issue 314') try: autoTester.check(int(float(123))) except: autoTester.check('a') try: autoTester.check(float(12.3)) except: autoTester.check('b') try: autoTester.check(int(float('123'))) except: autoTester.check('c') try: autoTester.check(int(float(' 123'))) except: autoTester.check('d') try: autoTester.check(float('')) except: autoTester.check('e') try: autoTester.check(float(' ')) except: autoTester.check('f') try: autoTester.check(float('drie')) except: autoTester.check('g') autoTester.check('Issue 316') autoTester.check(list(filter(None, [[1, 2], [3], [], [4, 5], [6]]))) autoTester.check( list(filter(lambda l: len(l) >= 2, [[1, 2], [3], [], [4, 5], [6]]))) autoTester.check('Issue 317') mylist = [] try: mylist.remove('value') except ValueError as exception: autoTester.check(exception.__class__.__name__) autoTester.check('Issue 331') autoTester.check(max(-5, 4, 1, 2, -3, 2)) autoTester.check(max([-5, 4, 1, 2, -3, 2])) autoTester.check(max((5, 6, 2, -2, -4))) autoTester.check(min(-5, 4, 1, 2, -3, 2)) autoTester.check(min([-5, 4, 1, 2, -3, 2])) autoTester.check(min((5, 6, 2, -2, -4))) autoTester.check('issue 356') try: raise TypeError("How are you?") except TypeError as exception: autoTester.check(exception) autoTester.check('Issue 369') class Vector: def __init__(self, *values): self.values = values def __iter__(self): for item in self.values: yield item def __add__(self, other): return Vector(*(x + y for x, y in zip(self, other))) def __str__(self): return str(list(self.values)) #__pragma__ ('opov') autoTester.check(str(Vector(1, 2, 3) + Vector(3, 4, 5))) #__pragma__ ('noopov') autoTester.check('Issue 387') run387(autoTester) autoTester.check('Issue 391') autoTester.check(int(False)) autoTester.check(int(True)) autoTester.check(int(1 == 2)) autoTester.check(int(1 != 2)) autoTester.check('Issue 392') class Example: d = {'A': 1, 'B': 2} rec = re.compile('(?P<decimal>\d+)', re.ASCII) def run(self): match = self.rec.match('42') if not match: print('ERROR: RE does not match') e = match.groupdict() autoTester.check("before: self.d=", self.d) autoTester.check("before: e=", e) self.d.update(e) autoTester.check("after: self.d=", self.d) example = Example() example.run() autoTester.check('Issue 398') # This used to give extra comma's so invalid syntax (no check calls needed) class Test398(object): #__pragma__ ('skip') def method1(self): pass def method2(self): pass #__pragma__ ('noskip') pass test398 = Test398() autoTester.check('Issue 399') __pragma__('keycheck') try: surpressWarning = {'a': 5}['a'] surpressWarning = {'a': 5}['b'] autoTester.check('no problem') except KeyError: autoTester.check('not found') autoTester.check('Issue 413') __pragma__('nokeycheck') class Foo: def __len__(self): return 3 def __getitem__(self, i): if i >= 3: raise IndexError return 'This is item ' + str(i) foo = Foo() #__pragma__ ('opov') autoTester.check('Attempt 1:') for i in foo: autoTester.check(i) autoTester.check('Attempt 2:') for i in range(len(foo)): autoTester.check(foo[i]) #__pragma__('noopov') autoTester.check('Issue 414') class Foo: pass foo = Foo() foo.bar = 'baz' foo.name = 'hello' foo.default = 'world' autoTester.check([x for x in dir(foo) if not x.startswith('__')]) #__pragma__('kwargs') def foo(*args, **kwargs): default = kwargs.get('default', 'bar') return default autoTester.check(foo()) autoTester.check(foo(default='Hello World')) autoTester.check('Issue 460') s460 = 'car' l460 = [11, 22, 33] t460 = (4, 5, 6) d460 = {-1: 'mmminusOne', 'b': 'bbbike'} #__pragma__ ('opov') l460[0] = 1 l460[-2] = 2 l460[-1] = 3 d460[-1] = 'minusOne' d460['b'] = 'bike' autoTester.check(s460[0], s460[1], s460[2], s460[-1], s460[-2], s460[-3]) autoTester.check(l460[0], l460[1], l460[2], l460[-1], l460[-2], l460[-3]) autoTester.check(t460[0], t460[1], t460[2], t460[-1], t460[-2], t460[-3]) autoTester.check(d460[-1], d460['b']) autoTester.check(s460[0], s460[1], s460[2], s460[-1], s460[-2], s460[-3]) autoTester.check(l460[0], l460[1], l460[2], l460[-1], l460[-2], l460[-3]) autoTester.check(t460[0], t460[1], t460[2], t460[-1], t460[-2], t460[-3]) autoTester.check(d460[-1], d460['b']) #__pragma__ ('noopov') #__pragma__ ('keycheck') try: autoTester.check(d460[-1], d460['c']) except: autoTester.check(111) try: autoTester.check(d460[-2], d460['b']) except: autoTester.check(222) #__pragma__ ('nokeycheck') a = [1, 2, 3] b = [4, 5, 6] c = '1,2,34,5,6' if __envir__.executor_name == __envir__.transpiler_name: autoTester.check(a + b) autoTester.check(a + b) #__:opov autoTester.check(a + b) else: autoTester.check(c) autoTester.check(a + b) #__:opov autoTester.check(c) #__pragma__ ('opov') if __envir__.executor_name == __envir__.transpiler_name: autoTester.check(a + b) #__:noopov autoTester.check(a + b) autoTester.check(a + b) #__:noopov else: autoTester.check(c) #__:noopov autoTester.check(a + b) autoTester.check(c) #__:noopov #__pragma__ ('noopov') autoTester.check( 'Issue 494') # {None} in formatted string gets converted to {} # Worked, should still work a = 1 autoTester.check(f'a={a}') # Failed, should now work a = None autoTester.check(f'a={a}') autoTester.check( 'Issue 515' ) # Method format() is failing to replace the replacement fields if the value is None autoTester.check('a: {}; b: {}'.format(None, 1)) autoTester.check('a: {}; b: {}'.format(1, None)) autoTester.check('a: {0}; b: {1}'.format(1, None)) autoTester.check('a: {0}; b: {1}'.format(1, [])) autoTester.check('a: {}; b: {}'.format(1, [])) autoTester.check('a: {0}; b: {1}'.format(1, {})) autoTester.check('a: {}; b: {}'.format(1, {})) autoTester.check('a: {0}; b: {1}'.format(1, 0)) autoTester.check('a: {}; b: {}'.format(1, 0)) autoTester.check( 'Issue 559' ) # Reexport everything imported, e.g. by the __init__.py of a module run559(autoTester)
def strptime(string, format): """ strptime(string, format) -> struct_time Parse a string to a time tuple according to a format specification. See the library reference manual for formatting codes (same as strftime()). Commonly used format codes: %Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %z Time zone offset from UTC. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. %I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM. Tradoffs of this Transcrypt implementation: 1. platform specific codes not supported 2. %% and %c not supported """ if not format: format = "%a %b %d %H:%M:%S %Y" ts, fmt = string, format def get_next(fmt): ''' returns next directive, next seperator, rest of format str''' def get_sep(fmt): res = [] if not fmt: return '', '' for i in range(len(fmt)-1): c = fmt[i] if c == '%': break res.append(c) return ''.join(res), fmt[i:] # return next seperator: d, sep, f = None, None, None if fmt: if fmt[0] == '%': d = fmt[1] sep, f = get_sep(fmt[2:]) else: sep, f = get_sep(fmt) return d, sep, f # directive / value tuples go in here: dir_val = {} while ts: d, sep, fmt = get_next(fmt) if sep == '': lv = None if d: # we have a directive, seperator is empty. Is the directive # fixed length, with next w/o sep? e.g. %Y%Z ? # then get the next one like: l = -1 if d == 'Y': l = 4 elif d == 'a': l = len(__weekdays[0]) elif d == 'A': l = len(__weekdays_long[0]) elif d == 'b': l = len(__months[0]) elif d in ('d', 'm', 'H', 'M', 'S'): l = 2 if l > -1: lv = [ts[:l], ts[l:]] if not lv: lv = [ts, ''] else: lv = _lsplit(ts, sep, 1) if d == None: ts = lv[1] continue ts, dir_val[d] = lv[1], lv[0] if fmt == '': break # defaults when not specified: t = [1900, 1, 1, 0, 0, 0, 0, 1, -1] ignore_keys = [] have_weekday = False for d, v in dir_val.items(): if d in ignore_keys: continue if d == 'p': continue if d in __lu.keys(): t[__lu[d]] = int(v) continue if d in ('a', 'A', 'b', 'B'): v = v.lower() if d == 'm': # we go the python 2(!) way for conflicting %b %m and take %m # why? because there IS no Py3 way (see strp time testlet) ignore_keys.append('b') ignore_keys.append('B') # better readable than short: if d == 'a': # funny. the weekday is only set but does not override %d. # -> produces impossible dates but well its how py does it: if not v in __weekdays: raise ValueError('Weekday unknown in your locale') have_weekday = True t[6] = __weekdays.index(v) elif d == 'A': if not v in __weekdays_long: raise ValueError('Weekday unknown in your locale') have_weekday = True t[6] = __weekdays_long.index(v) elif d == 'b': # month short. overruled by m if present if not v in __months: raise ValueError('Month unknown in your locale') t[1] = __months.index(v) + 1 elif d == 'B': # month long. overruled by m if present if not v in __months_long: raise ValueError('Month unknown in your locale') t[1] = __months_long.index(v) + 1 elif d == 'I': # 0-12 hour, with AM/PM. ampm = dir_val['p'] or 'am' ampm = ampm.lower() v = int(v) # thats how py does it if v == 12: v = 0 elif v > 12: raise ValueError("time data '" + string + \ "' does not match format '" + format + "'") if ampm == 'pm': v += 12 t[__lu['H']] = v elif d == 'y': t[0] = 2000 + int(v) # producing a y3k problem. try find me, then. elif d == 'Z': if v.lower() in ['gmt', 'utc']: t[-1] = 0 # get day of year, costing us an object, to stay safe: __date = __new__(Date(0)) __date.setUTCFullYear( t[0] ) __date.setUTCMonth(t[1] -1 ) __date.setUTCDate( t[2] ) __date.setUTCHours(t[3]) t[7] = _day_of_year(__date) if not have_weekday: t[6] = __date.getUTCDay() -1 return t
def mktime(t): ''' inverse of localtime ''' d = __new__(Date(t[0], t[1] - 1, t[2], t[3], t[4], t[5], 0)) return (d - 0) / 1000
Spec for all below (must have open to read this module): > https://docs.python.org/3.5/library/time.html Jul 2016, Gunther Klessinger, Axiros GmbH """ # we don't need those: __pragma__ ('nokwargs') # for js dates: from org.transcrypt.stubs.browser import __new__ # js date object. might be modified during calculations: __date = __new__(Date(0)) __now = __new__(Date()) # build the locale's weekday names __weekdays = [] __weekdays_long = [] __d = __new__(Date(1467662339080)) # a monday for i in range(7): for l, s in (__weekdays, 'short'), (__weekdays_long, 'long'): l.append(__d.toLocaleString(window.navigator.language, {'weekday': s}).lower()) __d.setDate(__d.getDate() + 1) # build the locale's months names
def run (autoTester): autoTester.check ('Issue 24') # Non keyword switch generates javascript SyntaxError switch = False autoTester.check (switch) autoTester.check ('Issue 27') # Python list.index () not translated correctly autoTester.check (['zero', 'one', 'two', 'three', 'four'] .index ('three')) autoTester.check ('Issue 36') # Bug in compiling lambda default argument values # Workaround for Python closures capturing variables rather than values # An extra enclosing scope is created to remember the value of the variable results = [] for i in range (10): # results.append (lambda: i) # Works nowhere # results.append (lambda j = i: j) # Works only in Python results.append ((lambda j: lambda: j) (i)) # Works in Python and Transcrypt autoTester.check ([result () for result in results]) autoTester.check ('Issue 37') # Python integer division not translated correctly autoTester.check (15 // 7) autoTester.check ('Issue 40') # Python parentheses dropped during translation autoTester.check (65 / (5 * 2)) autoTester.check ('Issue 50') # Wrong answer with parentheses moved during translation autoTester.check ((240 + 30 - 1) // 30 * 30) autoTester.check ('Issue 51') # Wrong answer with set() compare a = 1 b = 1 autoTester.check (a, b, {a, b} == {1, 2}) autoTester.check ('Issue 52') # Non keyword 'default' generates javascript SyntaxError switch, case, default = 'switch', 'case', 'default' autoTester.check (switch, case, default) autoTester.check ('Issue 54') # Type dict missing clear(), setdefault() aDict = {1: 11, 2: 22, 3: 33} autoTester.check (aDict) aDict.clear () autoTester.check (aDict) autoTester.check ('Issue 60') # Python bool() not translated three = 3 one = three & 1 seven = three | 4 eight = one << 3 four = eight >> 1 aTrue = bool (three & one) aFalse = bool (three & four) autoTester.check (3, three, 1, one, 7, seven, 8, eight, 4, four, True, aTrue, False, aFalse) autoTester.check ('Issue 65') # Adding two lists with + not supported __pragma__ ('opov') aList = [4, 5, 6] autoTester.check ([1, 2, 3,] + aList + [4, 5, 6]) autoTester.check (3 * [1, 2, 3]) autoTester.check ([1, 2, 3] * 3) aString = 'Crocodile' autoTester.check ('Tiger' + aString + 'Elephant') autoTester.check (3 * aString) autoTester.check (aString * 3) __pragma__ ('noopov') autoTester.check ('Issue 76') # Python //= not translated correctly initially17 = 17 autoTester.check (initially17) initially17 //= 2 autoTester.check (initially17) initially17 //= 2 autoTester.check (initially17) autoTester.check ('Issue 112') # When using -e6, iterating TypedArrays or other non-list Iterables doesn't work try: if __envir__.executor_name == __envir__.transpiler_name: # CPython doesn't know Int8Array x = __new__ (Int8Array (2)) else: x = [None, None] x [0] = 3 x [1] = 2 for i in x: autoTester.check (i) # Since JavaScript 5 gives no exception for a loop over a non-iterable, following code must only be executed for JavaScript 6 # Since Transcrypt doesn't get to see all modules loaded by CPython, __ifdef__ cannot be made to do its thing for all modules in an efficient way for CPython # But a normal 'if' will work if '__esv6__' in __symbols__: y = 3 for j in y: autoTester.check (j) except: # No 'Exception' can be used behind this, since this is a JavaScript exception, and no subclass of Exception. ??? How desirable is this behaviour? pass # autoTester.check ('Detected iterating over non-iterable') # Minifier masks this exception, so we'll have to pass if '__esv6__' in __symbols__: # "if" rather than "__pragma__ ('ifdef')" because CPython doesn't understand pragma's autoTester.check ('Issue 122') # Problem with yield (or rather with slicing beyond list end) def chunks (aList, chunkLength): for index in range (0, len (aList), chunkLength): yield aList [index : index + chunkLength] for chunk in chunks ([chr (index + 97) for index in range (26)], 10): autoTester.check (chunk) autoTester.check ('Issue 123') # Python % shouldn't behave like JS % autoTester.check (10 % 3, 10 % -3, -10 % 3, -10 % -3, 10 % 10, 10 % -10, -10 % 10, -10 % -10) autoTester.check ('Issue 125') # Strings not iterable abc = 'abc' for index in abc: autoTester.check (abc) autoTester.check ('Issue 127') # Can't use the key 'keys' in a dict autoTester.check ({"include_docs": "true", "keys": ["key1", "key2"], "limit": 50}) autoTester.check ('Issue 134') # Operator %= translated incorrectly x0, x1, x2, x3, x4, x5 = 5, 12, -5, -5, 0, 0 x0 %= 10; x1 %= 5; x2 %= 2; x3 %= -3; x4 %= 1; x5 %= -1000 autoTester.check (x0, x1, x2, x3, x4) autoTester.check ('Issue 136') # Method dict.get(key[, default]) not implemented aDict = {'a': 'ape', 'b': 'banana'} autoTester.check (aDict.get ('a', 'noApe'), aDict.get ('b'), aDict.get ('c', 'noCarot'), aDict.get ('d')) autoTester.check ('Issue 144') __pragma__('opov') aList = [x for x in [1, 2, 3]] autoTester.check (aList) __pragma__('noopov') autoTester.check ('<br><br>Issue 145<br>') # List sorting incorrect in case of multiple columns class SortTest: def __init__ (self): self.alphabet = 'abcdefghijklmnopqrstuvwxyz' self.nChars = 10 self.nCols = 10 self.nRows = 30 self.pseudoRandom = 0 def randomWord (): word = '' for iChar in range (self.nChars): self.pseudoRandom = (81212 * self.pseudoRandom + 28411) % 134456 # self.pseudoRandom = (1234 * self.pseudoRandom + 57) % 137 # Deliberately short period word += self.alphabet [self.pseudoRandom % 26] return word self.rows = [[randomWord () for iCol in range (self.nCols)] for iRow in range (self.nRows)] def sort (self): for iCol in reversed (range (self.nCols)): self.rows.sort (key = lambda row: row [iCol]) sortTest = SortTest () autoTester.check ('<br>Unsorted:<br>') for row in sortTest.rows: autoTester.check ('{}<br>'.format (','.join ([word for word in row]))) sortTest.sort () autoTester.check ('<br>Sorted:<br>') for row in sortTest.rows: autoTester.check ('{}<br>'.format (','.join ([word for word in row]))) autoTester.check ('<br><br>Issue 148<br>') # Allow key a.o. key 'items' in dict aDict = { 'items': [4, 5, 6] } for aKey, aValue in aDict.items (): autoTester.check ('{}: {}'.format (aKey, aValue)) autoTester.check ('<br><br>Issue 169<br>') # Add support for float('inf') and float('-inf') autoTester.check (int (1 / float ('inf')), int (1 / float ('-inf'))) autoTester.check ('<br><br>Issue 178<br>') # List Comprehensions / Operator Precedence Bug bitmaps = [ (2 , ''), (4 , ''), (8, 'i'), (16, 'm'), (32, 'y'), (64, 'u'), (128, 'g') ] for flags in (122, 233, 11, 55, 79, 201, 23, 111, 200, 100, 50, 25, 12, 6): autoTester.check (''.join ([x [1] for x in bitmaps if (x [0] & flags) > 0]))
def install (self): # The sprite holds an image that fabric can display self.image = __new__ (fabric.Rect ({ 'width': self.exp.scaleX (self.width), 'height': self.exp.scaleY (self.height), 'originX': 'center', 'originY': 'center', 'fill': 'white' }))
def __init__(*args): return __new__(cls(*args))
def run (autoTester): test2 (autoTester) try: raise Ex2 ('had') except Ex1 as exception: autoTester.check ('a') except Exception as exception: autoTester.check ('little') autoTester.check (exception) autoTester.check (333) try: raise Ex1 ('lamb') except Ex2 as exception: autoTester.check ('his') autoTester.check (exception) except Ex1 as exception: autoTester.check ('fleece') autoTester.check (exception) except Exception as exception: autoTester.check ('was') autoTester.check (exception) finally: autoTester.check ('white') autoTester.check (444) def test3 (): raise Ex3 ('as') autoTester.check (555) try: test3 () except Ex1 as exception: autoTester.check ('snow') autoTester.check (exception) except Exception as exception: autoTester.check ('and') autoTester.check (exception) finally: autoTester.check ('everywhere') autoTester.check (666) try: raise Ex3 ('that') except Ex1 as exception: autoTester.check ('mary') autoTester.check (exception) except: autoTester.check ('went') finally: autoTester.check ('the') autoTester.check (777) try: try: raise Ex3 ('lamb') except Ex1 as exception: autoTester.check ('was') autoTester.check (exception) finally: autoTester.check ('to') except Ex3 as exception: # We should get here, exception not swallowed autoTester.check ('go') autoTester.check (exception) try: raise __new__ (Table ('he', 'followed', 'her')) except Ex1 as exception: autoTester.check ('to') autoTester.check (exception) except Table as exception: # Pure JavaScript exception, if no Python __class__ autoTester.check ('school') autoTester.check (exception) except Ex3 as exception: autoTester.check ('one') autoTester.check (exception) finally: autoTester.check ('day') try: assert 2 * 8 / 4 == 2, 'Assert error 1' except AssertionError as exception: autoTester.check (exception) try: assert 2 * 8 / 4 == 4, 'Assert error 2' except AssertionError as exception: autoTester.check (exception) try: assert 2 * 8 / 4 == 2 except AssertionError as exception: autoTester.check (exception) try: assert 2 * 8 / 4 == 4 except AssertionError as exception: autoTester.check (exception) autoTester.check (888) try: autoTester.check ('hello world 1') except: autoTester.check ('error 1') else: autoTester.check ('no error 1') i = 1 + 2 try: autoTester.check ('hello world 2') if i == 3: # Prevent unreachable code warning raise Exception () except: autoTester.check ('error 2') else: autoTester.check ('no error 2') for raiseIt in (False, True): try: try: if raiseIt: raise Exception () autoTester.check ('no error 3') finally: autoTester.check ('anyhow 3') except: autoTester.check ('error 3')
def run (autoTester): autoTester.check ('Issue 24') # Non keyword switch generates javascript SyntaxError switch = False autoTester.check (switch) autoTester.check ('Issue 27') # Python list.index () not translated correctly autoTester.check (['zero', 'one', 'two', 'three', 'four'] .index ('three')) autoTester.check ('Issue 36') # Bug in compiling lambda default argument values # Workaround for Python closures capturing variables rather than values # An extra enclosing scope is created to remember the value of the variable results = [] for i in range (10): # results.append (lambda: i) # Works nowhere # results.append (lambda j = i: j) # Works only in Python results.append ((lambda j: lambda: j) (i)) # Works in Python and Transcrypt autoTester.check ([result () for result in results]) autoTester.check ('Issue 37') # Python integer division not translated correctly autoTester.check (15 // 7) autoTester.check ('Issue 40') # Python parentheses dropped during translation autoTester.check (65 / (5 * 2)) autoTester.check ('Issue 50') # Wrong answer with parentheses moved during translation autoTester.check ((240 + 30 - 1) // 30 * 30) autoTester.check ('Issue 51') # Wrong answer with set() compare a = 1 b = 1 autoTester.check (a, b, {a, b} == {1, 2}) autoTester.check ('Issue 52') # Non keyword 'default' generates javascript SyntaxError switch, case, default = 'switch', 'case', 'default' autoTester.check (switch, case, default) autoTester.check ('Issue 54') # Type dict missing clear(), setdefault() aDict = {1: 11, 2: 22, 3: 33} autoTester.check (aDict) aDict.clear () autoTester.check (aDict) autoTester.check ('Issue 60') # Python bool() not translated three = 3 one = three & 1 seven = three | 4 eight = one << 3 four = eight >> 1 aTrue = bool (three & one) aFalse = bool (three & four) autoTester.check (3, three, 1, one, 7, seven, 8, eight, 4, four, True, aTrue, False, aFalse) autoTester.check ('Issue 65') # Adding two lists with + not supported __pragma__ ('opov') aList = [4, 5, 6] autoTester.check ([1, 2, 3,] + aList + [4, 5, 6]) autoTester.check (3 * [1, 2, 3]) autoTester.check ([1, 2, 3] * 3) aString = 'Crocodile' autoTester.check ('Tiger' + aString + 'Elephant') autoTester.check (3 * aString) autoTester.check (aString * 3) __pragma__ ('noopov') autoTester.check ('Issue 76') # Python //= not translated correctly initially17 = 17 autoTester.check (initially17) initially17 //= 2 autoTester.check (initially17) initially17 //= 2 autoTester.check (initially17) autoTester.check ('Issue 112') # When using -e6, iterating TypedArrays or other non-list Iterables doesn't work try: if __envir__.executor_name == __envir__.transpiler_name: # CPython doesn't know Int8Array x = __new__ (Int8Array (2)) else: x = [None, None] x [0] = 3 x [1] = 2 for i in x: autoTester.check (i) # Since JavaScript 5 gives no exception for a loop over a non-iterable, following code must only be executed for JavaScript 6 # Since Transcrypt doesn't get to see all modules loaded by CPython, __ifdef__ cannot be made to do its thing for all modules in an efficient way for CPython # But a normal 'if' will work if '__esv6__' in __symbols__: y = 3 for j in y: autoTester.check (j) except: # No 'Exception' can be used behind this, since this is a JavaScript exception, and no subclass of Exception. ??? How desirable is this behaviour? pass # autoTester.check ('Detected iterating over non-iterable') # Minifier masks this exception, so we'll have to pass if '__esv6__' in __symbols__: # "if" rather than "__pragma__ ('ifdef')" because CPython doesn't understand pragma's autoTester.check ('Issue 122') # Problem with yield (or rather with slicing beyond list end) def chunks (aList, chunkLength): for index in range (0, len (aList), chunkLength): yield aList [index : index + chunkLength] for chunk in chunks ([chr (index + 97) for index in range (26)], 10): autoTester.check (chunk) autoTester.check ('Issue 123') # Python % shouldn't behave like JS % autoTester.check (10 % 3, 10 % -3, -10 % 3, -10 % -3, 10 % 10, 10 % -10, -10 % 10, -10 % -10) autoTester.check ('Issue 125') # Strings not iterable abc = 'abc' for index in abc: autoTester.check (abc) autoTester.check ('Issue 127') # Can't use the key 'keys' in a dict autoTester.check ({"include_docs": "true", "keys": ["key1", "key2"], "limit": 50}) autoTester.check ('Issue 134') # Operator %= translated incorrectly x0, x1, x2, x3, x4, x5 = 5, 12, -5, -5, 0, 0 x0 %= 10; x1 %= 5; x2 %= 2; x3 %= -3; x4 %= 1; x5 %= -1000 autoTester.check (x0, x1, x2, x3, x4) autoTester.check ('Issue 136') # Method dict.get(key[, default]) not implemented aDict = {'a': 'ape', 'b': 'banana'} autoTester.check (aDict.get ('a', 'noApe'), aDict.get ('b'), aDict.get ('c', 'noCarot'), aDict.get ('d')) autoTester.check ('Issue 144') __pragma__('opov') aList = [x for x in [1, 2, 3]] autoTester.check (aList) __pragma__('noopov') autoTester.check ('<br><br>Issue 145<br>') # List sorting incorrect in case of multiple columns class SortTest: def __init__ (self): self.alphabet = 'abcdefghijklmnopqrstuvwxyz' self.nChars = 10 self.nCols = 10 self.nRows = 30 self.pseudoRandom = 0 def randomWord (): word = '' for iChar in range (self.nChars): self.pseudoRandom = (81212 * self.pseudoRandom + 28411) % 134456 # self.pseudoRandom = (1234 * self.pseudoRandom + 57) % 137 # Deliberately short period word += self.alphabet [self.pseudoRandom % 26] return word self.rows = [[randomWord () for iCol in range (self.nCols)] for iRow in range (self.nRows)] def sort (self): for iCol in reversed (range (self.nCols)): self.rows.sort (key = lambda row: row [iCol]) sortTest = SortTest () autoTester.check ('<br>Unsorted:<br>') for row in sortTest.rows: autoTester.check ('{}<br>'.format (','.join ([word for word in row]))) sortTest.sort () autoTester.check ('<br>Sorted:<br>') for row in sortTest.rows: autoTester.check ('{}<br>'.format (','.join ([word for word in row]))) autoTester.check ('<br><br>Issue 148<br>') # Allow key a.o. key 'items' in dict aDict = { 'items': [4, 5, 6] } for aKey, aValue in aDict.items (): autoTester.check ('{}: {}'.format (aKey, aValue)) autoTester.check ('<br><br>Issue 169<br>') # Add support for float('inf') and float('-inf') autoTester.check (int (1 / float ('inf')), int (1 / float ('-inf'))) autoTester.check ('<br><br>Issue 178<br>') # List Comprehensions / Operator Precedence Bug bitmaps = [ (2 , ''), (4 , ''), (8, 'i'), (16, 'm'), (32, 'y'), (64, 'u'), (128, 'g') ] for flags in (122, 233, 11, 55, 79, 201, 23, 111, 200, 100, 50, 25, 12, 6): autoTester.check (''.join ([x [1] for x in bitmaps if (x [0] & flags) > 0])) def issue256 (): autoTester.check ('Issue 256') class C: def __init__ (self, value): self.value = value def f1 (value): # Generate parens after return return (C (value) .value or 'second') .capitalize () == 'First' def f2 (value): # Generate parens after return return (C (value) .value or 'second') .capitalize () == 'Second' def f3 (value): # Generate NO parens after return return C (value) .value or 'second' def f4 (value): # Generate NO parens after return return (C (value) .value or 'second') autoTester.check (f1 ('first')) autoTester.check (f1 ('')) autoTester.check (f2 ('first')) autoTester.check (f2 ('')) autoTester.check (f3 ('first')) autoTester.check (f4 ('')) issue256 () autoTester.check ('Issue 274') a = 3 del a autoTester.check ('Still alive') autoTester.check ('Issue 276') # Partial, other part tested in testlet 'operator_overloading' a = 2 b = a ** 3 a **= 4 autoTester.check (a, b) autoTester.check ('Issue 277') new = 3 autoTester.check (new) autoTester.check ('Issue 279') class A: TypeError = 111 js_TypeError = 222 autoTester.check (A.TypeError, A.js_TypeError) # ... Generated code should use py_TypeError and TypeError respectively autoTester.check ('Still alive') autoTester.check ('Issue 301') def filter_word (word0, word1): if len (word0) != len (word1): return False for char0, char1 in zip (word0, word1): if char0 != '_' and char0 != char1: return False return True autoTester.check (filter_word ('bee', 'beer')) autoTester.check (filter_word ('wine', 'wine')) autoTester.check (filter_word ('win_', 'wind')) autoTester.check (filter_word ('_in_', 'kind')) autoTester.check (filter_word ('min_', 'kind')) autoTester.check ('Issue 306') dict_306 = {'Abraham': 'Lincoln', 'Barack': 'O\'Bama', 'Thomas': 'Jefferson'} results = [] try: while True: results.append (dict_306.popitem ()) except Exception as exception: autoTester.check (sorted (results)) autoTester.check ('That\'s it') autoTester.check ('Issue 314') try: autoTester.check (int (float (123))) except: autoTester.check ('a') try: autoTester.check (float (12.3)) except: autoTester.check ('b') try: autoTester.check (int (float ('123'))) except: autoTester.check ('c') try: autoTester.check (int (float (' 123'))) except: autoTester.check ('d') try: autoTester.check (float ('')) except: autoTester.check ('e') try: autoTester.check (float (' ')) except: autoTester.check ('f') try: autoTester.check (float ('drie')) except: autoTester.check ('g') autoTester.check ('Issue 316') autoTester.check (list (filter (None, [[1, 2], [3], [], [4, 5], [6]]))) autoTester.check (list (filter (lambda l: len (l) >= 2, [[1, 2], [3], [], [4, 5], [6]]))) autoTester.check ('Issue 317') mylist = [] try: mylist.remove ('value') except ValueError as exception: autoTester.check (exception.__class__.__name__) #__pragma__ ('ifdef', '__esv6__') # Needed because Transcrypt imports are compile time if '__esv6__' in __symbols__: # Needed because CPython doesn't understand pragma's autoTester.check ('Issue 369') class Vector: def __init__ (self, *values): self.values = values def __iter__ (self): for item in self.values: yield item def __add__(self, other): return Vector (* (x + y for x, y in zip (self, other))) def __str__ (self): return str (list (self.values)) #__pragma__ ('opov') autoTester.check (str (Vector (1,2,3) + Vector (3,4,5))) #__pragma__ ('noopov') #__pragma__ ('endif') autoTester.check ('Issue 391') autoTester.check (int (False)) autoTester.check (int (True)) autoTester.check (int (1 == 2)) autoTester.check (int (1 != 2)) autoTester.check ('Issue 392') import re class Example: d = {'A': 1, 'B': 2} rec = re.compile ('(?P<decimal>\d+)', re.ASCII) def run(self): match = self.rec.match ('42') if not match: print('ERROR: RE does not match') e = match.groupdict () autoTester.check ("before: self.d=", self.d) autoTester.check ("before: e=", e) self.d.update (e) autoTester.check ("after: self.d=", self.d) example = Example () example.run ()
def run(autoTester): autoTester.check('Issue 40') autoTester.check(65 / (5 * 2)) autoTester.check('Issue 24') switch = False autoTester.check(switch) autoTester.check('Issue 37') autoTester.check(15 // 7) autoTester.check('Issue 27') autoTester.check(['zero', 'one', 'two', 'three', 'four'].index('three')) autoTester.check('Issue 36') # Workaround for Python closures capturing variables rather than values # An extra enclosing scope is created to remember the value of the variable results = [] for i in range(10): # results.append (lambda: i) # Works nowhere # results.append (lambda j = i: j) # Works only in Python results.append( (lambda j: lambda: j)(i)) # Works in Python and Transcrypt autoTester.check([result() for result in results]) autoTester.check('Issue 50') autoTester.check((240 + 30 - 1) // 30 * 30) autoTester.check('Issue 51') a = 1 b = 1 autoTester.check(a, b, {a, b} == {1, 2}) autoTester.check('Issue 52') switch, case, default = 'switch', 'case', 'default' autoTester.check(switch, case, default) autoTester.check('Issue 54') aDict = {1: 11, 2: 22, 3: 33} autoTester.check(aDict) aDict.clear() autoTester.check(aDict) autoTester.check('Issue 60') three = 3 one = three & 1 seven = three | 4 eight = one << 3 four = eight >> 1 aTrue = bool(three & one) aFalse = bool(three & four) autoTester.check(3, three, 1, one, 7, seven, 8, eight, 4, four, True, aTrue, False, aFalse) autoTester.check('Issue 65') __pragma__('opov') aList = [4, 5, 6] autoTester.check([ 1, 2, 3, ] + aList + [4, 5, 6]) autoTester.check(3 * [1, 2, 3]) autoTester.check([1, 2, 3] * 3) aString = 'Crocodile' autoTester.check('Tiger' + aString + 'Elephant') autoTester.check(3 * aString) autoTester.check(aString * 3) __pragma__('noopov') autoTester.check('Issue 76') initially17 = 17 autoTester.check(initially17) initially17 //= 2 autoTester.check(initially17) initially17 //= 2 autoTester.check(initially17) autoTester.check('Issue 112') try: if __envir__.executor_name == __envir__.transpiler_name: # CPython doesn't know Int8Array x = __new__(Int8Array(2)) else: x = [None, None] x[0] = 3 x[1] = 2 for i in x: autoTester.check(i) # Since JavaScript 5 gives no exception for a loop over a non-iterable, following code must only be executed for JavaScript 6 # Since Transcrypt doesn't get to see all modules loaded by CPython, __ifdef__ cannot be made to do its thing for all modules in an efficient way for CPython # But a normal 'if' will work if '__esv6__' in __symbols__: y = 3 for j in y: autoTester.check(j) except: # No 'Exception' can be used behind this, since this is a JavaScript exception, and no subclass of Exception. ??? How desirable is this behaviour? pass # autoTester.check ('Detected iterating over non-iterable') # Minifier masks this exception, so we'll have to pass if '__esv6__' in __symbols__: # "if" rather than "__pragma__ ('ifdef')" because CPython doesn't understand pragma's autoTester.check('Issue 122') def chunks(aList, chunkLength): for index in range(0, len(aList), chunkLength): yield aList[index:index + chunkLength] for chunk in chunks([chr(index + 97) for index in range(26)], 10): autoTester.check(chunk) autoTester.check('Issue 123') autoTester.check(10 % 3, 10 % -3, -10 % 3, -10 % -3, 10 % 10, 10 % -10, -10 % 10, -10 % -10) autoTester.check('Issue 125') abc = 'abc' for index in abc: autoTester.check(abc)