Issue with offset – Moment library using JavaScript

I am using a MomentJS library and want to set the start from date in such format: YYYY-MM-DDTHH:mm:ss.SSSZZ. This date I will send to some server which validates it.

Code:

moment.utc(date).utcOffset(date.getTimezoneOffset()).format("YYYY-MM-DDTHH:mm:ss.SSSZZ")

The problem is that this code returns: -0200 the timezone offset:

“2023-12-30T22:00:00.000-0200”

This service accepts only such format “2023-12-30T22:00:00.000+0000” with +0000 offset.

When I set utcOffset as 0: moment.utc(date).utcOffset(0).format("YYYY-MM-DDTHH:mm:ss.SSSZZ"). It removes the offset but changes date to be invalid date:

2023-12-31T00:00:00.000+0000

Is there a way to set this date: 2023-12-30T22:00:00.000 and make offset always +0000? Thanks.

JavaScript function output doesn’t display on textarea

Please help, I cant make to display the output to text area of the function attached to the button when clicked. Below code I have buttons called “GENERATE” and “PREVIEW”. The “GENERATE” button is expected to display the combined value of the selected dropdowns, input text into the first text area [Incident Description] however it won’t. I was able to make the function to works if i just have the “GENERATE” function in a HTML/JavaScript code but if i include the function/module of “PREVIEW” it wont work. PREVIEW function output for now is fine.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!----======== CSS ========--> 
    <link rel="stylesheet" href="style.css">
     
    <!----===== Iconscout CSS ===== -->
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">

</head>
<body>
    <div class = "main"></div>
    <div class="container">
        <header>Service Affecting Incident Notification</header>
        <form id ="form" >
                <div class="Incident Generator">
                    <span class="title">Service Affecting Incident</span>
                    <div class="fields">
                        <div class="input-field">
                            <label>Incident Status </label>
                            <select id="incstatus">
                                <option value="Open">Open</option>
                                <option value="Closed">Closed</option>
                            </select>
                      </div>
                      <div class="input-field">
                        <label>Incident Priority </label>
                        <select id="incpriority">
                            <option value="Low">Low</option>
                            <option value="Medium">Medium</option>
                            <option value="High">High</option>
                        </select>
                     </div>
                        <div class="input-field">
                            <label>Business Impact </label>
                            <select id="bizimpact">
                                <option value="Partial">Partial</option>
                                <option value="Full">Full</option>
                              </select>
                        </div>
                        <div class="input-field">
                            <label>Reported By </label>
                            <select id="reportedby">
                                <option value="Operator 1">Operator 1</option>
                                <option value="OPerator 2">OPerator 2</option>
                              </select>
                        </div>
                      
                        <div class="input-field">
                            <label>Incident Description</label>
                            <input type="text" id="insshortdesc" cols="100" placeholder="Enter Incident Description" >
                        </div>

                        <div class="input-field">
                            <label>Affected Features </label>
                            <select id="features">
                                <option value="Login">Login</option>
                                <option value="Signup">Signup</option>
                              </select>
                        </div>
                        <div class="input-field">
                            <label>Impacted Devices/App </label>
                            <select id="devices">
                                <option value="iOS">iOS/iPAD OS</option>
                                <option value="Android">Android Device</option>
                              </select>
                        </div>
                        <div class="input-field">
                            <label> Incident Description</label>
                            <textarea type="text" id="resultTextarea" rows="10" cols="100"></textarea>
                        </div>
                        <div><span id = "result"></span></div>

                        <span class="title">Incident Updates Goes Here</span>
                        <div class="input-field">
                             <textarea type="text" id="updateTextarea" rows="5" cols="100"></textarea>
                        </div>



                        <div>
                            </div><div>
                       
      
                      </div>   </br>  
                      <div>
                         <button id="upButton"  onclick="updateTextarea()">Generate</button>
                         <button>Incident Update</button>
                         <button id="subbutton" onclick="displaySummary()">Preview</button>
                      </div>
            </form>
            
    </div>
</div>
            
         
    </div>
  <div class="botcontainer"></class>
    <div><span id="incSummary"></span><br> 
    <div><span id="incDescription"></span><br> 
    <div><span id="biznotes"></span><br>    



