streaming rtsp media into an html5 page shows something in one browser but not others

I have a cam that sends via rtsp, it is live and i can watch it using vlc media player without any problem, but i want to embed that to my page and watch it there, i searched stackoverflow for a way doing that and found this:
https://stackoverflow.com/a/49377425/5183578

when i try it in normal html5 it works without problem:

English is not my mother language so there could be mistakes.

<!DOCTYPE html>
<html>
<body>

<h1>The video element</h1>


 <video id="video" controls width="250"> 

     <source src="http://...:8080" >


   
 </video> 


</body>
</html>

My problem is doing that in react, using firefox browser, i can see the stream but it is stopped and i need to refresh the page for it to move if i dont refresh it is like an image. In my stream i have date and time moving, when i refresh the page i can see seconds changing:
enter image description here

trying it with chrome and edge it shows this :

enter image description here

here is my react code:

  const CameraPreviewCanvas = useRef<any>();
  const CameraPreviewImage = useRef<any>();
 
 useEffect(() => {
    updateCanvas();
    const img = CameraPreviewImage.current;
    img.onload = updateCanvas;

    // unmount component when the camera is changed  to prevent memory leaks
    return () => {
      img.onload = null;
    };
  });
 
 <div style={state?.config?.previewStyle}>
        <div style={{ padding: "15px" }}>
          <canvas
            ref={CameraPreviewCanvas}
            width={canvasRenderWidth}
            height={canvasRenderHeight}
            onClick={onClickCanvas}
            onMouseMove={onMouseOverCanvas}
            style={canvasStyle}
          ></canvas>

          <video
            id="video"
            loop
            autoPlay={true}
            muted
            preload="auto"
            width="250"
            ref={CameraPreviewImage}
           
            style={{ display: "none" }}
          >
            <source src="http://...:8080" />

            <source src="http://...:8080" />
          </video>

         
        </div>
      </div>

How do i link a button to load a page and then play a specific song in wordpress

I have a music streaming site am developing, I have page1.html with different songs from different artists displayed with normal buttons on them, I want to make these buttons load a specific artist’s page (artist_X.html) and automatically scroll to the playlist and click the play button on the song whose title/button was clicked.
Guys any help, I have never done any extra coding inside WordPress except using plugins.
Thanks

Regex for email address format validation [duplicate]

Of course, it’s an old topic and it involves many similar questions with a tons of different answers, sometimes overcomplicated or just barely understandable. Here’s my handcrafted not-so-overengineered solution I managed to pull out after few days of digging the topic:

^(([A-Za-z0-9]+[_.-]?)+){2,}(?<![_.-])@{1}(([a-zA-Z0-9]{2,})+.)+[a-zA-Z0-9]{2,}$

What it does:

  • first group is at least one alphanumeric character
  • group ends at first occurance of ./_/-, if present
  • group can be repeated many times, allowing names like my.awesome_mailbox@...
  • a single @ character is following, but it can’t go immediately after ./_/-
  • then another group comes in for domain names, allowing many to be present like [email protected], ensuring that each is alphanumeric, two symbols min and ends with ., except the last one

