Javascipt video: Error getting userMedia: DOMException: Could not start video source

I want to write a video messanger on js and I havent video camera on my PC. So I connect my phone(use DroidCam) and permited for my webstie to use DroidCam Source. But in my cosole I see the next error: Error getting userMedia: DOMException: Could not start video source

My useEffect:

 useEffect(() => {
    async function startCapture() {
      try {
        localMediaStream.current = await navigator.mediaDevices.getUserMedia({
          audio: true,
          video: {
            width: 1600,
            height: 900,
          },
        });

        addNewClient(LOCAL_VIDEO, () => {
          const localVideoElement = peerMediaElements.current[LOCAL_VIDEO];

          if (localVideoElement) {
            localVideoElement.volume = 0;
            localVideoElement.srcObject = localMediaStream.current;
          }
        });
      } catch (error) {
        console.error("Error getting userMedia:", error);
        setCameraAvailable(false); // Устанавливаем флаг, если не удалось получить доступ к камере
      }
    }

    startCapture()
      .then(() => socket.emit(ACTIONS.JOIN, { room: roomID }))
      .catch((e) => console.error("Error getting userMedia:", e));

    return () => {
      if (localMediaStream.current) {
        // Добавляем проверку на null
        localMediaStream.current.getTracks().forEach((track) => track.stop());
      }

      socket.emit(ACTIONS.LEAVE);
    };
  }, [roomID]);

Maybe someone can help me?

I dont know what I should do

Vis.js Adds Extra Padding at the Top of a Complex Diagram

I’ve been working with vis.js to create a complex diagram, and I’ve encountered an issue that persists even in a simplified version of my project. The core of the problem is that, when I draw a large diagram, it seems to automatically add extra padding at the top, effectively pushing the diagram down.

This issue becomes more pronounced as the size of the diagram increases. For example, with var number_of_nodes = 100, the diagram gets pushed down by approximately half of the screen’s height. However, with var number_of_nodes = 10, the extra padding is much less noticeable.

    var xScale = 1;
    var yScale = 10;
    var number_of_nodes = 100.    // This is the value makes the issue visible. But less visible when using 10 
    var graph = new Graph(document.getElementById('mynetwork'), xScale, yScale, theme, number_of_nodes);

To reproduce the issue, you’ll need to set number_of_nodes to 100. I’ve created a complete example on jsfiddle, which can be found here: https://jsfiddle.net/master_chief/zy1Lfx2q/. Note: The number_of_nodes value needs to be updated to 100 in the example to observe the issue as described.

I have attempted step-by-step debugging but haven’t been able to identify the cause of this unwanted padding. Does anyone see any obvious mistakes in my code, or has anyone encountered a similar issue and found a solution?

Java Script Timer

I am trying to make a basketball point counter and I have already a lot of the html.
<!DOCTYPE html>
<html>
<head>
<title>Basketball Point Counter</title>
<script src="Genius_Hour.v.1.1.1.js"></script>
<link rel="stylesheet" href="Genius_Hour. v.1.1.1.css">
</head>
<body>
<h1>Basketball Point Counter</h1>
<div class = "enter">
<input type="number" id="min" min="1" max="60">
<h3>minutes</h3>
<button id = "start">Start!</button>
</div>
<div class="slabel">
<h2 id="hometeam">Home</h2>
<h3>Game Clock</h3>
<h2 id="awayteam">Away</h2>
</div>
<div class="scoring">
<h2 id="homescore">0</h2>
<h3 id="time">0</h3>
<h2 id="awayscore">0</h2>
</div>
</body>
</html>

If anybody could help me, thanks! 🙂

PostgreSQL “Error: could not determine data type of parameter $5”

I’m encountering an issue with my Node.js application when trying to insert data into a PostgreSQL database using the pg module. I have a table named offres with a column date_publication of type DATE. When I attempt to insert data into this table, I’m using the CURRENT_DATE function to automatically insert the current date into the date_publication column.

But when I post my data I receive an “Error: could not determine data type of parameter $5”

this is my current code :

app.post('/', async (req, res) => {
    try {
        const { titre, description, entreprise, lieu, date_limite, type_contrat, salaire, experience, diplome_requis, competences } = req.body;
        const newPost = await db.query('INSERT INTO public.offres(titre, description, entreprise, lieu, date_publication, date_limite, type_contrat, salaire, experience, diplome_requis, competences, created_at, updated_at) VALUES ($1, $2, $3, $4, CURRENT_DATE, $6, $7, $8, $9, $10, $11, NOW(), NOW())',
        [
            titre, 
            description, 
            entreprise, 
            lieu, 
            date_limite, 
            type_contrat, 
            salaire, 
            experience, 
            diplome_requis, 
            competences, 
        ]);
        res.json(newPost.rows[0]);
    } catch (err) {
        console.log(err);
        res.status(500).send('internal server error');
    }
});

I verify If my data-type where correctly set in type date into my psql database and all is good.

So how can I display the current date in date-publication whitout facing this error ?

Using JavaScript I am trying to create a function setQualified. This should set multiple ID’s to qualifiedCompanyValue, but it will only set 1. Why?

I have a function called setQualified. This function is supposed to get a list of bookable company ids and run specific functions if those IDs are in the bookableCompanies variable. The issue I am having is that it will only run the function for the first id in bookable companies. It will never run both functions and it will only set 1 id to the qualifiedCompanyValue. How can I make sure more than 1 id will get set to the qualifiedCompanyValue?

