How to define Type of dynamically added global variables for Intellisense

I am defining four global variables from a forEach loop using a line similar to this:

global[name] = buffer

with buffer being the type from node.js

and currently have the very ugly way to get my intellisense for it by having this after the loop:

// next line only so intellisense works, ALWAYS comment out before running
const btMapProvinces = Buffer.alloc(1), btMapTerrain = Buffer.alloc(1), btMapRivers = Buffer.alloc(1), btMapHeightmap = Buffer.alloc(1);

Now as i learned about how to use JSDoc to get Intellisense for arguments in modules i was sure i could use that to get Intellisense for my variables instead, but after reading through the whole documentation i can’t seem to get it working.

My current attempt looks like this:

/**
 * @var {Buffer} btMapProvinces
 * @var {Buffer} btMapTerrain
 * @var {Buffer} btMapRivers
 * @var {Buffer} btMapHeightmap
 */

but it just doesn’t work at all, no matter if it is right before the global[name] = buffer line, at the beginning of the script, or after the forEach…

Material UI DropDown Focus Remove

I want to remove focus background color for target drop down

<Drop

down
            options={branding}
            fullWidth
            id='Name'
            placeholder='Name'
            label='Name'
            name='Name'
            className='form-name-input name-textbox name-dropDown'
            data-test='name-dropbox'
            onChange={handleChange}
            value={values.brand}
            error={errors.brand}
            style= {{             
              MuiSelect: {
                select: {
                  "& .MuiSelect-select:focus": {
                    backgroundColor: 'transparent',
                  }
                }
            }}        
          }
          />

On focus i am getting the focus to white I need to change the color once drop down is removed, I d want to use inline styling only . want to remove backgroundCOlor in foucus or set it to transparent for only this dropdown

enter image description here

Hydration error due to if statement in Next.js

I am getting three errors due to the if statement in my _app.js file.

Error: Hydration failed because the initial UI does not match what was rendered on the server.
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

What is the cause of the error and how do I fix it?

import '../styles/globals.css'
import Popup from "../components/register-popup.js";
import { getCookies, setCookies, removeCookies } from 'cookies-next';

var isValid = getCookies("noPopup").noPopup != "valid";

function MyApp({ Component, pageProps }) {
  if (isValid) {
    return (
      <div>
        <Popup />
      </div>
    )
  } else {
    return (
      <div>
        <Component {...pageProps} />
      </div>
    )
  }
}

export default MyApp

How to Change date format plus add one day and change it back to same format?

I m trying to

  • Get a date from a span tag as a string
  • Convert it to date format
  • Add one day to it
  • Change it back to the original format
  • print it out in the same span tag.

Here’s the code so far:

the date string will be in “dd-mm-yyyy” format and i want the output to be in the same format

let fetched_date = $(".slot_date_selected").html();
let dateParts = fetched_date.split("-");
let dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); 
let date = new Date(dateObject);
let datatodays = date.setDate(new Date(date).getDate() - 1);
let todate = new Date(datatodays);
let datee = new Date(todate);
let dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                .toISOString()
                .split("T")[0];

console.log(dateString);

I m unable to get the addition.

Any help is greatly appreciated. d

How to add if statement in arrow function

i’m a beginner in JS and was wondering what is the syntax of an arrow function with an if statement with a regular function such as function

getStringLength(string){
      let stringLength;
        if (string.length === 1){
                stringLength = `La chaîne contient qu'un seul caractère`;
        } else {
                stringLength = `La chaîne contient ${string.length} caractères`;
        }
        return stringLength;
    }

Override variable type from external library

I am using a third party library for my react application. There are some incorrect/outdated types.

Let’s say the library has the following type declarations:

declare const Hello: (name: string) => void

export interface SomeInterface {
  property1: string
  property2: number
}

Let’s assume both of these types are incorrect and I need to override them:

import 'external-lib'

declare module 'external-lib'{
  export interface SomeInterface {
    property1: boolean
    property2: boolean
  }

  export declare const Hello: (name: string, age: number) => void
}

So I redeclared the interface to have boolean properties and Hello function to accept the age parameter. (This is correct implementation of the library).

My problem is, that while interface Someinterface is overridden by me properly, the function Hello still uses the internal library type.

Is there a way to override function type declaration from external library?

Pagination gives error if page slug and CPT slug is same wordpress

