‘interface’ declarations can only be used in TypeScript files

I made a little web site and I have some errors in it. My file is tsx but still gives this errors ‘interface’ declarations can only be used in TypeScript files.

enter image description here

But I use interface in other file but there is not such error

enter image description here

I don’t know what to do. https://github.com/g1org11/redeplorers

src>components>destinationComponets>Destination.tsx.

I try to fix this error with ChatGPT/search in Google but unfortunately I don’t find any solution.

React Native: Issue with TextInput – Placeholder Text Not Clearing on Focus

I’m currently working on a React Native project and encountering an issue with the TextInput component. Despite setting up a placeholder text, it’s not clearing when the input field gains focus. Here’s a simplified version of my code:

import React from 'react';
import { View, TextInput } from 'react-native';

export default function MyComponent() {
  return (
    <View>
      <TextInput
        placeholder="Type something..."
        clearButtonMode="while-editing"
      />
      {/* ...other components */}
    </View>
  );
}

Despite using clearButtonMode and checking the documentation, the placeholder text remains visible when I start typing. I’ve tried different approaches, but the issue persists.

Can someone please provide guidance on how to troubleshoot and resolve this new problem with the TextInput placeholder text not clearing on focus in React Native? Any insights or suggestions would be appreciated. Thank you!

Vite config is not copying files over to build folder

I have the following plugin used inside a vite config:

...
  copy({
    targets: [
      { src: './register.css', dest: './build' },
      { src: './fonts/**/*', dest: './build' },
    ],
    flatten: false,
  }),
...

the vite.config.ts file is in the same directory with register.css and the fonts directory.

enter image description here

hover, when I run the build command, the register.css and the fonts directory are not being copied over.

enter image description here

res.redirect giving 404 NotFound error even when the route is defined in the router

Its just a simple react application wich has a login form so i want when the user send his data after verification the user must be redirected to /home by res.redirect.
So i was just checking wether res.redirect works or not, so res.redirect(‘/home) is giving 404 notfound error, i cant understand why
But when i manually type http://localhost:3000/home, the home page opens up
heres the complete code

this is my router—->

import Homescreen from './Homescreen';
import SignUp from './SignUp';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

function Home(){
return(
    <div>
        <Router>
            <Routes>
                <Route exact path='/home' element={<Homescreen />} />
                <Route exact path='/login' element={ <SignUp /> }/>
            </Routes>
        </Router>
    </div>
)
}

export default Home;

this is my SignUp.jsx—->

import { useState } from 'react';
import './SignIn.css';

export default function SignUp() {

  const [data, setData] = useState({
      username: "",
      password: "",
  })
  
  const handleinp = (e)=>{
      const name = e.target.name;
      const value = e.target.value;
  
      setData((prev)=>{
        return {...prev, [name]:value};
      });
  }

  function handlesubmit(e){
      e.preventDefault();
      console.log("submit button clicked")
      
      fetch("/SignIn", {
        method: "POST",
        headers:{"Content-Type": "application/json"},
        body: JSON.stringify({username: data.username, password: data.password}),
      } ).catch((err)=>{
        console.log(err)
      })}

  return (
      <div>
          <div style={{backgroundImage: `url("https://assets.nflxext.com/ffe/siteui/vlv3/b85863b0-0609-4dba-8fe8-d0370b25b9ee/fdf508c8-97d0-42fd-a6f9-9bef6bf96934/IN-en-20230731-popsignuptwoweeks-perspective_alpha_website_large.jpg")`, width: "100vw", height: "100vh", backgroundSize: "cover"}}>
              
              <div className='login-content'>
                  <div className='sign-navbar'>
                      <h1 className='login-title'>FlimFair</h1>
                  </div>

                  <form className='inp-form ' >
                  <div className='inp b'>
                      <div className='inp-box'>
                        
                          <h1 className='inp-title'>Sign In</h1>
                          <input className='inp-text' type='email' placeholder='Enter Email' name='username' value={data.username} onChange={handleinp} required/>
                          
                          <input className='inp-text' type='password' placeholder='Password' name='password' value={data.password} onChange={handleinp} required/>
                          
                          <button className='inp-submit' type='submit' onClick={(e)=>handlesubmit(e)}>Submit</button>
                      </div>
                      
                      <h1 style={{color: "#d1a0a0", fontWeight: "500", marginTop: "7rem", fontSize: "1.8rem"}}>New to FlimFare? <a href='/' style={{textDecoration: "none"}}>Sign Up now</a></h1>
                      <h1 style={{color: "#d1a0a0", fontWeight: "500", fontSize: "1.5rem", margin: "2rem 0 3rem 0"}}>This page is protected by Google reCAPTCHA to ensure you're not a bot.</h1>
                  </div>
                  </form>

              </div>

          </div>
        
      </div>
  )
}

