Angular SSO not hitting the Login page when clicked

Currently trying to get my Angular app to SSO login with the Duende Identity server that I created. I’m able to hit everything in postman and login and get a token. Now I am trying to get the same results with the Angular app but when I click the login button I get the following error. I’m using the angular-oauth2-oidc package to make this simpler. I have posted the code that I have and cant seem to see why I can hit the login screen of the Identity server.

the correct link is /Account/Login but It never makes it there.

makes it here when I get the error:

http://localhost:5000/home/error?errorId=CfDJ8OrrbCpIWPdCjNyK...

Error
Sorry, there was an error : invalid_request
Request Id: 0HN3B2BKF8VK6:00000001

Errror

sso.config.ts

import { AuthConfig } from 'angular-oauth2-oidc';

  export const authCodeFlowConfig: AuthConfig = {      
  issuer: 'http://localhost:5000',
  clientId: 'nextApp',
  responseType: 'code',
  redirectUri: window.location.origin,
  // dummyClientSecret: 'secret',
  scope: 'openid profile auctionApp',
  strictDiscoveryDocumentValidation: false, 
  skipIssuerCheck: true,
  showDebugInformation: true,
};

HeaderComponent.ts

export class HeaderComponent implements OnInit{


constructor(private router: Router,private oauthService: OAuthService) 
{ 
  this.configureSingleSignOn(); 
}

configureSingleSignOn()
{
  this.oauthService.configure(authCodeFlowConfig);
  this.oauthService.loadDiscoveryDocumentAndTryLogin();     
} 

login() {
  this.oauthService.initImplicitFlow();          
}

HeaderComponent.html

 <li class="nav-item">
    <button class="nav-link" (click)="login()">LogIn</button>
 </li>

Javascript: TypeError: Cannot read properties of undefined (reading ‘startsWith’)

The error shows something to do with router.push(url)

My Submit function looks like this:

 const Submit= async()=>{
        const url = await PaymentMethod({ ...form.getValues(), price})
        router.push(url)
         }

PaymentMethod looks like this:


export const PaymentMethod = async (body) => {
    try{
        await connect()
        const transformedItem=[
        {
            price_data:{
                currency:'usd',
                product_data:{
                    name: body.title
                },
                unit_amount: body.price * 100,
            },
            quantity:1,
        },
    ]

The problem has to do something with the NEXT_PUBLIC_FRONTEND_URL but I’m not sure. The NEXT_PUBLIC_FRONTEND_URL is defined correctly in the .env file.


 const session = await stripe.checkout.sessions.create({
        payment_method_types:['card'],
        line_items:transformedItem,
        mode:'payment',
        success_url:`${process.env.NEXT_PUBLIC_FRONTEND_URL}/success`,
        cancel_url: `${process.env.NEXT_PUBLIC_FRONTEND_URL}/cancel`,
    })


Any suggestions what I’m doing wrong? Thanks!`

porting D3js code to powerbi not working showing blank chart

i am trying to port a D3 code on powerbi but it keeps giving me a blank display without showing any error:

this is my original D3 code tested working on html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Histogram with D3.js</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
  <style>
    /* Add any CSS styles here */
    .bar {
      fill: steelblue;
    }
  </style>
</head>
<body>
  <div id="histogram"></div>

  <script>
    // Load the CSV file
    d3.csv("unemployment-x.csv").then(function(data) {
      // Convert data values to numbers if necessary
      data.forEach(function(d) {
        d.rate = +d.rate; // Assuming "rate" is the column name containing numerical values
      });

      // Set up dimensions for the histogram
      var margin = {top: 20, right: 30, bottom: 30, left: 40},
          width = 960 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;

      // Create SVG element for the histogram
      var svg = d3.select("#histogram")
                  .append("svg")
                  .attr("width", width + margin.left + margin.right)
                  .attr("height", height + margin.top + margin.bottom)
                  .append("g")
                  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      // Create histogram scale
      var x = d3.scaleLinear()
                .domain([0, d3.max(data, function(d) { return d.rate; })])
                .range([0, width]);

      // Generate histogram bins
      var bins = d3.histogram()
                   .value(function(d) { return d.rate; })
                   .domain(x.domain())
                   .thresholds(20) // Adjust the number of bins as needed
                   (data);

      // Create y scale
      var y = d3.scaleLinear()
                .domain([0, d3.max(bins, function(d) { return d.length; })])
                .range([height, 0]);

      // Create bars for the histogram
      svg.selectAll(".bar")
         .data(bins)
         .enter().append("rect")
         .attr("class", "bar")
         .attr("x", 1)
         .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; })
         .attr("width", function(d) { return x(d.x1) - x(d.x0) - 1; })
         .attr("height", function(d) { return height - y(d.length); });

      // Add x axis
      svg.append("g")
         .attr("transform", "translate(0," + height + ")")
         .call(d3.axisBottom(x));

      // Add y axis
      svg.append("g")
         .call(d3.axisLeft(y));
    });
  </script>
</body>
</html>

my data is like this and i am trying to plot an histogram of unemployement rates frequency:

id,state,county,rate
1001,Alabama,Autauga County,5.1
1003,Alabama,Baldwin County,4.9
1005,Alabama,Barbour County,8.6
1007,Alabama,Bibb County,6.2
1009,Alabama,Blount County,5.1

To integrate this code with power bi i had to install D3js extension version 3.5 and had to get rid of the html part:


var margin = {top: 20, right: 30, bottom: 30, left: 40},
    width = pbi.width - margin.left - margin.right,
    height = pbi.height - margin.top - margin.bottom;

// Create SVG element for the histogram
var svg = d3.select("#histogram")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Create histogram scale
var x = d3.scale.linear()
          .range([0, width]);

// Generate histogram bins
var bins = d3.layout.histogram()
             .thresholds(20);

// Create y scale
var y = d3.scale.linear()
          .range([height, 0]);

// Load the CSV file
pbi.csv(type,function(data) {
      x.domain([0, d3.max(data, function(d) { return d.rate; })])
      bins.value(function(d) { return d.rate; })
          .domain(x.domain())
          (data);
           
      y.domain([0, d3.max(bins, function(d) { return d.length; })])

      // Create bars for the histogram
      svg.selectAll(".bar")
         .data(bins)
         .enter().append("rect")
         .attr("class", "bar")
         .attr("x", 1)
         .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; })
         .attr("width", function(d) { return x(d.x1) - x(d.x0) - 1; })
         .attr("height", function(d) { return height - y(d.length); });

      // Add x axis
      svg.append("g")
         .attr("transform", "translate(0," + height + ")")
         .call(d3.svg.axis().scale(x).orient("bottom"));

      // Add y axis
      svg.append("g")
         .call(d3.svg.axis().scale(y).orient("left"));
    });
function type(d) {
  d.rate = +d.rate;
  return d;}

Anyone can help me on this ? or suggest a better way for debugging?

BigCartel – Making sidebar & announcement scroll with page in ‘Sidecar Theme’

I’m trying to make the sidebar and the announcement text scroll along with the rest of the page. Currently as you start the scroll, they are left behind. I would like them to still be visible even if you’ve scrolled to the bottom of the page.

I appreciate any help you guys can provide!

https://github.com/bigcartel-themes/sidecar

I’m quite inexperienced with this, so I wouldn’t know where to start.

After npx expo prebuild, npx expo run:android wont work

I just installed a fresh react native app using
npx create-expo-app --template tabs
Then I proceeded with the following command
npx expo prebuild
Which ran and completed successfully. So I’m trying to run my app on my android emulator using the command npx expo run:android but I get an error I don’t understand as shown on the image below.
The error I get when try to run my app

package.json

{
  "name": "fin",
  "main": "expo-router/entry",
  "version": "1.0.0",
  "scripts": {
    "start": "expo start",
    "android": "expo run:android",
    "ios": "expo run:ios",
    "web": "expo start --web",
    "test": "jest --watchAll"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/vector-icons": "^14.0.0",
    "@react-navigation/native": "^6.0.2",
    "expo": "~50.0.17",
    "expo-font": "~11.10.3",
    "expo-linking": "~6.2.2",
    "expo-router": "~3.4.10",
    "expo-splash-screen": "~0.26.5",
    "expo-status-bar": "~1.11.1",
    "expo-system-ui": "~2.9.4",
    "expo-web-browser": "~12.8.2",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.73.6",
    "react-native-safe-area-context": "4.8.2",
    "react-native-screens": "~3.29.0",
    "react-native-web": "~0.19.6"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@types/react": "~18.2.45",
    "jest": "^29.2.1",
    "jest-expo": "~50.0.4",
    "react-test-renderer": "18.2.0",
    "typescript": "^5.1.3"
  },
  "private": true
}

app.json

{
  "expo": {
    "name": "fin",
    "slug": "fin",
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/images/icon.png",
    "scheme": "fin",
    "userInterfaceStyle": "automatic",
    "splash": {
      "image": "./assets/images/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "ios": {
      "supportsTablet": true
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/images/adaptive-icon.png",
        "backgroundColor": "#ffffff"
      },
      "package": "com.jbac76.fin"
    },
    "web": {
      "bundler": "metro",
      "output": "static",
      "favicon": "./assets/images/favicon.png"
    },
    "plugins": [
      "expo-router"
    ],
    "experiments": {
      "typedRoutes": true
    }
  }
}

tsconfig.json

{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {
    "strict": true,
    "paths": {
      "@/*": [
        "./*"
      ]
    }
  },
  "include": [
    "**/*.ts",
    "**/*.tsx",
    ".expo/types/**/*.ts",
    "expo-env.d.ts"
  ]
}

I hope the information I have provided is enough. I have googled this issue for hours with no success, This is my last hope so I appreciate in advance.

Tried to reinstall my android studio and emulator.
Tried to reinstall node js.
Tried to reinstall jdk.
Tried to re-create the project.
Tried to clear cache.

All in all I’m relatively new to this so i wasn’t sure what to try other than googling for solutions.
By the way, I was following a youtube tutorial by Simon building a Fintech clone with react-native.

I am getting an error: SyntaxError: missing: after property id 1: at line 2 [closed]

var oList = {
  "NO EXCEPTIONS TAKEN:" - 1,
  "MAKE CORRECTIONS NOTED:" - 1,
  "REVISE AND          RESUBMIT:" - 1,
  "REJECTED:" - 1
};
var dlg = initialize: {
    function(dialog)
  } {
    dialog.load({
      lst1: oList
    });
  },
  commit: function(dialog)
} {
  this.oSelect = dialog.store().lst1;
}, description: {
  name: “Review Action”,
  elements: [{
    type: “view”,
    elements: [{
        type: “static_text”,
        item_id: “stat”,
        name: “Select an Item”
      },
      {
        type: “popup”,
        item_id: “lst1”,
        char_width: 6
      },
      {
        type: “ok”
      }
    ]
  }]
}
`
    };

This is for an Adobe stamp to have the user choose a response that is added to the stamp. I’ve tried various ways to notate the var dlg = initialize: {function(dialog)} but nothing is working. I suspect I have other formatting errors as well.

Formatting Input Field onChange While Retaining Value

I am trying to format the value of an input field onChange. I am wanting to add a space after every 4th character (i.e. a credit card number). It is currently clearing the text field after the 5th character (which is technically the space).

This is what I have done and how to reproduce the above.

const [creditCardNumber, setCreditCardNumber] = useState<string>('');
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {

   let creditNum = e.target.value;
   let creditNumSpaced = creditNum.match(/.{1,4}/g);
   setCreditCardNumber(creditNumSpaced?.join(' ') ?? '');
};


<Input type='number' onChange={e => handleChange(e)} value={creditCardNumber}

How to include multiple script sources?

I have an issue that regars having multiple javascript srcs in one HTML file.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Match</title>
    <link rel="stylesheet" type="text/css" href="stylesMatch.css" />
    <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
            background-color: #eaf6f6;
        }
    </style>
    
</head>
<body>
    <h1 id="myH1">Match</h1>

