How to conditionally/lazy load a component in Qwik JS?

I am currently trying to develop a qwik app. I have a component, which returns a button, and a calender which should only be shown and rendered when this button is hovered. When I try to just import the component at the top of the file and render it like this:
{showCalender.value && < Calender />}
Qwik throws an error, saying that it couldnt resolve a file:
Failed to resolve import “../../calender_component_sqbjiybb91y.js”

But this isnt the file which I am trying to import, so I thought it must be, that qwik cant just render a component in the middle of the program after the main component is rendered.

To fix this, I tried to use a async function which looks like this:

const store = useSignal<any>(null);

const loadAndShowComponent = $(async () => {
    if (!store.value) {
        const module = await import('./calender');
        store.value = module.Calender;
    }
});

This function is then called when the button is hovered like this:

<button id="calenderView" class="mainEl" onMouseEnter$={async () => {
    showCalender.value = true

    loadAndShowComponent();

}} onMouseLeave$={() => {showCalender.value = false}}>
</button>

I expected, that this would fix the problem and import and render the component when the button is hovered, but instead it throwed the same error.

What am I missing? Which concept of qwik applies here?

How to show random book of the day? [closed]

I have 500 books. I want to get the book of the day. Every day I want to show a different book. When the number of books reaches 500, I want to reset back to ID 1. How can I randomly select a book from a list of 500 books so that I show a different book each day? I wanted to do something like book id % DATE NUMBER == 0 but I only have 500 books so that won’t work. Does anyone have any clue how to do this using javascript?

Is there a way of converting JavaScript to jquery for onclick functions

Iam using framework 7 and have been trying to embed JavaScript chat script by converting to jquery the problem is that framework 7 does not accept on click function in pure JavaScript

<div class="uRow" id="usr<?=$uid?>" onclick="msg.show(<?=$uid?>)"> <div class="uName"><?=$u["user_name"]?></div> <div class="uUnread"><?=isset($u["unread"])?$u["unread"]:0?></div> </div>

It shows this error = msg not defined, So what i have been trying to do is to convert the entire javascript code to jquery
So my problem is to change this div class function to jquery function and make it to match the jquery code .
So I have try to use this method I found on the internet

<div id="myDiv">Some Content</div>
$('#myDiv').click(divFunction);
function divFunction(){
 //some code
}

but get stuck on how to include the php values
to jquery but cannot figure how to go on about it. I am in need of assistance please
Here is my script

                        var msg = {

                  // (B) SHOW MESSAGES
                  
                  uid : null,  // current selected user
                  show : uid => {
                    // (B1) SET SELECTED USER ID
                    msg.uid = uid;

                    // (B2) GET HTML ELEMENTS
                    let hForm = document.getElementById("uSend"),
                        hTxt = document.getElementById("mTxt"),
                        hUnread = document.querySelector(`#usr${uid} .uUnread`),
                        hMsg = document.getElementById("uMsg");

                    // (B3) SET SELECTED USER
                    for (let r of document.querySelectorAll(".uRow")) {
                      if (r.id=="usr"+uid) { r.classList.add("now"); }
                      else { r.classList.remove("now"); }
                    }
                  },
                  
                };
