ReferenceError: localStorage is not defined at Object

I am using local storage to save the updatet variable value every time I run my test case but fore some reasons I get the error:

ReferenceError: localStorage is not defined at Object ReferenceError:
localStorage is not defined at Object.
(/app/Projects/Javascript/Mocha/27403_9907/Libraries/addNewBeneficiary.js:17:49)
at Module._compile (internal/modules/cjs/loader.js:1085:14) at
Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32) at
Function.Module._load (internal/modules/cjs/loader.js:790:12) at
Module.require (internal/modules/cjs/loader.js:974:19) at require
(internal/modules/cjs/helpers.js:93:18) at Object.
(/app/Projects/Javascript/Mocha/27403_9907/run/test.js:13:39) at
Module._compile (internal/modules/cjs/loader.js:1085:14) at
Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32) at
Function.Module._load (internal/modules/cjs/loader.js:790:12) at
ModuleWrap. (internal/modules/esm/translators.js:199:29) at
ModuleJob.run (internal/modules/esm/module_job.js:183:25) at async
Loader.import (internal/modules/esm/loader.js:178:24) at async
formattedImport
(/usr/lib/node_modules/mocha/lib/nodejs/esm-utils.js:7:14) at async
Object.exports.requireOrImport
(/usr/lib/node_modules/mocha/lib/nodejs/esm-utils.js:48:32) at async
Object.exports.loadFilesAsync
(/usr/lib/node_modules/mocha/lib/nodejs/esm-utils.js:88:20) at async
singleRun (/usr/lib/node_modules/mocha/lib/cli/run-helpers.js:125:3)
at async Object.exports.handler
(/usr/lib/node_modules/mocha/lib/cli/run.js:374:5)

I have created a JS file and uploaded it in a customized platform called Momentum, which we use for automated test. the code file is as following:

const { wd } = require("../setup/v2setup");

                    var isStepFailed = false;

                    var assert = require('assert');
                    var should = require('should');
                    var windowSize = null;
                    const axios = require('axios').default;

let storedXPathIndex = localStorage.getItem("storedXPathIndex");
                    let xPathIndex = (storedXPathIndex) ? ++storedXPathIndex : 0;
                    localStorage.setItem("storedXPathIndex", xPathIndex);
                    const max = 5;

                    exports.setAddNewBeneficiaryMethods = (driver) =>{

wd.addPromiseChainMethod('SelectAcc', () => {


                    
   if( ++xPathIndex > max ) xPathIndex = 0;
    return 

driver.swipeUntilElement("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.ScrollView/android.view.ViewGroup/androidx.recyclerview.widget.RecyclerView/android.view.ViewGroup["+ xPathIndex +"]")
})
}

wating for response from consumer in rabitmq and nodejs

I have two project with nodejs and typescript and a want to start comunication with rabitmq .

i install amqplib library from npm and use this config for published and subscriber project :

import amqp from ‘amqplib’;

export class MessageBroker {

    private static channel: amqp.Channel;

    public static async Initial(exchange: string, queue: string) {

        let cluster = await amqp.connect('amqps://mcbzjnsn:[email protected]/mcbzjnsn');
        let channel = await cluster.createChannel();

        await channel.assertExchange(exchange, 'direct', { durable: true, autoDelete: true });

        await channel.assertQueue(queue + '.' + exchange, {
            exclusive: true
        });

        await channel.bindQueue(queue + '.' + exchange, exchange, queue);

        channel.prefetch(1);

        this.channel = channel;

    }

    //Random id generator
    private static randomid() {
        return new Date().getTime().toString() + Math.random().toString() + Math.random().toString();
    }
    static async Publish(exchange: string, queue: string, message: any): Promise<void> {

        let id = this.randomid();

        MessageBroker.channel.sendToQueue(exchange, queue,
            Buffer.from(JSON.stringify(message)), { correlationId: id, replyTo: 'amq.rabbitmq.reply-to' })

    }

    static async SendToQueue(queue: string, message: any): Promise<void> {

        let id = this.randomid();

        MessageBroker.channel.sendToQueue(queue, Buffer.from('10'), {
            correlationId: id,
            replyTo: queue
        });
    }

    private static async Consume(exchange: string, queue: string): Promise<void> {



    }


}

now i want to use send message from project A to Project B with this code :

