Javascript canvas only works on Chrome, not Firefox

I can see that the canvas is there from dev tools and a outline goes around the canvas just fine.
I don’t get any errors from the console.

Firefox Version: 128.0.2 (64-bit)
I’m running Pop-os.

const canvas = document.getElementById("canvas")

const ctx = canvas.getContext("2d")

ctx.fillStyle = "red"
ctx.fillRect(30, 30, canvas.width, canvas.height)
<canvas id="canvas" width="300" height="300"></canvas>

The canvas should be completely filled with red, which it is on chrome.

Test Angular Input

I want an Angular test that mocks keydown of keys 1 and 2 and then assert that the value of the input is 12

My html:

<input
  id="myInput"
/>

My test:

fit('should update input value on key press', () => {
    const inputDebugElement = fixture.debugElement.query(
      By.css('#money-input')
    );
    const inputElement = inputDebugElement.nativeElement as HTMLInputElement;

    inputElement.value = '';
    inputElement.dispatchEvent(new Event('input'));

    const event1 = new KeyboardEvent('keydown', { key: '1' });
    const event2 = new KeyboardEvent('keydown', { key: '2' });

    inputElement.dispatchEvent(event1);
    inputElement.dispatchEvent(event2);

    fixture.detectChanges();

    expect(inputElement.value).toBe('12');
  });

The current result of my test:
the current result of my test

How can solve “Type ‘{}’ is not assignable to type ‘string'” problem

this my index.tsx file:

import React from "react";
import UserInput from "./userInput";

import {
  View,
  StatusBar,
} from 'react-native';


const App = ( ) => {
  return (
    <View>
      <StatusBar hidden/>
      <UserInput/>
    </View>
  );
};


export default App;

and this my userInput file:


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

const UserInput = ( text: string ) => {
  return (
    <View>
      <Text>
        { text }
      </Text>
    </View>
  );
};

export default UserInput;

my problem on index.tsx file on tag
this tag i made it has 1 param. I cant give a value to it.

I google it but i cant find any answer.

How can my Flask application push Websocket Messages to an asynchronous HTML page?

I’m having a few issues with a Flask application using socketIO.

I have an external device on IP 10.0.0.144 sending websocket messages to my application on 10.0.0.218:8089. I can see the incoming websocket messages in the PyCharm console.

10.0.0.144 - - [31/Jul/2024 11:21:43] code 400, message Bad request syntax ('{"ts":1722439304,"dio":{"dio1":{"in":true},"dio2":{"in":true},"dio3":{"label":"Link","in":true},"dio4":{"in":true}},"ain":{"ain1":{"voltage":12},"ain2":{"voltage":2},"ain3":{"voltage":10},"ain4":{"voltage":0}}}') 

10.0.0.144 - - [31/Jul/2024 11:21:43] "{"ts":1722439304,"dio":{"dio1":{"in":true},"dio2":{"in":true},"dio3":{"label":"Link","in":true},"dio4":{"in":true}},"ain":{"ain1":{"voltage":12},"ain2":{"voltage":2},"ain3":{"voltage":10},"ain4":{"voltage":0}}}" HTTPStatus.BAD_REQUEST

Additionally I’m trying to push these messages to an asynchronous HTML page, but the messages aren’t being pushed across from what I can see.

Flask code:

I wanted this to process the incoming messages and then push them to an asynchronous HTML page. The messages are being processed, and I have them stored in a list object. I’m really only concerned with messages originating from 10.0.0.144.

I’m honestly not even sure if this is the best approach from a project standpoint, but I’ve never done anything this advanced before.


from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)

thread = Thread()
thread_stop_event = Event()

messages = []

def get_values():
    while True:
        message = socketio.on(1024)
        while not thread_stop_event.is_set():
            messages.append(message)
            # Send the message to all connected clients
            socketio.emit('new_message', {'message': message})
            print(message)
            socketio.sleep(2)



@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the function to emit msgs thread only if the thread has not been started before.
    if not thread.is_alive():
        print("Starting Thread")
        thread = socketio.start_background_task(get_values)

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


# Start the Flask app with SocketIO
socketio.run(app, host='10.0.0.218', port=8089, allow_unsafe_werkzeug=True)

JS code:

$(document).ready(function(){
    //connect to the socket server.
    var socket = io.connect('http://10.0.0.218' + document.domain + ':' + location.port + '/test')
    var messages_received = [];

    //receive details from server
    socket.on('new_message', function(msg) {
        console.log("Received msg" + msg.number);
        //maintain a list of ten msgs
        if (messages_received.length >= 10){
            messages_received.shift()
        }
        messages_received.push(msg.number);
        messages_string = '';
        for (var i = 0; i < messages_received.length; i++){
            messages_string = messages_string + '<p>' + messages_received[i].toString() + '</p>';
        }
        $('#log').html(messages_string);
    });

});

Here’s a sample of the output console:

`* Running on http://10.0.0.218:8089
Press CTRL+C to quit

* Restarting with stat
  Server initialized for threading.
  Werkzeug appears to be used in a production deployment. Consider switching to a production web server instead.

* Debugger is active!

* Debugger PIN: 123-630-169
  RMoYImBp0_FvWs_lAAAA: Sending packet OPEN data {'sid': 'RMoYImBp0_FvWs_lAAAA', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
  10.0.0.218 - - [31/Jul/2024 11:54:54] "GET /socket.io/?EIO=4&transport=polling&t=P49W5nO HTTP/1.1" 200 -
  RMoYImBp0_FvWs_lAAAA: Received packet MESSAGE data 0/test,
  RMoYImBp0_FvWs_lAAAA: Received request to upgrade to websocket
  emitting event "new_message" to all [/]
  RMoYImBp0_FvWs_lAAAA: Sending packet MESSAGE data 0/test,{"sid":"Fzb-QYWF3SFFBr4EAAAB"}
  10.0.0.218 - - [31/Jul/2024 11:54:54] "POST /socket.io/?EIO=4&transport=polling&t=P49W64r&sid=RMoYImBp0_FvWs_lAAAA HTTP/1.1" 200 -
  10.0.0.218 - - [31/Jul/2024 11:54:54] "GET /socket.io/?EIO=4&transport=polling&t=P49W64s&sid=RMoYImBp0_FvWs_lAAAA HTTP/1.1" 200 -
  RMoYImBp0_FvWs_lAAAA: Upgrade to websocket successful
  Client connected
  Starting Thread
  emitting event "new_message" to all [/]
  emitting event "new_message" to all [/]
  10.0.0.144 - - [31/Jul/2024 11:54:59] code 400, message Bad request syntax ('{"ts":1722441301,"dio":{"dio1":{"in":true},"dio2":{"in":true},"dio3":{"label":"Link","in":true},"dio4":{"in":true}},"ain":{"ain1":{"voltage":12},"ain2":{"voltage":2},"ain3":{"voltage":10},"ain4":{"voltage":0}}}')
  10.0.0.144 - - [31/Jul/2024 11:54:59] "{"ts":1722441301,"dio":{"dio1":{"in":true},"dio2":{"in":true},"dio3":{"label":"Link","in":true},"dio4":{"in":true}},"ain":{"ain1":{"voltage":12},"ain2":{"voltage":2},"ain3":{"voltage":10},"ain4":{"voltage":0}}}" HTTPStatus.BAD_REQUEST -
  emitting event "new_message" to all [/]
  emitting event "new_message" to all [/]
  emitting event "new_message" to all [/]
  10.0.0.218 - - [31/Jul/2024 11:55:05] "GET /socket.io/?EIO=4&transport=websocket&sid=RMoYImBp0_FvWs_lAAAA HTTP/1.1" 200 -
  10.0.0.218 - - [31/Jul/2024 11:55:05] "GET / HTTP/1.1" 200 -
  Client disconnected
  10.0.0.218 - - [31/Jul/2024 11:55:05] "GET /static/application.js HTTP/1.1" 304 -`

HTML page:

<!DOCTYPE html>
<html>
<head>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.min.js"></script>
    <script src="static/application.js"></script>

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
  <div class="jumbotron">
    <h2>Asynchronous Flask Communication</h2>
    <p>Websocket Messages from field devices.</p>
  </div>
</div>

</div>

<div class="container" id="content">
    <div class="row">
        <p>Asynchronous page updates will appear here:</p>
        <h3>messages:</h3>
        <div id="log">
        </div> <!-- /#log -->
    </div>
</div>


</body>
</html>

New Tab in Html

I’m making a website that takes input (text) from a user, finds specific words in the text, and returns the full text with the words highlighted. Although I want to display the result in a new tab, the best thing I can do is a pop-up on Google Chrome.

