Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all 141337 articles
Browse latest View live

TCP socket Javascript (server) and Python (client)

$
0
0

I wrote a custom Python client and server that communicate through TCP sockets:

  1. Client connects to the server
  2. Client sits idle until server sends a custom command to the client (for example, server sends the amount of seconds it wants the client to sleep)
  3. Client executes the command (something like time.sleep(5))
  4. Client sends a response back to the server once the command is finished executing
  5. Go to Step 2 and repeat

The way I send and receive socket data is as follows:

  1. Create a message that is a JSON string
  2. Read/Write a message length to socket (when reading, client/server will freeze until the message is received, which is OK for my use case)
  3. Read/Write a message to socket (since the length is known, we know how many bytes we need to read from the socket to get the whole message)

I tried writing the server using Node.JS and keeping the client in Python (I have no JS experience):

var net = require('net');

var server = net.createServer(function(socket) {
    console.log('Connected:', socket.remoteAddress, ':', socket.remotePort);

    while (true) {
        // Send a custom command to the client
        values = prepareMessage({ 'command' : 'sleep', 'time' : '5' })
        socket.write(values[0]);
        socket.write(values[1]);

        // Wait for client to execute the command and receive response
        res = socket.read(32); // Message length is at most 32 bits
        while(res == null) {
            res = socket.read(32);
            console.log('Wait for message length');
        }
        console.log('Message length received, now read message');
        message = socket.read(res);
    }
});

server.listen(1337, '127.0.0.1');


/*
Converts message from dictionary to a correct format to pass onto the client
*/
function prepareMessage(msg) {
    var message = JSON.stringify(msg);
    var message_length = (message.length).toString(2);

    // Make the message contain 32 bits
    while(message_length.length < 32) {
        message_length = "0" + message_length;
    }

    return [message_length, message];
}

Problem is, my socket.read() method is constantly returning null, no matter what I send to it. Is there a way to convert my python server code to this?


The date changing to one day before while converting JavaScript Date object to a JSON string

$
0
0

I want to pass a Date object (Date is "12/01/2019" in MM/DD/YYYY format) as JSON string to an API. But while converting this date (without considering time zone) into the JSON string, the date is changing to one day before. Please see the code given below:

var newDate = new Date("12/01/19");
console.log(newDate)        // Showing Sun Dec 01 2019 00:00:00 GMT+0530 (India Standard Time)
var jsonDate = JSON.stringify(newDate);
console.log(jsonDate)       // Showing "2019-11-30T18:30:00.000Z"

The Date Dec 01, 2019 changes to Nov 30, 2019. In my case, I can't consider the time or time zone. I can't use 'Moment JS' also.

Why does this happen? Can anyone specify the reason behind this weird problem?

Is It write way to call apis in loop and use of async await

$
0
0

I have an array arr, I want to loop for each element of it. In the loop, I call two fxns A() and then B(), What I want is loop will run parallel but for each element fxn A must run first then fxn B.

what i am doing is it :

[1,2,3].forEach(async(i)=>{
await A(i);//which call API & console & returns iA 
await B(i);//which call API & console & returns iB  
console.log('A & B Completed for '+ i) 
 }  )

//Desired Result

1A
1B
A & B Completed for 1
3A //due to parallelism
3B
A & B Completed for 3
2A
2B
A & B Completed for 2

Is it write or any other good way, please help.

HttpEventType don't get ResponseHeader and Response

$
0
0

I got service to upload files, simple post.

I am trying to get response from every step:

// Upload to server
    this.dragdropService.addFiles(this.form.value.file)
      .subscribe((event: HttpEvent<any>) => {
        switch (event.type) {
          case HttpEventType.Sent:
            console.log('Request has been made!');
            break;
          case HttpEventType.ResponseHeader:
            console.log('Response header has been received!');
            break;
          case HttpEventType.UploadProgress:
            this.progress = Math.round(event.loaded / event.total * 100);
            console.log(`Uploaded! ${this.progress}%`);
            break;
          case HttpEventType.Response:
            console.log('File uploaded successfully!', event.body);
            setTimeout(() => {
              this.progress = 0;
              this.fileArr = [];
              this.fileObj = [];
              this.msg = "File uploaded successfully!"
            }, 3000);
        }
      })
  }

