Beispiel #1
0
def tag_clicked_img(event):
    tag = event.target.text
    # filepath = event.target.parent.parent.children[0].innerText
    # filepath = event.target.parent.children[0].src
    filepath = event.target.parent.parent.children[-1].innerText
    # print("ouawadiyo",dir(event.target))
    print(filepath, tag)
    # if filepath in tagged and tag in tagged[filepath]: # untag
    if filepath in tags_by_path and tag in tags_by_path[filepath]: # untag
        req = ajax.ajax()
        req.open("POST", "/untag/", True)
        req.bind("complete", untag_clicked_cb)

        sendthis = repr((filepath, tag))
        print(sendthis)
        req.send(sendthis)

        untag_this(filepath,tag)
        event.target.classList = "microtext"

    else:
        req = ajax.ajax()
        req.open("POST", "/tag/", True)
        req.bind("complete", tag_clicked_cb)

        sendthis = repr((filepath, tag))
        print(sendthis)
        req.send(sendthis)

        tag_this(filepath,tag)
        event.target.classList = "microtext tagged"
Beispiel #2
0
def onKeyDown(key):
  if key in "123456789":
    if not data.board[data.selectRow][data.selectCol][1]:
      data.board[data.selectRow][data.selectCol] = [key, False, []]
  elif key == "Up":
    data.selectRow = (data.selectRow - 1) % data.rows
  elif key == "Down":
    data.selectRow = (data.selectRow + 1) % data.rows
  elif key == "Right":
    data.selectCol = (data.selectCol + 1) % data.cols
  elif key == "Left":
    data.selectCol = (data.selectCol - 1) % data.cols
  elif key == "Backspace":
    data.board[data.selectRow][data.selectCol] = [0, False, []]
  elif key == "s":
    POST_URL = "http://128.237.212.209:8080/"
    req = ajax.ajax()
    req.bind('complete', onMessageSend)
    req.open('POST', POST_URL, True)
    data = {'message': 'testing if message sending works'}
    req.send(data)
  elif key == "g":
    GET_URL = "http://128.237.212.209:8080/echo"
    req = ajax.ajax()
    req.bind('complete', onMessageRecieve)
    req.open('GET', GET_URL, True)
    req.send({"woooho":"woo"})
  data.currNumber = data.board[data.selectRow][data.selectCol][0]
Beispiel #3
0
def urlopen(url, data=None, timeout=None):
    global result
    result = None

    def on_complete(req):
        global result
        if req.status == 200:
            result = req

    _ajax = ajax.ajax()
    _ajax.bind('complete', on_complete)
    if timeout is not None:
       _ajax.set_timeout(timeout)

    if data is None:
       _ajax.open('GET', url, False)
       _ajax.send()
    else:
       _ajax.open('POST', url, False)
       _ajax.send(data)

    if result is not None:
        if isinstance(result.text, str):
           return FileIO(result.text) #, url, {'status': result.status}
    
        return FileIO(result.text()) #, url, {'status': result.status}
    raise error.HTTPError('file not found')
Beispiel #4
0
def run(in_globals=False):
    global output
    doc["console"].value = ''
    src = editor.getValue()
    if storage is not None:
       storage["py_src"] = src

    t0 = time.perf_counter()
    try:
        if(in_globals):
            exec(src)
        else:
            ns = {}
            exec(src, ns)
        state = 1
    except Exception as exc:
        traceback.print_exc(file=sys.stderr)
        state = 0
    output = doc["console"].value

    print('Brython: %6.2f ms' % ((time.perf_counter() - t0) * 1000.0))
    
    # run with CPython
    req = ajax.ajax()
    req.bind('complete',on_complete)
    req.set_timeout(4,err_msg)
    req.open('POST','/cgi-bin/speed.py',True)
    req.set_header('content-type','application/x-www-form-urlencoded')
    req.send({'src':src})
    
    return state
 def send(self, msg, callback):
     POST_URL = "http://128.237.212.209:8080/"
     req = ajax.ajax()
     req.bind('complete', lambda data: self.callback(data))
     req.open('POST', POST_URL, True)
     data = {'message': 'testing if message sending works'}
     req.send(msg)
