Looking for Javascript code to get Quiz answers

So, here is this aptitude tests
It’s a course given by university to complete and get the certificate but I’m not able to find the answers anywhere, neither chatGPT . So , is there any javascript code which I can directly paste to the console and find my answers?

I try every possible answer but can’t pass the test, my deadline is approaching.

How to show dropdown elements with JS?

I just started learning html/css and I am making a website. I wanted to create click dropdown but I have to use JS. I know that I should learn it first and then try to use it but I have a time limit and have no time to learn it. So i copied this code and tweaked it to work for me but it just doesn’t work and I really need help. This is the code.

function Menu() {
    document.getElementById("phone-nav-bar").classList.toggle("show-nav-bar");
  }

  // Close the dropdown menu if the user clicks outside of it
  window.onclick = function(event) {
    if (!event.target.matches('.menu-button')) {
      var navBar = document.getElementById("phone-nav-bar");
      if (navBar.classList.contains('show-nav-bar')) {
        navBar.classList.remove('show-nav-bar');
      }
    }
  }
.mobile-phone-nav-bar{
    display:none;
}
.show-nav-bar{
    display: flex;
    flex-direction: column;
}
<div class="menu-toggle">

            <button class="menu-button" onclick="Menu()"><img src="assets/images/menu.png"></button>

            <div class="mobile-phone-nav-bar" id="phone-nav-bar">

                <a class="nav-button" href="index.html">Начало</a>
                
                <div class="train-dropdown">
                    
                    <button onclick="TrainDropdown()" class="dropdown-button">Влакове</button>
                    
                    <div id="trains" class="train-elements">
                    
                        <a id="first-element" href="#">Link 1</a>
                        
                        <a href="#">Link 2</a>
    
                        <a id="last-element" href="#">Link 3</a>
                    
                    </div>

                </div> 
                
                <a class="nav-button" href="#contacts">Контакти</a>
                <a class="nav-button" href="#aboutme">Повече за мен</a>
            
            </div>

        </div>

I would like display date exactly how it is on database using day.js

I have an app that I built where users can create trips. These trips have starts and end dates. Now, a user created a trip and sets the dates to be:
start date: 3rd of January, 2025
end date: 10 of January, 2025.
Problem started when users who wishes to book the trip were seeing different displayed dates. I knew I have messed things up and would like to know how best to approach this.
They want the dates to be same irrespective of the place the user wishes to book. This means that the user making the booking should see the exact date the trip creator had set for start and end dates.
They only wants displayed date and not time.
Here is how I am handling date for now. The app was built with next.js and express.js for backend. In the frontend, I am using React Callender for dates UI. I am using Day.js for date display and creation.
When the user creates the date in the frontend, I am storing it this way in backend.

import utc from "dayjs/plugin/utc";
var dayjs = require("dayjs");
dayjs.extend(utc);

export const convertDate = (date: Date | string) => {

  const converted = dayjs(new Date(date)).utc().format(); //dayjs.utc(newDate).format('YYYY-MM-DD')

  return converted;
};

This output for instance using the trip that was created: "2025-01-03T05:00:00Z" for start date and
2025-01-10T05:00:00Z.
On the client side, I am displaying the date this way:

 dayjs(response?.startDate).format("MMM-DD-YYYY")
 dayjs(response?.endDate).format("MMM-DD-YYYY")

Now, one of the users who wanted to book this trip saw trip dates as follows:
Start date: 2nd of January, 2025
End date: 9th of January, 2025. Obviously it is timezone issue.

We would like the user to see exactly 3rd of January, 2025 to 10th of January, 2025 irrespective of the user’s timezone.
How can I achieve this?

Polygons above the heatmap are transparent in Mapbox GL JS

Using mapbox gl js i’m trying to make both polygon and line layers above the heatmap layer. I have full opacities set on polygon and line layer like this:

const paint: LineLayer['paint'] = {
    'line-color': '#000000', 
    'line-opacity': 1,
    'line-width': 10,
};
const paint = {
    'fill-color': '#0080ff', 
    'fill-opacity': 1,
};

