Referencing one array to make changes in another given certain conditions in JavaScript

I have an array, called arr1, example [9, 0, 0 ,9, 9]. I made a copy of this and called it arr2. I am trying to add the value one (1) to certain indexes in arr2, dependent on the index position of arr1 and it being a nine (9).

For example,

if arr1[0] == 9, add one (1) to indexes [0], [3], [4] in arr2  
if arr1[3] == 9, add one (1) to indexes [0], [2], [3] in arr2  
if arr1[4] == 9, add one (1) to indexes [0], [1], [4] in arr2

So arr2 becomes [12, 1, 1, 11, 11].

Hope this makes sense, bear with me, I’m new to this.

Cheers.

Unable to send props in vuejs

I am trying to send 2 props to my navbar component but it does not receive the data.

Here is what I get instead of my data:

one

Code:

Front.vue (upper template)

<template>
    <front-nav :menus="menus" :settings="settings"></front-nav>
    <router-view :key="$route.fullPath"></router-view>
    <front-footer></front-footer>
</template>

<script>
    import frontNav from './frontNavBar.vue';
    import frontFooter from './frontFooter.vue';
    export default {
        name: 'front',
        data(){
            return {
                settings: {
                    name: '',
                    favicon: '',
                    logo: '',
                },
                menus: [],
            }
        },
        components: {
            frontNav,
            frontFooter
        },
        mounted() {
            this.getData();
        },
        methods: {
            getData() {
                axios.get('/api/general')
                .then(response => {
                    this.settings = response.data.settings[0];
                    this.menus = response.data.menus;
                })
                .catch(function (error) {
                    console.log('error', error);
                });
            }
        },
    }
</script>

Nabar component (receiving props)

<template>
    <div>data goes here...</div>
</template>


<script>
    export default {
        name: 'frontNav',
        props: ['settings', 'menus'],
        data() {
            //
        },
        mounted() {
            console.log('settings: ', this.settings)
            console.log('menus: ', this.menus)
        },
        methods: {
            //
        }
    }
</script>

results of console.log('settings: ', this.settings) and console.log('menus: ', this.menus) are in image above.

Any idea?

react_devtools_backend.js:3973 Warning: Cannot update a component (`BrowserRouter`) while rendering a different component (`SocialLogin`)

I am getting this warning in react: Warning: Cannot update a component (BrowserRouter) while rendering a different component (SocialLogin).

I went to the locations indicated in the stack trace and removed all setstates but the warning still persists. Is it possible this could occur from redux dispatch?

my code:

SocialLogin.js

const SocialLogin = () => {
      const [signInWithGoogle, googleUser, googleLoading, googleError] =
        useSignInWithGoogle(auth);

  return (
    <div>
      <div className=" d-flex justify-content-evenly ">
        <button
          onClick={() => signInWithGoogle()}
          type="submit"
          className="btn btn-outline-primary"
        >
          <img className="px-2" src={google} alt="" />
          Sign in with Google
        </button>
      </div>
    </div>
  );
};

export default SocialLogin;

Render problem when lifting state up in React

After reading the documentation and good practices. I decided to lift up the state in my code for a specific page. When I do this, I cause my app to be laggy because now every time I am updating a specific field in a form, it triggers to re-render every others forms field along with other widgets.

I tried to use, memo on each of my components but apparently it has no effect and the re-render is triggered each time.

The problem is that the component in the picture is very 6 levels down compared to where I am declaring and updating the state. So, when I want to update the value of this specific component, bassically, it setState my whole page.
A example of one of my component

CSS stylesheet not being applied to my React components, but the exact same code works for another similar project

I tried to fit in as much as I could show in the screenshot!
https://i.stack.imgur.com/pjcVg.png
Does anyone have any insight on why this might be happening or tips I could try to troubleshoot this?

I linked the stylesheets the same way for both projects, but I needed to create a different stylesheet and link it directly in the file for the component in order for the styles to be applied.

TLDR:

Project 1: CSS file is only linked in index.html and the styles are applied across all the JS files automatically.

Project 2: CSS file is linked the exact same way as in Project 1, but the styles are not applied in the JS files. A new stylesheet was required to be imported into the JS files.

DatepickerInput defaultValue is not working

I’m working on a requirement to display current date in the date field.

In the below example, if I change defaultValue to value, I see the currentDate is being displayed on page load for date element. But even after selecting a different date, I see current date is getting displayed.

If I keep defaultValue, current date is not getting displayed. Could someone suggest on how to display currentDate on page load and the date can be changed if needed to any other date.

