How should i use Moment( ).fromNow( )?

i’m making a blog using firebase, each post is a document created as:

await addDoc(postCollection, {
        title,
        body,
        comments: [
          {
            userId: "",
            content: "",
            name: "",
            userPhoto: "",
            at: "",
          },
        ],
        likes: { count: 0, users: [] },
        date: new Date().toLocaleDateString(),
        createdAt: serverTimestamp(),
        user: { name: auth.currentUser.displayName, id: auth.currentUser.uid },
      });

I’m not sure how i should use moment( ).fromNow( ), but i created the property “at” to register the time i make a comment. Each time i make a comment i pass moment( ).format( ) to the “at” propert.

At the comment section, i have the following span

<span>{moment(item.at).fromNow()}</span>

But it keeps showing that i made the comment “A few seconds ago”. How should i use it to work properly?

Thanks in advance

Stroke doesn’t draw if I write to it after getImageData. Do they conflict with each other?

I am simply drawing three lines with html inputs and canvas. But I want to draw two of them with the putimagedata method and the other one with the stroke method.

If I use stroke after I draw with the putimagedata method, the stroke doesn’t draw anything. The only way it draws is if I put my stroke method just before getimagedata method.

Are these two conflicting with each other or am I doing something wrong?

Here is my code:

function updateCanvas() {
  var startTime = performance.now()
  var first = document.querySelector('input[name="first"]:checked').value;
  var second = document.querySelector('input[name="second"]:checked').value;
  var canvas = document.getElementById("canvas");
  var start = parseInt(document.getElementById("start").value);
  var end = parseInt(document.getElementById("end").value);
  var byuk = parseInt(document.getElementById("byuk").value);
  var syuk = parseInt(document.getElementById("syuk").value);
  var canvasWidth = canvas.width;
  var canvasHeight = canvas.height;
  var ctx = canvas.getContext("2d");

  // THIS IS THE PLACE IT WORKS
  ctx.beginPath();
  ctx.lineWidth = 1;
  ctx.strokeStyle = 'red';
  ctx.moveTo(0, 200 + byuk);
  ctx.lineTo(399, 200 + syuk);
  ctx.stroke();
  //

  var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);


  function drawPixel(x, y, r, g, b, a) {
    var index = (x + y * canvasWidth) * 4;
    canvasData.data[index + 0] = r;
    canvasData.data[index + 1] = g;
    canvasData.data[index + 2] = b;
    canvasData.data[index + 3] = a;
  }
  for (var i = 0; i <= 400; i++) {
    drawPixel(i, 200, 50, 50, 50, 255);
  }

  if (start == end) {

    // THIS IS THE PLACE IT DOESNT DRAW EVEN IF STATEMENT WORKS
    ctx.beginPath();
    ctx.lineWidth = 1;
    ctx.strokeStyle = 'red';
    ctx.moveTo(0, 200 + byuk);
    ctx.lineTo(399, 200 + syuk);
    ctx.stroke();
    //

    var y = 200;
    for (var i = 0; i <= byuk; i++) {
      drawPixel(0, y, 255, 0, 0, 255);
      y++;
    }
    var y2 = 200;
    for (var i = 0; i <= syuk; i++) {
      drawPixel(399, y2, 255, 0, 0, 255);
      y2++;
    }
  }
  ctx.putImageData(canvasData, 0, 0);
  var endTime = performance.now()

  console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)
}

Thanks in Advance.

How to use Pyscript python function in javascript?

I have a Javascript code and wanted to implement python functions using Pyscript.

Simple Example:

let’s say I have a function:

<py-script>
def addOne(a):
    value = int(a) + 1
    return(value)
</py-script>

and say I want to use this function in javascript:

<script>
let compute = addOne(12)
</script>

The issue here is that it will say “addOne()” function is not defined.
I was wondering if there was a way to use pyscript python functions inside javascript?

Convert CSV to JSON including arrays of objects

In Excel I have created a spreadsheet that I would like to convert into JSON for my VS Code project. I am currently just using an online CSV to JSON converter https://www.convertcsv.com/csv-to-json.htm, however my problem is that I can’t seem to figure out a way to format it so that it uses arrays of objects.
e.g.

"arr": [
    {"id":1, "name": "obj1"},
    {"id":2, "name": "obj2"},
]

If I format in Excel like this:
enter image description here

The output looks like this:

[
 {
   "arr": {
      "id": [
         1,
         2
      ],
      "name": [
         "obj1",
         "obj2"
      ]
   }
}
]

Does anyone know how to format in Excel to get the desired array of objects? Otherwise can someone point me in the right direction for a script that will convert it correctly?
Thanks!

Plus equals two variables returns isNan( ) = true when the variables themselves return isNan() = false

I’m fairly new to Javascript and I’m running into an issue I can’t explain. Two variables that are numbers, and isNaN() returns false for both, when added together using += the result is returning isNaN() = true. Is there some nuance that I’m missing here?

