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

JSON filtering for multiple keys runs slow

$
0
0

My code works, but it seems to be running exceptionally slow.

I have an array of values to search and I have a JSON that I'm filtering.

var JSONPull;
var FilterJSON = [];
var TypeIDs = [34,35,36,37,38,39,40,11399,1230,17470,17471,1228,17463,17464,1224,17459,17460,18,17455,17456,1227,17867,17868,20,17452,17453,1226,17448,17449,21,17440,17441,1231,17444,17445,1229,17865,17866,1232,17436,17437,19,17466,17467,1225,17432,17433,1223,17428,17429,22,17425,17426,11396,17869,17870];

fetch('URL API')
    .then(res => res.json())
    .then((out) => {
        JSONPull = out;
        TypeIDs.forEach(function (index){
            FilterJSON = JSONPull.filter((element) => {
                console.log("index: "+index);
                console.log(element);
                console.log("type_id: "+ element.type_id);
                element.type_id === index;
            });
        })
    })

The console.logs are more just to watch the code while testing, but definitely shouldn't be causing these performance issues.

Could you please advise me on performance optimisation?


How to make a div go underneath another div based on screen size

$
0
0

I am working on a website right now and I currently have a div with two elements inside it, currently the elements are on the same line. Though if the screen size goes below a certain pixel size, I would like these elements to stack on top of each other, rather than staying on the same line and flowing into the other content. Wondering if anyone knows how to do this. I am using media queries on other things, but I don't know how to implement this into a media query.

push() a two-dimensional array

$
0
0

I'm trying to push to a two-dimensional array without it messing up, currently My array is:

var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]

And my code I'm trying is:

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;
var cols = 7;

for (var i = r; i < rows; i++)
{
    for (var j = c; j < cols; j++)
    {
        myArray[i][j].push(0);
    }
}

That should result in the following:

var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]

But it doesn't and not sure whether this is the correct way to do it or not.

So the question is how would I accomplish this?

Basic JS: Adding characters at cursor position, while maintaining cursor position

$
0
0

Say I am making a basic Calculator that allows whole expressions to typed by the user. I'll use a simple <input> tag.

