Generate Json UI Schema from a Json schema

I have a configuration repository made of different object (configuration). For each of them i know structure and field domains, so i have build a json schema for all my configuration (in the repository) based on the configuration “type” structure.

I am trying to use project like this to achive te json-schema to form conversion :
https://github.com/jarvelov/vue-form-json-schema

But in order to do so i also have to produce a UI Schema, and i don’t know how to generate such information in authomatic way.
I can build my own Json Schema converter/parser studying UI Schema definition first, but that seems very time consuming.

So i wondering if there is a better approach to my problem (assist configuration data-entry when you don’t know configuration structure in advance), or if there is a standard way to convert Json Schema to UI Schema.

Ps : Here what i mean for UI Schema
https://jsonforms.io/examples/gen-uischema/

How I could test location with MemoryRouter on React Router DOM v6?

Using React Router DOM (v6) with React Testing Library, I would like to know if there’s a way to deal with “mocked” history from createMemoryHistoryor an alternative like it.

Based on the example of Testing Library, I could mock the history on the Router component but in v6 this component doesn’t accept the history prop anymore.

So, my doubt is: how can I test history and location with RTL (React Testing Library) with React Router DOM v6? Should I keep using the MemoryRouter?

How to bind text to the label which is in JsonObj using jquery

I am getting data in an array which I need to bind to the label below is my code. When the array is empty I need to bind no records found which are working but I need to bind the data in the array to the label. Suppose if I have 2 items in the array I need to bind two items i.e slider 1 should have one item and again after sliding to the right I need to bind the second item.

If more than 1 item is there then the right slider should be enabled and if it has only 1 item right slider should be disabled if there are no items both the sliders should be disabled

enter image description here

enter image description here

