Why Nuxt does not set cookies on server route?

So my problem is that I try to set cookies at server route, but it server route does not set it at all. Here is my code:

export default defineEventHandler(async (e) => {
    const access_token : any = getCookie(e, 'access_token');
    const refresh_token : any = getCookie(e, 'refresh_token');

    if(typeof refresh_token === 'string') {
        const authHeader = `Bearer ${access_token}`;
        const readCategory = await $fetch.raw('http://localhost/admin/category', {
            method: 'GET',
            credentials: 'include',
            headers: {
                Authorization: authHeader,
                'X-Refresh-Token': refresh_token
            }
        });
        const token : any = readCategory.headers.get('token');
        console.log(token);
        setCookie(e, 'testing', 'asdasdasd', {path: '/', httpOnly: false, maxAge: 1800});
        setCookie(e, 'access_token', token, {path: '/', httpOnly: true, maxAge: 1800});
        return readCategory._data;
    }
    return {
        status: false,
        msg: 'sessionexpired'
    };
});

I have other server route that uses exactly the same code, but with just that exception that it does POST request. Other route works perfectly and sets “access_token” as cookie and browser receives it. I did check client routes and I did not see any problem in them. Token does have value and it even logs it to console, but for some odd reason setCookie does not work like it should work. Route does not even set this “testing” cookie back to browser for some reason.

EDIT: Oh and I did remove logic when checking if readCategory headers had token it it. I wanted to see if that blocks it from setting it, but it was not about that. Backend returns new access token every time when client sends one that is old or if client does not have one at all.

Open Job for Programmer [closed]

this is a open job opportunity. We only need 1 programmer. You must know the languages listed below:

Requirements:
HTML/HTML5, CSS, JavaScript, PhP, C#

Good to know languages:

Python, MySQL, Ruby

We have companies that come to us all the time needing website, we then take their ideas into our hands and create great professional, secure websites for their line of business.

Pay:
Each project/website pays anywhere from $1K-$7K USD.
-You get paid based on hours and how much work/coding you get done.

Great part time / fulltime job to pick up.

What We Are Looking For:

We are looking for someone that has a decent amount of knowledge and is super nice as well as professional.

Reply to this post and we will proceed with the interviewing process.

n/a…………………………….

Glide.js not rendering fully when parent container is display: none/visibility: hidden

I am using https://glidejs.com/ – in a normal pag view the glide slider is rendered correctly. However i have a use case were I have a display: none; + visibility: hidden; for the main div parent container on page load.