I have created a page with name “cases” and my CPT has same slug name “cases”. I have call the CTP data on cases page.
When I click on 2nd page it leads me to 404 error page.
So I found a solution: I have renamed the page with cases2. After renaming the page slug the pagination start working normally and lead me to 2nd page.

But I want to use same page name and same slug for custom post type. What can I do on this ?

Drag an Element as a window

I have an element that contains a couple of elements and I want that while clicking on the green header of the element it will be dragged with the mouse movement and it will stay in the last position(it’s a simulation for a windows window).

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body {
    overflow: hidden;
}
.container {
    height: 100vh;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}
.box {
    position: absolute;
    background-color: #000;
    width: 475px;
    height: 350px;
    border: solid 1px rgb(0, 255, 0);
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;
}
#header {
    position: absolute;
    height: 20px;
    width: calc(100% + 2px);
    transform: translateX(-1px);
    top: -20px;
    background-color: rgb(0, 255, 0);
}
.back-chiffre {
    background: #000 url(/De4G.gif);
    margin-top: 200px;
    margin-right: 100px;
}
 <div class="container">
<div id="element" class="box back-chiffre">
            <span id="header">
                <span class="right">
                    <i class="fa-solid fa-window-minimize"></i>
                    <i class="fa-solid fa-window-restore"></i>
                    <i class="fa-solid fa-xmark"></i>
                </span>
            </span>
        </div>
</div>

Calling Object.entries on an empty Array returns something [duplicate]

Using reduce function, I would like to get directors and their titles in a object. I accidentally initialized it as an empty array instead of an object. But I figured out that, calling Object.entries on this empty array was returning something.

And I would like to understand why this returns something. Is this about references ?

Code :

const films  = [
  { director: "Hayao Miyazaki", title: "title1" },
  { director: "Hayao Miyazaki", title: "title2" },
  { director: "Gerard", title: "title1" },
  { director: "Gerard", title: "title1" },
  { director: "Anne", title: "title1" },
];

// we want an object of directors and their titles, using reduce
const directorsFilms = films.reduce((a, { director, title }) => {
  if (!a[director]) a[director] = [];
  a[director].push(title);
  return a;
}, []); // my mistake, should have been an empty object "{}"

// prints something in PythonTutor but not in Codepen.
// referenced to an empty array
console.log(directorsFilms);

// but when you call Object.entries on this empty array, there are results
// I call Object.fromEntries to get the object I was supposed to have calling reduce, not important
const tmp = Object.fromEntries(Object.entries(directorsFilms));
console.log(tmp);

I don’t understand how this is possible… I would appreciate some insight. Thanks in advance! 🙂

splice in JavaScript doesn’t work as expected

This is my code and it all seems to work, except for this piece of code that instead of removing just the value removes all the values within the array.

Basically I have a favorites system and every time you click the button to save the item to favorites the cookie updates.

The cookie contains an array and using console.log it seems to me that everything works, except for using splice.

How can I remove only one element within the array and not all of it?

function salvaSlot(id_post){
  var array_slot_salvate = [];
  array_slot_esistente = JSON.parse(getCookie('slotPreferiteCookie'));
  console.log(array_slot_esistente);
  if(array_slot_esistente == null){
    array_slot_salvate[0] = id_post;
  } else {
    if(!array_slot_esistente.includes(id_post)){
      var lunghezza_array = array_slot_esistente.length;
      array_slot_salvate = array_slot_esistente;
      array_slot_salvate[lunghezza_array] = id_post;
    } else {
      var index = array_slot_salvate.indexOf(1);
      if (index > -1) {
          array_slot_salvate.splice(index, 1);
      }
    }
    deleteCookie('slotPreferiteCookie');
  }
  createCookie('slotPreferiteCookie', JSON.stringify(array_slot_salvate), 365);
  var xmlhttp = new XMLHttpRequest();
  var url = document.location.origin+'/wp-content/themes/website/ajax/slot-salvate.php';
  var params = 'slot_salvate='+array_slot_salvate;
    xmlhttp.open('POST', url, true);
  xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("notifiche-slot-preferite").innerHTML = xmlhttp.responseText;
        }
    }
  xmlhttp.send(params);
}

function getCookie(name) {
    var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return v ? v[2] : null;
}
function setCookie(name, value, days) {
    var d = new Date;
    d.setTime(d.getTime() + 24*60*60*1000*days);
    document.cookie = name + "=" + value + ";expires=" + d.toGMTString() + "; SameSite=None; Secure; path=/; domain=website.it";
}
function deleteCookie(name) { setCookie(name, '', -1); }