First case works fine - I got

console.log 'Request has been made'

but ResponseHeader is never called. Then I got response from UploadProgress - I got

console log: 'Uploaded! 100%'

and at the end I want to get Response to know if the file has been added. Also I want to show msg 'File upload successfully'

Why ResponseHeader and Response is never called?

localStorage ReactJs not working while push

$
0
0

I just tried to store array data inside localStorage with ReactJs.
Code Below :

storeData(){

    const datas = {
        name : this.state.prevName,
        id : Date.now()
    }

   var localDatas = localStorage.getItem('names');

    if(!localDatas){
        localStorage.setItem('names',JSON.stringify(datas));
    }else{
        var items = [];
        items = JSON.parse(localStorage.getItem('names'));
        items.push(datas);
        localStorage.setItem('names',JSON.stringify(items));
    }
}

It's working first time when undefined localDatas variable. I mean when there is no names set at localStorage.
if running for first time And whenever i tried to push new data then its generate error.
Error Below :

TypeError: items.push is not a function

     }else{
     68 |         var items = [];
     69 |         items = JSON.parse(localStorage.getItem('names'));
     > 70 |         items.push(datas);
     71 | ^         localStorage.setItem('names',JSON.stringify(items));
     72 |     }
     73 | }

How to solve this ?

How can I use a Javascript variable in href?

$
0
0

I am setting up a system for pagination with similarly-named pages. It is my first time trying Javascript, but with help from many other StackOverflow questions, I was able to set up a system that takes my original page's url and creates a "next" and "previous" link. However, these links are in the form of JS variables, and I don't know to insert them inside a html link.

My current code is:

function break_address(url_add) {
      var page = url_add.split("/").slice(-1);
    var num = url_add.split('page-')[1]; 
[1]; //next
  var numnext = parseInt(num)+1;
  var numprev = parseInt(num)-1;
  var nextpage = "https://MYCOMIC.neocities.org/page-" + numnext + ".html";
   var prevpage = "https://MYCOMIC.neocities.org/page-" + numprev + ".html";
   //this return is only so that I can make sure the new links were created correctly
    return [num, numnext,numprev,nextpage,prevpage]
 document.getElementById("next").setAttribute("href",nextpage);
}
//in the real code i am adding the current url with window.location.href instead
var url_add = "https://MYCOMIC.neocities.org/page-2.html"
console.log("Original address: "+url_add)
console.log(break_address(url_add))
<!--the links are set to # right now because I don't know how to set them up.--><a href="#"><img src="previous.png" alt="PREVIOUS PAGE" style="height: 75px; width: 75px; padding-left 50px, padding-right: 50px;"></a><a href="#"><img src="next.png" alt="NEXT PAGE" style="height: 75px; width: 75px; padding-left 50px, padding-right: 50px;"></a>

In another similar question on here, someone suggested adding something along the lines of

document.getElementById("next").href = nextpage;

and then recalling it by doing

<a id="nextpage">link</a>

However, when I tried to do this, the link was no longer active. When I added href back in, (<a href="#" id="nextpage">link</a>) then the link does work, but it links to the same page I am already on.

What am I doing wrong? How can I get my current page to redirect to the url I made in Javascript? (note: the urls /page-1.html, /page-2.html, and /page-3.html do all exist.)

Can we able to share message to predefined users reactnative share

$
0
0

I need to make a location Sharing app, and I have list of users already listed, and when I click on share of reactnative share I would like to populate all those listed users in to.

Unintentional cloning

$
0
0

This is supposed to clone when you press the button ONLY. I have been trying for the past few days to bind the button to a click function but I do not know why it does not work.

Snippet of the code below:

html:

<input type="button" value="+" id="button+" onclick="clone1()"/>
<div id="container"></div>
<div class="cloneitem">
    <style>
    select:invalid { color: gray; }
    </style>
    <form>
    <select required>
    <option value="" disabled selected hidden>How much?</option>
    <option value="S">A little</option>
    <option value="M">A good bit</option>
    <option value="L">A lot</option>
    </select>
    of
<input type=text id="ansbox">
</form>
</div>

js:

