Пример #1
0
def load_visible_macs():
    console.log("load_visible_macs")
    rows = document['devices'].getElementsByTagName('tr')

    l = len(rows)
    start = 0
    stop = l
    while True:
        if stop - start <= 1:
            break
        row = rows[(start + stop) // 2]
        if row.getBoundingClientRect().top <= 0:
            start = (start + stop) // 2
        else:
            stop = (start + stop) // 2

    for n in range(start, l):
        row = rows[n]
        if not is_scrolled_into_view(row):
            break

        for cell in row.getElementsByTagName('td'):
            if cell.getAttribute('class') == 'mac_address':
                mac = str(cell.textContent).strip().lower()
                if mac and all((_ch in '0123456789abcdef:')
                               for _ch in mac) and (mac not in loaded_devices):
                    load_device_details(mac)
                break
        else:
            continue
def handleApplyButtonClick(evt):
	# get selected operator.
	global Operators, opSelect, current_state, STATE_STACK
	global BACKTRACK_BUTTON, RESET_BUTTON

	# Get Operators
	i = opSelect.selectedIndex
	op = Operators[i]
	#sendBack = recieveNewState
	
	if (type(op) is Operator): # Get state straight from the operator
		new_state = op.state_transf(current_state)
		recieveNewState(new_state)
		
	elif (type(op) is AsyncOperator): #Pass it function to get new state

		try:	
			# Gives the state transfer function the new state.
			# receiveNewState that you see above
			# is the callback function called when 
			# op.state_transf finishes execution.
			op.state_transf(current_state,recieveNewState)
			
		except (Exception) as e:
			alert("An error occured when applying this operator. Error: "+str(e))		
	else:
		console.log("apples")
Пример #3
0
def input_field_keyup(event):
    if event.which == 13:
        if __debug__:
            console.log("input_field_keyup <enter>")
        if event.target.name not in input_fields:
            input_field_modified(event)
        input_field_activate(event)
Пример #4
0
 def attempt():
   console.log('connecting...')
   self.socket = websocket.WebSocket(WS_URL)
   self.socket.bind('message', on_message)
   self.socket.bind('open', on_open)
   self.socket.bind('close', wait_retry)
   self.socket.bind('error', lambda event: console.log(event))
Пример #5
0
def max_event(e):
    global tree
    r, m = tree.maxVis(tree.root)
    console.log(r, m)
    document['output'].text = ""
    document['output'] <= html.DIV(m, id="value")
    document['output'] <= html.DIV(r, id="path")
Пример #6
0
 def echo(req):
     """ write return value to consoel """
     try:
         txt = getattr(req, 'response')
         console.log(txt)
     except:
         console.log(req)
Пример #7
0
def main():
    global board_size
    board_size = 3
    global t
    t = ttt.TTT(board_size)
    console.log(t.get_board())
    display_board(t, board_size, None, None)
Пример #8
0
 def echo(req):
     """ write return value to consoel """
     try:
         txt = getattr(req, 'response')
         console.log(txt)
     except:
         console.log(req)
def destroy_menu(menuName,enabled = True):	
	if(enabled):
		enableOpSelect()
	try:
		menu = document.getElementById(menuName)
		gui.removeChild(menu)
	except:
		console.log("Destroy menu was called on a nonexistent object.")
Пример #10
0
def delete_event(e):
    global tree
    value = document['delete'].value
    value = int(value)
    tree.delete(value, tree.root)
    result = tree.toDICT(tree.root)
    console.log(result)
    update_tree(tree.root)
Пример #11
0
    def on_select(self, event):
        """ callback to show attributes for selected element """
        refid, symbol = self._selected(event)

        if not refid:
            return

        console.log('on_select', refid, symbol)
Пример #12
0
def get_user_info(ev):
    req = ajax.Ajax()
    req.bind('complete', on_complete)
    req.open('GET', '172.16.3.86:8080/')
    sel = document['user_id'].options
    selected = [option.value for option in sel if option.selected]
    console.log(selected[0])
    req.send()
Пример #13
0
 def connect(self):
   if USE_WEBSOCKETS:
     # Set up websockets
     self.try_ws_connect()
   else:
     # Poll every second if websockets aren't supported
     console.log('No websockets. Polling via AJAX.')
     self.send('update')
     timer.set_interval(lambda: self.send('update'), 1000)
Пример #14
0
def incr(event, element):
    console.log(
        event
    )  #imprime o console.log do javascript a função event( o que ta acontecendo )

    #Vai pegar o elemento com a tag: {myname}
    #document['write'], vai pegar o elemento com id='write', usando '.value' pega o valor do input
    element.data.counter += 1
    pass
Пример #15
0
def syntax_error(args):
    trace = Trace()
    info, filename, lineno, offset, line = args
    console.log("args", args)
    trace.write(f"  File {filename}, line {lineno}\n")
    trace.write("    " + line + "\n")
    trace.write("    " + offset * " " + "^\n")
    trace.write("SyntaxError:", info, "\n")
    return trace.buf
Пример #16
0
def dsw_event(e):
    global tree
    if treeType == 'AVL':
        alert("You cannot run DSW for AVL tree.")
        return
    tree.dsw(tree.root)
    result = tree.toDICT(tree.root)
    console.log(result)
    update_tree(tree.root)
Пример #17
0
def bind_os_delete_button(button):
    console.log("bind_os_delete_button" + button.name)
    delete_buttons.add(button.name)

    def os_delete_clicked(event):
        console.log("os_delete_clicked " + event.target.name)
        if document['show_os_delete'].checked:
            delete_os_entry(event)

    button.bind('click', os_delete_clicked)
Пример #18
0
def get_pos():
    global _canvas
    if _canvas is None:
       _c=document.get(selector='canvas')
       if len(_c) > 0:
          _canvas=_c[0]
          console.log(_canvas.id)
          _canvas.mousemove=_getMousePosition

    return _mouse_x, _mouse_y
Пример #19
0
 def check(self, assertion):
     assertion_type = assertion[0]
     data = assertion[1]
     if assertion_type == "match":
         return data in self.result
     elif assertion_type == "no_match":
         return data not in self.result
     else:
         console.log("Don't know assertion type", assertion_type)
     return False
Пример #20
0
def take_move(event):
    global t
    global board_size
    # console.log(event.target['data-x'])
    # console.log(event.target['data-y'])
    player_index = t.whose_turn()
    won = t.take(int(event.target['data-x']), int(event.target['data-y']))
    console.log(t.get_board())
    clear_board()
    display_board(t, board_size, check_won, (won, player_index))
Пример #21
0
def read_pages(presentation_file):
    lines = open(presentation_file).readlines()
    footer_text = None
    page_datas = []
    page_options = []
    page_htmls = []
    page_scripts = []
    code_spec, code_block = None, []
    text_block = []
    config_data = None
    in_header = True

    def flash_text_block():
        marked, scripts = markdown.mark('\n'.join(text_block))
        page_htmls.append(marked)
        page_scripts.extend(scripts)
        text_block[:] = []

    if lines and not lines[-1].startswith("!SLIDE"):
        lines.append("!SLIDE")  # sentinel

    for li, L in enumerate(lines):
        if L.startswith("!SLIDE"):
            if code_spec is not None:
                page_htmls.append(escape_code_block(code_spec, code_block))
                code_spec, code_block = None, []
            if text_block:
                if in_header:
                    config_data = json.loads(''.join(text_block))
                    text_block[:] = []
                else:
                    flash_text_block()
                    page_datas.append(('\n'.join(page_htmls), page_scripts))
            option_strs = L.split()[1:]
            for s in option_strs:
                if s not in SLIDE_OPTIONS:
                    console.log("line %d: invalid option found" % (li + 1))
            page_options.append(option_strs)
            in_header = False
            page_htmls = []
        elif L.startswith("```"):
            if text_block:
                flash_text_block()
            if code_spec is None:
                code_spec, code_block = L[len("```"):].strip(), []
            else:
                page_htmls.append(escape_code_block(code_spec, code_block))
                code_spec, code_block = None, []
        else:
            if code_spec is not None:
                code_block.append(L)
            else:
                text_block.append(L)

    return page_datas, config_data, page_options
Пример #22
0
def insert_event(e):
    global tree
    value = document['insert'].value
    value = int(value)
    if treeType == 'AVL':
        tree.insert(avl.Leaf(value), tree.root)
    elif treeType == 'BST':
        tree.insert(bst.Leaf(value), tree.root)
    result = tree.toDICT(tree.root)
    console.log(result)
    update_tree(tree.root)
Пример #23
0
def extend_options_list(name, value):
    if not value:
        return
    console.log("extend_options_list " + name + " '" + value + "'")
    options_list = document[name]
    value_set = set()
    for option in options_list.getElementsByTagName('option'):
        value_set.add(option.getAttribute('value'))
    if value not in value_set:
        option = options_list.appendChild(document.createElement('option'))
        option.setAttribute('value', value)
Пример #24
0
 def _decorator(coro_func):
     console.log("Registering test", coro_func.__name__)
     fut = asyncio.ensure_future(coro_func())
     self._tests.append((coro_func.__name__, fut))
     if timeout_sec is not None:
         timeout_at = self._loop.time()+timeout_sec
         handle = self.MASTER_LOOP.call_at(timeout_at, 
             self._set_exception_if_not_done, fut, asyncio.TimeoutError())
         fut.add_done_callback(lambda *args: handle.cancel())
         if timeout_at > self._global_timeout_at:
             self._global_timeout_at = timeout_at
     return coro_func
Пример #25
0
    def error_message(self, failure):
        assertion_type = failure[0]
        data = failure[1]

        if assertion_type == "match":
            text = "Expected to see **{expected}**, but didn't see it"
            return text.format(input=self.input, expected=data)
        elif assertion_type == "no_match":
            text = "Saw **{expected}** when it wasn't expected"
            return text.format(input=self.input, expected=data)
        else:
            console.log("Don't know test type", assertion_type)
Пример #26
0
def lookup(encoding):
    """lookup(encoding) -> CodecInfo
    Looks up a codec tuple in the Python codec registry and returns
    a CodecInfo object."""

    if encoding in ('utf-8', 'utf_8'):
       from browser import console
       console.log('encoding', encoding)
       import encodings.utf_8
       return encodings.utf_8.getregentry()

    LookupError(encoding)
Пример #27
0
def stop(click):
    global playing, idtimer
    timer.clear_timeout(idtimer)

    document['stop-btn'].unbind('click', stop)
    document['stop-btn'].id = "start-btn"
    document['start-btn'].bind('click', start)
    document['start-btn'].text = "START"

    console.log("Stop game of life execution")
    playing = False
    pass
Пример #28
0
    def img_onload(*args):
        #http://www.jaypan.com/tutorial/javascript-passing-arguments-anonymous-functions-without-firing-function
        #the onload files very slow so variables get messed up so we have
        #to use args[0].path[0] to figure out the correct image
        console.log(args)
        if hasattr(args[0], 'target'):  # Firefox
            this = args[0].target
        else:  #chrome
            this = args[0].path[0]

        this.canvas.width = this.width
        this.canvas.height = this.height
        this.canvas.getContext('2d').drawImage(this, 0, 0)
Пример #29
0
    def dispatch(self, event):

        console.log(event.data)

        command, args = self.parse(event.data)
        actions = self._events.get(command)
        if actions:
            if args:
                for action in actions:
                    action(args)
            else:
                for action in actions:
                    action()
Пример #30
0
def bind_show_os_delete_button():
    console.log("bind_show_os_delete_button")

    def show_os_delete_changed(event):
        for delete_button in set(delete_buttons):
            try:
                if event.target.checked:
                    document[delete_button].style.opacity = "1"
                else:
                    document[delete_button].style.opacity = "0"
            except KeyError:
                delete_buttons.remove(delete_button)

    document['show_os_delete'].bind('check', show_os_delete_changed)
Пример #31
0
def parse_trans(delta, attrs):
    if delta > 0: delta = 1
    elif delta < 0: delta = -1
    for attr in attrs:
        if attr.startswith("trans-"):
            a_s = _trans_tbl.get((delta, attr), None)
            if a_s is not None:
                return a_s
            else:
                console.log("invalid page-transition specifier: " + attr + "\n");
    if delta > 0:
        return "right", False
    else:
        return "left", False
Пример #32
0
 def f(*args, **kw):
     try:
         return func(*args, **kw)
     except Exception as exc:
         msg = ''
         try:
             if exc.args:
                 msg = '{0.info}\n{0.__name__}: {0.args[0]}'.format(exc)
             else:
                 msg = str(exc)
             import sys
             sys.stderr.write(msg)
         except Exception as exc2:
             console.log("Error printing exception traceback", exc2, func, args, kw)
Пример #33
0
    def os_deleted(response):
        invalidate_devices_list()

        if response.status != 204:
            console.log("Request failed: " + str(response.status))
            return

        console.log("remove " + os_hash)

        os_name = None
        for tr in document['operatingsystems'].getElementsByTagName('tr'):
            for td in tr.getElementsByTagName('td'):
                if td.getAttribute('class') == 'os_name':
                    buttons = td.getElementsByTagName('button')
                    if len(buttons):
                        button = buttons[0]
                        console.log("" + button.tagName)
                        if button.getAttribute('name') == event.target.name:
                            console.log("removing " + event.target.name)
                            os_name = node_text(td).strip()
                            tr.parentNode.removeChild(tr)
                            break
            else:
                continue
            break

        for option in document['opsys_name'].getElementsByTagName('option'):
            if option.getAttribute('value') == os_name:
                option.parentNode.removeChild(option)
Пример #34
0
def switch_card_sources (evt = None) :
	'switch to the next set of card source images'

	old = CARD_SOURCES [pos]

	global pos
	pos = (pos + 1) % len (CARD_SOURCES)
	card_dir = CARD_SOURCES [pos]

	new = card_dir
	console.log (f'switching deck from { old } to { new }')

	global app

	# use copyOfDeck because deck is empty and getting cards from board
	# doesnt get aces

	#cards = app._board.getAllCards ()
	#cards = app._deck.getCards ()
	cards = app._copyOfDeck.getCards ()
	debug (f'cards = { cards }')

	for card in cards:

		# erase old card image from board
		image = app._card2ImgDict [ id (card) ]
		image.erase ()

		# load new card image
		image_name = card_name (card)
		card_url = card_dir + image_name

		#cardimg = CardImg (card, app._canv)
		cardimg = image
		fabric.Image.fromURL (card_url , cardimg._onload)

		# update mapping from card to image

		app._card2ImgDict [ id (card) ] = cardimg

		debug (f'card = { card } : { image_name }')
		debug (f'new url = { card_url }')

	# update mapping and redraw board

	app._boardGui._card2ImgDict = app._card2ImgDict
	app._boardGui.displayLayout ()
	app.highlightMovableCards ()
	app.markGoodCards ()
Пример #35
0
 def f(*args, **kw):
     try:
         return func(*args, **kw)
     except Exception as exc:
         msg = ''
         try:
             if exc.args:
                 msg = '{0.info}\n{0.__name__}: {0.args[0]}'.format(exc)
             else:
                 msg = str(exc)
             import sys
             sys.stderr.write(msg)
         except Exception as exc2:
             console.log("Error printing exception traceback", exc2, func,
                         args, kw)
Пример #36
0
def bind_load_visible_devices_on_scroll():
    console.log("load_visible_devices_on_scroll")

    def scrolled_timeout():
        global scrolling_timeout
        scrolling_timeout = None
        load_visible_macs()

    def window_scrolled(event):
        global scrolling_timeout
        if scrolling_timeout:
            clear_timeout(scrolling_timeout)
        scrolling_timeout = set_timeout(scrolled_timeout, 500)

    window.bind('scroll', window_scrolled)
Пример #37
0
def test_simple_coroutine():
    console.log("coro_wait_secs")
    coro_wait_secs = wait_secs(0.1, 10)
    console.log("ensuring future")
    fut = asyncio.ensure_future(coro_wait_secs)

    console.log("asserting")
    assert asyncio.iscoroutine(coro_wait_secs), "Result of running a coroutine function should be a coroutine object"
    assert asyncio.iscoroutinefunction(wait_secs), "asyncio.coroutine decorator should return a coroutine function"
    assert isinstance(fut, asyncio.Future), "ensure_future should return a future"

    console.log("yielding")
    result = yield from fut

    console.log("asserting")
    assert fut.result() == result, "yield from future should return its result"
    assert result == 10, "Future result different from expected"
Пример #38
0
def recieveFile(req):
	if req.status == 200 or req.status == 0:
		# Get the name of the file from the response url
		url = req.responseURL
		sheetMusic = req.text
		console.log(sheetMusic)
		name = 'unknown'
		slashIndex = 0
		for i in range(len(url)):
			char = url[i]
			if (char == '/'):
				slashIndex = i
			elif (char == '.'):
				name = url[slashIndex+1:i]
		
		# Split up the sheet music.
		sheetMusic = [name] + req.text.split("\n")
		songs.append(sheetMusic)
		
	else:
		console.log("error" + req.text)
Пример #39
0
def playSong(music_num):
	console.log(songs[music_num])
	sheetMusic = songs[music_num]
	wait = 0
	
	# The first "note" is the name of the song
	console.log("playing song: " + sheetMusic[0])
	
	# Thus skip the first note when playing the song
	song = iter(sheetMusic)
	next(song)
	
	for note in song:
		values = note.split(" ")
		console.log(values)
		wait = wait + float(values[0])
		pitch = values[1]
		hold = values[2]
		
		#console.log(wait + " " + pitch + " " + sustain)
		piano.play({
			'wait' : wait,
			'pitch' : pitch,
			'env' : {'hold' : float(hold)},
			filter : { 'q' : 15 } 
		})
	def encode(self):
		result = {}
		result["Applicable"] = self.app
		textSplit = self.text.split(" ")
		
		if(textSplit[0] == 'Entered'):
			result["Condition"] = 'Entered Room'
			result["Room"] = int(textSplit[2])
		elif(textSplit[1] == 'puzzle'):
			if(textSplit[0] == 'Solved'):
				result["Condition"] = 'Solved puzzle'
			else:
				result["Action"] = 'Unsolve puzzle'
			result["Room"] = int(textSplit[4])
			result["Wall"] = textSplit[6]
		elif(textSplit[0] == 'Had'):
			result["Condition"] = 'Had Points'
			result["Points"] = int(textSplit[1])
		elif(textSplit[1] == 'minutes'):
			result["Condition"] = 'Minutes elapsed'
			result["Minutes"] = int(textSplit[0])
		elif(textSplit[1] == 'door'):
			result["Action"] = textSplit[0] + ' a door between two rooms'
			result["Room"] = int(textSplit[4])
			result["Room2"] = int(textSplit[6])
		elif(textSplit[0] == 'Display'):
			result["Action"] = 'Display a message'
			result["Message"] = textSplit[2]
			for i in range(3, len(textSplit)):
				result["Message"] += " " + textSplit[i]
		elif(textSplit[1] == 'Sound'):
			result["Action"] = 'Play sound from URL'
			result["URL"] = textSplit[4]
		elif(textSplit[2] == 'Points'):
			result["Action"] = textSplit[0] + " points"
			result["Points"] = int(textSplit[1])
		console.log(result)	
		return result
def create_json(state):
	global SOLUZION_VERSION, PROBLEM_NAME, PROBLEM_VERSION, PROBLEM_AUTHORS, PROBLEM_DESC
	
	#get the current date
	now = datetime.datetime.today()
	day = str(now.day)
	month = str(now.month)
	year = str(now.year)
	
	creationDate = month + '-' + day + '-' + year
	
	stateJSON = {"Soluzion Version" : SOLUZION_VERSION, "Problem Name" : PROBLEM_NAME, 
				 "Problem Version" : PROBLEM_VERSION, "Problem Authors"  : PROBLEM_AUTHORS, 
				 "Problem Creation Date" : creationDate, "Problem Description" : PROBLEM_DESC}
	
	#Rooms
	stateJSON["Rooms"] = []
	for room in state["Rooms"]:
		stateJSON["Rooms"].append(room.encode())
		#looks like stateJson = {"Rooms" : {1 : room1, 2 : room2, etc}, etc}

	stateJSON["Rules"] = []
	for rule in state["Rules"]:
		stateJSON["Rules"].append(rule.encode())
	
	stateJSON["Puzzles"] = {}
	for puzzle in state["Image_Puzzles"]:
		stateJSON["Puzzles"][puzzle] = state["Image_Puzzles"][puzzle].encode()
		
	for puzzle in state["Music_Puzzles"]:
		stateJSON["Puzzles"][puzzle] = state["Music_Puzzles"][puzzle].encode()	
	
	window.state_JSON = json.dumps(stateJSON)
	#console.log(window.state_JSON)
	
	req = ajax.ajax()
	req.bind('complete', lambda e: console.log('finished on brython side'))
	req.open('POST', 'dependencies//jsonPatch.php', True)
	req.set_header('content-type','application/x-www-form-urlencoded')
	req.send({'stateJSON' : window.state_JSON})
Пример #42
0
async def wait_secs(s, result):
    await asyncio.sleep(s)
    console.log("Returning result", result)
    return result
Пример #43
0
	#console.log(req.readyState)
	req.send()
	return saying
	
#console.log(get().text)
#def sayingHasChanged(saying):
#	Sayings.append(saying)

#def getSaying():
#	get()
#	saying = Sayings[0]
#	Sayings[:] = []
#	return saying

saying = get()
console.log(saying)
#saying = getSaying()
#console.log(saying)












Пример #44
0
	def regularSuccess(rec):
		console.log(rec.text)
		console.log(param1)
		console.log(param2)
Пример #45
0
 def click_handler(self,*args,**kwargs):
     for (k,v) in kwargs.items():
         console.log(k,":",v)
     for a in args:
         console.log(a)
     self.message = 'Clicked'
Пример #46
0
def test_calls(iterations):
    from browser import console
    times = []
    for _i in range(iterations):
        console.log("iteration: %s" % _i)
        t0 = time.time()
        # 40 calls
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        foo(1, 2, 3, 4)
        t1 = time.time()
        times.append(t1 - t0)
    return times
Пример #47
0
 def err_msg(*args):
     from browser import console
     console.log(args)
Пример #48
0
 def ngOnInit(self):
     console.log("Initializing Service Component for", self.service, "at", self.url)
     self.rpc = yield RPCClientFactory.get_client(self.service,self.url)
     self.methods = self.rpc.methods
     console.log("METHODS:",self.methods)
Пример #49
0
 def call_method(self,*args,**kwargs):
     console.log("Calling method ", self._name, "with args", self.args)
     self.result = yield self.meth(*self.args)