Why my javascript throw me a ‘ReferenceError: Can’t find variable: exports’ error?

Why my javascript throw me a ‘ReferenceError: Can’t find variable: exports’ error?

I have two file (app.js, util.js)
compiled from ts (app.ts, __util.ts)

When I use import { Time } from “../website/util“;

vscode didn’t give me a error or warning

but when I run index.html (script src = website/tscache/app.js) on safari, and open inspect elements, I received error:

ReferenceError: Can't find variable: exports

When I open file app.js, I saw:

File is a CommonJS module; it may be converted to an ES module.ts(80001)
(property) __esModule: true

that made me confused, when I compile ts, I didn’t receive error, at app.js, it just a warning, when I run on browser, I received an error. And now I have no idea how to fix it.

Some Image:
enter image description here
enter image description here
enter image description here
enter image description here

How do I insertAdjacentHTML on querySelectorAll class? [duplicate]

I want to add HTML to all elements having same class (.testimonial-text). However Everytime I use querySelectorAll to define the elements, insertAdjacentHTML returns an error that say ‘insertAdjacentHTML in not a function’ . It works fine when I user querySelector (which targets only first element of the class) but again I want to target and insert html on every element of the class.

var testimonialText = document.querySelector(".testimonial-text");
const testimonialTextBack = function () {
  const html = `<p>Testing</p>`;
  testimonialText.insertAdjacentHTML("beforeend", html);
};
testimonialTextBack();

HTTP retrieval failure when creating drop-in audio chat using Twilio

I am leveraging the Twilio Programmable Voice API to create a drop in audio chat room when a user completes a signup form.

I am using ngrok to listen to both my React frontend app and Django backend app so I can expose my local server to the internet.

However, when I complete the form, I get the prompt to activate my mic and then hear the error Sorry, an application error has occurred, goodbye before my call drops. My Twilio error logs shows the error:

Error - 11200
An attempt to retrieve content from https://f5b7-104-182-176-156.ngrok.io/voice_chat/rooms/Emmanuel returned the HTTP status code 404
HTTP retrieval failure

Possible Causes
Web server returned a 4xx or 5xx HTTP response to Twilio
Misconfigured Web Server
Network disruptions between Twilio and your web server
No Content-Type header attached to response
Content-Type doesn't match actual content, e.g. an MP3 file that is being served with Content-Type: audio/x-wav, instead of Content-Type: audio/mpeg

When I do a GET on an endpoint that should show me all my rooms http://127.0.0.1:8000/voice_chat/rooms I get an empty list, indicating that no rooms have been created?

Here is my React code:

...
const NewRoom = () => {
    const [state, setState] = useGlobalState();
    const history = useHistory();
    const updateRoomName = (createdRoomTopic) => {
        setState({...state, createdRoomTopic});
    };

    const createRoomHandler = () => {
        const userData = {'roomName': state.nickname, 'participantLabel': state.createdRoomTopic}
        console.log('Inside create room handler', userData.roomName, userData.participantLabel)
        axios.post('http://127.0.0.1:8000/voice_chat/rooms/', userData )
            .then(res => {
                console.log('axios call has been hit', res.data)
            })
    }

    const handleRoomCreate = () => {
        const selectedRoom = {
            room_name: state.createdRoomTopic, participants: []
        };
        const rooms = state.rooms;
        const roomId = rooms.push(selectedRoom);
        setState({...state, rooms });
        setState({...state, selectedRoom});
        createRoomHandler()
        history.push(`/rooms/${roomId}`);
    };

    return (
        <div>
            <input
                placeholder="Enter room topic..."
                onChange={ e => updateRoomName(e.target.value)}
            />
            <button onClick={handleRoomCreate}>
                Start room</button>
        </div>
    );
};

my urls.py:

urlpatterns = [
    path("rooms", RoomView.as_view(), name="room_list"),
    path("token/<username>", TokenView.as_view(), name="rooms"),
]

and my RoomView:

@method_decorator(csrf_exempt, name="dispatch")
class RoomView(View):
    def get(self, request, *args, **kwargs):
        rooms = client.conferences.stream(
            status="in-progress"
        )
        rooms_reps = [
            {
                "room_name": conference.friendly_name,
                "sid": conference.sid,
                "participants": [
                    p.label for p in conference.participants.list()
                ],
                "status": conference.status,
            } for conference in rooms]
        return JsonResponse({"rooms": rooms_reps})

    def post(self, request, *args, **kwargs):
        room_name = request.POST.get("roomName", "default")
        participant_label = request.POST.get("participantLabel","default")
        response = VoiceResponse()
        dial = Dial()
        dial.conference(
            name=room_name,
            participant_label=participant_label,
            start_conference_on_enter=True,
        )
        print(dial)
        response.append(dial)
        return HttpResponse(response.to_xml(), content_type="text/xml")

Would appreciate any help

guildMember is not defined

I was trying to do make welcome message when someone gets on my server but I am trying to do so it takes embed from another file. It says guildMember is not defined and I understand that but I don’t know how to define it.

Here is my index.js:

const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log('Hosted site'));

const { Client, Intents } = require('discord.js');
const Discord = require('discord.js');
const variable = require('./commands/variable');
const welcome = require('./commands/welcome');

const mongoose = require('mongoose');
mongoose.connect(process.env['mongo'], { useNewUrlParser: true, useUnifiedTopology: true }).then(console.log('Mongo is connected!'))

const fs = require('fs');
const prefix =  ('m?');

const client = new Client({
    intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
    partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});



client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(File => File.endsWith('.js'));
for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  client.commands.set(command.name, command)
}

client.once('ready', async () => {
  console.log('MBot is ready!');
  
client.user.setActivity("Vedad", {
  type: "LISTENING"
});
});

client.on('guildMemberAdd', guildMember => {

guildMember.guild.channels.cache.get('975033510186324069').send(welcome.wlc)
  
})


client.on('message', message => {

  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

   if (command === 'wlcmsgid') {
    client.commands.get('wlcmsgid').execute(message, args, Discord, client);}
     
    else if (command === 'ping') {
    client.commands.get('ping').execute(message, args, Discord, client);}
  
})

client.login(process.env['token']);

here is welcome.js file:

const Discord = require('discord.js');
const variable = require('./variable');

module.exports.wlc = new Discord.MessageEmbed()
        .setColor('#000000')
.setDescription(`━━━━━━━━━━━━━━━━━━━━━━━━
        
        Welcome <@${guildMember.user.id}> to **GhostCommunity!** 
        
        ━━━━━━━━━━━━━━━━━━━━━━━━`)

Here is my console error:

ReferenceError: guildMember is not defined
    at Object.<anonymous> (/home/runner/MBot-1/commands/welcome.js:8:21)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/home/runner/MBot-1/index.js:10:17)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

I just can’t figure out how to define guildMember in welcome.js. Please help, thank’s

does not work, please help me to solve the problem

Create a JavaScript function which converts the given array of numbers to an array of booleans. Each element is true if the number is a prime number, and false otherwise.

For example:

primeValues([4, 2, 7, 10, 13]) // result: [false, true, true, false, true]
primeValues([17, 3, 21]) // result: [true, true, false]

Sort JSON values in descending order and turn results in a text

So I got a .json file which has following written in it:

{
"a": "10",
"b": "59",
"c": "581",
"d": "1"
}

And I want the 3 highest ones (581, 59, & 10) to be converted into a text in descending order so it looks like this:

1. c - 581
2. b - 59
3. a - 10

So i can just display the top 3 in the console window like console.log(order);
I haven’t written any proper code which I can provide so I am very sorry.

Find a javascript fix pattern

If I have many javascript files, one of which has code with an error and the other without, how can I find the difference between them in order to find a pattern of fixing for all of them?
 