    <div id="container">
        <div id="stopWatch">
            00:00
        </div>
        <div id="controls">
            <button id="startBtn" onclick="start()">Start</button>
            <button id="stopBtn" onclick="stop()">Stop</button>
        </div>
    </div>
    
    <div id="container2">
        <div id="countdown">
            30
        </div>
        <div id="controlsThirty">
            <button id="startBtnThirty" onclick="startThirty()">Start</button>
            <button id="resetBtnThirty" onclick="resetThirty()">Reset</button>
        </div>
    </div>
    <script src="thirtySeconds.js"></script>
    <script src="stopwatch.js"></script>
</body>

First javascript code:

const display = document.getElementById("countdown");
let countdownTimer = null;
let timeLeft = 30;

function startThirty() {
    if (!countdownTimer) {
        countdownTimer = setInterval(updateCountdown, 1000);
    }
}

function resetThirty() {
    clearInterval(countdownTimer);
    countdownTimer = null;
    timeLeft = 30;
    display.textContent = formatTime(timeLeft);
}

function updateCountdown() {
    timeLeft--;
    display.textContent = formatTime(timeLeft);

    if (timeLeft === 0) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }
}

function formatTime(seconds) {
    const remainingSeconds = seconds % 60;
    return `${String(remainingSeconds).padStart(2, "0")}`;
}

