How to create object with JSON values in TypeScript

I have a json file named products.json which contains a list of products with their id, name, quantity, description and url of images relating to this product.
Example of the JSON file:

[
  {
    "id":1,
    "name": "APPLE IPHONE 13 256GO",
    "desc": "some desc ...",
    "price": 1599.0,
    "qty": 15,
    "imgUrls": "../Images/iphone-13"
  },
  {
    "id":2,
    "name": "GALAXY NOTE10",
    "desc": "some desc ...",
    "price": 200.0,
    "qty": 10,
    "imgUrls": "../Images/galaxy"
  },
  {
    "id":3,
    "name": "APPLE IPHONE 12 128GO",
    "desc": "some desc ...",
    "price": 1599.0,
    "qty": 15,
    "imgUrls": "../Images/iphone-12"
  }
]

Also, I have the Product object below:

export class Product {
  constructor(
    public id: number,
    public name: string,
    public desc: string,
    public price: number,
    public qty: number,
    public imgUrls: string[]
  ) {}
}

I want to create an array of type Product, which contains all my products imported from the json file.

I know that by adding the products manually it will be like this.

products: Product[] = [
new Product(1,
            "APPLE IPHONE 13 256GO",
            "some desc...",
            1599.0,
            15,
            ["../Images/iphone-13"]),
new Product(2,
            "GALAXY NOTE10",
            "some desc...",
            200.0,
            10,
            ["../Images/galaxy"]),
new Product(3,
            "APPLE IPHONE 12 128GO",
            "some desc ...",
            1599.0,
            15,
            ["../Images/iphone-12"])
];

but i want to create this object using the json file.

Thank you so much for yur help.

Sorry if i m not clear, you can mention that in comments so i can edit my question.

How can I make a routed-clickable box component on React?

I am trying to make a button that routes to another page.

I want have a stylish clickable box, instead of a plain button that gets routed to the its respective page. Im trying to code these boxes, and route them to their pages as well :
enter image description here
enter image description here

Any Idea on how I can do it?

I’m new to programming, really appreciate the feedback.

Javascript to send slack notification from zabbix is not working

I have a javascript to send slack notification from zabbix. it is sending only few alerts and most of the alerts are not sent. It just shows Error!. I am unable to check logs also. Please help.

var response,
    pl,
    params = JSON.parse(value),
    wurl = params.URL,
    clr = "00bdde",
    subj = params.Subject,
    msge = params.Message,
    pb = "Problem",
    rd = "Resolved",
    request = new CurlHttpRequest();
    
    if (subj.includes(pb)) {
      clr="de0000";
    };
    if (subj.includes(rd)) {
      clr="009600";
    };

    pl = '{"attachments": [{"color": "' + clr + '", "title": "' + subj + '", "text": "' + msge + '"}] }';
    Zabbix.Log(4, '[ Slack Webhook ] Sending request: ');

    request.AddHeader('Content-Type: application/json');
    response = request.Post(wurl, pl);

    return 'OK';

when I tested my challenge code .. it has returned an error ” expected undefined to equal 1″ .. please tell me where is the issue

when I tested the code below .. it returned an error “expected undefined to equal 1” please tell me where is the issue.

const digPow = (n, p) => {
  let k;
  n = n < 0 ? -n : n;
  p = p < 0 ? -p : p;
  let splittedStr = n.toString().split('');
  let result = splittedStr
    .map(digit => Math.pow(digit, p++))
    .reduce((curr, prev) => curr + prev, 0);
  k = (result / n) % 1 === 0 ? result / n : -1;

  console.log(parseInt(result), k);
};

digPow(89, 1);
digPow(92, 1);
digPow(695, 2);
digPow(46288, 3);

How to build a range slider with select box in Vue?

Hi I am new in Vue and I have a project that uses Vue, PHP and Laravel. price rangepicture link

I have to build a price filter like the picture. But I have no idea to code the select box that value will change when moving slide. Anyone has successed in doing this?

