Looping through json paginated urls

I am using a rest api that is paginated by URL e.g https://www.myapi.com/api/v1/jobs/?page=4

I need to loop through all the available pages. I have it working, but the data object get’s overwritten each time, how do I structure the code so I end up with one data object of all pages?

function fetchData(apiUrl) {
    fetch(apiUrl)
      .then((res) => res.json())
      .then((data) => {
     
         
        // work out how many pages there are using the total field
        var total = data.total
        var totalPages = Math.ceil(total /  data.items.length);

  
        if (feedCurrPage < totalPages) {
           var feedUrl ="https://www.myapi.com/api/v1/jobs/?page=" + feedCurrPage;
          feedCurrPage++

          // run next page
          fetchData(feedUrl);

        }else{
           // all loaded, so now let's use our data in another function
           createSearch(data);
        }
      
      });
  }

Deaktivate drag and drop for table in react

I want to deactivate the drag and drop function for the table.
Can anyone tell me how we can do this?

return(
        <div 
            className="grid-container"
        >
            <table
                className="grid-table" 
                onMouseLeave={() => props.handle_mouse(false)}
                onMouseDown={() => props.handle_mouse(true)}
                onMouseUp={() => props.handle_mouse(false)}
            >
                <tbody>
                    {grid}
                </tbody>
            </table>
        </div> 
    )

Electron Pos Printer prints empty receipt

I am using this library Electron Pos Printer, and I have made a small batch of code. I have successfully connected my POS thermal printer, but when I send a command to print, it only “prints” a small amount of blank paper. Any ideas on fixing this, or maybe a recommendation for some other library?

let printerName = "myprinter";
let widthPage = "155";
const data = [
    {
        type: "text", // 'text' | 'barCode' | 'qrCode' | 'image' | 'table
        value: "This is sample print job",
        style: `text-align:center;font-size:16px;`,
    },
    {
        type: "qrCode",
        value: "https://github.com/fssonca",
        height: 55,
        width: 55,
        style: "margin-left:50px",
    },
];
PosPrinter.print(data, {
    preview: false, // Preview in window or print
    width: widthPage, //  width of content body
    margin: "0 0 0 0", // margin of content body
    copies: 1, // Number of copies to print
    printerName: printerName, // printerName: string, check it at webContent.getPrinters()
    timeOutPerLine: 400,
    silent: true,
}).catch((err) => console.log(err));

Update object property after update array

I’m using an object array which contains array indexes and I wanted every time I change something in the array, it would update the index inside the object.

Example:

const move = (arr, from, to) => {
  const copy = Array.from(arr);
  const [removed] = copy.splice(from, 1);
  copy.splice(to, 0, removed);

  return copy;
};

const remove = (arr, index_to_remove) => {
  return arr.filter((_, index) => index !== index_to_remove);
};

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let obj = [
  {
    index: 1, //uses arr[1]
  },
  {
    index: 2, //uses arr[2]
  },
  {
    index: 0, //uses arr[0]
  },
  {
    index: 3, //uses arr[3]
  },
  {
    index: 5, //uses arr[5]
  },
];

arr = move(arr, 2, 6);
arr = remove(arr, 3)

After updating the array by moving or removing elements, I don’t know how to update the object that depends on these indexes.

How to add variables and methods in callback parameters

I’m making a custom middleware package as a project, and I ran into a problem. In one of the files, I have some jsdoc types (trying to make the package small so no typescript) for the callback:

class Response {
  constructor() {
    // Constructor stuff
  }
  /**
   * 
   * @param {string} path 
   */
  async useFile(path, file) {
    const res = await fetch(path, {
      method: 'GET',
      body: fs.readFile(file, (err, data) => {
        if (err) throw err
        else return data
      }),
      headers: {
        'Content-type': 'text/html'
      }
    })
    return JSON.stringify(res)
  }
}

I then import that Response class and use it as a type:

server.get('/', (req, res) => {
  res.useFile('index.html')
})

In my test folder, I’m creating a server and assigning it to this server variable. I then call the get method, using the useFile method on the response:

server.get('/', (req, res) => {
  res.useFile('index.html')
})

But when I run the code get this error:

res.useFile('/', './index.html')
      ^

TypeError: Cannot read properties of undefined (reading 'useFile')

I know that the res param is undefined (because it’s a parameter), so the useFile method won’t work, but I’ve seen other middleware packages like express do this without problems. How do I put these methods onto the params?