I personally found this pattern matches all emails I had at hand, but not allowing some obviously invalid inputs which other patterns frequently missing: double dots, dashes and underscores, stupid special characters (which are technically allowed, but I’ve never seen them in the real email names) and multiple @s. Please, enhoy with exploring my pattern (https://regex101.com/ to your help), any feedback is welcome!

Why my if statement is not working while the condition is true?

I am trying to create dynamic fields based on my selected attributes. I have 2 array objects addAttributes and fakeAttributes. fakeAttributes are the details of selected attributes. I have a dropdown select component if I pass the addAttributes it will show the data. If I select any option from my select component it will store into the setAttributes state.

Live code: https://codesandbox.io/s/summer-cloud-m0bvn?file=/src/App.js:1247-1678

 const [attributes, setAttributes] = useState([{ label: '', value: 1 }])

    const addAttributes = [
        { label: 'colors', value: 1 },
        { label: 'size', value: 2 },
    ]

    // Attributes data
     const fakeAttributes = [{
        label: 'colors',
        object: [
            { label: 'Black', value: 1 },
            { label: 'Green', value: 2 },
        ]
    },
    {
        label: 'size',
        object: [
            { label: 'M', value: 1 },
            { label: 'S', value: 2 },
        ]
    }
    ]

Dropdown UI. I am using npm i react-select package for the dropdown.
dropdown ui
This is my code where I am trying to filter and map those array objects if the value matches with the label it will show a text but the output is not showing also I did not get any error. The condition is matching.


<div className='flex flex-row gap-6'>
        <div className="basis-1/4">

            <label className="block text-sm font-medium text-gray-700 mb-3"> Size </label>
            <Select options={addAttributes} onChange={(e: any) => setAttributes(e)} className="shadow appearance-none border rounded w-full text-gray-700 leading-tight focus:outline-none focus:shadow-outline"  isMulti />

        </div>
         {fakeAttributes.map((attr) => {
          attributes.filter((list) => {
            console.log(typeof attr.label,":",attr.label,typeof list.label,":",list.label);
            if (list.label === attr.label) {
              console.log("ok I am in");
              return <h2>Output</h2>;
            }
          });
        })}

    </div>

Can any one please help me? How can I solve it?

Explanation of the above schema:

Working on the backend for an ecommerce application. Came across this schema for user model. If the user is seller then do we have to write the seller name again???

    const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: { type: Number, required: true },
    email: { type: String, required: true, unique: true },
    address: { type: String, required: true },
    password: { type: String, unique: true, required: true },
    isAdmin: { type: Boolean, required: true, default: false },
    isSeller: { type: Boolean, required: true, default: false },
    seller: {
        name: String,
        rating: { type: Number, required: true, default: 0 },
        numReviews: { type: Number, default: 0, required: true }
    }
}, {
    timestamps: true
});

How to get JSON Array value? I need to get murali printed

<!DOCTYPE html>
<html>
<body>

<h2>Creating an Array from JSON</h2>
<p id="demo"></p>

<script>
const myJSON = '[{password:"murali"}]';
const myArray = JSON.parse(myJSON).password;
document.getElementById("demo").innerHTML = myArray;
</script>

</body>
</html>

I need to get murali to get printed. This is for my React Project. I got to validate password. Hence I connected my mysql and retrive password from database and I need to validate it, In oder to validate I need to compare (database Password == input password). But as i retrive password I got the password in [{password: “murali”}] in this format and I am not able to compare with input password.

Change div background when div is scrolled (no height)

I should have a <div> change the background-color when it reaches the middle of the screen, but I cannot use the window height (jQuery(window).scrollTop();) because the size of the contents above the div is not known or is variable.

I started with this code, but I don’t know how to change the setting from “scroll from top” to “scroll/position of the div”: https://jsfiddle.net/cLo2t6kn/1/

Getting ECONNREFUSED when using Axios library in Express JS

I have a backend express server with Express JS

  1. My project is configured via a config.js file
  2. I have a running API in api.js which loads data from a json file testData.json and returns it to caller.
  3. In a separate file, serverRender.js I am calling the endpoint in api.js to console log the json data returned by it.
  4. I am calling serverRender.js from server.js and seeing a ECONNREFUSED error, I thought it was CORS but dont know how to resolve it here, and from other stackoverflow links like here I am not deriving much
  5. I have tried to access http://0.0.0.0:8080/api/contests which is my endpoint in this case from curl and web browser, both seem to work.

Big thanks, for any suggestion.

config.js

export default {
  port: env.PORT || 8080,
  host: env.HOST || '0.0.0.0',
  get serverUrl() {
    return `http://${this.host}:${this.port}`;
  }
};

server.js

import express from 'express';
import config from './config';
import apiRouter from './api';

const server = express();

// Calling the api endpoint
import './serverRender';


server.get('/', (req, res) => {
  res.send("hello world!")
});


// manage routes using the Express router
server.use('/api', apiRouter);

server.listen(config.port, config.host, () => {
  console.log('Listening at ', config.serverUrl);
});

api.js

import express from 'express';
import data from '../src/testData.json';