success: function (response) {
                    var json = response.d;
                    if (json.length == 0) {
                        $('.swiper-wrapper').append('<div class="swiper-slide">No rocords found</div>');
                    } else {
                        $.each(json, function (index, item) {
                            $('.swiper-wrapper').append('<div class="swiper-slide">Name : ' + item.Name + '<br />Number: ' + item.Number + '</div>');
                        });
                    }

Why when I create several html tags with javascript then I can not delete it with the same javascript?

When I create a form with the write () command, then I want to delete it, but I can’t. What is the cause of this problem?

In order to do this correctly, what command should I use or what should I change in my code?

var btn = document.querySelector('#btn');
var btn_alert = document.querySelector('#btn-alert');
var content = document.querySelector('.popup-container');
var div1 = document.getElementById('div1');

function message(message, btn) {
    document.write('<div id="div1"><div id="content" class="popup-container"><div class="box-item"><div class="icon-success"><span class="span1"></span> <span class="span2"></span><div class="ring"></div></div><h2 class="alert-title">Good job!</h2><div class="alert-content">' + message + '</div><div class="actions-btn"><button onclick="ok()" class="btn-alert" id="btn-alert">' + btn + '</button></div></div></div></div>')
}

function ok() {
    div1.removeChild(content);
}
<button class="btn-alert" id="btn">OK</button>

    <!-- <div id="content" class="popup-container dis-active">
        <div class="box-item">
        <div class="icon-success">
            <span class="span1"></span> 
            <span class="span2"></span>
            <div class="ring"></div>
        </div>
        <h2 class="alert-title">Good job!</h2>
        <div class="alert-content">is ok.</div>
        <div class="actions-btn">
        <button class="btn-alert" id="btn-alert">OK</button>
        </div>
        </div>
    </div>  -->

    
    <script src="script.js"></script>
    <script>
        message("خوش اومدی!", "کلیک کن");
    </script>

Mongoose-Unique-Validator giving unique error when trying to update a field (MongoDB/JavaScript)

I have a blog application using MongoDB/Mongoose on an Express server. I am using Mongoose-Unique-Validator.

Each user document has a ‘posts’ field which is an array consisting of post ID’s.
When a user makes a new post, I attempt to update their document to add the post to their posts array:

let user = await User.findByIdAndUpdate("61b45baa09caf8ee462248df")
    await post.save().then(savedPost => {
        user.posts = user.posts.concat(savedPost.id)
        user.save()
    })

When this code is run, the following error is outputted:

  errors: {
    _id: ValidatorError: Error, expected `_id` to be unique. Value: `61b45baa09caf8ee462248df`
        at validate (C:UsersaveryDesktopblogbackendnode_modulesmongooselibschematype.js:1277:13)
        at C:UsersaveryDesktopblogbackendnode_modulesmongooselibschematype.js:1252:24
        at processTicksAndRejections (node:internal/process/task_queues:96:5) {
      properties: [Object],
      kind: 'unique',
      path: '_id',
      value: new ObjectId("61b45baa09caf8ee462248df"),
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'User validation failed'

My User Schema is as follows::

const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')

const userSchema = mongoose.Schema({
    username: {
        type: String,
        unique: true
    },
    passwordHash: String,
    posts: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref:'Post'
        }
    ]
})

userSchema.plugin(uniqueValidator)

userSchema.set('toJSON', {
    transform: (document, returnedObject) => {
        returnedObject.id = returnedObject._id.toString()
        delete returnedObject._id
        delete returnedObject.__v
        delete returnedObject.passwordHash
    }
})

const User = mongoose.model('User', userSchema)

module.exports = User

Can anyone please help me figure out what the issue is here? Thanks in advance <3

Unhandled Rejection (TypeError): Cannot set properties of undefined (setting ‘srcObject’) in react js

I am making a video calling app using socket.io. But it gives an error.The error is Unhandled Rejection (TypeError): Cannot set properties of undefined (setting ‘srcObject’) though camera is allowed to use.What i have done wrong and how i can fix it any advice.Thanks in advance.

Here is my code which gives error

    import React, { useState, useEffect, useRef } from "react";
    import VideoContext from "./VideoContext";
    import { io } from "socket.io-client";
    import Peer from "simple-peer";
    import { message } from "antd";
    import firebase from 'firebase';
    import {db,auth} from "../firebases"
    import {useCollection} from 'react-firebase-hooks/firestore'
    import {useAuthState} from 'react-firebase-hooks/auth'
    const URL = "https://fathomless-tundra-67025.herokuapp.com/";       
    export const socket = io(URL);
    const VideoState = ({ children }) => {
      const [callAccepted, setCallAccepted] = useState(false);
      const [callEnded, setCallEnded] = useState(false);
      const [stream, setStream] = useState();
      const [chat, setChat] = useState([]);
      const [name, setName] = useState("");
      const [call, setCall] = useState({});
      const [me, setMe] = useState("");
      const [userName, setUserName] = useState("");
      const [otherUser, setOtherUser] = useState("");
      const [myVdoStatus, setMyVdoStatus] = useState(true);
      const [userVdoStatus, setUserVdoStatus] = useState();
      const [myMicStatus, setMyMicStatus] = useState(true);
      const [userMicStatus, setUserMicStatus] = useState();
      const [msgRcv, setMsgRcv] = useState("");
      const [screenShare, setScreenShare] = useState(false)
      const myVideo = useRef();
      const userVideo = useRef();
      const connectionRef = useRef();
      const screenTrackRef = useRef();
    const[dbId,setDbId]=useState(null)
    const[user,laoding,error]=useAuthState(auth)
    const[userId,setUserId]=useState(null)
      useEffect(() => {
        navigator.mediaDevices
          .getUserMedia({ video: true, audio: true })
          .then((currentStream) => {
            setStream(currentStream);
            myVideo.current.srcObject = currentStream;
          });
        if (localStorage.getItem("name")) {
          setName(localStorage.getItem("name"));
        }
        socket.on("me", (id) => setMe(id));
        socket.on("endCall", () => {
          window.location.reload();
        });
        socket.on("updateUserMedia", ({ type, currentMediaStatus }) => {
          if (currentMediaStatus !== null || currentMediaStatus !== []) {
            switch (type) {
              case "video":
                setUserVdoStatus(currentMediaStatus);
                break;
              case "mic":
                setUserMicStatus(currentMediaStatus);
                break;
              default:
                setUserMicStatus(currentMediaStatus[0]);
                setUserVdoStatus(currentMediaStatus[1]);
                break;
            }
          }
        });
    
        socket.on("callUser", ({ from, name: callerName, signal }) => {
          setCall({ isReceivingCall: true, from, name: callerName, signal });
        });
    
        socket.on("msgRcv", ({ name, msg: value, sender }) => {
          setMsgRcv({ value, sender });
          setTimeout(() => {
            setMsgRcv({});
          }, 2000);
        });
      }, []);
    
      // useEffect(() => {
      //   console.log(chat);
      // }, [chat]);
    
      const answerCall = () => {
        setCallAccepted(true);
        setOtherUser(call.from);
        const peer = new Peer({ initiator: false, trickle: false, stream });
    
        peer.on("signal", (data) => {
          socket.emit("answerCall", {
            signal: data,
            to: call.from,
            userName: name,
            type: "both",
            myMediaStatus: [myMicStatus, myVdoStatus],
          });
        });
    
        peer.on("stream", (currentStream) => {
          userVideo.current.srcObject = currentStream;
        });
    
        peer.signal(call.signal);
    
        connectionRef.current = peer;
        console.log(connectionRef.current);
      };
    
      const callUser = (id) => {
        const peer = new Peer({ initiator: true, trickle: false, stream });
        setOtherUser(id);
        peer.on("signal", (data) => {
          socket.emit("callUser", {
            userToCall: id,
            signalData: data,
            from: me,
            name,
          });
        });
    
        peer.on("stream", (currentStream) => {
          userVideo.current.srcObject = currentStream;
        });
    
        socket.on("callAccepted", ({ signal, userName }) => {
          setCallAccepted(true);
          setUserName(userName);
          peer.signal(signal);
          socket.emit("updateMyMedia", {
            type: "both",
            currentMediaStatus: [myMicStatus, myVdoStatus],
          });
        });
    
        connectionRef.current = peer;
        console.log(connectionRef.current);
      };
    
      const updateVideo = () => {
        setMyVdoStatus((currentStatus) => {
          socket.emit("updateMyMedia", {
            type: "video",
            currentMediaStatus: !currentStatus,
          });
          stream.getVideoTracks()[0].enabled = !currentStatus;
          return !currentStatus;
        });
      };
    
      const updateMic = () => {
        setMyMicStatus((currentStatus) => {
          socket.emit("updateMyMedia", {
            type: "mic",
            currentMediaStatus: !currentStatus,
          });
          stream.getAudioTracks()[0].enabled = !currentStatus;
          return !currentStatus;
        });
      };
    
      
        //SCREEN SHARING 
        const handleScreenSharing = () => {
    
          if(!myVdoStatus){
            message.error("Turn on your video to share the content", 2);
            return;
          }
        
          if (!screenShare) {
            navigator.mediaDevices
              .getDisplayMedia({ cursor: true })
              .then((currentStream) => {
                const screenTrack = currentStream.getTracks()[0];
    
      
                  // replaceTrack (oldTrack, newTrack, oldStream);
                  connectionRef.current.replaceTrack(
                    connectionRef.current.streams[0]
                      .getTracks()
                      .find((track) => track.kind === 'video'),
                    screenTrack,
                    stream
                  );
      
                // Listen click end
                screenTrack.onended = () => {
                  connectionRef.current.replaceTrack(
                      screenTrack,
                      connectionRef.current.streams[0]
                        .getTracks()
                        .find((track) => track.kind === 'video'),
                      stream
                    );
    
                  myVideo.current.srcObject = stream;
                  setScreenShare(false);
                };
      
                myVideo.current.srcObject = currentStream;
                screenTrackRef.current = screenTrack;
                setScreenShare(true);
              }).catch((error) => {
                console.log("No stream for sharing")
              });
          } else {
            screenTrackRef.current.onended();
          }
        };
    
         //full screen
         const fullScreen = (e) => {
          const elem = e.target;
      
          if (elem.requestFullscreen) {
            elem.requestFullscreen();
          } else if (elem.mozRequestFullScreen) {
            /* Firefox */
            elem.mozRequestFullScreen();
          } else if (elem.webkitRequestFullscreen) {
            /* Chrome, Safari & Opera */
            elem.webkitRequestFullscreen();
          } else if (elem.msRequestFullscreen) {
            /* IE/Edge */
            elem.msRequestFullscreen();
          }
        };
    
      const leaveCall = () => {
        setCallEnded(true);
    
        connectionRef.current.destroy();
        socket.emit("endCall", { id: otherUser });
        window.location.reload();
      };
    
      const leaveCall1 = () => {
        socket.emit("endCall", { id: otherUser });
      };
      const sendMsg = (value) => {
        socket.emit("msgUser", { name, to: otherUser, msg: value, sender: name });
        let msg = {};
        msg.msg = value;
        msg.type = "sent";
        msg.timestamp = Date.now();
        msg.sender = name;
        setChat([...chat, msg]);
      };
      // console.log("user email",user.email)
    const[users,loadse,e]=useCollection(db.collection('users').where('email','==',user.email))
    users?.docs?.map((doc)=>{
     // alert(doc.id)
     // console.log("dbge",doc.data().email)
      setUserId(doc.id)
      db.collection('users').doc(doc.id).set({
      socketId:me
    },{merge:true})
    })
       
    // console.log("userid",userId)
    
      return (
        <VideoContext.Provider
          value={{
            dbId,
            call,
            callAccepted,
            myVideo,
            userVideo,
            stream,
            name,
            setName,
            callEnded,
            me,
            callUser,
            leaveCall,
            answerCall,
            sendMsg,
            msgRcv,
            chat,
            setChat,
            setMsgRcv,
            setOtherUser,
            leaveCall1,
            userName,
            myVdoStatus,
            setMyVdoStatus,
            userVdoStatus,
            setUserVdoStatus,
            updateVideo,
            myMicStatus,
            userMicStatus,
            updateMic,
            screenShare,
            handleScreenSharing,
            fullScreen
          }}
        >
          {children}
        </VideoContext.Provider>
      );
    };
    
    export default VideoState;
    
        

Problem when using eval to create a function

It was a complicated code, I simplified it to this

class Wr{
    constructor(w){this.w=w}
}
class E{}
Array.prototype.popfirst=function(){
    this.splice(0,1)
}
function w(){
    let a=["Wr",new E()]
    eval(`var f=function(args){return new ${a[0]}(...args)}`)
    a.popfirst()
    console.log(f)
    console.log(",")
    console.log(...a)
    console.log(",")
    console.log(f(a))
}

I want f(a) to be new Wr(new E()),
but when l checked the console, I saw only one ƒ (){ this.splice(0,1) }. But I used 5 log()!

I fixed the code several times but still don’t understand where the problem is.

How to continously map an array in JavaScript?

I am trying to create an alert component in React.JS which would receive one array as props and then loop through all the elements inside and display them in the alert component.

I do not know how to restart the loop when the array map ends.

This is my code:

        useEffect(() => {
                props.messages.map((item, index) => {
                        setTimeout(() => {
                          setMessage(item);
                        }, 5000*index)
                      });
        },[]);

I want to run the loop continuously until the user closes the notification alert.

My guess is to wrap the map inside a while / do while in order to run it until the user closes the notification bar. I am having trouble restarting the loop once the map of the array gets to the last element.

“INVALID QUERY RESULT MASK” PostgreSQL through Javascript

I have been trying to access a psql function using the db.func function.

The following is my query

CREATE OR REPLACE FUNCTION play_game(game INT, IN userid INT, IN card INT, OUT uid INT, OUT cid INT, OUT cardfile varchar(255) ) RETURNS SETOF record as
$$
DECLARE
     playorder integer;
     
     cardtype varchar(6);
     cardcolor varchar(10);
     cardvalue integer;
     
     l_cardtype varchar(6);
     l_cardcolor varchar(10);
     l_cardvalue integer;
     cardid integer;
Begin
    -- check if this is the user who has to play
    SELECT play_order INTO playorder FROM user_game WHERE user_id = userid;
    
    IF playorder = 1 THEN
        -- get card attributes
        SELECT card_type, card_color, card_value
             INTO cardtype, cardcolor, cardvalue
            FROM card
         WHERE card_id = card;
     
         -- get the attributes of the last card that was played for this game
         select c.card_id, c.card_type, c.card_color, c.card_value
           INTO cardid, l_cardtype, l_cardcolor, l_cardvalue
           FROM play_card pc, card c
           WHERE pc.card_id = c.card_id
                  AND pc.game_id = game
                  AND pc.id = (SELECT MAX(id) FROM play_card WHERE game_id = game);
       Begin
            -- check this is the right card to play
            IF cardcolor = l_cardcolor AND
                 cardtype = 'NOM' THEN
                INSERT INTO play_card (game_id, user_id, card_id) VALUES (game, userid, card);
                -- delete card from draw card
                DELETE FROM game_card WHERE game_id = game and card_id = card;
            END IF;
            commit;
       End;
       
       -- move play to the next player
       Begin
          IF cardtype = 'NOM' THEN
               UPDATE user_game
                        SET play_order = play_order - 1
                 WHERE game_id = game;
               
               UPDATE user_game
                        SET play_order = (SELECT count(user_id) from user_game WHERE game_id = game)
                 WHERE game_id = game;
            ELSE
                  UPDATE user_game
                           SET play_order = 1 + (SELECT count(user_id) from user_game WHERE game_id = game) - play_order
                       WHERE game_id = game;
            END IF;
       End;
       
    End if;

    -- get game state and return to Front END
  RETURN QUERY SELECT gc.user_id, gc.card_id, c.image_file FROM game_card gc, card c WHERE gc.card_id = c.card_id AND gc.game_id = game ORDER BY user_id;
END;
$$ LANGUAGE plpgsql;

This is my javascript function

db.func("play_game", { gameId, userId, cardId })
    .then((results) => {
      let card = results;
    })
    .catch((error) => {
      console.log("error in play_game databse function: ", error);
    });

I have even tried passing the parameters without the object but I get the error saying “invalid query result mask”

It also gives the following hint:
No function matches the given name and argument types. You might need to add explicit type casts.

Please let me know what to do. Any help is appreciated. Thank you 🙂

how to auto generate git PATs?? (personal access tokens)?

I also using JavaScript, vue.js, Wsl , git ssh, and java ( Spring, Spring boot )

enter image description here

i have been trying to get Personal access token ( PATs ) from github.com.

but in the project that i am working on, the token is not permanent.

it just goes away after i have used the token several times.

in github.com it says This token expires on Mon, Jan 10 2022 but i think it has been

invalidated after i used it multiple times even if there is a month left before expiration date.

so i want to regenerate the token after invalidation through Java ( 1.8 ) or JavaScript

please let me know any ways to solve this problem

Rendering Approach for Complex Text Annotation

I am looking for a way to provide rendering of complex annotations for text in a javascript context. The annotations are based on the way a user has tagged individual words and groups of words. The annotating can be hierarchical. E.g. a group may have an annotation that spans the width of the group while individual words within the group may also have their own annotation. I have considered css, canvas and svg. With the latter two am not clear on how to position the rendering such that it lines up with the text. See sample markup below.

Sample markup

How to process socket.io events in their incoming order

I have the following setup:

async MyFunction(param) {
    //... Do some computation
    await WriteToDB()
}

io.on('connection', (socket) => {
    socket.on('AnEvent', (param) => MyFunction(param))
})

When an event comes in, it calls an asynchronous function which does some computation and in the end write the result to a database with another asynchronous call.

If MyFunction doesn’t have an asynchronous call to write the database in the end, for example

MyFunction(param) {
    //... Do some computation
}

then it is obviously that all events will be processed in their incoming order. The processing of the next event will only start after the processing of the previous one finishes. However, because of the asynchronous call to the database, I don’t know if those incoming events will still be fully processed in order. I am afraid that the processing of the next event starts before the previous await WriteToDB() finishes. How do I change the code to fully processing them in order?

Why does Node pass in the exports argument on top of the module argument?

It is known that each module in Node.js is wrapped in a function, where 5 arguments are passed in (i.e. exports, module, require, __filename, __dirname) and the module.exports object is returned.

Since exports is just an alias for module.exports, is there a reason why both module and exports are listed as 2 separate arguments? In terms of design, is it simply for the ease of accessing the exports object?

I couldn’t find this question being answered, but I’m happy to be redirected to an existing one.

// function (exports, module, require, __filename, __dirname) {

const a = 1;
console.log(a);

// return module.exports;
// }