assigning dynamically values of string array to properties of an object in typescript

suppose a component named searchBox receives tow inputs: @Input() titles: string[] and @Input() model: Object, that the number of titles values is equal to number of model properties. searchBox generates input box to number of titles length, and gets searching subjects from user and push them into a string array named titlesValues. so, searchBox should assigns the values of titlesValues to model properties peer to peer and outputs the model via @Output resultModel: Object. I tried to access each model property dynamically for assigning to, therefore I encoded this scenario in the following:

let i =0;
  Object.keys(this.model).forEach((key) => {
     this.model[key] = this.titlesValues[i];
   });

although I tested much statements and alternative codes to get desire result, but it gets bellow error:

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Object’.

how can I implement this scenario?
Best regards.

Javascript: Getting fromForm variable value

I’m trying to get the value from the “fromForm” variable but i dont know how can i get this value to use in the onSubmit function

$(window).on('load',function(){
    grecaptcha.render('recaptcha', {
        'sitekey' : '6LcFrN8cAAAAAMr2P3Nkvm7fDFzIykf30QykYlga',
        'callback' : onSubmit,
        'size' : 'invisible'
        });
});

$('form').submit(function (e) {
    e.preventDefault();
    grecaptcha.execute();
    var fromForm = $(this).data('test');
    }
);

function onSubmit(token){
    alert(fromForm);
};

Web page is blank (Problem with react-router)

I am trying to learn MERN mainly react by following a tutorial (https://www.youtube.com/watch?v=7CqJlxBYj-M) and I have followed the code exactly but when I run the server and open the web page it is blank.
I know the problem is with the four React route paths because if I remove them the web page displays the navbar. I also get no errors when running the server.
this is the app.js file code:

import React from 'react';
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter as Router, Route,} from "react-router-dom";

import Navbar from "./components/navbar.component"
import ExercisesList from "./components/exercises-list.component";
import EditExercise from "./components/edit-exercise.component";
import CreateExercise from "./components/create-exercise.component";
import CreateUser from "./components/create-user.component";

function App() {
  return (
    <Router>
      <div className="container">
      <Navbar />
      <br/>
      <Route path="/" exact component={ExercisesList} />
      <Route path="/edit/:id" component={EditExercise} />
      <Route path="/create" component={CreateExercise} />
      <Route path="/user" component={CreateUser} />
      </div>
    </Router>
  );
}

export default App;

This is the code for create-exercise:

import React, { Component } from 'react';


export default class CreateExercise extends Component{

    render() {
        return (
            <div>
                <p>You are on the create exercises List componentt</p>
            </div>
          
        )
    }
}

The other three have the same code.

React website on localhost CSS files missing after deploying to GitHub Pages but GitHub Pages website works fine

After creating my React app locally, I installed GitHub Pages using npm install gh-pages --save-dev and added both

`"homepage": "https://ryanloh88.github.io/ryanloh/"`

and

"scripts": {
"predeploy":"npm run build",
"deploy":"gh-pages -d build",...}

to my package.json. After running npm run deploy my website is uploaded to git hub pages successfully and everything works fine there, however when I tested my local app using npm start, my localhost:3000 website becomes unstyled and it seems the styles.css class is missing. Tried finding the issue online but to no avail, help would be much appreciated.

How do I use Node JS to execute a minecraft command on a wrapped minecraft server?

I am making a node discord bot that would have the ability to control a minecraft server, but for some reason I cannot get the bot to execute minecraft commands on the server itself.

Right now the bot receives normal discord strings from messages and interprets them as commands. This is the code I use to start the server:

var svEnv = cp.spawn("java", [
   "-Xms4096M",
   "-Xmx4096M",
   "-jar",
   "server.jar",
   "nogui"
], { shell: true, detached: true, cwd: `${config.server.directoryPath}`, stdio: [
   "inherit",
   "inherit",
   "inherit",
   "ipc"
]});

svEnv.stdout.on("data", out => {
   console.log(`Server Feedback: ${out}`);
})

svEnv.stderr.on("data", err => {
   if (!(err == "^C")){
      console.error(`~Server Error: ${err}`);
   }
})