When I tried using the “_blank” attribute that opens a new tab, I can’t write to that tab using “innerHTML.” Any ideas or advice will be greatly appreciated.

tags after {children} being duplicated in react app

i have a layout

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <PageHeader />
        <main className="flex flex-col items-center justify-between pt-24">
          {children}
        </main>
        <PageFooter />
      </body>
    </html>
  );
}

and a page using that

export default function Home() {
  return (
    <RootLayout>
      <ImageCarousel />
      <About />
      <PortfolioSection />
      <TestimonialSection />
      <NewBlogSection />
      <ContactFormSection />
    </RootLayout>
  );

but when the page loads everything after the {children} is duplicated an there is the run time error Error: Hydration failed because the initial UI does not match what was rendered on the server.
which looking into doesn’t seem to help all that much

regardless of what is passed as a child in as children into the rootlayout it happends

Error loading model on website served through GitHub pages: SyntaxError: Unexpected token ‘v’… (threejs)

so I’m fairly new to coding, GitHub pages all of it. I am trying to serve my website over there which includes three 3d models (their files being larger than 100mb) which I have added to the git repository using git lfs. I was successfully able to set up my repository but my models won’t load and despite everything I’ve tried, I end up with this error message:

SyntaxError: Unexpected token 'v', "version ht"... is not valid JSON
    at JSON.parse (<anonymous>)
    at GLTFLoader.parse (GLTFLoader.js:350:17)
    at Object.onLoad (GLTFLoader.js:245:11)
    at three.module.js:44214:38

Everything worked while I was building the site and serving it on my local server, but trying to get this published has been a real pain. I would appreciate any help!

Here is my repository link

and here is a snippet of the code in question:

const loader = new GLTFLoader(loadingManager);
let model;
loader.load('https://mxmadu.github.io/pretty-hurts/models/PHUK_PHACE_A.glb', function(gltf) {

  model = gltf.scene;
  model.rotation.set(0, Math.PI, 0);
  model.receiveShadow = true;
  scene.add(model);

I tried hosting the files on other file hosting platforms (nothing fancy just dropbox and google drive to see if those would give different results because I found out that the pointer file GitHub had created in the process of storing this large file wasn’t the right format?)

So I think I just need to figure out what I can change in my code to fix this

alert() inside useEffect gets triggered before the browser painting is completed. Shouldn’t it trigger after the browser is painted?

Let’s consider this to be the component:

const Alert = () => {
        useEffect(() => {
            alert("hello");
        }, []);
        return <div>Alert</div>;
    };

My understanding is that useEffect runs after the browser has painted.

But in this code, why does the alert pop up before the browser is painted completely?

NOTE: If it does not happen the first time, try refreshing it.

Call separate functions as per device orientation

I am looking for a solution to call different functions as per orientation

if (window.innerHeight > window.innerWidth) {
  alert("You are in portrait mode");
  <Portrait />
}

if (window.innerHeight < window.innerWidth) {
  alert("You are in landscape mode"); 
  <Landscape />
}

Written the following functions

export default function Landscape() {
  return (
    <main>...</main>
  );
}

function Portrait() {
  return (
    <main>...</main>
  );
}

Problem

  • Every time, only Landscape function getting called (I understand because I mentioned default)
  • Atleast, I was expecting Portrait function to be called, when device in portrait mode

Please help to get it done

Using On Click ‘Popup’ function with an Anchor Tag for Updating Data in Page as well as Database

I was facing the problem of Updating Data in Database with PHP.

My Code for the above is:

<tbody>
     <?php
     $i = 1;
     if ($num = mysqli_num_rows($result) > 0) {
         while ($row = mysqli_fetch_assoc($result)) {
             echo "
             <tr>
             <td>" . $i++ . "</td>
             <td>" . $row['course_name'] . "</td>
             <td>" . $row['semester'] . "</td>
             <td>
             **<a href='javascript:?$index=$row[srno]&cn=$row[course_name]&sems=$row[semester]' onclick='openEditPopup()'>
             <button class='edit-btn' ><i class='fa-solid fa-pen-to-square'></i> Edit</button>
             </a>**
             <a href='course.php?srno=" . $row['srno'] . "'><button class='dlt-btn' name='deleteCourse'><i class='fa-solid fa-trash'></i> Delete</button></a>
             </td>
             </tr>
             ";
         }
     }
     ?>
</tbody>

I want My popup to be opened where i can edit and it should be on the page itself while fetching details in the input tag of the popup so as to edit.

But Either Popup works by the above Code OR only Values i.e. index, cn and sems get fetched without opening the popup if i use this line:

**<a href='course.php?$index=$row[srno]&cn=$row[course_name]&sems=$row[semester]' onclick='openEditPopup()'>
  <button class='edit-btn' ><i class='fa-solid fa-pen-to-square'></i> Edit</button>
  </a>**

What is the Soln for this?

I tried watching tutorials and reading articles of using on click with anchor tag but none of them worked as i have that Popup Code where i want to edit.

Firebase Cloud Function returns “DEADLINE EXCEEDED” in Flutter app

I’ve built a cloud function in JavaScript (node: 18) to use the Gemini AI in my Flutter app. This function generates a list of workouts that may be long enough to throw a “DEADLINE EXCEEDED” error. However, the function worked successfully (status code: 200), so the problem should be in the length of the response. In fact, the error is thrown by the bloc function from which I call the cloud function.
Here are the debug console, the could function, the bloc function and the function log.

Debug console:

[firebase_functions/deadline-exceeded] DEADLINE EXCEEDED

#0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:648:7)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334:18)
<asynchronous suspension>
#2      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:22:24)
<asynchronous suspension>
#3      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:49:37)
<asynchronous suspension>
#4      new GenerateWorkoutBloc.<anonymous closure> (package:energi/logic/blocs/generate_workout/generate_workout_bloc.dart:24:26)
<asynchronous suspension>
#5      Bloc.on.<anonymous closure>.handleEvent (package:bloc/src/bloc.dart:229:13)
<asynchronous suspension>

Cloud function:

const functions = require("firebase-functions");
const { GoogleGenerativeAI } = require("@google/generative-ai");
const { prompt } = require("./prompt.cjs");

const apiKey = "key";
const genAI = new GoogleGenerativeAI(apiKey);

const generationConfig = {
  temperature: 0,
  topP: 0.95,
  topK: 64,
  maxOutputTokens: 8192,
  responseMimeType: "application/json",
  responseSchema: {
    type: "object",
    properties: {
      routine: {
        type: "object",
        properties: {
          workoutList: {
            type: "array",
            items: {
              type: "object",
              properties: {
                title: {
                  type: "string"
                },
                exerciseList: {
                  type: "array",
                  items: {
                    type: "object",
                    properties: {
                      exercise: {
                        type: "object",
                        properties: {
                          title: {
                            type: "string"
                          },
                          setList: {
                            type: "array",
                            items: {
                              type: "string"
                            }
                          },
                          timer: {
                            type: "integer"
                          },
                          id: {
                            type: "string"
                          }
                        },
                        required: [
                          "title",
                          "setList",
                          "timer",
                          "id"
                        ]
                      }
                    },
                    required: [
                      "exercise"
                    ]
                  }
                }
              },
              required: [
                "title",
                "exerciseList"
              ]
            }
          }
        },
        required: [
          "workoutList"
        ]
      }
    },
    required: [
      "routine"
    ]
  },
};

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  generationConfig: generationConfig,
});

const runtimeOpts = {
  timeoutSeconds: 300,
}


exports.generateWorkout = functions.runWith(runtimeOpts).https.onRequest(async (req, res) => {
  try {
    const content = await model.generateContent(prompt);
    const response = content.response.text();
    res.status(200).send({ data: response });
  } catch (error) {
    console.error(error);
    res.status(500).send({ error: 'Internal Server Error' });
  }
});

Bloc function:

on<Generate>((event, emit) async {
      emit(GenerateWorkoutInProgress());
      try {
        HttpsCallable callable =
            FirebaseFunctions.instance.httpsCallable('generateWorkout');
        final response = await callable.call(<String, dynamic>{
          "type": "object",
          "properties": {
            "routine": {
              "type": "object",
              "properties": {
                "workoutList": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "title": {"type": "string"},
                      "exerciseList": {
                        "type": "array",
                        "items": {
                          "type": "object",
                          "properties": {
                            "exercise": {
                              "type": "object",
                              "properties": {
                                "title": {"type": "string"},
                                "setList": {
                                  "type": "array",
                                  "items": {"type": "string"}
                                },
                                "timer": {"type": "integer"},
                                "id": {"type": "string"}
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        });
        final workouts = await fromAiData(
            json.decode(response.data) as Map<String, dynamic>);
        emit(GenerateWorkoutSuccess(workouts: workouts));
      } on FirebaseFunctionsException catch (error) {
        emit(GenerateWorkoutError());
        print(error.toString());
      } catch (error) {
        emit(GenerateWorkoutError());
        print(error.toString());
      }
    });

Cloud Function log

UPDATE: Here is the definition of the deadline exceeded error provided by the Firebase documentation:
deadline-exceeded: Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire.

Selenium doesn’t return all cookie values of the page

import logging
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)



try:
    # Set Chrome options to headless
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--window-size=1920,1200")
    chrome_options.add_argument("--ignore-certificate-errors")
    chrome_options.add_argument("--disable-extensions")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")

    # Initialize the Chrome driver
    logger.info("Initializing Chrome WebDriver")
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)

    if driver is None:
        raise Exception("Failed to initialize WebDriver")

    logger.info("Navigating to the webpage")
    driver.get("https://www.nayaraenergy.com/petrol-pump-near-me")

    # Ensure the page is fully loaded
    driver.implicitly_wait(10)  # Wait for up to 10 seconds for the elements to appear

    # Get the cookies
    logger.info("Retrieving cookies")
    cookies = driver.get_cookies()

    session_data = {}
    # Print the cookies
    for cookie in cookies:
        print(cookie)
        data = {
            cookie['name']: cookie['value']
        }
        session_data.update(data)
    print(session_data)
except Exception as e:
    logger.error(f"An error occurred: {e}", exc_info=True)

finally:
    if driver is not None:
        logger.info("Closing the driver")
        driver.quit()

I am trying to get the cookie information of the page –
The above code works to a certain extent, but fails to output all the cookie values

the whole data of the cookie is –
_fbp=fb.1.1722150867062.324436436556492225; _hjSessionUser_3422175=some_data;_gid=GA1.2.353944606.1722412003;_hjSession_3422175=some_data; _ga_6EDN8NZ3RQ=GS1.1.1722433679.6.0.1722433679.60.0.0; _ga_5WCBPP0WF1=GS1.1.1722433679.7.0.1722433679.0.0.0; _ga=GA1.2.1174399862.1722150866; _gat_gtag_UA_142048367_1=1; XSRF-TOKEN=eyJpdiI6IlA0MWIxZHR1WXZvaHBFZHhtU3E2dVE9PSIsInZhbHVlIjoieDV3ZVZRdEpxRWRreUVrWEZQQ0lUWEQ3dGRWUnhLa3JidjR5eGxIc3BVbGl3REZYWmN1SDdIb0dVdTZyN1lDTSIsIm1hYyI6IjgwNmExMTE4MDFkMTkyZGVlYmZkMzVlYjMyYTNhMzg0ODNiNDdmMjdiZTFkNmRlOTYxYzAxMWUwN2Q4YzgwNzAifQ%3D%3D; laravel_session=eyJpdiI6IjVoYkNuOG5hbXF3bVZZd0VGanpHNmc9PSIsInZhbHVlIjoiNm8yaGVXdWllbTQxWGJ1T3p5QkQ4Tmc1QXlhT2E2UG1KOUgyQnF5dkFkVHV4QWZobklGOEF1dG5weGNBNUdZdiIsIm1hYyI6IjljOWQ3MGI4MjgyM2Q1MDZiM2JjN2M1OTcxZWIxMDk0MzgyMTc3MTQ3ZDg1ODExNDdmY2EwN2JkMjJmNmY2Y2YifQ%3D%3D

This session has already expired, so no point trying the tokens
but when i use the get_cookies() function, it doesn’t outputs the hjSessionUser_3422175 and hjSession_3422175

Chatgpt was of no use, I tried finding the get_cookie function in their github repo to understand the workings, but can’t seem to find it, guess it’s built in in the webdriver itself.

Implement form with a few stages using React

I have a template for my website in Figma. There is a page with a bit of content and a pretty large form. This page contains first stage of my form on itself and after filling the data user can move on to the next stage of the form. Each stage of the form except first takes all place on the page. The problem is how to implement this functionality. I don’t think it’s a good way to use pages because of the URL addresses.

I’ll provide you with an image to understand the problem more clearly:
Scheme

Conditions:

  • User can’t visit any stage of form by URL address
  • User should be able to reload the page and their data will still be in its place (without the home page).