How to i render my detected URL to a hyperlink instead of plain text

I’m working on a chat application where users can message each other. I have used the anchorme library to detect links / URLs / Emails in text and convert them to clickable HTML which it does. But the detected URLs are not clickable it is just converted as plain
text. Is there a way to convert it to a hyperlink?enter image description here

  <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" href="css/styles.min.css">
    </head>
        <body>
        <div class="chat">
            <div id="sidebar" class="chat__sidebar">
    
            </div>
            <div class="chat__main">
                <div id="messages" class="chat__messages"></div>
    
                <div class="compose">
                    <form id="message-form">
                        <input name="msg" placeholder="Message" required autocomplete="off">
                        <button>Send message</button>
                    </form>
                    <button id="send-location">Send location</button>
                </div>
            </div>
        </div>
        <script id="message-template" type="text/html">
            <div class="message">
                <p>
                    <span class="message__name">{{username}}</span>
                    <span class="message__meta">{{createdAt}}</span>
                </p>
                <p>{{message}}</p>
            </div>
        </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.0.1/mustache.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.6.0/qs.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <script src="/js/chat.js"></script>
        <script src="https://raw.githack.com/alexcorvi/anchorme.js/gh-pages/dist/browser/anchorme.min.js"></script>
        </body>
        </html>
  Javascript client side:

    

> const socket = io()
>     
>     //Elements
>     const msg = document.querySelector('#message-form')
>     const messageFormInput = msg.querySelector('input')
>     const messageFormButton = msg.querySelector('button')
>     
>     //Templates
>     const messages = document.querySelector("#messages")
>     const messageTemplate = document.querySelector('#message-template').innerHTML
>     
>     
>     
>     //ref to index.js 
>     socket.on('message', (message) => {
>         const html = Mustache.render(messageTemplate, {
>             //will come from the value
>             username: message.username,
>             message: message.text,
>             createdAt: moment(message.createdAt).format('HH:mm')
>         })
>         messages.insertAdjacentHTML('beforeend', html)
>         scrollAuto()
>     })
>     
>     //Refers to html form input
>     msg.addEventListener('submit', (e) => {
>         //Prevents browser to update
>         e.preventDefault()
>     
>         messageFormButton.setAttribute('disabled', 'disabled')
>     
>         const message = e.target.elements.msg.value
>         socket.emit('sendMsg', message, (error) => {
>             messageFormButton.removeAttribute('disabled')
>             messageFormInput.value = ''
>             messageFormInput.focus()
>             //Enable after event acknowledged
>     
>             if (error) {
>                 return console.log(error)
>             }
>         })
>     })
>     
>     socket.emit('join', {
>         username,
>         room
>     }, (error) => {
>         if (error) {
>             alert(error)
>             location.href = '/'
>         }
> 
>     })
> 
Javascript server:
>     const path = require('path')
>     const http = require('http')
>     const express = require('express')
>     const socketio = require('socket.io')
>     
>     //Destructuring
>     const {
>         generateMessage,
>     } = require('./utils/messages')
>     
>     // Convert Urls
>     const anchorme = require("anchorme").default;
>     // Check for profanity
>     const Filter = require('bad-words')
>     //Initiate socket-io
>     const io = socketio(server)
>     
>     // Define path for Express config 
>     const publicDirectoryPath = path.join(__dirname, '../public')
>     app.use(express.static(publicDirectoryPath))
>     
>     //Server-side
>     io.on('connection', (socket) => {
>         console.log(' WebSocket Connection')
>     
>         // Listening for socket i.e messages
>         socket.on('sendMsg', (message, callback) => {
>             const user = getUser(socket.id)
>     
>             var result = anchorme(message, {
>                 attributes: [{
>                     name: "target",
>                     value: "_blank"
>                 }, ]
>             });
>             console.log(result)
>     
>             var filter = new Filter()
>             if (filter.isProfane(message)) {
>                 return callback('Profanity is not allowed')
>             }
>             io.to(user.room).emit('message', generateMessage(user.username, result))
>             callback()
>         })
>     })
> 
const generateMessage = (username, text) => {
>     return {
>         username,
>         text,
>         createdAt: new Date().getTime()
>     } }

Subquery returning different results when written as a function in TypeORM

