How to match values in JSON Arrays Efficiently

I have two JSON Arrays a and b. a is the array I want to add information to which is contained in b. a and b both have a keyNum which I will be using to match the needed information in b to the relevant record in a.

a is formatted like:

a = [
  {
    keyNum: ...,
    extra: ...
  }
]

With elements ordered by `keyNum (with descending ordering).

b is formatted like:

b = [
  {
    keyNum: ..,
    infoNeededIna; ...
  }
]

With elements also ordered, but not necessarily descending.

The data in the arrays are JSON strings which I have called from an API. the keyNum is an order number. B is essentially the parent which contains records of A in the database I am grabbing this from. Unfortunately, the info I need in B is not contained in the record of A

I need infoNeededIna into the a record where ever keyNum is equal between a and b. a and b have a many to one relationship to so it is likely that keeping track of the index i am looking in b would be much more efficient than starting the search at the first record each time.

I know how I could brute force this but I wanted to see if anyone knew a more elegant solution.

My thoughts now is that I could use a loop through a and use the keyNum to then pilot an inner loop into b to search for the relevant index of b and grab infoNeededIna.

Make an array of strings of the names saying whether or not they can go to The Matrix (Under the age of 18)

Make an array of strings of the names saying whether or not they can go to The Matrix (Under the age of 18)

console.log(makeStrings([
    {
        name: "Angelina Jolie",
        age: 80
    },
    {
        name: "Eric Jones",
        age: 2
    },
    {
        name: "Paris Hilton",
        age: 5
    },
    {
        name: "Kayne West",
        age: 16
    },
    {
        name: "Bob Ziroll",
        age: 100
    }
])); 
// ["Angelina Jolie can go to The Matrix", 
// "Eric Jones is under age!!", 
// "Paris Hilton is under age!!", 
// "Kayne West is under age!!", 
// "Bob Ziroll can go to The Matrix"]`

console.log(makeStrings([
    {
        name: "Angelina Jolie",
        age: 80
    },
    {
        name: "Eric Jones",
        age: 2
    },
    {
        name: "Paris Hilton",
        age: 5
    },
    {
        name: "Kayne West",
        age: 16
    },
    {
        name: "Bob Ziroll",
        age: 100
    }
])); 

function makeStrings(arr){
return arr.map((x) => x.age < 18) ? arr.map((x) => x.name + " can go to The Matrix ") :       arr.map((x) => x.name + " is underage!!"); 
}

Second request is not waiting the first requests response via fetch api in Firefox

I have a very strange behavior in Firefox.
The code as you can see below.
As soon as the the first request’s response returned, the header is enriched and the second request is sent. But I see in server logs that sometimes requests (second request) does not contain a token (custombackendtoken). How can that be?

You can reproduce the problem in firefox by reloading the page. While the page is loading or while the first request is running (via multiple trials of refresh).

The same scenario in chrome does not occur.
How can the second request go to the backend without a custombackendtoken header?

I would be very grateful if anyone has an idea.

export const fetchData = async (input: RequestInfo, options?: RequestInit, proxyPath?: string): Promise<Response> => {
  try {
    // first request
    const bearerToken = await getAuthToken(proxyPath);

    const reqOptions: RequestInit = options || {};
    reqOptions.headers = {
      ...reqOptions.headers,
      custombackendtoken: bearerToken,
    };

    // second request
    return await fetch(input, reqOptions);
  } catch (e) {
    console.error('Error.......', e);
    throw new Error(`Error....... Error: ${e}`);
  }
};


//getAuthToken
export default async (proxyPath: string): Promise<string> => {
  let token = await retrieveStoredToken(proxyPath);
  
  if (!token) {
    token = await createToken();
    if (!token) {
      throw new Error('Token can not be created!');
    }
    storeToken(proxyPath, token);
  }

  return token;
};

//retrieveStoredToken
const retrieveStoredToken = async (proxyPath: string): Promise<string | undefined> => {
  try {
    const response = await fetch(`${proxyPath}/token`, {
      credentials: 'same-origin',
    });

    return await response.json();
  } catch (e) {
    console.error('Error ..........', e);
  }
  return undefined;
};

Create a Curved-Side Diamond Shape with CSS

I’m creating my portfolio site. Now I want to create a diamond with this shape.

enter image description here

I tried my best to create this shape with Tailwind CSS, but I couldn’t. I even searched about it, but I didn’t find any suitable shape near to this. I would be so grateful if someone could help me.

Prompt function against HTML doc loading in JS [duplicate]

