Browse Source

get single context with error

Alessia 1 year ago
parent
commit
e5a43ceddb
4 changed files with 232 additions and 3 deletions
  1. 28 1
      flask_be/app.py
  2. 17 1
      flask_be/engine/handle_request.py
  3. 161 0
      site2/js/pagination.js
  4. 26 1
      site2/js/ricerca.js

+ 28 - 1
flask_be/app.py

@@ -39,7 +39,7 @@ def simpleQuery():
 # fino a qui
 #################################################################
 
-# chiama funzione per contesti
+# chiama funzione per contesti multipli
 @app.route('/get_context', methods=['POST'])
 def simpleContext():
 
@@ -66,5 +66,32 @@ def simpleContext():
 if __name__ == '__main__':
     app.run()
 
+# chiama funzione per contesti singoli
+@app.route('/get_context', methods=['POST'])
+def singleContext():
+
+    app.logger.info('Request successfully received by the Get Context API')
+
+    try:
+        queryGSC = request.get_json()
+        elem = queryGSC['elem']
+        params = queryGSC['params']
+    
+        output = handleGetSingleContext(elem, params, app.config['DATA_CONFIG'])
+
+        app.logger.info('Request successfully executed, sending output')
+        return output, 200
+
+    except Exception as err:
+        # Log the exception? Send it back to FE?
+        emptyOut = {}
+        app.logger.error(traceback.format_exc())
+        print(traceback.format_exc())
+        return emptyOut, 500
+
+
+if __name__ == '__main__':
+    app.run()
+
 
 

+ 17 - 1
flask_be/engine/handle_request.py

@@ -27,7 +27,7 @@ def handleOccGetQuery(queryList, cooccorrenzeObj, dataConfig):
 
     return res
 
-#Funzione da sistemare per il recupero dei contesti
+#Funzione per il recupero dei contesti multipli
 def handleGetContext(queryList, listResults, dataConfig):
 
     #res = []
@@ -43,6 +43,22 @@ def handleGetContext(queryList, listResults, dataConfig):
 
     return res
 
+#Funzione da sistemare per il recupero dei contesti singoli
+def handleGetSingleContext(elem, paramObj, dataConfig):
+
+    queryHandler = basicQueries(dataConfig)
+
+    indice = int(paramObj['indice'])
+    parole = int(paramObj['parole'])
+    periodi = int(paramObj['periodi'])
+    brani = int(paramObj['brani'])
+
+    res = queryHandler.contestosingolo(elem, indice, parole, periodi, brani)
+
+    return res
+
+#Funzione di decodifica
+
 def tempDecode(stringa):
     if stringa=='forma':
         return 0

+ 161 - 0
site2/js/pagination.js

