how to conditionally define an array and avoid to have a null as element? [duplicate]

let’s say we have the following code:

var numberofZeroArray = [10, 10, 10, 10, 10];

and I want to add another number between the second and third elements conditionally using a toggle

var addMore = XXX() // XXX() return true or false

so that when addMore is true then the add a number 5

[10, 10, 5, 10, 10, 10]

if false, keep the original list unchanged:

[10, 10, 10, 10, 10]

I tried

var addMore = true;
var numberofZeroArray = [10, 10, addMore ? 5 : null 10, 10, 10];  // is OK when addMore is true
// result is [10, 10, 5, 10, 10, 10]

it doesn’t meet the expected result when addMore is false:

var addMore = false;
var numberofZeroArray = [10, 10, addMore ? 5 : null 10, 10, 10]; 
// result is [10, 10, null, 10, 10, 10]

I could use spread operator to define separate arrays for the first two elements and last three elements, but it is not feasible to do when the array contains a lot number of element. so what’s the most easy way to achieve it?

how to add css files to all pages except login ang registration pages in vue.js

I am using vue3 node.js ,

I have two pages login.html and registration.html which are served by backend when user access '/','/login' and '/register' routes.

If user logins successfully he is redirected to '/u/record/' route which have content which user is authorized to see; the content comes from database through node.js which send it to vue.js frontend as json data.

These login and registration pages have completely different css then the '/record' page.

I want to apply external css to all pages of vue.js except login and registration pages.

I tried to define nested routes and addded beforeEnter() navigation guard to '/u/' which will load CssC.vue component which imports the external css file.

index.js:(contains route)

import { createRouter, createWebHistory } from 'vue-router'
import UserLogin from '../views/UserLoginView.vue'
import CssC from '../components/CssC.vue';

const routes = [
  {
    path: '/',
    name: 'index',
    component:UserLogin
  },{
    path: '/login',
    name: 'login',
    component: UserLogin
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/UserRegisterView.vue')
  },{
    path: '/u',
    component: () => import('../views/UserRoutesView.vue'),
    beforeEnter: [
      CssC
   ],
    children: [
      {
        path:'/u/record',
        component: () => import('../views/RecordView.vue')
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

CssC.vue

<style>
    @import url('../assets/css/style.css');
</style>

error :

vue-router.esm-bundler.js?ec2d:72 
        
       [Vue Router warn]: uncaught error during route navigation:
warn @ vue-router.esm-bundler.js?ec2d:72
triggerError @ vue-router.esm-bundler.js?ec2d:3300
eval @ vue-router.esm-bundler.js?ec2d:3037
Promise.catch (async)
pushWithRedirect @ vue-router.esm-bundler.js?ec2d:3030
push @ vue-router.esm-bundler.js?ec2d:2966
install @ vue-router.esm-bundler.js?ec2d:3380
use @ runtime-core.esm-bundler.js?d2dd:3834
eval @ main.js?fbea:6
./src/main.js @ app.js:52
__webpack_require__ @ app.js:217
(anonymous) @ app.js:1398
__webpack_require__.O @ app.js:263
(anonymous) @ app.js:1399
(anonymous) @ app.js:1401
vue-router.esm-bundler.js?ec2d:3302 
        
       TypeError: guard.call is not a function
    at eval (vue-router.esm-bundler.js?ec2d:1934:1)
    at new Promise (<anonymous>)
    at eval (vue-router.esm-bundler.js?ec2d:1908:1)
    at eval (vue-router.esm-bundler.js?ec2d:3416:1)
triggerError @ vue-router.esm-bundler.js?ec2d:3302
eval @ vue-router.esm-bundler.js?ec2d:3037
Promise.catch (async)
pushWithRedirect @ vue-router.esm-bundler.js?ec2d:3030
push @ vue-router.esm-bundler.js?ec2d:2966
install @ vue-router.esm-bundler.js?ec2d:3380
use @ runtime-core.esm-bundler.js?d2dd:3834
eval @ main.js?fbea:6
./src/main.js @ app.js:52
__webpack_require__ @ app.js:217
(anonymous) @ app.js:1398
__webpack_require__.O @ app.js:263
(anonymous) @ app.js:1399
(anonymous) @ app.js:1401
vue-router.esm-bundler.js?ec2d:72 
        
       [Vue Router warn]: Unexpected error when starting the router: TypeError: guard.call is not a function
    at eval (vue-router.esm-bundler.js?ec2d:1934:1)
    at new Promise (<anonymous>)
    at eval (vue-router.esm-bundler.js?ec2d:1908:1)
    at eval (vue-router.esm-bundler.js?ec2d:3416:1)

But its not working ! what am I doing wrong ?
And also is there any other better way to do this ?

I can share any other files from my project if you need to look at it …

How do I properly set up Passport Google OAuth 2.0 with ExpressJS?

I am trying to set up some user authentication and want to use Google’s OAuth2.0 to do so.

So far, I have set up a Google API Project at console.cloud.google.com and gotten an OAuth 2.0 Client ID and Client Secret (let’s say clientID = 'myID.apps.googleusercontent.com' and clientSecret = 'mySecret'). Noodling around, I found that I should be using passport and I would like to use passport-google-oauth20 (Only because it has the most downloads, if there is something better PLEASE let me know). Following the instructions, I have:

.env.js

module.exports = {
    google: {
        clientID: 'myID.apps.googleusercontent.com',
        clientSecret: 'mySecret'
    }
}

app.js

const express = require('express')
const passport = require('passport')
const env = require('./.env.js')
const app = express()
const baseURL = 'https://api.mywebsite.com'

var GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
    clientID: env.google.clientID,
    clientSecret: env.google.clientSecret,
    callbackURL: baseURL + "/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return cb(err, user);
    })
  }
))

