ERRO DE NODE_MODULE_VERSION

I have a error, inside project Node_MODULE_VERSION is 82, but outside a project Node_MODULE_VERSION is 93, how can i fix it?
i already downgrade and upgrade, but none of it works.
Outsidea project

{
  "node": "16.13.0",
  "v8": "9.4.146.19-node.13",
  "uv": "1.42.0",
  "zlib": "1.2.11",
  "brotli": "1.0.9",
  "ares": "1.17.2",
  "modules": "93", <<<<<<<<<
  "nghttp2": "1.45.1",
  "napi": "8",
  "llhttp": "6.0.4",
  "openssl": "1.1.1l+quic",
  "cldr": "39.0",
  "icu": "69.1",
  "tz": "2021a",
  "unicode": "13.0",
  "ngtcp2": "0.1.0-DEV",
  "nghttp3": "0.1.0-DEV"
}

Inside a project

{
  "node": "12.16.3",
  "v8": "8.5.210.26-electron.0",
  "uv": "1.34.2",
  "zlib": "1.2.11",
  "brotli": "1.0.7",
  "ares": "1.16.0",
  "modules": "82",<<<<<<<<<<<<<<<<<<<<<
  "nghttp2": "1.41.0",
  "napi": "5",
  "llhttp": "2.0.4",
  "http_parser": "2.9.3",
  "openssl": "1.1.0",
  "icu": "67.1",
  "unicode": "13.0",
  "electron": "10.4.2",
  "chrome": "85.0.4183.121"
}

the erro is in a image:
enter image description here

How to properly catch a HTTP error status code when using fetch?

When you use the fetch API in JavaScript and the result contains a status code that isn’t OK (not 2xx), an error that includes the status code and the method is being logged to the console in most browsers (I’ve tried Chrome, Edge and Opera). This makes sense, as this type of response usually means some kind of error on your side.

However this error is also present when using a .catch chain on your Promise (this is the most basic code example):

fetch("<some api call that returns a status code of 400>")
    .catch(_ => {});

This gives the same error in the console as not catching it.

If .catch(_ => {}) does not work, is there a way to suppress this error?

Typescript – Create custom type from common properties of an Array of object

I have an array of objects, which have a common key “foo” and I am trying to create a custom type out of this property

class Object1 {
   static foo = { reducer_one: {...} }
   object_1_method() {...}
}

class Object2 {
   static foo = { reducer_two: {...} }
   object_2_method() {...}
}

class Object3 {
   static foo = { reducer_three: {...} }
   object_3_method() {...}
}

const myArray = [Object1, Object2, Object3 ];

I am trying to get a reduced object type gathering all the different foo properties of all the initial objects in the array.

const finalObject = {
   reducer_one: {...},
   reducer_two: {...},
   reducer_three: {...}
}

I tried to reduce the array to an object with the objects’ respective foo property in order to retrieve its type but the output type of the reduce remains an empty object.

Thanks in advance for your help. Hope the description of the issue is clear enough

How to query for an object within an array in mongoose

I’m new to mongoose and I’m having trouble querying for specific objects within an array.

My data model looks like this:

{
  "users": [
    {
      "_id": "61b0d6637e169ddebf72c18a",
      "name": "Brian Test",
      "email": "[email protected]",
      "password": "xxx",
      "accountType": "type1",
      "__v": 0,
      "title": "title1",
      "about": "about1",
      "education": [
        {
          "recordId": 1,
          "institution": "institution1",
          "title": "title1"
        },
        {
          "recordId": 2,
          "institution": "institution2",
          "title": "title2"
        },
        {
          "recordId": 3,
          "institution": "institution3",
          "title": "title3"
        }
      ]
    }
  ]
}

The query I need is to perform a crud on education records. For it I’ll have the user ID and the education record ID.

I’m not sure how to nest the education record query within the user query.
I’ve tried something like this but It’s not working.

let user = await User.findOne({_id: req.user.user.id})
let recordToUpdate = await user.education.findOne({recordId: req.body.recordId})
console.log(recordToUpdate)

I’ll appreciate if you could give examples for reading, updating and deleting records aswell.
Thanks!