<script>


window.onload=function(){
          document.getElementById('subbutton','upButton').addEventListener('click', function(ev){
              ev.preventDefault(); // prevent the page submit
              });
         }


        function displaySummary() {
          
            var incstatus = document.getElementById('incstatus').value;
            var incpriority = document.getElementById('incpriority').value;
            var bizimpact = document.getElementById('bizimpact').value;
            var reportedby = document.getElementById('reportedby').value;
            var insshortdesc = document.getElementById('insshortdesc').value;
            var features = document.getElementById('features').value;
            var devices = document.getElementById('devices').value;
          
            var resultTextarea = document.getElementById('resultTextarea').value;

       
              
            var incSummary = 'Service Affecting Incident Notification:n';
            incSummary += 'Incident Status          : ' + incstatus + 'n';
            incSummary += 'Incident Priority        :' + incpriority + 'n';
            incSummary += 'Business Impact          :' + bizimpact + 'n';
            incSummary += 'Reported By              :' + reportedby + 'n';
            document.getElementById('incSummary').innerText = incSummary;

            var incDescription = 'n';
            incDescription += 'Incident Short Description             :' + insshortdesc + 'n';
            incDescription += 'Affected Features             :' + features + 'n';
            incDescription += 'Impacted Devices/Apps             :' + devices + 'n';
            incDescription += 'Impacted Service         :' + checkboxesValues.join(', ') + 'n';
            document.getElementById('incDescription').innerText = incDescription;
         

            var biznotes = 'Incident Descriptionn';
            biznotes += '' + resultTextarea + 'n';
            document.getElementById('biznotes').innerText =  biznotes;

        }


        function updateTextarea() {
            //Get the selected values from both dropdowns
            const bizimpactValue = document.getElementById('bizimpact').value;
            const featuresValue = document.getElementById('features').value;

         
            // Update the textarea dynamically based on the selected values
          document.getElementById('resultTextarea').value = getUpdatedMessage(bizimpactValue, featuresValue);
      
         
        }

          function getUpdatedMessage(bizimpactValue, featuresValue) {
            // Return the updated message dynamically based on the selected values
   
            if (bizimpactValue === 'Full') {
                return "Please note we are observing full system outage impacting " +
                    "the " + featuresValue + " functionality. " ;
            } else if (bizimpactValue === 'Partial') {
                return "We are observing intermittent outage impacting the " +
                    featuresValue + " functionality. " ;
            }
            return '';
        }


    </script>


</body>
</html>

GENERATE function module works as expected when in seperate html/javascript program

Does given method runs immediately or will it wait until the data is fully collected? [closed]

class InputHandler
{
    formData = new FormData()
    params = {
        'input_ids': ['name', 'surname', 'age']
    }
    
    grabInputs()
    {
        for (const inputId of this.params.input_ids) {
            this.formData.append(inputId, document.getElementById(inputId).value)
        }

        // I want this method to work only when all data is received:
        this.sendData()
    }

    async sendData()
    {
        try {
            const response = await fetch(this.endpoint, {
                method: "POST",
                body: this.formData
            })

            if (!response.ok) {
                throw Error(response.statusText)
            }

            let json = await response.json().then( (json) => {
                return json
            })

        } catch (e) {
            //
        }
    }

I think it is possible that method sendData() will fire before the data is collected, becouse I read that DOM tree is slow, so probably in some cases method sendData() may not send all the fields.

How can I make sure that method sendData() fires always after loop get all values from inputs?

How to show/handle errors thrown while running JavaScript flow actions in Power Automate Desktop?

The documentation about script actions states, that a variable ScriptError is produced:

https://learn.microsoft.com/en-us/power-automate/desktop-flows/actions-reference/scripting#variables-produced-2

However, when trying to display that Variable using a Display message flow action or Set variable flow action, I get the error

Variable 'ScriptError' does not exist.

I also tried the flow action On block error to handle errors thrown by a JavaScript/JScript action. The script runs silently without showing any error.

=> How to show/handle errors for script actions in Power Automate Desktop?

Related:

How to return result from JavaScript action in Power Automate Desktop?

Create new page when new path is added

How can I create a entirely new page when I modify my website’s URL, adding a new path to it. I’m focused in using react router, but can change depending on difficulty.

Is something similar to what dontpad.com does, where it creates a new notepad site when you add a new path.

Just want a general idea, so I can start working on it.

I’m just planning, nothing done already.

How to detach pendulum bob from string?

I’ve implemented F = ma in order to write an interactive code that I would say somewhat simulates a pendulum. However, I would like to make it so that once the user releases their finger, the ball detaches itself from the string and goes flying all the way due to the tension it was feeling. How could I do so?:

// A simple simulation of F = ma using vanilla javascript
// F is the net force applied on an object
// m is the mass of the object
// a is the acceleration of the object

// Create a canvas element to display the simulation
var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);

