how to validate input of type number?

I am practicing with vue, how can I optimize this conditional code.

The idea is that the number type input does not accept 01,02…
That is, when they enter 01, type 1. This up to the number 09, but at the same time accept 0.1 0.2 0.3…

    let checkQty = ""
    saleQty.value === '01' ? checkQty = 1 : checkQty = saleQty.value
    saleQty.value === '02' ? checkQty = 2 : checkQty = saleQty.value
    saleQty.value === '03' ? checkQty = 3 : checkQty = saleQty.value
    saleQty.value === '04' ? checkQty = 4 : checkQty = saleQty.value
    saleQty.value === '05' ? checkQty = 5 : checkQty = saleQty.value
    saleQty.value === '06' ? checkQty = 6 : checkQty = saleQty.value
    saleQty.value === '07' ? checkQty = 7 : checkQty = saleQty.value
    saleQty.value === '08' ? checkQty = 8 : checkQty = saleQty.value
    saleQty.value === '09' ? checkQty = 9 : checkQty = saleQty.value

Slider in HTML. Picture is disappearing after some seconds

I wanted to put slider in my ecommerce django website. But, while doing this I am getting an error. I don’t what’s the problem. I got this code from w3school. There it worked well, but in my code it’s not working properly.
html

<div class="slideshow-container">

<div class="mySlides fade">

  <img src="{% static 'images/ad1.png' %}" style="width:100%">

</div>

<div class="mySlides fade">

  <img src="{% static 'images/ad1.png' %}" style="width:100%">
 
</div>

<div class="mySlides fade">

  <img src="{% static 'images/ad1.png' %}" style="width:100%">
  
</div>

<a class="prev" onclick="plusSlides(-1)" style="margin-left:-5%;"> <img src="{% static 'images/arrow-left-1.png' %}"></a>
<a class="next" onclick="plusSlides(1)"style="margin-right:-5%;"> <img src="{% static 'images/arrow-right-2.png' %}"></a>

</div>
<br>

<div style="text-align:center">
  <span class="dot" onclick="currentSlide(1)"></span> 
  <span class="dot" onclick="currentSlide(2)"></span> 
  <span class="dot" onclick="currentSlide(3)"></span> 
</div>

style

 * {box-sizing: border-box}
body {font-family: Verdana, sans-serif; margin:0}
.mySlides {display: none}
img {vertical-align: middle; }