def requestFile(url):
	
	req = ajax.ajax()
	req.bind("complete",mySuccess("hello","goodbye"))
	req.set_timeout(timeout,err_msg)
	req.open('GET',url,True)
	req.send()
Beispiel #7
0
def send():
    req = ajax.ajax()
    req.bind('complete',on_complete)
    req.open(document['req_method'].value, '/ajax', True)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
    req.send({'param_name': 'param_value'})
Beispiel #8
0
 def __init__(self, idAli, cb):
     DIALOG.__init__(self)
     tab = TABLE()
     self <= tab
     self.callback = cb
     #self.inText = INPUT(Class="form-control")
     #self.inText.bind('keyup',self.entrou)
     #tab<=TR(TD('Peso (g):')+TD(self.inText))
     self.sel = SELECT(Class='form-control',
                       size=8)  # style={'max_width':'90px'})
     ##self.sel.bind('input',self.selected)
     #tab<=TH("Escolha medida", colspan=2)
     self.inMedQty = INPUT(Class="form-control", size=4)
     tab <= TR(TD('Medida caseira, quantidade') + TD(self.inMedQty))
     tab <= TR(TD(self.sel, colspan=2))
     add = SPAN(Class='glyphicon glyphicon-ok-circle')
     add.bind('click', self.added)
     can = SPAN(Class='glyphicon glyphicon-remove-circle')
     can.bind('click', self.cancelled)
     tab <= TR(
         TD(can, style={
             'text-align': 'right',
             'padding': '6pw'
         }) + TD(add, style={
             'text-align': 'center',
             'padding': '6pw'
         }))
     req = ajax.ajax()
     req.bind('complete', self.complete)
     req.open('POST', '/nutsvc', True)
     req.set_header('content-type', 'application/x-www-form-urlencoded')
     d = {'op': 'MEDIDAS', 'q': idAli}
     req.send(d)
Beispiel #9
0
def load_device_details(mac):
    s_mac = mac.replace(':', '').lower()
    ajax_request = ajax.ajax()
    ajax_request.bind('complete',
                      lambda response: device_details_loaded(response, mac))
    ajax_request.open('GET', '/device/' + s_mac, True)
    ajax_request.send()
Beispiel #10
0
	def __init__(self, idAli, cb):
		DIALOG.__init__(self)
		tab = TABLE()
		self<=tab
		self.callback = cb
		#self.inText = INPUT(Class="form-control")
		#self.inText.bind('keyup',self.entrou)
		#tab<=TR(TD('Peso (g):')+TD(self.inText))
		self.sel = SELECT(Class='form-control', size=8)     # style={'max_width':'90px'})
		##self.sel.bind('input',self.selected)
		#tab<=TH("Escolha medida", colspan=2)
		self.inMedQty = INPUT(Class="form-control", size=4)
		tab<=TR(TD('Medida caseira, quantidade')+TD(self.inMedQty))
		tab <=TR(TD( self.sel, colspan=2))
		add = SPAN( Class='glyphicon glyphicon-ok-circle' )
		add.bind('click',self.added)
		can = SPAN( Class='glyphicon glyphicon-remove-circle' )
		can.bind('click',self.cancelled)
		tab <=TR(TD(can,style={'text-align':'right','padding':'6pw'})+TD(add,style={'text-align':'center','padding':'6pw'}))
		req = ajax.ajax()
		req.bind('complete',self.complete)
		req.open('POST','/nutsvc', True)
		req.set_header('content-type','application/x-www-form-urlencoded')
		d = {'op':'MEDIDAS','q':idAli}
		req.send(d)
Beispiel #11
0
def urlopen(url, data=None, timeout=None):
    global result
    result = None

    def on_complete(req):
        global result
        if req.status == 200:
            result = req

    _ajax = ajax.ajax()
    _ajax.bind('complete', on_complete)
    if timeout is not None:
        _ajax.set_timeout(timeout)

    if data is None:
        _ajax.open('GET', url, False)
        _ajax.send()
    else:
        _ajax.open('POST', url, False)
        _ajax.send(data)

    if result is not None:
        if isinstance(result.text, str):
            return FileIO(result.text)  #, url, {'status': result.status}

        return FileIO(result.text())  #, url, {'status': result.status}
    raise error.HTTPError('file not found')
