React how to show xml view with expand and collapse functions? (react-xml-viewer)

Hi I wanted to show xml view in my application. To achieve that I was using react-xml-viewer but also I wanted to add all expand and collapse functions aswell when I check react-xml-viewer I couldn’t see it. Is there any way to achieve this with react-xml-viewer or is there any package that I can use. Both solution is ok for me.

import React from 'react';
import XMLParser from "react-xml-parser";
import * as s from './XMLDetail.styles';
import XMLViewer from "react-xml-viewer";

const XMLDetail = props => {
const {
    isDarkMode = false,
    appHdrData = "",
    documentData = "",
    isOpenButton=false,
} = props;

//Return
return (
    <div>
        <s.ColumnContainer>
            <s.Customlabel isOpenButton={isOpenButton} >Header</s.Customlabel>
            <s.Customlabel isOpenButton={isOpenButton} >Document</s.Customlabel>
        </s.ColumnContainer>
        <s.XMLDetailContainer>
            <s.XMLContainer isOpenButton={isOpenButton}>
                <XMLViewer xml={appHdrData}/>
            </s.XMLContainer>
            <s.XMLContainer  isOpenButton={isOpenButton}>
                <XMLViewer xml={documentData}/>
            </s.XMLContainer>
        </s.XMLDetailContainer>
    </div>
)

}

export default XMLDetail

TypeError: jwt.sign is not a function help guys

generateToken.js

    const jwt = require('jsonwebtoken');
  const generateToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: '30d'
});
 };
  module.exports = generateToken;

userController.js

 const asyncHandler = require('express-async-handler')
 const User = require("../Models/userModal");
 const generateToken = require('../utils/generateToken');




const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;

const user = await User.findOne({ email });

if (user && (await user.matchPassword(password))) {
    res.json({
        _id: user._id,
        name: user.name,
        email: user.email,
        token: generateToken(user._id),
    });
  } else {
    res.status(401);
    throw new Error("Invalid Email or Password");
}
});


 const registerUser = asyncHandler(async (req, res) => {
const { name, email, password, } = req.body;

const userExists = await User.findOne({ email });

if (userExists) {
    res.status(404);
    throw new Error("User already exists");
}

const user = await User.create({
    name,
    email,
    password,
});

if (user) {
    res.status(201).json({
        _id: user._id,
        name: user.name,
        email: user.email,
        token: generateToken(user._id),
    });
 } else {
    res.status(400);
    throw new Error("User not found");
}
});

module.exports = { registerUser, authUser }

userModel

const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')

const userSchema = mongoose.Schema(
 {
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: [true, 'The email is unique']

    },
    password: {
        type: String,
        required: true
    },
  }
);
userSchema.pre('save', async function (next) {
if (this.isModified('password')) {
    next();
}
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
 });
 userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};

const User = mongoose.model('user', userSchema);
module.exports = User;

.env

JWT_SECRET:'piyush1234'

And here’s the error in postman

{

TypeError: jwt.sign is not a function
   at generateToken (C:UsersYassine JedidiDesktopprojet alaserverutilsgenerateToken.js:3:16)
   at C:UsersYassine JedidiDesktopprojet alaserverControllersuserControllers.js:50:20
   at runMicrotasks (<anonymous>)
   at processTicksAndRejections (internal/process/task_queues.js:93:5)

}

How access Response in Express outside Route controller

I am using Express JS for backend API.

I need to simply use res object from custom service, not route controller.

Of course I am calling service function from controller and I know that I can easily pass res as an argument and access it, but I wonder if there is other case or maybe better practice.

const videoaskResponse = async (req, res, next) => {
  try {
    await webhookService.handleVideoaskResponse(req.body, res)

    res.status(200).json({ received: true })
  } catch (error) {
    next(error)
  }
}

Here’s example how I handle that case.

Cannot convert undefined or null to object in Next.js

Hey I am building a login page with Next.js and next-auth
I have also written in providers array in [...nextauth].js.

But when I run the code

import { getProviders, signIn } from "next-auth/react";

function Login({ providers }) {
  return (
    <div className="bg-black min-h-screen w-full flex justify-center items-center flex-col ">
      <img className="w-48 mb-5" src="/spot-it-aye.png" alt="" />

      {Object.values(providers).map((provider) => (
        <div key={provider.name}>
          <button
            className="bg-green-500 p-4 rounded-full hover:rounded-lg"
            onClick={() => signIn(provider.id, { callbackUrl: "/" })}>
            Login With {provider.name}
          </button>
        </div>
      ))}
    </div>
  );
}