this is my server.js—->

const express = require("express");
require('./connect');
const cors = require('cors');
const bodyParser = require('body-parser');
const expressSession = require("express-session");

const port = process.env.PORT || 5000;

const app = express();
app.use(cors());
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({extended:false}));
app.use(require('body-parser').text({type: '*/*'}));
app.use(expressSession({secret: "secret", resave: false, saveUninitialized:false}));


app.post("/SignIn", async(req, res)=>{
    console.log(req.body);
    res.redirect('/checkout')})



app.listen(port, ()=>{
    console.log(`Server running successfully on port no. ${port}`);
})

the server correctly logs the incoming data

this is the error iam getting—->

SignUp.jsx:24 
GET http://localhost:3000/checkout 404 (Not Found)

Tried to find solutions from ChatGPT, google, youtube but nothing worked

Executing powershell script from javascript (Discord.js command)

TL;DR: const spawn=require('child_process').spawn; spawn('powershell.exe', ['D:/Dev/My Bot/test.ps1']); doesn’t work

Hello,

I am using discord.js to make a bot, i want a command to execute a powershell script when it’s called, the command handling, registering works fine, but the execution of the script isn’t successful.

Here is the code of my command:

const { SlashCommandBuilder } = require('discord.js');
const spawn = require('child_process').spawn;

const authorizedUsers = ['...', '...'];

