chartjs ticks on x scale is offset

In a chart where x is time I use the options.scales.x.ticks.callback method to manually add months to the x axis.

It works, but the labels are offset month/2 ~15 days

I have fixed it by adding 15 to the values

But how to fix it in a proper way so each the first in each month is exactly at the tick thats is defined in the callback function and not offset by 50%?

options.scales.x.ticks.callback = function(value, index){
    return x_ticks[index] ?? null;
};

const day = 60*60*24, x_ticks = {};
let j = 15;
for(let i=res.time_start; i<=res.time_end; i+=day){
    const d = new Date(i * 1000);
    if(d.getUTCDate() === 1){
        x_ticks[j] = d.toLocaleString(LANG, {
            month: 'long'
        }).substring(0, 3)+' '+d.getUTCFullYear().toString().substring(2);
    }
    j++;
}

Hiding/Unhiding all paragraphs with a certain markup

Is it possible, using HTML and JavaScript (and CSS), to do have a link I can click on that will toggle the visibility of all DOM elements with a special CLASS attached? It doesn’t necessarily need to be a CLASS. Another option (if possible) is a new tag, f.ex. <P2> that works like <P> (inheritance?) that I can use on the paragraphs that need to be toggeable. The primary requirement is that a single click will toggle all the paragraphs (or <DIV>s, or whatever) at the click.

Ie.

<P CLASS=”Hideable”>This text can be toggled visible/hidden</P>

and then

<A onClick=”<some javascript>”>Hide/Unhide</A>

The “<some javascript>” part should then toggle the visibility of all “<P>”s with the class “Hideable”.

Note: I’m a novice in HTML/JavaScript/CSS, so please don’t assume I know what you are talking about 🙂

Tweaking py-shiny layout

I created a minimal example (directly editable online). I have few very small questions how to tweak it to look better.

  1. First of all, how to set the height to 100%? The problem is the the “category” selectize which goes “inside” of the outer box.
    enter image description here

  2. How to get rid of these borders around the outer box. What helped on one page was ui.tags.style(ui.HTML(".bslib-sidebar-layout .sidebar { border: 0px; }")),

enter image description here

  1. Since I follow the same structure of the page on every page – how can I set both 1 and 2 globally?

Many thanks in advance!

Why does npm start fail due to CORS error, but HOST=127.0.0.1 npm start succeed?

I am developing a simple application using Flask for the backend and React for the frontend. When I try to start my React application using npm start, I encounter a CORS error. However, when I use HOST=127.0.0.1 npm start, the application runs successfully without any CORS error.

Here is the code snippet for the Flask application:

#!/usr/bin/env python3

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)


@app.route("/")
def index():
    return "reachedn"


if __name__ == "__main__":
    app.run(port=5000)

Here is the code snippet for the React application:

import React, { useEffect, useState } from 'react';

const localhost = window.location.hostname

function App() {
  const [response, setResponse] = useState('');

  useEffect(() => {
    fetch(`http://${localhost}:5000/`)
      .then((response) => {
        if (!response.ok) {
          throw Error('Network response was not ok');
        }
        return response.text();
      })
      .then((data) => setResponse(data))
      .catch((error) => console.log(error));
  }, []);

  return (
    <div>
      <h2>"reached" expected:</h2>
      <p>{response}</p>
    </div>
  );
}

export default App;

I am using the hostname dynamically from window.location.hostname for the fetch URL. Does anyone know why specifying the host as 127.0.0.1 resolves the CORS error, while just using npm start does not?

How to set basePath dynamically in Nextjs next.config.js?

I am trying to set the basePath dynamically in Nextjs (next.config.js).

I have a requirement to set it dynamically so please anyone has an idea please suggest a solution.

Here is the detail of the requirement.

I have one domain ex: http://demo.com and I want to deploy my code on same domain.

Here i want two env first is stg and uat like

http://demo.com/stg

and

http://demo.com/uat

Here only context changed and I want to deploy the same build on both env, I don’t want to rebuild the code env specifically.

Thanks

Monaco Editor get cursor position in text as index number

I am retrieving text as string from editor and want to insert some marker text _CURSOR_ to position of cursor.

Here is the code:


let editor = /* ... */;

// Getting text
let text = editor.getValue();

// Getting cursor position
let pos = editor./* ??? */

// Adding text
text = text.substring(0, pos) + '_CURSOR_' + text.substring(pos);

How do I get the absolute position of cursor in resulting string? getPosition() returns an object containing line and column values but I can’t use them to insert my marker text.

Unable to perform pointer interaction as the element inherits `pointer-events: none` in jest

I updated the project libraries. Now all my pointer-events are none. How can I set them all to auto again?

This is the error message I get:

Unable to perform pointer interaction as the element inherits pointer-events: none:

DIV#:rr:  <-- This element declared `pointer-events: none`
 DIV(testId=user-search/results)
  DIV
   DIV
    UL#user-search-suggestions
     LI#user-search-item-L06973  <-- Asserted pointer events here

Isotope JS filter not working when search field is used in conjunction with buttons

I’m using Isotope.js for filtering which includes buttons and a search bar. I know combination filters can work in Isotope because this Codepen showcases a working demo of it.

However, adapting the above to my use case doesn’t seem to work.

See my demo here:

document.addEventListener('DOMContentLoaded', function() {

  // store filter for each group
  var buttonFilters = {};
  var buttonFilter;
  // quick search regex
  var qsRegex;

  var container = document.querySelector('.grid');
  var gridItems = container.querySelectorAll('.grid-item');
  var searchInput = document.querySelector('.rSidebar__search');
  var resourceCards = document.querySelectorAll(".resourceCard");

  /*
  * init Isotope
  */

  var iso = new Isotope(container, {
    itemSelector: '.resourceCard',
    layoutMode: 'fitRows',
    transitionDuration: '0.5s',
    // filter: function( itemElem ) {
    //   return qsRegex ? itemElem.textContent.match( qsRegex ) : true;
    // },
    filter: function (itemElem) {
      var item = this;
      var $item = item;
      var textContent = $item.textContent;

      // Check if textContent is defined before calling match
      var searchResult = qsRegex ? itemElem.textContent.match( qsRegex ) : true;
      var buttonResult = buttonFilter ? $item.is(buttonFilter) : true;
      return searchResult && buttonResult;
    },
  });

  /*
  * search filtering
  */

  // use value of search field to filter
  searchInput.addEventListener('keyup', debounce(function () {
    qsRegex = new RegExp(searchInput.value, 'gi');
    iso.arrange();
  }, 200));


  // flatten object by concatting values
  function concatValues( obj ) {
    var value = '';
    for ( var prop in obj ) {
      value += obj[ prop ];
    }
    return value;
  }

  // debounce so filtering doesn't happen every millisecond
  function debounce( fn, threshold ) {
    var timeout;
    threshold = threshold || 100;
    return function debounced() {
      clearTimeout( timeout );
      var args = arguments;
      var _this = this;
      function delayed() {
        fn.apply( _this, args );
      }
      timeout = setTimeout( delayed, threshold );
    };
  }

  /*
  * Create functions to sort isotope cards
  */

  function sortCards(){
    var selectedFilters = [];
    document.querySelectorAll('.selected').forEach(function(selectedItem) {
      selectedFilters.push(selectedItem.getAttribute('data-filter'));
    });
    var selector = selectedFilters.join(', ');
    iso.arrange({ filter: selector });
  }

  /*
  * Perform isotope filtering on li click
  */

  const optionLinks = document.querySelectorAll('.rSidebar__options-li');

  optionLinks.forEach(function(optionLink) {
    optionLink.addEventListener('click', function(event) {
      event.preventDefault();

      console.log(event);

      this.classList.toggle('selected');
      sortCards();

      // Scroll to the top of the #all-posts element smoothly
      const allPostsElement = document.getElementById('all-posts');
      if (allPostsElement) {
        allPostsElement.scrollIntoView({ behavior: 'smooth' });
      }
    });
  });

  iso.layout();


  /* another test */

  // var optionLinks2 = document.querySelectorAll('.rSidebar__options-li');
  //
  // // Add a click event listener to the 'filters' element
  // optionLinks2.forEach(function(optionLink2) {
  //   optionLink2.addEventListener('click', function(event) {
  //
  //
  //     var target = event.target;
  //
  //     console.log(target);
  //
  //     // Check if the clicked element has the class 'button'
  //     if (target.classList.contains('buttonTemp')) {
  //       var buttonGroup = target.closest('.button-group');
  //       console.log("buttonGroup " + buttonGroup);
  //       var filterGroup = buttonGroup.getAttribute('data-filter-group');
  //       console.log("filterGroup " + filterGroup);
  //       var dataFilter = target.getAttribute('data-filter');
  //       console.log("dataFilter " + dataFilter);
  //
  //       // Set filter for the group
  //       buttonFilters[filterGroup] = dataFilter;
  //
  //       // Combine filters
  //       var buttonFilter = concatValues(buttonFilters);
  //
  //       // Isotope arrange
  //       iso.layout();
  //
  //
  //
  //     }
  //   });
  // });

  /*
  * end
  */

});
.container {
  padding: 100px 0;
}

.rSidebar__options {
  padding-left: 0;
}
.rSidebar__options-li {
  margin-bottom: 17px;
  display: flex;
  align-items: center;
  cursor: pointer;
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
}
.rSidebar__options-li.selected .rSidebar__options-square {
  background-color: blue;
}
.rSidebar__options-square {
  height: 20px;
  width: 20px;
  border: 2px solid black;
}
.rSidebar__options-label {
  margin-left: 10px;
}