`

convert JSON with a regex [duplicate]

  {
    "Id": 46,
    "Catnaam": "salontafels",
    "ParentId": 36,
    "Overzichtsafb": null
  },
  {
    "Id": 47,
    "Catnaam": "ronde salontafels",
    "ParentId": 46,
    "Overzichtsafb": null
  },
  {
    "Id": 48,
    "Catnaam": "houten salontafels",
    "ParentId": 46,
    "Overzichtsafb": null
  },

I have JSON structure as shown above but what I want is the following:

  {
    Id: "46",
    Catnaam: "salontafels",
    ParentId: "36",
    Overzichtsafb: null
  },
  {
    Id: "47",
    Catnaam: "ronde salontafels",
    ParentId: "46",
    Overzichtsafb: null
  },
  {
    Id: "48",
    Catnaam: "houten salontafels",
    ParentId: "46",
    Overzichtsafb: null
  },

In Javascript I receive the JSON structure after calling a webmethod. There, I try to convert this JSON to what I want using a regular expression:

arr = arr.replaceAll(""([A-Za-z]*)":", "$1:");

But apparently, the regex doesn’t work, as the same JSON is returned from the regex. Does somebody have a suggestion about the regex I could use?

How do I save data in express.js and show it in the webpage without a database?

So I am doing this project and I have to make a website in which i can create blog text posts, and then show those posts to access what i posted. I am using html css js node.js, ejs and express.js, I cant use a database so how should I do this?

Currently I have made a website and i can show the inputs after the post button is pressed, but when i refresh the page, data goes away and i have to do it over again.

Is there any logic I can use to make this happen?

`app.post("/submit", (req, res) => {
    console.log(req.body);
    const articles = req.body.post
    res.render("index.ejs", {data: articles});

});`

“file:” is automatically added to the dependencies of the package.json

I don’t know why but when I save my files the package.json will automatically add a dependency like this:
"backend-project-test-name": "file:",

"dependencies": {
    "bcryptjs": "^2.4.3",
    "backend-project-test-name": "file:",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "jsonwebtoken": "^9.0.2",
    "moment": "^2.30.1",
    "mongoose": "^8.6.0",
    "multer": "^1.4.5-lts.1",
    "uuid": "^10.0.0",
    "yup": "^1.4.0"
  },

I tried to remove it many times but it keeps coming back

Chrome Native Messaging – Problems with communicating with C# native application

I am writing a Chrome Extension which communicates with a native application via Native Messaging.

In my background script I’ve included the following to send a string to the native application:

            let port = chrome.runtime.connectNative('com.camou')
            console.log(port)
            port.postMessage({ text: "invisible" })
            port.onMessage.addListener(function (msg) {
                console.log('Received' + msg);
            });

In my native C# application, I’ve included the following:



                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    _ = NativeMethods.SetConsoleMode(NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE), NativeMethods.ENABLE_BINARY_MODE);
                    _ = NativeMethods.SetConsoleMode(NativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), NativeMethods.ENABLE_BINARY_MODE);
                }

                Stream stdin = Console.OpenStandardInput();
                int length = 0;
                byte[] bytes = new byte[4];
                stdin.Read(bytes, 0, 4);

                // Convert the 4 bytes to an integer (message length)
                if (BitConverter.IsLittleEndian)
                {
                    length = BitConverter.ToInt32(bytes, 0);
                }

                // Ensure the message length does not exceed 1024*1024
                if (length > 1024 * 1024)
                {
                    // Print error message to stderr
                    Console.Error.WriteLine("Message length exceeds maximum allowed size.");
                    return;
                }

                byte[] messageBytes = new byte[length];
                int bytesRead = 0;
                while (bytesRead < length)
                {
                    int read = stdin.Read(messageBytes, bytesRead, length - bytesRead);
                    if (read == 0)
                    {
                        Console.Error.WriteLine("Unexpected end of stream.");
                        return;
                    }
                    bytesRead += read;
                }

                // Convert bytes to string using UTF-8 encoding
                string input = Encoding.UTF8.GetString(messageBytes);
                Console.WriteLine("Received message: " + input);
                SendResponseToChrome("Hello from native app!");
                

I’ve registered the native application and the native application starts up when the port.postMessage is called but with an error “Unchecked runtime.lastError: Error when communicating with the native messaging host.”.

I’ve looked at previous answers (e.g. How to get Chrome Native Messaging to Listen to application?) and tried to mimic what other posters are doing, but they somehow do not work for me. Please let me know if you’re able to spot where I’ve gone wrong.

I gather from the error message that I’ve made a mistake in my C# application (particularly when trying to parse the message from the background script) but I can’t identify the error specifically.

Thanks!

Graph – Identify looping path

I need some help with a Graph that may have a looping path.
The graph is built in jsPlumb, but I’d also be happy to get a general idea of ​​the solution.

The graph represents some flow/path for incoming phone call.
Each node represents an action to be triggered and can have [0,1,2,…] next and/or previous nodes.

enter image description here

The issue is to check that all possible paths from the starting node to the last node contain, at least, one specific node (by action type).
For example: each Call was assigned to some Model before other actions were activated.

Recursion from end nodes failed in case of a path loop. And I have no idea how to solve this problem

Cannot get response from an API call in the express.js backend

I want to make an API call from my backend server running express.js. I expect when I visit http://localhost:3004/api/weather?city=[cityName], I should see the json response from openweathermap.org.
Instead, I get the message “unknown endpoint” from my middleware. Thats the terminal output from the server:

Time: 2024-09-08T08:02:14.510Z
Method: GET
Path:   /api/weather
Query:  { city: 'zagreb' }
Headers: {
  host: 'localhost:3004',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
  'sec-ch-ua-mobile': '?0',
  'sec-ch-ua-platform': '"macOS"',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  'sec-fetch-site': 'none',
  'sec-fetch-mode': 'navigate',
  'sec-fetch-user': '?1',
  'sec-fetch-dest': 'document',
  'accept-encoding': 'gzip, deflate, br, zstd',
  'accept-language': 'en,de-DE;q=0.9,de;q=0.8,fr-FR;q=0.7,fr;q=0.6,en-US;q=0.5,hr;q=0.4,nl;q=0.3',
  cookie: 'Webstorm-8aead92d=3b86ad4a-0728-412a-9b16-792fba3736a2'
}
Body:   {}
IP:     ::1

Here is my code for the Route:

require('dotenv').config()
const weatherRouter = require('express').Router()
const axios = require('axios')

const apiKey = process.env.API_KEY

weatherRouter.get('/api/weather', async (req, res, next) => {
    const { city } = req.query
    if (!city) {
        return res.status(400).json({ error: 'City must be provided' });
    }
    try {
        console.log(`Fetching weather data for ${city}`);
        const response = await axios.get(`http://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=5&appid=${apiKey}`);
        res.json(response.data);
    } catch (error) {
        res.status(500).json({ error: 'Failed to fetch weather data' });
    }
    next()
})