module.exports = {
    data: new SlashCommandBuilder()
        .setName('start_server')
        .setDescription('Start the minecraft modded server.'),
    async execute(interaction) {
        // If the user is authorized to run the command
        if (authorizedUsers.includes(interaction.user.id)) {
            console.log('Starting minecraft server');

            spawn('powershell.exe', ['D:/Dev/My Bot/test.ps1']);

            console.log('Minecraft server started !');
            await interaction.reply('Minecraft server started !');
        }
        else {
            await interaction.reply('You can't use this command');
        }
    },
};

The two messages are correctly sent in the console, the bot also replies to my message in discord, but the script isn’t executed

Can you help me with this ?

Gapless audio loop HTML5 and Javascript

I am creating a button that when clicked should play a song on repeat. When it starts the song again there seems to be a small delay. The song is 10.54 seconds long in a .wav file. Because the clip is so short when it repeats you really notice it. How can I remove the gap?

function toggleBox(audioId, element) {
  var audio = document.getElementById(audioId);

  audio.play();
}
<audio id="audio5" preload="auto" loop>
    <source src="sonidos/sonido5.wav" type="audio/wav">
</audio>

<div class="box" onclick="toggleBox('audio5', this)"></div>

I have tried answers from other people but none work.

How to access this funcion in another html [duplicate]

I have this code

   <div id="main">

    <div id="head">
        <ui:insert name="cabecera"><ui:include src="header.xhtml"/></ui:insert>
    </div>
    
    <div id="menu">
        <ui:insert name="menu"><ui:include src="menu.xhtml"/></ui:insert>
    </div>
    <div id="contenedor">           
        <iframe id="frameCuerpo" src="init.xhtml" name="frameCuerpo" frameborder="0" scrolling="auto" />            
    </div>  
    
    <div id="footer">
        <ui:insert name="pie"><ui:include src="footer.xhtml"/></ui:insert>
    </div>
</div>

I want to call a function which is on the menu.xhtml from the init.html which is load in the iframe “frameCuerpo”.

Anyway to do this?

The function is this:

     function expandMenu(submenu){
                    
        PF('myPanelMenu').headers.each(function ()
        {               
            var header = $(this);
            if (header.text() == submenu)
            {               
                PF('myPanelMenu').expandRootSubmenu(header, false);
            }
        });
                    
    }

I want to expand a menuitem on primefaces <p:panelMenu> in menu.xhtml from init.xhtml

i cant use with oauth2.0 , used interseptors axios

const setInterceptors = (api, authStore) => {
const Unauthorized = 401;
const Forbidden = 403;
const Error = 404;
const ErrorServer = 500;
let isRefreshed = false;
let refreshQueue = [];
    const processQueue = async () => {
        while (refreshQueue.length > 0) {
            const queuedRequest = refreshQueue.shift();
            try {
                const response = await api(queuedRequest.config);
                queuedRequest.resolve(response);
            } catch (error) {
                queuedRequest.reject(error);
            }
        }
    };
    
    api.interceptors.request.use(
        (config) => {
            if (authStore.tokens.accessToken) {
                config.headers["Authorization"] =
                    "Bearer " + authStore.tokens.accessToken;
            } 
            console.log('request');
            // if(isRefreshed){
            //   debugger
            // }
            return config;
        },
        (error) => Promise.reject(error)
    );
    
    api.interceptors.response.use(
        (response) => {
            console.log('response');
            return response;
        },
        async (error) => {
            const { config, response } = error;
            if (response && response.status === Unauthorized) {
                if (!config.isRetry) {
                    config.isRetry = true;
                    try {
                        if (!isRefreshed) {
                            isRefreshed = true;
                            await authStore.refresh();
                            processQueue();
                            return api(config);
                        } else {
                            return new Promise((resolve, reject) => {
                                refreshQueue.push({ config, resolve, reject });
                            });
                        }
                    } catch (error) {
                        console.log(error, 'catch retry');
                    }
                }
            } else if (response && response.status === Forbidden) {
                console.log("forbidden");
            } else if (response && response.status === Error) {
                console.log("404");
            }
            return Promise.reject(error);
        }
    );

};

export default setInterceptors;

api it was standart axios, authStore -> pinia

i dont know how to stop mupltiply request’s after take 401 error
i have 4 request and 1 response –> after this i can block request, but it doesn’t make sense.

i want to take first 401 error, and stop request’s

request books–> in component
enter image description here

I searched through the documentation but still don’t understand how to do it

Scroll to the selected row of a datatable

I would like my datatable to automatically scroll to the row selected by the user. My goal is the selected row to be displayed on top of the table. Below is my attempt with a MRE :

# libs
library(shiny)
library(shinyjs)
library(DT)

# data
data <- data.frame(
  ID = 1:100,
  Name = LETTERS[1:100],
  Value = rnorm(100)
)

# app
shinyApp(
  ui = fluidPage(
    dataTableOutput("table"),
    tags$script(HTML(
      "Shiny.addCustomMessageHandler('scrollToSelectedRow', function(selectedRow) {",
      "  table.row(selectedRow - 1).scrollTo(false);",
      "});"
    ))
  ),
  server = function(input, output, session) {
    output$table <- renderDT({
      datatable(
        data,
        selection = 'single',
        options = list(
          paging = FALSE
        )
      )
    })
    
    # observer
    observeEvent(input$table_rows_selected, {
      selectedRow <- input$table_rows_selected
      session$sendCustomMessage("scrollToSelectedRow", selectedRow)
    })
  }
)

How to silently revalidate cached data in Apollo Client in React?

I have an implementation of Apollo client’s useQuery in my React code that I need to update itself every time the user navigates to the page.
I tried using the query’s refetch function but it triggers the loading state of the query, hence making the cache useless.
What i need is for the data in cache to be rendered initially, but have it run the graphQl query in the background and update the cache if the data returned from the query is different from what has been saved on the cache. Basic cache revalidation.
How do I go about implementing this, please?

playsinline Limitation on iOS Chrome: Achieving True Video Invisibility for Audio Playback

Why is the playsinline attribute not working for inline video playback in the latest versions of Chrome on iOS devices?

Despite implementing various solutions from Stack Overflow, I’m unable to achieve a completely hidden video with audio playback using playsinline on the latest Chrome for iOS. I’m expecting that video should not visible on the screen. Are there reliable methods for hiding the video completely while still allowing audio playback in this scenario?

Re-Mapping object keys with dot as nested objects with preserved value types Typescript

I would like to be able to re-map object keys 'prefix.suffix': value as {prefix: { suffix: value }} but I struggle how to properly type the new re-mapped object. Typescript always drives me crazy when it comes to bit more complex typing especially for objects.
How can I get my remappedData with nested object from keys that have a dot and preserve the value types.

export namespace LocationSchemas {
  export type BasicFields = {
    name: FieldProps;
    region: Region;
    types: Types;
    "alt.number"?: FieldProps;
    "alt.centreNumber"?: FieldProps;
    "typeDetails.available": TypeDetails;
    "typeDetails.virtual": TypeDetails;
    "internal.name"?: FieldProps;
    "internal.type": FieldProps;
    "internal.format"?: FieldProps;
    "internal.status": InternalTradingStatus;
  };

  export type FieldProps = {
    visible: boolean;
    editable: boolean;
  };

  export type PossibleValueAs<T> = {
    value: T;
  };
  export type PossibleValueAsString = PossibleValueAs<string>;
  export type PossibleValueAsStringArray = PossibleValueAs<string[]>;
  export type PossibleValueAsIso = PossibleValueAs<{
    isoCountryCode: string;
    isoSubdivision?: string;
  }>;

  export type Types = FieldProps & {
    possibleValues: PossibleValueAsStringArray[];
    defaultValue?: PossibleValueAsStringArray[];
  };

  export type TypeDetails = FieldProps & { defaultValue: boolean };

  export type Region = FieldProps & {
    possibleValues: PossibleValueAsIso[];
    defaultValue?: PossibleValueAsIso;
  };

  export type InternalTradingStatus = {
    visible: boolean;
    editable: boolean;
    possibleValues: PossibleValueAsString[];
  };
}

const remapKeys = (fields: LocationSchemas.BasicFields) => {
  return Object.entries(fields).reduce((base, currentValue) => {
    const [key, value] = currentValue;

    if (key.includes(".")) {
      const [firstHalf, secondHalf] = key.split(".");

      base[firstHalf] = { ...base[firstHalf], [secondHalf]: value };
    } else {
      base[key] = value;
    }

    return base;
  }, {});
};

const data: LocationSchemas.BasicFields = {
    name: {
        visible: true,
        editable: true,
    },
    types: {
        visible: true,
        editable: true,
        possibleValues: [
            {
                value: ["Razor"],
            },
            {
                value: ["Deck"],
            },
        ],
    },
    region: {
        visible: true,
        editable: true,
        possibleValues: [
            {
                value: {
                    isoCountryCode: "GB",
                    isoSubdivision: "ENG",
                },
            },
            {
                value: {
                    isoCountryCode: "FR",
                },
            },
        ],
    },
    "alt.number": {
        visible: true,
        editable: true,
    },
    "alt.centreNumber": {
        visible: true,
        editable: true,
    },
    
    "typeDetails.available": {
        visible: true,
        editable: true,
        defaultValue: false,
    },
    "typeDetails.virtual": {
        visible: true,
        editable: true,
        defaultValue: false,
    },
    "internal.name": {
        visible: true,
        editable: true,
    },
    "internal.type": {
        visible: true,
        editable: true,
    },
    "internal.status": {
        visible: true,
        editable: true,
        possibleValues: [
            {
                value: "TRADING",
            },
            {
                value: "UNKNOWN",
            },
        ],
    },
};



const remappedData = remapKeys(data) // I want object with re-mapped keys

(JS) – Error while accessing stomp (socket) in my html page through scripts

Spring Boot WebSocket Example










    
    
    
    Send

<ul></ul>

    var socket = new SockJS('/ws');
    var stompClient = Stomp.over(socket);

    function connectAndSendMessage(message) {
        stompClient.connect({}, function (frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/user/topic/messages', function (message) {
                showMessage(JSON.parse(message.body).content);
            });

            // Send the message after successfully reconnecting
            stompClient.send("/app/chat/send", {}, JSON.stringify(message));
        });
    }
    function sendMessage() {
        var sender = document.getElementById('sender').value;
        var receiver = document.getElementById('receiver').value;
        var content = document.getElementById('content').value;
        var message = {
            sender: sender,
            receiver: receiver,
            content: content
        };

        // Check if stompClient is connected before sending a message
        if (stompClient.connected) {
            stompClient.send("/app/chat/send", {}, JSON.stringify(message));
        } else {
            // If not connected, attempt to connect and send the message
            connectAndSendMessage(message);
        }
    }

    function showMessage(message) {
        var ul = document.getElementById('messages');
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(message));
        ul.appendChild(li);
    }