This is the code I’m using to try to execute the commands:

svEnv.stdin.write(`${cmd}n`);

Whenever I attempt to use the code above to execute a command, the server doesn’t respond at all. It’s as if it doesn’t even receive the input.

All the solutions I have visited, even those with the same exact use case as myself have said this is the correct way to implement this. I have to guess that the reason it doesn’t work is because of the way I have the child process spawn configured.

Basically what I’m asking is how does the spawned process need to be configured to receive commands?

Please Note: This is my first time using the child process module in node js, so if you have any tips on how it works please let me know.

Summarizing a list of Channels

Heres the problem I have:

Turn this string input: “Ch 471: PRO BM R #5,Ch 472: PRO BM R #4,Ch 473: PRO BM R #3,Ch 481: PRO BM L #5,Ch 482: PRO BM L #4,Ch 484: PRO BM L #3”

Into this string output:
Ch 471-473: PRO BM R #3-5
Ch 481-484: PRO BM L #3-5

Im attempting to write a function in JavaScript that essentially filters through a string of channels separated by commas of x amounts and then summarizes them in the format above. In the example above there are 6 different channels with positions and units.

The deciding/grouping factor are the positions (In the above example, PRO BM R and PRO BM L) – So finding all the channels and units on one position and then summarizing that info.

Heres details on nomenclature:

  • Channels = Ch 471
  • Positions = PRO BM R
  • Units = #5

What I have tried so far, and what Im assuming I would need to do is use several loops to split() the data

  • First by comma
  • Then by :
  • Then by # sign

Then push the data into 3 different arrays

  1. Channel Array
  2. Position Array
  3. Unit Array

Then filter through each array to find unique values, max values, etc. I just can’t wrap my head around this problem though?

Any pointers, example code, or assistance of any kind is welcomed!

how to stop multiple query Node JS

After chcecking if the name already exist, the program keeps running to the next query and still insert data (also shows error becasue it sends multiple response). How to make it stop after it run if (results.rowCount > 0) ?

const addCategory = (req, res) => {
    let { name } = req.body

    //check if name exist
    pool.query(queries.checkNameExists, [name], (error, results) => {
        if (error) throw error
        if (results.rowCount > 0) {
            return res.status(409).send(`Category ${name} already exists!`)
        }
    })

    //insert new category
    pool.query(queries.addCategory, [name], (error, results) => {
        if (error) throw error
        res.status(201).send("Category created succesfully!")
    })
}

How to check if two numbers are sequential in JS? Codewars Kata

I’m trying to solve this kata:

You are given a list of unique integers arr, and two integers a and b. Your task is to find out whether or not a and b appear consecutively in arr, and return a boolean value (True if a and b are consecutive, False otherwise).

It is guaranteed that a and b are both present in arr.

Test examples:

consecutive([1, 3, 5, 7], 3, 7), false
consecutive([1, 3, 5, 7], 3, 1), true 
consecutive([1, 6, 9, -3, 4, -78, 0], -3, 4), true

This is what I have so far:

for (let i = 0; i < arr.length; i++) {
  let index2 = arr.indexOf(b)
  let index1 = arr.indexOf(a)

    let diff = (index2) - (index1)

    if (diff > 1) {
        console.log(diff, 'false');
        return false
    } else {
        console.log(diff, 'true');
        return true
    }
}

The test examples are passing but then when I submit the solution, some other tests are not passing. I don’t get to see the tests that are not passing so I’m stuck on this. Also, I thought that, in case a and b are the same number, so in case I had

cons([4, 6, 4, 5, 6], 4, 4)

my solution wouldn’t pass this test, so how could I improve it?

How to fix the error in v-model rendering

I have the following fragments in my index.blade.php:

The content section:

.
.
.
<div class="col-12 col-md-12 mb-3">
    <label for="attachment" text-muted">Attachment</label>
    <div class="col-md-12">
        <div>
            <b-form-file
                ref="attachment"
                id="attachment"
                v-model.trim="$v.feedback.upload.attachment.$model"
                placeholder="Click to upload..."
            ></b-form-file>
        </div>
    </div>