/* Slideshow container */
.slideshow-container {
  max-width: 80%;
  position: relative;
  margin: auto;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
/*.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .prev, .next,.text {font-size: 11px}
}

script

<script>
var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1}    
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";  
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";  
  dots[slideIndex-1].className += " active";
}
</script>

It’s working well, but disappearing after about a second and when to press next showing the picture, but again disappearing. Please, help!

Parse text results from Tesseract.js

I’m completly new to OCR and tesseract.js. I’m trying to get datas from a card image like this one and store datas into specifics variables.

What i’ve done so far :

<script>
    Tesseract.recognize(
        'carte.png',
        'fra', {
        logger: m => console.log(m)
        }
    ).then((res) => res).then(({
        data
    }) => {
        console.log(data.text, typeof(data.text)); // returns type as string
    })
</script>

I get this in console :

=2 certi
_ NOM Prénom
Certificatn°: 1245644868
Catégorie: Décideur exploitation agricole
Service
æ" référent :
-
FranceAgriMer
 string 

I want to parse and store those datas like this :

  • name = “NOM”
  • firstname = “Prénom”
  • certificateNumber = “1245644868”
  • category = “Décideur exploitation agricole”
  • expirationDate = “Juin 2020”

Thanks in advance !

Which event should be cancelled to stop a contenteditable keyboard shortcut?

I am trying to build around contenteditable by first disabling it’s text styling behavior from keyboard shortcuts, such as ctrl+b or ctrl+i.

I am using event.preventDefault() when these shortcuts are detected on keyup and keydown events — however sometimes rarely, I am noticing that contenteditable still ignores event.preventDefault() and the keyboard shortcut and styles/unstyles the selected text with it’s own way.

Is there any way I can fully disable these keyboard shortcuts other than cancelling keyup and keydown?

How to Avoid Image overlapping using d3 | Javascript

I have this code that shows an number in image format in the map , but as you can see red number 2 and 8 are overlapping , what can i do for that not to happen.
is there any easy way to avoid that ? like using css or can only be done with d3.

that’s the image that illustrate the overlapping problem.
enter image description here

thats the code i use :
Thanks for the help !

<script>

var php_varRed = '<?php echo json_encode($redSide) ?>';
var php_varBlue = '<?php echo json_encode($blueSide) ?>';
const positionMapBlueSide = JSON.parse(php_varBlue);
const positionMapRedSide = JSON.parse(php_varRed);

for (var cont=0; cont<positionMapBlueSide.length;cont++) {

var cords = [
                  [positionMapBlueSide[cont][1]['x'] ,positionMapBlueSide[cont][1]['y']],
                  [positionMapBlueSide[cont][2]['x'] ,positionMapBlueSide[cont][2]['y']],  

                  [positionMapRedSide[cont][1]['x'] ,positionMapRedSide[cont][1]['y']],
                  [positionMapRedSide[cont][2]['x'] ,positionMapRedSide[cont][2]['y']],

//only posting  the first two coordinates here  , but it goes until 10.
             
              ],

    domain = {
            min: {x: -120, y: -120},
            max: {x: 14870, y: 14980}
    },
    width = 325,
    height = 325,
    bg = "./assets/imgs/mapa2.gif",
    xScale, yScale, svg;

color = d3.scale.linear()
    .domain([0, 3])
    .range(["white", "steelblue"])
    .interpolate(d3.interpolateLab);

xScale = d3.scale.linear()
  .domain([domain.min.x, domain.max.x])
  .range([0, width]);

yScale = d3.scale.linear()
  .domain([domain.min.y, domain.max.y])
  .range([height, 0]);

svg = d3.select("#map"+cont).append("svg:svg")
    .attr("width", width)
    .attr("height", height);

svg.append('image')
    .attr('xlink:href', bg)
    .attr('x', '0')
    .attr('y', '0')
    .attr('width', width)
    .attr('height', height);
   
    svg.append('svg:g').selectAll("circle")
    .data(cords)
    .enter().append("svg:circle")
   
    

        .attr('cx', function(d) { return xScale(d[0]) })
        .attr('cy', function(d) { return yScale(d[1]) })
        .attr('fill',function (a) { 
            
     
        switch(a[0]){
          case(positionMapBlueSide[cont][1]['x']): return "url(#image1Blue)"; break; 
          case(positionMapBlueSide[cont][2]['x']): return "url(#image2Blue)"; break;

        
          case(positionMapRedSide[cont][1]['x']): return "url(#image1Red)"; break; 
          case(positionMapRedSide[cont][2]['x']): return "url(#image2Red)"; break;

        
        //only posting  the first two coordinates here  , but it goes until 10.


        }  
        })  

        .attr('r', 16)
    
}

    </script>

How to handle multiple async operations using promises?

I have some code with 2 functions. taskA requires some value and gets that value via a callback that returns the value inside a promise. taskB provides the value via a callback that is also passed as a parameter, but this callback is synchronous.

How can I get the value from taskB and pass it to taskA, and get the result to pass it back to taskB? I can modify taskA, but taskB must provide its value and obtain a result via a synchronous callback.

async function taskA(requestValue: () => Promise<Value>, provideResult: (result) => void) {
  while(someCondition) {
    await requestValue();
    // do something with value
    provideResult(result);
  }
}

function taskB(valueCallback: (value) => Result) {
  let state = someState;
  ...
  let handleEvent = (event) => {
    let result = valueCallback(convertToValue(event));
    state = updateState(result);
  }
}

Connecting to wss in node.js

I have a problem connecting to a certain game’s websocket. In python it connects without a problem, but in node.js I don’t want to connect anymore. Anyone know why?
Python code that works fine:

import websocket
import json
#websocket.enableTrace(True)
ws = websocket.WebSocket()
ws.connect("wss://unia.margonem.pl/ws-engine")
ws.send('{"g":"initlvl=1&&t=init","p":""}')
log = ws.recv()
print(format(log))

Node.js code that won’t work:

const WebSocket = require('ws');
const ws = new WebSocket("wss://unia.margonem.pl/ws-engine");
ws.onopen = function() {
    console.log('Połączono z serwerem.');

}
//ws.onerror = a => {
    //console.log(a)
    //return;
//};

ws.onclose = function() {
    console.log("Rozłączono")
    return;
};

Why its giving me this error # Fatal error in , line 0 # Fatal JavaScript invalid size error 169220804?

The code consist of making an array from a range of number and as well having a third argument in which it indicates the steps from the numbers, if it has a step of 2 well for example it goes from [1,3,5] the code works fine except when I pass step with a negative number as an argument Ex. NumberRange(10,5,-2); Thats when the error appears, in the code it shows the logic I used for a negative step.
Image of the error

”’

function NumberRange(start, end, step){
            
            var numberList = [];

            if(typeof(step) == 'undefined'){
                
                if(start < end){
                    for(;start <= end; start++){
                        numberList.push(start);
                    }

                    console.log(numberList);
                }
                else if(start > end){
                    for(;start >= end;){
                        numberList.push(start);
                        start -= 1;
                    }
                    
                    console.log(numberList);
                }
            }
            else if(start > end && (Math.sign(step) == -1)){  // This is the logic I created when a negative step is given as an argument.
                for(;start >= end; start - step){
                    numberList.push(start);
                }

                console.log(numberList);
            }
            else if(start < end && (Math.sign(step) == -1)){
                console.log("Negative step cant work since the value of the beginning of the list is less than the end of it")
            }
            else{
                for(;start <= end;){
                    numberList.push(start);
                    start += step;
                }

                console.log(numberList);
            }

            //return numberList;
        };

        NumberRange(10,5,-2);

”’

Nodejs search and paginate returned results

I need help or advice on how to manage this. I’m working on a node / mysql project. I need to paginate my data which I’ve managed to implement successfully. Now I only have one problem that has taken me over two days trying to solve to no avail. When a user searches in my site and let’s assume the search results is over 100 records, I need to paginate these results on the frontend. Now the issue is,how do I maintain the search query when the user clicks on page 2 or 3. The situation at the moment is when the user searches the first page record is returned successfully and well paginated but when he clicks on page 2 the search query ain’t there anymore. so am trying to figure out how to maintain this query search in my app so that when he searches for 1000 records they’re able to be paginated and he maeuvres through each page containing the search results successfully.

this is my backend pagination code at the moment with the pagination and my frontend template is ejs

app.get('/jobs', (req, res) => {       
    
    db.query(sql, (err, result) => {
        if(err) throw err;
        const numOfResults = result.length;
        const numberOfPages = Math.ceil(numOfResults / resultsPerPage);
        let page = req.query.page ? Number(req.query.page) : 1;
        if(page > numberOfPages){
            res.redirect('/?page='+encodeURIComponent(numberOfPages));
        }else if(page < 1){
            res.redirect('/?page='+encodeURIComponent('1'));
        }
        //Determine the SQL LIMIT starting number
        const startingLimit = (page - 1) * resultsPerPage;
        //Get the relevant number of POSTS for this starting page
        sql = `SELECT * FROM photos LIMIT ${startingLimit},${resultsPerPage}`;
        db.query(sql, (err, result)=>{
            if(err) throw err;
            let iterator = (page - 5) < 1 ? 1 : page - 5;
            let endingLink = (iterator + 9) <= numberOfPages ? (iterator + 9) : page + (numberOfPages - page);
            if(endingLink < (page + 4)){
                iterator -= (page + 4) - numberOfPages;
            }
            res.render('index', {data: result, page, iterator, endingLink, numberOfPages});
        });
    });
});

Can’t Install MongoDB

I just tried many tips in stackoverflow to solve my issue:

Failed to start mongod.service: Unit mongod.service not found

I try this: Failed to start mongod.service: Unit mongod.service not found

still nothing

I do in this page: can’t install mongodb on ubuntu 16.10

and still nothing

I do on this page: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

it give me something, then when I update my linux, there are some word about mongodb

when I want to write: udo apt-get install -y mongodb-org

it give this:

mongodb-org : Depends: mongodb-org-shell but it is not going to be installed
           Depends: mongodb-org-server but it is not going to be installed
           Depends: mongodb-org-mongos but it is not going to be installed

how to solve?

I just don’t know, hopefully I can install with you advise, and run my code, thanks

Trying to cast string to number returns NaN

I’m confused… I have a number as a string ('3'), and I want it to become a normal Number-type number. If I go into any console and do Number('3'), it’ll return 3.

However, in this code it returns NaN:

const attr = "rating='3'";
const [attrName, attrValue] = attr.split('=');
// if the attrValue is a number, cast it as such
if (!Number.isNaN(attrValue)) {
    const numAttr = Number(attrValue);
    console.log('num: ', numAttr, attrValue.length, attrValue.charCodeAt(0));
}

I confirm that the first char code of the number string is 39, which is single apostrophe, and its length is 3, so no sneaky hidden chars.. The numAttr value is NaN though. It also does go into the if statement, which presumably tells me that it can, in fact, become a number?

React Native – How to test functions within a function

I am using jest to do testing for my newly built app. However, i am finding difficulties to test certain components when they are in a function. Sounds confusing, but it goes like this:

export default function Calculation(){
...

const sum = (a, b) => {
    return a + b;
  }

const divide= (a, b) => {
    return a / b;
  }
...

When i want to test the sum function i get expected 0 arguments, but got 2

import Calculation from "./Calculation";

test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});

Is there a way to import sum and divide to do the testing without needing to make a separate functions file to do this?

How to properly test middlewares?

I have a problem with testing my middlewares in NodeJS, here is my code:

middleware:

export const requestMiddleware = (req: Request, res: Response, next: () => void) => {
    //some stuff

    next(); //TypeError: next is not a function ---- error from Jest
}

and my middleware.test.ts

describe('errorHandler', () => {
  const req: Request;
  const res: Response;
  const next: () => void;

    beforeEach(() => {
      req = {
        headers: {some: "stuff"},
        method: "GET",
      } as Request;
      res = new Response(req);
      next = jest.fn();
    });

  test('should test middleware', () => {
    requestMiddleware (req, res, next);
    console.log("RES: ", res);

    expect(res.statusCode).toBeDefined()
    expect(res.statusCode).toBe(500)
  })
})

when I launch above test the Jest return me this:

  ● requestMiddleware › should test middleware

    TypeError: next is not a function

      67 |
    > 68 |     next(error);
         |     ^
      69 |   }
      70 |

      at requestMiddleware (src/middlewares/handlers.ts:68:5)

can someone tell me why my next() function in requestMiddleware is not properly mocked by Jest?

thanks for any help!