Beispiel #12
0
def load_opsys_list():
    ajax_request = ajax.ajax()
    ajax_request.bind(
        'complete',
        lambda response: opsys_list_loaded(response, get_details=True))
    ajax_request.open('GET', '/opsys/', True)
    ajax_request.send()
Beispiel #13
0
    def fetch_data(self):
        self.commits = []

        req = ajax.ajax()
        req.open("GET", url.format(self.current_branch), True)
        req.bind("complete", self.loaded)
        req.send()
Beispiel #14
0
def GETu3(vIDs):
    url = link(Url='u3', Id=','.join(vIDs))
    req = ajax.ajax()
    req.bind('complete', DONEu3)
    req.open('GET', url, True)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.send()
Beispiel #15
0
def on_complete(req):
    # ** extract for ID **
    try:
        id_search = str(document.query['id'])  # extract ID
    except:
        id_search = default_demon  # if ID parameter does not exist

    # * Load ID list *
    r_json = json.loads(req.text)  # convert to json
    r_json = r_json['values']  # extract the values section

    # r_json is now an array of IDs with index that is OFF BY ONE compared to row number

    # ** search for the specific ID **
    id_array = []
    id_array.append(id_search)
    try:
        demon_no = r_json.index(id_array)
    except:
        demon_no = -1
    row_no = demon_no + 1

    # ** URL setup **
    row_select = "'The List'!" + str(row_no) + ":" + str(row_no)
    apiurl = "https://sheets.googleapis.com/v4/spreadsheets/1xaMERl70vzr8q9MqElr4YethnV15EOe8oL1UV9LLljc/values/" + row_select + "?key=" + key

    # ** Ajax call setup **
    if demon_no != -1:
        call = ajax.ajax()
        call.bind('complete', on_complete2)
        call.open('GET', apiurl, True)
        call.send()
    else:
        document['levelname'] <= 'There is no demon with the ID ' + str(
            document.query['id']) + '!'
    def run_performance_test(self, src):
        #execute code
        t0 = time.perf_counter()
        try:
            exec(src)
            state = 1
        except Exception as exc:
            traceback.print_exc(file=sys.stderr)

        self.add_brython_result(int((time.perf_counter() - t0) * 1000.0))
        src = src.replace('\r\n', '\n')

        self._timings[self._filename]['code'] = src

        def err_msg(*args):
            from browser import console
            console.log(args)

        #also run this for cpython via cgi-bin
        # run with CPython
        req = ajax.ajax()
        req.bind('complete', self.on_cpython_complete)
        req.set_timeout(4, err_msg)
        req.open('POST', '/cgi-bin/script_timer.py', False)
        req.set_header('content-type', 'application/x-www-form-urlencoded')
        req.send({'filename': self._filename})

        return state
def send_ajax(data, url, method, on_complete):
    # print('send_ajax data:', data)
    req = ajax.ajax()
    req.bind('complete', on_complete)
    req.open(method.upper(), url, True)
    req.set_header('Content-type', 'application/json')
    req.send(json.dumps(data))
Beispiel #18
0
def datasets_by_keyword_search(ev):
    panel = document["main_panel"]
    #document <= panel
    #panel.getValues()
    #root = panel.element.dom
    #x = panel.g12.value
    #keyword = panel.getAttribute("g12")
    #keyword = panel["g12"].value
    #search_in = panel.getAttribute("sel1")
    #search_in = panel["sel1"].value
    #g12 = document["g12"]

    keyword = document["g12"].value
    search_in = document["selector1"].value

    #keyword = g12.value
    #search_in = sel1.value

    #document <= keyword
    #document <= search_in

    req = ajax.ajax()
    req.bind('complete', onComplete)
    req.open('POST', "cgi-bin/microarray_server.py", True)
    req.set_header('content-type', 'application/json')
    #req.set_header('Access-Control-Allow-Origin', '*')
    req.send(
        json.dumps({
            'mode': 'datasets_by_keyword',
            'keyword': keyword,
            'search_in': search_in
        }))

    status_indicator_computing(1)