The user can type whatever they want, but I want to make it even easier for the client, I want to add a closing parenthesis immediately after they type (, so I set up my javascript to detect when ( is input by into the input field, then += a ) to the input field.

The problem with my code is that it adds the parenthesis to the end of the input, regardless of where they type the parenthesis, even at the beginning.

How can I add a character where ever the cursor is?

My code is as follows:

input = document.querySelector("input[type=text]");

input.addEventListener(`keyup`, (event)=>
{
  if(event.key === `(`)
  {
    input.value+=`)`;
  }
});
<input type="text" placeholder="Put mathematical expression"></input>

Dynamic extension of prototype lookup chain leads to weird bug

$
0
0

I'm currently trying to globally / permanently inject my own set of functions into the prototype of Node's IncomingMessage class. To do so, I came up with this abomination of code:

class RequestHelpers {
    get ip() { return this.socket.remoteAddress; } //https://nodejs.org/api/net.html#net_socket_remoteaddress
    foobar() { return this; }
    get foobar2() { return "1"; }
}

const IncomingMessage = require("http").IncomingMessage;

RequestHelpers.prototype.__proto__ = IncomingMessage.prototype;
IncomingMessage.__proto__ = RequestHelpers;
IncomingMessage.prototype = RequestHelpers.prototype;

While this (seems to) work and does exactly what I need it to do (Makes it as tho IncomingMessage extends my RequestHelpers, which then extends whatever IncomingMessage originally extended) there seems to be some weird issue, and I'm wondering if it is something that can be ignored.

If I now send a HTTP request who'se request handler looks like the following (I am using Polka, which is a wrapper around the native HTTP server) and access it theres no issues at all:

index(req, res) {
    res.end(JSON.stringify({ip: req.ip, foobar: req.foobar(), foobar2: req.foobar2}));
}

However, if I set a breakpoint at the res.end call and manually call any of my methods / access any of my getters in the console, I am being greeted with this message after resuming execution (Eventho they return the expected output):

(node:3348) [DEP0016] DeprecationWarning: 'GLOBAL' is deprecated, use 'global'

Just setting a breakpoint or inspecting the request object (While seeing my own methods in there) does not trigger the issue.

Iterating trough the object using Object.getPrototypeOf yields the following output. As expected, my class is added right in the beginning. Why it is that it is now being presented as IncomingMessage, I dont know.

Default:

IncomingMessage {_readableState: ReadableState, readable: true, _events: Object, _eventsCount: 1, _maxListeners: undefined, …}
Readable {setTimeout: , _read: , destroy: , _addHeaderLines: , _addHeaderLine: , …}
[...]

And with my hack:

IncomingMessage {_readableState: ReadableState, readable: true, _events: Object, _eventsCount: 1, _maxListeners: undefined, …}
IncomingMessage {constructor: , ip: <accessor>, foobar: , foobar2: <accessor>}
Readable {setTimeout: , _read: , destroy: , _addHeaderLines: , _addHeaderLine: , …}
[...]

Last off: Why am I even doing it like this? The idea is to have a zero performance impact way to add my methods into the original class. Obviously I could alternatively pollute the original prototype and write my methods directly into it, but, at least to me, this seems like a better solution.

If somebody has an idea whats going on here I'd appreciate some input.

Finding key in array

$
0
0

Take a look on "this.state.winners":

import React, { Component } from "react";

const playingPlayers = [
    {uid: 1, name: 'John'},
    {uid: 2, name: 'Emperor'},
    {uid: 3, name: 'King'}
];

class Queue extends Component {
    constructor(props) {
        super(props);
        this.state = {
          winners: this.props.winners // here is winner players
        }
    }
    addPlayer(player){
        return (
            <div>
                <li>{player.name}</li>
            </div>
        );
    }
    render(){
        return (
            <React.Fragment>
                {playingPlayers.map(player => this.addPlayer(player))}
            </React.Fragment>
        );
    }
}

export default Queue;

Example results:

John
Emperor
King

uid 2 and uid 3 is winner on my array (this.props.winners)

Now, for example, I would like to mark or highlight uid 2 and 3 in the list above.

For example, like this result:

John
Emperor (is winner)
King  (is winner)

How can i do ? how can mark this winners without rebuilding list ?

Also you can see my example in here:

https://stackblitz.com/edit/react-ab4nia?file=index.js

How to create Dynamic Header and footer for web pages in JS?

$
0
0

I am developing a website and there are many pages in the website, so I want the header and footer files dynamically calling to all the web pages.

I have written a script but it is not working. Please help.

Here is the script:

<!DOCTYPE html><html lang=""><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="description" content=""><meta name="author" content=""><title>BooksThread</title><link rel="shortcut icon" href=""><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap-theme.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><link rel="stylesheet" href="css/style.css"><script src="js/index.js"></script><!--book hover effect files--><link rel="stylesheet" type="text/css" href="css/book-hover/normalize.css" /><link rel="stylesheet" type="text/css" href="css/book-hover/demo.css" /><link rel="stylesheet" type="text/css" href="css/book-hover/component.css" /><script src="js/book-hover/modernizr.custom.js"></script><!--*------------font awesome---------------*--><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"><!--*******************google fonts**************************--><link href="https://fonts.googleapis.com/css?family=Domine" rel="stylesheet"><link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet"><!--***************************************************************-->


		**<script src="jquery-3.3.1.min.js"></script>**</head>
	**<script>
		$(function(){
			$("#header").load("header/footer/header.html");
			$("#header").load("header/footer/footer.html");
	});**</script><body>
	**<div id="header"></div>**<center><h1 style="color: black; padding: 10%;">Starter Template</h1></center>

	**<div id="footer"></div>**</body></html>

I have created a folder named HEADERFOOTER and in this folder, I have created 2 HTML files named header.html and footer.html

HEADER.HTML File

<!DOCTYPE html><html lang=""><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="description" content=""><meta name="author" content=""><title>BooksThread</title><link rel="shortcut icon" href=""><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap-theme.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><link rel="stylesheet" href="css/style.css"><script src="js/index.js"></script><!--book hover effect files--><link rel="stylesheet" type="text/css" href="css/book-hover/normalize.css" /><link rel="stylesheet" type="text/css" href="css/book-hover/demo.css" /><link rel="stylesheet" type="text/css" href="css/book-hover/component.css" /><script src="js/book-hover/modernizr.custom.js"></script><!--*------------font awesome---------------*--><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"><!--*******************google fonts**************************--><link href="https://fonts.googleapis.com/css?family=Domine" rel="stylesheet"><link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet"><!--***************************************************************--><!--[if IE]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script><![endif]--><!--mycode--><!----></head><body><!--nav bar--><nav class="navbar navbar-expand-lg fixed-top header navbar-light" style="background-color: #fff;"><a class="navbar-brand" href="index.html"><img src="img/Capture.JPG" alt="BOOKSthread" title="Books Thread" class="img-responsive" style="height: 70px; width: 210px;"></a><button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button><div class="collapse navbar-collapse" id="navbarSupportedContent"><ul class="navbar-nav mr-auto"><li class="nav-item active nav-heading"><a class="nav-link nav-head-color"  href="#" style="color: black;">Home <span class="sr-only">(current)</span></a></li><li class="nav-item nav-heading"><a class="nav-link" href="#" style="color: black;">How It Works</a></li><li class="nav-item dropdown nav-heading"><a class="nav-link dropdown-toggle" href="#"  data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: black;">
          Category<b class="caret"></b></a><ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"><li><a class="" href="#">Action</a></li><li><a class="" href="#">Another action</a></li><li><a class="" href="#">Something else here</a></li></ul></li><li class="nav-item nav-heading"><a class="nav-link" href="#" style="color: black;">New Arrivals</a></li><li class="nav-item nav-heading"><a class="nav-link" href="#" style="color: black;">Subscription Plan</a></li><li class="nav-item nav-heading"><a class="nav-link" href="#" style="color: black;">About Us</a></li></ul><form class="form-inline my-2 my-lg-0"><input class="form-control mr-sm-2" id="search" type="search" placeholder="Search" aria-label="Search" style="width:300px;"><button class="btn btn-outline-success my-2 my-xl-0" type="submit">Search</button></form><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><button type="button" class="btn btn-primary btn-sm">Login</button><span>&nbsp;&nbsp;&nbsp;</span><button type="button" class="btn btn-warning btn-sm">Signup</button></div></nav></body></html>

FOOTER.HTML File

<!DOCTYPE html><html lang=""><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="description" content=""><meta name="author" content=""><title>BooksThread</title><link rel="shortcut icon" href=""><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap-theme.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><link rel="stylesheet" href="css/style.css"><script src="js/index.js"></script><!--book hover effect files--><link rel="stylesheet" type="text/css" href="css/book-hover/normalize.css" /><link rel="stylesheet" type="text/css" href="css/book-hover/demo.css" /><link rel="stylesheet" type="text/css" href="css/book-hover/component.css" /><script src="js/book-hover/modernizr.custom.js"></script><!--*------------font awesome---------------*--><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"><!--*******************google fonts**************************--><link href="https://fonts.googleapis.com/css?family=Domine" rel="stylesheet"><link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet"><!--***************************************************************--><!--[if IE]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script><![endif]--><!--mycode--><!----></head><body><!-- Footer --><footer class="page-footer font-small blue-grey lighten-5 mt-4 footer"><!-- <div style="background-color: #fbc73b;"><div class="container"><!-- Grid row<div class="row py-4 d-flex align-items-center"><!-- Grid column<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0"><h6 class="mb-0">Get connected with us on social networks!</h6></div><!-- social networks list <div class="col-md-6 col-lg-7 text-center text-lg-right social-networks"><!-- Facebook <a href="#" class="facebook"><i class="fa fa-facebook"></i></a><!-- Google +<a href="#" class="google"><i class="fa fa-google"></i></a><!--youtube<a href="https://www.youtube.com/channel/UCAVLpSGz_chkNQGdcnJyJDA" class="google"><i class="fa fa-youtube"></i></a><!--Instagram<a href="https://www.youtube.com/channel/UCAVLpSGz_chkNQGdcnJyJDA" class="instagram"><i class="fa fa-instagram"></i></a></div><!-- Grid column</div><!-- Grid row-</div></div>--><!-- Footer Links --><div class="container text-center text-md-left mt-5"><!-- Grid row --><div class="row mt-3 dark-grey-text"><!-- Grid column --><div class="col-md-3 col-lg-4 col-xl-3 mb-4"><!-- Content --><div class="white"><h6 class="text-uppercase font-weight-bold">booksthread</h6><hr class="teal accent-3 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"><p>Choose the books you want to read, from the online catalogue and we deliver the physical copies of the books to your homes</p></div></div><!-- Grid column --><!-- Grid column --><div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4"><!-- Links --><h6 class="text-uppercase font-weight-bold white" style="color: white;">who we are</h6><hr class="teal accent-3 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"><p><a class="dark-grey-text none" href="#!" style="text-decoration: none;">About Us</a></p><p><a class="dark-grey-text none" href="#!" style="text-decoration: none;">Contact Us</a></p><p><a class="dark-grey-text none" href="#!" style="text-decoration: none;">Privacy Policy</a></p><p><a class="dark-grey-text none" href="#!" style="text-decoration: none;">Registeration</a></p></div><!-- Grid column --><!-- Grid column --><div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4"><!-- Links --><h6 class="text-uppercase font-weight-bold white" style="color: white;">Social Network</h6><p class="social-networks"><a href="#" class="facebook"><i class="fa fa-facebook"></i></a></p><p class="social-networks"><a href="#" class="google"><i class="fa fa-google"></i></a></p><p class="social-networks"><!--youtube --><a href="https://www.youtube.com/channel/UCAVLpSGz_chkNQGdcnJyJDA" class="google"><i class="fa fa-youtube"></i></a></p><p class="social-networks"><!--Instagram--><a href="https://www.youtube.com/channel/UCAVLpSGz_chkNQGdcnJyJDA" class="instagram"><i class="fa fa-instagram"></i></a></p></div><!-- Grid column --><div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4"><!-- Links --><h6 class="text-uppercase font-weight-bold white" style="color: white;">get in touch</h6><hr class="teal accent-3 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"><p><a class="dark-grey-text none" href="#!" style="text-decoration: none;">Lajpat Nagar, India</a></p><p><a class="dark-grey-text none" href="mailto:customercare@booksthread.com" style="text-decoration: none;">customercare@booksthread.com</a></p><p><a class="dark-grey-text none" href="#!" style="text-decoration: none;">011-41416816</a></p><p><a class="dark-grey-text none" href="#!" style="text-decoration: none;">FAQ</a></p></div><!-- Grid column --><!--<div class="col-md-4 col-lg-2 col-xl-2 mx-auto mb-4"><!-- Links<h6 class="text-uppercase font-weight-bold">Contact</h6><hr class="teal accent-3 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"><p><i class="fa fa-home mr-3"></i> New York, NY 10012, US</p><p><i class="fa fa-envelope mr-3"></i> info@example.com</p><p><i class="fa fa-phone mr-3"></i> + 01 234 567 88</p><p><i class="fa fa-print mr-3"></i> + 01 234 567 89</p></div>--><!-- Grid column --></div><!-- Grid row --></div><!-- Footer Links --><!-- Copyright --><div class="footer-copyright text-center text-black-50 py-3 white" style="color:white; background-color: #212121;"><center><a class="white" href="https://booksthread.com" style="text-decoration: none;">© 2018 Copyright: BOOKSthread</a></center></div><!-- Copyright --></footer><!-- Footer --><!----></body></html>

Please help to create the dynamic header and footer in across all the pages.

Thanks!!

{FIXED} I have 2 jS files. One contains a constructor, and the other calls it. VSCode recognizes it's a constructor, but it says it isn't defined/

$
0
0

Main jS file:

const canv = document.getElementById("canv");
const ctx = canv.getContext("2d");
canv.width = 500;
canv.height = canv.width;
let c = new Creature(0, 0, 10, 5, 2);
c.showStats();

Constructor file:

function Creature(x, y, speed, sight, energy) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.sight = sight;
    this.energy = energy;
    this.showStats = function () {
        console.log(this.x, this.y, this.speed, this.sight, this.energy);
    }
}