What I did until now.

    <template>
          <div class="col-12 col-lg-7 pb-2 pl-5"> 
            <div class="row align-items-baseline">
                <div class="col-3 col-lg-3 text-navy font-weight-bold">
                    予算
                </div>
                <vue-slider
                    ref="slider"
                    v-model="slider_value" :enable-cross="false"
                    :dot-size="dotSize"
                    :dot-style="dotStyle"
                    :rail-style="railStyle"
                    :process-style="processStyle"
                    :min="0"
                    :max="100"
                    :tooltip="false"
                    class="col-7 col-lg-7 pl-lg-1"
                ></vue-slider>
            </div>
                <!-- ID Example -->
            <div class="row align-items-baseline ml-lg-3">
                <div class="col-5 col-lg-5 px-1 inputSelectWrap">
                    <select name="">
                        <option>下限なし</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                </div>
                <div class="text-center px-1">~</div>
                <div class="col-5 col-lg-5 px-1 inputSelectWrap">
                    <select name="">
                        <option>上限なし</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                </div>
            </div>
        </div>
    </template>

<script>
// import component
import VueSlider from 'vue-slider-component/dist-css/vue-slider-component.umd.min.js'
import 'vue-slider-component/dist-css/vue-slider-component.css'

// import theme
import 'vue-slider-component/theme/default.css'
export default {
    components: {
       'vueSlider': VueSlider,
    },
    data: () => ({
        slider_value: [0, 100],
        dotStyle: {
            backgroundColor:"#fff",
            borderColor:"#fff",
        },
        processStyle: {
            backgroundColor: "#1d3557",
        },
    }),

ACS Group video call – not sending video to the call

I’m not getting any video from a group call. I’m able to record the call, but when I watch the video, I only see a round profile option for each participant. No video is getting sent. How do I get the stream sent to the call?

callClient = new CallClient();
        var tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
        callAgent = await callClient.createCallAgent(tokenCredential);
...
var deviceManager = await callClient.getDeviceManager();
        await deviceManager.askDevicePermission({ video: true });
        await deviceManager.askDevicePermission({ audio: true });
        // Listen for an incoming call to accept.
        callAgent.on('incomingCall', async (args) => {
            try {
                var incomingCall = args.incomingCall;
            } catch (error) {
                console.error(error);
            }
        });
        camera = (await deviceManager.getCameras())[0];
        
        localVideoStream = new LocalVideoStream(camera);
        localVideoStreamRenderer = new VideoStreamRenderer(localVideoStream);
        const view = await localVideoStreamRenderer.createView();

          document.getElementById("myVideo").appendChild(view.target);  
...
        const destinationToCall = { groupId: "E51F195A-45D2-4F83-8CE4-565A333A9706" };
        call = callAgent.join(destinationToCall);
...
        await call.startVideo(localVideoStream);

Use JavaScript to find element by its CSS property value

How do I find the element by matching its CSS property value?

For example, if the background color of the element is green, then do something…

const elm = document.getElementsByClassName('elm');

[...elm].forEach(function(s) {
  //find the element which background color is green
  
  //then console.log(theItem)
})
.elm {
  width: 200px;
  height: 100px;
}

.elm1 {
  background-color: red;
}

.elm2 {
  background-color: green;
}

.elm3 {
  background-color: blue;
}
<div class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

How to correctly use Context API and Provider

I’m implementing a dark mode, and I got stuck at this part of my project, where everything looks like working, but don’t. There is no error, but my Context at App, don’t re-render when I use the setTheme inside the Provider, how can I fix it ?

App.jsx

import { useContext } from "react"
import { ThemeLocalContext, ThemeLocalProvider } from "./context/ThemeContext"
import { ThemeProvider } from "styled-components"
import {Paths} from "./pages/Paths/"
import { GlobalStyle } from "./styles/GlobalStyle/GlobalStyle"

function App() {

  const theme = useContext(ThemeLocalContext);
  console.log(theme)
  return (
    
    <div>
      <ThemeLocalProvider>
        <>
        <ThemeProvider theme={theme}>
        <GlobalStyle/>
        <Paths/>
        </ThemeProvider>
        </>
      </ThemeLocalProvider>
    </div>
  )
}

export default App

ThemeContext.jsx

import React, { createContext, useState } from "react";
import { lightTheme } from "../styles/Theme/lightTheme";
import { darkTheme } from "../styles/Theme/darkTheme";


export const ThemeLocalContext = createContext(lightTheme);

export const ThemeLocalProvider = ({children}) => {
    const [theme, setTheme] = useState(darkTheme);

    const handleChange = () => {
        setTheme(theme.title === 'light'? darkTheme : lightTheme)
    }

    return (
        <ThemeLocalContext.Provider value={[theme, handleChange]}>
            {children}
        </ThemeLocalContext.Provider>
    )
}

I don’t think the error is here, but I’ll also let my Header code here, this is where I run the setTheme function, who is named by handleChange, and I use it whit theme[1].

Header.jsx

import ReactSwitch from "react-switch";
import {useContext, useState} from 'react'
import { ThemeLocalContext } from "../../context/ThemeContext";

const Header = () => {

    const theme = useContext(ThemeLocalContext)
    
    return(
        <div>
        <h1>{theme[0].colors.primary}</h1>
        <ReactSwitch 
        checked={theme[0].title === 'dark'}
        onChange={theme[1]}
        />
        </div>
    )
}
export default Header;

I have a variable that is CLEARLY defined but console says it isn’t [duplicate]

I am trying to get input from the user and then log it to a Discord server. It normally works, but when I try to give the Modal/Embedded message a title and description through a variable that has a value from a window.prompt it doesn’t work.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SendWebhook</title>
</head>

<body>
    <button onclick="sendMessage()">Send message </button>
    <script>
        function sendMessage() {

            var userInputLogContent = window.prompt("Enter your message (this won't affect the embedded Modal): "); 
            var userInputLogDescription = window.prompt("Enter whats inside the modal");
            var userInputLogTitle = window.prompt("enter heading for modal");

            const request = new XMLHttpRequest;
            request.open("POST", "my link here, this does work ");
            request.setRequestHeader('Content-type', 'application/json');

            const params = {
                username: "",
                avatar_url: "",
                content: userInputLogContent, // This works, because it isn't in the myEmbed
                embeds: [ myEmbed ]
            }

            request.send(JSON.stringify(params));
        }

        function hexToDecimal(hex) {
            return parseInt(hex.replace("#", ""), 16)
        }
        
        var myEmbed= {
            author: {
                name: ""
            },
            title: userInputLogTitle, // This isn't defined (according to inspect console)
            description: userInputLogDescription, // Not defined (according to inspect console)
            color: hexToDecimal("#2e5883") // This is color
        }
    </script>
</body>

How to get longitude and latitude data from an array inside object and display them as google map link on output

How can I get the coordinates and display them as a google map link on the output. I couldn’t figure out and any advice would be much helpful. Thank you.
[`

function searchCity(city) {
    //var r=JSON.parse(xhr.responseText);
    document.getElementById("searchvalues").innerHTML = "Search by City" + "<br>";
    //structure table
    var output = "<tr><th> Location </th><th> City </th><th> Phone </th><th> Vaccine Type </th><th> Map Link</th></tr>";
    var searchid;
    var map = obj.point{coordinates:[]};;
    for (var i = 0; i < r.length; i++) {
        var obj = r[i];
        searchid = obj.city.toUpperCase(); 
        if (searchid.startsWith(city.toUpperCase())) {
            output += "<tr><td>";
            output += obj.location;
            output += "</td><td>";
            output += obj.city;
            output += "</td><td>";
            output += obj.phone;
            output += "</td><td>";
            output += obj.vaccinetype;
            output += "</td><td>";
            output += <a href='https:www.google.com/maps/search/?api=1&query=' + map + ' target=_blank'> Click here to see map </a>;
            output += "</td></tr>";            
            
        }
    }
    document.getElementById("searchresults").innerHTML = output;
}

`]1

How can I fetch data to display on a new HTML page after clicking a button on a main index.html page?

I have two html files (index.html and allUsers.html) and a JavaScript index.js
The index.html has a button allUsersButton.

My goal is that when the allUsersButton is clicked, I should see the allUsers.html page, and be able to see the fetched data which should be injected into the div named allUsersDivId.

So far, no data loads on the allUsers.html page and I get an error on the console “Uncaught TypeError: Cannot set properties of null (setting ‘onclick’)”.
Should both the index.html and the allUsers.html have the script linked in them? What’s the best way to put this together?

index.html

<body>
    <form action="http://localhost:7050/hello" method="POST">
        <label for="username">User name:</label>
        <input type="text" id="username" name="username"><br><br>      
        <input type="submit" value="Submit">
    </form>

    <button type="button" id="allUsersButton">All Users</button>
    
    <script src="index.js"></script>
</body>

allUsers.html

<body>
    <div id = "allUsersDivId">
    </div>
    <script src="index.js"></script>
</body>

index.js
Here I have a function for fetching and inserting the data into the div allUsersDivId which is in the allUsers.html, and an onClick listening on the allUsersButton which is in the index.html.

document.getElementById("allUsersButton").onclick = function() {displayAllUsers()};

function displayAllUsers() {
    window.location.href='allUsers.html'
    fetch("http://localhost:7050/allusers")
    .then((response) => {
        if (response.ok) {
        return response.json();
        } else {
        throw new Error("NETWORK RESPONSE ERROR");
        }
    })
    .then(data => {
        for(var i = 0; i < data.length; i++){
           const userName = data[i].username 
           const userNameDiv = document.getElementById("allUsersDivId")
        
           const heading = document.createElement("h1")
           heading.innerHTML = userName
           userNameDiv.appendChild(heading)
        }
    })
.catch((error) => console.error("FETCH ERROR:", error));    
}

What’s the best way to link this all together?

How to build 2D array when looping through sets of data using Google Apps Script?

So, the data looks like this:

enter image description here

The code below build an array like this:

[1,"Forro","Teste Molde",2,"36 + 38 + 40 + 42",4,8,"Não Espelhado","Tecido/Pé","Obs",2,"Tag Código Produto","Molde 2",5,"36 + 40",2,10,"Sim","Tecido/Pé2","Obs 2"]

But it needs to be like this, starting in Risco and ending in Obs:

[
 [1,"Forno","Teste Molde",2,"36 + 38 + 40 + 42",4,8,"Não Espelhado","Tecido/Pé","Obs"],
 [2,"Tag Código Produto","Molde 2",5,"36 + 40",2,10,"Sim","Tecido/Pé2","Obs 2"]
]

Here’s the code I’m wrestling with:

function salvarCorte(status) {
  if (status != '') {
    const dadosCorte = sheetCorte.getRange(1, 1, sheetCorte.getLastRow(), sheetCorte.getLastColumn()).getValues();
    let outerArray= [];
    var innerArray = [];
    const parametrosRisco = ["Risco", "Matéria Prima", "Molde", "Tamanho", "Grade", "Consumo Unit.", "Espelhado", "Tecido/Pé", "Obs", "Qtd/Peças"];
    let startedArray = false
    for (let r = 0; r < dadosCorte.length; r++) {
      if (dadosCorte[r][0] == 'Risco') {
        startedArray = true
      }
      if (startedArray == true) {
        if (parametrosRisco.indexOf(dadosCorte[r][0]) > -1) {
          innerArray .push(dadosCorte[r][1]);
        }
        if (parametrosRisco.indexOf(dadosCorte[r][2]) > -1) {
          innerArray .push(dadosCorte[r][3]);
        }
        if (dadosCorte[r][0] == 'Obs') {
          startedArray = false;
        }
      }
    }
    outerArray.concat(innerArray )
  }
}

Why am I getting NaN as a result here [closed]

I am trying to create a yearly salary calculator using HTMl and Javascript for an assignment, however whenever I try to call my function to replace the innerHTMl, it flashes NaN for a second and then goes back to the original HTML. I was wondering if anyone knew what is going on and how to potentially fix it.

function calcSalary() {
  var wage = document.getElementById('hourly').value;
  var wage2 = parseInt(wage.value);
  var hours = document.getElementById('week').value;
  var hours2 = parseInt(hours.value);

  var calculate = wage2 * hours2 * 52;
  document.getElementById('output').innerHTML = calculate;
}
<!DOCTYPE html>
<html>

<head>
  <title>Colin's Resume</title>
  <link rel="stylesheet" href="externalstyle1.css">
</head>

<body>
  <div class="divone">
    <h1>Colin Rooney's Resume</h1>
  </div>
  <div class="divtwo">
    <br>
    <div class="divthree">
      <p>My Skills</p>
      <br>
      <div class="divfour">
        <h2>Other Pages</h2>
        <a href="https://www.albany.edu/~cr897544/myexternal1.html/">My Work Experience</a>
        <a href="https://www.albany.edu/~cr897544/myexternal2.html/">My Education</a>
      </div>
      <div class="divfive">
        <h1>Salary Calculator</h1>
        <form name="myform">
          <label for="hourly">Hourly Rate:</label>
          <input type="text" id="hourly"><br><br>
          <label for="week">Hours Per Week:</label>
          <input type="text" id="week"><br><br>
          <button onclick="calcSalary()">Calculate</button>
        </form>
      </div>
      <div class="divsix">
        <p id="output">Output Here</p>
      </div>
      <div>
        <p>.</p>
        <a href="mailto:[email protected]/">Send me an eMail!</a>
      </div>
    </div>
  </div>
</body>

</html>

React Router Dom Blank Screen While Compiling

I am building a Music Streaming Application, that works as a streaming services for 4 playlists. The names of these playlists are Metal, Rock, Rap, House. I have created individual files for them named, Metal.js, Rock.js, Rap.js, House.js. These four playlists are nested on my Home.js page.

Question#1:

The part I’m stuck on is routing a button link from Home.js to either of the playlists. I followed a tutorial on how to use react-router-dom, however when I implemented it on my code, I was returned with a blank screen.

What’s wrong with it?

The Code:

Home.js

import React, { Component } from 'react';
import '../components/Home.css';
import {
    BrowserRouter as Router,
    Routes,
    Route,
    Link
  } from "react-router-dom";
  import Rap from './Rap';
  import House from './House';
 import Metal from './Metal';
 import Rock from './Rock';

export default class Home extends Component{
   
    render(){
        return(
            <Router>
            
            <div> 
                <h1> Home</h1>
                <img src={process.env.PUBLIC_URL + '/things.png'} alt="things" />

<button>
<Link to="/metal">
     <button type="button">
          Click Me!
     </button>
 </Link>
</button>
<button>
<Link to="/rap">
     <button type="button">
          Click Me!
     </button>
 </Link>
</button>
<button>
<Link to="/rock">
     <button type="button">
          Click Me!
     </button>
 </Link>
</button>
<button>
<Link to="/house">
     <button type="button">
          Click Me!
     </button>
 </Link>
</button>

            </div>
        <div>
        <Routes>
      <Route path="/S" element={<S/>} />
      <Route path="/Rock" element={<Rock />} />    
      <Route path="/House" element={<House />} />   
      <Route path="/Rap" element={<Rap />} />   
    </Routes>
        </div>
        </Router>
            
        )
    }
}

Additionally I will include one of the playlist components(they are all the same).

House.js

import React, { Component } from 'react';

export default class House extends Component{
    render(){
        return(
            <div> 
                <h1> HOUSE</h1>
              
            </div>
        )
    }
}


Thank You!

building barebones OS to run a chromium view

I am trying to create a custom operating system that runs a chromium window. I am not entirely sure where to start. I would love to create the OS from the ground up but it seems my only solution would be to create a custom Linux kernel. My main goal is to have the most barebones OS possible that is able to run javascriptV8 engine and render and interact with the DOM. I have seen https://www.webosose.org/samples/ and https://github.com/runtimejs both look semi promising. but I was wondering if I could get any input on where to start. I am not afraid to do a good amount of work. Does anyone know of some good references for this. I just think it would be cool and weird to have an Operating system that’s primary language was JS and a desktop environment of a predefined html page. After some research would https://support.google.com/webdesigner/answer/10043691?hl=en be a good resource?