Beispiel #19
0
def register_new_os(osname):
    def os_hash_generated(response):
        if response.status != 200:
            console.log("Request failed: " + str(response.status))
            return

        result_hash = None
        parser = window.DOMParser.new()
        tree = parser.parseFromString(response.text, 'application/xml')
        opsys_root = tree.getElementsByTagName('operating_systems')[0]
        for os in opsys_root.getElementsByTagName('operating_system'):
            if str(os.textContent).strip() == osname:
                result_hash = os.getAttribute('hash')
                break

        if result_hash:
            opsys_list_loaded(response, put_details=True)

    ajax_request = ajax.ajax()
    ajax_request.bind('complete', os_hash_generated)
    ajax_request.open('POST', '/opsys/', True)
    ajax_request.set_header('Content-Type', 'text/xml;charset=utf-8')

    os_root = document.createElement('operating_systems')
    os_entry = os_root.appendChild(document.createElement('operating_system'))
    os_entry.appendChild(document.createTextNode(osname))

    ajax_request.send(remove_xmlns(os_root.outerHTML))
Beispiel #20
0
def click_search2(ev):
    select_probe_or_gene = document["select_probe_or_gene"]
    input_probe_or_gene = document["input_probe_or_gene"]
    selector_min_sample_size = document["selector_min_sample_size"]
    selector_max_pvalue = document["selector_max_pvalue"]
    selector_max_num_results = document["selector_max_num_results"]

    req = ajax.ajax()
    req.bind('complete', onComplete)
    req.open('POST', "cgi-bin/microarray_server.py", True)
    req.set_header('content-type', 'application/json')

    if select_probe_or_gene.value == "gene name":
        req.send(
            json.dumps({
                'mode': "pvalues_by_gene",
                'gene': input_probe_or_gene.value,
                'max_pvalue': selector_max_pvalue.value,
                'max_num_results': selector_max_num_results.value,
                'min_sample_size': selector_min_sample_size.value
            }))
        status_indicator_computing(1)

    elif select_probe_or_gene.value == "probe name":
        req.send(
            json.dumps({
                'mode': "pvalues_by_probe",
                'probe': input_probe_or_gene.value,
                'max_pvalue': selector_max_pvalue.value,
                'max_num_results': selector_max_num_results.value,
                'min_sample_size': selector_min_sample_size.value
            }))
        status_indicator_computing(1)
Beispiel #21
0
 def save_vote(self, *args):
     req = ajax.ajax()
     req.open('GET',
         window.root_url +
         '/save_vote/?' + self.save_vote_query() +
         '&callback=?')
     req.send()
def GETu2():
    url = link(Url='u2', Id=Cooked[4])
    req = ajax.ajax()
    req.bind('complete', DONEu2)
    req.open('GET', url, True)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.send()
Beispiel #23
0
 def __init__(self, url, method='GET', data=None, **kwargs):
     self._url = url
     self._req = ajax.ajax()
     self._req.bind("complete", self._complete_handler)
     self._data = data
     self._method = method
     super(HTTPRequest, self).__init__(**kwargs)
Beispiel #24
0
def run(in_globals=False):
    global output
    doc["console"].value = ''
    src = editor.getValue()
    if storage is not None:
        storage["py_src"] = src

    t0 = time.perf_counter()
    try:
        if (in_globals):
            exec(src)
        else:
            ns = {}
            exec(src, ns)
        state = 1
    except Exception as exc:
        traceback.print_exc(file=sys.stderr)
        state = 0
    output = doc["console"].value

    print('Brython: %6.2f ms' % ((time.perf_counter() - t0) * 1000.0))

    # run with CPython
    req = ajax.ajax()
    req.bind('complete', on_complete)
    req.set_timeout(4, err_msg)
    req.open('POST', '/cgi-bin/speed.py', True)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.send({'src': src})

    return state