VSCode knows it's a constructor, and knows what arguments to take, but I still get a console error saying Uncaught ReferenceError: Creature is not defined.

How do I fix this?


making an HTML page for receiving and displaying items using Web Bluetooth

$
0
0

this HTML page has to run offline i want to use JS for that which can use chrome to open the web app i am new to web bluetooth and i haven't been able to find resources to help me read strings off my bluetooth device

i know i have to setup SPP on the host controller then send strings when host is paired to client but on the application side the i am not able to try any simple solution there are limited number of bluetooth devices which can be connected to arduino and be configured to SPP

Gatsby, Gsap - gsap animations not working after build

JS - submit more than one form with one button

$
0
0

I'm trying to submit more than 1 form and decided to do so with JS. (at least the subbmiting part) so i have this simple form:

<form action="test/submit.php" method="post" id="submit_template">
    <center>
        <input type="hidden" id="payment" name="DB_Table" value="payment">
            <div id="template" class="collapse.toggle">
                <input type="text" placeholder="Full Name" name="Full_Name">
                <input type="text" placeholder="Full Name" name="Full_Name">
            </div>
    </center>
</form>

I created a JS to change the ID for that form id - such as "submit_template1...2..." etc and the button looks like this:

<button id="submit" type="button" name="submit" value="submit" class="button=1" onclick="submitForms()">Submit</button>

