Build boolean expression from arrays and evaluate entire expression at one time in javascript

I have two arrays – one that contains booleans, and the other operators:

to_eval = [true, true, false, false]
ops=['&&', '||', '&&']

Out of this I’d like to build an expression

result = true && true || false && false

Which should evaluate to true based on precedence rules

If I iterate over the arrays evaluating as I go, the result is false.

I could build a string and use Eval or Function – but from what I have been reading this can cause security issues in a web application.

Is there a way in Javascript to build out an expression without evaluating it till it is fully formed so that precedence rules are observed without using Eval or Function?

A button allowing at most one click per second [closed]

I wanted to implement a button in Javascript that allows at most one click per second, so I thought of 4 solutions ( 2 are working and 2 aren’t). each solution has its branch in the following repository:
https://github.com/codiaji/OneClickPerSecond
Can you tell me, If I did well with the working solutions, and why aren’t the other ones not working.
finally, If you’ve other tricks to implement this feature tell me about briefly.

I want to add date and time on navbar element named ‘UK CT’ when it is clicked

    <!doctype html>
    <html lang="en">
    <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" 
    crossorigin="anonymous">
    <title>Hello, world!</title>
    <script>
    let a,b;
    let date,date1;
    let time,time1;
    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    setInterval(() => {
    a = new Date();
    date = a.toLocaleDateString(undefined, options);
    time = a.getHours() + ':' + a.getMinutes() + ':' + a.getSeconds();
    document.getElementById('time').innerHTML = time + "<br>on " + date;
    }, 1000);
    setInterval(() => {
    const date1 = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
    time1=a.getHours() + ':' + a.getMinutes() + ':' + a.getSeconds();
    document.getElementByClassName('navbar-nav mr-auto nav-item active nav- 
    link').onclick="time1 + "<br>on " + date1;;";
    document.getElementById(time1).innerHTML = time1 + "<br>on " + date1;
    }, 1000);
    </script>
    </head>
    <body>
    </html>

1.I want to see the current time and date of United Kingdom .
2.So I have used a ‘UK CT’ as an anchor tag in navigation bar.When we click on ‘UK CT’ it
should show the current time and date.
3.The data and time should be shown in Jumbotron template.

Websocket ws.onmessage event isn’t fire when i try to call outside of the block that has new Websocket() initialize

when i try to call this function after websocket initialize, ws.onmessage event isn’t fire so that data value is not change

let data;
async function spin(betAmount) {
    let development; 
    await fetch('../config.json')
        .then(response => response.json())
        .then(dev => development = dev.development)
    if(wsConnection === null) {
        wsConnection = new WebSocket(development.wss_url)
        wsConnection.onopen = () => {
            console.log('WebSocket connection initialize')
        }
    } else {
        wsConnection.onmessage = (event) => {
            data = event.data
        }
        console.log(wsConnection.onmessage)
        console.log(data)
    }
}

The best practice for handling different styles on mobile and desktop nextjs

I have a project with nextjs in this project I have some SSR and some static and CSR pages. On some parts of my website, I have different styles on mobile and desktop. I want to know is using media queries for handling this stuff is the best approach Due to the fact media queries might render additional components. in other hands, if I want to handle that by js I should determine the window size and with this approach, my data rendered on client-side and I can’t use SSR and SSG features (prerendering data) anymore
I read some articles and opinions like

How do you go about responsiveness

and as far as I understood using media query is better approach than others but I would be very grateful for any opinions

XSS Vulneraility in Javascript [closed]

One of our Javascript code got flagged for having XSS vulnerability. But I am not JS expert. But I dont think there is one here. Am I right in thinking that this was a false flag?

this.getStepProcessStatus = function(saveType) {
        
    var requestUrl = functionRequestUrl + "getStepProcessStatus";
    
    callReturn = this.makeControllerCall(requestUrl, false);
    
    if (callReturn == null) {
        
        callReturn = "COMPLETE_WITH_ERRORS";
        
        window.clearInterval(this.processSaveTimer);
        
    } else if (callReturn == "COMPLETE") {
        
        createMessage(saveType + " complete", "From APP", "S", "");
        
        window.clearInterval(this.processSaveTimer);
        
    } else if (callReturn == "COMPLETE_WITH_WARNINGS") {
        
        createMessage(saveType + " completed with warnings", "From APP", "S", "");
        
        window.clearInterval(this.processSaveTimer);
        
    } else if (callReturn == "COMPLETE_WITH_ERRORS") {
        
        createMessage(saveType+" completed with errors", "From APP", "E", "");
        
        window.clearInterval(this.processSaveTimer);
    }
    
    return callReturn;
};

Is my identification right? The only line I can remotely think of… is this one… var requestUrl = functionRequestUrl + "getStepProcessStatus"; But not a 100% sure. So any pointers would be helpful.

Thanks in advance.

How to check all the form fields were given to enable the submit button?

I need to enable the submit button, only when all the Input values were given.

I have a form like the below in my blade file.

<form method="POST" id="contactForm">
 <div class="row">
   <div class="col-6">
     <input type="text" name="name" id="name" value=""/>
     <div class="error">Error Message</div>
   </div>
   <div class="col-6">
     <input type="text" name="email" id="email" value=""/>
     <div class="error">Error Message</div>
   </div>
   <div class="col-12">
     <textarea name="body" id="message" rows="5"> Enter your message</textarea>
        <div class="error">Error message</div>
   </div>
   <div class="col-12">
      <input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
   </div>
</form>

Added the required attribute inside the controller.

In controller:

public  function store()
{
$data = request()->validate([
         'name' => 'required',
         'email'   => 'required|email',
         'body' =>  'required',
        ]);
}

The problem is, even if I add the name field and click the button , the submit button is disabled on click.

The button should be disabled, only when all the input fields were given.

Script:

 const button = document.querySelector("#buttonSubmit");
 const buttonExpirationDataKey = 'button-disabled-expiration';
 button.addEventListener("click", () => {
   var form = document.getElementById("contactForm");
             var fields = ["name", "email","body"];
             var i, l = fields.length;
             var fieldname;
             for (i = 0; i < l; i++) {
               fieldname = fields[i];
                if(form[fieldname].value  !== ""){
                  button.disabled = true;
                  let now = new Date();
                  let expirationTime = 1000 * 5; // 5 secs to disable the submit button
                  let expirationDate = new Date(now.getTime() + expirationTime);
                  localStorage.setItem(buttonExpirationDataKey, expirationDate);
                  button.dataset.enabledAt = expirationDate;
                }
                 else {
                   button.disabled = false;
                }
               return false;
              }
            });

The for loop iterates over each input element, if the particular input element have a value and then If we click the submit. The button is disabled and stored in the local storage.

How to check all the form input and the textarea has values and then after clicking the submit button, the button should be disabled for 5 secs.

https://jsfiddle.net/1vgzj8oc/

How could I do this? Could anyone please help?

rotate specific image marker in google maps

I am trying to rotate specific copy of image marker in google maps.

First i have a unique icon :

      this.iconMarker = {
        url: "assets/Component 1 – 1.svg",
        anchor: new google.maps.Point(10, 10),
        labelOrigin: new google.maps.Point(20, 47),
      };

I have 3 marker that each take this configuration of icon :

for(let i=0 ; i< 3; i++){

  new google.maps.Marker({
    position: myLatLng,
    map,
    icon: this.iconMarker,
  });
}

we assume that for each marker we have a id i.

marker 1 : id = 0
marker 2 : id = 1
marker 3 : id = 2

To rotate image in google maps i use this method :

google.maps.event.addListenerOnce(this.map, "idle", () => {
        $(`img[src="assets/Component 1 – 1.svg"]`).css({
          transform: "rotate(" + message.bearing+ "deg)",
        });
      });

In order to receive bearing for each marker i use web socket:

  this.socket.onmessage = (message) => {
       
// we found bearing as message.bearing 
// we have also id of marker as message.id ( 0 or 1 or 2)

// here we apply rotation for every marker 
 
   }

My problem is whatever i receive bearing for a marker and apply rotation all marker rotate !
After searching for a while i can’t found a solution to rotate specific copy of image with specific id.

Any idea?

Can we call powershell command from browser extension in Javascript?

I know this is security-wise an absolute No-Go. But my customer is going to use a SAPUI5 developed application in the browser within the intranet upon which my preinstalled browser extension will be invoked (using “matches”) which should simply collect the PRINTER names on the local workstation and supplies back to the application which is to be used for further processes. I have the below node js code which return the printernames but how to run this in browser engine.

const { exec } = require('child_process');
exec('get-printer | Select-Object Name | ConvertTo-Json', { 'shell': 'powershell.exe' }, (error, stdout, stderr) => {
console.log(stdout);
}) 

why it’s not working and i dont get any errors? (Database)

We tried to get the “res” manually by giving the ID manually and it worked, but when we try to do it automatically like below, it doesn’t work and doesn’t give any errors. Why please?

   await db.query(`SELECT * FROM players WHERE masterid IS NULL AND SPAM = 0`, async (err, rows) => {
        console.log("players to assign ", rows.rows.length)
        await rows.rows.forEach(async function (row, index) {
            //console.log("fetching " + row.username);
            let bot = configuration.bots[Math.floor(Math.random() * configuration.bots.length)];

            //console.log(row.username, " is online ");

            let res = await db.query(`SELECT count(*) FROM players WHERE spam = 0 AND request_timestamp IS NOT NULL AND message_timestamp IS NULL AND masterid = ${bot}`).then((value) => {return value});
            res = res.rows[0].count;
            let playerAssigned = 0;
            await sleep(500);

            if(res < 50 && playerAssigned < 50){
                console.log("assegnato a:",res,bot,row.id)
                let err;
                await db.query(`UPDATE players SET masterid=${bot} WHERE id=${row.id}`,(err,res)=>{console.log("errore",err);err = err})
                console.log("errore",err)
                console.log(row.username, " assiged to " + bot);
                console.log("#################################################################")
            }

I have to make a program integrated into html (i chose javascript/p5.js but i’m still new to it) that creates a 4×4 grid and draws like Armin Hoffman

So far, I’ve done research into the design by Armin Hoffman (rubber band design). The objective is to create a grid of circles which can be selected to change from white to black and connect these circles in a natural fluid shape that avoids white circles but never traps them. I’ve been using Codecademy to learn the basics while copying and studying examples on the p5.js website and additionally following The Coding Train on Youtube (specifically: 7.4 mouse interaction and 7.6 clicking on objects).

[Armin Hofmann’s Design][1]
[1]: https://i.stack.imgur.com/cjN41.jpg

Check @MauriceMeilleur on Twitter between Feb 2021 and Aug 2021

Also: https://discourse.processing.org/t/shape-generator-help-armin-hofmanns-rubber-band-shape-generator/33190

…

Anyway every time i try to make a matrix or array of x and y values stored and to be used in the for loop within the function draw/ function setup, it becomes invalid and it doesn’t show the shapes i would like.

I know I’m missing info and I look like a total beginner, I apologize for any migraines i cause.

This is my latest trial:

class boundingBox {

  createBox() {
    stroke(0);
    strokeWeight(3);
    fill(255, 255, 255, 255);
    rect(100, 100, 700, 700);
  }
}

//___________________________________________________________
function Bubble(x, y, x1, y1, x2, y2, x3, y3) {
  // creating a distinction from x/y private and x/y public
  this.x = x;
  this.y = y;

  this.x1 = x1;
  this.y1 = y1;

  this.x2 = x2;
  this.y2 = y2;

  this.x3 = x3;
  this.y3 = y3;

  //this.x = x = [225,350,475,600];
  //this.y = y = [225,350,475,600];
  // creating color public for later use
  this.col = color(255);

  // this expression works to make a public function within a private function
  this.display = function() {
    stroke(0);
    fill(this.col);
    // creating the ability to display the circles within the parameters set
    //ellipse(this.x, this.y, 48,48);

    // in theory this should loop through the x array position values against all the y values in it's array creating multiple circles
    for (i=0; i<4; i++) {
      ellipse(this.x/*[i]*/, this.y, 100, 100);

      ellipse(this.x1, this.y1, 100, 100);

      ellipse(this.x2, this.y2, 100, 100);

      ellipse(this.x3, this.y3, 100, 100);
    }
  }

  //this.move = function() {
  //  //making the circles change position and act like they are moving within air
  //  this.x = this.x + random(-0.5, 0.5);
  //  this.y = this.y + random(-0.5, 0.5);

  //  this.x1 = this.x1 + random(-0.5, 0.5);
  //  this.y1 = this.y1 + random(-0.5, 0.5);

  //  //this.x = this.x + random(1, 0.5);
  //  //this.y = this.y + random(1, 0.5);
  //}

  // again expression to make function but this time implementing a clicking function
  this.clicked = function() {
    // calculating the distance from the circle center to help fill it with color and nothing else
    var d = dist(mouseX, mouseY, this.x, this.y)
      // diameter of the circle
      if (d < 50) {
      this.col = color(0, 0, 0)
    }
  }

  

  //joinBubbles(bubbles); {
  //  bubbles.forEach(element => {
  //    let dis = dist(this.x, this.y, element.x, element.y);
  //      stroke(200, 200, 200, 127);
  //      line(this.x, this.y, element.x, element.y);
  //  });
  //}
  
  
//}

//class lines {
//  constructor(){
//  this.x4 = x4;
//  this.y4 = y4;
//  this.x5 = x5;
//  this.y5 = y5;
//  }
  
//  this.displayLine = function(){
//    stroke(0)
//  }
  
}

let bubbles = [];
let boxii = [];

function setup() {
    
  createCanvas(1536,1250);
  
    for(let i = 0; i<1; i++){
    boxii.push(new boundingBox());
    }
  
    for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x = 200;
    var y = i;
    bubbles.push(new Bubble(x,y/*x1,y1*/));
    }
    
    for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x1 = 375;
    var y1 = i;
    bubbles.push(new Bubble(x1,y1/*x1,y1*/));
    }
    
        for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x2 = 550;
    var y2 = i;
    bubbles.push(new Bubble(x2,y2/*x1,y1*/));
    }
    
        for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x3 = 700;
    var y3 = i;
    bubbles.push(new Bubble(x3,y3/*x1,y1*/));
    }
    
    //for (let i = 0; i < 1; i++) {
    //var x1 = 400;
    //var y1 = 200;
    //bubbles.push(new Bubble(x1,y1));
    //}
    
    //for (let i = 200; i < 1000; i+=200){
    //var x2 = 200;
    //var y2 = i;
    //bubbles.push(new Bubble(x2,y2));
    //}
    
}

    function mousePressed(){
  // checking where the mouse presses so that clicking outside the circle does nothing
  for (let i = 0; i < bubbles.length; i++) {
    
  //for (let i = 0; i < 4; i++) {
  // using this function on all the circles and again using .this to bring properties from /bubble
  bubbles[i].clicked();
  }
  }

function draw() {    background(140);

  for(let i = 0; i<1; i++) {
    boxii[i].createBox();
  }

      for (let i = 0; i < bubbles.length; i++) {
    //bubbles[i].move();
    bubbles[i].display();
  }
  
  if (mousePressed) {
    for (let i = 0; i < bubbles.length; i++) {
    bubbles[i].display(fill(0))
  }}

}

mudar de class a cada evento

To querendo simular uma conversa de whatsapp, a intenção era que a cada mensagem digitada, a class da div criada a partir desse evento, fosse modificada fazendo com que a mensagem flutuasse pra direita ou pra esquerda.

$('#enviar').click(e =>{
            const valor = $(':input').val()
            console.log(valor)
            const usuario1 = $('<div id="enviado" ></div>').html('')
            
            $(usuario1).html(valor).addClass('mensagem1').addClass('mensagem2')

            $(usuario1).toggleClass('mensagem1')
            $('main').append(usuario1)
        })
.mensagem1{
    background-color: blue;
    clear: both;
    float: left;
    padding: 5px;
    margin-top: 10px;
    margin-left: 10px;
    font-size: 25px;

}
.mensagem2{
    background-color: green;
    clear: both;
    float: right;
    padding: 5px;
    margin-top: 10px;
    margin-right: 10px;
    font-size: 25px;
    opacity: 1;
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bate Papo</title>
    <link rel="stylesheet" href="estilo/style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <header>
        <h2>Nome</h2>
    </header>
    <main>
        
    </main>
    <aside id="campus_mensagem">
        <input type="text" id="mensagem" placeholder="Digite uma mensagem">
        <img src="imagens/seta2-removebg-preview.png" alt="seta" id="enviar">
    </aside>
    <script>
        $('#enviar').click(e =>{
            const valor = $(':input').val()
            console.log(valor)
            const usuario1 = $('<div id="enviado" ></div>').html('')
            
            $(usuario1).html(valor).addClass('mensagem1').addClass('mensagem2')

            $(usuario1).toggleClass('mensagem1')
            $('main').append(usuario1)
        })
    </script>
</body>
</html>