I have a huge query that consists of 2 subqueries. Since I intend to use the subqueries at multiple places, I wanted to extract it as a function.

Here is the original query that works perfectly fine and returns expected results:

  public async findUsers(): Promise<UserEntity[]> {
    return this.createQueryBuilder('users')
        .andWhere('users.user_type = :userType', { userType: UserType.Parent })
        .andWhere(qb => {
          const subquery = qb
              .subQuery()
              .select('COUNT(*)')
              .from(EventEntity, 'e')
              .where('e.object_id = users.member_id')
              .andWhere('e.event_type = :eventType', { eventType: EventType.LOGIN })
              .getQuery();
          return subquery + '= 0';
        })
        .andWhere(qb => {
          const subquery = qb
              .subQuery()
              .select('COUNT(*)')
              .from(UserEntity, 'u1')
              .where('u1.primary_Id = users.member_id')
              .andWhere('u1.user_type = :userTypeChild', { userTypeChild: UserType.Child })
              .getQuery();
          return subquery + '= 0';
        })
        .getMany();
  }

However, when I try to put the subquery inside a function, it returns different results. Here is the query:

  public async findUsers(): Promise<UserEntity[]> {
    return this.createQueryBuilder('users')
        .andWhere('users.user_type = :userType', { userType: UserType.Parent })
        .andWhere(`(${this.subquerysql()}) > 0`)
        .andWhere(qb => {
          const subquery = qb
              .subQuery()
              .select('COUNT(*)')
              .from(UserEntity, 'u1')
              .where('u1.primary_Id = users.member_id')
              .andWhere('u1.user_type = :userTypeChild', { userTypeChild: UserType.Child })
              .getQuery();
          return subquery + '= 0';
        })
        .getMany();
  }

  private subquerysql(): string {
    const query = getConnection()
        .createQueryBuilder()
        .select('COUNT(*)')
        .from(EventEntity, 'e')
        .innerJoin('users', 'u','e.object_id = u.member_id')
        .andWhere(`e.event_type = 'LOGIN'`)
        .getSql();
    return query;
  }

Here is the error that I am getting:

I can’t seem to figure why the query isn’t working(when I put subquery inside a function). I am writing this inside userRepository

How to decide when to rerender in React

I’m creating a small project with the mern stack. In the homepage of this project, you can see the things that the current user has. THe problem is that the list can change in every moment, because other user can happend to that list other stuff. SO, to make it refresh, I put it in the useEffect hook. The problem now is that my server is reciving a tons of request, and always the same one. I don’t know if is the case to set a timer that rerender after x second, to make the work of my server lighter, or there is a way to remake the request to the server in some case. Here is the small code that manage the request:

    const [file, setFile] = useState([]);
    useEffect(() => {
        axios.post("http://127.0.0.1:5050/file/getfilesbycreator",{creator:localStorage.getItem('user')})
        .then(res => {
            setFile(res.data);
        })
        .catch(err => console.log(err))
    })

If someone has any suggestion, please tell me. I read something about rerender react, but I didn’t found out better way then a timer, or something similar.Thanks

Contact form 7 Ajax without JQuery

For optimization purposes, we have removed the use of jQuery. But we continue to use the Contact Form 7 to collect contacts. The form submits fine, but it does reload the page. How to make a custom Ajax dispatch for this form without using JQuery?

Reder only specific key value based on another key value with Javascript in React component

In my React application I need to grep the url with "type": "Three"?

How to find and return only specific key value based on another key value with Javascript?

From the api I get an array of images:

   "images": [
        {
          "url": "https:example/c18336d6-61ee-4c7c-be6b-397352b6fd63",
          "type": "One"
        },
        {
          "url": "https://example/c18336d6-61ee-4c7c-be6b-397352b6fd63",
          "type": "Two"
        },
        {
          "url": "https://example/c18336d6-61ee-4c7c-be6b-397352b6fd63",
          "type": "Three"
        },
      ]
    },

