Beginner site issues

I am new here and am really excited about this website, as I have been having trouble with technology lately, making my life more difficult instead of easy. I’m all about bringing back efficiency.
That being said, does anybody know why it keeps logging me out every time I click on any link?
For reference, I am using an iPhone 13 max Pro and it is up-to-date

Thank you, everyone

Using nextjs app router – How can i set the page title on a server rendered component?

I’m loading a blog post from the server where I will have access to things like the blog post title. But according to the migration guide for app router this exists outside of my page. How do I update it?

docs: https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#step-3-migrating-nexthead

async function onLoad (slug: string): Promise<PostInterface> {
  const res = await API.get(`/posts?slug=${slug}`, {
    headers: {
      // ...
    }
  })

  const post = res.data.data.posts[0]
  if (!post) redirect('/404')
  return post
}

export const metadata: Metadata = {
  title: 'My Page Title That Needs To Be Replaced'
}

async function Page ({ params }: { params: { slug: string } }) {
  const post = await onLoad(params.slug)
  const { title } = post

  // ... how do i change my document.title from server side?
  // metadata.title = title will not work
}

export default Page

how to split a continues hex string into space delimited hex blocks of 32 tuplets each?

I have a fairly long hex string Buffer.toString("hex") that I want to print to a log file in a block of 32 tuplets each.

So basically going from
e01102020809020300800202020809020208095f520c8066054445472b44739621e0d003040401d21044454946583532463447444a4d010000d3104445472b445333374f53474b32010000d4104445472b44533337474b563033010000d503040401d6104445472b444342324354473031010000d7104445472b44504450535f5f5f5f0106009000

to

e0 11 02 02 08 09 02 03 00 80 02 02 02 08 09 02 02 08 09 5f 52 0c 80 66 05 44 45 47 2b 44 73 96
21 e0 d0 03 04 04 01 d2 10 44 45 49 46 58 35 32 46 34 47 44 4a 4d 01 00 00 d3 10 44 45 47 2b 44
53 33 37 4f 53 47 4b 32 01 00 00 d4 10 44 45 47 2b 44 53 33 37 47 4b 56 30 33 01 00 00 d5 03 04
04 01 d6 10 44 45 47 2b 44 43 42 32 43 54 47 30 31 01 00 00 d7 10 44 45 47 2b 44 50 44 50 53 5f
5f 5f 5f 01 06 00 90 00

I have tried hex.replace(/.{64}/g, "$1n") to wrap the hex string after 32 tuplets but don’t know how to add the spaces between the tuplets now.
I would prefer to do that in one regex, if possible?

href values I get start with “/url?q=” using Cheerio

I am trying to use cheerio for scraping. However I got small problem. All the href values I get on the client side start with “/url?q=”. For example like this:

'/url?q=https://www.nimh.nih.gov/health/topics/auti… pkCZkQFnoECAYQAg&usg=AOvVaw1E4L1bLVm9OdBSFMkjJftQ'

The element from the google search is:

<a jsname="UWckNb" href="https://www.nimh.nih.gov/health/topics/autism-spectrum-disorders-asd"...

It doesn’t contain "/url?q=". Where does "/url?q=" come from?

app.get('/scrape', (req, res) => {
    request('https://www.google.com/search?q=asd', (error, response, html) => {
        if (response.statusCode == 200) {
            
            const $ = cheerio.load(html);
            const results = [];
            const links = $('a'); 
            links.each((index, link) => {
                const href = $(link).prop('href'); 
                const h3 = $(link).find('h3'); 
                
                if (h3.length > 0) {
                    const textContent = h3.text().trim();
                    results.push({ href, textContent }); 
                }
            });
        
            const responseData = {
                links: results,
                total: results.length
            };

            res.json(responseData); 
        } else {
            console.error('Unexpected status code:', response.statusCode);
            res.status(500).send('Unexpected status code.'); 
        }
    });
});

I know that I can solve it like this:

 const actualUrl = decodeURIComponent(href.split('/url?q=')[1].split('&')[0]);

But I would like to know where this "/url?q=", what am I doing wrong?

Jquery dialogue with ajax to block submission again

I have a jquery dialog to submit a question. I need to block the submission until I get a response with a loading image. I tried several ways and nothing works to disable the dialog and show image. Here is the code

