How to use an imported Excel file inside Anylogic model

I have detailed wind historical data on an Excel sheet, (Speed and Direction) categorized by hour, day, month, and year, and I have imported the file into Anylogic by the builtin tool, however, I searched and I knew that in order to use the data in the Excel file I have to include the data into a Data Set, but I can’t find any field in the “Properties” of the Data set that can link the Excel sheet to this Data set, anyone can help me do that?

what I want to do is for the Anylogic to check the table (row by row for each hour of the day) and create a dynamic variable, so when the wind speed is larger than a certain number (for example 10 m/s), then this wind speed will trigger another condition.

I have tried the Anylogic help, I asked Chat GPT 3.5, but its knowledge stops at the Anylogic version of January 2022, so it’s not that recent, and I tried finding a few papers but with no luck.

webpack 5 historyApiFallback does not solve the refresh issue in react application, no matter what is done?

i have created a react app using node backend. everything works fine, except when any page from the app is refreshed, and then it shows a ton of 404s. from reading around i have understood that historyApiFallback should solve this issue, but for whatever reason i can not get it to work. page refresh still results in 404s.

i’ve tried to configure the devserver in many many ways i;ve found in several of posts here, but no way works. i’ve tried to use historyApiFallback.rewrites, simply set it to true, used index : ‘/’
also added the publicPath:’/’ in the output, have also added the base tag in the index.html, but no good news.

any direction would be helpful right now..

webpack.config.js


const port = 3000;
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output:{
       path: path.resolve(__dirname,'/dist'),
       filename:'main.[fullhash].js',
       publicPath: "/",
    },
    module:{
        rules:[

            {
                test:/.(js|jsx)$/,
                exclude: /node_modules/,
                use:[
                    {loader:"babel-loader"},
                ],
                
                
            },

            {
                test:/.css$/,
                use:[
                    "style-loader",
                    "css-loader"
                ],
            }

        ]

    },
    plugins:[
       new HtmlWebpackPlugin({
           template:'./public/index.html',
       })
    ],
    devServer:{
        port: 3000,
        historyApiFallback:{
            rewrites: [
                { from: /./, to: './index.html' }
            ],
            index: 'index.html',
        },
        //historyApiFallback:true,
        open:true
    }

}

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <base href="/"/>
    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JS to run this app.</noscript>
    <div id="root"></div>
    <div id="portal"></div>
    
  </body>
</html>

HTML sanitization removes allowed attributes and styles

The html sanitization leaves only SAMPLE text from SAMPLE text. The text is sanitized by both sanitize and sanitizeforCards. Why do the sanitizers remove style=”color: rgb(230, 0, 0);” from the span tag?

My sanitizer is below:

import sanitizeHtml from 'sanitize-html'

const sanitizerConfig = {
  allowedTags: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'div', 'b', 'i', 'strong', 'em', 'span', 'ul', 'ol', 'li', 'a',
    'u', 's', 'br'],
  allowedAttributes: {
    a: ['href', 'target', 'style'],
    span: ['style'],
    h1: ['style'],
    h2: ['style'],
    h3: ['style'],
    h4: ['style'],
    h5: ['style'],
    h6: ['style'],
    p: ['style'],
    div: ['style'],
    b: ['style'],
    i: ['style'],
    strong: ['style'],
    em: ['style'],
    ul: ['style'],
    ol: ['style'],
    li: ['style'],
    u: ['style'],
    s: ['style']
  },
  allowedStyles: {
    '*': {
      'text-align': [/^left$/, /^right$/, /^center$/]
    },
    span: {
      'text-decoration': [/^underline$/],
      color: true
    }
  }
}
const sanitizerConfigForCards = {
  allowedTags: ['p', 'div', 'b', 'i', 'strong', 'em', 'span', 'ul', 'ol', 'li'],
  allowedAttributes: {
    span: ['style']
  },
  allowedStyles: {
    span: {
      color: true
    }
  }
}

export const sanitize = (content) => sanitizeHtml(content, sanitizerConfig)
/** Sanitizes user-generated html content for displaying it inside of card components. */
export const sanitizeforCard = (content) => sanitizeHtml(content, sanitizerConfigForCards)

Uncaught ReferenceError: process is not defined using vite

i am facing this issue