.resourceCard {
  border: 2px solid black;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>

<div class="container">
  <div class="row justify-content-between">

    <div class="col-3">
      <div class="rSidebar">
        <input class="rSidebar__search" type="text" placeholder="Search" name="search" aria-label="Search">
        <ul class="rSidebar__options button-group" data-filter-group="type">
          <li class="rSidebar__options-li" data-filter=".blogs-and-news" data-query="blogs-and-news">
            <span class="rSidebar__options-square"></span>
            <span class="rSidebar__options-label d-block buttonTemp" data-filter=".blogs-and-news">Blog & News</span>
          </li>
            <li class="rSidebar__options-li" data-filter=".case-study" data-query="case-studies">
            <span class="rSidebar__options-square"></span>
            <span class="rSidebar__options-label d-block buttonTemp" data-filter=".case-study">Case Studies</span>
          </li>
        </ul>
      </div>
    </div>

    <div class="col-7">
      <div class="grid">

        <article class="resourceCard grid-item case-study">
          <div class="resourceCard__body background--white d-flex flex-column">
            <span class="resourceCard__body-title fw-bold" role="heading">Case study post</span>
          </div>
        </article>

        <article class="resourceCard grid-item blogs-and-news">
          <div class="resourceCard__body background--white d-flex flex-column">
            <span class="resourceCard__body-title fw-bold" role="heading">Blogs and news post</span>
          </div>
        </article>

      </div>
    </div>

  </div>
</div>

In the above, perform the following steps to recreate the issue(s):

  1. When running the demo, search for “news” and it will filter to the news post (working)
  2. Rerun the demo and now click either of the checkbox options. This will sort the cards accordingly (working).
  3. Rerun the demo and now, enable both checkboxes, and then search for “news”. This will not filter the cards (not working), to show the news post.
  4. Similar to the above, when a checkbox is enabled, and you search for a term that isn’t present (e.g. “test”), it doesn’t hide all the cards (to imply that no results found with that searched term).

I’m stumped with this one as I’ve tried to follow the demo and alter my code, but cannot see where my issue lies?

Connect to aws ec2 node by websocket

I have created a chain node on aws ec2 instance using geth.
Do I need to enable something or what ip should I use to connect to it?
I am using web3.js using new Web3.providers.WebsocketProvider(‘wss_address’, abiOptions)

I enabled ws for it using –ws. Where I got “WebSocket enabled url=ws://127.0.0.0.1:8546”.

How to use Next.js 13 Metadata in Client Component

While adding new features to my Next.js app, I integrated i18n using next-intl and i18next, and I relied on useState and useEffect. Now, I need to implement SEO.

I’m currently struglling with components usage for each of these features:

  • useTranslations works in client components (can also be used in server components).
  • Metadata works only in server components (for SEO purposes).
  • useState and useEffect works only in client components (for interactivity)

How to create QR code from our input images in expressjs?

I have an expressjs app. I want to create a QR code containing an image that I uploaded. Here is an example: https://codepen.io/xiongbinsh/full/goyobm According to our input image, they are creating a QR code. If I create an API, can we do the same idea in exprssjs?

app.post('/generate', (req, res) => {
  const text = req.body.text;
  const errorLevel = req.body.error_level;
  const userSize = parseInt(req.body.size);

  // Determine the QR size.
  let QRsize = -1;
  if (userSize === 0) {
    for (let i = 0; i < sizes[errorLevel].length; i++) {
      if (text.length < sizes[errorLevel][i]) {
        QRsize = i + 1;
        break;
      }
    }
  } else {
    if (text.length < sizes[errorLevel][userSize - 1]) {
      QRsize = userSize;
    }
  }

  // Check if the text is too long.
  if (QRsize === -1) {
    if (userSize === 0) {
      if (errorLevel === 'H') {
        res.send('Too much text.');
      } else {
        res.send('Too much text. Try decreasing the error level.');
      }
    } else {
      res.send('Too much text. Try decreasing the error level or increasing the size.');
    }
    return;
  }

  // Generate the QR code.
  const qr = qrcode(QRsize, errorLevel);
  qr.addData(text);
  qr.make();

  // Generate the controls QR code.
  const controls = qrcode(QRsize, errorLevel);
  controls.addData(text);
  controls.make(true);

  // Generate the halftone QR code.
  const halftoneQRImage = halftoneQR(qr.returnByteArray(), controls.returnByteArray());

  // Send the halftone QR code image to the user.
  res.type('image/png').send(halftoneQRImage);
});

How to notice to the user that element has been “disable”? [closed]

In the field of information technology, I am a newcomer, and I’m currently facing a bit of difficulty in my project. In that project, I have a list of categories that are represented using input elements, and one of them is disabled. I need to figure out how to display a notification when a user clicks on a disabled input.

I want to display a dialog with a button to close it. In this project, I am using HTML and JavaScript