// Get the context of the canvas
var ctx = canvas.getContext("2d");

// Define some constants
var G = 9.8; // gravitational acceleration
var DT = 0.01; // time step
var R = 20; // radius of the object

// Define the initial state of the object
var x = 100; // x position
var y = 100; // y position
var vx = 0; // x velocity
var vy = 0; // y velocity
var ax = 0; // x acceleration
var ay = 0; // y acceleration
var m = 1; // mass
var Fx = 0; // x force
var Fy = 0; // y force

// Define a function to update the state of the object
function update() {
  // Apply the net force to the object
  Fx = 0; // no horizontal force
  Fy = m * G; // only vertical force due to gravity

  // Calculate the acceleration of the object
  ax = Fx / m; // F = ma
  ay = Fy / m; // F = ma

  // Calculate the velocity of the object
  vx = vx + ax * DT; // v = v + a * dt
  vy = vy + ay * DT; // v = v + a * dt

  // Calculate the position of the object
  x = x + vx * DT; // x = x + v * dt
  y = y + vy * DT; // y = y + v * dt

  // Check for collision with the boundaries of the canvas
  if (x < R) {
    // hit the left wall
    x = R; // set the position to the wall
    vx = -vx; // reverse the velocity
  }
  if (x > canvas.width - R) {
    // hit the right wall
    x = canvas.width - R; // set the position to the wall
    vx = -vx; // reverse the velocity
  }
  if (y < R) {
    // hit the top wall
    y = R; // set the position to the wall
    vy = -vy; // reverse the velocity
  }
  if (y > canvas.height - R) {
    // hit the bottom wall
    y = canvas.height - R; // set the position to the wall
    vy = -vy; // reverse the velocity
  }
}

// Define a function to draw the object and the canvas
function draw() {
  // Clear the canvas
  ctx.fillStyle = "white";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // Draw the object as a circle
  ctx.fillStyle = "red";
  ctx.beginPath();
  ctx.arc(x, y, R, 0, 2 * Math.PI);
  ctx.fill();

  // Draw some text to show the state of the object
  ctx.fillStyle = "black";
  ctx.font = "20px Arial";
  ctx.fillText("x: " + x.toFixed(2), 10, 30);
  ctx.fillText("y: " + y.toFixed(2), 10, 60);
  ctx.fillText("vx: " + vx.toFixed(2), 10, 90);
  ctx.fillText("vy: " + vy.toFixed(2), 10, 120);
  ctx.fillText("ax: " + ax.toFixed(2), 10, 150);
  ctx.fillText("ay: " + ay.toFixed(2), 10, 180);
  ctx.fillText("m: " + m.toFixed(2), 10, 210);
  ctx.fillText("Fx: " + Fx.toFixed(2), 10, 240);
  ctx.fillText("Fy: " + Fy.toFixed(2), 10, 270);
}

// Define a function to run the simulation
function run() {
  // Update the state of the object
  update();

  // Draw the object and the canvas
  draw();

  // Request the next animation frame
  requestAnimationFrame(run);
}

// Start the simulation
run();

As you can see within my code above, I’ve attempted to do so by applying the tension force the ball was feeling. Yet I am still having trouble detaching it from the string.

why when i refresh browser it redirect me to the login in laravel and react