i tried to create a JS for subbmitting all forms the code looks like this:

submitForms = function()
{
    for(i = 0 ; i < document.getElementsByTagName("form").length ; i++)
    {
        document.getElementById("submit_template" + i).submit();
    }
}

when i have more than 1 form it get the following error: Uncought TypeError: Cannot read property 'submit' of null at submitForms (:106) at HTMLButtonElement.onclick

funny thing is that if i go to the F12 console and do something like: var i = 1 document.getelementbyid("submit_template" + i).id

it works perfectly...

any ideas?

Thanks in Advance.

Java and typescript generate difference PBKDF2 hash

$
0
0

I want communicate between java and typescript with encrypted AES-GCM data (PBKDF2 hash used for password) .
I used random bytes for pbkdf2 :

randomBytes(Base64): wqzowTahVBaxuxcN8vKAEUBEo0wOfcg4e6u4M9tPDFk=   

This is my java PBKDF2 Code :

    private String salt = "1234";
    private static final String KEY_ALGORITHM = "AES";
    private Key generateKey(byte[] randomBytes) throws Exception {
        var randomPassword = new String(randomBytes);
        KeySpec keySpec = new PBEKeySpec(randomPassword.toCharArray(), salt.getBytes(), 10000, 256);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        var kdf2SecurePassword = secretKeyFactory.generateSecret(keySpec).getEncoded();
        return new SecretKeySpec(kdf2SecurePassword, KEY_ALGORITHM);
    }   