function openHelpDialog(a) {
    
    document.getElementById("helpDialog").style.display = "block";
    a.$btnHamburger.addClass('disabled'); 
   $(".ui-dialog-titlebar").append("<img src='static/img/global/chatbot.png'/>");
    toggleMenuItems(false);
    
    $("#hpQuestion").val("");
   
     $("#helpDialog").dialog({
        modal: true,
        width: 350,
        zIndex: 9999,
        buttons: {
            
            "Send": function(e) {
               
                if (validateHelpForm()) {                    
                    var formData = new FormData();
                    formData.append("hpQuestion", $("#hpQuestion").val());
                                     
                    $("#hpQuestion").val($("#usermsg").val());
                    
                    $.ajax({
                        type: "POST",
                        url: "submitQuestion.htm",
                        data:  formData,                        
                        contentType: false,
                        processData: false,
                        
                         beforeSend : function() {
                             
                              document.getElementById('usermsg').setAttribute("disabled","disabled");
                             
                              $("#usermsg").val("");
                        
                        },
                        success: function(responseMessage) {
                           var md = $("#hpQuestion")
                            md.val(md.val() +"nResponse:" +responseMessage)
                           
                             $("#usermsg").val("");
                        }                        ,
                        complete : function() {
                          document.getElementById('helpDialog').removeAttribute("disabled");
                          
                           $("#usermsg").val("");                 
                        },
                        error: function(error) {
                            customAlert("Error submitting the Question: " + error.responseText);
                        }
                    });
                    
                    toggleMenuItems(true);
                    
                }
            }
        },
       close: function() {
           
           toggleMenuItems(true);            
        }
    });
    
}

Also want to add the image to the left of the dialog title. currently it adds below the title and on each open call, mutliple images gets added.
Any help here is greatly appreciated

Warning: google.maps.Marker is deprecated. Please use google.maps.marker.AdvancedMarkerElement

I have a problem, I have already updated google.maps.Marker to oogle.maps.marker.AdvancedMarkerElement, however I still get the same warning, the code is:

  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});

                    const map = new google.maps.Map(document.getElementById('map'), {
                        zoom: 7,
                        mapId: "DEMO_MAP_ID",
                        center: {
                            lat: lat,
                            lng: lng
                        }
                    });

                   directionsRenderer.setMap(map);
                   directionsRenderer.setPanel(document.getElementById('directions-panel'));




                    directionsRenderer.setOptions({
                        suppressMarkers: true
                    });


        // Crear elementos
        const greendivElement = document.createElement('div');
        const greenimgElement = document.createElement('img');
        const greenpElement = document.createElement('p');

        // Establecer atributos y contenido
        greenimgElement.src = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
        greenimgElement.alt = 'Tu ubicación';
        greenpElement.textContent = 'Tu ubicación';
        greendivElement.style.position='absolute';
        greendivElement.style.width='130px';
        greenpElement.style.fontWeight = 'bold';
        greenpElement.style.fontSize = '20px';
        greenpElement.style.fontFamily='Arial';
        greenpElement.style.marginTop='-20px';
        greenpElement.style.color="black";
        greenimgElement.style.top='-30px';
        greenimgElement.style.left='100';
        greenimgElement.style.position='relative';

        // Agregar elementos al DOM
        greendivElement.appendChild(greenimgElement);
        greendivElement.appendChild(greenpElement);

                    // set markers

                    const marker = new google.maps.marker.AdvancedMarkerElement({
                        position: {
                            lat: lat,
                            lng: lng
                        },
                        map: map,
                        content: greendivElement,

                    

                    });

The warning is removed if I remove these two lines:

directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById(‘directions-panel’));

I would like you to please help me solve it.

Javascript array.join returns empty value on array of strings

(I’m pretty new to javascript so sorry if this is rather obvious!)

My code pulls artist ids from spotify’s api and stores them as strings in an array. I need to concatenate them into a string seperated by commas, so I tried to use array.join.

let artistIds = [];
spotify.getMyTopArtists().then(
  (data) => {
    for(let i = 0; i < 5; i++){
      const str = data.body.items[i].id
      artistIds.push(str)
    }
  }
)
console.log(artistIds);
let str = artistIds.join(",");
console.log(str);

The spotify object is from the spotify-web-api-node library.

I though this would just concat the strings with commas in between, but the console output looks like this:
enter image description here

Tradingview widget – how to call save_image function?

I’m trying to find a way to save the chart that the tradingview widget generates from the code.

When i open https://s3.tradingview.com/tv.js, i see that a save_image function is defined, is there a way to call that function in javascript? Do i have to find another way to save an image of the chart?

Here is what i tried:

<div class="tradingview-widget-container" style="height:100%;width:100%">
    <div id="tradingview_009af"></div>
    <div id="basic-area-chart-demo" style="height:calc(100% - 32px);width:100%"></div>
    <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/" rel="noopener nofollow" target="_blank"><span class="blue-text">Track all markets on TradingView</span></a></div>
    <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
</div>