</div>
.
.
.

The script section:

.
.
.
var app = new Vue({
    el: '#app',
    data() {
        return {
            'feedback': { 'upload': {'attachment': null} }
        }
   }
})
.
.
.

Everytime I try to load the page, it caused this error as below:

[Vue warn]: Error in render: “TypeError: $v.feedback.upload is undefined”
(found in Root)

I would like to ask what caused the above error because when I commented the v-model.trim="$v.feedback.upload.attachment.$model" line, everything loads fine.
Thank you in advance for any response.

Showing graph on click

I’m working on a project for a time attendance system. Basically, I have a user registration system with admin verification. In the admin panel, I want to show working hours of workers by dates. I’m using Plotly.js for that. The problem is when I call onClick function by clicking button without adding return false; my graph disappears after a few seconds. If I add return false, then the graph shows; however, if I want to change to other worker, then the graph won’t show and it would go wide right.

Here is the code:

    <?php
session_start();
// Include config file
require_once "conn.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta charset="UTF-8">
    <title>Admin pregled korisnika</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
    body{ font: 14px sans-serif;}
    .wrapper {
            width: 420px; padding: 20px;
            text-align:center;
            float: left;
            margin-left: 5%;
            width: 45%;
            margin-top: 10%;
            background-color: #191970   ;
            border-radius: 20px;
            box-shadow:20px 20px 30px grey;
            color:white;
    }
    .right {
        float:right;
    }
    #myPlot{width:40%;overflow:visible;margin-top:10%;}
    #users {
        //font-family: Arial, Helvetica, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }
    
    #users td, th {
        border: 1px solid #191970;
        padding: 8px;
    }
    
    #users tr{background-color: white;color:#191970}
    
    
    #users th {
        padding-top: 12px;
        padding-bottom: 12px;
        text-align: left;
        background-color: #191970;
        color: white;
        text-align: center;
        }
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: #191970;
            position: fixed;
            top: 0;
            width: 100%;
        }

        li {
            float: right;
            height:100%;
            border-left: 1px solid white;
            
        }
        li a {
            display: block;
            color: white;
            font-size: 16px;
            text-align: center;
            padding: 26px 33px;
            text-decoration: none;
            height:100%;
            vertical-align: middle;
        }
        li a:hover{
            background-color: white;
            -webkit-box-shadow:inset 0px 0px 0px 3px #191970;
            -moz-box-shadow:inset 0px 0px 0px 3px #191970;
            box-shadow:inset 0px 0px 0px 3px #191970;
            color:#191970;
            text-decoration: none;
            height:100%;
            vertical-align: middle;
        }
        .dugme{
            margin: auto 3%;
            background-color: #191970;
            color: white;
            padding: 8px 16px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            transition-duration: 0.4s;
            cursor: pointer;
            border-radius: 4px;
            border-style: solid;
            border-width: 3px;
            border-color: #191970;
        }
        .dugme:hover {
            background-color: white;
            color: #191970;
            border-style: solid;
            border-width: 3px;
            border-color: #191970;
            border-radius: 4px;
     }
  </style>
</head>
<body>
    <ul> 
        <a href="#" class="navbar-brand">
            <img src="https://i.imgur.com/E0uimCR.png" height="58" alt="CoolBrand">
        </a>
        <li><b><a href="logout.php">ODJAVI SE</a></b></li>
        <li><b><a href="admin.php">ADMIN</a></b></li>
    </ul>
    
<div class="wrapper">
    
    <h1>Pregled korisnika: </h1>

    <table id = "users">
        <tr>
            <th>Id</th>
            <th>Korisničko ime</th>
            <th>Ime</th>
            <th>Prezime</th>
        </tr>

        <?php
            $query = "SELECT * FROM korisnici WHERE stat = 1 ORDER BY id ASC";
            $result = mysqli_query($conn, $query);
            while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
        ?>
        <tr>
            <td><?php echo $row['id'];?></td>
            <td>
                <form action ="aktivnosti.php" method ="POST">
                    <button class="dugme" onclick="getVrijeme(); return false;" name  ="uname" value = "<?php echo $row['uname'];?>"/><?php echo $row['uname'];?></button>
                    
                </form>
            </td>
            <td><?php echo $row['ime'];?></td>
            <td><?php echo $row['prezime'];?></td>
        </tr>
    

    <?php
            }
            ?>
            </table>