How can I fix this?

Navigation with arrow keys to the left does not work with input readOnly

I have built a table with 4 columns. 1 column is text and the other 3 are inputs that are set to readOnly. For this table I have written an arrowKeyCodeNavigation. The operation works so far. But if I navigate for example in the first row to the right I can’t get back with left. Do you know how I can navigate neither back to the left when I am on a readOnly field?

// HTML

  <td
          [formGroupName]="rowIndex"
          *ngFor="let column of displayedColumns; let columnIndex = index;"
        >
          <div
            *ngIf="attributesWithFormControls.includes(column.attribute); else otherColumns"
          >
            <span>
              <label>
                <input
                  style="background-color: yellow"
                  class="current-cell"
                  [id]="'row-' + rowIndex + '-col-' + columnIndex"
                  type="text"
                  arrow-div
                  [formControl]="rowControl.get(column.attribute)"
                  (focus)="onFocus($event)"
                  readonly
                />
              </label>
            </span>
          </div>
          <ng-template #otherColumns>
            <div
              class="current-cell"
              tabindex="0"
              [id]="'row-' + rowIndex + '-col-' + columnIndex"
              arrow-div
            >
              Here is a Number
            </div>
          </ng-template>
        </td>

// TS

 /**
   * Use arrowKey
   * @param object any
   */
  move(object) {
    console.log('move', object);

    const id = object.element.nativeElement.id;

    console.log(id);

    const arr = id.split('-');
    let row: number = Number(arr[1]);
    let col: number = Number(arr[3]);

    switch (object.action) {
      case 'UP':
        --row;
        break;
      case 'DOWN':
        ++row;
        break;
      case 'LEFT':
        --col;
        break;
      case 'RIGTH':
        ++col;

        if (col >= this.columns.length) {
          // move past last column
          col = 0; // go to column at zero index  (1st column)
          ++row; // go to next row
        }

        break;
    }
    this.setFocus(row, col);
  }

  onFocus(event: FocusEvent): void {
    console.log('onFocus', event.target);

    const target = event.target as HTMLElement;

    if (target.tagName === 'INPUT') {
      this.currentInputInFocus = target;
    }
  }

  private setFocus(row: number, col: number) {
    console.log(`setFocus [row:${row}] [col:${col}]`);
    const newElementToFocusOn = document.getElementById(
      `row-${row}-col-${col}`
    );
    if (newElementToFocusOn) {
      console.log('focusing');
      this.currentInputInFocus = newElementToFocusOn;
      this.currentInputInFocus.focus();
    }
  }

Here is my work in stackblitz: https://stackblitz.com/edit/angular-wmfjhh-sj39il?file=app%2Ftable-basic-example.html

On straching a div open sidenavbar

Hi everyone when I’m using my phone i get to know that there is one feature given by my phone ,they provided a straight line while straching that div I’m able to open sidenavbar navbar I’m wonder can we do this in html i’ll post video what I’m talking about

Video link ‘
https://drive.google.com/file/d/1UB5WGIVIxuoCNaF_TLYJzhyMowqKzMHD/view?usp=drivesdk

Here you will you get video related to what I’m talking about

While sending request to Auth0 to get access token, is it possible to hide payload with secret keys which are visible?

I’m using Auth0 for sign in/sign up flow and user has possibility to update his profile information.

In order to do that I’m requesting a token from auth0 using url 'https://YOUR_DOMAIN/oauth/token', sending in payload this sensitive information

data: {
    grant_type: 'client_credentials',
    client_id: 'YOUR_CLIENT_ID',
    client_secret: 'YOUR_CLIENT_SECRET',
    audience: 'https://YOUR_DOMAIN/api/v2/'
  }

which is in plain text visible in Network Request browser.

This is procedure I’m following is here: https://auth0.com/docs/secure/tokens/access-tokens/get-management-api-access-tokens-for-production

So is possible to hide this payload data which contains this sensitive information? Since with this token you can manipulate users data if you know userID.

Or there is some other way to retrieve token from auth0 before updating profile?

Thank you

Service worker not available on localhost subdomain

An angular app I’ve build is based on subdomains and during development I used primary.localhost:3006 port. I need to add the PWA functionality to it but when I direct to the subdomain on localhost the service worker is not available in chrome devtools.

Upon research I saw that apparently subdomains on localhost are not whitelisted to user service workers, does that mean there is no way I can implement this?