module.exports = weatherRouter

The final goal is, that I make the request from a form from the frontend running react.js. This currently does not work either.
That is the code I wrote on the frontend to link it to with be backend:

import axios from 'axios'
const baseUrl = '/api/weather'

const getWeatherData = async city => {
    const response = await axios.get(`${baseUrl}?city=${city}`)
    return response.data
}

export default { getWeatherData }

Can anyone tell me what I am doing wrong?

How can I add preloader in my custom wordpress theme?

I’m trying to add preloader on my theme. When I’m using this code in functions.php then It work fine. But I’m not interest use CSS & JS on functions.php

Please help me.

add_action('init', 'Devnuru_Preloader');
function Devnuru_Preloader()
{
  if (! is_admin() &&  $GLOBALS["pagenow"] !== "wp-login.php") {

    $delay = 1;  //seconds
    $loader = 'http://devnuru.local/wp-content/uploads/2024/09/devnuru-spinner.svg';
    $overlayColor = '#ffffff';
    echo '<div class="Preloader"><img 

src="' . $loader . '" alt="" style="height: 150px;"></div>

 <style>
.Preloader {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: ' . $overlayColor . ';
  z-index: 100000;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>

<script>
document.body.style.overflow = "hidden";
document.addEventListener

("DOMContentLoaded", () => setTimeout( function() { 

document.querySelector("div.Preloader").remove(); 

document.body.style.overflow = "visible"; } , ' . $delay . ' * 1000));
</script>
';
  }
}

When I’m putting HTML Code in my footer & CSS code in my main CSS file & JS code in JS file then It’s not working.

Custom Masking PhoneField component in React

I need to create a phone field component that supports custom phone number masks and includes the country code. Do you have any suggestions for a library that could help with this? If you have alternative ideas, I’d appreciate the help.

Explanation: In certain applications, the phone input field needs to accommodate various phone number formats depending on the country, including the country code (e.g., +1 for the US). A library that supports custom phone number masks would allow the field to automatically format numbers as they’re being typed (e.g., (123) 456-7890), and still account for variations in different countries.

This feature is important for improving user experience, ensuring consistency, and validating the entered phone numbers effectively. I’d like to know if there’s a preferred library or approach you recommend for building this.

I have tried using react-phone-input-2, but I was only able to mask the phone numbers, not the country code.

Why does going to the empty route create 2 requests in Express?

Here is my code:

const express = require('express')
const app = express()

let counter = 0

app.use((req, res, next) => {
    counter ++
    console.log(counter + ' request fulfilled');
    console.log(req.url)
    next()
})

app.get('/check1', (req, res) => {
    res.send('Got a new request')
})

app.get('/check', (req, res) => {
    res.send('You got back')
})

app.listen(3000, () => {
    console.log('Listening on port 3000');
})

I am just learning, so it might be silly question, but I do not understand, why if I am going from “localhost:3000/check” to “localhost:3000/chec”(non-existing route) my app.use() counts it as 2 requests?

Here is my console output with surfing the routes:

PS E:CodeStuding004 Server-Express> node .index.js
Listening on port 3000
1 request fulfilled
/check
2 request fulfilled
/check1
3 request fulfilled
/check
4 request fulfilled
/chec
5 request fulfilled
/chec

As you can see /chec request was called twice, eventhough I moved to the URL once.

Changing the playback rate in Wavesurfer on iOS produces choppy, glitchy sound

Description of the issue

My simple set up to let the user change the playback speed in Wavesurfer works like a charm on my computer (Chrome, Monterey, MacBook Pro), but it breaks on my mobile, when accessing my website, a Django project hosted on Heroku. The sound is fine as long as I keep a 1.00 x speed, but changing it wreaks havoc: the sound becomes choppy, glitchy, jerky.

The issue seems to lie in the audioContext manipulation that changes the volume of the different channels: if, in the code quoted below, I don’t call changeChannelVolume(), changing the playback rate doesn’t cause any problem. The speed example, where no audioContext, splitter or merger are created, works well with an audioRate different than 1. Again, all of this refers to my iPhone, I don’t experience any issue on my desktop browser.

  • Whether I pass “audioRate: 2” as an option to the Wavesurfer creator, or set “audio.playbackRate = 2” doesn’t make a difference.
  • Nor specifying “backend: WebAudio”

If you could help me fix this, I would be very grateful!

Reproducing the issue

On my phone, going to https://wavesurfer.xyz/examples/?webaudio.js and adding to the settings “audioRate: 2” causes the same behaviour as in my project, while everything works fine on my computer. Along the same lines, I tried audio.playbackRate = 2. That works on my computer, but causes the same issue on my cellphone.

Audio file format used

WAV, MP3, FLAC

System

Chrome, Safari, Firefox, iOS 17.6.1, iPhone 12 mini

Relevant code snippets

If more is needed I’ll be happy to share other parts of the code, but because the problem happens on one of the official examples, I don’t think this is necessary):