Beispiel #25
0
        def on_submit(event):
            event.preventDefault()
            name = document['org_name_field'].value
            boards = [o.value for o in input2 if hasattr(o, 'selected') and o.selected]
            users = [o.value for o in input3 if hasattr(o, 'selected') and o.selected]
            owner = getApiLink('users', document['body'].__getattribute__('data-userid'))
            if name and boards and users:
                data = {
                    'name': name,
                    'boards': boards,
                    'users': users,
                    'owner': owner
                }
                def on_complete(response):
                    if response.status == 201:
                        hide_modal()
                    else:
                        alert(response.text)

                req2 = ajax.ajax()
                req2.bind('complete', on_complete)
                req2.open('POST', '/api/organizations/?format=json', True)
                req2.set_header('content-type', 'application/x-www-form-urlencoded')
                req2.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                req2.send(data)
  def run_performance_test(self, src):
      #execute code
      t0 = time.perf_counter()
      try:
        exec(src)
        state = 1
      except Exception as exc:
        traceback.print_exc(file=sys.stderr)

      self.add_brython_result(int((time.perf_counter() - t0) * 1000.0))
      src = src.replace('\r\n','\n')
      
      self._timings[self._filename]['code'] = src

      def err_msg(*args):
          from javascript import console
          console.log(args)

      #also run this for cpython via cgi-bin
      # run with CPython
      req = ajax.ajax()
      req.bind('complete',self.on_cpython_complete)
      req.set_timeout(4,err_msg)
      req.open('POST','/cgi-bin/script_timer.py',False)
      req.set_header('content-type','application/x-www-form-urlencoded')
      req.send({'filename': self._filename})

      return state
Beispiel #27
0
 def entrou(self, event):
     if event.which == 13:
         req = ajax.ajax()
         req.bind('complete', self.complete)
         req.open('POST', '/nutsvc', True)
         req.set_header('content-type', 'application/x-www-form-urlencoded')
         d = {'op': 'QUERY', 'q': event.currentTarget.value}
         req.send(d)
Beispiel #28
0
	def mostra(self, idNut):
		self.style.display='block'
		req = ajax.ajax()
		req.bind('complete',self.completeFetch)
		req.open('POST','/nutsvc', True)
		req.set_header('content-type','application/x-www-form-urlencoded')
		d = {'op':'FETCH','q':idNut}
		req.send(d)
Beispiel #29
0
	def entrou(self, event):
		if event.which==13:
			req = ajax.ajax()
			req.bind('complete',self.complete)
			req.open('POST','/nutsvc', True)
			req.set_header('content-type','application/x-www-form-urlencoded')
			d = {'op':'QUERY','q':event.currentTarget.value}
			req.send(d)
Beispiel #30
0
 def mostra(self, idNut):
     self.style.display = 'block'
     req = ajax.ajax()
     req.bind('complete', self.completeFetch)
     req.open('POST', '/nutsvc', True)
     req.set_header('content-type', 'application/x-www-form-urlencoded')
     d = {'op': 'FETCH', 'q': idNut}
     req.send(d)
Beispiel #31
0
 def __init__(self):
     self.ajax = ajax.ajax()
     self.ajax.bind('complete',self.on_complete)
     self.root = __file__[:__file__.rfind('/')]+'/'
     self.append_script(self.root + "music.js")
     self.append_script(self.root + "image.js")
     self.display = Display()
     self.image = Image()
     self.mixer = Mixer()
Beispiel #32
0
 def _get(self, resource, callback=None, errback=None):
     """ _get(resource, callback=None, errback=None): make http GET to backend """
     req = ajax.ajax()
     if callback:
         req.bind('complete', callback)
     else:
         req.bind('complete', self.echo)
     req.open('GET', self.endpoint + resource, True)
     req.send()
Beispiel #33
0
def query(url, callback):
    global Cnt
    url = url + "&nonce=" + str(Cnt)
    Callbacks[url] = callback
    req = ajax.ajax()
    req.open('GET', url, True)
    req.send()
    req.bind('complete', ajax_end)
    Cnt += 1
Beispiel #34
0
def _get(resource, callback=None, errback=None):
    """ _get(resource, callback=None, errback=None): make http GET to backend """
    req = ajax.ajax()
    if callback:
        req.bind('complete', callback)
    else:
        req.bind('complete', echo)
    req.open('GET', _ENDPOINT + resource, True)
    req.send()
Beispiel #35
0
def save():
    req = ajax.ajax()
    req.open("POST", "/save/", True)
    req.bind("complete", save_cb)
    presentation[current] =document["edit"].value
    req.send(repr(presentation))

    html_str, scripts = markdown.mark(presentation[current])
    document["present"].html = html_str