//-----------------------------------------------------------------
//set Qualified Runs Company1Qualified() and beaconQualified();
//Check if user qualified and set Qualified Company
function setQualified(qualificationCode) {
  console.log("Function setQualified");

  const Company1Id = "0011U00002LNeJ9QAL";
  const beaconId = "0011U00002BkHdaQAF";
  let isCompany1Q = "";
  let isBeaconQ = "";

  // Get List of Bookable Companies.
  let bookableCompanies =
    window.formyoula.form_fields["04ed-50d5-70f1"].get("value");
  console.log("Bookable Companies:", bookableCompanies);
  var companiesArray = bookableCompanies.split(",");

  //This is the field where we store the company id of the tour location the user picked.
  //Get [CompanyId] Pg2
  const choosenCompany =
    window.formyoula.form_fields["1a73-1a95-32e3"].get("value");

  if (companiesArray.includes(Company1Id)) {
    isCompany1Q = Company1Qualified(qualificationCode);
    console.log("isQualified Company1:", isCompany1Q);
  }

  if (companiesArray.includes(beaconId)) {
    isBeaconQ = beaconQualified();
    console.log("isQualified Beacon:", isBeaconQ);
  }

  const qualifiedCompanyValue =
    isBeaconQ && isCompany1Q
      ? `${Company1Id}, ${beaconId}`
      : isBeaconQ
      ? beaconId
      : isCompany1Q
      ? Company1Id
      : "";
  const autoTourQualifiedValue = isBeaconQ || isCompany1Q ? "true" : "false";
  //Set [Qualified Company]  Pg 2
  window.formyoula.form_fields["b57d-0a9a-0bf5"].set({
    value: qualifiedCompanyValue,
  });

  console.log("Qualified Companies:", qualifiedCompanyValue);

  //Set [Auto Tour Qaulified] Pg2
  window.formyoula.form_fields["26d6-d9d7-5ccd"].set({
    value: autoTourQualifiedValue,
  });

  // Check if choosenCompany is in the list of qualified companies
  const isChoosenCompanyQualified =
    qualifiedCompanyValue.includes(choosenCompany);
  console.log("Is Choosen Company Qualified:", isChoosenCompanyQualified);

  // If customer is no longer Qualified for the Tour Location they choose
  if (!isChoosenCompanyQualified) {
    // Show a Toastify message if the chosen company is not qualified
    Toastify({
      text: "There no future promotions available for the company you have choosen.",
      duration: 0, // Duration in milliseconds Set duration to 0 to prevent automatic close
      close: true, // show close button
      gravity: "top", // Set the position of the toast top or bottom
      position: "center", // `left`, `center` or `right`
      style: {
        background: "linear-gradient(to right, #EE5A24, #EA2027",
        width: "600px",
        margin: "auto",
        border: "2px solid snow",
        padding: "12px 40px",
      },
      stopOnFocus: true, // Stop the timer when the toast is hovered
    }).showToast();

    // Call the function to reset the tour location fields
    resetTourLocation();

    stopSpinner();
    enableButton("nextBtn");
  } else {
    stopSpinner();
    enableButton("nextBtn");
  }

  // Set hidden field value based on Id - [reScoredCustomer] -Pg1
  window.formyoula.form_fields["f988-036e-4758"].set({
    value: true,
  });
}

Image are not displaying | building a quiz True False app with React js

Images are not displaying on a webpage and the rest is working fine! I am not getting any kind of errors, Some questions have the same images.
enter image description here

JSON FILE (quiz.json) I have around 1000 questions and answers with images stored in a JSON file.

[
    {
      "img": "./img_sign/550.png",
      "q": "In una carreggiata del tipo rappresentato si puu00f2 sorpassare anche in curva",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/550.png",
      "q": "La carreggiata del tipo rappresentato u00e8 a doppio senso di circolazione",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/550.png",
      "q": "In una carreggiata extraurbana del tipo rappresentato le corsie interne sono, di norma, riservate al sorpasso",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/550.png",
      "q": "In una carreggiata del tipo rappresentato non si puu00f2 effettuare l'inversione di marcia",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/550.png",
      "q": "In una carreggiata extraurbana del tipo rappresentato si puu00f2 sorpassare indifferentemente sia da destra che da sinistra",
      "a": "false", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/550.png",
      "q": "In una carreggiata extraurbana del tipo rappresentato si puu00f2 sempre marciare per file parallele",
      "a": "false", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/550.png",
      "q": "In una carreggiata del tipo rappresentato possiamo iniziare un sorpasso anche se il conducente che sta dietro ha giu00e0 iniziato la stessa manovra",
      "a": "false", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "Nella strada rappresentata, per ogni senso di marcia, la corsia di destra u00e8, di norma, dedicata alla marcia ordinaria",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "La strada rappresentata u00e8 composta da tre corsie per ogni senso di marcia",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "Nella strada rappresentata, per ogni senso di marcia, le corsie di centro e di sinistra sono dedicate, di norma, al sorpasso",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "La strada rappresentata u00e8 composta da una carreggiata",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "Nella strada rappresentata, per ogni senso di marcia, la corsia di centro u00e8 dedicata, di norma, alla marcia ordinaria",
      "a": "false", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "Nella strada rappresentata, per ogni senso di marcia, la corsia di destra u00e8 dedicata, di norma, al sorpasso",
      "a": "false", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "La strada rappresentata u00e8 composta da due carreggiate",
      "a": "false", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/552.png",
      "q": "Nella strada rappresentata, per ogni senso di marcia, la corsia di sinistra u00e8 dedicata, di norma, alla marcia ordinaria",
      "a": "false", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/562.png",
      "q": "La strada rappresentata u00e8 composta da tre carreggiate",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/562.png",
      "q": "La strada rappresentata u00e8 composta da otto corsie",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/562.png",
      "q": "Nella strada rappresentata le carreggiate laterali sono, di norma, a senso unico",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/562.png",
      "q": "Nella strada rappresentata la carreggiata centrale u00e8, di norma, a doppio senso di circolazione",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/562.png",
      "q": "La strada rappresentata consente, di norma, il sorpasso anche in curva",
      "a": "true", "options": ["true", "false"]
    },
    {
      "img": "./img_sign/562.png",
      "q": "La strada rappresentata u00e8 composta da quattro carreggiate, tutte a senso unico",
      "a": "false", "options": ["true", "false"]
    }

]