Second javascript code:

const display = document.getElementById("stopWatch");
let timer = null;
let startTime = 0;
let elapsedTime = 0;
let isRunning = false;

function start(){
    if(!isRunning){
        startTime = Date.now() - elapsedTime;
        timer = setInterval(update, 10);
        isRunning = true;
    }
}

function stop(){
    if(isRunning){
        clearInterval(timer);
        elapsedTime = Date.now() - startTime;
        isRunning = false;
    }
}

function update(){
    
    const currentTime = Date.now();
    elapsedTime = currentTime - startTime;

    let minutes = Math.floor(elapsedTime / (1000 * 60) % 60);
    let seconds = Math.floor(elapsedTime / 1000 % 60);

    minutes = String(minutes).padStart(2, "0");
    seconds = String(seconds).padStart(2, "0");

    display.textContent = `${minutes}:${seconds}`;
}

CSS in case anyone is wondering:

#myH1{
    text-align: center;
    font-size: 4rem;
    font-family: "Arial", sans-serif;
    color: hsl(0, 0%, 25%);
}
#container{
    margin-left: 700px;
    margin-right: 700px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 30px;
    border: 5px solid;
    border-radius: 50px;
    background-color: white;
}

#container2{
    margin-top: 50px;
    margin-left: 1000px;
    margin-right: 1000px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    border: 4px solid;
    border-radius: 30px;
    background-color: white;
}


#stopWatch{
    font-size: 5rem;
    font-family: monospace;
    font-weight: bold;
    color: hsl(0, 0%, 30%);
    text-shadow: 2px 2px 2px hsla(0, 0%, 0%, 0.75);
    margin-bottom: 25px;
}

#countdown{
    font-size: 5rem;
    font-family: monospace;
    font-weight: bold;
    color: hsl(0, 0%, 30%);
    text-shadow: 2px 2px 2px hsla(0, 0%, 0%, 0.75);
    margin-bottom: 25px;
}
#controls button{
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
    margin: 5px;
    min-width: 125px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    color: white;
    transition: background-color 0.5s ease;
}

#controlsThirty button{
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
    margin: 5px;
    min-width: 125px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    color: white;
    transition: background-color 0.5s ease;
}

#startBtn{
    background-color: hsl(115, 100%, 40%);
}
#startBtn:hover{
    background-color: hsl(115, 100%, 30%);
}

#startBtnThirty{
    background-color: hsl(166, 100%, 40%);
}
#startBtnThirty:hover{
    background-color: hsl(166, 100%, 30%);
}
#stopBtn{
    background-color: hsl(10, 90%, 50%);
}
#stopBtn:hover{
    background-color: hsl(10, 90%, 40%);
}
#resetBtnThirty{
    background-color: hsl(205, 90%, 60%);
}
#resetBtnThirty:hover{
    background-color: hsl(205, 90%, 50%);
}

The issue is that when I include both javascript files with the tag only the first one works (in this case only functions from thirtySeconds.js work), when I swap them the other one doesn’t work. Does anyone know what should I do?

I looked all over the internet, youtube – tried stuff like defer, type=”module” but nothing seemed to work.

Can’t read value of POST

I can’t get the values from a simple form. It has 2 files: APP.js and FORM.ejs. I am trying to receive the values from the form.

APP.js:

const http = require('http');
const express = require("express");
const S1_APP = express();
const ejs = require("ejs"); 
const bodyParser = require("body-parser"); 
S1_APP.use(bodyParser.urlencoded({ extended: false }));
S1_APP.set('view engine', 'ejs');//template engine

S1_APP.get("", function (req, res) {
    res.render('FORM.ejs');  
});

S1_APP.post("/",function(req, res) {

// here I need to read the value (myvalue 1 or 2) 
// that is send via the form in FORM.ejs
// I have tried req.body, that is empty
// I have tried req.value, that is undefined

});
S1_APP.listen(8080, function (err) {
    if (err) console.log(err);
    console.log("Server listening on PORT 8080");
});

FORM.ejs:

<html lang="en" >
<head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"></head>

<body>
    <form method="POST" action="/">
        <button type="submit" value="myvalue1"  >POST 1</button>
        <button type="submit" value="myvalue2"  >POST 2</button>
    </form>
</body>
</html>

How use node js and write backend in nuxt 3?

How use node js and write backend in nuxt 3?
How use node js and write backend in nuxt 3?
How use node js and write backend in nuxt 3?
How use node js and write backend in nuxt 3?
How use node js and write backend in nuxt 3?
How use node js and write backend in nuxt 3?
How use node js and write backend in nuxt 3?
How use node js and write backend in nuxt 3?
answers answers answers

how can I improve webRTC signaling service code?

I am learning webRTC and tried to implement signaling service through websockets. I am still a beginner in backend development so not sure how correct my code is. Can you please review it and let me know the mistakes and how can I make scale it for multiple users using the service in real-time?

server code

const express = require('express');
const app = express();
const http = require('http');
const path = require('path');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

const fs = require("fs");

console.log(path.join(__dirname, "../public"));

// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, "../client")));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../client/client1.html'));
});

var users = 0;
var roomCount = 1;

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.join("room" + roomCount);
  users++;

  if (users == 1) {
    users++;
    io.to(Array.from(socket.rooms)[1]).emit("becomeClient1");
  } else {
    users = 0;
    roomCount++; // assuming roomCount won't overflow
    socket.emit("becomeClient2");
    io.to(Array.from(socket.rooms)[1]).emit("notifyClient1");
  }

  socket.on("client1offer", (client1offer) => {
    console.log("cl1 offer--------" + JSON.stringify(client1offer));
    socket.broadcast.to(Array.from(socket.rooms)[1]).emit("client1offer", client1offer);
  });

  socket.on("client1IceCandidates", (client1iceCandidate) => {
    console.log("ice--------" + client1iceCandidate);
    socket.broadcast.to(Array.from(socket.rooms)[1]).emit("client1IceCandidates", client1iceCandidate);
  });

  socket.on("client2answer", answer => {
    console.log("cl2 answer emit");
    socket.broadcast.to(Array.from(socket.rooms)[1]).emit("client2answer", answer);
  });

  socket.on("disconnect", () => {
    console.log("----socket close----------");
  });
});

server.listen(8082, () => {
  console.log('listening on *:8082');
});

user end code for video calling feature

let localStream;
let remoteStream;

const servers = [{
  urls: [
    "stun.l.google.com:19302",
    "stun1.l.google.com:19302",
    "stun2.l.google.com:19302"
  ]
}];

const lc = new RTCPeerConnection(servers);
const dc = lc.createDataChannel("channel");
const rc = new RTCPeerConnection(servers);

async function init() {
  try {
    localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    document.getElementById("user-1").srcObject = localStream;

    console.log("Local stream obtained successfully.");
  } catch (error) {
    console.error("Error accessing local media stream:", error);
  }
}