Beispiel #36
0
def click_dataset_id_button(ev):
    b = ev.target
    datasetID = b.gds
    min_sample_size = document["selector_min_sample_size"]
    max_pvalue = document["selector_max_pvalue"]
    max_num_results = document["selector_max_num_results"]
    min_sample_size = min_sample_size.value
    max_pvalue = max_pvalue.value
    max_num_results = max_num_results.value

    req = ajax.ajax()
    req.bind('complete', onComplete)
    req.open('POST', "cgi-bin/microarray_server.py", True)
    req.set_header('content-type', 'application/json')
    req.send(
        json.dumps({
            'mode': 'description_for_dataset',
            'dataset_id': datasetID
        }))

    teq = ajax.ajax()
    teq.bind('complete', onComplete)
    teq.open('POST', "cgi-bin/microarray_server.py", True)
    teq.set_header('content-type', 'application/json')
    teq.send(
        json.dumps({
            'mode': 'subsets_for_dataset',
            'dataset_id': datasetID
        }))

    leq = ajax.ajax()
    leq.bind('complete', onComplete)
    leq.open('POST', "cgi-bin/microarray_server.py", True)
    leq.set_header('content-type', 'application/json')
    leq.send(
        json.dumps({
            'mode': 'pvalues_for_dataset',
            'dataset_id': datasetID,
            'min_sample_size': str(min_sample_size),
            'max_pvalue': str(max_pvalue),
            'max_num_results': str(max_num_results)
        }))

    status_indicator_computing(3)
Beispiel #37
0
def click_filename(event):
    req = ajax.ajax()
    req.open("POST", "/getcontent/", True)
    req.bind("complete", content_cb)
    # print(event.target.parent.children[0].textContent)
    # print('got here')
    # print(event.target.innerText)
    # print(event.target.children[0].innerText)
    # req.send(event.target.children[0].textContent)
    req.send(event.target.parent.children[0].textContent)
Beispiel #38
0
def _archiveTask(task_id):
    link = getApiLink('tasks', task_id)

    req = ajax.ajax()
    req.open('DELETE', link, False)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
    req.send()

    del document['task_' + task_id]
Beispiel #39
0
def _archiveList(lists_id):
    link = getApiLink('boardlists', lists_id)

    req = ajax.ajax()
    req.open('DELETE', link, False)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
    req.send()

    document['tasks_for_list_' + lists_id].parent.style.display = 'none'
def get_table(ev):
    req = ajax.ajax()
    req.bind('complete', update_table)
    # send a POST request to the url
    url = f'/table/{get_selected(industry_name)}/{get_selected(year)}/{get_selected(bedroom)}'
    url = quote(url)
    req.open('GET', url, True)
    #req.set_header('content-type','application/x-www-form-urlencoded')
    # send data as a dictionary
    req.send()
Beispiel #41
0
def add_to_do(ev):
    url = os.path.join(BASE_URL, 'create/')
    text = doc["form_text_input"].value
    req = ajax.ajax()
    req.bind('complete', on_complete)
    # send a POST request to the url
    req.open('POST', url, True)
    req.set_header('content-type','application/x-www-form-urlencoded')
    # send data as a dictionary
    req.send({'text': text })
Beispiel #42
0
def cool_ajax(url: str,
              handler: Callable,
              method: str = 'GET',
              disable_cache: bool = True) -> None:
    request = ajax.ajax()
    if disable_cache:
        url = add_parameters_to_url(url, {'_': random.randint(0, 10**8)})
    request.open(method, url, True)
    request.bind('complete', handler)
    request.send()
Beispiel #43
0
 def __ajax__(fn):
     req = ajax.ajax()
     req.bind('complete', fn)
     req.open('POST', self.url_, True)
     req.set_header('content-type', 'application/x-www-form-urlencoded')
     req.send({
         'name': attr,
         'args': json.dumps(list(args)),
         'kwargs': json.dumps(kwargs),
         'csrfmiddlewaretoken': self.csrftoken
     })
Beispiel #44
0
def star_toggle(event):
    mark = 'star_empty.png' in event.target.src
    set_star(mark)
    selected = [opt for opt in document['boardSelect'] if hasattr(opt, 'value') and opt.value == document['boardSelect'].value].pop()
    selected.data_star = 'true' if mark else 'false'

    req = ajax.ajax()
    req.open('PATCH', getApiLink('boards', selected.value) + '?format=json', True)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
    req.send({'star': mark})