</script>

Just after launching the project in locally , which is a module for chat, in my frontend, i am receiving an error while inspecting the html page given above.
fyi, i wrote an spring boot application which replica a chat/message section of it.

Error encounting,

GET https://cdn.jsdelivr.net/stomp.js/2.3.3/stomp.min.js net::ERR_ABORTED 404 (Not Found)
localhost/:11
GET http://localhost:8080/stomp.min.js net::ERR_ABORTED 404 (Not Found)

(index):23 Uncaught ReferenceError: Stomp is not defined
at (index):23:27

refereshToken is empty aws-amplify javascript

I use aws-amplify as shown below,

Amplify.configure({
  Auth: {
   
    region: config.aws.region,


    identityPoolRegion: config.aws.region,

    userPoolId: process.env.userPoolId,

    userPoolWebClientId: process.env.appClientId,


    oauth: {
      domain: process.env.domain,
      //  scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'],
      redirectSignIn: `${process.env.redirectSignIn}`,
      redirectSignOut: process.env.redirectSignout,
      responseType: code // NOTE: It was set to 'token' earlier and I used to get accessToken/IDToken back but refreshToken was empty
    }
  }
});

As you can see responseType was set to token and I was able to do microsoft SSO login successfully. I used to get AccessToken/IdToken in redirect URL but refreshtoken as always empty.

I want to generate refershToken to refresh session at later stage.

To get a refreshtoken, I saw I need to change responseType to code as shown above,

How I call to oauth2 endpoint (with responseType = code)

const azureLogin = () => {
    window.location.href = `https://${process.env.domain}/oauth2/authorize?identity_provider=${process.env.identityProviderName}&redirect_uri=${process.env.redirectSignIn}&response_type=${process.env.responseType}&client_id=${process.env.appClientId}&scope=aws.cognito.signin.user.admin+email+openid+phone+profile`;
  };

From my app, whenever I do (SSO) login it does following things,

browser’s URL changes to something :

https://login.microsoftonline.com/62xxx-7x-4xxxf50-axx7-fxxx692/saml2?SAMLRequest=fZJbS8MwF********************

Then it changes to,

http://localhost:3000/auth/redirect?code=bccxxx-exx-4xx-8x-9xxxxxx

I get code but I don’t what should I do with this code. how to use this code to get accessToken, IdToken and refreshToken?

Can someone pls help me with the flow?

PS: I checked AWS-amplify document also but flow is not clear. On top of it, there are no examples available which I can take help from.