Then in my React component I want to use this value:

    const MyComponent = () => {

      const items =
        nodes.map((item) => {
            return {
              myImage: // Here I need e.g. the url value of the images array with type = Three.
            };
          }) || [];

   return <Slides items={items} />

  export default MyComponent;

How to expect the date to contain another date in Cypress?

This would be silliest question which I am asking here. I was going through Cypress automation and was working on one of the scenario.

I wanted to verify whether the date is matching or containing the date or not.

System date – 11/30/2021 06:18:33 PM and derived application date – 11/30/2021 6:18:38

How can I match and assert this using Cypress?

expect('11/30/2021 06:18:33 PM').to.have.string('11/30/2021 6:18:38');

I am getting below error :-

AssertionError

expected '11/30/2021 06:18:33 PM' to contain '11/30/2021 6:18:38'

MDC Web Textfield component outline disappearing

I am having an issue with MDC web textfield component. The issue is that the outline does not stay when I click on the textfield to type in an input. See below for the pug and javascript code :

div.mdc-layout-grid__cell--span-4.mdc-layout-grid__cell--span-12-phone.mdc-layout-grid__cell--span-12-tablet
  label.mdc-text-field.mdc-text-field--filled
    span.mdc-text-field__ripple
    span.mdc-floating-label(id="first_name") First Name :
    input.mdc-text-field__input(type="text" aria-labelledby="first_name")
    span.mdc-line-ripple
div.mdc-layout-grid__cell--span-4.mdc-layout-grid__cell--span-12-phone.mdc-layout-grid__cell--span-12-tablet
  label.mdc-text-field.mdc-text-field--outlined
    span.mdc-notched-outline
    span.mdc-notched-outline__leading
    span.mdc-notched-outline__notch
      span.mdc-floating-label(id="last_name") Surname :
    span.mdc-notched-outline__trailing
  input.mdc-text-field__input(type="text" aria-labelledby="last_name")
const textFields = [].map.call(document.querySelectorAll('.mdc-text-field'), function (el) {
    return new mdc.textField.MDCTextField(el);
});

const notchedOutline = [].map.call(document.querySelectorAll('.mdc-notched-outline'), function (el) {
    return new mdc.notchedOutline.MDCNotchedOutline(el);

});

const floatingLabel = [].map.call(document.querySelectorAll('.mdc-floating-label'), function (el) {
    return new mdc.floatingLabel.MDCFloatingLabel(el);

});

const lineRipple = [].map.call(document.querySelectorAll('.mdc-line-ripple'), function (el) {
    return new mdc.lineRipple.MDCLineRipple(el);

});
```[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/E8t9g.png

Type ‘string’ is not assignable to type ‘ undefined’

I have one React Component in which I am using useState hook.
I tried to set value to general onClick of menu item.

const [value,setValue]= useState("");

<Menu.Item onClick={()=>setValue("general"))>

</Menu.Item>

In another file I am passing that value.

<ChannelForm
   value={value}
/>

I am using TypeScript. Have declared prop type definition as

value?: "general" | "competitive" | "social" | "podcast";

But while passing value as a props I am getting above error.

Passing a variable to python using Ajax method

I want to pass a variable using Ajax from a JS function to a python function in my Django project.
I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs.
However how to I pass my variable through this ajax call? I just want to pass the local variable so it can be printed by the python function.

JS

function calling (){
    var local = 25
    
    $.ajax({
        type:'GET',
        url:'printsome/',
        success: function(response){
            console.log('success');
            console.log(local);
        },
        error: function (response){
            console.log('error');
        }
    });

}

python

def print_some(request):
    from django.http import JsonResponse
    print('this python function was called')
    return JsonResponse({})

Calculate duration startDate & endDate from an HTML form

Im wondering if anyone can point me to some documentation on how to solve my issue.
Still new at native JS, and looking to do some date calculations.

Basically I need to calculate the duration between X and Y dates from and HTML forms input type date.

I have a rough sketch of my HTML and JS..
but still I cannot solve the issue without propper guidance and documentation.

       <div>
          <form>
              <label for="start-date"></label>
              <input type="date" id="start-date">

              <label for="end-date"></label>
              <input type="date" id="end-date">

              <label for="duration"></label>
              <input type="text" id="duration">
         </form>
       </div>

    const startDate = document.getElementById("start-date").value
    const endDate = document.getElementById("end-date").value
    let duration_from_form = document.getElementById("duration").value

    let duration = endDate - startDate;


    if (duration_from_form === ""){
        duration_from_form = duration;
    }
}

I know both of them a rough mockups and not ideal, but I’d love some help finding propper documentation on this matter.
Kind regards

How to optimize router in nodejs koa?

I use koa to create a nodejs application, and I try to optimize.

app.js

'use strict';
const Koa = require("koa");
const Router = require("koa-router");
const router = new Router();

const stuff = require("./router/stuff.js");
router.use("/stuff", stuff.routes());
//more routers like above
const home = require("./router/home.js");
router.use(home.routes());

app.use(router.routes(), router.allowedMethods());
app.listen(port);

There’re some router files in folder router, such as stuff.js, home.js, client.js

stuff.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("stuff", {

        });
    })
module.exports = router;

home.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("home", {

        });
    })
module.exports = router;

client.js

'use strict';
const router = require("koa-router")();
router
    .get("/", async (ctx) => {
        await ctx.render("client", {

        });
    })
module.exports = router;

I think the way I wrote is still very amateurish, how to optimize it? Thank you.

Animating grid layout using CSS variables

I’m trying to animate a grid layout using transitions. As far as I can tell, this should be implemented: https://ishoudinireadyyet.com/

I even found a demo of this working: https://codepen.io/matuzo/post/animating-css-grid-layout-properties

But I cannot get it to work myself. What am I doing wrong? https://stackblitz.com/edit/gridlayout-animation?file=index.html

const toggleSidebar = () => {
  const layoutEl = document.querySelector('.layoutEl');
  const currentWidth = getComputedStyle(layoutEl).getPropertyValue('--collapse-panel-width');
  const isOpen = currentWidth == '30rem';
  layoutEl.style.setProperty('--collapse-panel-width', !isOpen ? '30rem' : '2rem');
};
@property --collapse-panel-width {
  syntax: '<length>';
  initial-value: 2rem;
  inherits: true;
}

.layoutEl {
  --collapse-panel-width: 2rem;
  display: grid;
  overflow: hidden;
  grid-template: 
    'header   header' auto 
    'content sidebar' 1fr 
    'footer   footer' auto 
    / 1fr var(--collapse-panel-width);
  gap: 0.3rem;
  height: 100vh;
  transition-property: all;
  transition-duration: 0.5s;
  transition-timing-function: ease-in-out;
}

header {
  grid-area: header;
  background-color: #0055ff;
  color: white;
}

main {
  grid-area: content;
}

aside {
  grid-area: sidebar;
  background-color: #0055ff;
  color: white;
}

footer {
  grid-area: footer;
  background-color: #0055ff;
  color: white;
}
<html>

<head>
  <meta charset="UTF-8" />
</head>

<body class="layoutEl">
  <header>Header</header>
  <main>
    <h1>Main content</h1>
    <button type="button" onclick="toggleSidebar()">Toggle sidebar</button>
  </main>
  <aside>Sidebar</aside>
  <footer>Footer</footer>
</body>

</html>

existe t-il un moyen de filtrer une table dynamiquement avec le nombre d’enregistrement a l’appuie

bonjour!!!
j’aimerais filtrer les elements de ma table et afficher dynamiquement le resultat. Je m’explique j”ai une table voiture avec 100 enregistrement qui contient les champs “couleur” “marque” “annee”. dans ma vue il a trois input et en dessous une div qui montre le nombre total d’enregistrement. S’il choisit couleur rouge par example alors il aura dans la div 48 enregistrement.a chaque fois qu’il selectionne un element.on lui retourne le nombre d’enregistrement correspondant. svp aidez moi

Javascript Determine if page was redirected by tag or window.location.href?

The question is pretty much the same as the title.

Is there a way in Javascript to determine whether the page has been redirected by < a href > HTML tag or by window.location.href?

I need conditions for clearing saved states of data-table:

on reload

and

on redirected via < a href > tag.

I don’t want to clear saved states for a redirection via window.location.href.

I got one on reload:

if (performance.navigation.type == 1){
      var table = $('#categoryList').DataTable();
      table.state.clear();
      table.search("").draw(); 
      table.column( '0:visible' ).order( 'asc' ).draw();
      table.page.len(10).draw();
    }

I’m looking for another one on redirected via < a href >.