const audio = new Audio()
audio.controls = true
// Assuming only one audio file
{% for audio_file in track.get_audio_files %}
audio.src = '{{ audio_file.url }}'
{% endfor %}
const audioContext = new AudioContext()

const waveforms = [
    {% for audio_file in track.get_audio_files %}
        WaveSurfer.create({
            container: '#waveform-{{ forloop.counter }}',
            splitChannels: [
                {
                    waveColor: "rgba(255, 255, 255, 0.7)"
                },
                {
                    waveColor: "rgba(255, 255, 255, 0.7)"
                },
                {
                    waveColor: "rgba(255, 255, 255, 0.7)"
                }
            ],
            barWidth: 5,
              // Optionally, specify the spacing between bars
            barGap: 5,
              // And the bar radius
            barRadius: 2,
            plugins: [regions, hover]
            hideScrollbar: false,
            media: audio,
            audioRate: 1,
            normalize: true
        })
    {% endfor %}
];

function changeChannelVolume(audio) {
    const mediaNode = audioContext.createMediaElementSource(audio)

    // Create a splitter node that can split into 3 channels
    const splitter = audioContext.createChannelSplitter(3);

    // Create gain nodes for each channel
    const channel1Gain = audioContext.createGain();
    const channel2Gain = audioContext.createGain();
    const channel3Gain = audioContext.createGain();

    // Create a merger node to combine the 3 channels back into the audio stream
    const merger = audioContext.createChannelMerger(3);

    // Connect the splitter to the gain nodes
    splitter.connect(channel1Gain, 0);  // First channel
    splitter.connect(channel2Gain, 1);  // Second channel
    splitter.connect(channel3Gain, 2);  // Third channel

    // Connect the gain nodes to the merger
    channel1Gain.connect(merger, 0, 0); // Channel 1 to input 1 of merger
    channel2Gain.connect(merger, 0, 1); // Channel 2 to input 2 of merger
    
    // Blend third channel into both left (channel 1) and right (channel 2)
    channel3Gain.connect(merger, 0, 0); // Mix channel 3 into the left channel
    channel3Gain.connect(merger, 0, 1); // Mix channel 3 into the right channel

    // Connect the merger back to the Wavesurfer's output
    merger.connect(audioContext.destination);

    // Finally, connect the wavesurfer source to the splitter
    console.log("Connecting splitter to audio")
    mediaNode.connect(splitter)

    // Function to update gain based on slider input
    function updateGain(gainNode, sliderId) {
        const slider = document.getElementById(sliderId);
        slider.addEventListener('change', function () {
            gainNode.gain.value = parseFloat(this.value);
        });
    }

    // Bind sliders to their respective gain nodes
    updateGain(channel1Gain, 'volume-1');
    updateGain(channel2Gain, 'volume-2');
    updateGain(channel3Gain, 'volume-3');
}