For example, if I have this source code: 
var x = whatever;
if (x === Nan) {//} eslint will throuth an error saing use-isnan so to fix it, I have the target code: 
var x = whatever;
if (isNan(x)) {}
 
 

Form input checkbox and file type isn’t functioning

I’m trying to make a form for adding a blog page.

I have title form, date form, content form, checkbox for blog category form and image form for the topic image.

When I try to fill the form, only the 3 of the 4 checkbox forms that worked and when I click upload image it won’t show the file selector.

Here’s the screenshot:
Form screenshot

This is what I’m trying to achieve:
Form screenshot

I’ve tried to browse for solution but my English isn’t very good for browsing, I don’t know the keyword to search for the solution.

Please help, I’ve stuck on this for 3 hours.

Here’s the full code:

let blogs = []

function addBlog(event) {
    event.preventDefault()

    let inputName = document.getElementById("inputProjectName").value
    let inputContent = document.getElementById("inputDescription").value
    let inputImage = document.getElementById("inputImage")

    const projectDate = {

        startDate: document.getElementById("inputStartDate").value,
        endDate: document.getElementById("inputEndDate").value
    }

    image = URL.createObjectURL(image.files[0])

    let cardIcons = {
        html: document.querySelector('input[name="checkHtml"]').checked,
        css: document.querySelector('input[name="checkCss"]').checked,
        nodeJs: document.querySelector('input[name="checkNode"]').checked,
        reactJs: document.querySelector('input[name="checkReact"]').checked
    }

    let blog = {
        title: inputName,
        date: projectDate,
        content: inputContent,
        icons: cardIcons,
        image: inputImage
    }

    blogs.push(blog)

    console.table(blogs)
}
/* FORM */

.mpi-title {
    width: 100%;
    margin: 50px 0px;
    font-size: 30px;
    text-align: center;
    font-family: 'Lato', sans-serif !important;
    font-weight: 700;
}

.mpi-form-container {
    display: flex;
    justify-content: center;
}

.mpi-form {
    width: 540px;
    display: flex;
    justify-content: center;
}

.mpi-form label {
    font-size: 25px;
    font-weight: bold;
}

.mpi-form .mpi-name input,
.mpi-date input {
    width: 100%;
    height: 50px;
    padding: 5px;
    box-sizing: border-box;
    font-size: 20px;
    font-weight: 400;
    padding-bottom: 5px;
    margin-top: 5px;
    margin-bottom: 20px;
    border: 1px solid #c4c4c4;
    border-radius: 8px;
    box-shadow: 0 5px 5px rgb(0 0 0 / 26%);
}

.mpi-date {
    flex-grow: 1;
    display: flex;
    gap: 10px;
}

.mpi-date .date-start {
    flex: 50%;
}

.mpi-date .date-end {
    flex: 50%;
}

[type="date"]::-webkit-datetime-edit {
    opacity: 0;
}

[type="date"]::-webkit-calendar-picker-indicator {
    opacity: 0;
    width: 100%;
}

.mpi-desc textarea {
    width: 100%;
    font-size: 20px;
    font-weight: 400;
    padding: 8px;
    margin-top: 5px;
    margin-bottom: 20px;
    border: 1px solid #c4c4c4;
    box-sizing: border-box;
    border-radius: 8px;
    height: 200px;
}

.mpi-check {
    display: flex;
    gap: 120px;
    margin: 20px 0px;
}

.mpi-check label {
    font-size: 20px;
}

.check-left {
    display: flex;
    flex-direction: column;
    row-gap: 20px;
}

.check-right {
    display: flex;
    flex-direction: column;
    row-gap: 20px;
}

.check-label {
    display: block;
    position: relative;
    padding-left: 35px;
    color: #514a4a;
    margin-bottom: 12px;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.check-label input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
}

.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 5px 5px rgb(0 0 0 / 26%);
}

.check-label:hover input~.checkmark {
    background-color: #ccc;
}

.check-label input:checked~.checkmark {
    background-color: #2196F3;
}

.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

.check-label input:checked~.checkmark:after {
    display: block;
}