So im having a problem about my login state of the application the problem is when i logged in and try to refresh the browser it redirects me to the login page my guess here is the routing has the problem also additional the token is not yet expired this is my code looks like

RequireAuth.jsx

import { useEffect } from 'react';
import useAuth from '../hooks/useAuth';

    const RequireAuth = ({ allowedRoles }) => {
      const { auth } = useAuth();
      const location = useLocation();


      return (
        auth?.role_id
        ? (
        allowedRoles.some(role => role === auth.role_id)
          ? <Outlet />
          : auth.user
            ? <Navigate to="/unauthorized" state={{from: location }} replace />
            : <Navigate to="/login" state={{ from: location }} replace />
          )
        : <Navigate to="/login" state={{from: location }} replace />
      );
    }
    export default RequireAuth;

This is my Login.jsx looks

import React from 'react';
import * as MUI from '../../import';
import axios from '../../api/axios';
import BGIMG from '../../assets/SchoolBG1.jpg';
import useAuth from '../../hooks/useAuth';
import useLoginStore from '../Store/LoginStore'
import { useForm, Controller } from 'react-hook-form';
import { useState, useEffect } from "react";
import { Link, useNavigate, useLocation} from 'react-router-dom';
import { DevTool } from '@hookform/devtools';


const defaultTheme = MUI.createTheme();
const EMAIL_REGEX =  /^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([^<>()[].,;:s@"]+.)+[^<>()[].,;:s@"]{2,})$/i;
const LOGIN_URL = '/api/login'