</div>

<?php

if(isset($_POST['uname'])){
    require_once "conn.php";
    $uname = $_POST['uname'];
    $string1 = $string2 = $string3 = "";
    $mysqli_qry = "SELECT * FROM $uname";
    $result2 = mysqli_query($conn,$mysqli_qry);
    if ($br=mysqli_num_rows($result2) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result2)) {
        $string1 = $string1. $row["datum"] . "*";
        $string2= $string2. $row["vrijemerada"] . "*";
    }
}

}
?>

<div class="right"><div id="myPlot"></div></div>
    <script>
        function getVrijeme(){
    var data1 = <?php echo json_encode($string1,JSON_HEX_TAG);?>;
    var data2 = <?php echo json_encode($string2,JSON_HEX_TAG);?>;
    var poz1=[];
    var poz2=[];
    var j=0;
    for(var i=0;i<data1.length;i++){
        if(data1[i]=='*'){
            poz1[j++]=i;
        }
    }
    j=0;
    for(var i=0;i<data2.length;i++){
        if(data2[i]=='*'){
            poz2[j++]=i;
        }
    }
    var radnovr=[];
    var datumi=[];
    radnovr[0]=data1.substring(0,poz1[0]);
    datumi[0]=data2.substring(0,poz2[0]);
    for(i=1;i<poz1.length;i++){
        radnovr[i]=data1.substring(poz1[i-1]+1,poz1[i]);
    }
    for(i=1;i<poz2.length;i++){
        datumi[i]=data2.substring(poz2[i-1]+1,poz2[i]);
    }
    var data = [{
        x: radnovr,
        y: datumi,
        type: "bar",
        }];
    var layout = {
        xaxis: {title: "Datumi"},
        yaxis: {title: "Provedeni sati"},
        title: "Provedeni sati na dnevnom nivou.",
        plot_bgcolor: "white",
        paper_bgcolor: "white"
    };

    Plotly.newPlot("myPlot", data, layout);
}
    </script>

</body>
</html>

Error in Test Api with jest and supertest