let ans=document.querySelector("p")
let text;
text=Math.floor(Math.random()*100+1);

flag=true;
while(flag===true){
    let guessed=parseInt(prompt("Guess the number?"));
    if (guessed===text){
        ans.textContent="Congratulations! U guessed it right!";
        flag=false;
    }
    else if (guessed>text){
        ans.textContent="Guess lower!";
    }
    else if (guessed<text){
        ans.textContent="Guess higher!";
    }
    
}

How do i prompt the user using prompt() function after the HTML has completely loaded?

The above code will not load complete html and prompts the user immediately as you reload the page.

is it OK to use javascript for machine coding rounds? [closed]

I’ve come across that a lot of big tech companies are focussing on machine coding round where we have to write our code in OOP format. But I’ve been coding in javascript only for almost 2 years so is it a good idea to choose JS for this round or I should learn another OOP programming language to clear this round ?

I am trying to clear my doubts on machine coding rounds during an interview process and also want to clear the doubt of using javascript as the language for this round. If anyone has already use JS for this round please help me with this doubt.

Turning off Strict mode in JavaScript

In the JS Engine of a browser console such as the browser console of Google Chrome, the Strict mode is turned off by default unless you explicitly put the “use strict” directive.

But in an IDE like the VSCode, it seems like the execution happens in the Strict mode by default. How do you turn that off in VSCode?

I looked up the Settings of the IDE, but could not find anything related to the execution.

React useEffect executes before mobx store updates

I have an react app where I check user is authorized with useEffect and mobx. But when useEffect checks store.isAuth it is false and idk after 10 ms it is true, but I am already on another page. Please help me!

I don’t want to React navigate me on another page when useEffect checks store.isAuth

App.js

import React, { FC, useContext, useEffect, useState } from 'react';
import { Context } from "./index";
import { observer } from "mobx-react-lite";
import {BrowserRouter, Routes, Route, Navigate, useNavigate} from 'react-router-dom';
import AppRouter from './components/AppRouter';

const App = () => {
    const { store } = useContext(Context);
    const navigate = useNavigate();

    useEffect(() => {
        console.log(process.env.REACT_APP_API_URL)
        if (localStorage.getItem('token')) {
            store.checkAuth();
        }

        // getOrders();
    }, []);

    useEffect(() => {
        store.checkOrdersInWork();
    }, []);
    

    useEffect(() => {
        if (!store.isAuth) {
            console.log('NAVIGATE TO /login');
            navigate('/login');
        }
    }, []) // [store.isAuth]


    if (store.isLoading) {
        return <div>Загрузка...</div>
    }


    return (
            <div>
                <AppRouter/>
            </div>

    );
};

export default observer(App);

store.js

    user = {};
    isAuth = false;
    isLoading = false;
    orderId = '';
    ordersInWork = [];

    constructor() {
        makeAutoObservable(this);
    }

    setAuth(bool) {
        this.isAuth = bool;
    }

    setOrdersInWork(orders) {
        this.ordersInWork = orders;
    }

    setUser(user) {
        this.user = user;
    }

    // setSborshik(bool) {
    //     this.isSborshik = bool;
    // }

    setLoading(bool) {
        this.isLoading = bool;
    }

    setOrderId(orderId) {
        this.orderId = orderId;
    }

    async login(email, password) {
...

index.js

import React, { createContext } from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import Store from "./store/store";
import { BrowserRouter } from 'react-router-dom';

export const store = new Store();

export const Context = createContext({
    store,
})

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
    <Context.Provider value={{
        store
    }}>
        <BrowserRouter>
            <App />
        </BrowserRouter>

    </Context.Provider>
);

Strapi 4 + Nuxt 3 Auth Problems

I’ve successfully integrated an authentication function into my Nuxt 3 application with Strapi serving as the backend. Everything seems to be running smoothly when I use Node.js 18 with Strapi and Node.js 16 with Nuxt.

However, here’s the issue:

Nuxt 3 requires Node.js version 18 to function properly. Yet, when I set up Node.js version 18, the application keeps logging out whenever a user is authenticated and I make a refresh. Additionally, the jwt_cookie seems to disappear.

I’ve experimented with various solutions, including adjusting the SameSite settings and CORS settings in both Nuxt and Strapi, but unfortunately, none of these attempts have resolved the issue.

Has anyone encountered a similar problem or can offer any insights?

Best Regards,

Mr. Marcel Superman

  • Search the web for similar soulutions but none of them worked for me
  • Read the documentation
  • Asked Chat GPT

Jquery load problem — for one person only

