cannot run javascript program in terminal Mac

I have made a JavaScript hello world program in BBEdit, and saved it as app.js. But when I’m trying to run the file in Terminal, I keep getting the error (syntax error near unexpected token `’Hello world”).

The code:

console.log("Hello world")

The odd thing is, when I type console.log("Hello world") into terminal, it works, just not when placing app.js into terminal.

What am I doing wrong?

Sorting in Lexicographical sort

Input to your program are 3 strings S1 S2 and S3 of lower case alphabets and no spaces or special characters. S1 and S2 are the same size. Here are the constraints on S1 and S2:
In string S1 and S2 the alphabets at the same index can be replaced with each other.
If alphabet p can be replaced with q then q can also be replaced with p
If alphabet p can be replaced with alphabet q , and the alphabet q can be replaced with alphabet r then alphabet p can also be replaced with r.
1 < length of strings S1,S2,S3 < 999999
length of string S1 = length of string S2
All the strings consist of lowercase English letters.
Ex : You are given two strings:
S1−pqr
S2−zrg
Here, the alphabet p can be replaced with alphabet z, alphabet q can be replaced with r, and alphabet r with g. The alphabet q can also be replaced with g according to the 3rd rule above.

Input format
First line: String S1
Second line: String S2
Third line: String S3

Output format
You can replace any alphabet of S3 with any of these alternatives based on the properties learned from S1 and S2. By doing so you can construct many such new strings. Out of all these strings your program should output the smallest string assuming they are sorted lexicographically.

Sample Input
dcba
edcb
decb

Output
aaaa

Javascript Admin, User – setAccess Level OOP

I have such a problem.
I created three classes, User, Admin and App.

The App class creates new users with different access levels. Admin can change passwords, email and access level of other users.
Currently, the Admin can change the above options himself.

e.g. const admin = New Admin (…)
admin.setPassword (…)

I want to use the App class and be able to creating an Admin, User and the possibility that the created admin can change the password, an email, to another User.

`use strict`
class Validator {
    static isStrings(...value) {
        value.forEach(el => {
            if (typeof el !== "string") {
                throw new Error("it is not a string value")
            }
            if (el.length === 0) {
                throw new Error("Provide a string value")
            }
        });
    }
    static checkEmail(email) {
        const regex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-](.{7,32})+@[a-zA-Z0-9]+(?:.[a-zA-Z0-9].{1,3})*$/g
        if (!regex.test(email)) {
            throw new Error(`Email address has a wrong format! Correct format is 8-32 characters, at least one capital letter, one number and one special character `);
        }
    }

    static checkPassword(password) {
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!#$%^&*()<>?])+.{9,32}$/g
        if (!regex.test(password)) {
            throw new Error(`Invalid password. Password must have from 8 to 32 characters, includes at least one capital letter, one number and one special character  `);
        }
    }
    static checkGender(gender) {
        if (!["male", "female"].includes(gender.toString().toLowerCase())) {
            throw new Error("Gender, male or female only")
        }
    }

    // - data (nieważne jaka wejdzie) do konstruktora musi wejść w formacie MM/DD/YYYY

    static checkDate(value) {
        const regex = /^d{2}/d{2}/d{4}$/g
        const correctDate = regex.test(value)
        if (!correctDate) {
            throw new Error("Incorrect date format. Correct one is MM/DD/YYYY")
        }
    }

    static checkInputAccessLevel = (accLevel) => {
        if (!["admin", "user"].includes(accLevel.toString().toLowerCase())) {
            throw new Error(`Access level is not an "admin" or "user"`)
        }
    }

}
class User {
    constructor(name, secondName, dateOfBirth, password, gender, emailAddress) {
        Validator.isStrings(name, secondName)
        // Validator.checkInputAccessLevel(accessLevel)
        Validator.checkPassword(password)
        Validator.checkGender(gender)
        Validator.checkEmail(emailAddress)
        Validator.checkDate(dateOfBirth)

        this.name = name
        this.secondName = secondName
        this.dateOfBirth = dateOfBirth
        this.password = password
        this.gender = gender
        this.emailAddress = emailAddress
        this.accessLevel = "user"
    }
    changeName = (value) => {
        this.name = value
    }
    changeSecondName = (value) => {
        this.secondName = value
    }
    changeDateOfBirth = (value) => {
        this.dateOfBirth = value
    }
    changeGender = (value) => {
        this.gender = value
    }
}



class Admin {
    constructor(name, secondName, dateOfBirth, password, gender, emailAddress) {
        Validator.isStrings(name, secondName)
        // Validator.checkInputAccessLevel(accessLevel)
        Validator.checkPassword(password)
        Validator.checkGender(gender)
        Validator.checkEmail(emailAddress)
        Validator.checkDate(dateOfBirth)

        this.name = name
        this.secondName = secondName
        this.dateOfBirth = dateOfBirth
        this.password = password
        this.gender = gender
        this.emailAddress = emailAddress
        this.accessLevel = "admin"
    }

    setPassword = (newPassword) => {
        Validator.checkPassword(newPassword)
        this.password = newPassword
    }
    setEmail = (newEmail) => {
        Validator.checkEmail(newEmail)
        this.emailAddress = newEmail

    }
    setAccessLevel = (level) => {
        Validator.checkInputAccessLevel(level)
        this.accessLevel = level
    }

}

class App {
    constructor() {
        this.allUsers = []
    }
    createAdmin = (name, secondName, dateOfBirth, password, gender, emailAddress) => {
        const admin = new Admin(name, secondName, dateOfBirth, password, gender, emailAddress)
        this.allUsers.push(admin)
        return admin
    }
    createUser = (name, secondName, dateOfBirth, password, gender, emailAddress) => {
        const user = new User(name, secondName, dateOfBirth, password, gender, emailAddress)
        this.allUsers.push(user)
        return user
    }
    showAllUsers = () => {
        return this.allUsers
    }
}


// const userAdmin = new Admin("John", "Smith", "27/02/1969", "Password!@#1!", "male", "[email protected]")
// const userUser = new User("Andy", "Hopkins", "07/02/1999", "AndyHopkons!@#1!", "male", "andyHopkons!@#[email protected]")

// console.log(userAdmin)
// console.log(userUser)


const app = new App
app.createAdmin("John", "Smith", "27/02/1969", "Password!@#1!", "male", "[email protected]")
app.createUser("Andy", "Hopkins", "07/02/1999", "AndyHopkons!@#1!", "male", "andyHopkons!@#[email protected]")

console.log(app.showAllUsers())

Hide HERE Map API Key to use with document object

I’m making an express application that requires a map. I’m using the HERE Maps API for javascript boilerplate to render the map. https://developer.here.com/documentation/examples/maps-js

I am already using the dotenv package for environment variables (port, host) in my application. But I don’t know how to hide the map API key in the backend when I need to use the document object to render the map. Currently, I’m using a separate file config.js to store the variable but the key is still visible in the frontend.

In conclusion, I can hide the API key in the backend but I can’t render the map in the backend and I can render the map in the frontend but I can’t hide the API key in the frontend. How can I both hide the API key and render the map?

Minimum, reproducible, example:-

Structure of root directory

| public
    | config.js
    | map.js
| views
    | index.pug
| .env
| index.js
| package.json

index.pug

doctype html
html
    head
        link(rel="stylesheet" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css")
        script(src="https://js.api.here.com/v3/3.1/mapsjs-core.js")
        script(src="https://js.api.here.com/v3/3.1/mapsjs-service.js")
        script(src="https://js.api.here.com/v3/3.1/mapsjs-ui.js")
        script(src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js")
        script(src="config.js" defer)
        script(src="map.js" defer)
    body
        #map(data-lat=lat data-lng=lng)

config.js

const config = {
    MAP_API_KEY: `${API_KEY}`
}

map.js

const mapEl = document.getElementById('map')
const platform = new H.service.Platform({
    apikey: config.MAP_API_KEY
})
const defaultLayers = platform.createDefaultLayers()
const map = new H.Map(mapEl, defaultLayers.vector.normal.map, {
    center: {
        lat: parseFloat(mapEl.dataset.lat),
        lng: parseFloat(mapEl.dataset.lng)
    },
    zoom: 5,
    pixelRatio: window.devicePixelRatio || 1
})
window.addEventListener('resize', () => map.getViewPort().resize())
const behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map))
const ui = H.ui.UI.createDefault(map, defaultLayers)

Angular click event on button wont fire until clicked twice

I’m currently creating an application in angular. The module I am working on gives you ability to join or create a room.

The initial ui of the room module:
https://gyazo.com/81afe2b5f7119326d00b518fc4e0979f

upon clicking on “join room” button we go to the join ui:
https://gyazo.com/0728a182b27a143fcefd9d71d0c33c44

once I click on the Join button i get an error of:
ERROR DOMException: An attempt was made to use an object that is not, or is no longer, usable

However, once i click the join button for the second time I am able to connect to the websocket server and get no issues

I believe it has something to do with the use of *ngIf and the dom not loading properly
the main code for the html is :

<button *ngIf="isEnterRoomShown" id="createRoomBtn" mat-raised-button (click)="createRoom()">Create Room</button>
  <button *ngIf="isEnterRoomShown" id="joinSessionBtn" mat-raised-button (click)="joinRoom()">Join room</button>
  <div [hidden]="isEnterRoomShown">
    <button  id="join" mat-raised-button (click)="join()">Join</button>
  </div>

and the component:

  createRoom() {
    const name = this.nameInput.nativeElement.value;
    this.websocket = this.wsService.initWebsocket();
    const wsData = {
      message: "create-room",
      name,
    };
    this.rService.username = name;
    if (this.websocket.readyState === 0) {
    }
    this.waitForSocketConnection(this.websocket, () => {
      this.websocket.send(JSON.stringify(wsData));
    });
  }

  joinRoom() {
    // console.log(this.joinRoomForm.value.roomId);
    // console.log(this.joinRoomForm.value.name);
    this.isEnterRoomShown = !this.isEnterRoomShown;
  }

  join() {
    console.log("join?");

    if (!this.websocket) {
      this.websocket = this.wsService.initWebsocket();
    }
    console.log("before name");
    const name = this.nameInput.nativeElement.value;
    console.log("after name");
    this.rService.username = name;
    console.log("after service");
    if (this.websocket) {
      this.websocket.send(
        JSON.stringify({
          message: "join-room",
          name,
          id: this.roomId.nativeElement.value,
        })
      );
    }

    this.outRoom = false;
    console.log("setting session id");
    this.sessionId = this.roomId.nativeElement.value;
  }

I am still pretty new to stackoverflow and angular development, please let me know if you need extra clarification on anything. I have tried to search for similar questions on stackoverflow and have found no answers.

Confused about the strange performance of useMemo Hook in React

This is my own hook which is used to realize debounce in React Hooks

import { useMemo, useRef } from "react";
import { debounce } from "lodash";

export function useDebounceFn(fn, wait) {
  const fnRef = useRef(fn)
  fnRef.current = () => {
    debugger
    fn()
  }

  const debounceFn = useMemo(() => {
    // can get the newest fn everytime
    return debounce(() => {
      fnRef.current()
    });

    // only can get the first fn
    return debounce(fnRef.current);
  }, []);

  return {
    run: debounceFn,
    cancel: debounceFn.cancel,
  }
}

I think debounce(fnRef.current) is equal to debounce(() => { fnRef.current() } ,but the truth is that they are different and i wonder why. Is there any wrong with my code or just useMemo do something different in these two cases.

Set number input max based on the sum of 4 inputs using jquery and reset quantity

I followed this thread Set number input max based on the sum of 4 inputs using jquery and the code below works as expected:

$("input[type='number'].wapo-product-qty").val(0); 
$("input[type='number'].wapo-product-qty").change(function () {
$.each($("input[type='number'].wapo-product-qty"), function (index, element) {
    var total = 0;
    $.each($("input[type='number'].wapo-product-qty").not($(element)), function 
(innerIndex, innerElement) {
        total += parseInt($(innerElement).val());
    });
    if ($(element).val() > 6 - total) {
        alert("The total value for all inputs can not exceed 6");
                  $(element).val(0);
        return false;
    } else {
        $(element).attr("max", 6 - total);
        }
    });
});

But I need the quantity selector to start from 0 and not from 1.

I added this for that, but I don’t know is the best approach:

 $("input[type='number'].wapo-product-qty").val(0); 

Once the condition of the maximum number of quantities is reached, the fields for which the quantity has not been selected with the selector are reset to 0.

For example in my case:

4 input fields: 

0 -> change to 2
0 -> change to 2
0 -> change to 2
0 -> change to 1 -> we are over 6, condition reached

But the last input it remains 1, so I would like to reset to 0 for this reason.

Thanks

jquery html return php Uncaught SyntaxError: Unexpected identifier

I’m trying to jquery to return php value inside div I’m using .html() but I did get Uncaught SyntaxError: Unexpected identifier
my html code is :

<script>
        $( document ).ready(function()
            $('#post-msg-<?= $divId ?>').html(`<?= humhubactionsTextFormatAction::text_html($model->message) ?>`);
        });
    </script>

on inspect element I see my php code is :

$( document ).ready(function() {
            $('#post-msg-e369853df766fa44e1ed0ff613f563bd').html('<p></p><img src="http://127.0.0.1/index.php?file=d2dd907d-bfd4-40ab-832f-bd8c161fd60e+" alt="" title="" />
<p> 
            <div class="div-div">
                <div>
                    <div class="div-title-description">
                        <h2>
                            <span class="div-title">Title-text</span>
                        </h2>
                        <p class="div-description">Description - text </p>
                    </div>                
                </div>
            </div>
        </p>
');
        });

How to render multiple notifications with help of notistack in react?

I’m trying to use React’s ‘notistack’ module to display several notifications as a stack. However, it appears that I am making a mistake, as Whenever I receive a warning:

react_devtools_backend.js:3973 Warning: Cannot update during an existing state transition (such as within render)

I’m using the state here to set the Response messages(they are coming from api), which are an array of notifications. Once the alerts have been rendered, I should also make the state of the Response messages an empty array.

renderPage.js

import React, { useState, useContext } from "react";
import axios from "axios";

import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";

import { SnackbarProvider } from "notistack";

import Zoom from "@material-ui/core/Slide";

import Notification from "../../components/Notification";
import { handleResponse } from "../../services/responseHandler";
import { SelectedRunnerContext } from "./RunnersPage";

export function RunnersForm() {
    const { selected } = useContext(SelectedRunnerContext);
    const [responseMessages, setResponseMessages] = useState([]);
    const notistackRef = React.createRef();
    const onClickDismiss = (key) => () => {
        notistackRef.current.closeSnackbar(key);
    };

    const MakePostRequest = (event) => {
        event.preventDefault();
        setResponseMessages([]);
        const data = {
            selected_runners: selected,
        };

        const requestOptions = {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            body: data,
        };
        axios
            .post("/messages", requestOptions)
            .then((response) => {
                const result = handleResponse(response.data);
                setResponseMessages(result);
            })
            .catch((error) => {
                console.log(error);
            });
    };

    return (
        <>
            <Button onClick={MakePostRequest}>Post</Button>
            {!!responseMessages.length && (
                <SnackbarProvider
                    maxSnack={4}
                    ref={notistackRef}
                    dense
                    preventDuplicate
                    anchorOrigin={{
                        vertical: "bottom",
                        horizontal: "right",
                    }}
                    TransitionComponent={Zoom}
                    sx={{
                        width: 700,
                    }}
                    style={{
                        fontSize: 15,
                        fontWeight: 700,
                    }}
                    action={(key) => (
                        <Button onClick={onClickDismiss(key)}>
                            <Typography
                                variant="subtitle2"
                                style={{
                                    fontWeight: 600,
                                    fontSize: 16,
                                    color: "#00579b",
                                }}
                            >
                                Dismiss
                            </Typography>
                        </Button>
                    )}
                >
                    <Notification messages={responseMessages} />
                </SnackbarProvider>
            )}
        </>
    );
}

Notification.js

import React, { Fragment } from "react";
import { useSnackbar } from "notistack";

export default function Notification(props) {
    const { enqueueSnackbar } = useSnackbar();
    const { messages } = props;
    const options = {
        variant: "success",
        autoHideDuration: 6000,
        transitionDuration: { enter: 400, exit: 400 },
    };

    messages.forEach((msg) => {
        enqueueSnackbar(msg, options);
    });
    return <></>;
}

How to make a squiggly button

I want to make squiggly buttons that works like what it’s supposed to without checking for every pixel in the squiggly button.
I also would like to stack them up like clicking on countries within borders.
What is the simplest way to do this?

replace the array of elements with the help of another array of elements if its have both common value

here is logical question
this is my referenceArray to compare and change with originalArray

const referenceArray = [
                       { name: 'animal', source: ['duck', 'cat'], target: ['water', 'ground'] },
                       { name: 'car', source: ['tata', 'kia'], target: ['tiago', 'sector'] },
                       { name: 'bike', source: ['honda', 'hero'], target: ['livo', 'xtream'] },
                       { name: 'vehicle', source: ['honda', 'hero'], target: ['hard', 'soft'] },
                       ];

and this is i want to change the array originalArray
source and target values with the help of referenceArray source and target
if its matched take name value and set thet value to originalArray source and target

const originalArray = [
    { source: 'water', target: 'hero' },
    { source: 'tata', target: 'ground' },
    { source: 'livo', target: 'kia' },
    { source: 'hero', target: 'sector' },
  ];

here is the expected output how we want

 const output1 = [
    { source: 'animal', target: ['bike', 'vehicle'] },
    { source: 'car', target: 'animal' },
    { source: 'bike', target: 'car' },
    { source: ['vehicle', 'bike'], target: 'car' },
  ];


 const output2 = [
    { source: 'animal', target: 'bike' },
    { source: 'animal', target: 'vehicle' },
    { source: 'car', target: 'animal' },
    { source: 'bike', target: 'car' },
    { source: 'vehicle', target: 'car' },
    { source: 'bike', target: 'car' },
  ];

any output is acceptable for me if you get output2 that is more appreciable

I’m confusing how to achieve this data format without getting key value conflicts
please anyone can help me out please that is so appreciable

thanks advance

Error: animal.image.map is not a function

I am currently making a shelter web app using mern stack and i am struggling to display an image from my object. i already used the map but i think it is only for array objects. so i am clueless how to get the images.url on my animal object.

this is my animalSchema

const mongoose = require('mongoose')

const animalSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please enter name'],
        trim: true,
        maxLength: [100, 'The name cannot exceed 100 characters']
    },
    ...
    image: 
        {
            public_id: {
                type: String,
                required: true
            },
            url: {
                type: String,
                required: true
            },
        }
})
module.exports = mongoose.model('Animal', animalSchema);

AnimalReducer

export const animalDetailsReducer = (state = { animal: {} }, action) => {
    switch(action.type) {
        case ANIMALS_DETAILS_REQUEST:
        return {
            ...state,
            loading: true,
        }
        case ANIMALS_DETAILS_SUCCESS:
        return {
            loading:false,
            animal: action.payload,

        }
        case ANIMALS_DETAILS_FAIL:
        return {
            ...state,
            error: action.payload
        }
        case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }
        default:
        return state;
    }
}

and this is what i use on my frontend for showing the animal details

                            {animal.image && animal.image.map(img => (
                                    <div key={img.public_id}>
                                        <img className="d-block w-100" src={img.url} alt="" />
                               

Animal’s name, gender, breed and type are showing, only the animal.url is not.

Convert Manifest V2 to V3 [closed]

Someone can convert this Manifest V2 to Manifest V3 for me ?

{
    "background": {
        "scripts": ["assets/pack.js", "background.js"]
    },
     "browser_action": {
        "default_popup": "popup.html"
     },
    "web_accessible_resources": ["assets/css.css", "assets/pack.js", "assets/Observe.js", "assets/script.js", "assets/DragonBound.js"],
    "name": "Company X",
    "description": "Company X",
    "manifest_version": 2,
    "version": "1.0.131",
    "icons": {
        "16": "assets/icons/16.png",
        "19": "assets/icons/19.png",
        "24": "assets/icons/24.png",
        "32": "assets/icons/32.png",
        "48": "assets/icons/48.png",
        "64": "assets/icons/64.png",
        "128": "assets/icons/128.png",
        "256": "assets/icons/256.png",
        "512": "assets/icons/512.png"
    },
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
    "permissions": ["*://*/*", "tabs", "webRequestBlocking", "webRequest", "management"]
}