<script type="text/javascript">
    const widget = window.tvWidget = new TradingView.widget(
        {
          "autosize": true,
          "symbol": "NASDAQ:AAPL",
          "interval": "D",
          "timezone": "Etc/UTC",
          "theme": "dark",
          "style": "1",
          "locale": "en",
          "enable_publishing": false,
          "allow_symbol_change": true,
            "save_image": true,
          "studies": [
            "STD;RSI"
          ],
          "container_id": "tradingview_009af"
        }
    );

    window.addEventListener('message', function(event) {
        try {
          var data = JSON.parse(event.data);
          if (data.provider === 'TradingView' && data.name === 'widgetReady') {
            console.log("The TradingView chart widget is fully loaded and ready!");
            widget.save_image();
          }
        } catch (err) {
            console.log(err)
        }
    });
</script>

I tried to call widget.save_image() but it will raise a TypeError: widget.save_image is not a function error. Is there any way to save this? The widget has a button that let’s you save an image of the chart locally, so i thought that it would be possible to call that function from my code too. Thanks in advance!

New to React. Wokring on a Youtube tuorial that is a bit outdated so mine isnt the exact same but I cannot get passed this one part

I am running my spring boot application on port 8080 and have set up a react app on visual code. I created a proxy for the connection. I am using render() to have a ‘Loading’ piece pop up as the information is grabbed but its stuck at Loading and I dont know why.

Here is the Category.js
import React, { Component } from ‘react’;

class Category extends Component {

state = {
    isLoading : true,
    Categories : []
}

 async componentDidMount(){
    const response = await fetch('/api/categories');
    const body = await response.json();
    this.setState({Categories :body, isLoading: false});
    }
 render(){ 
    const{Categories, isLoading} = this.state;
    if(isLoading)
        return(<div>Loading......</div>);
    
    return (
        <div>
            <h2>Categories</h2>
            {
                Categories.map( category =>
                <div id={category.id}>
                    {category.name}
                </div>
                )
            }
        </div>
    );
}

}

export default Category;

And...... Here is the index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Category from './Category';

import reportWebVitals from './reportWebVitals';
//import * as serviveWorker from './serviceWorker';

//ReactDOM.render(<Category/>, document.getElementById('root'));
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Category/>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))

reportWebVitals();
//serviveWorker.unregister();

I am trying to get passed this loading state and show the actual categories.

Sigma.js v2 dashed edges (lines)

What is the best way to have dashed graph edges in sigma.js v2? I understand that I need custom Webgl program + shaders, but it’s not an easy stuff to implement. Has someone implemented it already?

I stuck with customizing default edge program and its shaders.

“slideToLoop” to last slide in Swiper behaves wrongly, I want it to take me to end of the slide, but it takes me to the start

UPD: I’ve used rewind instead of loop, and it’s seem to be alright.

I understand what that might be the problem with loop, but I need some solution

When I click “play video” it takes me to the end, when I slide to other next slides and press button again, it shows the video like it’s first slide:
https://imgur.com/a/9jPw0ce

<script>
const galleryThumbs = new Swiper('.product__thumbnails', {
  loop: true,
  slidesPerView: 4,
  spaceBetween: 14,
  navigation: {
    nextEl: '.slider-nav__next',
  },
});

const galleryTop = new Swiper('.product__gallery', {
  loop: true,
  autoHeight: true,
  spaceBetween: 10,
  thumbs: {
    swiper: galleryThumbs,
  },
});

galleryThumbs.on('click', function () {
    const lastVisibleSlide = galleryThumbs.visibleSlides[galleryThumbs.visibleSlides.length - 1];
    const lastVisibleIndex = parseInt(lastVisibleSlide.getAttribute('aria-label').split(" / ")[0]);
    const nextIndex = lastVisibleIndex + galleryThumbs.params.slidesPerView;
    const currentIndex = parseInt(galleryThumbs.clickedSlide?.getAttribute("aria-label").split(" / ")[0]);
    console.log(currentIndex, galleryThumbs.slides.length);
    console.log(lastVisibleIndex, "- lastVisibleIndex");
    // if (currentIndex >= galleryThumbs.slides.length) {
    //   galleryThumbs.slideToLoop(0);
    //   galleryTop.slideToLoop(0);
    // } else 
    if (currentIndex === lastVisibleIndex) {
      galleryThumbs.slideToLoop(currentIndex - 1);
      galleryTop.slideToLoop(currentIndex - 1);
    }
});

{% if has_video %}
  $('button.product__play').click(function(e) {
    e.preventDefault();
    // galleryThumbs.slideToLoop({{ video_sequence_number }} - 1);
    galleryTop.slideToLoop({{ video_sequence_number }} - 1);
    const slideVideo = $('.slider__gallery').find('.slider__slide[data-slide="video"]');
    if (slideVideo.length > 0) {
      slideVideo.find(".deferred-media__poster").trigger('click');
    } else {
      console.error('Video element not found.');
    }
  });
  {% endif %}
</script>

I’ve tried a lot of other combinations of using “slideTo” or “slideToLoop”

ES6 Proxy. Why when the target object changed, the proxy object also changed