I have a page on my website that was visited 96 times. Only 1 page visit generated the javascript error “Uncaught TypeError: $ is not a function” which I understand means that the jquery library didn’t load properly. What I don’t understand is:
(a) How could this problem happen to this person when it didn’t to anyone else.
(b) What can I add to my code to detect the problem and handle it. Note that I store the useragent of each visit and the visitor in question had the same useragent as many other page visits that did not have the problem.

NOTE: The last several questions I posted on this website were rejected for various reasons, so if this happen to this question, I’d be super grateful if someone could please give me specific instructions as to what I can do to make this question accepted.

How can I access the list of Wi-Fi networks using React.js in a web application?is possible to fetch the Wi-Fi networks using js/reactjs

Here, I am using the node-wifi package on my backend to reterive the available wifi network connection, and it works fine on my local system. However, when I try to run it on my live server, I encounter error logs. Upon investigation, I discovered that node-wifi is not supported on end-user devices’ Wi-Fi networks.

Therefore, I installed the same package in my React app and encountered error logs. Is there another package available to scan for Wi-Fi networks on the client-side and render network connections?

Vue js, Vue js method returning undefined

I have a vue class

export default {
  data() {
    return {
      tasks: [],
      currentSort:'name',
      currentSortDir:'asc',
      companies: []
    };
  },
  async created() {
    this.storage.tasks++;
    try {
      this.tasks = await Monitor.Task.getTasks();
      this.companies = await Monitor.getCompanies();
    } catch (code) {
      this.notify("danger", "Не удалось загрузить задачи", code);
    } finally {
      this.storage.tasks--;
    }
  },
  computed: {
    mappedTasks() {
      return _.chain(this.tasks)
          .sort((a,b) => {
            let modifier = 1;
            if(this.currentSortDir === 'desc') modifier = -1;
            if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
            if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
            return 0;
          })
          .map(it => {
            let statusText;
            switch (it.status) {
              case "NOT_COMPLETED":
                statusText = "Ожидает выполнения";
                break;
              case "COMPLETED":
                statusText = "Завершено";
                break;
              case "CANCELED":
                statusText = "Отменено";
                break;
              default:
                statusText = "Неизвестно";
            }
            const companyName = this.getCompanyById(it.companyId).name;

            let updated
            if(it.updatedAt !== null) {
              updated = Moment(it.updatedAt).utcOffset(TIME_ZONE).format("YYYY-MM-DD HH:mm:ss")
            }

            const values = {
              statusText,
              createdAt: Moment(it.createdAt).utcOffset(TIME_ZONE).format("YYYY-MM-DD HH:mm:ss"),
              updatedAt: updated,
              companyId: companyName
            };


            return _.assign({}, it, values);
          })
          .value();
    },
  },
  methods: {
    sort:function(s) {
      if(s === this.currentSort) {
        this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
      }
      this.currentSort = s;
    },
    getCompanyById(id) {
      return this.companies.find(company => company.id === id);
    }
  }
}

The proplem that in method getCompanyById this.companies is undefined therefore method doens’t return company. I tried to make to make method async and like this:

async getCompanyById() {
  let  companies = await Monitor.getCompanies()
  return companies
}

In this case, I have that status of companies is pending. I don’t undenstand why in computed.mappedTask I can’t get companies from async created unlike tasks

How can I display nii.gz segmentation data into 3D model on website?

I tried to use three.js to display nii.gz images but it was a headache.

I don’t know what I did wrong so I tried another method which is generate the 3D model using python. I was using MyVi but there was too many errors.

I searched and read many thesis articles. Mostly, they only display their segmentation result on python. I need to do this on website though.

Is there any direct and simpler method to display nii.gz on website?

As mentioned, if python to javascript (I’m using React and Three.js) works, please tell me how to do it!

If not, please tell me what are solutions!!

Thanks

Making Gantt Chart Column Labels More Readable

enter image description hereDescription:
I’m currently working on a Gantt chart where the column labels have become unreadable due to the large number of columns. Although I’ve attempted to adjust the column width, it hasn’t completely resolved the issue.

Details:

I’ve set the column width property, but it hasn’t adequately addressed the readability problem.
The column labels currently display intervals for every minute, which is overwhelming and makes the chart difficult to interpret.
I’d like to change the column labels to display intervals of 15 minutes instead, which would improve readability without losing too much detail.
Question:
How can I modify the Gantt chart configuration or settings to change the column labels to display intervals of 15 minutes instead of every minute? Are there any specific options or parameters that I should adjust to achieve this?

Any insights or suggestions would be greatly appreciated. Thank you!