app.get('/auth/google', passport.authenticate('google', {scope: ['profile']})
)

app.get('/auth/google/callback', passport.authenticate('google', {failureRedirect: '/login'}), (req, res) => {
        // Successful authentication, redirect home.
        res.redirect('/');
    }
)

When I start the server and go to https://api.mywebsite.com/auth/google, I get redirected to https://accounts.google.com/signin/oauth/error?authError=some_mess&client_id=myID.apps.googleusercontent.com with an Error 400: redirect_uri_mismatch and referencing redirect_uri: http://127.0.0.1:5000/auth/undefined/auth/google/callback in the details. When I check the Google Console, I am explicitly allowing https://api.mywebsite.com in the Authorized JavaScript origins and all of https://api.mywebsite.com, https://api.mywebsite.com/auth/google/callback, and http://127.0.0.1:5000/auth/undefined/auth/google/callback in the Authorized redirect URIs.

How can I set this all up properly?

Bonus: If I wanted to run a validity check (say make sure the user is in a database), how could I do that?

Send data to iframe, process server side, return message back as json

I’m creating a simple app that can be embedded on external websites.

Here is what I’ve done so far:

  • Made a javascript file that website owners can include on their websites (ex: parentwebsite.com)
  • Given a target element, my script will then create a button. Once the button is clicked, I launch a modal window
  • I start gathering variables from the page and append them to my URL (the URL from my own domain) (ex: mydomain.com?k=v&a=b&c=d)
  • I make an iframe inside the modal window, set its src to the URL I created above, and display the iframe
  • Depending on what data is being passed to that URL, I display various information
  • My URL is a PHP/Laravel script

So far it’s working fine. I’m also displaying a form inside my iframe. I would like to capture the information the user enters in the form, post it back to my script, get some results back and display it back in the iframe. What’s the best way to go about this?

Should I just create an actual <form action="mydomain.com?k=v&a=b&c=d" method="post"> inside my iframe and post to my url?

Is there a way to do this using postMessage and do the server-side processing as well?

Is there a javascript framework that can make this whole process a bit easier?