and this is typescript code :

  private static importKey(randomBytes: ArrayBuffer) {
    return crypto.subtle.importKey(
      'raw',
      randomBytes,
      {name: 'PBKDF2', length: 256},
      true,
      ['deriveKey']
    );
  }

  private generateAESKey(baseKey, salt) {
    const encSalt = new TextEncoder().encode(salt);
    const algorithm = {
      name: 'PBKDF2',
      hash: 'SHA-256',
      iterations: 10000,
      salt: encSalt
    };
    return crypto.subtle.deriveKey(
      algorithm,
      baseKey,
      {name: 'AES-GCM', length: 256},
      true,
      ['encrypt', 'decrypt']
    );
  }     

Result in java and typescript :

Java Key       : hrG2Hw/bec9JoI+EcemfUxR/5lGw718kYOcCWRRbulk=
typescript Key : EGPcTUQUmYpNHoCDuD7rkIVaHkPSqEZYan4HnWfhFSc=     

Why i have difference result ?
What part of code has wrong ?

UPDATE
Interesting, I try to generate pbkdf2 key with linux nettle-pbkdf2 command, result exactly match by javascript output :

USERNAME@HOSTNAME:~$ echo -n "wqzowTahVBaxuxcN8vKAEUBEo0wOfcg4e6u4M9tPDFk=" | base64 -d | nettle-pbkdf2 -i 10000 -l 32 --raw "1234"  | base64
EGPcTUQUmYpNHoCDuD7rkIVaHkPSqEZYan4HnWfhFSc=    