Quiz.jsx This is my code

import { useState, useEffect } from "react";
import questionsData from "../components/quiz.json";
function App() {
const [questions, setQuestions] = useState([]);
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [showScore, setShowScore] = useState(false);
const [score, setScore] = useState(0);

useEffect(() => {
// Shuffle the array of questions
const shuffledQuestions = shuffleArray(questionsData);
// Slice the array to get the first 30 questions
const selectedQuestions = shuffledQuestions.slice(0, 30);
setQuestions(selectedQuestions);
}, []);

const shuffleArray = (array) => {
for (let i = array.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [array[i], array[j]] = [array[j], array[i]];
}
return array;
};

const handleAnswerOptionClick = (selectedOption) => {
if (selectedOption === questions[currentQuestionIndex]?.a) {
  setScore(score + 1);
}

const nextQuestionIndex = currentQuestionIndex + 1;
if (nextQuestionIndex < questions.length) {
  setCurrentQuestionIndex(nextQuestionIndex);
} else {
  setShowScore(true);
}
};

const restartQuiz = () => {
// Shuffle the array of questions again
const shuffledQuestions = shuffleArray(questionsData);
// Slice the array to get the first 30 questions
const selectedQuestions = shuffledQuestions.slice(0, 30);
setQuestions(selectedQuestions);
setCurrentQuestionIndex(0);
setShowScore(false);
setScore(0);
};

const calculateResult = () => {
const passingScore = 27; // Set the passing score here
if (score >= passingScore) {
  return <p className="text-green-500">Congratulations! You passed.</p>;
} else {
  return <p className="text-red-500">Sorry! You failed.</p>;
}
};

return (
<div className="App bg-gray-100 min-h-screen flex justify-center items-center">
  {showScore ? (
    <div className="text-center">
      <h1 className="text-4xl font-bold mb-4">
        You scored {score} out of {questions.length}
      </h1>
      <h2 className="text-xl mb-2">
        You answered {score} questions correctly.
      </h2>
      {calculateResult()}
      <button
        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        onClick={restartQuiz}
      >
        Restart Quiz
      </button>
    </div>
  ) : (
    <div className="text-center">
      <h2 className="text-xl mb-2">
        Question {currentQuestionIndex + 1} of {questions.length}
      </h2>
      <h1 className="text-4xl font-bold mb-4">
        {decodeURIComponent(questions[currentQuestionIndex]?.q)}
      </h1>
      <img
        src={questions[currentQuestionIndex]?.img}
        alt="Question"
        className="max-w-full mb-4"
      />
      <div className="grid grid-cols-2 gap-4">
        {questions[currentQuestionIndex]?.options.map((option, index) => (
          <button
            key={index}
            className="bg-white hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded"
            onClick={() => handleAnswerOptionClick(option)}
          >
            {decodeURIComponent(option)}
          </button>
        ))}
      </div>
    </div>
  )}
</div>
);
 }

export default App;

Any suggestions would be helpful Thank you!

WordPress jquery form submit

I have some jquery that i plug some numbers in via some text fields then it should print out the results, this works fine on my local machine.

However when I add to my wordpress environment the submit button just refreshes the page..

any idea why this is ?