init().then(() => {
  console.log("--------------->>>>>>>>>>>>>>>>>>>>>>>>>>");
  var socket = io();
  socket.on("connect", () => {
    console.log("WebSocket connected");

    rc.addEventListener("track", e => {
      console.log("Track received:", e.track);
      if (e.streams && e.streams[0]) {
        document.getElementById("user-2").srcObject = e.streams[0];
      }
    });

    lc.addEventListener("track", e => {
      console.log("Track received from remote:", e.track);
      if (e.streams && e.streams[0]) {
        document.getElementById("user-2").srcObject = e.streams[0];
      }
    });

    localStream.getTracks().forEach(track => {
      lc.addTrack(track, localStream);
      console.log("Tracks added to lc.");
    });

    localStream.getTracks().forEach(track => {
      rc.addTrack(track, localStream);
      console.log("Tracks added to rc.");
    });
  });

  socket.on("error", (error) => {
    console.error("WebSocket error:", error);
  });

  socket.on("becomeClient1", () => {
    console.log("Received becomeClient1 event");

    socket.on("notifyClient1", () => {
      console.log("Client 2 joined.");

      try {
        dc.onmessage = e => console.log("Received message: " + e.data);
        dc.onopen = e => {
          console.log("Data channel connection opened.");
          dc.send("heyyyyyy");
          socket.disconnect();
        };

        lc.createOffer().then(o => {
          lc.setLocalDescription(o);
          console.log("Local description set successfully." + JSON.stringify(o));
          socket.emit("client1offer", o);
        });

        lc.onicecandidate = event => {
          console.log("New ICE candidate. " + JSON.stringify(event));
          if (event.candidate) {
            socket.emit("client1IceCandidates", event.candidate);
          }
        };
      } catch (error) {
        console.error("Error setting up client 1:", error);
      }
    });

    socket.on("client2answer", answer => {
      lc.setRemoteDescription(answer).then(() => {
        console.log("remote description for cl1 set");
      });
    });
  });

  socket.on("becomeClient2", () => {
    console.log("Received becomeClient2 event");

    try {
      rc.onicecandidate = e => {
        console.log("New ICE candidate.");
      };

      rc.ondatachannel = e => {
        rc.dc = e.channel;
        rc.dc.onmessage = e => {
          console.log("Received message from client 1: " + e.data);
          rc.dc.send("supp");
        };
        rc.dc.onopen = e => {
          console.log("Data channel connection opened.");
        };
        socket.close();
      };

      socket.on("client1offer", offer => {
        console.log("-------------<<>>>>>>");
        rc.setRemoteDescription(offer).then(() => {
          console.log("cl1 offer set");
          rc.createAnswer().then(answer => {
            rc.setLocalDescription(answer);
            socket.emit("client2answer", answer);
          }).then(() => {
            console.log("Local description for cl2 set.");
          });
        });
      });

      socket.on("client1IceCandidates", client1IceCandidate => {
        console.log("cl1 ice ---> " + client1IceCandidate);
        rc.addIceCandidate(client1IceCandidate);
      });
    } catch (error) {
      console.error("Error setting up client 2:", error);
    }
  });
});


I opened several tabs in my browser and its working properly but not sure how reliable the app will be if deployed.

prepopulate input with ajax – TypeError: ‘stepUp’ called on an object that does not implement interface HTMLInputElement

Trying to prepopulate the runtime hours input on a modal form from the latest value in the db using ajax on a bootstrap page. When I try to fill it in, I get the error: TypeError: ‘stepUp’ called on an object that does not implement interface HTMLInputElement.

the PHP code to generate json

<?php
include('db.php');
include('function.php');
//error_reporting(E_ALL); 
//ini_set('display_errors', 1);
$compressor_hours = '';
//get the last read runtime hours of each compressor
$compressor_hours .= "SELECT MAX(r.id),
MAX(CASE c.compressor_name WHEN 'CM101' THEN c_r.runtime_hours END) AS runtime_hours1, 
MAX(CASE c.compressor_name WHEN 'CM201' THEN c_r.runtime_hours END) AS runtime_hours2, 
MAX(CASE c.compressor_name WHEN 'CM301' THEN c_r.runtime_hours END) AS runtime_hours3
FROM plant_readings r 
LEFT JOIN compressor_readings c_r ON c_r.plant_readings_id = r.id
LEFT JOIN compressors c ON c_r.compressor_id = c.id;";
//return one row of plant_readings_id | runtime_hours1 | runtime_hours2 | runtime_hours3
 
$statement = $connection->prepare($compressor_hours);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();

foreach($result as $row)
{
    $sub_array = array();
    $sub_array[] = $row["runtime_hours1"];  
    $sub_array[] = $row["runtime_hours2"];  
    $sub_array[] = $row["runtime_hours3"];  

     $data[] = $sub_array;
}
$output = array(
    "data" => $data
);
echo json_encode($output);
?>

Then the modal JS