<DatepickerInput
                                    id="run-now-date-range-from"
                                    label="Time frame from date"
                                    isSrOnlyLabel={true}
                                    name="runNowOptions.dateRange.dateRangeFrom"
                                    defaultValue={currentDate}
                                    validate={value => {
                                        let error = "";

                                        if (!validateDate(value)) {
                                            error = controllerData?.reportTemplates[selectedReportTemplateIndex]?.runNowOptions?.dateRange?.showFutureDate
                                                ? "Please enter a from date up to 46 days in the future."
                                                : "Please enter a from date.";
                                        }

                                        return error;
                                    }}
                                    settings={{
                                        endDate: getDateRange(controllerData?.reportTemplates[selectedReportTemplateIndex]),
                                        startDate: controllerData?.reportTemplates[selectedReportTemplateIndex]?.runNowOptions?.dateRange?.showFutureDate ? "0d" : "",
                                    }}
                                />


import React, { InputHTMLAttributes } from "react";
import { InputProps } from "./utils/input-types";
export declare type DatepickerInputProps = InputHTMLAttributes<HTMLInputElement> & InputProps & {
settings?: any;
microcopy?: string;
validate?: (any: any) => string;
};
declare const DatepickerInput: React.FC<DatepickerInputProps>;
export default DatepickerInput;

Functon coding in JS using PIXI.Js

can anyone describe or give me explanation about below coding ???
where the function for pattern same object

and how to make the pattern over 3 same object, like 4 or 5

i’m very newbie about coding. i’m still learning what is the function

get arrayCardsID() {
const cards = Lib.arrShuffle(CARDS.map(card => card.id))
return Lib.arrShuffle(cards.reduce((acc, cur, i) => acc.concat(new Array(i + 1).fill(cur)), []))
}

createCombination() {
    const cardsID = this.arrayCardsID

    return new Array(4).fill(0).map(() => {
        return new Array(4).fill(0).map(() => {
            return cardsID[Lib.randomInteger(0, cardsID.length - 2)]
        })
    })
}

getLines(cmb, row = 0, col = 0) {
    const res = new Array(3).fill(0).map(() => {
        return { id: cmb[row][col], cards: [[row, col]] }
    })

    if (cmb[row]?.[col + 1] === cmb[row][col]) res[0].cards.push(...this.getLines(cmb, row, col + 1)[0].cards)
    if (cmb[row + 1]?.[col + 1] === cmb[row][col]) res[1].cards.push(...this.getLines(cmb, row + 1, col + 1)[1].cards)
    if (cmb[row - 1]?.[col + 1] === cmb[row][col]) res[2].cards.push(...this.getLines(cmb, row - 1, col + 1)[2].cards)

    return res
}

Why doesn’t load data into my collection? mongodb

This is what appears on my mongo databaseThis is my app.post to insert the data, when I Submit it console.log the object with the dates but with create It just says “null” ->
App listening on port 4000
{ ‘”title”’: ‘adaw’, ‘”body”’: ‘dwdw’ }
null { _id: new ObjectId(“6274a7a58d8946ca10ae57c4”), __v: 0 }