Discord.js Bot Quiz Command

I was looking for a command that would give a question and 4 options ( if possible as buttons or reactions), where i could give questions in the code with the correct answer, but all i could find online were for slash commands, getting questions from a website or were v12 of discord.js.

I don’t know much, so any help would be great.

JS: How to calculate face value after dice roll animation

I’ve created a neat little dice roll animation. It is essentially 6 div elements inside a wrapper container that has been styled into a cube via CSS. I’ve got it rotating with drag gestures in a fluid way.

The issue: I don’t know how best to calculate the value that is facing outward after a roll. I’ve made it so that the die automatically rotates to increments of 90 as a dice would using GSAP draggable plugin, e.g: Draggable.create(... but I don’t know how to devise a proper method to calculate how to detect which side is facing the user after a roll is completed. The most obvious method using an if/else statement for every conceivable combination of rotations seems a clunky way to approach it.

Is there any insight into this or where I might start to understand a good method for this?

https://codepen.io/mhcdotcom/pen/ExQYZam

Any help is greatly appreciated.

Thank you, All.
Moe

Detecting device orientation in Quaternion

I’m trying to make an Unity WebGL app where the web window feeds the orientation data into Unity, where alpha, beta, gamma will be converted to Quaternion. However, the gamma rotation only goes from -90 to 90, so when the device is landscape pointing up (equivalent to screen is facing down), the gamma goes to -90 then reset to 90, and changing the alpha and beta accordingly, meshing up the rotation. Is there a way I can get the device orientation in Quaternion instead of Euler angles?

Why regular for doesnt work, but for in works [duplicate]

Why does for in is working in this situation, but not regular for? its driving me crazy trying to make it work.

let valores = [‘ponto’, ‘number0’, ‘number1’, ‘number2’, ‘number3’, ‘number4’, ‘number5’, ‘number6’, ‘number7’, ‘number8’, ‘number9’]

//NOT WORKING

      for (i = 0; i < valores.length; i++) {
  document.getElementById(valores[i]).addEventListener('click', e => {
    e.preventDefault()

    if (document.querySelector('.operador').innerHTML == '') {

        document.querySelector('.valor').innerHTML += document.getElementById(valores[i]).innerText
    }
    else {
        document.querySelector('.valor2').innerHTML += document.getElementById(valores[i]).innerText
    }
})

};

//WORKING ??

           for (let a in valores) {
document.getElementById(valores[a]).addEventListener('click', e => {
    e.preventDefault()

    if (document.querySelector('.operador').innerHTML == '') {

        document.querySelector('.valor').innerHTML += document.getElementById(valores[a]).innerText
    }
    else {
        document.querySelector('.valor2').innerHTML += document.getElementById(valores[a]).innerText
    }
})

};

Error message “Uncaught TypeError: Cannot read properties of null (reading ‘innerText’)”.
it doesnt make any sense for me why one is working, while the other cant read proporties of null..

Multi element JSON object from JavaScript

I have a Javascript JSON object

const student = { name: "bob", age: 7, grade: 6 }

and I can pass it to my Web API using axios POST command by

JSON.stringify(student)

and I can build my student object by looping an array and passing in a value such as

let studentArr= []
const student = { name: studentArr[i]["name"], age: studentArr[i]["age"], grade: studentArr[i]["grade"}

I’m using I in the example as the index because it could have 100 students. As long as I pass in only one value for it, everything works fine. My question is how can I make it into a multi-element JSON object from my array. I’ve been spoiled by Newtonsoft.Json where I can pull data from a SQL database and create a JSON object. If I just JSON.stringify(studentARR) is shows empty. I want to pass to the Web API all of the students on one post so the Web API can make a document and download it back.

I seen many different ways of trying to accomplish this and the methods seem to change over time. Thanks for the help

Error when deploying app on Heroku or Railway

This is my first time deploying a MERN app and I keep coming across these errors:

I’m getting this error when attempting to deploy it in Heroku:

remote: Module not found: Error: Can’t resolve ‘./Store’ in
‘/tmp/build_1d3d428a/frontend/src’

I wanted to try deploying it using another technology because I heard that Heroku was having issues. This error comes up when I try deploying the same app in Railway:

Failed to compile. Module not found: Error: Can’t resolve ‘./Store’ in
‘/workspace/frontend/src’

I’m guessing something is wrong with the Store file but I’m not sure what it is.
Here is the code in that file:

import { createContext, useReducer } from "react";

export const Store = createContext();

//define initial state in cart based on local storage
const initialState = {
  //check if user exists
  userInfo: localStorage.getItem("userInfo")
    ? JSON.parse(localStorage.getItem("userInfo"))
    : null,

  cart: {
    //get shipping address, payment method and cart items based on user
    shippingAddress: localStorage.getItem("shippingAddress")
      ? JSON.parse(localStorage.getItem("shippingAddress"))
      : {},
    paymentMethod: localStorage.getItem("paymentMethod")
      ? localStorage.getItem("paymentMethod")
      : "",
    cartItems: localStorage.getItem("cartItems")
      ? JSON.parse(localStorage.getItem("cartItems"))
      : [],
  },
};

//update state in cart
//instead of creating duplicate items of the same product, we increase the amount of the one product if button is pressed more than once

function reducer(state, action) {
  switch (action.type) {
    //add items to cart
    case "CART_ADD_ITEM":
      const newItem = action.payload;
      const existItem = state.cart.cartItems.find(
        (item) => item._id === newItem._id
      );
      const cartItems = existItem
        ? state.cart.cartItems.map((item) =>
            item._id === existItem._id ? newItem : item
          )
        : [...state.cart.cartItems, newItem];
      localStorage.setItem("cartItems", JSON.stringify(cartItems));
      return { ...state, cart: { ...state.cart, cartItems } };
    //second case: remove item from cart
    case "CART_REMOVE_ITEM": {
      const cartItems = state.cart.cartItems.filter(
        (item) => item._id !== action.payload._id
      );
      localStorage.setItem("cartItems", JSON.stringify(cartItems));
      return { ...state, cart: { ...state.cart, cartItems } };
    }
    //clear cart
    case "CART_CLEAR":
      return { ...state, cart: { ...state.cart, cartItems: [] } };
    //update user info based on data from the backend
    case "USER_SIGNIN":
      return { ...state, userInfo: action.payload };
    //case where user is signed out
    case "USER_SIGNOUT":
      return {
        ...state,
        userInfo: null,
        cart: {
          cartItems: [],
          shippingAddress: {},
          paymentMethod: "",
        },
      };
    //update shipping address with data from payload
    case "SAVE_SHIPPING_ADDRESS":
      return {
        ...state,
        cart: { ...state.cart, shippingAddress: action.payload },
      };
    //save payment method
    case "SAVE_PAYMENT_METHOD":
      return {
        ...state,
        cart: { ...state.cart, paymentMethod: action.payload },
      };
    default:
      return state;
  }
}

export function StoreProvider(props) {
  const [state, dispatch] = useReducer(reducer, initialState);
  const value = { state, dispatch: dispatch };
  return <Store.Provider value={value}>{props.children}</Store.Provider>;
}

Please let me know if I should include anything else. I’m not sure what is making the file/app undeployable.

Can someone help me with the freeCodeCamp Use Recursion to Create a Range of Numbers exercise?

Here is the problem.

Use Recursion to Create a Range of Numbers
Continuing from the previous challenge, we provide you another opportunity to create a recursive function to solve a problem.

We have defined a function named rangeOfNumbers with two parameters. The function should return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both startNum and endNum are the same.

my solution was

function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0);
    return [startNum];
  } else {
    const numbers = rangeOfNumbers(startNum, endNum - 1);
    numbers.push(endNum);
    return numbers;
  }
}

Why is this wrong?