$(document).ready(function(){
    $('#add_button').click(function(){
        $('#plant_readings_form')[0].reset();
        $('.modal-title').text("Add New Readings");
        $('#action').val("Add");
        $('#operation').val("Add");

        $.ajax({
            url:"fetch_prefill_data.php",
            method:"POST",
            data:{runtime_hours1: runtime_hours1,
                runtime_hours2: runtime_hours2,
                runtime_hours3: runtime_hours3},
            dataType:"json",
            success:function(data)
            {
                var runtime_hours1 = $('#runtime_hours1').val();
                var runtime_hours2 = $('#runtime_hours2').val();
                var runtime_hours3 = $('#runtime_hours3').val();
                runtime_hours1.val()=data.runtime_hours1;
                runtime_hours2.val()=data.runtime_hours2;
                runtime_hours3.val()=data.runtime_hours3;
            }
        })
    });

Any ideas what I’m doing wrong? The input field, whose name & id correspond does not get prefilled & throws the error.

burger menu pushing items to the bottom

My burger menu always makes some problems and when I try to include it into any page the items on the page get pushed to the bottom. I tried it fixing it with position absolute but it didnt really work out either. I just want my elements to be on the right side of the burger menu and also float left didnt really looked good either.

Here is my code of the burger menu in html


<body> 
<div id=alles>
    
<div class=schale> 
    <div class=burger>
    
        <div class=bar>
        </div>
    </div>
</div>
    <div class=seitenbar>
     <form>
         <div class=buttoncontainer>
            <div class=buttonbox>
                <i class="fa-regular fa-house"></i>  <input class=buttons formaction=homepage.php type=submit value=Home>  
            </div>    
            <div class=buttonbox>
                <br> <i class="fa-regular fa-key"></i> <input class=buttons formaction=register.php type=submit value=Registrierung>
            </div>
            <div class=buttonbox>
                <br>  <i class="fa-regular fa-clipboard-user"></i>  <input class=buttons formaction=login.php type=submit value=Login>
            </div>
        </div>   
     </form>
    </div>
     
</div>
</body>

and the css code of the burger menu

*{
   margin: 0;
    
}
.buttoncontainer{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    padding-left: 0.5vw;
    padding-right: 0.5vw;
}


.buttons{
    margin-top: 5vh;
    margin-bottom: 1vh;
    height: auto;   
    width: auto;
    border-radius: 5%;
    transition: 0.3s;
   border-radius: 1vh;
}

.buttons:hover{
    transition: all 0.3s;
   color:cadetblue;
   background-color: #1c1c21;
}
.schale{
    
    position: relative;
    display:flex;   
    width: 10vw;
    min-height: 6vh;
    
    background-color: #1c1c21;
    z-index: 0;
}

.burger {
    position: relative;
    min-height: 2vh;
    width: auto;
    border-color: red;
    padding-top: 0.5vw;
    margin-top: 0.5vw;
    margin-left: 1vw;    
    /* transition:all .5s ease-in-out; */
    z-index: 0;
}

.bar{
    min-height: 0.5vh;
    min-width:1vw;
    background-color: cadetblue;
    border-radius: 5%;
    transition: all  0.5s ease-in-out;
    border-color: brown;
    z-index: 0;
}

.bar::before, .bar::after{
    content: "";
    position: absolute;
    min-height: 0.5vh;
    min-width: 1vw;
    background-color: cadetblue;
    border-radius: 5%;
    transition: all 0.5s ease-in-out;
}

.bar::before{
    transform: translateY(-1vh);
}

.bar::after{
    transform: translateY(1vh);
}

.burger.offen .bar{
    transform: translateX(-1.5vw);
    background-color:transparent;
    background-color:   transparent;
}

.burger.offen .bar::before{
transform: rotate(45deg) translate(1vw, -2vh);
}

.burger.offen .bar::after{
    transform: rotate(-45deg) translate(1vw, 2vh);
}

.seitenbar{
    position: relative;
    display: flex;
    justify-content: left;
    align-content: center; 
    width:  10vw;
    left:   -21vw;
    height: 94.91vh;
    background-color: #1c1c21;
    transition: all 0.5s ease-in-out;
    z-index: 2;
    
}

.fa-house{
 color:cadetblue;
}
.fa-key{
    color:cadetblue;
}

.fa-clipboard-user{
    
    color:cadetblue;
}


and the javascript part of the menu

const burgerr = document.querySelector(".burger");
var seitenbar = document.querySelector(".seitenbar");
let öffnen = false;
burgerr.addEventListener("click", () =>{

    if (öffnen == false) {
        burgerr.classList.add("offen");
        öffnen = true;
       seitenbar.style.left= "0px";
        
    }
   else {
        burgerr.classList.remove("offen");
        öffnen = false;
        seitenbar.style.left="-21vw"
    }
    // if (öffnen==true) {
    //     alert("test")
    // }
}

);


and here is my html code of the page that I want to have the burger included

<body>
    <?php
    include "menu.php"    ?>

<link rel=stylesheet href=dashboard.css>

<div id=alles>


    <div id=boxen> 
        <div id=veranstaltungen class=elemente>
            Veranstaltungen
            <!-- Alle Veranstaltungen anzeigen können
            Anzeige, welche Veranstaltungen im Studiengang noch fehlen
            Anzeige, welche Veranstaltungen im Studiengang noch fehlen -->
        </div>
        <div id=veranstaltungen_fertig class=elemente>
        abeschlossene veranstaltungen
        </div>
        <div id=studiengang class=elemente>
        Studiengang
        <!-- Die Noten der Studenten anzeigen lassen, in der Form, dass zu jedem Studiengang jedes Modul angezeigt wird -->
        </div>
    </div>


    
</div>

</body>

and the css code of the page


#boxen{
    display:grid;
    border-style: solid;
    border-width: 1vw;
    border-color:black;
    grid-template-columns: auto;
    grid-template-rows: 1vw, 1vw, 1vw;
    justify-content: center;
}

.elemente{
    border-style: solid;
    border-width:5vw;
    border-color:cornflowerblue;
}

Does anybody know how to fix this problem?

(sorry if this post is bad its my first post)

I already tried it with float:left; but it didnt work and position absolute also didnt really workout

Koa.js Redirect Not Working as Expected – Returns “Not Found”

I’m new to Koa.js, and I’m trying to create a simple authentication flow with Spotify. Here’s my code:

import koa from "koa";
import querystring from "node:querystring";

const port = 54832;
const client_id = "myClientID";
const redirect_uri = `http://localhost:${port}/callback`;
const scope = "user-read-currently-playing";

export default function requestAuth() {
    const server = new koa();
    let response = {};

    server.use(async (ctx) => {
        const { url, method } = ctx.request;

        if (method === "GET" && url === "/login") {
            ctx.body = "You will be redirected to Spotify auth page";

            ctx.redirect(
                "https://accounts.spotify.com/authorize?" +
                    querystring.stringify({
                        response_type: "code",
                        client_id: client_id,
                        scope: scope,
                        redirect_uri: redirect_uri,
                    })
            );
        } else if (method === "GET" && url.includes("/callback")) {
            if (!ctx.request.query.error) {
                response.code = ctx.request.query.code;
            } else {
                console.log(ctx.request.query.error);
            }
        }
    });

    server.listen(port);

    return response;
}

I want to redirect users to the Spotify login page when they visit the /login URL. However, instead of redirecting to Spotify, I am being redirected to the URL http://localhost:54832/response_type=code&client_id=myClientID&redirect_uri=http%3A%2F%2Flocalhost%3A54832&scope=user-read-currently-playing and getting a “Not Found” output in the response body.

Am I doing something wrong with the way I’m handling the redirect? Could it be an issue with my server setup or with the way Koa.js handles redirects? Any suggestions on how to troubleshoot or fix this?

A little earlier I had the same problem with Express JS. As I understood then, the problem was caching, which is difficult to disable in this framework. This is exactly why I switched to Koa JS. But since the problem persists in this case too, I am completely confused

when new comment added database javascript must send notification [duplicate]

hello everyone im trying to when new comment added to the database , javascript will send notification and here is my code for ajax.php

    <?php

require_once "config.php";


$id = $_GET['id'];
$q = $_GET['q'];


$totalComments = 0;
$count = $db->count('comments', [
    "id[<]" => $id,
    'OR' => [
        "name[~]" => $q,
        "comment[~]" => $q,
    ],
]);
$totalComments += $count;

// Check if there are new comments
if ($totalComments!== $count) {
    
    // Instead, return a flag to indicate new comments
    $newComments = true;
} else {
    $newComments = false;
}

$result = getComment2($db, $id, $q?? '');


echo json_encode([
    "count" => $count,
    "data" => $count > 0? array_values($result) : null,
    "newComments" => $newComments, // Add a flag to indicate new comments
]);

and also here its my notification.js file

window.addEventListener('load', () => {
    if (!window.Notification) return;
  
    Notification.requestPermission().then(permission => {
      if (permission === 'granted') {
        // Listen for new comments flag from PHP script
        document.addEventListener('ajaxComplete', event => {
          const xhr = event.detail.xhr;
          const response = JSON.parse(xhr.responseText);
          if (response.newComments) {
            sendNotification();
          }
        });
      }
    });
  });
  
  const sendNotification = () => {
    let notification = new Notification('Yeni yorum', {
      body: 'Yeni yorum yapıldı. ',
      icon: '#icon yolu',
      title: 'Çiçek sepeti yorum'
    });
  };

when i try add new comment, nothing happens can someone help me ?