How to style the items from MenuBar Primereact component?

I’m coding my website with React, Primeflex and Primereact. I am using the MenuBar component and I need to style the items in the component, but anything I am trying to do isn’t working. How can I style it?

import { Menubar } from 'primereact/menubar';
import { Button } from 'primereact/button';
import { useNavigate } from 'react-router-dom';
import imgDev from '../assets/img-dev.svg';

function Header() {
    const navigate = useNavigate();

    const items = [
        {
            label: 'Menu',
            command: () => navigate('/')
        },
        {
            label: 'Experiências',
            command: () => navigate('/experiencias')
        },
        {
            label: 'Formação',
            command: () => navigate('/formacao')
        },
        {
            label: 'projetos',
            command: () => navigate('/projetos')
        }
    ];

    const start = (
        <img src={imgDev} alt="Logo" style={{ width: 40, height: 40, marginRight: '10px' }} />
    );

    const end = (
        <Button className='bg-orange-500 border-none' label='Meu Currículo' icon='pi pi-file' />
    );

    return(
        <Menubar className='w-full bg-gray-900 border-none fixed top-0 left-0 p-3 z-1' model={items} start={start} end={end} />
    );
}

export default Header;

I’ve got an image that is within a class container due size. I want to create a mouseover event to swap images, but with the same size constraints

I’m trying to apply a mouseover event to change an original image to new image, and then back to the original image upon mouseout. However, the original image files are very large, so I’m using a container class to display them in the size I want.

The problem is that when I hover over the image, it displays the new image, but it’s at the original size instead of being within the constraints of the container.

const imageContainer = document.querySelector('.flex-container');
const image = document.getElementById('bookCover2');
const originalSrc = 'Book_2_Cover.png';
const newSrc = 'Book_2_Back.png';

imageContainer.addEventListener('mouseover', () => {
image.src = newSrc;
});

imageContainer.addEventListener('mouseout', () => {
image.src = originalSrc;
});

my button styling is having issues, how do i fix? [closed]