<button type="button" class="border-0 btn btn-outline-light btn-sm" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Set the playback rate." id="playbackRateButton">
    <div class="d-flex flex-nowrap">
        <label for="playbackRate" class="form-label" style="margin-right: 0.3em; margin-bottom:0em"><i class="fa-solid fa-person-running"></i></label>
        <input type="range" class="align-middle form-range" id="playbackRate" min="0" max="4" step="1" value="1" />
        <span id="playbackRate" style="margin-left: 0.3em">1x</span>
    </div>
</button>

function playbackListener() {
    const speeds = [0.25, 0.5, 1, 2, 4]
    // Add event listener for the playback rate slider
    document.querySelector('input[id="playbackRate"]').addEventListener('input', (e) => {

        // Use the slider value as an index for the speeds array
        const speed = speeds[e.target.valueAsNumber]
        console.log("speed", speed)
        document.querySelector('span[id="playbackRate"]').textContent = speed + 'x';
        
        primaryWaveform.setPlaybackRate(speed, true)
        primaryWaveform.play();
    });
};

playbackListener();

Limit dynamic text to 2 lines within div

I am generating text from a JSON file and displaying it within a div, when the user types a word in an input it scrolls to the current word and if the current word is on the next line then 3 lines appear in the div, how can I set only display 2 lines at once in the div

                 <div className="box">
                    <p className="word">
                        {wordList.map((word, wordIndex) => {
                            const currWord = typedHistory[wordIndex] || "";
                            const isCurrentWord = wordIndex === typedHistory.length;
                            const hasWrongChars = currWord.split("").some((char, index) => char !== word[index]);
                            const isExcessLength = currWord.length > word.length;
                            const isIncomplete = currWord.length >= 0 && currWord.length < word.length && typedHistory.includes(currWord);
                            const shouldHighlightWordRed = hasWrongChars || isExcessLength || isIncomplete;
                            return (
                                <span key={wordIndex} ref={isCurrentWord ? currentWordRef : null}>
                                    {word.split("").map((char, charIndex) => {
                                        let charColor = "#fff";

                                        if (wordIndex < typedHistory.length) {
                                            charColor = shouldHighlightWordRed ? "red" : "green";
                                        } else if (isCurrentWord) {
                                            const typedChar = typedChars[charIndex] || "";
                                            charColor = typedChar === char ? "green" : typedChar !== "" ? "red" : "#fff";
                                        }
                                        return (<>
                                            <span key={charIndex} style={{ color: charColor, backgroundColor: (isCurrentWord && charIndex === typedChars.length) ? 'grey' : 'transparent', paddingBottom: (isCurrentWord && charIndex === typedChars.length) ? '5px' : '0px', paddingTop: (isCurrentWord && charIndex === typedChars.length) ? '5px' : '0px' }}>{char}</span>
                                        </>
                                        );
                                    })}
                                    {' '}
                                </span>
                            );
                        })}
                    </p>
                </div>
.box {
  font-size: 1.5rem;
  height: calc(2 * 2.4em); /* Allow only two lines of text */
  overflow-y: hidden; /* Prevent vertical scrolling within the div */
  padding: 1.5rem; /* Adjust padding to vertically center */
  line-height: 1.8em; /* Ensure consistent line height */
  display: block;
  white-space: normal;
  background-color: var(--sub-alt-color);
  border-radius: 10px;
  color: var(--text-color)
}
.box .word {
  position: relative;
  margin: 0 5px 2px;
}

Should I modify it in such a way that the first line is at the center of the screen, so that the next line also scrolls to that position in this way only 2 lines appear?
enter image description here