After a few seconds, with javascript, the display: none; is removed and visibility is set to visible. At this point the Glide.js slider shows but it’s not rendered properly (maybe because it does not know what dimensions to use since the parent divs are hidden/not displayed. When i do a simple manual resize of the browser window with the mouse, the Glide.js is “re-rendered” automatically and it works perfectly, as if it was never broken.

Is there a way to force a redraw or redo of the Glide.js code so that the JS is correctly applied AFTER the page is fully displayed via the JS after the predetermined time to show the full content?

Why does my ray traced diffuse lighting cut off sharply?

I’ve been following Ray Tracing In One Weekend in Javascript and have been doing well until it was time to implement diffuse lighting. After a lot of debugging, the output it produced didn’t match the expected output.
Expected Result

My Result

The diffuse lighting cuts off sharply, almost resembling reflections instead? I have no clue what has cause this to happen; perhaps there’s something wrong with how new rays are calculated?

Replit Code

Here are some of the most important chunks of code:

This is a recursive function that calculates colour output from rays

function rayColour(r, world, depth) {
  if (depth <= 0) {
    return new Colour(0, 0, 0);
  }

  var rec = world.hit(r, 0, infinity, rec);
  if (rec[0]) {
    var target = rec[1].p.add(rec[1].normal).add(randomInUnitSphere());
    return rayColour(new Ray(rec[1].p, target.subtract(rec[1].p)), world, depth-1).multiply(0.5);
  }
  var unitDirection = normalize(r.dir);
  var t = 0.5 * (unitDirection.y + 1);
  return new Colour(1, 1, 1).multiply(1-t).add(new Colour(0.5, 0.7, 1).multiply(t));
}

Main rendering function for a pixel

for(var p = 0; p < ppt; p++) {
    var i = curPixel % WIDTH;
    var j = HEIGHT-1 - Math.floor(curPixel / WIDTH);

    var pixelColour = new Colour(0, 0, 0);

    for (var s = 0; s < samplesPerPixel; ++s) {
      var u = (i + Math.random()) / (WIDTH-1);
      var v = (j + Math.random()) / (HEIGHT-1);
      var r = cam.getRay(u, v);
      pixelColour = pixelColour.add(rayColour(r, world, maxDepth));
    }

    putPixel(i, HEIGHT-1-j, pixelColour, samplesPerPixel);
    curPixel++;
  }

Sphere Ray collision

hit(r, tMin, tMax, rec) {
    var oc = r.origin().subtract(this.center);
    var a = r.dir.lengthSquared();
    var halfb = dot(oc, r.dir);
    var c = oc.lengthSquared() - this.radius*this.radius;
    
    var discriminant = halfb*halfb - a*c;
    if (discriminant < 0) return [false, rec];
    var sqrtd = Math.sqrt(discriminant);

    // find nearest collision
    var root = (-halfb - sqrtd) / a;
    if (root < tMin || tMax < root) {
      root = (-halfb + sqrtd) / a;
      if (root < tMin || tMax < root) return [false, rec];
    }

    rec.t = root;
    rec.p = r.at(rec.t);
    var outwardNormal = (rec.p.subtract(this.center)).divide(this.radius);
    rec.setFaceNormal(r, outwardNormal);

    return [true, rec];
  }

Collision for all physical objects

hit(r, tMin, tMax, rec) {
    var tempRec = new hitRecord();
    var hitAnything = false;
    var closestSoFar = tMax;

    for (var i in this.list) {
      var tempRec = this.list[i].hit(r, tMin, closestSoFar, tempRec)
      if (tempRec[0]) {
        hitAnything = true;
        closestSoFar = tempRec[1].t;
        rec = tempRec[1];
      }
      tempRec = new hitRecord();
    }

    return [hitAnything, rec];
  }

Any help would be appreciated!

Is it possible to write a script to pull color when referencing the unique function or via named ranges?

I’m trying to make a drop down that pulls data from a second hidden tab. Basically, when I click the drop down it will have a list of main color choices (Ex. “Purples”,”Greens”,”Blues”) and when one is selected, the custom color name will show up below (Ex “Greens” will pull up the list saying lime and sage etc).

When I use the =Unique function it works to pull the text in the correct order– but it ignores color. The colors are important for me because the background color is the color that the text is (Example “91: Lavender” is highlighted a certain shade of purple).

The list is long, so conditional formatting (though works) is going to be awful. I was hoping to find a script somewhere that has the ability to use the unique function to trigger a copy of the colors within the unique range.

Any workaround would be appreciated, so feel free to suggest alternative routes. I just need the dropdown to be able to pull the color name list with correlated highlight/background color without putting in around 95 conditional format rules manually.

I am fine if there is a script to link the cell color to the name color for conditional highlight so long as it isn’t manual.

Many thanks for your time even if you can’t help! =)


I made a dropdown list based off the colors and used an =if function in the sheet so that if it sees the specific color name it pulls the list from the other page. I cannot get it to pull color however.

I tried using named functions at first, but it didn’t work at all- so I gave up on that for now.

I tried using =unique, and it pulled the list in the correct order, but not the colors associated to the range. I understand now I need some script to pull colors, but I don’t know how to properly convey it.


I am still new to learning coding and scripts, so please be kind as I am still learning. Putting in notes for me in the script would be much appreciated since I’m not just trying to get the answer to copy, I would like to understand. If that is too much extra, I will just take the answer as-is. Thank you very kindly =)

The result of a Comparison between an input number and a random number never equals to true