$(function clone1(){

$('input').click(function(){
    $('.cloneitem:first').clone().appendTo('#container').find("input:text").val("")
    ;
});

});


How to remove a file without affecting other file upload in HTML

$
0
0

I'm trying to upload a file in the header and after clicking submit, the uploaded file will be assigned to other file uploads but when I click the (X) button, all of the file upload associated will be removed as well. The sample image is uploaded here.

As much as possible, please limit the solution to JavaScript/jQuery only. Thanks.

Sample code below:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>

<p>Click on the "Choose File" button to upload a file:</p>


  <input type="file" id="myFile" name="filename">
  <br />
  <br />
  <input type="submit" onclick="test(event)">
  <br />
  <br />
  <input type="button" value="X" onclick="removeFile('#myFile1')"><input type="file" id="myFile1" name="filename">
  <input type="button" value="X" onclick="removeFile('#myFile2')"><input type="file" id="myFile2" name="filename">
  <input type="button" value="X" onclick="removeFile('#myFile3')"><input type="file" id="myFile3" name="filename">


<script>
function test(e)
{
    e.preventDefault();
    $("#myFile1")[0].files = $("#myFile")[0].files;
    $("#myFile2")[0].files = $("#myFile")[0].files;
    $("#myFile3")[0].files = $("#myFile")[0].files;
}

function removeFile(value)
{
    $(value).val('');
}
</script>

</body>
</html>

Do not be confused that when after removing a file, there is still file uploaded which is actually isn't.

Why can I add named properties to an array as if it were an object?

$
0
0

The following two different code snippets seem equivalent to me:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

and

var myObject = {'A': 'Athens', 'B':'Berlin'};

because they both behave the same, and also typeof(myArray) == typeof(myObjects) (both yield 'object').

Is there any difference between these variants?

Trying to grab variable named 0

$
0
0

I want to get some data and i'm using

 $.each(data, function(index,value)
  {
    console.log(value);    
    var name = value.0.name;
  });[enter image description here][1]
 [1]: https://i.stack.imgur.com/4qnbo.jpg

I'm getting undefined which i believe is due to the 0. is there a different way to represent the 0?

Unable to see Mobile Menu when adding this code

$
0
0

**

Unable to see my mobile menu when I use this thing. But when I paste > the header straight into the index it works fine.

**

<html><head><title></title><script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script><script>
    $(function() {
      $("#header").load("header.html");
      $("#footer").load("footer.html");
    });</script></head><body><div id="header"></div><!--Remaining section--><div id="footer"></div></body></html>

How to distinct and merge objects from an array of objects in Javascript

$
0
0

I have an array of objects.

[
  { _id: { year: 2020, month: 1 } },
  { _id: { year: 2019, month: 1 } },
  { _id: { year: 2019, month: 2 } },
  { _id: { year: 2019, month: 4 } },
  { _id: { year: 2019, month: 5 } },
  { _id: { year: 2019, month: 8 } },
  { _id: { year: 2019, month: 9 } },
  { _id: { year: 2019, month: 11 } }
]

I want to remove the duplicate year properties from the objects and push different month data in one array object.

I want to get below output:

[
  {
    "_id": {
      "year": 2020,
      "month": [1]
    }
  },
  {
    "_id": {
      "year": 2019,
      "month": [1, 2, 4, 5, 8, 9, 11]
    }
  }
]

I have tried but cannot get the expected output:

let arr = [
  { _id: { year: 2020, month: 1 } },
  { _id: { year: 2019, month: 1 } },
  { _id: { year: 2019, month: 2 } },
  { _id: { year: 2019, month: 4 } },
  { _id: { year: 2019, month: 5 } },
  { _id: { year: 2019, month: 8 } },
  { _id: { year: 2019, month: 9 } },
  { _id: { year: 2019, month: 11 } }
];

let newArr= []; 
    arr.forEach(function (item) { 
        let isMatch = newArr.filter(function (elem) {
            return elem._id.year === item._id.year 
        })
        if (isMatch.length == 0) {
            newArr.push(item)
        }
        else {
            newArr.find(x => x._id.year === item._id.year)._id.month.push(...item._id.month);
        }
    })
    console.log(newArr);

Here Map Not loading properly on IE Browser

$
0
0