export default Login;

export async function getServerSideProps() {
  let providers = await getProviders();

  return {
    props: {
      providers,
    },
  };
}

I get the

Unhandled Runtime Error

TypeError: Cannot convert undefined or null to object.

Any help would be appreciated.image

React Native app not showing information on Android from App.js

I got a problem.

I create a notification system in my react-native app to unify the design on Android and iOS.

So I implement the system in App.js and directly in RootContainer like that :

App.js

render () {
  return (
    <Provider store={context.store}>
      <RootContainer />
    </Provider>
  )
}

RootContainer

render() {
    return (
        <StyleProvider style={getTheme(material)}>
            <View style={styles.applicationView}>
                <NotificationToast 
                    message={this.props.infoNotif}
                    onTimeOut={() => this.props.initialDeleteInfoNotif()}
                />
                <StatusBar barStyle='light-content' />
                <ReduxNavigation />
            </View>
        </StyleProvider>
    )
}

So, the NotificationToast is my notification system. He will find this.props.infoNotif from my Redux.

In iOS, everything work perfectly, but on Android, anything happens.

And I don’t know why.

Copy and paste files in Firefox with javascript

Good morning.
I am trying to copy a file to a page that receives it, this works fine in chrome, edge and opera, but not in firefox….

The idea is to copy one or several files and to be able to paste them in the browser, the function below recognizes the paste effect, consults the clipboardData and inserts these images or videos in some input files.

The only browser that is not supported is Firefox, and version 83 of chrome as far as I have tested.


window.addEventListener("paste",copyPasteFunction); 

function copyPasteFunction(e){
        var fileInput = document.querySelector("input");
        if(e.clipboardData.files.length > 0){
            fileInput.files = e.clipboardData.files;
            $("input").eq(0).trigger("change");        
        }else{            
            console.log("%cFirefox or unsupported browser", "color:red");
        }
  }

¿Does anyone know of any other method to copy a file, paste it into a page and have it read and inserted into an input?

Thank you very much!

Codeigniter 4 call database inside javascript

I am new to codeigniter 4, and i am using javascript to display the error message using keyup function. The user should register unique username. how can i check the database if username is already taken?

note: without pressing the sign up button(I already try “rules”, but it is need to click the button). the error must display as long as he type his username. This is my EXAMPLE in matching password, and it is already done. myproblem now is checking the database username.

**myrepassword.onkeyup = function() {
  if(myrepassword.value.match(myInput.value)) {  
    repassword.classList.remove("invalid");
    repassword.classList.add("valid");
    document.getElementById("message_repsw").style.display = "none";
  } else {
    repassword.classList.remove("valid");
    repassword.classList.add("invalid");
    document.getElementById("message_repsw").style.display = "block";
    document.getElementById("repassword").innerHTML = "Password does'nt match"
  }
  
}**

How to parse React Typescript into jscodeshift code

Given the code snippet, including a simple tsx string of a React component:

// test.ts

    import j from "jscodeshift";

    const code = `
    const words: string[] = ["hello", "world"];
    
    export default function(){
        return <div>{words.map(word => <span>{word}</span>)}</div>;
    }
    `;

    const ast = j(code);

    console.log(ast.toSource());

When that file is executed with node ts-node test.ts it errors like this:

.../jscodeshift/node_modules/@babel/parser/src/parser/error.js:97
    const err: SyntaxError & ErrorContext = new SyntaxError(message);
                                            ^
SyntaxError: Const declarations require an initialization value (1:11)
...

How can I use the j options to use a parser that successfully parses the .tsx code?

I expect something like

const ast = j(code, { parser: something, plugins: [somethingElse]});

But I couldn’t make it work, so far

In Javascript two same looking strings are not equal?

I’m trying to compare two passwords , one from DB and other is user entered. The one from db is hashed and stored in binary format. So I have to conver it to string before comparing.

 console.log(
      user.PasswordHash.toString('base64') ===
        '$2a$10$UZptbo5h4lQFYmK352CPf.jDvPZh1pm3uC3Nb0wEVjF/RUCw2OU2G'
    ); //false

When I look in console user.PasswordHash.toString(‘base64’) evaluates to $2a$10$UZptbo5h4lQFYmK352CPf.jDvPZh1pm3uC3Nb0wEVjF/RUCw2OU2G which is the same value.