await MessageBroker.Publish('coin', 'transaction',{
            type:MessageBrokerType.Transfer,
            to:'0x36f5C37B48c7888634b9285ae30eeACa5AD427C0',
            amount:100
        });

and I need wait to projectB response but it does not wait for response from projectB and go the next line.

now, how can I do it? ( wait for response from the result of project B )

Re-use email of deleted Apple ID

I have an old Apple ID, is created by email “x” and I deleted it over 2 months ago.

Now, I want to re-use the email “x” to set for my current Apple ID.

But, they said that, this email is used, although it was deleted.

Can I re-use it one more time ? Do I have any mistakes ? Thanks all.

Script error when Transform PO to Item Receipt Error

I’m new to suitescript, I’ve got a schedule script to Transform a PO to Item Receipt. Which needs to create a record on Subrecord on inventorydetail sub record, I get “USER_ERROR”,”message”:”The total inventory detail quantity must be 1.” – Not sure what I have done wrong. If i use the same code for a non stock and remove the sub record insert line and coding it works

   var csvPOId = 73586;
        var csvPOLocationId = 1;
        var csvPOQty = 1;
        var csvBinId = '';
        var csvSerialLot = '';
        var csvInvQty = 1;
        //

        try {
            var itemReceiptRec = record.transform({
                fromType: record.Type.PURCHASE_ORDER,
                fromId: csvPOId,
                toType: record.Type.ITEM_RECEIPT,
                isDynamic: false
            });
        } catch (e) {
            log.error({
                title: e.name,
                details: e.message
            });
        }


        // Get count - Sublist Lines
        var count = itemReceiptRec.getLineCount({
            sublistId: 'item'
        });

        for (var i=0; i < count; i++) {

            // Item Sub List - Mark as Received
            var itemReceived = itemReceiptRec.getSublistValue({
                sublistId: 'item',
                fieldId: 'itemreceive',
                line: i
            });

            // Location
            itemReceiptRec.setSublistValue({
                sublistId: 'item',
                fieldId: 'location',
                value: csvPOLocationId, // '11 - Central Main Warehouse',
                line: i
            });
            // Quantity

            itemReceiptRec.setSublistValue({
                sublistId: 'item',
                fieldId: 'quantity',
                value: csvPOQty,
                line: i
            });

            // Inventory Detail Sub Record [inventorydetail]

            var subrec = itemReceiptRec.getSublistSubrecord({
                sublistId: 'item',
                line: i,
                fieldId: 'inventorydetail'
            });
            subrec.insertLine({
                sublistId: 'inventoryassignment',
                line: 0
            });
            // // Quantity - Mandatory
            subrec.setSublistValue({
                sublistId: 'inventoryassignment',
                fieldId: 'quantity',
                line: 0,
                value: csvInvQty
            });
        var itemRecID = itemReceiptRec.save({
            enableSourceing: true
        });

        log.debug({
            title: 'New Item Receipt Record',
            details: 'Internal ID ' + itemRecID
        });

Javascript onclick how to undo when clicked again

I’m creating a filter to search for your perfect shoe’s by answering questions. Right now I’ve got a couple of questions, each with multiple answers. By clicking on an answer a variable gets edited with the data of the value of that answer. The problemm is that you can click on the variable as many times as you like and the value will keep being added. Is there a way to change the color of the answer button when clicked and when clicked again it undo’s adding the value to the variable and changes the color back?

Code:

<div class="container">
    <div id="question"></div>
    <div id="answer"></div>
    <button onclick="check()" id="nextbtn">Next</button>
    <div id="finalLink"></div>      
</div>
<script type="text/javascript">

    var ShoeTest = [
        [
            'Whats your size?',
            ['41', '41'],
            ['42', '42'],
            ['43', '43']
        ],
        [
            'What color would you like?',
            ['Red', 'red'],
            ['Blue', 'blue'],
            ['Yellow', 'yellow'],
            ['Green', 'green']
        ],
        [
            'What brand would you like?',
            ['Adidas', 'adidas'],
            ['Nike', 'nike'],
            ['Puma', 'puma']
        ]
    ];

    let parms = [];

    count = 1;
    var questionNumber = 0;
    var button = document.getElementById('answer');
    var question = document.getElementById('question');
    var answerButton;
    var flag = true;

    function getLink(parms) {
        return ""+parms.join("&")
      };

      button.addEventListener("click",function(e) {
        const tgt = e.target;
        parms.push(tgt.value);
        console.log(getLink(parms))
      })

    function check(){
        oldAnswerButton = document.querySelectorAll('.filter_anwser');
        oldQuestion = document.getElementById('question');
        for(let z = 0; z < oldAnswerButton.length; z++){
            oldAnswerButton[z].style.display = 'none';
        }
        //question 
        for (let y = 1; y < ShoeTest[questionNumber].length; y++){
            // button
            var btn = document.createElement('button');
            btn.value = ShoeTest[questionNumber][y][1];
            btn.className = "filter_anwser";
            btn.textContent = ShoeTest[questionNumber][y][0];
            btn.setAttribute('data-el', 1);
            btn.onclick = ButtonColor();
            button.appendChild(btn);
            // class
            answerButton = document.querySelectorAll('.filter_anwser');
        }
        // question
        question.textContent = ShoeTest[questionNumber][0];
        question.id = "questionID";
                
        console.log(".....");
        // adds 1 to question to see a different question
        questionNumber++;
    }

    function ButtonColor(){
        btn = document.getElementById('answer');
        btn.style.backgroundcolor = flag ? "unclicked" : "clicked"
       flag = !flag;
    }

Also if you have multiple answers of one questions add a , between instead of a &?

Failure to get response from POST jQeury [duplicate]

So I got a quick script working with HTML and JS, but I can’t for the love of me get the response from the POST request. Here is what I have currently have:

<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="something()">Click Me!</button>
<script>
function something(){
  const Url = 'https://somelink.com';
  const date = 'somedata'
  var V
  
  $.post(Url,date,function(data) {
  V = data
  });
  
  alert(V)
}
</script>
</body>
</html>

I did try having the alert in the function(data) part but it would not register for some exact reason so I moved it out. Now it registers the alert but it can not get the response from the request.

I am testing it in JS Fiddle and the console log is “50:9 Uncaught ReferenceError: V is not defined”. Any and all help/nudges will be greatly appreciated. My goal is to get the response from the request and use it further down the line, so I am just testing as a proof of concept/correct coding with the alert.

React – history push throwing error: Failed to execute ‘pushState’ on ‘History’

I have a page on the URL:http://localhost:10001/track/8311c15a-7f7f-47ff-b81a-6f6904ad191c/my-form where I have a form. After the form is submitted I am using react’s router history to redirect to a success page

const MyComponent = ({match, location, history}: RouteComponentProps

const onSubmit = () => {
  history.push(`/${baseUrl}/success`)
}

But, when I try to do so, I get an error:

Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL 'http://track/8311c15a-7f7f-47ff-b81a-6f6904ad191c/success' cannot be created in a document with origin 'http://localhost:10001' and URL 'http://localhost:10001/track/8311c15a-7f7f-47ff-b81a-6f6904ad191c/my-form'.

It is the first time I have encountered this error. What am I doing wrong here?

My JQurery-AJAX code in my Django project for displaying a default value in a calculation based field fails to do so?

These are two of few models in my project:

class Package(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE)
    treatment=models.ForeignKey(Treatment, on_delete=CASCADE)
    patient_type=models.ForeignKey(PatientType, on_delete=CASCADE)
    date_of_admission=models.DateField(default=None)
    max_fractions=models.IntegerField(default=None)
    total_package=models.DecimalField(max_digits=10, decimal_places=2)
    package_date=models.DateTimeField(auto_now_add=True)

class Receivables(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    rt_number=models.CharField(max_length=15)
    discount=models.DecimalField(max_digits=9, decimal_places=2, default=0)
    approved_package=models.DecimalField(max_digits=10, decimal_places=2)
    approval_date=models.DateField(default=None)
    proposed_fractions=models.IntegerField()
    done_fractions=models.IntegerField()
    base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    receivables_date=models.DateTimeField(auto_now_add=True)

I needed the approved_package in Receivables to display a default value calculated by subtracting discount from the total_package in Package. And it should all be in real time. So I wrote an AJAX code in Jquery in an HTML file and included the file in my main template. The code looks like:

<script>
    $('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
     var csr = $("input[name=csrfmiddlewaretoken]").val();
     console.log(textSelected);
        pkg={patient:textSelected, csrfmiddlewaretoken:csr}
        $.ajax({
            url:"{% url 'pt_name' %}",
            method: "POST",
            data: pkg,
            dataType: "json",
            success: function(data){
                console.log(data);
                console.log(data.pkg);
                console.log(data.ptt);
                var tp=data.pkg;
                var ptt=data.ptt;
                $('#id_discount').change(function(){
                    console.log('tp value: ', tp);
                    console.log('ptt value: ', ptt);
                    var discount=document.getElementById('id_discount').value;
                    console.log('discount value: ', discount);
                    var approved_package=document.getElementById('id_approved_package').value;
                    if (ptt=='CASH')
                    approved_package=tp-discount;
                    console.log('approved package new value: ', approved_package);
                });
            }
        });
    });
</script>

The code runs fine in the console of the browser. It fires all the codes. It calculates the approved_package but the result still does not show up in the field as a default value when I enter the discount value. What is wrong with my code? Can someone point it out?

Is the following form of functional components valid?

Pretty new to React here. Thus far, I’ve only been using components that either take no arguments or props. Then, I always render the component using the form <SomeComponent {...props}/>

However, I came across a situation where I didn’t even realize that some of the functions I was creating were actually functional components since they were returning JSX. However, they were visibly different from the way I’m used to making and using components. It looked something like this:

  const MoneyExample = (category, amount) => {
    if (typeof amount !== "number" || typeof category !== "string") {
      return;
    }
    return (
      formatter.format(amount) !== "$0" && (
        <>
          <h4>{category.charAt(0).toUpperCase() + category.slice(1)}</h4>
          <p>{formatter.format(amount)}</p>
        </>
      )
    );
  };

and then rendering it inside another component using like this

{MoneyExample("Budget", someAmount)}

instead of the more common form

<MoneyExample budget={"Budget"} amount={someAmount} />

I’ve tried looking around for info, but I’m not even really sure how to phrase the question. Is this type of thing against React’s principles or completely fine? Sorry if this is obvious to some.

Javascript source missing in the page at first loading

I have an Html page executed in an Iframe where at first loading, sometimes in the source I see that js code is missing at all including the opening js script tag: <script language="Javascript>" but more surprisingly (at least to me), I have links like: href="javascript:namefunction where the string javascript:namefunction is missing too. Is this javascript:namefunction missing part connected to the wrong js loading in the page?
I tried to understand the possible reasons but could not figure out.

How to use addEventListener on multiple input fields to invoke keyup event on them in JavaScript?

I have multiple input fields on which I want to apply onkeyup event on all of them with passing ID of textbox as a parameter. I want multiple keyup event because I want to handle some calculations on the basis of input ID. I tried but failed. Please suggest some solutions.

function GetDynamicTextBox(value) {
    return '<td class="">'+'<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";>{OptionsPlaceholder}</select>'
                        +'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_co"></td>'
                        +'<td><select class="js-example-placeholder-single js-states form-control" id="ldriverselect"></select>'
                        +'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_driver"></td>'
                        +'<td class=""><select class="js-example-placeholder-single js-states form-control" id="ltruckselect"></select>'
                        +'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_truck"></td>'
                        + '<td><input name = "tripnumber" type="text" class="form-control" id="ltripnumber"/></td>'
                        +'<td><select id="lsubtrip" name="subtrip" class="js-example-placeholder-single js-states form-control"><option disabled selected></option>'
                        +'<option value="1">1</option><option value="2">2</option><option value="3">3</option></select>'
                        + '<td><input name = "date" type="date" class="form-control" id="ldate"/></td>'
                        + '<td><input name = "pickupcity" type="date" class="form-control" id="lpickupcity"/></td>'
                        + '<td><input name = "pickupstate" type="date" class="form-control" id="lpickupstate"/></td>'
                        + '<td><input name = "deliverydate" type="date" class="form-control" id="ldeliverydate"/></td>'
                        + '<td><input name = "delivercity" type="text" class="form-control" id="ldelivercity"/></td>'
                        + '<td><input name = "deliverstate" type="text" class="form-control" id="ldeliverstate"/></td>'
                        + '<td><input name = "loadnumber" type="text" class="form-control" id="lloadnumber"/></td>'
                        + '<td><input name = "loadrate" type="text" class="form-control" id="lloadrate" /><span id="lerrormessage"></span></td>'
                        + '<td><input name = "dispatchfee" type="text" class="form-control" id="ldispatchfee" readonly/></td>'
                        + '<td><input name = "fuel" type="text" class="form-control" id="lfuel"/></td>'
                        + '<td><input name = "cardfee" type="text" class="form-control" id="lcardfee"/></td>'
                        + '<td><input name = "onloadrepair" type="text" class="form-control" id="lonloadrepair"/></td>'
                        + '<td><input name = "shoprepair" type="text" class="form-control" id="lshoprepair"/></td>'
                        + '<td><input name = "trailerrent" type="text" class="form-control" id="ltrailerrent"/></td>'
                        + '<td><input name = "comcheck" type="text" class="form-control" id="lcomcheck"/></td>'
                        + '<td><input name = "advance" type="text" class="form-control" id="ladvance"/></td>'
                        + '<td><input name = "miscellenous" type="text" class="form-control" id="lmiscellenous"/></td>'
                        + '<td><input name = "misc1" type="text" class="form-control" id="lmisc1"/></td>'
                        + '<td><input name = "misc2" type="text" class="form-control" id="lmisc2"/></td>'
                        + '<td><input name = "misc3" type="text" class="form-control" id="lmisc3"/></td>'
                        + '<td><input name = "misc4" type="text" class="form-control" id="lmisc4"/></td>'
                        + '<td><input name = "total" type="text" class="form-control" id="ltotal" readonly/></td>'
                        + '<td><input name = "layover" type="text" class="form-control" id="llayover"/></td>'
                        + '<td><input name = "addtl1" type="text" class="form-control" id="laddtl1"/></td>'
                        + '<td><input name = "addtl2" type="text" class="form-control" id="laddtl2"/></td>'
                        + '<td><input name = "addtl3" type="text" class="form-control" id="laddtl3"/></td>'
                        + '<td><input name = "subtotal" type="text" class="form-control" id="lsubtotal" readonly/></td>'
                        + '<td><input name = "paymentmode" type="text" class="form-control" id="lpaymentmode"/></td>'
                        + '<td><input name = "pay" type="text" class="form-control" id="lpay"/></td>'
                        + '<td><input name = "notes" type="text" class="form-control" id="lnotes"/></td>'
                        + '<td><input name = "grandtotal" type="text" class="form-control" id="lgrandtotal" readonly/></td>'
                        + '<td><button type="button" class="btn btn-outline-info text-info" onclick="savetriplist();">Submit</button>' 
                        +'<button type="button" class="btn btn-outline-danger text-danger remove">Remove</button></td>'
            }

Use Express post request to emit Socket.io

I want get username when user post it, but io.sockets.emit is not working. However, When i didn’t put io.sockets.emit on app.post, It is working.

my html

<html>
    <body>
        <form action="chat" id="main" method="post">
            <div>
                <input type="text" id="id" name="username" value="" placeholder=" " required />
                <label for="id">暱稱</label>
            </div>
            <div>
                <input type="text" id="key" name="key" value="" placeholder=" " />
                <label for="key">房號</label>
            </div>
            <button type="submit" value="加入房間" class="btn">加入房間</button>
        </form>
    </body>
</html>

my js

io.on('connection', (socket) => {

    socket.on('joinRoom', username => {
        console.log(username);
        console.log("joinRoom");
    });
    socket.on('chat message', msg => {
        const user = getCurrentUser(socket.id);
        console.log(user);
        io.emit('chat message',  msg);
  });
});
app.post('/chat', urlencodedParser, function (req, res) {
    io.sockets.emit('joinRoom', "aa")
    console.log(req.body)
    res.sendFile('public/chat.html', { root: __dirname })
});

‘joinRoom’ seems not receive anything.

join value FormData with axios use javascript

i send value using postman with body form data format like this :

example with postman

analisa_type:1;1;2
eficiency_type:0;1;1

I input array data with separator (;)

i am confused how to separate it on axios
this is my code

let eficiency_name = this.items_efiicieny.map(x => x.analisa_exception_label).join(";");
let eficiency_type = this.combine.map(x => x.object_type).join(";");

const f = new FormData();
f.append("analisa_type", eficiency_name);
f.append("label_type", eficiency_type);

how to format the form data so that the value is like in postman?