I’m comparing an input number that the user enters to a random number from(0 to 3) made by computer..
The result never ends up equal even when both numbers are equal..
It always returns “sorry! It’s not a match”.

<!DOCTYPE html>
<html>
<head>
<body>

<h1> Guessing Game </h1>

<input type="number" id="id1">
<button type="button" onclick="game()">Click me.</button>

<p>Computer: </p>
<p id="id2"></p>

<script>

function game(){

var user = document.getElementById("id1").value;
var computer = Math.round(Math.random()*3);

if(user === computer)
{

document.getElementById("id2").innerHTML = "It's a Match: " + computer;
}
else{

document.getElementById("id2").innerHTML = "Sorry Not Match: " + computer;
}
}
</script>

</body>

</head>
</html>

How to pass JSON object from Node JS middleware to .ejs

I’m working with a NodeJS Express app with an EJS engine.

How can I pass a json object to my table.ejs file to be displayed in a table?

This is how I’m currently trying to do it. (I added some dummy JSON data into this table.ejs script and the table populated, so I know that portion works.)

This is a snippet of the middleware function that I have. I’m receiving data in from a Python API.

app.js

app.post('/process', upload.single('file'), (req, res) => {
axios.post('http://127.0.0.1:5000/receive', jsonData)
    .then(response => {

      const jsonData_response = response.data;
      res.render("table", { jsonData_res: jsonData_res });
      //console.log(jsonData_res);
    })
    .catch(error => {
      console.error('Error sending data:', error);
    });

I want to pass this json to my table.ejs file to be displayed in a data table.

Here is the snippet of html from my table.ejs

table.ejs

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">

                <script>
                   let dataset  = JSON.parse('<%-JSON.stringify(jsonData_res)%>');
                        $('#example').DataTable({
                            data: dataSet,
                            columns: [
                                { title: 'Name' },
                                { title: 'Position' },
                                { title: 'Office' },
                                { title: 'Extn.' },
                                { title: 'Start date' },
                                { title: 'Salary' },
                            ],
                        });
                    });
                </script>
                <div>
                    <table id="example" class="display">

                    </table>
                </div>

DiscordAPIError[50035]: Invalid Form Body message_id[NUMBER_TYPE_COERCE]: Value “Cannot read properties of null (reading ‘premium’)” is not snowflake

I’m coding a premium system in discord.js v14, and I’ve finish everything but there’s an error occurred.

There’s the code to redeem premium code:

await interaction.deferReply({ ephemeral: true });

        try {
            let user = await premiumUser.findOne({ Id: interaction.user.id });

            let code = interaction.options.get('code').value;
            console.log(`>${code}<`);

            if (user && user.isPremium) {
                return await interaction.editReply({
                    embeds: [
                        new EmbedBuilder()
                            .setColor(`Red`)
                            .setTitle(`Error:`)
                            .setDescription(`You're already a premium user.`)
                            .setTimestamp(),
                    ],
                });
            } else {
                const premium = await premiumCode.findOne({
                    code: code.toUpperCase(),
                });

                if (premium) {
                    const expires = moment(premium.expiresAt).format(
                        "dddd, MMMM Do YYYY HH:mm:ss"
                    );

                    user.isPremium = true;
                    user.premium.redeemedBy.push(interaction.user.id);
                    user.premium.redeemedAt = Date.now();
                    user.premium.expiresAt = premium.expiresAt;
                    user.premium.plan = premium.plan;

                    user = await user.save({ new: true }).catch(console.error);
                    client.userSettings.set(interaction.user.id, user);
                    await premium.deleteOne().catch(console.error);

                    return interaction.editReply({
                        embeds: [
                            new EmbedBuilder()
                                .setColor(`Random`)
                                .setDescription(`You have successfully redeemed the premium!`)
                                .addFields({
                                    name: 'Expires At',
                                    value: expires,
                                }),
                        ],
                    });
                } else {
                    return interaction.editReply({
                        embeds: [
                            new EmbedBuilder()
                                .setColor(`Red`)
                                .setTitle(`Error:`)
                                .setDescription(`This code is invalid. Please try again with a valid code.`),
                        ],
                    });
                }
            }
        } catch (err) {
            await interaction.editReply(err);
            console.error(err);
        }