Query builder how to use “where” clause on nested documents

I’m having some issues using the Mongoose queries. I’m just trying to find documents in a collection using the where clause.

Unfortunately, it seems you can’t use the where clause on nested documents.


This is the collection schema

const schema: Schema = new Schema({
    game: { type: Schema.Types.ObjectId, ref: 'Game', required: true, index: true },
    players: [{ type: Schema.Types.ObjectId, ref: 'Player', required: true, index: true }],
    scores: [{ type: String }],
    resultDate: { type: Date}
});

I’m trying to find all games where type = 1v1, so I tried this

let query = Matchs.find()
    .populate('game')
    .populate('players')
    .where('game.name').equals('Trackmania')

const matchs: Match[] = await query.exec();

This returns an empty array.


Notes

  • Removing the where clause returns the correct results (all Matchs)
  • Any where clause on game returns an empty array
  • I’d like to use query builder instead of passing a json because I use some parameters to define what I am querying

I read that where clause didn’t work on nested documents, but there must be a way to do this right ? Am I missing something ?

Javascript >= comparison with two negative numbers producing incorrect result

I’ve come across strange behaviour where both before and after using toFixed() the same number is visibly greater than the other (correct). However the toFixed() version produces an incorrect comparison? This seems to happen when both numbers are negative and >= is the operand.

let lastVal = 0.091;
let currentVal = 0.093;
let newVal = 0.094;

let oldSlope = lastVal - currentVal;
let newSlope = currentVal - newVal;
let oldSlopeFixed = (lastVal - currentVal).toFixed(16);
let newSlopeFixed = (currentVal - newVal).toFixed(16);

document.getElementById("one").innerHTML = "oldSlope = " + oldSlope + ", newSlope = " + newSlope;
document.getElementById("two").innerHTML = "oldSlopeFixed = " + oldSlopeFixed + ", newSlopeFixed = " + newSlopeFixed;

if ((newSlope) >= (oldSlope))
{
    document.getElementById("three").innerHTML = "newSlope >= oldSlope  (correct)";
}
if (!((newSlopeFixed) >= (oldSlopeFixed)))
{
    document.getElementById("four").innerHTML = "newSlopeFixed < oldSlopeFixed  (incorrect ... what???)";
}
<!DOCTYPE html>
<html>
<body>

<p id="one"></p>
<p id="two"></p>
<p id="three"></p>
<p id="four"></p>

</body>
</html>

Question Regarding chrome.windows.onRemoved.addListener (Chrome API)

I want to execute a piece of code when the window of my panel extension is closed.
I know that chrome.windows.onRemoved.addListener is the function I’m Looking for but by default it accepts only [“normal”, “popup”] window_types (see attached screenshot) or click on this link https://developer.chrome.com/docs/extensions/reference/windows/

How do I format the filter object so that it accepts panel type windows?
Thank you for your time 🙂enter image description here

How to have multiple submit buttons for a quiz on one page

I’m creating a language quiz and it requires multiple submit buttons on one page through which one can check their answers. Having one submit button works fine. But so far, having multiple submit buttons creates issues where one submit button, when pressed, generates two (if there are 2 questions) of the same answers under both submit buttons. So after one click you will see 4 of the same answers. And only one submit button will be disabled. See scripts below for more info.

Below you’ll find the html form for 1 of the quiz questions.

<form id="formId">
<h5>1. I am strong</h5>
<p>Translate the above sentence.</p>
<input type="text" id="q1" /><br><br>
<input type="submit" class="btn btn-outline-primary" id="submitId" value="Check answer" />
</form>

Below you’ll find the javascript that gives the answer when submit button is clicked.

<script>
var answers = {
    "q1": ["Ik ben sterk"]
    
};
function markAnswers(){
    $("input[type='text']").each(function(){
        console.log($.inArray(this.value, answers[this.id]));
        if($.inArray(this.value, answers[this.id]) === -1){
            $(this).parent().append("<br>The correct answer: Ik ben sterk");
        } else {
            $(this).parent().append("<br><font style='color:green;'>Correct!</font>");
        }
    })
}
$("form").on("submit", function(e){
    e.preventDefault();
    markAnswers();
});
</script>

The script below is to make sure user cannot submit answer again.

<script>
var form = document.getElementById('formId');
var submitButton = document.getElementById('submitId');

form.addEventListener('submit', function() {

   // Disable the submit button
   submitButton.setAttribute('disabled', 'disabled');

   // Change the "Submit" text
   submitButton.value = 'Check answer';
            
}, false);
</script>