Beispiel #45
0
def getais():
    """
    Makes an AJAX call to get the list of possible AIs

    :return: list of AIs
    """
    req = ajax.ajax()
    req.open('GET', 'getais/', False)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.send()
    return json.loads(req.text)
Beispiel #46
0
def get_json(url, cb):
    def cb_wrap(rsp):
        if rsp.status in (0, 200):
            cb(rsp.json)
        elif rsp.status == 500:
            alert('API error')

    req = ajax.ajax()
    req.bind('complete', cb_wrap)
    req.open('GET', '../' + url, False)
    req.send()
Beispiel #47
0
def getgsb():
    """
    Makes an AJAX call to get the starting board

    :return: 32-element list
    """
    req = ajax.ajax()
    req.open('GET', 'gsb', False)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.send()
    return json.loads(req.text)
Beispiel #48
0
    def fetch(self, url, data=None, callback=None):
        assert self.itemFactory

        req = ajax.ajax()
        req.bind("complete", self._fetchCallback)
        req.callback = callback

        # pass the arguments in the query string
        req.open("POST", url, True)
        req.set_header("content-type", "application/x-www-form-urlencoded")

        req.send(data or {})
Beispiel #49
0
    def upload_pnml(self, name, body, callback=None, errback=None):
        """  upload_pnml(filename, body, callback=None, errback=None): upload xml petri-net definition"""
        req = ajax.ajax()

        if callback:
            req.bind('complete', callback)
        else:
            req.bind('complete', self.echo)

        req.open('POST', self.endpoint + '/petrinet/' + name, True)
        req.set_header('content-type', 'application/xml')
        req.send(body)
Beispiel #50
0
def id_projet_on_input_ajax():
    ba = ajax.ajax()
    ba.bind('complete', id_projet_on_input_on_receipt)
    #ba.open('POST',url,True)
    #ba.set_header('content-type','application/x-www-form-urlencoded')
    #ba.send({'x':0, 'y':1})

    param_get = make_addr_param({"projet": document["id_projet"].value})
    ba.open("GET", "/django/stock_labo/ajax_sample_lab_projet" + param_get,
            True)
    ba.set_header("content-type", "application/x-www-form-urlencoded")
    ba.send()
Beispiel #51
0
def getiswon(board):
    """
    Makes an AJAX call to determine whether the game has been won.

    :param board: 32-element list
    :return: NOWIN, REDWIN, or BLACKWIN
    """
    req = ajax.ajax()
    req.open('get', 'iswon/' + "?board=%s" % json.dumps(board), False)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.send()
    return json.loads(req.text)
Beispiel #52
0
def get_list(ext = 'txt', sortkey = 0):
    print('pulling list', ext)

    current_ext = ext
    req = ajax.ajax()
    req.open("POST", "/list/", True)
    if ext.lower() in ['jpg', 'png', 'gif']:
        req.bind("complete", get_list_mosaic)
        # req.bind("complete", get_list_img)
    else:
        req.bind("complete", get_list_cb)
    req.send(repr([ext, sortkey]))
Beispiel #53
0
def run(in_globals=False):
    global output
    global result
    doc["console"].value = ''
    src = editor.getValue()
    if storage is not None:
       storage["py_src"] = src

    t0 = time.perf_counter()
    ns = {}
    try:
        if(in_globals):
            exec(src)
        else:
            exec(src, ns)
        state = 1
    except Exception as exc:
        traceback.print_exc(file=sys.stderr)
        state = 0
    output = doc["console"].value

    brython_time = (time.perf_counter() - t0) * 1000.0


    print(TIME_FORMAT_STRING % ('Brython', brython_time))
    result = {'Brython': '%6.2f' % brython_time}

    # run with CPython
    req = ajax.ajax()
    req.bind('complete', on_complete)
    req.set_timeout(4, err_msg)
    req.open('POST', '/time_cpython', False)
    req.set_header('content-type','text/plain')
    req.send(src)

    # run Javascript version, if it exists
    js_src = None
    if in_globals:
        print('\nCan\'t run JS_CODE if in_globals is True')
    else:
        js_src = ns.get('JS_CODE')

    if js_src:
        t0 = time.perf_counter()
        window.eval(js_src)
        js_time = (time.perf_counter() - t0) * 1000.0
        print(TIME_FORMAT_STRING % ('JS', js_time))
        result['JS'] = '%6.2f' % js_time
    else:
        print('\nStore Javascript code in a global named JS_CODE and I will run it for you')

    return state, result