[nest]: property not available in the current context error

I’m trying to use a service inside a decorator and this decorator is used over ServiceX function, which is called from some serviceY. However getting an error. Spent quite a long time with no success. Any help will be appreciated.

Error: Nest can't resolve dependencies of ServiceX. Please make sure that the "logger" property is available in the current context.
// myDecortor.ts

import { Inject } from '@nestjs/common';
import { LoggerService } from '../../logger/logger.service';

export function myDecorator(bubble = true) {
  const injectLogger = Inject(LoggerService);

  return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
    injectLogger(target, 'logger');  // This logger property is not accessible to ServiceX

    //get original method
    const originalMethod = propertyDescriptor.value;

    //redefine descriptor value within own function block
    propertyDescriptor.value = async function(...args: any[]) {
      // something
    };
  };
}

importing LoggerModule in ServiceXModule

// serviceX.module.ts

import { LoggerModule } from '../../logger/logger.module';
/// .....

@Module({
  imports: [LoggerModule],
  providers: [serviceX],
  exports: [ServiceX],
})


Using decortor over a method of ServiceX class.

// serviceX.service.ts

import { myDecorator } from '../logger/myDecorator';

@myDecorator()
async serviceXfunction() {
  //some more stuff
}

Importing serviceX module in ServiceY

// serviceY.module.ts

import { ServiceXModule } from '../../logger/serviceX.module';
/// .....

@Module({
  imports: [ServiceXModule],
  providers: [serviceY],
  exports: [ServiceY],
})


// serviceY.service.ts

import { ServiceX } from '../logger/serviceX.service';

constructor(private readonly serviceX: ServiceX){}

async serviceYfunction() {
  await serviceX.serviceXfunction();
}

How to hide on page load [duplicate]

I’m making a prank .html page for a friend. The prank was, you would push a button and a phrase would pop up under the button. I figured out a way to hide the phrase and unhide it. The problem is that, when you load into the page, the phrase would already be on the screen. How do I keep it hidden on page load?

function Function() {
  var x = document.getElementById("urmom");
  
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<button onclick="Function()">Try it</button>

<div id="urmom">
  ur mom
</div>

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

create javascript map with two keys

I would like to create a map in JavaScript with two keys or need to know if there is a better solution. I need to know if key1 is part of the collection and if so get data1 and in another case I need to know if a value of type key2 is part of the collection and get its data. How do you do this in JavaScript?

Example:

const contacts = new Map();
contacts.set('key_person',  {phone: "617-555-4321", address: "321 S 2nd St"});

const contacts2 = new Map();
contacts.set('key_city',  {phone: "617-555-4321", address: "321 S 2nd St"});

At the moment I have maps with redundant information in order to get data by key_person and key_city. I want a joint map where I can filter for both keys at a time. Thanks you

Calling jest.clearAllMocks() in beforeEach clears calls within a test?

I’m seeing an issue in Jest where calling jest.clearAllMocks() inside a beforeEach callback seems to wipe out calls to a mocked function that are made not before but WITHIN a specific test. I can repro it as follows:

THIS PASSES:

__tests__/testy.test.js

const AWS = require("aws-sdk");
const { handler } = require("../index.js");

describe("Lambda function tests", () => {
    it("sent the expected CSV data to S3", async () => {
        // RUN THE LAMBDA, await completion
        await handler();
        // The S3 constructor should have been called during Lambda execution
        expect(AWS.S3).toHaveBeenCalled();
    });
});

THIS GIVES ME A FAILURE:

__tests__/testy.test.js

const AWS = require("aws-sdk");
const { handler } = require("../index.js");

describe("Lambda function tests", () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });
    it("sent the expected CSV data to S3", async () => {
        // RUN THE LAMBDA, await completion
        await handler();
        // The S3 constructor should have been called during Lambda execution
        expect(AWS.S3).toHaveBeenCalled();
    });
});

The failure message in the console:

expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

I’m using jest version 27.4.3 in Node v14.18.1. In case it matters, I’m mocking aws-sdk like this:

__mocks__/aws-sdk.js

const AWS = jest.createMockFromModule("aws-sdk");