const router = express.Router();

router.get('/contests', (req, res) => {
  res.send({ contests: data.contests });
});

export default router;

testData.json

{
  "contests": [
    {
      "id": 1,
      "categoryName": "Business/Company",
      "contestName": "Cognitive Building Bricks"
    }
  ]
}

serverRender.js

import axios from 'axios';
import config from './config';

axios
  .get(`${config.serverUrl}/api/contests`)
  .then((resp) => {
    console.log(resp.data);
  })
  .catch((error) => {
    console.error
  });

package.json

{
  "name": "learn-fullstack-javascript",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "nodemon --exec babel-node server.js",
    "dev": "webpack -w --mode=development",
    "test": "echo "Error: no test specified" && exit 1"
  },
 
  
  "homepage": "https://github.com/jscomplete/learn-fullstack-javascript#readme",
  "dependencies": {
    "axios": "^0.26.0",
    "ejs": "^3.1.6",
    "express": "^4.17.2",
    "mongodb": "^4.3.1",
    "node-sass-middleware": "^0.11.0",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.17.0",
    "@babel/core": "^7.17.2",
    "@babel/node": "^7.16.8",
    "@babel/plugin-proposal-class-properties": "^7.16.7",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.2.3",
    "eslint": "^8.8.0",
    "eslint-plugin-react": "^7.28.0",
    "json-loader": "^0.5.7",
    "nodemon": "^2.0.15",
    "webpack": "^5.68.0",
    "webpack-cli": "^4.9.2"
  }
}

Trying to set the value of input field in formik

i am trying to create a job posting form using react , mui , formik and yup in which
i am creating a tag input field same as stackoverflow have but when i am setting the value of tag after adding new tag using setTags then it is adding the second last tag not the last.

   import { TextField } from '@material-ui/core';
   import "../../App.css";
   const TagsInput = props => {
     const [tags, setTags] = React.useState(props.tags);
     const removeTags = indexToRemove => {
       setTags([...tags.filter((_, index) => index !== indexToRemove)]);
        };
     const addTags = (event,tags) => {
        if (event.target.value !== "") {
             setTags([...tags, event.target.value]);
             props.selectedTags([...tags, event.target.value]);
             props.setFieldValue('tag',tags)
             event.target.value = "";
             }
        };
    return (
        <div className="tags-input">
            <ul id="tags">
                {tags.map((tag, index) => (
                    <li key={index} className="tag">
                        <span className='tag-title'>{tag}</span>
                        <span className='tag-close-icon'
                            onClick={() => removeTags(index)}
                        >
                            x
                        </span>
                    </li>
                ))}
            </ul>
            <TextField
               type="text"
                onKeyUp={event => event.key === "Enter" ? addTags(event,tags) : null}
                placeholder="Add tags"
            />
        </div>
    );
};