Beispiel #54
0
    def _rpc(self, method, params=[], callback=None, errback=None):
        """  _rpc(method, params=[], callback=None, errback=None): make JSONRPC POST to backend """
        self.seq = self.seq + 1
        req = ajax.ajax()

        if callback:
            req.bind('complete', callback)
        else:
            req.bind('complete', self.echo)

        req.open('POST', self.endpoint + '/api', True)
        req.set_header('content-type', 'application/json')
        req.send(json.dumps({'id': self.seq, 'method': method, 'params': params}))
Beispiel #55
0
 def __init__(self, url, method='GET', data=None, **kwargs):
     super(HTTPRequest, self).__init__(**kwargs)
     self._url = url
     self._req = ajax.ajax()
     self._req.bind("complete", self._complete_handler)
     self._data = data
     self._method = method
     self._req.open(self._method, self._url, True)
     self._req.set_header('content-type', 'application/x-www-form-urlencoded')
     if self._data is None:
         self._req.send()
     else:
         self._req.send(self._data)
Beispiel #56
0
    def commit(self, schema, oid, action, payload={}, callback=None):
        """ commit(schema, oid, action, payload={}, callback=None): post new event to api  """
        req = ajax.ajax()

        if callback:
            req.bind('complete', callback)
        else:
            req.bind('complete', self.echo)

        req.open('POST', self.endpoint + '/dispatch/%s/%s/%s' % (schema, oid, action), True)
        req.set_header('content-type', 'application/json')
        data = json.dumps(payload)
        req.send(str(data))
Beispiel #57
0
 def click(self, ev):
     cx = math.floor((ev.clientX/self.boardscale)-0.5)
     cy = math.floor((ev.clientY/self.boardscale)-0.5)
     if self.multiplayer and self.session_id != None:
         req = ajax.ajax()
         req.bind('complete', self.moveover)
         req.open('POST',"/clickonboard",True)
         req.set_header('content-type','application/x-www-form-urlencoded')
         req.send({"action":"clickonboard", "session_id":str(self.session_id), "clickx":str(cx), "clicky":str(cy)})
     else:
         for k in self.shiplist:
             if IsOneTileMove(k.coord[0], k.coord[1], cx, cy):
                 k.coord = [cx,cy]
Beispiel #58
0
 def send(self, operation, data, action=lambda t: None, method="POST"):
     def on_complete(req):
         if req.status==200 or req.status==0:
             print( req.text)
             action(req.text)
         else:
             print( "error "+req.text)
     req = ajax()
     req.on_complete = on_complete
     url = "/record/"+ operation
     req.open(method,url,True)
     req.set_header("Content-Type","application/json; charset=utf-8")
     req.send(data)
Beispiel #59
0
def deleteBoard(event):
    selected = [opt for opt in document['boardSelect'] if hasattr(opt, 'value') and opt.value == document['boardSelect'].value].pop()
    new_opts = [opt for opt in document['boardSelect'] if hasattr(opt, 'value') and opt.value != document['boardSelect'].value]
    document['boardSelect'].clear()
    for opt in new_opts:
        document['boardSelect'] <= opt
    loadListsForSelectedBoard()
    updateStar()

    req = ajax.ajax()
    req.open('POST', '/board_delete', True)
    req.set_header('content-type', 'application/x-www-form-urlencoded')
    req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
    req.send({'boards_id': selected.value})
Beispiel #60
0
 def ajax_request_question(self, handler):
     req = ajax.ajax()
     req.bind('complete', handler)
     queue = [q['id'] for q in window.questions]
     for question in self.questions:
         if question.answer is None:
             queue.append(question.data['id'])
     params = self.save_vote_query()
     params['queue'] = ','.join('q%d'%x for x in queue)
     req.open('GET',
         window.root_url +
         translate('/') + 'get_question/?' +
         '&'.join('%s=%s'%(k, v) for k, v in params.items()) +
         '&callback=?')
     req.send()