Above scripts are just for one question. If I add another question and I copy paste scripts and change the ID’s to q2, formId2 and submitId2 it will not work as described earlier. What do I need to change to the scripts in order for this to work? Any suggestion is welcome. Thanks.

How to return an array of arrays from UrlFetchApp.Fetchall

I’m crawling a large number of URLs (20,000), in order to scrape some html from each page. However my code is slow because urlfetchapp is wrapped within a for lopp. To overcome the 30 minute execution limit, I thought about using urlfetchapp.all to pass over 100 urls at a time in order to speed up execution and then create an array of the returned html code and then lookup the substrings within them.

The function urlReferrer is the initial code, and test (below) is what I am working on in order to speed up the run time

However (in function – test) urlFetchApp.fetchAll doesn’t appear to return an array of getContentText for each url, it only returns getContentText for the first url in the range. Any idea on how to fix this?

  function urlReferrer() {
    
          var urlFetchOptions = {muteHttpExceptions: true};
        
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var importSheet = ss.getSheetByName("deduplicated");
        var importSheetLastRow = importSheet.getLastRow();
        
        
        var importRange = importSheet.getRange(2,1,importSheetLastRow-1,1).getValues();
        
        // crawls urls
        
        for(var z = 0; z < importRange.length; z++) {
            
           try { 
            var response = UrlFetchApp.fetch(importRange[z],urlFetchOptions);
           }
           catch(e) {
             Logger.log(e);
        }
        
        // if response code is equal to 200 
        
        if (response.getResponseCode() == 200) {
            
            var html = response.getContentText();
        }
        
        // get first string. Split string if true, else continue
        
        var string1 = html.split('@type":"ListItem","position":2,"item":{"@type":"Thing","@id":"')[1]; 
        
        if( string1 == null) {
          categoryURLs.push(["invalid html"]);
          continue;
        }
        // Logger.log(string1);
        
        var string2 = string1.split('</script><!-- HTML_TAG_END -->')[0]; 
        
        
          // split the string depending on whether there are 3 or 4 breadcrumbs
          // if contains position 5, then 4, then 3, then 2
        
        
          if (string2.indexOf("x22positionx22:6") >= 0) {
        
                  // Logger.log("yes");
                
                 var subString = string2.substring(
                  string2.indexOf('"position":6,"item":{"@type":"Thing","@id":"') + 44,
                  string2.lastIndexOf('","name'));
                  // Logger.log(subString);
                  categoryURLs.push([subString]);
          
          } else if (string2.indexOf("x22positionx22:5") >= 0) {
        
                  // Logger.log("yes");
                
                 var subString = string2.substring(
                  string2.indexOf('"position":5,"item":{"@type":"Thing","@id":"') + 44,
                  string2.lastIndexOf('","name'));
                  // Logger.log(subString);
                  categoryURLs.push([subString]);
        
        
           } else if (string2.indexOf("x22positionx22:4") >= 0) {
        
                  // Logger.log("yes");
                
                 var subString = string2.substring(
                  string2.indexOf('"position":4,"item":{"@type":"Thing","@id":"') + 44,
                  string2.lastIndexOf('","name'));
                  // Logger.log(subString);
                  categoryURLs.push([subString]);
                  
                        
                } else if (string2.indexOf("x22positionx22:3") >= 0) {
        
                  // Logger.log("yes");
                
                 var subString = string2.substring(
                  string2.indexOf('"position":3,"item":{"@type":"Thing","@id":"') + 44,
                  string2.lastIndexOf('","name'));
                  // Logger.log(subString);
                  categoryURLs.push([subString]);
                        
                } else  {
        
                 var subString = string2.substring(
                  string2.indexOf('"http"'),
                  string2.lastIndexOf('","name'));
                  // Logger.log(subString);
                  categoryURLs.push([subString]);
                       
                } 
            
              }
              
              Logger.log(categoryURLs);
              
              var range = importSheet.getRange(2, 2, categoryURLs.length,1);
    
              range.setValues(categoryURLs);
        }






    function test () {
    
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var importSheet = ss.getSheetByName("deduplicated");
      var importSheetLastRow = importSheet.getLastRow();
     
      var importRange = importSheet.getRange(2,1,importSheetLastRow-1,1).getValues();
      var merged = [].concat.apply([], importRange);
      console.log(merged);
    
      // fetch all urls
      var responses = UrlFetchApp.fetchAll(merged);
      var responseMapped = JSON.stringify(responses.map(function(e) {return e.getContentText()}));
    
      console.log(responseMapped[0]);
    
    }
        