Uncaught ReferenceError: process is not defined
at module.exports (cloudinary.js?v=2e344892:6593:34)
at ../backend/node_modules/cloudinary/lib/utils/index.js (cloudinary.js?v=2e344892:9716:56)
at __require2 (chunk-624QZG55.js?v=9b95bc90:16:50)
at ../backend/node_modules/cloudinary/lib/cloudinary.js (cloudinary.js?v=2e344892:14211:21)
at __require2 (chunk-624QZG55.js?v=9b95bc90:16:50)
at ../backend/node_modules/cloudinary/cloudinary.js (cloudinary.js?v=2e344892:14366:22)
at __require2 (chunk-624QZG55.js?v=9b95bc90:16:50)
at cloudinary.js?v=2e344892:14369:16

i am using cloudinary.js file to upload files to cloudinary and using process.env values but now i am facing this above error in console.
i have not used any env value in fronted code.
frontend and backend folder have different package.json files

i am expecting to resolve this error

How to resize maximized child window programmatically

I want to launch my web application in maximized window (not full screen) application mode from command line.

This is my script to launch the app:

$flags = "--app=$applicationUrl --new-window --start-maximized"
(New-Object -ComObject WScript.shell).Run('chrome.exe ' + $flags)

My app launched in maximized window, application mode.

But the problem is, when I open a child window from my application, the child window is also in maximized size. Which I don’t want it.

I want the child window to be able to resize to a fixed height and width.

I have tried to use the window.resizeTo(1400, 1000) function to resize the child window, it is not working while child window is in maximized size.

If I click the restore down button on the child window to make it small first, for example 800,600. Then run the window.resizeTo(1400, 1000) it will work.

How can I achieve this?

Is there a way to mimic the restore down button behavior using JavaScript?

node js: req.body returns empty object even with express.json() and express.urlencoded()