app.post('/posts/store',(req,res)=>{
            console.log(req.body)
            BlogPost.create(req.body,(error,blogpost) =>{
                console.log(error,blogpost)
            res.redirect('/')
            })
            })` 

How to get “Failed to fetch” reason?

Some of my users are encountering a “Failed to fetch” issue on certain fetch requests. I’m trying to figure out why. It’s fetching from the same domain, so it shouldn’t be a CORS issue.

Is there any way I can get more info? e.g. in Chrome, when I intentionally block the URL, it tells me blocked:devtools. Can I get similar info out of the error object in a .catch block? e.g. bad headers, CORS rejection, lost internet, whatever?

enter image description here

My button is not responding to my event listener?

Below is my code. I am trying to generate a random hex color that will replace the background color when my button is clicked but I can’t get it to work.

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Color Changer</title>
    </head>
    <body>
        <h1>
            <button id="newColor">Click Me</button>
        </h1>
    </body>
</html>

scripts.js

const btn = document.getElementById("newColor");

btn.addEventListener("click", function onClick(event) {
    let randColor = "#" + Math.floor(Math.random()*16777215).toString(16);
    document.body.style.backgroundColor = randColor;
});

How to run a CLI nodejs app on different TTYs?

My app should print logs and run a node.js REPL. But logs mess up the REPL, so I tried to run the REPL in another TTY.

Here is a sample code:

// app.js

const fs = require('fs')
const repl = require('repl')
const getTTYFile = () => '/dev/pts/4' // TODO

const TTYFile = getTTYFile()

let read = fs.createReadStream(TTYFile)
let write = fs.createWriteStream(TTYFile)
repl.start({
    input: read, output: write,
    terminal: true, useColors: true
})

setInterval(() => console.log('I am log'), 1000)

I opened a terminal tab without shells in KDE. Then I started my nodejs app:

konsole --new-tab --hold -e tty # outputs `/dev/pts/4`
node app.js

Here are the problems:

  • Input echoes twice, screenshot: konsole
  • Read-line doesn’t work (Can not move the cursor or clear screen…).

How should I fix my code?

Dealing with optional characters in regex

I’m trying to use regex to capture the URL from the @font-face CSS property, and I’m struggling to deal with the open and closing quotes (since they’re optional). Here’s what my current regex looks like (?<=url()(Insert Regex).

I’m using a look-behind to get everything that comes after url( — the “insert regex” portion is the part I’m struggling with.

Here’s an example of two separate cases that I’d want to solve for. The first one has no quotes surrounding the URL:

@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
src: url(fonts/montserrat-v18-latin-regular.eot');

The second case does have quotes surrounding the URL

@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 700;
src: url('fonts/source-sans-pro-v14-latin-700.eot');

Any help would be appreciated — thanks!

Score tracking is not functioning in my “Rock Paper Scissors” game

I am very new to Javascript and have decided on making a rock-paper-scissors game in an attempt to get comfortable with JS. Currently, I am noticing that when I click on a button (to choose rock, paper, or scissors), I notice that the score isn’t keeping track of whether the player wins or the computer wins. This also leads me to wonder if the functions in the JS file are working or not, which I am also unsure of.

What I have in my HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Rock-Paper-Scissors</title>
</head>
<body>
    <header>
        <h1>Rock Paper Scissors</h1>
    </header>

    <main>
        <div class="rules">
            <p>Which do you choose?</p>
            <p>First to score 5 wins</P>
        </div>
        
        <div class="scores">
            <div id="playerScore">
                <p>Player: 0</p>
            </div>

            <div id="computerScore">
                <p>Computer: 0</p>
            </div>
        </div>

        <div class="buttons">
            <button id="rock" type="submit" value="rock"><img src="./images/rock.svg" alt="rock"></button>
            <button id="paper" type="submit" value="paper"><img src="./images/paper.svg" alt="paper"></button>
            <button id="scissors" type="submit" value="scissors"><img src="./images/scissors.svg" alt="scissors"></button>
        </div>
    <script src="script.js"></script>
</body>
</html>

What I have in my JS file:

const queryElement = (query) => document.querySelector(query);

const playerPoints = document.querySelector('#playerScore');
const computerPoints = document.querySelector('#computerScore');
const rockEl = queryElement("#rock");
const paperEl = queryElement("#paper");
const scissorsEl = queryElement("#scissors");

const choices = [rockEl, paperEl, scissorsEl];

function onSelection() {
    console.log(this.value);
  }

let compScore = 0;
let playerScore = 0;

function computerPlay() {
    let choices = ["rock", "paper", "scissors"];
    return choices[Math.floor(choices.length * Math.random())];
} 

function playRound(playerSelection) {
    let computerSelection = computerPlay()
    
    if (playerSelection === "Rock" && computerSelection === "Scissors") {
        playerPoints.textContent = ++playerScore
        return("You Win!");
    } else if (playerSelection === "Rock" && computerSelection === "Paper") {
        computerPoints.textContent = ++compScore
        return("You Lose!");
    } else if (playerSelection === "Rock" && computerSelection === "Rock") {
        return("It's A Tie!");
    }
    
    else if (playerSelection === "Paper" && computerSelection === "Rock") {
        playerPoints.textContent = ++playerScore
        return("You Win!");
    } else if (playerSelection === "Paper" && computerSelection === "Scissors") {
        computerPoints.textContent = ++compScore
        return("You Lose!");
    } else if (playerSelection === "Paper" && computerSelection === "Paper") {
        return("It's A Tie!");
    }
    
    else if (playerSelection === "Scissors" && computerSelection === "Paper") {
        playerPoints.textContent = ++playerScore
        return("You Win!");
    } else if (playerSelection === "Scissors" && computerSelection === "Rock") {
        computerPoints.textContent = ++compScore
        return("You Lose!");
    } else if (playerSelection === "Scissors" && computerSelection === "Scissors") {
        return("It's A Tie!");
    } else
        return("Uh oh, something went wrong");
}

document.getElementById('rock').onclick = playerSelection;
document.getElementById('paper').onclick = playerSelection;
document.getElementById('scissors').onclick = playerSelection; 

function gameEnd() {
    if (playerScore > computerScore) {
        console.log("Game Over! You Win!");
    } else if (computerScore > userScore) {
        console.log("Game Over! You Lose!")
    }
}

function game() {
    console.log(playRound(playerSelection));
    if (playerScore < 5 && computerScore < 5) {
        game()
    } else {
        gameEnd();
    }
}

choices.forEach((choice) => {
    choice.addEventListener("click", onSelection);
  });

Javascript filter cachedata

How can i filter the Event_Type ? what I want is to get the value of Event_Type which is the MT

this is my current code

        if (cachedData) {
            let cachedDatas = JSON.parse(cachedData);
            for (var data in cachedDatas) {
                var keys = data == 'Event_Type' ? 'R150274705' : data;
                console.log("keys", keys)
                let code = data.filter((val) => {
                    return cachedDatas['Event_Type'] == val.code;
                })
            }
        }

this is the data

{"Event_Type":"MT","Subject":"","startDate":"07/05/2022 11:43 AM","startDateRaw":"2022-05-07T03","description":""}