export default TagsInput```

 Props which i have passed 
props = <selectedTags={selectedTags} setFieldValue={setFieldValue}  tags={[]}>

Example:
like if i enter *html* as first tag then it sets *[]* as value of tag 
if i enter *css* as sencond tag then it sets *['html']* as value of tag
if i enter *js* as third tag then it sets *['html','css']* as value of tag

Plese help me out how can i fix this bug.


How to handle POST request in Shopify app using Next.js, Koa, MongoDB embedded app?

I’m testing Shopify’s next.js/koa setup and I want to connect to MongoDB and post some data.
I read this guide – https://dev.to/raphaelchaula/adding-mongodb-mongoose-to-next-js-apis-3af and did the same things, the difference is maybe I am using shopify’s boilerplate and there are things I cannot figure out.

The problem is that I am getting HTTP 405 – Method Not Allowed when I try to POST some data.

In server.js I don’t have /cart route handler (I don’t know if I have to).

My middleware:

import mongoose from "mongoose";

const connectDB = (handler) => async (req, res) => {
 if (mongoose.connections[0].readyState) {
   // Use current db connection
   return handler(req, res);
 }
 // Use new db connection
 await mongoose.connect(process.env.mongoDBurl, {
   useUnifiedTopology: true,
   useFindAndModify: false,
   useCreateIndex: true,
   useNewUrlParser: true,
 });
 return handler(req, res);
};

export default connectDB;

My model (this is testing schema):

import mongoose from "mongoose";
var Schema = mongoose.Schema;

var cart = new Schema({
  id: {
    type: Number,
    required: true,
  },
  store: {
    type: String,
    required: true,
  },
  createdAt: {
    type: Date,
    required: true,
  },
});

mongoose.models = {};

var Cart = mongoose.model("Cart", cart);

export default Cart;

The /api/cart.js route:

import connectDB from "../../middleware/mongodb";
import Cart from "../../models/cart";

const handler = async (req, res) => {
  if (req.method === "POST") {
    const { id, store, createdAt } = req.body;
    if (id && store && createdAt) {
      try {
        // Hash password to store it in DB
        var cart = new Cart({
          id,
          store,
          createdAt,
        });
        // Create new cart
        var cartcreated = await cart.save();
        return res.status(200).send(cartcreated);
      } catch (error) {
        return res.status(500).send(error.message);
      }
    } else {
      res.status(422).send("data_incomplete");
    }
  } else if (req.method === "GET") {
    res.status(200).send("Success");
  } else {
    res.status(422).send("req_method_not_supported");
  }
};

export default connectDB(handler);

My mondoDB url is inside next.config.js:

module.exports = {
  webpack: (config) => {
    const env = {
      API_KEY: apiKey,
      mongoDBurl:
        "mongodb+srv://<username>:<password>@cluster0.wscad.mongodb.net/myFirstDatabase?retryWrites=true&w=majority",
    };
    config.plugins.push(new webpack.DefinePlugin(env));

    // Add ESM support for .mjs files in webpack 4
    config.module.rules.push({
      test: /.mjs$/,
      include: /node_modules/,
      type: "javascript/auto",
    });

    return config;
  },
};

Flutter – Return Null value while using Http Request in Cloud Functions

Here is my issue, I have a callable Cloud Function I would like to use on my Flutter app.

You can find the code below.

However, each time I press the button corresponding to the function I always have a “null” value on my app coming from Cloud Functions even if my answer is printed into the console.

From what I understand, the function return a “null” value as the jsonResponse is not here yet.

I would like to find a way to return the jsonResponse only when the answer is there.

I tried async, await, and promises already, but maybe I used it the wrong way ?

Thank you

exports.writeMessage = functions.https.onCall(async (data, context) => {

  global.XMLHttpRequest = require("xhr2");
  function makeRequest(method, url) {
    appleMusicKey = 'XXXXXXX'
    return new Promise(function (resolve, reject) {
      let http = new XMLHttpRequest();
      http.open(method, url);
      http.setRequestHeader('Authorization', 'Bearer ' + appleMusicKey);
      http.onload = function () {
        if (this.status >= 200 && this.status < 300) {
          resolve(JSON.parse(http.response)['data'][0]['attributes']['url'].toString());
        } else {
          reject({
            status: this.status,
            statusText: http.statusText
          });
        }
      };
      http.onerror = function () {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      };
      http.send();
    });
  }

  async function doAjaxThings() {
    var isrcCode = 'QMBZ92168114';
    let result = await makeRequest("GET", `https://api.music.apple.com/v1/catalog/fr/songs?filter[isrc]=${isrcCode}`);
    
    console.log(result);

    return new Promise(function (resolve, reject) {
      resolve(result);
      reject('error');
    });
  }

  doAjaxThings();

});

Whats wrong witch my pattern on this function [duplicate]

error – Uncaught SyntaxError: Invalid regular expression: /^[0-9]{2}+-[0-9]{3}/: Nothing to repeat

function code :

kod.onblur = function(){
var regex = /^[0-9]{2}+-[0-9]{3}/i;
if(kod.value.match(regex)){
    span[3].innerHTML = "Poprawny kod";
    span[3].style.color = 'lime';
}else{
    span[3].innerHTML = "podaj Poprawny kod";
    span[3].style.color = 'lime';
}

i need to match somethink like that 19-200 or 10-621