AWS.S3 = jest.fn().mockImplementation(() => ({
    upload: jest.fn(() => ({ promise: jest.fn() })),
    headObject: jest.fn(() => ({
        promise: jest.fn(() => ({ ContentLength: 123 })),
    })),
}));

module.exports = AWS;

What could be happening here?

How to render a list of array items depending on the selected calendar item in a Vue project?

Here’s the calendar I’m talking about:

CalendarApp

So, basically, I’ve tried to create a following feature: Each day item contains an empty array which will then contain the N number of tasks that are added to that empty array by the purple button below depending on which day is active (The highlighted one), so each day item will have its own array of tasks and I can switch between them to see how many tasks on which day are created. I use Vuex and Vue3 Composition API for this project.

Calendar component:

Calendar.vue

<template>
<div class="wrapper">
  <div class="calendar-wrapper">
      <div class="calendar-row"
           v-for="(day, idx) in dayArr"
           :key="idx"
        >
          <div
            id="card"
            class="day-card "
            :class="{ 'active' : activeDay === idx + 1 }"
            @click="switchDay(idx)"
          > 
              <div class="card-info">
                <p class="name">{{ day.dayOfWeek }}</p>
                <p class="day">
                    {{ day.currDay }} 
                </p>
              </div>
             <div class="dot-wrapper">
                <div class="dot-status undone" />
                <div class="dot-status undone" />
             </div>
          </div>

      </div>
  </div>
</div>
</template>

<script>
/* eslint-disable no-unused-vars */
import { useStore } from 'vuex'
import { onMounted, ref } from 'vue'