const value = {};
const proxy = new Proxy(value, {
      get(target, prop, receiver) { return Reflect.get(target, prop, receiver) },
      set(target, prop, value, receiver) {
        Reflect.set(target, prop, value, receiver);
        return true;
      }
    });

Why when the target object changed, the proxy object also changed

ref to value not equal proxy

value === proxy return false;

Is this normal behavior or am I doing something wrong?

Coloris JS – Programmatically change color to random value on load

I am using the Coloris JavaScript library in order to allow the user to select a custom color for an element on the page. I would like to randomly select a color on page load and apply it to the element by default. Here’s what I tried so far:

document.addEventListener("DOMContentLoaded", function(event) { 
  
  const colorInput = document.querySelector('.instance1');
  const colorSquare = document.querySelector('.custom-color');
  
  Coloris({
    el: '.color-fields'
  });

  Coloris.setInstance('.instance1', {
      themeMode: 'dark',
      closeButton: true,
      onChange: (color) => {
          colorSquare.style.backgroundColor = color;
      }
  });
  
  // Set random color value on load
  colorInput.value = '#'+(0x1000000+Math.random()*0xffffff).toString(16).substr(1,6);
  
  // Trigger change
  colorInput.dispatchEvent(new Event('input', { bubbles: true }));

});
.custom-color {
  display:flex;
  align-items:center;
  justify-content:center;
  width:300px;
  height:300px;
  border:1px solid black;
}
<script src="https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.js"></script>
<link href="https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.css" rel="stylesheet"/>
<input class="color-fields instance1" type="text" value="green" data-coloris="">
<div class="custom-color"><span>CHANGE COLOR</span></div>

The color picker works when you use it manually and the input value is correctly getting set to a random color, but it doesn’t seem to be triggering the change on load. I tried adding colorInput.dispatchEvent(new Event('input', { bubbles: true })); after setting the value to a random color, but that didn’t change anything. Any thoughts?

how to make a virtual or digital map from scratch [closed]

Good afternoon, I am in a small project, myself and some friends, we are trying to make a digital or virtual map for a zoo, it is supposed to be an interactive tourist map and it is also only displayed on a web page while the user is inside the zoo and in a similar way to pokemon go there is a pin that moves according to the real-time location of the user, it must also have some pins that show references to areas of interest such as animal habitats or attractions within the zoo (or something as simple as the bathrooms), among other details but this is the most important.

My problem here is that I have been researching on my own how to do this, but the tutorials that I find on YouTube only teach how to insert a Google Maps iframe into an HTML file and that is also another problem!!, because the zoo itself is so small that in Google Maps it is only rendered as a rectangle and even though it has a satellite view it looks very blurry. Another solution I have investigated is to create a digital image/photo of a zoo map and use the HTML Geolocation API and the Javascript leaflet library to add to that map image the latitude and longitude of the location of that zoo in the real world, hence giving the functionality to the pin to move in real time with the user.

However, I have serious doubts about these solutions and I would appreciate it if you could clarify my doubts.

How do I solve this using HTML CSS and JS?

How to Efficiently Read Large Datasets from Firestore with Reduced Latency?

I’m working on a project that requires fetching large datasets from Firestore to display patient data. The data is structured as follows: patients/daily(collection)//document, where each document contains summary and samples fields. My goal is to read this data efficiently to display it in my application.

Problem:

Regardless of the approach I take, fetching data for significant intervals (e.g., the last 2 years, 3 months intervals going back 2 years, or combinations like 3m, 3m, 6m, 1y), the operations consistently take over 30 seconds, which is far from optimal. I’m seeking a method to significantly reduce this latency.

What I’ve Tried:

  1. Fetching the Last 2 Years Directly: Attempted to fetch the entire dataset for the last two years in one go.
  2. Interval Fetching: Tried fetching data in intervals (3m, 3m, 6m, 1y) sequentially.
  3. Batch Processing: Considered batch processing but unsure how to implement it effectively in Firestore.

Questions:

  1. Are there any Firestore-specific strategies or optimizations for reading large datasets that I might be overlooking?
  2. Is there a more efficient way to structure my database or queries to improve read performance?
  3. Could Firestore’s local caching capabilities be leveraged to improve subsequent read operations’ latency?
const collectionRef = collection(db, "patients", id, "daily");

const startDateStr = startDate.toISOString().split("T")[0];
 
const q = query(
  collectionRef,
  where("start_time", ">=", startDateStr),
  where("start_time", "<", endDateStr)
);
const querySnapshot = await getDocs(q);

After this i go over every snapshot to retrieve the summary and samples into 2 different arrays one for the summary and one for the samples.

I expected that by breaking down the fetch operations into smaller intervals or by batching, I could reduce the overall latency. However, none of these methods have reduced the fetch time to under 30 seconds.