jQuery("#roi").submit(function (event) {
  event.preventDefault();
  window.cost_by_industry = parseInt($("#cost_by_ind").val());
  window.cost_by_employee_count = parseInt($("#cost_by_employee_c").val());
  window.no_empoyees = parseInt($("#no_emp").val());
  window.month_invest = parseInt($("#month_inv").val());
  window.expected_a_grow = 0.05;
  window.aas = 120000;
  window.fpr = 0.75;
  window.avr = 0.75;

  //managed risk year 1
  var roiCalc = function () {
    return ((0.3 * (cost_by_industry + cost_by_employee_count)) / 2) * 0.2;
  };
  var result = roiCalc();
  const formattedPrice1 = result.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //managed risk year 2
  var roiCalc2 = function () {
    return result * (1 + expected_a_grow);
  };
  var result2 = roiCalc2();
  const formattedPrice2 = result2.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //managed risk year 3
  var roiCalc3 = function () {
    return result2 * (1 + expected_a_grow);
  };
  var result3 = roiCalc3();
  const formattedPrice3 = result3.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //managed risk total
  var roiCalcfinal = function () {
    return result + result2 + result3;
  };
  var results_total = roiCalcfinal();
  const formattedPrice_total_mr = results_total.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //Empower Analysts year 1
  var roiCalc_emp_1 = function () {
    return (no_empoyees / 2000) * aas;
  };
  var ea_result = roiCalc_emp_1();
  const formattedPrice_ea_1 = ea_result.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //Empower Analysts year 2
  var roiCalc_emp_2 = function () {
    return ea_result * (1 + expected_a_grow);
  };
  var ea_result2 = roiCalc_emp_2();
  const formattedPrice_ea_2 = ea_result2.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //Empower Analysts year 3
  var roiCalc_emp_3 = function () {
    return ea_result2 * (1 + expected_a_grow);
  };
  var ea_result3 = roiCalc_emp_3();
  const formattedPrice_ea_3 = ea_result3.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  ///Empower Analysts total
  var roiCalc_emp_final = function () {
    return ea_result + ea_result2 + ea_result3;
  };
  var emp_results_total = roiCalc_emp_final();
  const formattedPrice_total_ea = emp_results_total.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //TP year 1
  var tp1 = function () {
    return month_invest * (1 - fpr) * 3 * 2 * (aas / 2080) * 12;
  };
  var tp1_results = tp1();

  //FP year 1
  var fp1 = function () {
    return month_invest * fpr * 3 * 1 * (aas / 2080) * 12;
  };
  var fp1_results = fp1();

  //TP year 2
  var tp2 = function () {
    return month_invest * (1 - avr) * (1 - fpr) * 3 * 1 * (aas / 2080) * 12;
  };
  var tp2_results = tp2();

  //fp year 2
  var fp2 = function () {
    return month_invest * (1 - avr) * fpr * 3 * 0.5 * (aas / 2080) * 12;
  };
  var fp2_results = fp2();

  //reduce aleart vol year 1
  var rav1 = function () {
    return tp2_results + fp2_results + tp1_results + fp1_results;
  };
  var rav_results_1 = rav1();
  const formattedPrice_year_rav_1 = rav_results_1.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //reduce aleart vol year 2
  var rav2 = function () {
    return rav_results_1 * (1 + expected_a_grow);
  };
  var rav_results_2 = rav2();
  const formattedPrice_year_rav_2 = rav_results_2.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //reduce aleart vol year 3
  var rav3 = function () {
    return rav_results_2 * (1 + expected_a_grow);
  };
  var rav_results_3 = rav3();
  const formattedPrice_year_rav_3 = rav_results_3.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  //reduce aleart vol total
  var rav_total = function () {
    return rav_results_1 + rav_results_2 + rav_results_3;
  };
  var rav_results = rav_total();
  const formattedPrice_total_rav = rav_results.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
  });

  $("#output").show();
  $(".manage_risk_1").text(formattedPrice1);
  $(".manage_risk_2").text(formattedPrice2);
  $(".manage_risk_3").text(formattedPrice3);
  $(".results_total").text(formattedPrice_total_mr);
  $(".emp_results_1").text(formattedPrice_ea_1);
  $(".emp_results_2").text(formattedPrice_ea_2);
  $(".emp_results_3").text(formattedPrice_ea_3);
  $(".emp_results_total").text(formattedPrice_total_ea);
  // $(".tp1_results").text(tp1_results);
  // $(".tp2_results").text(tp2_results);
  // $(".fp1_results").text(fp1_results);
  // $(".fp2_results").text(fp2_results);
  $(".rav_results_1").text(formattedPrice_year_rav_1);
  $(".rav_results_2").text(formattedPrice_year_rav_2);
  $(".rav_results_3").text(formattedPrice_year_rav_3);
  $(".rav_results_total").text(formattedPrice_total_rav);
});
#output {
  display: none;
  font-size: 26px;
  margin-top: 50px;
}
.help-inline {
  display: none;
}
.result {
  padding-top: 10px;
}
.roi-success {
  background: #269526;
  color: white;
}
.roi-danger {
  background: #d74e26;
  color: white;
}
input[type="text"] {
  width: 100%;
  display: block;
  margin: 15px 0;
}
.btn {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-lg-8 col-lg-offset-2">
      <h1>Calculator</h1>
      <p class="lead">copy copy copy </p>
      <form id="roi">
        <b>test</b>
        <select id="cost_by_ind">
          <option value="10930000">Healthcare</option>
          <option value="5900000">Financial</option>
          <option value="4820000">Pharmaceuticals</option>
          <option value="4780000">Energy</option>
        </select>
        <b>Cost by employe count</b>
        <select id="cost_by_employee_c">
          <option value="3310000">0 - 499</option>
          <option value="3290000">500 - 1000-</option>
          <option value="4870000">1001 - 5000</option>
          <option value="4330000">5001 - 10000</option>
          <option value="5460000">10001 - 25000</option>
          <option value="5420000">25001 - 100000</option>
        </select>

        <div class="control-group">
          <b>No Employees</b>
          <input id="no_emp" class="form-control" type="text" placeholder="Number of Employees">
        </div>
        <div class="control-group">
          <b>Monthly </b>
          <input id="month_inv" class="form-control" type="text" placeholder="Monthly Investigations">
        </div>
        <button type="submit" class="btn btn-primary btn-block">Calculate ROI</button>
      </form>
      <!--show output here-->
      <div class="well" id="output">

        <p> year 1 = <span class="manage_risk_1"></span></p>
        <p> year 2 = <span class="manage_risk_2"></span></p>
        <p> year 3 = <span class="manage_risk_3"></span></p>
        <strong>Total k = <span class="results_total"></span></strong>

        <p>Es year 1 = <span class="emp_results_1"></span></p>

        <p>year 2 = <span class="emp_results_2"></span></p>

        <p>year 3 = <span class="emp_results_3"></span></p>

        <strong>Total   = <span class="emp_results_total"></span></strong>

        <!--         <p>TP1 <span class="tp1_results"></span></p>

        <p>TP2 <span class="tp2_results"></span></p>

        <p>FP1 <span class="fp1_results"></span></p>

        <p>FP2 <span class="fp2_results"></span></p> -->

        <p> year 1 = <span class="rav_results_1"></span></p>

        <p> year 2 = <span class="rav_results_2"></span></p>

        <p> year 3 = <span class="rav_results_3"></span></p>

        <strong>Total  = <span class="rav_results_total"></span></strong>
      </div>
    </div>
  </div>
</div>

Validate.js + Choices.js – Rule Required Not Working

Hope everything fine with all.
I’m trying to do a validation with my form, using “validate.js”, but I have the “Choices.js” to show my select field in a beaultiful way, but when I try to put a rule to validate if this field is in blank, it seems that nothing happen, the field it’s ignored and I dont get the error.

— Validate.js + Choices.js: Field “ID_Blog_Tag” -> Not Working

— Only Validate.js: Field “ID_Blog_Tag_2” – Working

Important point is that the “ID_Blog_Tag_2″ select works because I’m not using Choices.js and I have the required=”true” and .

For field “ID_Blog_Tag”, that dont works, I tried to use with required=”true” but didn’t worked.

Then I used some alerts to help me try to understand:

— alert($(‘#ID_Blog_Tag’).val()); –> Lenght of 1, but showed in blank

— alert($(‘#ID_Blog_Tag option:selected’).val()); –> UNDEFINED

Then I tried to use function inside the rules with return false or alert (But didn’t worked):

rules:{
    ID_Blog_Tag:{
        required: function(element) {
            return false;
        }
    }
}

I really need some help, suggestion, light here on what I can do! And I can change the Choices.js because there’s another form using that.

My HTML:

<form name="Form__Send">
    <div class="card-header justify-content-between">
        <div class="card-title">Formulário</div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-6">
                <div class="mb-3">
                    <label class="form-label fs-14 text-dark" for="Titulo">Título</label>
                    <input type="text" class="form-control" id="Titulo" name="Titulo">
                </div>
            </div>
            <div class="col-6">
                <div class="mb-3">
                    <label class="form-label fs-14 text-dark" for="ID_Blog_Tag_2">Tag</label>
                    <select class="form-select" id="ID_Blog_Tag_2" name="ID_Blog_Tag_2" required="true">
                        <option value=""></option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label fs-14 text-dark" for="ID_Blog_Tag">Tag</label>
                    <select class="form-control" id="ID_Blog_Tag" name="ID_Blog_Tag" required="true" multiple>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                </div>
            </div>
            <div class="col-6">
                <div class="mb-3">
                    <label class="form-label fs-14 text-dark" for="Imagem" >Imagem</label>
                    <div class="filepond--div"><input type="file" class="multiple-filepond" id="Imagem" name="Imagem" accept="image/jpeg, image/png, image/webp" data-allow-reorder="true" data-max-files="4" data-max-file-size="3MB" multiple></div>
                </div>
            </div>
            <div class="col-12 text-center">
                <button type="submit" class="btn btn-success" id="Btn__Send">Enviar</button>
                <button type="button" class="btn btn-danger" id="Btn__Cancel">Cancelar</button>
            </div>
        </div>
    </div>
</form>

My JS:

(function(){
    "use strict";
    const multipleCancelButton = new Choices(
        '#ID_Blog_Tag',{
            allowHTML: true,
            removeItemButton: true,
            placeholderValue: 'Clique para selecionar',
            maxItemCount: 2,
            delimiter: ',',
            paste: false,
            duplicateItemsAllowed: false,
            editItems: false,
            loadingText: 'Carregando',
            noResultsText: 'Nenhum resultado encontrado',
            noChoicesText: 'Não há opções para escolher',
            itemSelectText: 'Clique para selecionar'
        }
    );
})();
$(function(){
    $("form[name='Form__Send']").validate({
        // >>>>> VALIDATION
        onclick: false,
        onkeyup: false,
        rules:{
            Titulo:{
                required: true
            },
            ID_Blog_Tag_2:{
                required: true
            },
            ID_Blog_Tag:{
                required: true
            },
            Imagem:{
                required: true
            }
        },
        messages:{
            Titulo:{
                required: "<i class="ri ri-arrow-right-s-line"></i> Adicionar título!<br />"
            },
            ID_Blog_Tag_2:{
                required: "<i class="ri ri-arrow-right-s-line"></i> Adicionar TAG 2!<br />"
            },
            ID_Blog_Tag:{
                required: "<i class="ri ri-arrow-right-s-line"></i> Adicionar tag!<br />"
            },
            Imagem:{
                required: "<i class="ri ri-arrow-right-s-line"></i> Adicionar imagem!<br />"
            }
        },
        errorPlacement: function(error, element){
            return false;
        },
        invalidHandler: function(form, validation){
            var Str__Error  = "";
            var Str__Qty    = validation.numberOfInvalids();
            if(Str__Qty){
                if(validation.errorList.length > 0){
                    for(x=0;x<validation.errorList.length;x++){
                        Str__Error += validation.errorList[x].message;
                    }
                }
                Swal.fire({
                    backdrop: 'rgba(0,0,0,0.15)',
                    background: 'rgba(255,255,255,1)',
                    confirmButtonColor: '#228822',
                    confirmButtonText: 'Ok',
                    customClass: {
                        cancelButton: 'no-select',
                        confirmButton: 'btn-info no-select',
                        footer: 'no-select',
                        htmlContainer: 'no-select',
                        title: 'no-select'
                    },
                    focusConfirm: false,
                    html:
                        'Formulário com '+Str__Qty+' erro(s)!<br /><br />'+
                        '<div class="text-center">'+
                            '<div class="d-inline-block text-start">'+
                                Str__Error+
                            '</div>'+
                        '</div>',
                    icon: 'error',
                    showCancelButton: false,
                    showCloseButton: false,
                    showConfirmButton: true,
                    title: 'Erro'
                })
            }
        },
        submitHandler: function(form){
            Swal.fire({
                backdrop: 'rgba(0,0,0,0.15)',
                background: 'rgba(255,255,255,1)',
                cancelButtonColor: '#DD3333',
                cancelButtonText: 'Cancelar',
                confirmButtonColor: '#228822',
                confirmButtonText: 'Enviar',
                customClass: {
                    cancelButton: 'btn btn-danger no-select',
                    confirmButton: 'btn btn-success no-select',
                    footer: 'no-select',
                    htmlContainer: 'no-select',
                    title: 'no-select'
                },
                focusCancel: false,
                focusConfirm: false,
                html: 'Voc&ecirc; deseja enviar os dados inseridos no formul&aacute;rio?',
                icon: 'warning',
                showCancelButton: true,
                showCloseButton: false,
                showConfirmButton: true,
                title: 'Enviar formulário'
            }).then((result) => {
                if(result.value){
                    // >>>>> AJAX
                    $.ajax({
                        
                    });
                }else if(result.dismiss === Swal.DismissReason.cancel){
                    
                }
            });
        }
    });
});

What is the reason for not being able to retrieve the token value in a GET request?

I found two instances of localhost in the developer tools network tab. So when navigating to ‘/’, the first entry is of type ‘document’ with localhost, and the second entry is of type ‘xhr’ also with localhost. I noticed that only the second type contains the token value in the request headers.

server.js

app.get('/', loginRequired, (req, res) => {
    res.sendFile(__dirname + '/views/index.html'); 
});

login-required.js

const jwt = require('jsonwebtoken');

const loginRequired = async (req, res, next) => {
    // TEST CODE
    const userToken = req.headers["authorization"]?.split(' ')[1];
    console.log(userToken + '  TEST===1');

    // if(userToken) { <= The page experiences infinite loading when using this logic.
    //     next(); <= (userToken === undefined)
    // }
    next() // undefined value and the actual token **sequence are printed in the console.**

}

module.exports = loginRequired;

test.js (front)

const userToken = localStorage.getItem('token');
if (userToken) {
    const headers = {
        authorization: `Bearer ${userToken}`,
    };

    axios.get('/', { headers, withCredentials: true })
        .then(response => {
            // console.log(response.data);
        })
        .catch(error => {
            console.error(error);
        });
} else {
    // Handle case when token doesn't exist
}

test.js is linked to index.html via a script tag.

The cause I am considering is as follows.
(1) Send a GET request to (‘/’).
(2) The server executes loginRequired.
(3) loginRequired is executed while not receiving HTML from the server, resulting in the token value becoming undefined.
(4) After passing through next(), the server responds with HTML from the client.
(5) Display the HTML in the browser and load the JavaScript associated with that HTML.
(6) At this point, the loaded JavaScript retrieves the logic of sending a GET request (/) and retrieves the token value again from the server.js as a response to loginRequired.

In other words, the JavaScript needs to be loaded in order to retrieve the userToken from local storage and make a request to fetch the token value.

However, shouldn’t token validation and authorization occur before the GET request, ensuring that the HTML is loaded only after permission is granted?

I need your advice. Thank you.

Defining File Path in HTML js

I want to run some js files that run online offline.

I write the selected part in the image as ‘./www-static/doc/phsss.js’. (It works in the photo.) But I fail.

As a similar example:
Working: page_params.jqueryVersion = ‘https://aaa.com/www-static/js/lib/jquery-3.6.0.min.js’;
Not Working: page_params.jqueryVersion = ‘./www-static/doc/jquery-3.6.0.min.js’;

How can I solve the problem?

How to drag and drop with the flexbox -javascript

I am working to drag and drop horizontally and trying to use flexbox for positioning.

And I am having 2 problems.

First, even when the list-container is not flexbox (it is set to block), the items are not being drag and drop as it should. As the item goes further to right, the x-offset (I think…) becomes bigger. I think it might have to do with the fact that list-items are set to float left? but I am unsure.

The second problem I am having is that when I try to set the list-container to flex it does not work. I searched and it had to do with the fact flex now have rows, not just columns but I don’t understand how to implement that with my current codes.

Here are my codes:

html

<div class="list-container clicked__clue" id="books">
        <ul class="list">
          <li class="list-item book4" draggable="true">
            <a class="list-item-name">기이현상청 사건일지</a>
          </li>
          <li class="list-item book1" draggable="true">
            <a class="list-item-name">맨 끝줄 소년</a>
          </li>
          <li class="list-item book5" draggable="true">
            <a class="list-item-name">억지로라도 쉬어가라</a>
          </li>
          <li class="list-item book3" draggable="true">
            <a class="list-item-name">로펌 인 코리아</a>
          </li>
          <li class="list-item book7" draggable="true">
            <a class="list-item-name">거미 여인의 키스</a>
          </li>
          <li class="list-item book6" draggable="true">
            <a class="list-item-name">을사늑약 1905</a>
          </li>
          <li class="list-item book9" draggable="true">
            <a class="list-item-name">다른 방식으로 보기</a>
          </li>
          <li class="list-item book2" draggable="true">
            <a class="list-item-name">발이 없는 나의 여인은 노래한다</a>
          </li>
          <li class="list-item book8" draggable="true">
            <a class="list-item-name">닐과 순다리</a>
          </li>
        </ul>
      </div>

javascript

const list = document.querySelector(".list");

let draggedTarget;
let helper;
document.addEventListener("dragstart", function(e) {
  draggedTarget = e.target;

  helper = document.createElement("div");
  helper.innerText = draggedTarget.querySelector(".list-item-name").innerText;
  helper.style.position = "absolute";
  helper.style.top = "-9999px";
  helper.style.padding = "1rem";
  helper.style.backgroundColor = "#000";
  helper.style.color = "#ddd";
  helper.style.fontSize = "1.5rem";
  helper.style.fontFamily = "Consolas";
  document.querySelector(".top").appendChild(helper);
  
  e.dataTransfer.setDragImage(helper, 0, 0);
});

document.addEventListener("dragenter", function(e) {
  if (e.target !== draggedTarget && e.target.classList[0] === "list-item") {
    const ep = e.target.previousElementSibling;
    const en = e.target.nextElementSibling;
    const dp = draggedTarget.previousElementSibling;
    const dn = draggedTarget.nextElementSibling;

    if (!ep && !dn) {
      list.removeChild(draggedTarget);
      e.target.insertAdjacentElement("beforebegin", draggedTarget);
    } else if (!en && !dp) {
      list.removeChild(draggedTarget);
      e.target.insertAdjacentElement("afterend", draggedTarget);
    } else if (ep && ep != draggedTarget) {
      list.removeChild(e.target);
      list.removeChild(draggedTarget);
      ep.insertAdjacentElement("afterend", draggedTarget);
      draggedTarget.insertAdjacentElement("afterend", e.target);
    } else if (!ep) {
      list.removeChild(e.target);
      list.removeChild(draggedTarget);
      dn.insertAdjacentElement("beforebegin", e.target);
      e.target.insertAdjacentElement("beforebegin", draggedTarget);
    } else if (en && en != draggedTarget) {
      list.removeChild(e.target);
      list.removeChild(draggedTarget);
      en.insertAdjacentElement("beforebegin", draggedTarget);
      draggedTarget.insertAdjacentElement("beforebegin", e.target);
    } else if (!en) {
      list.removeChild(e.target);
      dp.insertAdjacentElement("afterend", e.target);
    }
  } 
});

document.addEventListener("dragover", function(e) {
  e.preventDefault();
});

document.addEventListener("drop", function(e) {
  e.preventDefault();
  helper.parentNode.removeChild(helper);
}); 

Print the first text – delete it and then print the second text

I had previously created a question similar to this:

Display the second text after finishing printing the first text

But now I want to print a text, then delete it word by word at the same speed as I printed the text, and then type the second text at the same speed.
For this purpose, I wrote the following code:

const text1 = "Your first sentence here"; // Enter your first sentence here
const text2 = "Your second sentence here"; // Enter your second sentence here

let i = 0;

function typeSentence(text, element) {
  const interval = setInterval(() => {
    if (i === text.length) {
      clearInterval(interval);
      if (text === text1) {
        clearText();
      }
    } else {
      element.text(element.text() + text[i]);
      i++;
    }
  }, 100); // Speed of animation (adjust as needed)
}

function clearText() {
  const interval = setInterval(() => {
    if (!$("#loading-text").text()) {
      clearInterval(interval);
      typeSentence(text2); // Call typeSentence to print the second sentence
    } else {
      $("#loading-text").text($("#loading-text").text().substring(0, $("#loading-text").text().length - 1));
    }
  }, 100); // Speed of animation (adjust as needed)
}

typeSentence(text1, $('#loading-text'));
 #loading-text {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin: 20px auto;
            width: 50%;
            opacity: 1;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="loading-text"></div>

The above code correctly types and deletes the first text, but does not type the second text!

According to the answer that was created for my previous question, I edited the code as follows:

const text1 = "Your first sentence here"; // Enter your first sentence here
const text2 = "Your second sentence here"; // Enter your second sentence here

const texts = [text1, text2]; // Array of sentences
const element = $('#loading-text'); // Element to display text

let i = 0;
let currentTextIndex = 0; // Index of the current sentence in the array

function typeSentence() {
  if (i < texts[currentTextIndex].length) {
    element.text(element.text() + texts[currentTextIndex][i]);
    i++;
  } else {
    if (currentTextIndex < texts.length - 1) {
      // Clear the element and move to the next sentence
      clearText();
    } else {
      clearInterval(tId); // Stop typing if all sentences are finished
    }
  }
}

function clearText() {
  i = 0; // Reset character index
  currentTextIndex++; // Move to the next sentence in the array
  element.text(""); // Clear the element content
}

// Start typing the first sentence
const tId = setInterval(typeSentence, 100); // Speed of animation (adjust as needed)
 #loading-text, #loading-text2 {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin: 20px auto;
            width: 50%;
            opacity: 1;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="loading-text"></div>

This code correctly prints the second text, but creates a new problem!

After printing the first text, it should be deleted at the previous speed, and then the second text is printed, but this does not happen, and after the first text is printed, it immediately disappears and the second text starts to be printed!

How do I get a type safe function return value in this case?

I’ve got the following code:

const soil = {
  roots: {
    test: testRoot({test: 'hi'}),
    blank: blankRoot({blank: 'hi'}),
  },
};

soil.roots.test is of type Hive<TestRootInput, TestRootOutput> and
soil.roots.blank is of type Hive<BlankRootInput, BlankRootOutput>.

Find the type Hive below:

type Hive<T, K> = {
  set: (newValue: Partial<T>) => void;
  listen: (listenFunction: HiveListenFunction<K>) => void;
  value: K;
};

I can do the below console.log, and my IDE gives me the suggestion for the property test2 because it is known beforehand.

console.log(soil.roots.test.value.test2)
// output: "hi"

Then, I’ve got the function sap, which returns the values of the passed Root objects:

type BranchSap = {
  roots: Root<any, any>[];
};

const sap = <T extends BranchSap>(sap: T): T['roots'][number]['value'][] => {
  const roots = sap.roots;

  return roots.map(root => root.value);
};

I then call the function sap like this:

const testSap = sap({roots: [soil.roots.test, soil.roots.blank]});

I can now console log the following:

console.log(testSap[0], testSap[1]);
// output: {test2: 'hi'} {blank2: 'hi'}

However, my IDE does not allow me to access the property test2 on testSap[0] and blank2 on testSap[1] because they are not known.

How can I rewrite the function sap to return strongly typed values?

I am trying to write function which accepts an Array of generic types, and have this function return a strongly typed result.

Vue animation :: warning issue

I have a working example of VUE JS menu animation … however the problem is I have two root elements inside the menu component…

App.vue

<script setup>
import { ref } from 'vue'
import Menu from './Menu.vue'

const menuVisible = ref(false)
const toggle = () => {
  menuVisible.value = !menuVisible.value
}
</script>

<template>
  <h1>Side bar animation</h1>
  <button @click="toggle">Toggle menu</button>
  <Menu :visible="menuVisible" @update:visible="toggle" v-show="menuVisible"/>
</template>

Menu.vue

<script setup lang="ts">
import {  toRefs, watchEffect, onBeforeUnmount, onMounted } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  }
});

const { visible } = toRefs(props);

const emit = defineEmits(['update:visible']);

const hidemenuBar = () => {
  emit('update:visible', false);
};

watchEffect(() => {
  document.body.style.overflow = visible.value ? 'hidden' : 'auto';
  document.body.style.paddingRight = visible.value ? '15px' : '0px';
});

onBeforeUnmount(() => {
  document.body.style.overflow = 'auto';
  document.body.style.paddingRight = '0px';
});

</script>

<template>
  <transition name="fade">
    <div v-if="visible" class="menubar-overlay" @click="hidemenuBar"></div>
  </transition>
  <transition name="slide">
    <div class="menubar-container" v-if="visible">
      <div class="menubar__header">
        <h2 class="menu-headline">Menu</h2>
        <div>
          <i @click="hidemenuBar" class="cursor-pointer pi pi-times p-2"></i>
        </div>
      </div>
       <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
       </ul>
       <button @click="hidemenuBar">Close</button>
    </div>
  </transition>
</template>

<style scoped>
.slide-enter-from,
.slide-leave-to {
  transform: translateX(100%);
}

.slide-enter-to,
.slide-leave-from {
  transform: translateX(0);
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 1s;
}

/* menubar */
.menubar-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.7);
  cursor: pointer;
}
.menubar-container {
  position: fixed;
  display: grid;
  align-items: start;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  max-width: 200px;
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  margin-left: auto;
  background-color: white;
  z-index: 100;
}

.menubar__header {
  z-index: 2;
  display: flex;
  justify-content: space-between;
  margin: 20px;
  border-bottom: 2px solid black;
}
</style>

However, the problem is when I wrap the transitions in Menu.vue into a template the animation doesn’t work at all… if I wrap it in a div, it only works one-way (slide-in, no slide-out)

Any idea how to fix it?

Playground: here