I keep getting the error when running my test case by jest :(( ,the idea is to get the token and send it with post testcase. At first i thougt that i did not get the token, but i run node exportToken and it work well. Here is my code. (Ps: For security reason i will not fill my firebaseConfig.)

my exportToken.js

const puppeteer = require('puppeteer');

const axios = require('axios');

const generateToken = async () => {
const browser = await puppeteer.launch({
    headless: true
});

const page = await browser.newPage();

await page.goto('https://example.com');

await page.addScriptTag({ path: 'firebase.js' });

const idToken = await page.evaluate(async () => {
    return await new Promise(resolve => {
        document.body.innerHTML = '<div id="recaptcha-container"></div>';
        const firebaseConfig = {
            apiKey: "",
            authDomain: "",
            projectId: "",
            storageBucket: "",
            messagingSenderId: "",
            appId: "",
            measurementId: ""
        };
        firebase.initializeApp(firebaseConfig);
        firebase.auth().languageCode = "vi";
        firebase.auth().settings.appVerificationDisabledForTesting = true;

        var phoneNumber = "+84975346330";
        var testVerificationCode = "112233";

        // This will render a fake reCAPTCHA as appVerificationDisabledForTesting is true.
        // This will resolve after rendering without app verification.
        var appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
        // signInWithPhoneNumber will call appVerifier.verify() which will resolve with a fake
        // reCAPTCHA response.

        firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
            .then(function (confirmationResult) {
                console.log(confirmationResult)
                confirmationResult.confirm(testVerificationCode).then((result) => {
                    // User signed in successfully.
                    const user = result.user;
                    user.getIdToken().then((idToken) => {
                        console.log(idToken)
                        resolve(idToken)
                    });
                }).catch((error) => {
                    resolve(error)
                });
            }).catch(function (error) {
                resolve(error)
            });
    })
})

await browser.close();

return idToken;
};

module.exports = generateToken();

my test.js

const request = require('supertest');

const axios = require('axios');

const generateToken = require('./exportToken');

const server = request.agent("http://localhost:9000");

describe("Unittest", function () {

it("Post /sessionLogin", async () => {

    const MyToken = await generateToken;

    server
        .post("/sessionLogin")
        .expect(200) // THis is HTTP response
        .send({ idToken: MyToken })

});
})  

I run node to get the Token and it work, and then use jest to test case but it keep showing this error.

C:UsersAdminDesktopDynocredit_vn_backend-test> npm test
> jest

FAIL  test/test.js (5.086 s)
Unittest
× Post /sessionLogin (3710 ms)

● Unittest › Post /sessionLogin

ENOENT: no such file or directory, open 'C:UsersAdminDesktopDynocredit_vn_backend- 
testfirebase.js'



Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        5.242 s
Ran all test suites.
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. 
Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

Unexpected output from what is expected to get in javascript

I am getting a durres output instead of the constantine, is there anything I am missing out? Here’s the photo

HTML:

  '''<div class="gnrt">
     <div class="cntnr">
       <select id="countryz" name="countryz">
         <option value="random">Random</option>
          <?php foreach($region['regions'] as $regn => $rgn){ ?>
           <option value="<?php echo $rgn['code'];?>"><?php echo $rgn['name'];?> (Region) 
 </option>

         <?php } foreach($countryarr1['countries'] as $countkey1 => $countname1){?>
           <option value="<?php echo $countname1['code'];?>"><?php echo $countname1['name'];?> 
  (Countries)</option>

            <?php } foreach($countrysts['countrySets'] as $cntrysts => $sts){ ?>
           <option value="<?php echo $sts['code'];?>"><?php echo $sts['name'];?> (Set)</option>
         <?php } ?>
        </select>
       </div>

     <div id="citycont" class="citycont">
     <?php foreach($countryarr1['countries'] as $countkey1 => $countname1){?>
        <div class=<?php echo $countname1['code'];?>>
         <select id="citied" name="citytest">
         <?php foreach($countname1['cities']['options'] as $cntrykey2 => $cntrys){?>
           <option value="<?php echo $cntrys['code'];?>"><?php echo $cntrys['code'];?></option>
         <?php } ?>
         </select>
       </div>
       <?php } ?> 
     </div>'''

Javascript:

 ''' <script type="text/javascript">
$(document).ready(function(){
  $('#countryz').bind('change', function(){
    var trycountry = $('#countryz').val();
    var uzer = "qwerty";
    var password = "password";

      if(trycountry=="ftl" || trycountry=="mesh1" || trycountry=="mesh2" || trycountry=="courir" || trycountry=="nikena" || trycountry=="nikena" || trycountry=="nikeas"){

        if(trycountry=="us" || trycountry=="mx" || trycountry=="cu" || trycountry=="pr" || trycountry=="gt" || trycountry=="ni" || trycountry=="nikena") {
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "us.proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "185.193.157.60";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
          });
        }
      
        else if(trycountry=="sg" || trycountry=="id" || trycountry=="my" || trycountry=="ph" || trycountry=="vn" || trycountry=="th" || trycountry=="nikeas"){
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "sg.proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "51.79.228.223";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
          });
        }

      
        else if(trycountry=="au" || trycountry=="nz" || trycountry=="pg"){
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "au.proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "51.161.196.188";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
          });
        }
      
        else{
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "91.239.130.17";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_set-" + trycountry);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
          });
        }
      }
       else{
      $(document).ready(function(){
      $('#citied').bind('change', function(){
        var elements = $('div.citycont');
        var trycity = $(this).val();

        if(trycountry=="us" || trycountry=="mx" || trycountry=="cu" || trycountry=="pr" || trycountry=="gt" || trycountry=="ni" || trycountry=="nikena") {
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "us.proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "185.193.157.60";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
          });
        }
      
        else if(trycountry=="sg" || trycountry=="id" || trycountry=="my" || trycountry=="ph" || trycountry=="vn" || trycountry=="th" || trycountry=="nikeas"){
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "sg.proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "51.79.228.223";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
          });
        }

        else if(trycountry=="au" || trycountry=="nz" || trycountry=="pg"){
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "au.proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "51.161.196.188";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
          });
        }
      
        else{
          $(document).ready(function(){
          $('#hst').bind('change', function(){
          var iptype = $('#hst').val();
            if(iptype=="dns"){
              var setcountry = "proxy.iproyal.com";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }else if(iptype=="iphst"){
              var setcountry = "91.239.130.17";
                $(document).ready(function(){
                  $('#tpz').bind('change', function(){
                  var httptype = $('#tpz').val();
                  if(httptype=="http|https"){
                    var texts = "12323";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }else if(httptype=="socks5"){
                    var texts = "12325";
                    $('#foruse').val(setcountry + " : " + texts + " : " + uzer + " : " + password + "_country-" + trycountry + "_city-" + trycity);
                  }
                  }).trigger('change');
                });
            }
          }).trigger('change');
        });
        }
      }).trigger('change');
      });
      }

  }).trigger('change');
});

”’

Typing this randomly, says I have a lot codes…………………………………………………………………………………………………………………………..

How to run shell command from javascript client-side?

I have the simplest program: 1 HTML file, 1 CSS file, and 1 JS file, just run directly on my own computer. And all I’m trying to do is that when you press a button in the program, one single shell command (Windows) is run directly on the computer. This will generate file, which in turn will be used further inside the program.

It appears you cannot access your local files through JS alone, so I installed NodeJS (which is completely new to me). But I still can’t get it to work that way either.

The only way I finally got NodeJS to host the HTML page in a way that the JS and CSS files also work, is by copying the code I got here: https://stackoverflow.com/a/13635318. (I called it server.js).

But I still haven’t been able to find a way to call upon server.js while client-sided to run that shell command. Some posts suggest using AJAX for this, like here https://stackoverflow.com/a/53897335, but I haven’t been able to find any way to successfully catch that in server.js.

How do I convert this to a functional component?

I’m trying to practice reactjs and how can I convert this class component to a functional component?

     handleChange = (e) => {
    const { name, value } = e.target;
    this.setState( {
        [name] :value
    })
  };

So far, I could only do this and I’m quite lost when it comes to the this.setState

 const handleChange = (e) => {
    const { name, value } = e.target;
  };

null is not an object (evaluating ‘user.uid’)

I want to retrieve a field value of a document in Users collection by referencing it via the where condition from Firestore. I use the context api to pass the user object of the logged in user in my app. I get this error that user.uid is null. I can’t spot where the mistake is. I have added the relevant piece of code.

EditProfile.js

const EditProfile = () => {
  const { user } = React.useContext(AuthContext);

  const [name, setName] = React.useState();

  React.useEffect(() => {
    const userid = user.uid;
    const name = getFieldValue("Users", userid);
    setName(name);
  }, []);

  
};

export default EditProfile;

passing and getting value via context

export const AuthContext = React.createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = React.useState(null);

  return (
    <AuthContext.Provider
      value={{
        user,
        setUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
const AppStack = () => {
  return (
    <AuthProvider>
      <BottomTab.Navigator>
        <BottomTab.Screen
          name="ProfileStack"
          component={ProfileStack}
        />
      </BottomTab.Navigator>
    </AuthProvider>
  );
};

export default AppStack;

ProfileStack.js

export const ProfileStack = ({ navigation }) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Profile"
        component={Profile}
      />
      <Stack.Screen
        name="EditProfile"
        component={EditProfile}
      />
    </Stack.Navigator>
  );
};

getFieldValue function

export const getFieldValue = (collection, userid) => {
    firestore()
      .collection(collection)
      .where("userid", "==", userid)
      .get()
      .then((querySnapshot) => {
        if (querySnapshot.size === 0) {
          return "";
        }
        if (querySnapshot.size === 1) {
          const { name } = querySnapshot[0].data();
          return name;
        }
      })
      .catch((e) => console.log(e));
  };