body` of form in my database but it returns empty object even with express.json() and express.urlencoded()
i tried it with body-parser too and even log it in console but it is the same

this is main index:

const app = express();
let port = 3000;
const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default class Application {
  constructor() {
    this.setConfigServer();
    this.configDatabase();
    this.setConfig();
    this.setRoutes();
  }
  setConfigServer() {
    app.listen(port, () => {
      console.log(`server is listening to port ${port}`);
      console.log("http://localhost:3000");
    });
  }

  async configDatabase() {
    await mongoose.connect("mongodb://localhost:27017/test");
  }

  setConfig() {
    app.use(express.static(__dirname + "/public"));
    app.set("view engine", "ejs");
    app.set("views", path.join(__dirname, "/views"));
    app.use(expressEjsLayout);
    app.set("layout extractScripts", true);
    app.set("layout extractStyle", true);
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
  }

  setRoutes() {
    app.use(routes.router);
  }
}

router file ===>

const router = express.Router();
const SignInController = new signInController()

router.get("/register",SignInController.getForm)
router.post("/register",(req,res)=>{
        res.setHeader("Content-Type", 'application/json');
        req.header("Content-Type", 'application/json');
        res.write("you posted:n");
        res.end(JSON.stringify(req.body));
})

export default{router}

Changing the color of a parent div to the color of active child element on click

Pretty much what’s written above, I want to change the color of the container div so that it reflects the color of specific selected active elements.

So for example, the container’s background is a shade of grey – when I click on the element, the element contains a blue background. I want that blue background to then fill the grey element. And so on and so forth with different selected elements and colors. I only included one element, but at least 4 more elements will need this coding.

I imagine this needs to be done with Javascript? I have seen solutions for on hover and they required JS.


<div id="tabTopBar">
        <div class="tabTop">
            <a id="armory" href="armory.html" class="active">Armory</a>
            <a id="peerless" href="peerless.html">Peerless</a>
        </div>
    </div>

Respective css


#tabTopBar {
    margin: 0;
    padding: 0;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 50px;
    background-color: #dddddd;
}

.tabTop {
    overflow: hidden;
    border: 1px solid black;
    background-color: gray;
}

#armory.active {
    background-color: #0e343d;
    color: white;
    pointer-events: none;
}

#armory:hover {
    background-color: #879a9e;
    color: black;
}

#peerless.active {
      background-color: #bab757;
      color: white;
      pointer-events: none;
}

#peerless:hover {
      background-color: #dcdbab;
      color: black;
}

#tabTopBar {
    margin: 0;
    padding: 0;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 50px;
    background-color: #dddddd;
}

.tabTop {
    overflow: hidden;
    border: 1px solid black;
    background-color: gray;
}

.tabTop a {
    float: left;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
}

#armory.active {
    background-color: #0e343d;
    color: white;
    pointer-events: none;
}

#armory:hover {
    background-color: #879a9e;
    color: black;
}

#peerless.active {
    background-color: #bab757;
    color: white;
    pointer-events: none;
}

#peerless:hover {
    background-color: #dcdbab;
    color: black;
}
   <div id="tabTopBar">
        <div class="tabTop">
            <a id="armory" href="#armory" class="active">Armory</a>
            <a id="peerless" href="#peerless">Peerless</a>
        </div>
    </div>

Unable to submit web app form data to google sheets because “form is unavailable”

I just started getting a “Sorry, unable to open the file at this time” error while trying to submit web app data to google sheets. It hasn’t ever happened before.

Weird thing is, the dropdown values in my form still are being populates from the google sheet columns. Permissions are correct–anyone with a link has access as an editor.

When I execute the code, it runs fine. I suspect it coming from my doGet function, but im not sure.

Code.gs

// Function to handle GET requests
function doGet(e) {
  try {
    var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect');
    var subs = getDistinctSubstations();
    var url = getUrl();
    htmlOutput.message = '';
    htmlOutput.subs = subs;
    htmlOutput.url = url;
    return htmlOutput.evaluate();
  } catch (error) {
    return HtmlService.createHtmlOutput('Error: ' + error.message);
  }
}

// Function to handle POST requests
function doPost(e) {
  var parcel = e.parameter.parcel.toString();
  var substation = e.parameter.substation.toString();
  var comment = e.parameter.comment.toString();
  var status = e.parameter.status.toString();
  var date = new Date();
  
  // Check if the record already exists based on parcel and status
  if (!isDuplicateStatus(parcel, status)) {
    addRecord(comment, parcel, date);
    addToStatuses(parcel, status, date);
    deleteDuplicateRows(); // Delete duplicate rows after adding the new record
    var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect');
    var subs = getDistinctSubstations();
    htmlOutput.message = 'Record Added';
    htmlOutput.subs = subs;
    return htmlOutput.evaluate(); 
  } else {
    return ContentService.createTextOutput("Duplicate status submission found. Record not added.");
  }
}

// Function to check for duplicate status submissions
function isDuplicateStatus(parcel, status) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var statusSheet = ss.getSheetByName("Statuses");
  var dataRange = statusSheet.getRange(3, 1, statusSheet.getLastRow() - 2, statusSheet.getLastColumn());
  var data = dataRange.getValues();
  
  for (var i = 0; i < data.length; i++) {
    if (data[i][0] === parcel && data[i][1] === status) {
      return true; // Found a duplicate status submission
    }
  }

  return false; // No duplicate status submission found
}

// Function to get distinct substations
function getDistinctSubstations() {
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/");
  var rdSheet = ss.getSheetByName("Raw Data"); 
  var subs = rdSheet.getRange('E2:E').getValues().flat().filter((sub, index, self) => self.indexOf(sub) === index && sub !== "");
  return subs;
}

// Function to get parcels based on substation
function getParcels(substation) {
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/");
  var rdSheet = ss.getSheetByName("Raw Data"); 
  var lastRow = rdSheet.getLastRow();
  var substationValues = rdSheet.getRange('E2:E' + lastRow).getValues().flat();
  var parcelValues = rdSheet.getRange('D2:D' + lastRow).getValues().flat();
  var filteredParcels = [];
  
  for (var i = 0; i < substationValues.length; i++) {
    if (substationValues[i] === substation && parcelValues[i]) {
      filteredParcels.push(parcelValues[i]);
    }
  }
  
  return filteredParcels;
}

// Function to get the maximum status for a parcel
function getMaxStatusForParcel(parcel) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var statusSheet = ss.getSheetByName("Statuses");
  var lastRow = statusSheet.getLastRow();
  var parcelValues = statusSheet.getRange('A4:A' + lastRow).getValues().flat();
  var statusValues = statusSheet.getRange('B4:B' + lastRow).getValues().flat();
  var maxStatus = "";

  for (var i = parcelValues.length - 1; i >= 0; i--) {
    if (parcelValues[i] == parcel && statusValues[i]) {
      maxStatus = statusValues[i];
      break;
    }
  }

  return maxStatus;
}

// Function to add a new record to the Comments sheet
function addRecord(comment, parcel, date) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheetByName("Comments");
  var formattedDate = Utilities.formatDate(new Date(date), Session.getScriptTimeZone(), "MM/dd/yy");
  dataSheet.appendRow([parcel, comment, formattedDate]);
}

function addToStatuses(parcel, status, date) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var statusSheet = ss.getSheetByName("Statuses");
  var isDuplicate = isDuplicateStatus(parcel, status);
  
  // If not a duplicate, append the row
  if (!isDuplicate) {
    var formattedDate = Utilities.formatDate(new Date(date), Session.getScriptTimeZone(), "MM/dd/yy");
    statusSheet.appendRow([parcel, status, formattedDate]);
  }
}

// Function to delete duplicate rows from the Statuses sheet
function deleteDuplicateRows() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var statusSheet = ss.getSheetByName("Statuses");
  var dataRange = statusSheet.getRange(3, 1, statusSheet.getLastRow() - 2, statusSheet.getLastColumn());
  var values = dataRange.getValues();

  // Create an object to store unique rows
  var uniqueRows = {};
  var uniqueData = [];

  // Iterate through the rows and store unique rows in the object
  for (var i = 0; i < values.length; i++) {
    var row = values[i];
    var key = row.join(",");
    uniqueRows[key] = row;
  }

  // Extract unique rows from the object
  for (var key in uniqueRows) {
    uniqueData.push(uniqueRows[key]);
  }

  // Clear the existing data from row 3 to the last row and write back the uniqueData
  statusSheet.getRange(3, 1, statusSheet.getLastRow() - 2, statusSheet.getLastColumn()).clearContent();
  if (uniqueData.length > 0) {
    statusSheet.getRange(3, 1, uniqueData.length, uniqueData[0].length).setValues(uniqueData);
  }
}

function getUrl() {
  return "https://docs.google.com/spreadsheets/";
}

html:

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <title>Comment Submission Form</title>
  <style>
    /* Your CSS styles here */
    body {
      font-size: 15px;
      background-color: #f0f8ff; /* Light blue background color */
    }
    .container {
      width: 50%;
      margin: 0 auto; /* Center the container horizontally */
      text-align: center; /* Center the content inside the container */
      padding-top: 20px; /* Add space at the top */
    }
    h1 {
      margin-top: 20px; /* Add space between header image and header text */
      font-size: 20px;
    }
    select {
      width: 50%; /* Set the width of dropdown menus to fill the container */
      font-size: 12px; /* Set font size for dropdown values */
    }
    textarea {
      height: 100px;
      width: 250px;
      font-size: 12px;
      width: 100%; /* Set font size for textarea */
    }
    input[type="submit"] {
      font-size: 12px; /* Set font size for submit button */
    }
    .submit-message {
      color: red;
      font-size: 12px;
    }
    .landowner-info {
      float: center;
      margin-top: 20px;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      background-color: #f9f9f9;
      width: 100%; /* Extend size of landowner info box */
    }
  </style>
  <script src="https://apis.google.com/js/api.js"></script>
  <script>
    function updateParcelInfo(parcel) {
      updateMaxStatusForParcel(parcel);
      getLandownerInfo(parcel);
    }

    function getLandownerInfo(parcel) {
      google.script.run.withSuccessHandler(function(landownerInfo) {
        var landownerInfoArray = landownerInfo.split(" (Phone: ");
        document.getElementById("landowner-info-content").innerText = landownerInfoArray[0];
        document.getElementById("phone-info-content").innerText = "Phone: " + landownerInfoArray[1].slice(0, -1); // Remove the closing parenthesis
      }).getLandownerInfo(parcel);
    }

    function getParcels(substation) {
      google.script.run.withSuccessHandler(function(parcels) {
        var parcelDropdown = document.getElementById("parcel");
        parcelDropdown.innerHTML = "";
        parcels.forEach(function(parcel) {
          if (parcel.trim() !== "") {
            var option = document.createElement("option");
            option.value = parcel;
            option.text = parcel;
            parcelDropdown.appendChild(option);
          }
        });

        // Update max status immediately after selecting parcel
        var selectedParcel = parcelDropdown.value;
        updateMaxStatusForParcel(selectedParcel);
        // Fetch landowner info
        getLandownerInfo(selectedParcel);
      }).getParcels(substation);
    }

    function updateMaxStatusForParcel(parcel) {
      google.script.run.withSuccessHandler(function(maxStatus) {
        var statusDropdown = document.getElementById("status");
        statusDropdown.innerHTML = ""; // Clear previous options
        ["", "Outreach", "Negotiating", "Signed"].forEach(function(status) {
          var option = document.createElement("option");
          option.value = status;
          option.text = status;
          if (status === maxStatus) {
            option.selected = true; // Select the option if it matches the max status
          }
          statusDropdown.appendChild(option);
        });
      }).getMaxStatusForParcel(parcel);
    }

    function validateForm() {
      var parcel = document.getElementById("parcel").value;
      var substation = document.getElementById("substation").value;
      var comment = document.getElementById("comment").value;
      var status = document.getElementById("status").value; // Get status value

      if (!parcel || !substation || !comment || !status) {
        document.getElementById("submit-message").innerText = "All fields are required.";
        return false; // Prevent form submission
      }

      // Disable form submit button to prevent resubmission
      document.getElementById("submit-button").disabled = true;

      return true; // Allow form submission
    }

    // Reload the page after form submission to prevent resubmission popup
    window.onload = function() {
      if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
      }
    };

    // Prevent form resubmission popup on page reload
    if (window.history.replaceState) {
      window.addEventListener("beforeunload", function () {
window.history.replaceState(null, null, window.location.href);
      });
    }
  </script>
</head>
<body>
  <div class="container">
    <img src="https://i.imgur.com/16QsZja.png" alt="Header Image" style="width: 100%; max-width: 200px;">

    <h1>Comment Submission Form</h1>

    <form method="post" action="https://docs.google.com/spreadsheets/" onsubmit="return validateForm()">
      <label>Substation</label><br>
      <select name="substation" id="substation" onchange="getParcels(this.value)">
        <option value=""></option>
        <? var subs = getDistinctSubstations(); ?>
        <? subs.forEach(function(sub) { ?>
          <option value="<?= sub ?>"><?= sub ?></option>
        <? }); ?>
      </select><br><br>

      <label>Parcel</label><br>
      <select name="parcel" id="parcel" onchange="updateParcelInfo(this.value)">
        <!-- Parcel dropdown will be populated dynamically -->
      </select><br><br>

      <label>Status</label><br>
      <select name="status" id="status">
        <!-- Status dropdown will be populated dynamically -->
      </select><br><br>

      <label>Comment</label><br>
      <textarea name="comment" id="comment"></textarea><br><br>

      <input type="submit" name="submitButton" id="submit-button" value="Submit" />
      <span id="submit-message" class="submit-message"></span>
    </form>

    <div class="landowner-info">
      <h2>Landowner Info</h2>
      <p id="landowner-info-content">Loading...</p>
      <p id="phone-info-content"></p>
    </div>
  </div>
</body>
</html>

Plotly javascript legend lables

I want to restrict number of characters in a legend and on hover I want to display the full text of legend.

enter image description here

I Have the above function to show tooltip on mouseover.
I’m trying to change legend text using

enter image description here

when I do console.log(element[0].firstChild.innerHTML), it gives me substring of legend but on graph it still shows original value.
Any help is appreciated! Thank you!

The Show function in jquery not working on chrome mobile

I have a form HTML :

<form name="form-question" method="post" action="validate_question.php" id="form_question">
<div>
    <h1 class="mt-1 mb-4 text-center"><?= $data['question']; ?></h1>
</div>
<div id="loose" style="display: none;">
    <?php include 'templates/not_correct.php';  ?>
</div>
<div>
    <?php foreach ($data['propositions'] as $key => $proposition): ?>
        <div class="option">
            <input type="radio" id="<?= $key; ?>" name="option" value="<?= $key; ?>" >
            <label for="<?= $key; ?>"><?= $proposition; ?></label>
        </div>
    <?php endforeach; ?>
</div>
<div class="bottom-button" id="validateButtonWrapper">
    <input type="hidden" name="code_step" value="<?= $code_step; ?>" />
    <input type="hidden" name="id_team" value="<?= $check_password['id']; ?>" />
    <input type="submit" id="validateButton" class="btn btn-primary" value="Valider" />
      </div>
  </form>
<div id="win" style="display: none;">
    <?php include 'templates/correct.php';  ?>
</div>

<div id="already_answered" style="display: none;">
    <?php include 'templates/already_answered.php';  ?>
</div>

I have a Jquery code to treat my form in ajax :

 $('#form_question').submit(function(e){
        e.preventDefault(); 
        var formData = $(this).serialize();

        $.ajax({
            type: 'POST',
            url: 'validate_question.php',
            data: formData,
            success: function(response){
                var correctLabel = $('label[for="' + response.correct_answer + '"]');
                correctLabel.addClass('correct-answer');
                if (response.message == 'Réponse correcte') {
                    $('#form_question').hide();
                    $('#win').show();
                }
                if (response.message == 'Réponse incorrecte') {
                    $('#loose').show();
                }
                if (response.message == 'Cette question a déjà été répondue.') {
                    $('#form_question').hide();
                    $('#already_answered').show();
                }
            },
            error: function(xhr, status, error){
                console.error(xhr.responseText);
            }
        });
    });

I have this PHP code validate_question.php to treat the form

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/vendor/autoload.php';
use DotenvDotenv;
$dotenvPath = __DIR__;
$dotenv = Dotenv::createImmutable($dotenvPath);
$dotenv->load();

require_once 'config.php';
require_once 'functions.php';

$response_data = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['option'])) {
    // get response of question 
    $response = $_POST['option'];
    $code_step = $_POST['code_step'] ? $_POST['code_step'] : NULL;
    $id_team = $_POST['id_team'] ? $_POST['id_team'] : NULL;
    $id_step = get_id_step_by_code($db, $code_step);
    $already_answered = check_step_team($db, $id_team, $id_step['id']);

    if (NULL !== $response) {
        if (!$already_answered) {
            if (NULL !== $id_step && NULL !== $code_step) {
                // check if response correct
                $result = get_answer_by_step($db, $code_step, $response);            
                if ($result['is_answer_correct']) { 
                    $response_data['success'] = true;
                    $response_data['message'] = 'Réponse correcte';
                    $response_data['correct_answer'] = $result['correct_answer'];
                    record_step_for_team($id_team, $code_step, $db);
                } else {
                    $response_data['success'] = false;
                    $response_data['message'] = 'Réponse incorrecte';
                    $response_data['correct_answer'] = $result['correct_answer'];
                    record_step_for_team($id_team, $code_step, $db, false);
                }
            } else {
                $response_data['success'] = false;
                $response_data['message'] = 'Aucune réponse reçue.';
            }
        } else {
            $response_data['success'] = false;
            $response_data['message'] = 'Cette question a déjà été répondue.';
        }
    } else {
        $response_data['success'] = false;
        $response_data['message'] = 'Aucune réponse reçue.';
    }
} else {
    echo json_encode('erreur');
}
echo json_encode($response_data);
?>

When I validate the form, I have a page with my div id = win (or already_answered) BUT It works only on desktop or on firefox or brave browser but it does not work on Chrome mobile.
Don’t understand why ?
Thanks for your answers

images do not match the card from pokeapi.co

I’m having problems with my front end in java. the names are correct , but the images do not match. it is not getting the pokemon data in the correct order.

let currentPageUrl = 'https://pokeapi.co/api/v2/pokémon/';

window.onload = async () => {
  try {
    await loadCharacters(currentPageUrl);
  } catch (error) {
    console.log(error);
    alert('Erro ao carregar cards');
  }

  const nextButton = document.getElementById('next-button');
  nextButton.addEventListener('click', loadNextPage);

  const backButton = document.getElementById('back-button');
  backButton.addEventListener('click', loadPreviousPage);
};

async function loadCharacters(url) {
  const mainContent = document.getElementById('main-content');
  mainContent.innerHTML = '';
  try {
    const response = await fetch(url);
    const responseJson = await response.json();

    responseJson.results.forEach((character) => {
      const card = document.createElement("div");
      card.style.backgroundImage = `url('https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${character.url.replace(/D/g, "")}.png')`
  
    card.className = "cards"
      const characterNameBG = document.createElement("div")
      characterNameBG.className = "character-name-bg"
      const characterName = document.createElement("span")
      characterName.className = "character-name"
      characterName.innerText = `${character.name}`
      characterNameBG.appendChild(characterName)
      card.appendChild(characterNameBG)

(https://i.stack.imgur.com/dthCQ.png)

Mongodb finding $near by data in array of objects

I’m trying to retrieve one specific object from an existing array inside the DB document, using wildcards $near and $geometry.

I have a model that looks like this:

const schema = new mongoose.Schema({
name: {...},
email: {...},
...
locations: [
    {
      name: String,
      address: String,
      mapurl: String,
      location: {
        type: {
          type: String,
          default: "Point",
        },
        coordinates: [
          {
            type: Number,
          },
        ],
      },
    },
  ],
}

Schema indexed like that:

schema.index({ "locations.location": "2dsphere" });

Document in DB looks like this:

{
"_id": ...,
"name": ...,
"email": ...,
"locations": [
    {
      "name": "name 1",
      "address": "address 1",
      "mapurl": "https://maps.google.com/SOME_MAP_URL_1",
      "location": {
        "type": "Point",
        "coordinates": [
          11.1111,
          12.2222
        ]
      },
      "_id": {
        "$oid": "..."
      }
    },
    {
      "name": "name 2",
      "address": "address 2",
      "mapurl": "https://maps.google.com/SOME_MAP_URL_2",
      "location": {
        "type": "Point",
        "coordinates": [
          22.3333,
          23.4444
        ]
      },
      "_id": {
        "$oid": "..."
      }
    },
    {
      "name": "name 3",
      "address": "address 3",
      "mapurl": "https://maps.google.com/SOME_MAP_URL_3",
      "location": {
        "type": "Point",
        "coordinates": [
          33.4444,
          34.5555
        ]
      },
      "_id": {
        "$oid": "..."
      }
    },
  ],
}

I’m trying to query DB for a specific Object in an Array and than get all info I need from that Object with .select():

const q = {
    _id: place._id,
    "locations.location": {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [22.333, 23.444]
        },
        $maxDistance: 100, // 100m
      },
    },
  };

  const storeCoords = await Place.find(q).select("locations.location");

As the result I’m expecting to get only one specific Object from Array that is near 100 meters from provided coordinates, but instead I’m getting the whole Array with all existing Object there, including the one I need.

Expecting result:

{
  "coords": [
    {
      "_id": "...",
      "locations": [
        {
          "location": {
            "type": "Point",
            "coordinates": [22.3333, 23.4444]
          }
        },
      ]
    }
  ]
}

Actual result:

{
  "coords": [
    {
      "_id": "...",
      "locations": [
        {
          "location": {
            "type": "Point",
            "coordinates": [11.1111, 12.2222]
          }
        },
        {
          "location": {
            "type": "Point",
            "coordinates": [22.3333, 23.4444]
          }
        },
        {
          "location": {
            "type": "Point",
            "coordinates": [33.4444, 34.5555]
          }
        }
      ]
    }
  ]
}

I might use that $near and $geometry in a wrong way or completly wrong wildcards.
Please, advise.

Installing angular 12.0.1 for Node.js 14.21.3 in Ubuntu 22.04

I am trying to install Angular 12.0.1 in Node.js v14.21.3 in Ubuntu 22.04.

I get this error after installation when I want to check the version:

(base) mona@ada:~$ sudo npm install -g @angular/[email protected]
npm WARN deprecated [email protected]: Please use @jridgewell/sourcemap-codec instead
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: this library is no longer supported
npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated @npmcli/[email protected]: This functionality has been moved to @npmcli/fs
/usr/bin/ng -> /usr/lib/node_modules/@angular/cli/bin/ng

> @angular/[email protected] postinstall /usr/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

? Would you like to share anonymous usage data with the Angular Team at Google under
Google’s Privacy Policy at https://policies.google.com/privacy? For more details and
how to change this setting, see https://angular.io/analytics. Yes
+ @angular/[email protected]
added 235 packages from 182 contributors in 15.206s
(base) mona@ada:~$ ng v
Node.js version v14.21.3 detected.
The Angular CLI requires a minimum Node.js version of v18.13.

Please update your Node.js version or visit https://nodejs.org/ for additional instructions.

I installed node v14.X using the following:

curl -sL https://deb.nodesource.com/setup_14.x -o setup_14.sh

sudo sh ./setup_14.sh

sudo apt update

sudo apt-get install -y nodejs

mona@ada:~$ node -v
v14.21.3

Updates:

I followed https://angular.io/guide/versions and installed node v14.15.0 and then proceeded to install Angular 12.0.1. However, I still get the same message:

(dimo-labeling) mona@ada:~/dimo-labeling/frontend$ node -v
v14.21.3
(dimo-labeling) mona@ada:~/dimo-labeling/frontend$ sudo apt-get remove nodejs
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages will be REMOVED:
  nodejs
0 upgraded, 0 newly installed, 1 to remove and 441 not upgraded.
After this operation, 121 MB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 479633 files and directories currently installed.)
Removing nodejs (14.21.3-deb-1nodesource1) ...
dpkg: warning: while removing nodejs, directory '/usr/lib/node_modules' not empty so not removed
Processing triggers for man-db (2.10.2-1) ...
(dimo-labeling) mona@ada:~/dimo-labeling/frontend$ node -v
bash: /usr/bin/node: No such file or directory
(dimo-labeling) mona@ada:~/dimo-labeling/frontend$ nvm install 14.15.0
Downloading and installing node v14.15.0...
Downloading https://nodejs.org/dist/v14.15.0/node-v14.15.0-linux-x64.tar.xz...
######################################################################################################################################################################################################################################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v14.15.0 (npm v6.14.8)
(dimo-labeling) mona@ada:~/dimo-labeling/frontend$ node -v
v14.15.0
(dimo-labeling) mona@ada:~/dimo-labeling/frontend$ npm install -i @angular/[email protected]
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: this library is no longer supported

> [email protected] postinstall /home/mona/dimo-labeling/frontend/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)


> @angular/[email protected] postinstall /home/mona/dimo-labeling/frontend/node_modules/@angular/cli
> node ./bin/postinstall/script.js

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/webpack-dev-server/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ @angular/[email protected]
added 1327 packages from 1176 contributors and audited 1332 packages in 15.114s

86 packages are looking for funding
  run `npm fund` for details

found 262 vulnerabilities (2 low, 163 moderate, 79 high, 18 critical)
  run `npm audit fix` to fix them, or `npm audit` for details
(dimo-labeling) mona@ada:~/dimo-labeling/frontend$ ng v
Node.js version v14.15.0 detected.
The Angular CLI requires a minimum Node.js version of v18.13.

Please update your Node.js version or visit https://nodejs.org/ for additional instructions.

enter image description here

How can I sort by highest when I have an array and there are objects of prices?

There is a function where I can sort maybe prices from highest to low or from low to high. Here is an example of the function

myarray.sort((a,b) => b.age - a.age)

But how can I sort when I have some objects in my array and in there is an array of objects and this prices I have to sort.

Here in durationcontract is the array and there are prices

Array:

const arr = [
  {
    id: 25,
    name: 'Mercedes-Benz C63s AMG',
    durationcontract: [
        {
            duration: '12',
            price: '24' 
        }, 
        {
            duration: '24',
            price: '800' 
        }, 
    ],
  },
  {
    id: 25,
    name: 'Mercedes-Benz C63s AMG',
    durationcontract: [
        {
            duration: '12',
            price: '60' 
        }, 
        {
            duration: '24',
            price: '120' 
        }, 
    ],
]

I have to sort all items in the array by the highest or lowest price in durationcontract.

I am struggling and hope anyone can help me

expected Output:

 [
  {
    id: 12,
    name: 'Seat',
    durationcontract: [
        {
            duration: '12',
            price: '24' 
        }, 
        {
            duration: '24',
            price: '1200' 
        }, 
    ],
  },
  {
    id: 25,
    name: 'Mercedes-Benz C63s AMG',
    durationcontract: [
        {
            duration: '12',
            price: '24' 
        }, 
        {
            duration: '24',
            price: '800' 
        }, 
    ],
  },
  {
    id: 25,
    name: 'Mercedes-Benz C63s AMG',
    durationcontract: [
        {
            duration: '12',
            price: '60' 
        }, 
        {
            duration: '24',
            price: '120' 
        }, 
    ],
]