How can i make a single straight line in HTML Canvas which is bound to the input of the mouse

I’ve got a question which i can’t seem to figure out the right way. For some context. I’m trying to make a sort of connect the dots game. People can click on a circle and link the circle to the next one. Connecting the dots is working fine, but i wanted to add a function that when clicked on the first dot, users get a perfect straight line from the clicked dot to the mouse input. This way the users get some feedback on which dot they clicked, and how they can link to each other.

Here is a codePen that shows what i want to achieve. The only thing different is that the dots in this “pen” are animated, and i want them to stand still.

I tried a lots of things so far, and found multiple StackOverflow articles about this subject. So far i got connecting the dots working. Also the user draws a line when a dot is selected. The big issue however is that every movement of the user is resulting in drawing a line on the canvas. This line which is only used as feedback which dot is selected and how the user can draw his cursor to the next dot, is filling the screen with thousands of instances in no-time. I only want to show them one single line at a time, leading to their mouse cursor as the endpoint. Just like the codePen i did mention earlier on.

Here is my JS code so far.

    var dotColor = "#FF0000";
    var strokeColor = "#FF0000";
    var mouse = {
      x: undefined,
      y: undefined
    };

    var obj;


    var data = {
      canvas: null,
      ctx: null,
      clickedDot: null,
      dots: [{
        x: 180,
        y: 50
      }, {
        x: 20,
        y: 50
      }]
    };

    window.addEventListener('mousemove', function(e) {
      mouse.x = e.x;
      mouse.y = e.y;
      renderActiveLink();
    });

    function circleCollision(c1, c2) {
      var a = c1.r + c2.r,
        x = c1.x - c2.x,
        y = c1.y - c2.y;

      if (a > Math.sqrt((x * x) + (y * y))) return true;
      else return false;
    }

    function prepCanvas() {
      var res = window.devicePixelRatio || 1,
        scale = 1 / res;
      data.canvas = document.getElementById('dots');
      data.ctx = data.canvas.getContext('2d');

      data.canvas.width = 500;
      data.canvas.height = 300;

      data.ctx.scale(res, res);

      data.canvas.addEventListener('mousedown', function(e) {
        checkForDot(e);
      });
      data.canvas.addEventListener('mouseup', function(e) {
        checkForDot(e);
      });
    }

    function drawDots() {
      var i = 0;
      for (; i < data.dots.length; i++) {
        var d = data.dots[i];
        data.ctx.beginPath();
        data.ctx.arc(d.x, d.y, 5, 0, 2 * Math.PI);
        data.ctx.fillStyle = dotColor;
        data.ctx.fill();
        data.ctx.closePath();
      }
    }

    function drawLine(toDot) {
      data.ctx.beginPath();
      data.ctx.moveTo(data.clickedDot.x, data.clickedDot.y);
      data.ctx.lineTo(toDot.x, toDot.y);
      data.ctx.lineWidth = 5;
      data.ctx.strokeStyle = strokeColor;
      data.ctx.stroke();
      data.ctx.closePath();
    }

    function checkForDot(e) {
      var i = 0,
        col = null;
      for (; i < data.dots.length; i++) {
        var d = data.dots[i],
          c1 = {
            x: d.x,
            y: d.y,
            r: 50
          },
          c2 = {
            x: e.pageX,
            y: e.pageY,
            r: 50
          };
        if (circleCollision(c1, c2)) {
          col = d;
        }
      }
      if (col !== null) {
        if (data.clickedDot !== null) drawLine(col);
        data.clickedDot = col;
        obj = col;
      } else data.clickedDot = null;
    }

    function renderActiveLink() {
      data.ctx.beginPath();
      data.ctx.lineWidth = 5;
      data.ctx.shadowBlur = 0;
      data.ctx.moveTo(obj.x, obj.y);
      data.ctx.lineTo(mouse.x, mouse.y);
      data.ctx.strokeStyle = '#000000';
      data.ctx.stroke();
    }



    prepCanvas();
    drawDots();
*{
  margin:0;
  padding: 0;
}

#dots {
  border: 1px solid black;
}
<canvas id="dots"></canvas>

Also to be seen in this JSFiddle.

Hope someone here can help me out. If any more information is needed, i will be glad to answer your questions :D.