@@ -0,0 +1,161 @@
+/*
+ * jQuery Pagination
+ * Author: Austin Wulf (@austinwulf)
+ *
+ * Call the paginate method on an array
+ * of elements. Accepts # of items per page
+ * as an argument. Defaults to 5.
+ *
+ * Example:
+ *     $(selector).paginate(3);
+ *
+ * Released under the MIT License.
+ *
+ * v 1.0
+ */
+
+(function($){
+    
+    var paginate = {
+        startPos: function(pageNumber, perPage) {
+            // determine what array position to start from
+            // based on current page and # per page
+            return pageNumber * perPage;
+        },
+
+        getPage: function(items, startPos, perPage) {
+            // declare an empty array to hold our page items
+            var page = [];
+
+            // only get items after the starting position
+            items = items.slice(startPos, items.length);
+
+            // loop remaining items until max per page
+            for (var i=0; i < perPage; i++) {
+                page.push(items[i]); }
+
+            return page;
+        },
+
+        totalPages: function(items, perPage) {
+            // determine total number of pages
+            return Math.ceil(items.length / perPage);
+        },
+
+        createBtns: function(totalPages, currentPage) {
+            // create buttons to manipulate current page
+            var pagination = $('<div class="pagination" />');
+
+            // add a "first" button
+            pagination.append('<span class="pagination-button">&laquo;</span>');
+
+            // add pages inbetween
+            for (var i=1; i <= totalPages; i++) {
+                // truncate list when too large
+                if (totalPages > 5 && currentPage !== i) {
+                    // if on first two pages
+                    if (currentPage === 1 || currentPage === 2) {
+                        // show first 5 pages
+                        if (i > 5) continue;
+                    // if on last two pages
+                    } else if (currentPage === totalPages || currentPage === totalPages - 1) {
+                        // show last 5 pages
+                        if (i < totalPages - 4) continue;
+                    // otherwise show 5 pages w/ current in middle
+                    } else {
+                        if (i < currentPage - 2 || i > currentPage + 2) {
+                            continue; }
+                    }
+                }
+
+                // markup for page button
+                var pageBtn = $('<span class="pagination-button page-num" />');
+
+                // add active class for current page
+                if (i == currentPage) {
+                    pageBtn.addClass('active'); }
+
+                // set text to the page number
+                pageBtn.text(i);
+
+                // add button to the container
+                pagination.append(pageBtn);
+            }
+
+            // add a "last" button
+            pagination.append($('<span class="pagination-button">&raquo;</span>'));
+
+            return pagination;
+        },
+
+        createPage: function(items, currentPage, perPage) {
+            // remove pagination from the page
+            $('.pagination').remove();
+
+            // set context for the items
+            var container = items.parent(),
+                // detach items from the page and cast as array
+                items = items.detach().toArray(),
+                // get start position and select items for page
+                startPos = this.startPos(currentPage - 1, perPage),
+                page = this.getPage(items, startPos, perPage);
+
+            // loop items and readd to page
+            $.each(page, function(){
+                // prevent empty items that return as Window
+                if (this.window === undefined) {
+                    container.append($(this)); }
+            });
+
+            // prep pagination buttons and add to page
+            var totalPages = this.totalPages(items, perPage),
+                pageButtons = this.createBtns(totalPages, currentPage);
+
+            container.after(pageButtons);
+        }
+    };
+
+    // stuff it all into a jQuery method!
+    $.fn.paginate = function(perPage) {
+        var items = $(this);
+
+        // default perPage to 5
+        if (isNaN(perPage) || perPage === undefined) {
+            perPage = 5; }
+
+        // don't fire if fewer items than perPage
+        if (items.length <= perPage) {
+            return true; }
+
+        // ensure items stay in the same DOM position
+        if (items.length !== items.parent()[0].children.length) {
+            items.wrapAll('<div class="pagination-items" />');
+        }
+
+        // paginate the items starting at page 1
+        paginate.createPage(items, 1, perPage);
+
+        // handle click events on the buttons
+        $(document).on('click', '.pagination-button', function(e) {
+            // get current page from active button
+            var currentPage = parseInt($('.pagination-button.active').text(), 10),
+                newPage = currentPage,
+                totalPages = paginate.totalPages(items, perPage),
+                target = $(e.target);
+
+            // get numbered page
+            newPage = parseInt(target.text(), 10);
+            if (target.text() == '«') newPage = 1;
+            if (target.text() == '»') newPage = totalPages;
+
+            // ensure newPage is in available range
+            if (newPage > 0 && newPage <= totalPages) {
+                paginate.createPage(items, newPage, perPage); }
+        });
+    };
+
+})(jQuery);
+
+/* This part is just for the demo,
+not actually part of the plugin */
+$('.article-loop').paginate(2);

+ 26 - 1
site2/js/ricerca.js

@@ -77,7 +77,7 @@ function processOccData(response){
 }
 
 //Funzione per gestire i contesti
-function processContext(response){
+function processSingleContext(response){
   if(response.length==0){
       alert('No results!')
   }
@@ -616,6 +616,8 @@ function createOccRow(num, elem) {
   var row = document.createElement('div');
   row.className = "row height d-flex justify-content-center align-items-center";
   row.id = num;
+  var onClickCommand = "goToSingleContext(" + num + ")";
+  row.setAttribute("onclick", onClickCommand);
 
   if (elem.hasOwnProperty('Titolo Abbreviato')) {
     var colTitolo = document.createElement('div');
@@ -679,6 +681,29 @@ function createOccRow(num, elem) {
 
 //
 
+//START GET SINGLE CONTEXT
+
+function goToSingleContext(num) {
+  console.log(arrayResponse);
+  console.log(arrayResponse[num]);
+  let params = {"indice": num, "parole": 31, "periodi": 0, "brani": 0};
+
+
+  queryGSC = {
+    elem: arrayResponse[num],
+    params: params
+}
+
+  getData('/get_single_context', queryGSC)
+    // After request finishes, process response data
+    .done(response => processSingleContext(response))
+    .fail(err => {
+      console.log(err);
+      $("#loader").css("display", "none");
+      alert('Something went wrong!');
+    });
+}
+
 $(document).on("click", ".deleteCC", function (ev) {
   var deleteID = "occ_" + this.id;
   const element = document.getElementById(deleteID);