export default {
  
  /*=============================================
  =            Setup            =
  =============================================*/
    setup() {
    // ? Turn the remaining days into an array 
    const fillDayArray = () => {
      dayArr.value = Array(daysRemainingThisMonth)
        .fill('')
        .map((item, index) => {
          return {
            currDay: moment().add(index, 'day').format('D'),
            dayOfWeek: moment().add(index, 'day').format('dddd'),

            // Empty array for added tasks:
            tasks: []
  
          };

      })

      }
     // Make the clicked day active
    const switchDay = (idx) =>  {
      activeDay.value = idx + 1
    }

    onMounted(() => {
      fillDayArray() 
      
    })

</script>

Area where tasks are rendered and created:

TaskView.vue

<template>
    <div class="task-wrapper">
        <p id="task-counter">
            Tasks Today: {{ taskArr.length }}
        </p>
        <div class="task-counter-wrapper">                 
            <!-- ? Render if there are no tasks available: -->
            <div 
                class="empty-msg"
                v-if="taskArr.length == 0"
            >
                <p>Start by adding a New Task!</p>
            </div>

            <div 
                class="task-list" 
                v-for="(task, idx) in taskArr"
                :key="idx"
            >
                <div class="list-item">
                    <div class="container">
                        <input class="list-checkbox" type="checkbox">
                        ({{ idx + 1}}) {{ task.name }}
                    </div>

                    <div class="item-actions">
                        <button 
                            class="edit-item btn"
                            @click="getClickedTask(task)"
                        > 
                            <img class="icon" src="./Images/editing.png">
                        </button>

                        <button 
                            class="delete-item btn"
                            @click="deleteItem(idx)"
                        >
                            <img class="icon" src="./Images/delete.png">
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="item-card">
            <ItemCard />
        </div>  

        <div class="add-task-wrapper">
            <button 
                id="add-task-btn"
                @click="addItem()"
            >
                + Add a new task
            </button>
        </div>
    
    </div>
</template>

<script>
/* eslint-disable vue/no-unused-components */
import ItemCard from './ItemCard.vue'
import { useStore } from 'vuex'
// import { computed } from '@vue/reactivity'

export default {
    components: {
        ItemCard
    },

    setup() {
        const store = useStore()
        const taskArr = store.state.taskArr
    
    
        const getClickedTask = (item) => {
            store.state.clickedTask = item
            
            store.state.cardStatus ?
                store.state.cardStatus = false 
                :
                store.state.cardStatus = true
        };

        // ! Delete Item:
        const deleteItem = (idx) => {
            store.state.taskArr.splice(idx, 1)
        }

        const addItem = () => {
            store.state.taskArr.push(
                {
                    name: 'Empty Task' + Math.random().toString().substring(0, 4), 
                    description: 'No description...' 
                }
            )
        }
            
    },

}
</script>

Main area where all other component are rendered:

Main.vue

<template>
 <div id="main">
     <!-- ! Top Level: -->
    <div class="auth">
        
    </div>
    
    <div class="greeting-block">
         <button @click="signOutUser">Sign Out</button>
         <h1 id="greet-user"> {{ user?.email }}</h1>
    </div>

     <div class="header-container">
         <Header />
         <Menu />
         
     </div>

    <div class="calendar-display">
        <Calendar />
    </div>

 
    <div class="task-list">
        <TaskView />
    </div>

 </div>
</template>

<script>
/* eslint-disable vue/no-unused-components */
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
// ? UI Components:
import Header from './Header.vue';
import Calendar from './Calendar.vue';
import Menu from './Menu.vue';
import TaskView from './TaskView.vue';
// ? Auth components:
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Auth from '../Auth.vue'
// ? Firebase:
import { getAuth } from '@firebase/auth'
import { signOut } from '@firebase/auth'
import { useAuthState } from '../firebase'
// ? Router:
import { useRouter } from 'vue-router'
// ? Store: 
import { useStore } from 'vuex'
// ? ref():
import { ref } from 'vue'


export default {
    components: {
        Header,
        Calendar,
        Menu,
        TaskView,
        Login,
        Register,
        Auth
    },
     name: 'Home',

    setup() {
        /*=============================================
        =            Firebase            =
        =============================================*/
        const { user } = useAuthState()
        const auth = getAuth()  

        const router = useRouter()
        const signOutUser = async () => {
            try {
                await signOut(auth)
                router.push('/auth')
            
            } catch(e) {
                alert(e.message)
            }
        }
        /*=====  End of Firebase  ======*/
        const store = useStore()


        const taskArr = store.state.taskArr
        
    }
}
</script>

Vuex store

index.js

state: () => {
    return {
      cardStatus: false,

      clickedTask: null,
      taskStatus: null,

      dayIsActive: 'active',

      cardVisible: true,
      // The desired array
      taskArr: [ ]
    }
  },

I think that I probably need to use props, but I really have no idea how do I implement this here. Any ideas would be very appreciated!

Javascript: Creating and Calling Dynamic Variables? [duplicate]

I have a script that contains 3 questions. I have started by creating 3 variables (ex: var q1 = “question here”) and I have a function that randomly picks a number between 1 and 3 and chooses that question (var question = “q” + rand;) but if I want to reference this variable called question to output the question in HTML (ex: document.getElement.Id(“output”).innerHTML += question;) how would I do so?

Here is my code:

// Questions List
        var q1 = " Question 1 here"
        var q2 = "Question 2 here"
        var q3 = "Question 3 here"

  // Randomly generate a question and then output it
        var randy = Math.floor(Math.random()*3+1);
        var question = "q" + randy;
        document.getElementById("output").innerHTML += question;
        
    
<!doctype html>
<html>
<body>
  <div id="output"></div>
</body>
</html>

So basically the script will choose a question from 1 to 20 and output it to my HTML div tag.

Sorry if this isn’t clear. Any help is greatly appreciated.

React Native encrypt a message with publicKey. Convert encrypted to base64

I need to do, for react native, encryption of a message.
I tried several libraries, but none worked.
(
JSEncrypt (not supported)
NODERSA (didn’t work)
expo-crypto (I couldn’t set the public key because I have my key)
react-native-rsa (it didn’t work either because of the key)
)

I wonder if anyone knows a way to do this!?


I have the public key and the message.
I need to encrypt the message with the public key and pass it to base64.

Multiple Calls to Custom Hook not yielding expected result

I am having a hard time understanding why the onClick event handler (which invokes 2 calls to a custom hook wrapper function) is not responding properly. I expect that everytime I click the button in the example would swap its border color from green to red based on a value that is being incremented. I understand the example is rudimentary and could easily be solved by conditioning the error prop on the value.value instead of sharing , but this is a simplified example of a more complex interaction, and I have boiled down the issue to a simple example for clarification. Any help would be appreciated.
https://codesandbox.io/s/custom-hooks-with-closure-issue-2fc6g?file=/index.js

Why does my tab don’t change when clicking the button?

I’m developing a new website, with a multi-step form where the steps are all in separated divs. The problem is: when i click in the first button, it shows the second page, but then it goes back to the first.
Here’s my javascript code:

<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
}

function next(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab"); 
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= x.length) {
    //...the form gets submitted:
    document.getElementById("regForm").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);

}