export default function Login() {
  const { setAuth } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const from = location.state?.from?.pathname || "/";
  const [loggedIn, setLoggedIn] = useState();

  const {
    errMsg,
    setErrMsg,
    loading,
    setLoading,
    showPassword,
    expirationTime,
    setExpirationTime,
    handleTogglePassword,
    token,
    setToken,
  } = useLoginStore();
  
  const form = useForm();
  const { register, handleSubmit, control, formState } = form;
  const { errors } = formState;
 
  //Accepted Domains for the email
  const isSupportedDomain = (email) => {
    const supportedDomains = ['yahoo.com', 'gmail.com', 'outlook.com'];
    const educationalDomainRegex = /@[a-zA-Z0-9.-]+.(edu(.[a-zA-Z]{2})?|[a-zA-Z]{2}.[a-zA-Z]{2})$/;
    const domain = email.split('@')[1];
    return supportedDomains.includes(domain) || educationalDomainRegex.test(email);
  };

  const csrf = () => axios.get("/sanctum/csrf-cookie")

  const onSubmit = async (data, event) => {
    event.preventDefault(); // Prevent default form submission behavior
    setLoading(true);
    await csrf()
    try {
      const config = {
        headers: {
          "Content-type": "application/json",
        }
      };
      const postData = {
        email_address: data.email_address,
        password: data.password,
      };

      const response = await axios.post(
        LOGIN_URL,
        JSON.stringify(postData),
        config,
      ); 

      const { remember_token, user, roles_name, expires_at } = response.data;

      setLoggedIn(remember_token)

      console.log(JSON.stringify(response?.data));
      
      const role_id = response?.data?.user?.role_id;

      setExpirationTime(new Date(expires_at).getTime());
      
      setLoading(false);

      // Set the authenticated user state using setAuth from your useAuth hook
      setAuth({ user, remember_token, roles_name, role_id, expirationTime});

        // Set the token and expiration time in local storage
        localStorage.setItem('remember_token', remember_token);

      const rolePath = role_id === 1  ? '/'  : role_id === 2 ? '/' : role_id === 3 ? '/scholar-dashboard' : '/login';
  
      // Navigate the user to the intended route (from variable contains the intended route)
      navigate(rolePath);
      
    } catch (err) {
      setLoading(false);
      if(err.response?.status === 422){
        setErrMsg('Email address and password are required');
      }
      else if(err.response?.status === 409){
        setErrMsg('Email Address already been taken');
      }
      else if(err.response?.status === 500){
        setErrMsg('Server Error');
      }
      else if (err.response?.status === 401) {
        setErrMsg('Login failed. Please check your credentials and try again.');
      }
      else{
        setErrMsg('Network error occurred. Please try again.');
      }
    }
  }


  {/* When its size to a Tablet mode the Left Grid display none  */}
  const isMobile = MUI.useMediaQuery('(max-width:768px)');

  return (
    <MUI.ThemeProvider theme={defaultTheme}>

    {/*  Right Grid is the Picture Grid  */}
    <MUI.Grid container component="main" sx={{ height: '100vh' }}>
      <MUI.CssBaseline />
      {!isMobile && (
        <MUI.Grid
          container 
          alignItems='center' 
          justifyContent='center'
          item
          xs={false}
          sm={12}
          md={7}
          sx={{
              display: 'flex', // Use flex container
              flexDirection: 'column', // Stack items vertically
              alignItems: 'center', // Center items horizontally
              justifyContent: 'center', // Center items vertically
              backgroundImage: `url(${BGIMG})`,
              backgroundRepeat: 'no-repeat',
              backgroundColor: (t) =>
                t.palette.mode === 'light' ? t.palette.grey[50] : t.palette.grey[900],
              backgroundSize: 'cover',
              backgroundPosition: 'center',
              textAlign: 'center',
              padding: '2rem', // Add padding to the content
            }}
        >
          <br />
          <MUI.Typography variant="h2" color="background.paper" paragraph>
            Welcome to Gado and Jess <br/> Jalandoni Scholarship Program
          </MUI.Typography>
          <MUI.Typography variant="h5" color="background.paper" paragraph>
            Empowering dreams through education.
          </MUI.Typography>
        </MUI.Grid>
      )}

      {/* Left Grid is the Login Form  */}
      <MUI.Grid item xs={12} sm={12} md={5} component={MUI.Paper} elevation={6} square container 
        alignItems='center' 
        justifyContent='center'
        sx={{
          p: 3,
        }}>

        {loading && (
            <MUI.Backdrop
            open={loading}
            sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
            >
              <MUI.Box
                sx={{
                  position: 'absolute',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(-50%, -50%)',
                  zIndex: (theme) => theme.zIndex.drawer + 2,
                }}
              >
                <MUI.CircularProgress />
              </MUI.Box>
            </MUI.Backdrop>
          )}
        
        {errMsg && (
        <p id="errMsg" style={{ color: 'red' }}>
          {' '}
          <MUI.InfoIcon className="infoErr" /> {errMsg}
        </p>
      )}

        <MUI.Box
          sx={{
            my: 1,
            mx: 4,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            width: '100%', 
          }}>
            <img src='https://raw.githubusercontent.com/TianMeds/image--stocks-for-coding/main/Scholarlink%20Logos.png' alt="Logo" style={{ width: '200px', height: '150px' }} />
            <MUI.Typography component="h3" variant="h4" sx={{ textAlign: 'left', fontWeight: 'bold'  }}>
              Login
            </MUI.Typography>

            <MUI.Typography>
              Welcome back! Please enter your details.
            </MUI.Typography>
          <br/>
          {/* Email Textfield  */} 
              <MUI.Box component="form" sx={{ mt: 1,  width: '100%', }}  onSubmit={(event) => handleSubmit((data) => onSubmit(data, event))(event)} method='post' >
                <MUI.Grid item>
                  <MUI.TextField
                    variant='standard'
                    margin="dense"
                    fullWidth
                    type='email'
                    id="email_address"
                    autoComplete='off'
                    placeholder='Email Address'
                    {...register('email_address', { 
                      pattern: {
                        value: EMAIL_REGEX,
                        message: 'Invalid email address'
                      },
                      validate: 
                        value => isSupportedDomain(value) || 'Email domain not supported',
                      required: {
                        value: true,
                        message: 'Email address is required'
                      },
                    })}
                  />
                  {errors.email_address &&(
                    <p id="errMsg">
                      <MUI.InfoIcon className="infoErr" /> 
                      {errors.email_address.message}
                    </p>
                  )}
                </MUI.Grid>
                <br/> <br/>
                {/* Password Textfield  */}
                <MUI.Grid item>
                  <MUI.TextField
                    variant='standard'
                    margin="dense"
                    fullWidth
                    type={showPassword ? 'text' : 'password'}
                    id="password"
                    placeholder='Password'
                    InputProps={{
                      endAdornment: (
                        <MUI.InputAdornment position="end">
                          <MUI.IconButton onClick={handleTogglePassword} edge="end">
                            {showPassword ? 
                            <MUI.VisibilityIcon sx={{ fontSize: '1.2rem' }} /> : <MUI.VisibilityOffIcon sx={{ fontSize: '1.2rem' }}  />
                            }
                          </MUI.IconButton>
                        </MUI.InputAdornment>
                      ),
                    }} 
                    {...register('password', { 
                      required: {
                        value: true,
                        message: 'Password is required'
                      },
                    })}
                  />
                  {errors.password &&(
                    <p id="errMsg">
                      <MUI.InfoIcon className="infoErr" /> 
                      {errors.password.message}
                    </p>
                  )}
                </MUI.Grid>

            <br/>

              {/* Remember Me Checkbox  */}
              <MUI.FormControlLabel
                control={<MUI.Checkbox value="remember" color="primary" />}
                label="Remember me"
              />

              {/* Login Button  */}
              <MUI.Button
                type="submit"
                fullWidth
                variant="contained"
                sx={{ mt: 3, mb: 2, color: 'white', backgroundColor: '#311b92', borderRadius: '10px' }}
              >
                Sign In
              </MUI.Button>

            {/* Forgot Password Link  */}
              <MUI.Grid container>
                <MUI.Grid item xs>
                  <MUI.Link href="#" variant="body2" style={{ textDecoration: 'none' }}>
                    Forgot password?
                  </MUI.Link>
                </MUI.Grid>
              </MUI.Grid>

              
          </MUI.Box>
        </MUI.Box>
      </MUI.Grid>
      <DevTool control={control} />
    </MUI.Grid>
  </MUI.ThemeProvider>
  )
}