And there’s the error, I’ve got 2 types of them:

DiscordAPIError[50035]: Invalid Form Body
message_id[NUMBER_TYPE_COERCE]: Value "Cannot set properties of null (setting 'isPremium')" is not snowflake.
>SIGMA-YQ9T-MPO6-RPLP-PREMIUM<
TypeError: Cannot set properties of null (setting 'isPremium')
    at Object.callback (/home/container/commands/premium/redeem.js:40:32)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async module.exports (/home/container/events/interactionCreate/handleCommands.js:102:9)
    at async Client.<anonymous> (/home/container/handlers/eventHandler.js:21:17)
>SIGMA-YQ9T-MPO6-RPLP-PREMIUM<

I tried many ways and search the similar error on stake overflow to fix but didn’t work, please help me

It’s a premium system in discord.js. An error occurred while I execute /redeem command, and I don’t know and cannot find out where the problem is and don’t know how to fix it.

How to use createCipheriv() method in react-native-crypto? I want to create the secret password in my app

Could someone please help me with how to use react-native-crypto?

I was previously using react-native-rncryptor to generate a secret password from the user’s password and the ‘secret’ string. However, when I tried building the APK file, this module stopped working.

 const encryptedPassword = await RNCryptor.encrypt(
        userCredential.password,
        'secret'
      );

Now, I am considering using the react-native-crypto module instead. However, I am unsure which function to use and how to use it. I attempted using createCipheriv(), but it did not work.

I would appreciate any assistance in understanding how to utilize react-native-crypto and which function would be suitable for my use case.

  public void encrypt(String text, String password, Promise promise) {
    JNCryptor cryptor = new AES256JNCryptor();
    byte[] plaintext = text.getBytes();

    try {
      byte[] ciphertext = cryptor.encryptData(plaintext, password.toCharArray());
      String base64 = Base64.encodeToString(ciphertext, Base64.DEFAULT);
      promise.resolve(base64);
    } catch (CryptorException e) {
      e.printStackTrace();
      promise.reject(e);
    }
  }

This is the code block what I used in the issue app.

import RNCryptor from 'react-native-rncryptor';
     const encryptedPassword = await RNCryptor.encrypt(
        userCredential.password,
        'secret'
      );

JavaScript: How to match array values with each occurrence and not with all the matches

I have two arrays:

const array1 = ["A", "S", "S", "G"]; // multiple occurrences of 'S'.
const array2 = ["S", "F", "J", "A"]; // single occurrence of 'S'.

I want to match the array2 with array1 for each of the instances. So I made a function:

const matchedArray = (array1, array2) => {
    let finalArray = [];
    array1.forEach((char, idx) => array2.includes(char) ? finalArray[idx] = `✅${char}` : finalArray[idx] = char);
    return finalArray;
}

But as you can understand that .includes() matches with all the instances of that character. So a single instance of "S" on the array2 matches with the two Ss of the array1. So the function is returning:

["✅A", "✅S", "✅S", "G"]

How can I achieve the finalArray be like:

["✅A", "✅S", "S", "G"]

How to pass a json object to the rest of my project from a web api in javascript

I am making a react web based planer that stores events entered by the user in a sql server accessed by a c# asp.net api. The api and the fetch statement both return what I expect them to, but I’m struggling to pass the data I receive around the rest of my project.

Here is the fetch command I use, with json being the final value I’m trying to use (it holds the details of events in the format Day, Month, Year, Title, Tag)

fetch(BaseUrl + '/api/eventreader/6', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
        },
    })
        .then(response => response.json())
        .then(json => {

            
        }

        )

I’ve tried to set a global variable in the file the set it equal to json, but it always comes out as undefined. I have also tried to add the elements to an array, but the array also says it is empty. Any ideas?

Fetching posts from the facebook

I want to fetch the news posts from facebook page of somebody and display it on a news page of the
website that is built by react js