</script>

My html/php code for first two divs:

 <div class="tab">
    <div id="layout">
        <div class="main">
            <div class="logo">
                <img src="pictures/propcomp.png"/>
            </div>   
            <div class="text">
                <h3 class="blue">Olá!</h3> <br>
                <h3 class="grey">Seja bem vindo(a) à empresa número 1 na pesquisa Google nesse modelo de férias. Bem como já temos mais de 11.300 inscritos no nosso canal no YouTube.</h3>
                <h3 class="blue"><strong>Parabéns!</strong></h3>
                <h3 class="blue normal"><strong class="negrito">Você foi pré-selecionado pelos nossos Analistas de Férias de Alto Padrão </strong> para
                    participar de uma consultoria <strong class="negrito">gratuita e exclusiva</strong> de férias onde na mesma você
                    conhecerá um método de viajar mais e melhor com sua família. Contudo o seu
                    tempo para gente vale ouro, então vamos te presentear com um brinde para que
                    você participe da consultoria. Leia até o final se você quiser saber qual é o brinde!</h3> <br>
            </div>
            <div class="home">
                <a href="">
                <button class="btn btn-beleza" type="button" id="nextBtn" onclick="next(1)">
                 <label class="beleza">Beleza! Quero Participar!</label> 
                <img src="pictures/arrow.svg" />
                </button>
            </a>
            <div class="beneficio">
                <a href="" style="display: flex;"><img src="pictures/interrogacao.svg"/><h4 class="blue normal">Por que estou recebendo esse benefício?</h4></a> 
                
       </div>
            </div>
            <div class="footerimg">
                                 <img style="width:30px; height: 44.5px;"src="pictures/logopequeno.png"/>
                </div>
        </div>
    </div>
</div>

<div class="tab">
<div class="layout">
        <div class="main">
            <div class="text">
                <div class="uausorriso">
                    <h3 class="blue negrito">Uauuuuuuuu, você é demais!!</h3> 
                    <img src="pictures/sorriso.png"/>
                </div>
                <h3 class="grey normal">Te parabenizamos por priorizar suas férias e novas experiências. Aliás, tudo passa e o
                    que fica são os momentos que vivemos com as pessoas que amamos. Afinal, qual é
                    a história que você vai contar?</h3>
                <h3 class="blue normal">Para começar, qual é o seu nome?</h3>
            </div>
            <div class="">
              
                    <input class="inputfield" style="margin-left:32%;"type="text" id="nome" name="nome"><br>
                   
                    <div class="avancar">
                    <a href="">
                    <button class="btn" type="button" id="nextBtn" onclick="next(1)">
                     <h3>Avançar</h3> 
                    <img src="pictures/arrow.svg" />
                    </button>
                </a>
                </div> 
        </div>
    </div>
</div>

I’ve put this online so you can see visually: https://testedeferias.000webhostapp.com/

Vue get params from url & path to app in subfolder of laravel

i used Vue 2.6 for little App with flipbook-vue, and i mounted it in subfolder of my Laravel APP in public/dist/.

I need to get params from url, and i do it like that:

Router index.js:

export default new Router({
  mode: 'history',
  routes: [{ path: "/:numer", component: Newspaper }]
})

vue.config.js:

module.exports = {
  publicPath: '/gazetka/',
}

And in Vue component i use $route.params to get this params.
The problem is that Vue reads the subfodler name dist to me as a parameter.
How do I get around it?
I tried .htaccess but it doesn’t work locally.