Yet polygon and line are transparent. They are not transparent when i hide the heatmap layer.

Is there some workaround to display polygons with heatmap but without transparency from the heatmap?

screenshot of map

I tried to set beforeIds on layers but it had no effect. I tried also MapLibre but it has the same problem.

list update in php after delete data using ajax

Here is my code. I am trying to delete selected data from the database using AJAX, and after successfully deleting the data, I am thinking about how to update and refresh the data in #memo_list. I’ve tried several approaches but am having difficulty, so I am posting this question. Does anyone know a solution to this?

PHP:

<form id="deleteForm">
    <table class="memo_list">
        <thead>
            <tr>
                <th>memo</th>
                <th>select </th>
            </tr>
        </thead>
        <tbody>
<?
    $sql = " select * from TABLE where member_id = 'member_id' order by datetime ";
    $result = sql_query($sql);

    for($i = 0; $row = sql_fetch_array($result); $i++) { 
?>
            <tr >
                <td><?=$row['memo']?></td>
                <td><input type="checkbox" name="id" value="<?=$row['id']?>"></td>
            </tr>
        </tbody>
    </table>

    <button type="button" id="deleteBtn">Delete Selected</button>
</form>

...

<script>
document.getElementById("deleteBtn").addEventListener("click", function() {
    // collect selected items
    
});

// 
if (selectedItems.length === 0) {
    // nothing
    return;
}

// AJAX 
var jsonString = JSON.stringify(selectedItems);
$.ajax({
        type: "POST",
        url: "./_ajax.delete_call.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });
});
</script>

AJAX(_ajax.delete_call.php) :

<?
include_once("./_common.php");

$data = json_decode(stripslashes($_POST['data']));

// here i would like use foreach:
foreach($data as $d){
    sql_query("delete from TABLE where id = '{$d}'");
}
$msg = "";

?>

How do I make my mega menu items container fixed when i hover on mega menu items

So i am working on a shopify project i am using tailwind for styling , In shopify we can add navigation items , so i made a mega menu and in that mega menu present it’s items , so when user hovers on the mega menu item all the content inside that will be made seen but i want that to be fixed a container where all nested items can be seenenter image description here[[

(https://i.sstatic.net/Dt5ehx4E.png)](https://i.sstatic.net/XIe9GUuc.png)

Code below


<div class="shadow-xl"> 
<div class="container  mx-auto flex justify-between items-center px-0"> 
  <nav class="hidden lg:flex w-full text-base font-medium"> 
    <ul class="flex w-full justify-between p-3 space-x-2"> 
      {% for link in linklists.mini-header.links %}
        <li class="relative group text-gray-700 hover:bg-[#E87303] hover:text-white px-2 py-2 rounded whitespace-nowrap"> 
          {% if link.title == "Image" %}
            <img src="{{ 'saree' | image_url }}" alt="best sellers" class="h-6 w-6" width="24" height="24" />
          {% else %}
            <a href="{{ link.url }}" class="text-md">
              {{ link.title }}
            </a>
          {% endif %}
      
          {% if link.links != blank %}
            <div class="relative">
              <div class="absolute z-50 top-0 hidden mt-2 bg-white text-gray-700 rounded-lg shadow-lg group-hover:block dropdown-menu" style="width: 1200px;">
                <ul class="flex space-x-8 p-4">
                  {% for child in link.links %}
                    <li class="px-4 py-2 ">
                      <h3 class="font-bold font-playfair text-xl text-gray-900 px-2 py-2">{{ child.title }}</h3>
                      {% if child.links != blank %}
                        <ul class="space-y-2">
                          {% for grandchild in child.links %}
                            <li class="px-2 py-1" style="white-space: nowrap; width: 100%;">
                              <a href="{{ grandchild.url }}" class="block w-full">
                                {{ grandchild.title }}
                              </a>
                            </li>
                          {% endfor %}
                        </ul>
                      {% endif %}
                    </li>
                  {% endfor %}
                </ul>
              </div>
            </div>
          {% endif %}
        </li>
      {% endfor %}
      
    </ul>
  </nav>
</div>
</div>

<style>

nav ul li .dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0; 
  z-index: 50;
  background-color: white;
  display: none; 
  max-width: 1400px; 
  white-space: nowrap;
}

nav ul li:hover .dropdown-menu {
  display: block;
}



</style>
<script>

document.addEventListener("DOMContentLoaded", function() {
  const dropdownMenus = document.querySelectorAll('.dropdown-menu');

  dropdownMenus.forEach(menu => {
    const parentLi = menu.closest('li');

    parentLi.addEventListener('mouseenter', function() {
      menu.style.left = '0';
      menu.style.display = 'block';

      const rect = parentLi.getBoundingClientRect();
      const dropdownWidth = menu.offsetWidth;
      const overflowRight = (rect.right + dropdownWidth) - window.innerWidth;

      if (overflowRight > 0) {
        menu.style.left = `-${overflowRight}px`;
      } else {
        menu.style.left = '0';
      }
    });

    parentLi.addEventListener('mouseleave', function() {
      menu.style.display = 'none';
    });
  });
});
  </script>
  

previous issue i faced was whenever i hovered in it items would slide away i corrrected that using javascript but now my problem is whenever i hover on any mega menu item , the container which has all nested items should be fixed for all mega menu items , how can i achieve that

pair numbers from multiple arrays

Trying to sort some data from a array of arrays which could be different every time.

ie:

data = [
   [ null, 1000, null, null, null ],
   [ 2000, null, 3000, 4000, 5000 ]
]

What i am trying to get out of this array is a set of array pairs, the first value in the first array is null and should be paired in new array with 2000, then 1000 pair is null and should paired as separate array as well and so on.

Expected Pairs

Expected Result:

data = [
   [null, 2000],
   [1000, null],
   [null, 3000],
   [null, 4000],
   [null, 5000],
]

the actual data set can be larger in any direction ie:

data = [
   [ null, 1000, null, null, null, 6000, 7000  ],
   [ 2000, null, 3000, 4000, 5000, null, null  ]
   [ 3423, null, 4545, 1435, 9898, null, 7643  ]
]

now the expected pairs would be

data = [
   [null, 2000, 3423],
   [1000, null, null],
   [null, 3000, 4545],
   [null, 4000, 1435],
   [null, 5000, 9898],
   [6000, null, null],
   [7000, null, 7643],
]

I know its a multidimensional array so i am looping over the data set then over each data array from that data set and trying to push each number into a new array, but all i can achieve is a flat version of the data ie:

data: [
    [
        null
    ],
    [
        1000
    ],
    [
        null
    ],
    [
        null
    ],
    [
        null
    ],
    [
        2000
    ],
    [
        null
    ],
    [
        3000
    ],
    [
        4000
    ],
    [
        5000
    ]
]

My Code:

  const test = [
    [null, 1000, null, null, null],
    [2000, null, 3000, 4000, 5000]
  ];

  const testFunc = dataSet => {
    const lineChartData = [];
    dataSet.map(numbersSet =>
      numbersSet.map(number => lineChartData.push([number]))
    );
    return lineChartData;
  };

  console.log("TEST", testFunc(test));

Node JS / Javascript: Promise, uncaught exception not being handled by ‘reject’

I set up the following to handle queries to a SQLite database. When there are no errors with the query, it performs as expected and all rows are logged to the console.

When I test the functionality by adding a typo to the table name, I get an uncaught exception. I’m not sure why this is the case, and I thought that the exception would be handled by reject(). I’m new to JS and not sure where I’m going wrong here. Any help appreciated.

const sqlite3 = require("sqlite3").verbose();
const dbPath = "db_path";
const db = new sqlite3.Database(dbPath);

const query = (command, method = "all") => {
  return new Promise((resolve, reject) => {
    db[method](command, (error, result) => {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
};

async function getResults() {
  const results = await query("SELECT * FROM nonexistant_table");
  console.log(results);
}
getResults();

This is the exception I’m getting:

node:internal/process/promises:391
    triggerUncaughtException(err, true /* fromPromise */);
    ^

Error: SQLITE_ERROR: no such table: set_master1
--> in Database#all('SELECT * FROM set_master1', [Function (anonymous)])
    at D:test_folderjs_tutorialmain.js:7:15
    at new Promise (<anonymous>)
    at query (D:test_folderjs_tutorialmain.js:6:10)
    at getResults (D:test_folderjs_tutorialmain.js:18:25)
    at Object.<anonymous> (D:test_folderjs_tutorialmain.js:21:1)
    at Module._compile (node:internal/modules/cjs/loader:1469:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
    at Module.load (node:internal/modules/cjs/loader:1288:32)
    at Module._load (node:internal/modules/cjs/loader:1104:12) {
  errno: 1,
  code: 'SQLITE_ERROR',
  __augmented: true
}

Node.js v20.18.0

Identify which browsers are vulnerable to XSS attacks through inline-styles?

Our corporate security policy has a restriction that prevents adding comments to ServiceNow work notes and comments that include embedded HTML. The reasoning is that the user could inject malicious HTML with JavaScript, though I’m not convinced this policy is still valid as ServiceNow has added improvements since this feature was introduced in 2017. We’d like to enable it, so I’m trying to validate the extent of that security risk.

Out of the box, ServiceNow has an HTML Sanitizer that has both a whitelist and backlist of HTML elements and their attributes.

While the following is not a comprehensive list, here’s the sample code that I’m using for testing:

Possible XSS attacks:

1. [code]<script>alert('XSS Attack!');</script>[/code]
2. [code]<img src="image.jpg" onerror="alert('XSS Attack!');" />[/code]
3. [code]<iframe src="https://www.google.com"></iframe>[/code]
4. [code]<a href="javascript:alert('XSS Attack!');">Link</a>[/code]
5. [code]<div style="background-image: url('javascript:alert('XSS Attack')');"></div>[/code]
6. [code]<input type="text" value="XSS" onfocus="alert('XSS Attack');" />[/code]

As expected, the resulting HTML obtained from the browser shows that the HTMLSanitizer either HTML encoded or stripped out the elements and attributes that would allow for code injection:

<br>Possible XSS attacks:
<br>
<br>1. &lt;script&gt;alert('XSS Attack!');&lt;/script&gt;
<br>2. <img src="image.jpg">
<br>3. <iframe></iframe>
<br>4. Link
<br>5. <div style="background-image: url('javascript:alert('XSS Attack')');"></div>
<br>6. <input type="text"></div>

The only exception is the CSS attack through an inline-style where a URL could point to a JavaScript block:

<div style="background-image: url('javascript:alert('XSS Attack')');" />

The Network tab of the Developer tools shows that the inline style was evaluated, but failed with a net::ERR_UNKNOWN_URL_SCHEME

net::ERR_UNKNOWN_URL_SCHEME

It appears that Chrome 129 doesn’t recognize the javascript: url scheme in this context.

As I’m not a web developer, is there a good reference material that would list which browsers support this and would therefore be vulnerable?

How to access property values of objects in a list [duplicate]

I am using a code like the following:

let books = {       
1: {"author": "Chinua Achebe","title": "Things Fall Apart", "reviews": {} },       
2: {"author": "Samuel Beckett","title": "Molloy, Malone Dies, The Unnamable, the trilogy", "reviews": {} } 
}

booklist = Object.values(books); 
let the_book = booklist[book_index]; 

book_index is set from the isbn:

public_access.get('/review/:isbn',function (req, res) {
   let book_index = parseInt(req.params.isbn);
   book_index -=1;
   let the_book = booklist[book_index];
   console.log(the_book)        Returns one key/value pair based on the value of isbn
});
 

I have tried different ways of accessing individual key/value pairs within the_book and nothing has worked so far. I cannot find the correct syntax for it.

I checked and confirmed that the_book is properly initialized and has values.

Js logic building

Does anyone have any tips for logic building for Js functional problems mostly, like i understand most of the code i go through later on , but many times unable to just come up with the intution, also like it’s little different from normal logics we write for basic functions, like recently i implemented Currying, but then i thought i’d be able to come up with the logic of currying with placeholders support on my own, but i couldn’t so like how much should one practice to and from where to start getting intution build on our own?

TO come up with the code for functional programming concepts like currying and currying with placeholder support

Backend with Node JS [closed]

I need help with node js. I want to be backend developer with knowing of node js. Can you please help me with some guideline and courses i can do which lead me to know how eveything works. Thank you!

Backend development with Node JS

change zindex and opacity of objects on canvas

I’ve made a canvas where objects are created randomly along the x axis of the top of the canvas, and each object has is randomised between 3 different sizes to render.

Depending on the size the object is randomised to I have a conditional if statement which changes the speed the item moves down and when it reaches off the bottom of the canvas it randomises it’s size, position (back to the top of the canvas and a random x axis position) and speed again. All of the above works.

However I’m also trying to make it so dependant on the size the object is given it also changes it’s opacity and z-index and that isn’t working, here’s my code I’ve tried below and any help with it would be most appreciated:

const canvasContainer = document.querySelector('#canvasContainer');
let newCanvas = document.createElement('canvas');
let canvas = document.querySelector('#canvas');

const canvasWidth = 500;
const canvasHeight = 500;

const obstacleImage = new Image();
obstacleImage.src = "./obstacle.png"
const obstacles = [];
const numberOfObstacles = 10;
    
newCanvas.setAttribute('id', 'canvas'); 
newCanvas.setAttribute('width', canvasWidth);
newCanvas.setAttribute('height', canvasHeight);

canvasContainer.append(newCanvas);
canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');

// Create the randomiser

    function ChooseRandom(min, max) {
        return Math.floor(Math.random() * ((max + 1) - min) + min);
    }
  

// Generating number of obstacles (in an array with a for loop)
  
    for (let i = 0; i < numberOfObstacles; i++) {
        const variableValue = ChooseRandom(1, 3);
        const x = ChooseRandom(50, 450);
        const y = ChooseRandom(50, 450);
        const obstacle = {
            x: x,
            y: y,
            width: 20 * variableValue,
            height: 20 * variableValue,
            speed: 0
        }

        obstacles.push(obstacle);
    }


// Changes to make during intervals for movement

    setInterval( () => {
    
        ctx.clearRect(0, 0, 2000, 2000); // clear canvas elements from their old positions
      

    // [setInterval] loop through each obstacle and perform actions
      
        for (let i = 0; i < obstacles.length; i++) {
            const obstacle = obstacles[i];

            if (obstacle.width <= 20) {
                obstacle.speed = 1;
                obstacle.style.zIndex = 1;
                obstacle.style.opacity = 0.33;
            } else if (obstacle.width <= 40) {
                obstacle.speed = 1.5;
                obstacle.style.zIndex = 2;
                obstacle.style.opacity = 0.66;

            } else {
                obstacle.speed = 2;
                obstacle.style.zIndex = 3;
                obstacle.style.opacity = 1;
            }


            obstacle.y += obstacle.speed / 2; 
            
            ctx.drawImage(
                obstacleImage,
                obstacle.x,
                obstacle.y,
                obstacle.width,
                obstacle.height
            );

    // [setInterval] check if the obstacle has gone of the bottom of the canvas, then increase score and randomise it again if so
  
            if (obstacle.y > 500) {
                const variableValue = ChooseRandom(1, 3);
                obstacle.x = ChooseRandom(0, 450);
                obstacle.y = ChooseRandom(0, 0);
                obstacle.width = 20 * variableValue,
                obstacle.height = 20 * variableValue
            }

        }


    }, 5);
  
body {
    max-height: 100vh;
    overflow: hidden;
}

#canvasContainer {
    display: flex;
    justify-content: center;
    /* background: black; */
}

canvas {
    background-color: black;
    width: 100%;
    max-width: 500px;
    object-fit: contain;
}
<section id="canvasContainer">
    </section>