API.php


//Protected Route
Route::group(['middleware' => ['auth:sanctum']], function() {
    Route::post('/scholars', [ScholarController::class, 'store']);
    Route::put('/scholars/{user_id}', [ScholarController::class, 'update']);
    Route::delete('/scholars/{user_id}', [ScholarController::class, 'destroy']);
    Route::post('/users', [UserController::class, 'store']);
    Route::put('/users/{id}', [UserController::class, 'update']);
    Route::delete('/users/{firstname}', [UserController::class, 'destroy']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::apiResource('/scholars', ScholarController::class)->only(['index', 'show']);
    Route::apiResource('/users', UserController::class)->only(['index', 'show']);
    Route::apiResource('/roles', RoleController::class)->only(['index', 'show']);
    Route::get('/scholars/search/{user_id}', [ScholarController::class, 'search']);
    Route::get('/users/search/{firstname}', [UserController::class, 'search']);
   // Route::get('/refresh-token', [AuthController::class,'refreshToken']); 
});


//Public Route
Route::post('/login', [AuthController::class, 'login']);


Route::middleware('auth:api')->get('/scholar', function (Request $request){
    return $request->scholar();;
});

Route::middleware('auth:api')->get('/user', function (Request $request){
    return $request->scholar();;
});

if there is still needed part of the code to be checked im willing to send it

Cant display data

so i am writing a React application to fetch and display data and sort it according to popularity but its not working

this is the api link – https://s3.amazonaws.com/open-to-cors/assignment.json

import React, { useState, useEffect } from "react";

const App = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(
          "https://s3.amazonaws.com/open-to-cors/assignment.json"
        );
        const print = await response.json();
        const ans = Object.values(print);
         const sortedProducts = ans.data.sort(
           (a, b) => b.Popularity - a.Popularity
         );
        setProducts(ans);
        // setProducts(print);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Product List</h1>
      <ul>
        {products.map((product, index) => (
          <li key={index}>
            <strong>Title:</strong> {product.title},<strong>Price:</strong>{" "}
            {product.Price},<strong>Popularity:</strong>
            {product.Popularity}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

i tried to convert fetched data into object but didnt work

How do i upload a folder that contains all my code files to my Github repo using Github’s REST API programmatically?

How do I upload a folder that contains all my code files to my Github repo using Github’s REST API programmatically? Can anyone help me do that in JavaScript with Node.js?

Currently, when I try to run my code, it only uploads files, but how do I upload a folder instead? I don’t want to upload files one by one. Any idea what to do?

async function upload() {
  const message = 'amogus';
  const content = 'aaaaa';
  const owner = 'MY-USERNAME';
  const repo = 'MY-REPO-NAME';
  const path = 'my-project';
  const auth = '{MY ACCESS TOKEN HERE}';

  const existingFile = await (await fetch(
    `https://api.github.com/repos/${owner}/${repo}/contents/${path}`,
    {
      method: 'GET',
      headers: {
        Accept: 'application/vnd.github+json',
        Authorization: `Bearer ${auth}`
      }
    }
  )).json();

  await (await fetch(
    `https://api.github.com/repos/${owner}/${repo}/contents/${path}`,
    {
      method: 'PUT',
      headers: {
        Accept: 'application/vnd.github+json',
        Authorization: `Bearer ${auth}`
      },
      body: JSON.stringify({
        message: message,
        content: btoa(content),
        sha: existingFile.sha,
      }),
    }
  )).json();
}

Get and save elements info from DataTable in each pagination

I am currently using a sql query to retrieve information from my database when the page loads. The result of the query is a php array $data[] which is passed through the DataTables plugin (jquery) $(‘#table’).DataTable() to paginate the results and on the other hand I call the save_codes() function to temporaly backup the values of the textarea elements in the table, so that later the user can undo changes to the value of these.

    $(document).ready(function(){
    var id_query = '<?php echo $id_query; ?>';
    $.ajax({
                url: location.origin + '/program/functions.php',
                type: 'POST',
                data: { 
                    consultadatetable: id_query,
                },
                dataType: 'JSON',
                async: true,
                
                success: function(data){
                    var dataSrc = [];
                    $('#table').DataTable({
                        "data":  data.data,
                        "dom": '<"top"lif>rBt<"bottom"ilp><"clear">',
                        "lengthMenu": [[50,100,150,-1], [50,100,150,"All"]],
                        select: true
                    });
                    save_codes();
                }
    });
    });
    var textareas_list = [];

    function save_codes()
    {
        textareas_list = document.querySelectorAll(".code");
        textareas_list_size = textareas_list.length;
        
        for (var i = 0; i < textareas_list_size; i++) 
        {
            var id = textareas_list[i].id;
            var value = textareas_list[i].value;
            code_list.push({identificator: id, code: value});
        }
    }

This function does its job perfectly when the page is loaded for the first time, the problem is that when I move to another page of the table, using the DataTables pagination feature, the save_codes() function is not able to update the information contained in code_list since the page is not reloading and the function is not called again.

Does anyone know how I can infer in the DataTables pagination to update the information that my function stores, so that the information it saves in code_list always corresponds to the results of each active pagination?

Thank you very much in advance.

The information temporarily stored by the save_codes() function must always correspond to the results of the active paging of the table.

Node.js issues in VS

Im new to the development world. Im getting to know how VS works.

And I type this in the editor:

var greeting='Hello, World!';
console.log(greeting);

I have saved this as Hello_World.js. Then I type in the terminal node Hello_World.js and all I get back is: node Hello_World.js instead of the actual text.

I have downloaded the most up to date version of node.js and im not sure what I am doing wrong as I dont know how to use VS yet. Could I have some advice please? And thank you..

how would I turn this code into a program that can be opened like normal

I created a program that determines if you are jolly or not, and I want to turn it into a program that can be executed like a normal program

I haven’t tried anything yet because I don’t know where to start. The result I want is that there’s a window that opens and there’s a button you can click. it runs the code that was made and displays what it would inside the console.

public class Main {
    public static void main(String[] args) {
        //this displays if you're jolly or not
        System.out.println("even is Jolly, odd is not");
        System.out.println("With the rules in place," + jollyStatement());

    }

    public static double amountOfPresents() {
        //this is where a Random Number Generator will grab a number from 1-100, round it up to a whole number, and ships it down to the statement below
        int max = 100;
        int min = 0;
        double RNG = Math.floor(Math.random() * (max - min) + min);
        return (int) RNG;
    }

    public static boolean isJolly (double presentCount)
    {
        boolean jolly = false;
        if (presentCount % 2 == 0)
        {
            jolly = true;
        }
        return jolly;
    }

    public static String jollyStatement ()
    {
        double presentCount = amountOfPresents();
        String jollyOrNot = " since you gifted " + presentCount + ", that means you are not jolly";
        if (isJolly(presentCount))
        {
            jollyOrNot = " Since you gifted " + presentCount + ", that means that you are jolly";
        }
        return jollyOrNot;
    }
}

Here’s the code in question

input date rages in both array ranges

I have been working with this code:

var rangesInputRange1 = [
    { startDate: parseDate("15/04/2024"), endDate: parseDate("01/05/2024") },
    { startDate: parseDate("01/06/2024"), endDate: parseDate("30/06/2024") }
];

var rangesInputRange2 = [
    { startDate: parseDate("01/04/2024"), endDate: parseDate("14/04/2024") },
    { startDate: parseDate("01/07/2024"), endDate: parseDate("31/08/2024") }
];

function parseDate(dateString) {
    var parts = dateString.split("/");
    return new Date(parts[2], parts[1] - 1, parts[0]);
}

function isDateInRanges(date, ranges) {
  return ranges.some(function(range) {
    return date >= range.startDate && date <= range.endDate;
  });
}

function countDaysInRange(startDate, endDate) {
  var oneDay = 24 * 60 * 60 * 1000;
  return Math.round(Math.abs((startDate - endDate) / oneDay));
}

jQuery('#start-date, #end-date').on('change', function() {
  var startDate = parseDate(jQuery('#start-date').val());
  var endDate = parseDate(jQuery('#end-date').val());

  var daysInRange1 = isDateInRanges(startDate, rangesInputRange1) ? countDaysInRange(startDate, endDate) : 0;
  var daysInRange2 = isDateInRanges(startDate, rangesInputRange2) ? countDaysInRange(startDate, endDate) : 0;

  var inputRange1 = jQuery('input.checkbox1');
  var inputNumber1 = jQuery('input.number1');
  var inputRange2 = jQuery('input.checkbox2');
  var inputNumber2 = jQuery('input.number2');

  inputRange1.prop('checked', daysInRange1 > 0).trigger('change');
  inputNumber1.val(daysInRange1).trigger('change');
  inputRange2.prop('checked', daysInRange2 > 0).trigger('change');
  inputNumber2.val(daysInRange2).trigger('change');
});

jQuery('#start-date, #end-date').trigger('change');

I have succeeded in if #start-date and #end-date are in same rangesInputRange. in this case, the code works fine.

How can I calculate daysInRange if the selected dates are in both rangesInputRange? (example: dates 10/04/2024 to 17/04/2024)

or selected dates are in part in only one rangesInputRange? (example: 28/08/2024 to 03/09/2024).

(date dormat: dd/mm/YYYY)

many thanks

Issue with sendPasswordResetEmail() Function in Firebase-React Project

I am currently developing a React project with Firebase integration, and I’ve come across an error when attempting to use the sendPasswordResetEmail() function from the Firebase Authentication module. The error message displayed is as follows:

services_firebaseConfig_config__WEBPACK_IMPORTED_MODULE_1_.auth.sendPasswordResetEmail is not a function

This issue is particularly puzzling, because all other aspects of the Firebase SDK seem to be functioning correctly in my application, including Authentication, Storage, and Firestore. Additionally, I have verified that there are no errors in my Firebase SDK configuration.

Could you please provide some guidance on what might be causing this issue with the sendPasswordResetEmail() function? I am uncertain whether this is related to the way I am importing or initializing Firebase in my project, or if it’s an issue with the Firebase SDK itself.

Here are some details regarding my project setup:

  • React Version: [18.2.0]
  • Firebase SDK Version”firebase”: “^10.7.1”,

I have verified that there are no errors in my Firebase SDK configuration.