The code is to set fps on frame rate in a side-scrolling game. I’m trying to determine why this.frameTimer += deltaTime is equating to isNaN() = true, where the variables individually are equating to false. The end goal is to get a valid number to compare against another variable. Thanks for your help.

draw(context,deltaTime) {     
   if (this.frameTimer > this.frameInterval) {
       if (this.FrameX < this.maxFrame) { this.FrameX++
       this.frameTimer = 0 }
       else this.frameX = 0
   } else {
        this.frameTimer // isNaN(this.frameTimer) returns false
        this.deltaTime // isNaN(this.deltaTime) returns false
        this.frameTimer += deltaTime // isNaN(this.frameTimer) returns true
   }
   context.drawImage(this.image, this.width * this.frameX, this.height * this.frameY, this.width, this.height, this.x, this.y, this.width, this.height)
}

display:inline-block not aligning properly?

So I have been trying out using status bars with JavaScript and have come across this issue where it seems like when I use “display:inline-block” it doesn’t align my two elements properly. Any help or someone pointing out a dumb mistake a made would be appreciated.

document.getElementById("myBar").style.width = "50%";
#myProgress {
  width: 20%;
  background-color: #ddd;
  display: inline-block;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: #04AA6D;
}

h1 {
  font-size: 30px;
  font-family: Arial, Helvetica, sans-serif;
  display: inline;
}
<h1>Stat:</h1>
<div id="myProgress">
  <div id="myBar"></div>
</div>

Problem with Axios and extra slash when used with Laravel

Time for me to ask some help as I simply do not understand the issue, spent a good 6 hours on this, going nowhere 🙁

I have an Axios GET request which may have the last parameter empty.

axios.get(this.fetchAllUsersRoute + '/' + this.status + '/' + this.pagination + '/' + this.search);

My laravel route:

Route::get('/fetch-users/{status}/{pagination}/{search?}', 'MyController@fetchUsers')->name('fetch-users');

When the this.search is empty I am getting this:

Request URL: https://mywebsite.dev/fetch-users/0/1/
Request Method: GET
Status Code: 301 Moved Permanently (from disk cache)

It redirects to here on each request:

https://mywebsite.dev/fetch-users/0/1

The last / slash seems to be causing a redirection when this value is left empty.

As soon as I remove it, the problem stops…no redirection.

Any idea how I can make the last slash disappear if the last value is empty?

Thank you.

Sort 2d Array by ascending order using Javascript

I’ve tried a map and forEach loop and still can’t get this to sort by alphabetical order. Not sure what I am missing here.

My array:

const filtData = [
  [
    {
      gameType: "Rowing",
    },
    {
      gameType: "Rowing",
    },
    {
      gameType: "Rowing",
    },
  ],
  [
    {
      gameType: "Golf",
    },
    {
      gameType: "Golf",
    },
    {
      gameType: "Golf",
    },
  ],
  [
    {
      gameType: "Soccer",
    },
    {
      gameType: "Soccer",
    },
    {
      gameType: "Soccer",
    },
  ],
  [
    {
      gameType: "Baseball",
    },
    {
      gameType: "Baseball",
    },
    {
      gameType: "Baseball",
    },
  ],
]

Js:

filtData.forEach(d => d.sort((a,b) => a.gameType - b.gameType))
console.log(filtData) /* <--fails  */

const sortedData = filtData.map((d) => d.sort((a, b) => {
  return a.gameType - b.gameType;
}));
console.log("sortedData", sortedData)/* <--fails  */

JsFiddle:
https://jsfiddle.net/eL510oq3/

React.JS Carousel Images Not Showing

So after spending ours figuring out how to route the images folder to my Slider.js component I still can’t seem to make the images pop up.

Here’s my Slider.js code

import React, {useState} from 'react'
import './Slider.css'
import BtnSlider from './BtnSlider'
import dataSlider from './dataSlider'

export default function Slider() {

    const [slideIndex, setSlideIndex] = useState(1)

    const nextSlide = () => {
        if(slideIndex !== dataSlider.length){
            setSlideIndex(slideIndex + 1)
        } 
        else if (slideIndex === dataSlider.length){
            setSlideIndex(1)
        }
    }

    const prevSlide = () => {
        if(slideIndex !== 1){
            setSlideIndex(slideIndex - 1)
        }
        else if (slideIndex === 1){
            setSlideIndex(dataSlider.length)
        }
    }

    const moveDot = index => {
        setSlideIndex(index)
    }

    return (
        <div className="container-slider">
            {dataSlider.map((obj, index) => {
                return (
                    <div
                    key={obj.id}
                    className={slideIndex === index + 1 ? "slide active-anim" : "slide"}
                    >
                        <img 
                        src={process.env.PUBLIC_URL + `/images${index + 1}.jpg`} 
                        />
                    </div>
                )
            })}
            <BtnSlider moveSlide={nextSlide} direction={"next"} />
            <BtnSlider moveSlide={prevSlide} direction={"prev"}/>

            <div className="container-dots">
                {Array.from({length: 5}).map((item, index) => (
                    <div 
                    onClick={() => moveDot(index + 1)}
                    className={slideIndex === index + 1 ? "dot active" : "dot"}
                    ></div>
                ))}
            </div>
        </div>
    )
}