i tried to fetch the posts from facebook and display it on frontend of the website by react js

How can I add a ‘Show More’ button to my personal blog?

Issue Overview

I want my personal blog (ntnbr.com) to start by displaying the 12 most recent posts (on all devices). At the bottom of those 12 posts, I want a ‘Show More’ button to be displayed, that, when clicked, will display the next 12 posts. Once all of the posts on the page are displayed, I want the ‘Show More’ button to disappear.

General Info

I am running my site with ghost.org on Ghost(Pro), and can only inject custom code into the header or the footer of my Ghost site. You can inspect my blog to see anything you want / anything that will help.

Here’s the current code that is being injected into the {{ghost_head}} tag on every page of the site:

<script defer data-domain="nathanbrown.ghost.io" src="https://plausible.io/js/script.js"></script> 
<link rel="preconnect" href="https://rsms.me/">
<link rel="stylesheet" href="https://rsms.me/inter/inter.css">

<script>
  window.addEventListener('DOMContentLoaded', function () {
    var nextLink = document.querySelector('a.navigation-item.navigation-next');
    var previousLink = document.querySelector('a.navigation-item.navigation-previous');

    if (nextLink) {
      nextLink.remove();
    }

    if (previousLink) {
      previousLink.remove();
    }
  });
</script>

<style>
  body {
      font-family: 'Inter', sans-serif;
  }
  .gh-article-title {
      font-size: 74px;
      line-height: 1.1;
  }
    
  .gh-article-excerpt {
      font-size: 32px;
      line-height: 1.2;
  }  
  
  ul.nav {
      font-size: 12px;
      font-weight: 600;
  }
    
  .gh-head-members {
      font-size: 12px;
      font-weight: 600;
  }
  @media only screen and (max-width: 600px) {
  .gh-article-title {
      font-size: 42px;
      line-height: 1.1;
  }
  .gh-article-excerpt {
      font-size: 24px;
      line-height: 1.2;
  }
</style>

I do not currently have any custom code injected in the site footer.

How can I help?

Please provide code that will help me solve my problem. You can provide me code that I can inject in the header or the footer. Also, please note that my website renders differently on mobile vs. tablet vs. computer – because it renders different numbers of columns (and therefore posts) based on the screen size.

Bonus Points

If you can:

  1. not affecting any of my previously existing CSS or JavaScript code
  2. centering the ‘Show More’ button and making it look somewhat nice

That’d be great!

What I tried (that didn’t work)

I’m not very experienced with code, but I asked ChatGPT and wasn’t able to figure it out with ChatGPT. ChatGPT suggested I insert this code in my header / footer:

<script>
  // Wait for the DOM to load
  document.addEventListener("DOMContentLoaded", function() {
    // Select the blog post elements
    var blogPosts = document.querySelectorAll(".blog-post");

    // Set the number of posts to initially display
    var postsToShow = 16;
    var currentVisible = postsToShow;

    // Loop through the blog post elements and hide those exceeding the initial display limit
    for (var i = postsToShow; i < blogPosts.length; i++) {
      blogPosts[i].style.display = "none";
    }

    // Function to show the next set of posts
    function showMorePosts() {
      // Calculate the next visible range
      var nextVisible = currentVisible + postsToShow;

      // Loop through the blog post elements and show the next set
      for (var i = currentVisible; i < nextVisible; i++) {
        if (i < blogPosts.length) {
          blogPosts[i].style.display = "block";
        }
      }

      // Update the current visible count
      currentVisible = nextVisible;

      // Hide the "Show more" button if all posts are visible
      if (currentVisible >= blogPosts.length) {
        document.getElementById("show-more-button").style.display = "none";
      }
    }

    // Attach an event listener to the "Show more" button
    document.getElementById("show-more-button").addEventListener("click", showMorePosts);
  });
</script>

and also suggested that ‘In your HTML code, add a button at the bottom of the 16 posts with the id show-more-button:’

<button id="show-more-button">Show more</button>

But I don’t know how to make that work / if it’ll even work for my website. Would appreciate any help!