I am using HERE Map on a website. The Map loads perfectly fine on all browsers except "Internet Explorer". The Example on Here Map Documentation also doesn't load on "Internet Explorer".

Console shows following error in **`https://js.api.here.com/v3/3.1/mapsjs-core.js`** file :

Object doesn't support property or method 'trunc'

Unhandled promise rejection TypeError: Object doesn't support property or method 'values'

Map loads properly on Chrome

enter image description here

Map Fails on IE

enter image description here

Here Map Documentation Map doesn't work on IE

enter image description here

Masking Name with Regex in Javascript

$
0
0

I wanna mask a name with the provisions that if there are more than 4 letters it will form the following masking :

Jason Mamoa ---> Ja**n Ma**a

I have tried this :

var name ="Jason Mamoa";
var regex =/\b[^\W]{2}([^\W]{2,})[^\W]\b/g;
console.log(nama.replace(regex,"**$1*"));

but the opposite happened, like this :

Jason Mamoa --> **so* **mo*

How to trigger click event on child component in VueJS unit test?

$
0
0

I have the following Vue component:

<template>
    <div>
        <div>
            <year-btn @click="incrementYear"
                ref="increment-btn"/>
        </div>
    </div>
</template>

<script>
import yearBtn from "@/components/formInputs/yearBtn.vue";

export default {
    components: {
        "year-btn": yearBtn,
    },
    data() {
        return {
            monthAndYear: {
                year: 2000,
            },
        };
    },
    methods: {
        incrementYear() {
            this.monthAndYear.year++;
        },
    },
};
</script>

And I have the following Vue unit test.

it('test', async () => {
    wrapper = factory();

    wrapper.setData({
        monthAndYear: {
            year: 2020,
        },
    });

    wrapper.find({ ref: "increment-btn" }).trigger("click");
    await wrapper.vm.$nextTick();

    result = wrapper.vm.monthAndYear.year;
    expect(result).toEqual(2021);
});

Unfortunately, the above test fails because the click event on the 'year-btn' component fails to be triggered by Vue Test Utils. I know this because, if I replace my template with the following code the test passes.

<template>
    <div>
        <div>
            <button @click="incrementYear"
                ref="increment-btn"></button>
        </div>
    </div>
</template>

My question is, how do I trigger a "click" event on a child component (year-btn) that my component is using?

Below is what the year-btn component looks like:

<template>
    <button @click="$emit('click')">
        Click me
    </button>
</template>

How to save an array using AdonisJs migrations?

$
0
0

I'm trying to save an array to a PostgreSQL database, but I can't!

'use strict'

const Schema = use('Schema');

class UsersSchema extends Schema {
  up () {
    this.create('users', (table) => {
      table.increments();
      table.string('name', 255).notNullable();
      table.string('languages', 255).notNullable().defaultTo('[]');
      table.timestamps();
    });
  }

  down () {
    this.drop('users');
  }
}

module.exports = UsersSchema;

I tried to save like a string, like an array and use JSON.parse(), but it doesn't work

Material-table: How to change disable action button if my rowdata.status = cancelled

$
0
0

How to disable the action button based on rowdata.???

I am using material-table with remote data features.

I have to disable icon: build when rowdata.status is canceled.

I tried to look at the documentation but it didn't help. I also tried checking StackOverflow answers but no luck

Here is my code. Please help in fixing it.

Thanks in advance