I recently added a music player to my website (https://potatoishere.neocities.org/ for reference) and I’ve been having a couple issues with the functionality of the buttons.

  • First issue is that the button shows even when nothings playing
    (before I edited the code to change the style it wasn’t doing it and
    now it is).

  • Second issue is that when refreshing the website the buttons don’t
    load when playing music until I refresh it again.

  • The last issue is that when I hide the div on my neocities website,
    it also hides the buttons when I click the button that opens the
    website.

I have no idea what is causing any of these issues and my website runs an iframe with a github page since neocities isn’t cooperating with the way the the spotify player runs.

(https://potatoisnthere.github.io/HEEELP/ is the github page for reference).

Why is my field resetting when selecting a date in React?

I’m working on a React form where I need to handle a Date of Birth field using an <input type="date">. I want the field to accept dates in the YYYY-MM-DD format, both for displaying the date and for storing it in the state.

When I enter a date manually, the input resets. And when I select a date from the calendar, it doesn’t accept the input.

Here’s some part of my code:

    import React, { ChangeEvent } from 'react';

const RegisterForm: React.FC<RegisterFormProps> = ({
  dateOfBirth,
  setDateOfBirth,
  isValidAge,
}) => {
  // Handle changes in date input
  const handleDateChange = (e: ChangeEvent<HTMLInputElement>) => {
    const inputDate = e.target.value; // This will be in the format YYYY-MM-DD
    setDateOfBirth(inputDate); // Update the state with the YYYY-MM-DD format
  };

  return (
    <form className="form">
      <div className="form-group">
        <label>Date of Birth</label>
        <div className="input-container">
          <Calendar size={18} className="input-icon" />
          <input
            type="date"
            value={dateOfBirth}  // Directly bind the state in YYYY-MM-DD format
            onChange={handleDateChange}  // Update the state when the user selects a date
            className="input"
            required
          />
        </div>
        {dateOfBirth && !isValidAge && (
          <p className="age-error">You must be at least 15 years old to register</p>
        )}
      </div>
    </form>
  );
};

export default RegisterForm;

express js app.all() throwing error for no apparent reason [duplicate]

this is the code im trying to run

const express = require("express");
const app = express()

app.all('*', (req, res) => {
  res.status(404).send('<h1>resource not found</h1>')
});

app.listen(5000, () => {
  console.log('server is listening on port 5000...')
});

and running node app.js shows this:

C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:73
            throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);
            ^

TypeError: Missing parameter name at 1: https://git.new/pathToRegexpError
    at name (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:73:19)
    at lexer (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:91:27)
    at lexer.next (<anonymous>)
    at Iter.peek (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:106:38)
    at Iter.tryConsume (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:112:28)
    at Iter.text (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:128:30)
    at consume (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:152:29)
    at parse (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:183:20)
    at C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:294:74
    at Array.map (<anonymous>)

the only thing ive installed using npm in this project is nodemon and express.js

ive tried using both the normal versions and the @latest ones

ES6 arrow functions this inside a class versus inside an object [duplicate]

I’m trying to get a better understanding of how the arrow functions work in modern JavaScript. I have the following example:

class Person {
    name = 'Max';
    printMyName () {
        console.log(this.name); // this is required to refer to the class!
    }
}
 
const person = new Person();
person.printMyName();

class Person2 {
  name = 'Max2';
  printMyName = () => {
    console.log(this.name);
  }
}

const person2 = new Person2();
person2.printMyName();
    
    
const user = {
    name: "John",
    logName () {
        console.log(this.name);
    },
    logNameArrow: () => {
            debugger;
        console.log(this.name);  //this is Window here
    },
};
user.logName(); // logs 'John'
console.log('===============================');
user.logNameArrow(); // logs result

Which I’ve put here: https://jsfiddle.net/52qy8fd6/1/

this works inside a JavaScript class, but not in a JavaScript object.

Can anyone explain why the scoping is different in these two cases? Maybe instantiating my class with a new statement is binding this?

JavaScript function not returning array [duplicate]

I have an ESRI 3.46 JavaScript application. There are a couple of functions which return data from an API. I am looping through the results and creating an array to be returned to other areas of my application. The problem I am having is the function is returning
“undefined” instead of the array. If I send the results to the console before the return statement, the data is there. I am also using a little PHP in this.

        function requestDomains(layer){
          var dUrl = '<?php echo $emapFS; ?>/queryDomains';
          var domainRequest = new Request({
            "url" : dUrl,
            "content": {
              "f": "json",
              "layers": '['+layer+']',
            },
            async: false
          });
          //domainRequest.then(domainParse, requestFailed);
          domainRequest.then(function(response){
            var domains = response.domains
            var arr = [];
            //console.log(domains);
            jQuery.each(domains, function(key, value){
              var dname = value.name;
              arr[dname] = [];
              var cValues = value.codedValues;
              jQuery.each(cValues, function(k, v){
                var dcode = v.code.toString();
                var dvalue = v.name.toString();
                arr[dname][dcode] = dvalue;
              });
            });
            console.log(arr);  //<------------ This returns the array in console. Looks good
            return arr;

          });
        }

        function MainTabContent (results){
          var template = "";
          var wfeatures = results.features[0];
          //console.log("Main");
          var MainArray = <?php echo $mainFields; ?>;
          var layerid = mapLayers['Main Lines'];
          //console.log(layerid);
          var cDomains = requestDomains(layerid);
          console.log(cDomains); // <-----------------------This returns undefined
          template = "<i>Total features returned: " + wfeatures.length + "</i>";
          template += "<table border='1' style='width:1000px;'>";
          template += "<tr>"
          jQuery.each(MainArray, function(tkey, tvalue){
            template += "<th>"+tvalue+"</th>"
          });
          //template += "<th>Data</th>"
          template += "</tr>";
          for (var i = 0, il = wfeatures.length; i < il; i++)
          {
            template += "<tr>";
            jQuery.each(MainArray, function(key, value){

                switch(key)
                {
                  case "<?php echo $switchFields[4]; ?>":
                    template += '<td width="300">'+ wfeatures[i].attributes[key] +'</td>';
                  break;
                  case "<?php echo $switchFields[3]; ?>":
                    template += '<td width="100">'+ wfeatures[i].attributes['DIAMETER'] +' '+ wfeatures[i].attributes['MATERIAL'] + '<a href="#" onclick="showFeature(mainResults.features[0]['+ i +']); return false;">(show)</a></td>';
                  break;
                  case "<?php echo $switchFields[5]; ?>":
                    asbuilt = wfeatures[i].attributes[key];
                    //console.log(asbuilt);
                    if(asbuilt != 'Null')
                    {
                      template += '<td><a href="<?php echo base_url(); ?>gis/ab/' + asbuilt + '" target="_blank">' + asbuilt + '</a></td>';
                    } else {
                      template += '<td>&nbsp;</td>';
                    }
                  break;
                  case "<?php echo $switchFields[0]; ?>":
                    unitid = wfeatures[i].attributes[key];
                    template += "<td>"+ wfeatures[i].attributes[key] +"</td>";
                  break;
                  case "<?php echo $switchFields[1]; ?>":
                    unitid2 = wfeatures[i].attributes[key];
                    template += "<td>"+ wfeatures[i].attributes[key] +"</td>";
                  break;
                  case "<?php echo $switchFields[6]; ?>":
                    facilityID = wfeatures[i].attributes[key];
                    template += '<td><div class="csspointer" style="color:blue;text-decoration:underline;" onClick="window.open('/gis/HansenQuery/'+facilityID+'/COMPWMN', '',  'width=400,height=400,menubar=no,scrollbars=yes')">Asset Data</div></td>';
                  break;
                  case "<?php echo $switchFields[7]; ?>":
                    mLength = parseFloat(wfeatures[i].attributes[key]);
                    template += "<td>"+ Math.round(mLength) +"</td>";
                  break;
                  default:
                  template += "<td>"+ wfeatures[i].attributes[key] +"</td>";
                }

            });
            //template += '<td><div class="csspointer" style="color:blue;text-decoration:underline;" onClick="window.open('/gis/HansenQuery/'+unitid+'/COMPWMN/'+unitid2+'', '',  'width=400,height=400,menubar=no,scrollbars=yes')">Hansen</div></td>';
            template += "</tr>";
          }
          template += "</table>";

          return template;
        }

The above code was shortened a bit. I initially had the request for the data in one function and the parsing of the data into an array in another.

How to inspect why YouTube player onStateChange doesn’t trigger

On a web page, I created YouTube player objects with new YT.Player(id, {events: {'onStateChange': ...}}). The resulting players have players[i].options.events.onStateChange. The iframes have message event listeners.

But that onStateChange event doesn’t trigger for some of the players in one particular browser tab that is currently open. The line d.j.G(e,h) in www-widgetapi.js is not reached when those problematic players pause or play. It is reached for the other players.

When I open the same page in a new tab, all events get triggered. So it’s a rare error (possibly depending on the order of loaded content and/or user actions). I can’t replicate it consistently, let alone work towards a minimal example. So I want to inspect it in the currently open browser tab where it occurred.

How can I inspect why the existing onStateChange event doesn’t trigger for those players in that browser tab?

I’ve read a dozen of posts about onStateChange not triggering, but my code doesn’t have the same bugs that those posts describe.

How to disallow foreign characters in Gravity Forms / HTML / JS and allow English characters only? (Chinese, Russian, Arabic letters etc)

Using Gravity Forms in WordPress I created a contact form.

Now customers enter Chinese characters into the fields, such as Name, Message. But this information is being sent to another system which does not allow these characters and they are converted into question marks: ??????

I am looking for a type of functionality that disallows any foreign type of character sets other than English and all its special character variations to be typed into the input field.

Preferably a native feature already existing in Gravity Forms or another plugin that would add this feature. If this does not exist, I might go into the code to change it.

How do I achieve this please?

Convert ESC POS Command 24 dot double density into 8 dot single density

I need a function that return array of byte array 8 dots single density, this function running as expected however the printing speed is the issue, it takes quite long time to print the image even though the quality is not my priority. I’ve tried to change this code into bit-image-mode 8 dots single density to speed up the printing but the image ratio somehow becoming 2:3 instead of 1:1. Can anyone help me convert this code to support 8 dots single density?

Thanks!

function convertGSv0ToEscAsterisk(bytes) {
    // Extract header info
    const xL = bytes[4] & 0xFF;
    const xH = bytes[5] & 0xFF;
    const yL = bytes[6] & 0xFF;
    const yH = bytes[7] & 0xFF;
  
    const bytesByLine = xH * 256 + xL;
    const dotsByLine = bytesByLine * 8;
    const nH = Math.floor(dotsByLine / 256);
    const nL = dotsByLine % 256;
    const imageHeight = yH * 256 + yL;
    const imageLineHeightCount = Math.ceil(imageHeight / 24.0);
  
    // Pre-allocate the result array
    const returnedBytes = new Array(imageLineHeightCount + 2).fill(null).map((_, i) => {
      if (i === 0) return EscPosPrinterCommands.LINE_SPACING_24;
      if (i === imageLineHeightCount + 1) return EscPosPrinterCommands.LINE_SPACING_30;
      return new Uint8Array(6 + bytesByLine * 24);
    });
  
    // Process each image line
    for (let i = 0; i < imageLineHeightCount; i++) {
      const imageBytes = returnedBytes[i + 1];
      const pxBaseRow = i * 24;
  
      // Set command header
      imageBytes[0] = 0x1B;
      imageBytes[1] = 0x2A;
      imageBytes[2] = 0x21;
      imageBytes[3] = nL;
      imageBytes[4] = nH;
  
      // Pre-calculate bit masks for improved performance
      const bitMasks = Array.from({ length: 8 }, (_, idx) => 1 << (7 - idx));
  
      // Process image data
      for (let column = 0; column < dotsByLine; column++) {
        const byteOffset = 5 + column * 3;
        const bitColumn = bitMasks[column % 8];
        const srcByteOffset = Math.floor(column / 8) + 8;
  
        for (let byteRow = 0; byteRow < 3; byteRow++) {
          const dstIndex = byteOffset + byteRow;
          if (dstIndex >= imageBytes.length - 1) continue;
  
          for (let k = 0; k < 8; k++) {
            const pxRow = pxBaseRow + byteRow * 8 + k;
            if (pxRow >= imageHeight) continue;
  
            const srcIndex = bytesByLine * pxRow + srcByteOffset;
            if (srcIndex >= bytes.length) continue;
  
            if ((bytes[srcIndex] & bitColumn) === bitColumn) {
              imageBytes[dstIndex] |= bitMasks[k];
            }
          }
        }
      }
  
      imageBytes[imageBytes.length - 1] = EscPosPrinterCommands.LF;
    }
    return returnedBytes;
  }

Custom Mathjs unit

I would like to use mathjs in order to ease unit conversion. To do so, I introduce new units as following :

import { unit, createUnit, evaluate } from 'mathjs';
createUnit('gCO2eq');
createUnit('kgCO2eq', unit(1000, 'gCO2eq'));

const a = evaluate('10000 gCO2eq');
console.log(a.toString());

This outputs:

10000 gCO2eq

But I expected it to be

10 kgCO2eq

Any idea why I got this result instead?

When is chosen only display partial value of in – HTML

I have a SELECT that is pulling in 2 db fields (TYPE and DESCRIPTION) to form the displayed OPTION values (option example: ft - full-time, pt - part time, sl - seasonal, etc.).
When the drop-down options are displayed, I want to see both TYPE and DESCRIPTION (as detailed in my example) but I only want the TYPE displayed on the form/page after it is selected.

<label>Employee Type</label>
<select>
  <Option value="" disabled selected hidden>--Select Type--</Option>
  @if (Model.DropDownItems != null) {
    @foreach (var item in Model.DropDownItems) {
      <option value="@item.Type">@item.Type - @item.Desc</option>
    }
  }
  else {
    <option value="" disabled>No data available</option>
  }
</select>

Any assistance with this would be greatly appreciated.

REGEX: How to get substring from nested braces using regular expressions [duplicate]

Is there a way to get a substring from a string with nested curly braces where the nesting level is not fixed using regular expressions with pure javascript?

For example we need to get the some text substring from all this strings:

"error: {error: {error: {some text}; at 'aaa', line 11;} at 'bbb', line 22'} at 'ccc', line 33';"
"error: {error: {some text}; at 'aaa', line 11;} at 'bbb', line 22';"
"error: {some text}; at 'aaa', line 11;"