How to access DOM object of a web page using external JS file? [closed]

$
0
0

For Example : I want to insert data in google web page and press search button using my JS file. How can I achieve this? I am trying to write a form auto-filler for any web page.

Javascript echo for each an array while also converting from string to int

$
0
0

I have an array with two values, my goal is to take the roman numerals, convert them into integers, then outputting them one by one using for each. My issue is in my roman numeral function converter, I get the error Uncaught TypeError: str1.charAt is not a function on line 16 which is the code var num = char_to_int(str1.charAt(0));

var dynastyReign = [ 
  {"One Dynasty": "MXLI"},
  {"Two Dynasty": "MCCCIIII"},
  {"Three Dynasty": "MCCCXCVIII"},  
  {"Four Dynasty": "MCDXLV"},   
  {"Five Dynasty": "MDCLXIV"}, 
  {"Six Dynasty": "MCMXLIX"},
  {"Seven Dynasty": "MMMXICX"}
];

function roman_to_Int(str1) {
if(str1 == null) return -1;
var num = char_to_int(str1.charAt(0));
var pre, curr;

for(var i = 1; i < str1.length; i++){
curr = char_to_int(str1.charAt(i));
pre = char_to_int(str1.charAt(i-1));
if(curr <= pre){
num += curr;
} else {
num = num - pre*2 + curr;
}
}

return num;
}

function char_to_int(c){
switch (c){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return -1;
}
}

var year = dynastyReign.map(d => Object.values(d)[0]);

dynastyReign.forEach(function(year) {
document.write(roman_to_Int(year));
});

How I made my code is first, to create a converter function from roman numbers to int, declare a variable to only get the roman number portion of the array (var year), then using for each to output the integer along with the converter roman_to_Int(year). I am not sure which part should i fix, any help would be appreciated.

Object method returns NaN

$
0
0

I'm trying to learn how the this keyword works from a tutorial, and got an unexpected output. I've an Object that has two methods. One changes the value of the object's properties and the other is for the summary.

The problem is when I tried to Objects method, it gives me a NaN value instead of the actual value I passed as parameter. I don't know where the problem is. I had gone through this question's answer, but it really doesn't solved my problem.

This is my Code:

let myObject = {
  day: 'Monday',
  mettings: 0,
  meetdone: 0,
  addMeeting: function(num) {
    this.meetings = this.meetings + num

  },
  summary: function() {
    return `you have ${this.meetings} number of meetings.`
  }

}
myObject.addMeeting(4)
console.log(myObject.summary());

Issues running my React Application with Webpack

$
0
0

This code is my webpack.config.js file.

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: "./src/index.js",
    output: {
        path: path.join(__dirname, "./dist"),
        publicPath: '/dist/',
        filename: "index_bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                },
            },
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader"]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html"
        })
    ],
    devServer: {
        publicPath: '/dist/'
    }
};

I'

Attached is my error message.

I've tried reinstalling some packages and modifying this config file from the starterkit but to no avail.

Thanks in advance!

ejs and express public and private route's view pages

$
0
0

Recently I am creating a website using express and ejs, so other than express and ejs, I will also have one css and one javascript file on the frontend, the site I am creating will have a dashboard which the user has to login first to see and use the dashboard so overall my site will have few public routes and two or three private routes(which user has to login to interact with).

My question is not on performance point of view but on security point of view:

For my frontend javascript file do I need to split into two files so one js file is for all the public routes pages and another one is for all private routes pages? if I just use one client side js file for both public and private routes view pages is there going to be any kind of security issues? because if I am only using one client side js file, I will also using that js file to manipulate different kind of DOM element in private routes(for example dashboard.ejs) too.

Example:

If I have two public route, index.ejs and about.ejs, when user visit those public route the server will send public.js to the client side, like this:

<body>
  <div class="container">
    <h1>index page</h1>
  <div>
  <script src="./public.js"></script> //This js file is used for all PUBLIC routes view pages
</body>
<body>
  <div class="container">
    <h1>about page</h1>
  <div>
  <script src="./public.js"></script> //This js file is used for all PUBLIC routes view pages
</body>

and after user login and gain access to the private route view page which for example is dashboard.ejs, the server will send private.js to the client side, like this:

<body>
  <div class="container">
    <h1>dashboard page</h1>
  <div>
  <script src="./private.js"></script> //This js file is used for all PRIVATE routes view pages
</body>

Is there a need to use above way to avoid any kind of security issues or I can just use one client side js file to take care of all public and private routes view pages DOM manipulation etc...?

sorry if this question is kind of... I am still new to web development.

Thanks

Mapping to a function in React

$
0
0

I am relatively new to react and I am trying to map a list of locations to the google maps API. I cant figure out how to pass each argument to the function for the google API. Any help would be great. Thanks in advance.

export class Mapping extends React.Component {

  state = {
    zoom: 1,
  }

  render() {

    Geocode.fromAddress("Eiffel Tower").then(
      response => {
        const { lat, lng } = response.results[0].geometry.location;
        console.log(lat, lng);
      },
      error => {
        console.error(error);
      }
    );

    return (
      <div>
      <Map className="Map" center={[47, -29]} zoom={this.state.zoom}>
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
        />
        {this.fromAddress}
        {data.features.map((loc, i) => 
          <Marker key={i} position={[
            loc.geometry.coordinates[0],
            loc.geometry.coordinates[1]
          ]}/>
          )}
      </Map>
    </div>
    )
  }
} 

export default Mapping;

Upload multiple images in a angular and firebase project, It is not working in sequence

$
0
0
  async onSubmit(formValue) {
    this.isSubmitted = true;
    if(this.selectedImageArray.length > 0) {  // 4 images in this array
      for (let index = 0; index < this.selectedImageArray.length; index++) {  // Loop through this image array
          await new Promise(resolve => {
              setTimeout(()=> {
                  console.log('This is iteration ' + index); 
                  var filePath = `images/tours/${this.selectedImageArray[index].name.split('.').slice(0,-1).join('.')}_${new Date().  getTime()}`;
                  const fileRef = this.storage.ref(filePath);
                  this.storage.upload(filePath, this.selectedImageArray[index]).snapshotChanges().pipe(
                    finalize(() => {
                      fileRef.getDownloadURL().subscribe((url) => {
                        formValue[`imageUrl${index+1}`] = url;
                        console.log(url);
                      });
                    })  
                  ).subscribe()
                  resolve();
              }, 3000);
          });
      }
      console.log('After loop execution');
      // this.value(formValue);
    }
  }

After submitting the code it will download and print 3 urls and then it print 'after loop execution' then it print 4th one I don't understand why. See here in console

İmage

see in the image line no of code execution. What I want to execute code in sequence after all images download then after it will go out of loop.

How to detect current elements in viewport while user scrolls with optimal performance?

$
0
0

What I have is a div that contains about 30 cards. What I want to achieve is: every time the user scrolls I will retrieve the cards in the current viewport and consider them as "visited". So for example, after the first scroll, the current cards in the viewport are cards with id = 1,2,3,4 and I will mark them as visited after the first scroll. How can I achieve that with optimal performance?

<div class="search-results">
   <div class="search-card" id="card-1"></div>
   <div class="search-card" id="card-2"></div>
   <!-- 30 elements with class = "search-card" -->
</div>
Viewing all 138134 articles
Browse latest View live


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