What is happening?

bcrypt.compareSync(
      password,
      user.PasswordHash.toString('base64')); //false

Any help is appreciated.

Maintain the odd/even table style after hiding tr from table

So I’ve created a JS function that filters specific rows in the table away, but since It’s only a hide/show filter, the odd/even rows gets mixed up.

This is how my JS filter works.

var hide_info_checkbox = document.getElementById("hide_info");
var hide_debug_checkbox = document.getElementById("hide_debug");

hide_info_checkbox.addEventListener('change', function() {
  var info_td = document.getElementsByClassName("info");
  if (this.checked) {
    for (var i = 0; i < info_td.length; i++) {
      info_td[i].classList.add("ftp_hide_row");
    }
  } else {
    for (var i = 0; i < info_td.length; i++) {
      info_td[i].classList.remove("ftp_hide_row");
    }
  }
});

hide_debug_checkbox.addEventListener('change', function() {
  debug_td = document.getElementsByClassName("debug");
  if (this.checked) {
    for (var i = 0; i < debug_td.length; i++) {
      debug_td[i].classList.add("ftp_hide_row");
    }
  } else {
    for (var i = 0; i < debug_td.length; i++) {
      debug_td[i].classList.remove("ftp_hide_row");
    }
  }
});
/*
    FTP styling
*/

.ftp_table {
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
  overflow-wrap: break-word;
}

.ftp_table tr:nth-child(even) {
  background-color: #d8d8d8;
}

.ftp_hide_row {
  display: none;
}
<input type="checkbox" id="hide_info" name="hide_info" value="hide_info">
<label for="hide_info"> Hide INFO</label>
<input type="checkbox" id="hide_debug" name="hide_debug" value="hide_debug">
<label for="hide_debug"> Hide DEBUG</label>
<table class="ftp_table" id="ftp_table">
  <tbody>
    <tr>
      <th>Log</th>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:15.946 INFO [conftest:101] -------------- Global Fixture Setup Started --------------</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:16.009 DEBUG [Geni:37] Initializing </td>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:16.059 INFO [ArtifactoryWrapper:21] Downloading</td>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:16.061 INFO [ArtifactHandler:55] Art</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:16.063 DEBUG [SessionManager:84] GET</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:16.070 DEBUG [connectionpool:227] Starting new HTTP connection (1)</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:17.422 DEBUG [connectionpool:452] 200 None</td>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:17.561 INFO [SessionManager:52] No application/json Content-Type header in GET response</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:17.422 DEBUG [connectionpool:452] 200 None</td>
    </tr>
  </tbody>
</table>

As you can see, the odd/even gets mixed up, since I only add a class which hides the rows, and doesn’t delete them:

enter image description here

Is there a way to fix this, so the odd/even is as expected?

Simplify lambda return value from spreading

If you’ve got something like this:

const someObjectArray = [
  {property: 'foo', property2: 'bar', property3: 'baz'},
  {property: 'fooDiff', property2: 'barDiff', property3: 'bazDiff'}
]

const someOtherObjectArray = someObjectArray
  .map(({property2, property3}) => ({property2, property3}))

Is there a kind of short-form-syntax to express this?

map(({property2, property3}) => ({property2, property3}))

AudioContext was not allowed to start in PlyrJs

I’m using PlyrJS with vimeo and it works just fine on PC but not mobile.

When I change devices in chrome dev tools to phone there is an error “The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page” that I can’t solve.

Important: I’m not trying to autoplay the video, only play on click. My html looks like this:

<div class="plyr__video-embed">
 <iframe src="https://player.vimeo.com/video/148751763" allow=""></iframe>
</div>

and the plyr-part script:

const players = Plyr.setup('.plyr__video-embed', {
    controls: [],
    ratio: '9:16',
    autoplay: false
});

Can someone give me a clue on how to fix this?

Create discord channel with specific roles js

let myRole = message.guild.roles.cache.find(role => role.name === "Admin");
  message.guild.channels.create(
                           channelName2, 
                          {
                            type: "GUILD_TEXT",
                            permissionOverwrites: [
                              {
                                id: myRole.id,
                                allow: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
                              },
                              {
                                id: myRole.id,
                                deny: ["VIEW_CHANNEL"]
                              }
                            ]           
                          }

Bot creates the text channel but has no permissions edited and it ignored almost whatever I write in “id: XXXXXX”