<MaterialTable
  icons={tableIcons}
  tableRef={this.tableRef}
  title="Your Rollouts"
  options={{
    actionsColumnIndex: -1,
    search: true
    // pageSize: 10,
    //  pageSizeOptions: [10, 20, 50]
  }}
  columns={[
    {
      title: "Rollout ID",
      field: "_id"
    },
    { title: "Status", field: "rolloutStatus" },
    { title: "Created By", field: "createdby" },
    { title: "Created Date", field: "CreatedDate", type: "datetime" },
    { title: "Updated Date", field: "updateddate", type: "datetime" },
    { title: "CRQ Number", field: "crqnumber" }
  ]}
  actions={[
    {
      icon: () => <Refresh />,
      tooltip: "Refresh Data",
      isFreeAction: true,
      onClick: () => this.tableRef.current.onQueryChange()
    },

    {
      icon: () => <Build />,
      tooltip: "Perform action",
      onClick: (event, rowData) => {
        this.setState({ visible: true });
      }
    },

    {
      icon: () => <Visibility />,
      tooltip: "View Rollout",
      onClick: (event, rowData) => {
        alert(rowData.xml);
      }
    }
  ]}
  data={query =>
    new Promise((resolve, reject) => {
      let url = "http://localhost:5000/getRollout?";
      if (query.search) {
        url += "querysearch=" + query.search;
        url += "&per_page=" + query.pageSize;
        url += "&page=" + (query.page + 1);
        fetch(url)
          .then(response => response.json())
          .then(result => {
            console.log(result.data);
            resolve({
              data: result.data.filter(pub => pub._id.includes(query.search)),
              page: result.page - 1,
              totalCount: result.total
            });
          });
      } else {
        url += "per_page=" + query.pageSize;
        url += "&page=" + (query.page + 1);
        if (query.orderBy) {
          let sortOrder = query.orderDirection;
          url += "&sort=" + query.orderBy.field + "&sortOrder=" + sortOrder;
        }

        console.log(url);

        fetch(url)
          .then(response => response.json())
          .then(result => {
            console.log(result);
            resolve({
              data: result.data.filter(pub => pub._id.includes(query.search)),
              page: result.page - 1,
              totalCount: result.total
            });
          });
      }

      console.log(url);
      console.log(query.orderBy);
      console.log(query.orderDirection);
    })
  }
/>;

set scroll bar to specific div

$
0
0

I have a scroll bar inside a div called "smsBlk". I would like to move this scroll bar to a particular element ("msgUnread") which is a child element of "smsBlk". All the child elements will be rendered dynamically.

<div id="smsBlk" class="" style="height: calc(100vh - 320px);overflow-y: scroll;margin-bottom: 10px;padding: 20px;width:100%;background: #ecf0f1;">
<div class="msg"></div>
<div class="msg"></div>
<div class="msg"></div>
<div id="msgUnread" class="msg"></div>
<div class="msg"></div>
<div class="msg"></div>
</div>

Tried using offSet().Top. But,no luck. offSet().Top of msgUnread element was returning negative value if we scroll to bottom. This scrollbar is not for entire page. Can any one please help me to achieve the functionality? Thanks in advance!

ActionController::ParameterMissing (param is missing or the value is empty: field)

$
0
0

I am stuck on this backend issue and cannot understand why it is not defined. The id is passed into the params at the start of the handledFormSubmit function, but when the field is passed into a const and defined as const field = Field.findyById(id); => the output of field is then undefined.

Why is it losing its value? (attached the screenshot of the event in the DOM below for more information)

ActionController::ParameterMissing (param is missing or the value is empty: field):

Controller:

def index
  @fields = Field.all
  render json: @fields
end

def update
  @field = Field.find_by(id: params[:id])
  @field.update(field_params)

  if @field.save
    render json: @field, status: :accepted
  else
    render json: { errors: @field.errors.full_messages }, status: :unprocessible_entity
  end
end

private

def field_params
  params.require(:field).permit(:id, :name, :coordinates, :locations)
end

Adapter:

fetchFields() {
    return this.get(`${this.baseUrl}/fields`);
}

updateField(id, input) {
    return this.patch(`${this.baseUrl}/fields/${id}`, input);
}

get(url) {
    return fetch(url).then(res => res.json());
}

patch(url, input) {
    return fetch(url, {
        method: 'PATCH',
        headers: this.headers,
        input: JSON.stringify(input),
    }).then(res => res.json());
}

App:

handleFormSubmit(e) {
    e.preventDefault();
    const id = e.target.dataset.id;
    const field = Field.findById(id);
    const coordinates= e.target.querySelector('input').value

    const inputJSON = { name, coordinates };
    this.adapter.updateField(field.id, inputJSON).then(updatedField => {
      const field = Field.findById(updatedField.id);
      field.update(updatedField);
      this.addFields();
    });
  }

handleEditClick(e) {
    const id = parseInt(e.target.dataset.id);
    const field = Field.findById(id);
    document.querySelector('#update').innerHTML = field.renderUpdateForm();
}

image of dev console

Viewing all 141337 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>