.check-label .checkmark:after {
    left: 9px;
    top: 5px;
    width: 5px;
    height: 10px;
    border: solid white;
    border-width: 0 3px 3px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

.mpi-image {
    overflow: hidden;
    height: 50px;
    width: 100%;
    font-size: 20px;
    font-weight: 400;
    box-sizing: border-box;
    margin-top: 5px;
    margin-bottom: 20px;
    background: #f4f3f3;
    border: 1px solid #c4c4c4;
    border-radius: 8px;
    cursor: pointer;
    padding-right: 8px;
    box-shadow: 0 10px 10px rgb(0 0 0 / 26%);
}

.mpi-image label {
    width: 100%;
    height: 50px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.mpi-choose {
    margin-top: -2px;
    border-radius: 8px;
    align-items: center;
    padding: 13px 10px 13px 10px;
    background-color: #e4e4e4;
    color: #b2abab;
}

.mpi-attach {
    padding-right: 10px;
}

.mpi-submit button {
    margin-top: 30px;
    float: right;
    padding: 10px 30px;
    border: none;
    border-radius: 25px;
    background-color: var(--btn);
    color: white;
    font-size: 15px;
    font-weight: bold;
    cursor: pointer;
    margin-bottom: 110px;
}

.mpi-submit button:hover {
    background-color: var(--btn-hover)
}


/* x FORM */
        <div class="mpi-form">
            <!--MP = My Project Input-->
            <form onsubmit="addBlog(event)">
                <div class="mpi-name">
                    <label for="inputProjectName">Project Name</label>
                    <input type="text" id="inputProjectName">
                </div>
                <div class="mpi-date">
                    <div class="date-start">
                        <label for="inputStartDate">Start Date</label>
                        <input type="date" id="inputStartDate">
                    </div>
                    <div class="date-end">
                        <label for="inputEndDate">End Date</label>
                        <input type="date" id="inputEndDate">
                    </div>
                </div>
                <div class="mpi-desc">
                    <label for="inputDescription">Description</label>
                    <textarea name="inputDescription" id="inputDescription"></textarea>
                </div>
                <div class="mpi-check-cont">
                    <label for="checkTitle">Technologies</label>
                    <div class="mpi-check">
                        <div class="check-left">
                            <div>
                                <label for="checkHtml" class="check-label">HTML
                                    <input type="checkbox" id="checkHtml" name="checkHtml"check>
                                    <span class="checkmark"></span>
                                </label>
                            </div>
                            <div>
                                <label for="checkNode" class="check-label">Node Js
                                    <input type="checkbox" id="checkNode" name="checkNode">
                                    <span class="checkmark"></span>
                                </label>
                            </div>
                        </div>
                        <div class="check-right">
                            <div>
                                <label for="checkCss" class="check-label">CSS
                                    <input type="checkbox" id="checkCss" name="checkCss">
                                    <span class="checkmark"></span>
                                </label>
                            </div>
                            <div>
                                <label for="reactJs" class="check-label">React Js
                                    <input type="checkbox" id="checkReact" name="checkReact">
                                    <span class="checkmark"></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <label>Upload Image</label>
                    <div class="mpi-image">
                        <label for="input-blog-image">
                    <div class="mpi-choose">Choose</div>
                    <div class="mpi-attach"><i class="fa-solid fa-paperclip"></i></div>
                    </label>
                        <input type="file" id="inputImage" hidden />
                    </div>
                </div>
                <div class="mpi-submit">
                    <button type="submit">Submit</button>
                </div>
            </form>

Thanks

I want to highlight the Specific word in my ajax response loop

I want to highlight the word which user has searched. I am getting an array in response which will shows the occurrence of that word.
I want to highlight that word inside my array which I received.

 success:function(response){
                     console.log(response); 
                      $("#h5data").append(sessionStorage.getItem("word"));
                      $("#WC").append(response.doc.count);

                      $.each(response.doc.occurrence, function (key, value) {  
          $('#exampleid').append("<tr>
                <td>"+key+"</td>
                <td>"+value+"</td>
                </tr>");


        });

This is my ajax response which is showing the occurrence but now I have to highlight the word which user has searched.

Create a new Date for any specific timezone

I am using Google Apps Script to check and re-format date data from some Google Sheets. But the problem is the result shows the times for the user who run the code. I want to show the date for any specific time zone. How is it possible?

Suppose, my input is checkDate('14/5/2022'); and it returns the date
object for that time zone instead of my time zone.

Here is my code:

/**
 * This will return a JS Date object with a valid date input.
 * Unless this will return a false status
 */
function checkDate(input) {
  // const timeZone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
  if (input instanceof Date && !isNaN(input)) {
    // will execute if a valid date
    return input;
    
  } else {
    // If not a valid date
    const splitter = input.indexOf('/') === -1 ? '-' : '/';
    const dateArr = input.split(splitter);

    if(dateArr.length === 3) {
      const year = dateArr[2].length === 2 ? '20' + dateArr[2] : dateArr[2];
      const NewTime = new Date(Date.UTC(year, dateArr[1]-1, dateArr[0], 0, 0, 0));

      return NewTime;
    } else {
      return false;
    }
  }
}

console.log(checkDate(new Date()));
console.log(checkDate('14/5/2022'));

Expected input
checkDate('14/5/2022') and timeZone = 'GMT+1;

Expected Output
2022-05-14T00:00:00.000 french time. Not the UTC time.

Is it possible?

Assign value only when key is a valid property of a type in TypeScript

I have a type, e.g.:

type Output = {
    fieldA?: string;
    fieldB?: string;
}

And I have an object, e.g.:

const input = { fieldA: "A", fieldB: "B", other: "C" };

Now I want to map the value to another object of type Output, so I want to loop through the object keys and assign only when the key is a valid property of type Output, e.g.:

let output: Output = {};
Object.keys(input).forEach(k => {
    if (k is keyof Output) {
        output[k] = input[k];
    }
});

How do you achieve the above?

How to add a hover effect with dynamic styles to a component element?

I have this component where hover effect is currently applied with pseudo-class :hover in .scss file. But I want to apply the hover effect with dynamic values.

So suppose if I want the element’s background to change on hover, the current css looks like this:

.element {
     display: flex;
     justify-content: center;

     &:hover {
          background-color: red;
     }
}

But now I want the hover background color to have dynamic values that is available inside the component provided by the user from the UI so the color could be anything. Another thing which I also want to achieve is to add a class to the element when it is selected. What I mean is when hovered, the background will change to a dynamic value but if the element is selected, that same color will be the background color. And if unselected, it will go back to the original color.

I’m new to Angular so I’m not sure how to achieve this. Anyone can help me?

Why doesn’t setting NodeJS module cache to false get NodeJS to reload module?

I have 2 files, one named one.js and other name first.js.
one.js

var first = require("./first.js")
require.cache[first.module.id].loaded=false
require("./first.js")

first.js

console.log("First is running");
module.exports={module}

It’s output is:

First is running

and not

First is running
First is running

as I expected. Why is it that even though I set the loaded property of the first.js module to false, it is still not being reloaded?

Learning Typescript: object passed into a async function and then renaming one of the props of the object [duplicate]

I have this code I am using in my Javascript version of the application.
Basically I am passing this object

{
email,
password
}

to a async function.
Then the conveniently rename the email property to identifier

I wrote the code below:

// Login user
    const login = async ({ email: identifier, password }) => {
        console.log('login of AuthContext.js')
        console.log({ identifier, password })

        const res = await fetch(`${NEXT_URL}/api/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                identifier,
                password,
            }),
        })

        const data = await res.json()
        console.log('data of AuthContext.js', data)

        if (res.ok) {
            console.log('res.ok of login')
            setUser(data.user)
            router.push('/account/dashboard')
        } else {
            console.log('else of login')
            console.log('data', data)
            setError(data.message)

            // setError(null)
        }
    }

How to convert async ({ email: identifier, password })
into Typescript????