It shows this when I click and slide through. Just need to make sure the src is working enter image description here

react-router-dom Link change URL but doesn’t render [duplicate]

So this is my code, I’m trying to make a simple router with 3 pages, but it’s doesn’t work. I followed the tutorial on the official page of react-router-dom.

import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

import Home from './Compoments/Home';
import Register from './Compoments/Register';
import Connexion from './Compoments/Connexion';

import './App.css';

function App() {
  return (
    <Router>
      <nav>
        <ul className='nav-links'>
          <li>
            <Link to="/">Logo</Link>
          </li>
          <ul>
            <li>
              <Link to="/register">Inscription</Link>
            </li>
            <li>
              <Link to="/connect">Connexion</Link>
            </li>
          </ul>
        </ul>
      </nav>

      <Switch> 
        <Route path="/register">
          <Register />
        </Route>
        <Route path="/connect">
          <Connexion />
        </Route>
        <Route exact path="/">
          <Home />
        </Route>
      </Switch> 
    </Router>
  );
}

export default App; 

React Vite Proxy Configuration

After switch to vite, I am trying to mimic proxy: "http://localhost:5000" which I previously used in package.json

Here is my vite config

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:5000",
        changeOrigin: true,
        secure: false,
      },
    },
  },
});

I have react app running on port 3000. When I send a request in the root url (http://localhost:3000) everything works fine

const { data } = await axios.get("api/user/me");

  • Well, not really fine. Even though proper data is returned in response, in the console request gets sent to http://localhost:3000/api/user/me instead of http://localhost:5000/api/user/me. Can anyone explain this behaviour?

The main problem lies when I navigate to another page (e.g. http://localhost:3000/dashboard), then the same request gets sent to http://localhost:3000/dashboard/api/user/me.

What am I doing wrong? I want to send requests to http://localhost:5000, no matter the location

I found a workaround by specifying FE url before every request const { data } = await axios.get("http://localhost:3000/api/user/me");, but still is there a way to mimic package.json proxy behaviour?

How can I validate a field that has to accept only valid Windows paths?

I need to validate a field which MUST accept only valid Windows paths. What I am wondering is what is for real a “valid Windows path”. I mean, what are those requirements?

I have this regex /^(?:[a-z]:)?[/\]{0,2}(?:[./\ ](?![./\n])|[^<>:"|?*./\ n])+$/gmi => https://regex101.com/r/4JY31I/1 but you can enter things like a dot (.) but not double dot like (..), you can enter such a thing like iuygiugi and it will still work. So I am wondering what should I test for when validating this field or if is it ok to leave the regex as it is right now?

Eg: C:// or whatever that is a requirement for a valid path.

Complete one promise array first, then complete another promise array Javascript

I have a problem with promises and have no idea how resolve this:

My idea is to have two methods that are a “dispatcher”. In testFetchFaceCharacter() call all promises that i need to resolved first. Need all data from state: {Body:{}, TopA:{}, eyes:{}} When testFetchCharacter() finished, immediately start testFetchTopCharacter(), only if all previous promises executed successfully.

However, at this point (with this code) have a errors. The promises aren’t executed “Synchronously”. still retrived “asynchronously”. Wich “should not happen”. Since it “reduce” (from what i read in several articles) avoided that behavior.

const buildCharacter = (state) => {
  try {
    testFetchFaceCharacter(state);
    testFetchTopCharacter(state);
  } catch (e) {
    console.error(e + "En buildCharacter");
}

const testFetchCharacter = (state) => {
  const promises = [
    fetchCustom(state.Body.id, state.Body.file),
    fetchCustom(state.TopA.id, state.TopA.file),
    fetchCustom(state.eyes.id, state.eyes.file),
    fetchCustom(state.mouth.id, state.mouth.file),
    fetchCustom(state.nose.id, state.nose.file),
    fetchCustom(state.eyebrow.id, state.eyebrow.file),
    fetchCustom(state.Clothing.id, state.Clothing.file),
  ];
  
  promises.reduce(async (previousPromise, nextPromise) => {
    await previousPromise
    return nextPromise
  }, Promise.resolve());
}

const testFetchTopCharacter = (state) => {
  const promises = [
    fetchCustom(state.beard.id, state.beard.file),
    fetchCustom(state.hat.id, state.hat.file),
    fetchCustom(state.hair.id, state.hair.file),
    fetchCustom(state.glass.id, state.glass.file)
  ];

  promises.reduce(async (previousPromise, nextPromise) => {
    await previousPromise
    return nextPromise
  }, Promise.resolve());
}

Y try this:

Execute -> Body
Execute -> TopA
Execute -> [eyes, mouth, nose, Clothing, eyebrow] //No matter the order

then
 Execute [beard, hat, hair, glass] //not matter the order