Best way to visualize JavaScript objects hierarchy? [closed]

I’m learning JavaScript and exploring objects and prototype based nature of it.

I need help with the a tool that can help me visualize objects and their prototypes and constructors. So which object ‘inherits’ from which object through the prototype chain.

Something that would list all the properties and methods of an object, with its prototype objects and theirs properties and objects…

I’m using VS Code now and built in Debugger, is there some better extension for VS Code or some other code that would visualize objects and their prototypes better?

Thanks!

Vue & JavaScript error. Помогите пожалуйста [closed]

Прошу помощи, в vue новый. Скачал скрипт админ панели
И нужно в vue view подключить в шаблоне JS файлы админской панели

Делаю так:

<script>
      import Apex from "apexcharts";
      import jQuery from "jquery";

      import '../../assets/js/app.min'

      import '../../assets/js/pages/demo.dashboard.js'


export default {
    name: "Index",
   // components: {AdminDashboardLayout},
    data: function () {
        return {}
    },
}

и в файле App.min содержится код, и начинается он так

!function (i) {
"use strict";

function t() {
    this.body = i("body"), this.window = i(window), this.menuContainer = i("#leftside-menu-container")
}
....

И Проблема в том, что когда я запускаю обычный файл панели, без vue, то все js отлично работают,
но у меня всё идет плохо и при запуске даёт ошибку enter image description here

И по моему проблема в неверном подключении файлов js, но подключить их так же как в файле без vue я не могу, потому что в template нельзя подключать через script tag. Я пробовал разные своеобразные методы что то в роде
document.head.addChild… и тут был тег скрипт , но vue не дал мне этого сделать

Мучаюсь уже второй день, помогите пожалуйста

setting an action from an event-listener on a separate HTML page (setting dropdown value from a click event on a separate HTML page)

I have a website with a 2 html pages. On the landing page, I have bootstraps “cards” which are basically acting like buttons. If you click on one, it’ll link you to the second page.

Here’s one of the clickable “cards”:

<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" id="arrest-data">
    <div class="box-part text-center"> <i class="fa-solid fa-3x fa-handcuffs" aria-hidden="true"></i>
        <div class="title">
            <h3>Data Examples 1</h3>
        </div>
   <div class="text"> <span>Crime data and other crime statistics</span> </div> <a href="#" class="get-data">GET DATA</a>
</div>

On a separate page, I have a filterable table, with dropdowns to filter different categories:

<div class="container">
<div class="row dropdowns">
  <div class="col-4">
    <select id="categoryDropdown">
      <option value="All">All Topics</option>
      <option value="Category: Arrest Data">Arrest Data</option>
      <option value="Category: Use of Force">Use of Force</option>
      <option value="Category: Human Trafficking">Human Trafficking</option>
      <option value="Category: Treatment and Diversion">Treatment and Diversion</option>
      <option value="Category: Drug and Overdose Data">Drug and Overdose Data</option>
    </select>
  </div>
  <div class="col-4">
    <select id="formatDropdown">
      <option value="All">All Formats</option>
      <option value="Format: Dashboard">Dashboard</option>
      <option value="Format: PDF">PDF</option>
      <option value="Format: Data Story">Data Story</option>
      <option value="Format: CSV">CSV</option>
    </select>
  </div>
  <div class="col-4">
    <select id="associateStatusDropdown">
      <option value="All"> All Users </option>
      <option value="Yes">Active Users</option>
      <option value="No">Inactive Users</option>
    </select>
  </div>
</div>
<table class="table">
  <thead>
    <tr>
      <th> SL.NO </th>
      <th> Data </th>
    </tr>
  </thead>
  <tbody id="download-forms-table-tbody">
    <tr>
      <td> 1 </td>
      <td> 
        <div class="project-title">
        Criminal Arrest Data
        </div>
        <div class="project-description">
            <p>Example Arrest Data blah blah.</p>
        </div>
        <div class="project-category">
            <b>Category</b>: Arrest Data
        </div>
        <div class="project-format">
            <b>Format</b>: Dashboard
        </div>
        <div class="project-last-update">
            <b>Last Updated</b>: 5/16/2022
        </div>
        <div class="project-associated-data">
            <b>Associated Data</b>: 5/16/2022
        </div>
      </td>
    </tr>
     <tr>
      <td> 2 </td>
      <td> 
        <div class="project-title">
        Demographics of Arrest Data
        </div>
        <div class="project-description">
            <p>Example Arrest Data Demographics blah blah.</p>
        </div>
        <div class="project-category">
            <b>Category</b>: Arrest Data
        </div>
        <div class="project-format">
            <b>Format</b>: PDF
        </div>
        <div class="project-last-update">
            <b>Last Updated</b>: 5/16/2022
        </div>
        <div class="project-associated-data">
            <b>Associated Data</b>: 5/16/2022
        </div>
      </td>
    </tr>
   <tr>
      <td> 3 </td>
      <td> 
        <div class="project-title">
        Drug Data
        </div>
        <div class="project-description">
            <p>Example Drug Data blah blah.</p>
        </div>
        <div class="project-category">
            <b>Category</b>: Drug Data
        </div>
        <div class="project-format">
            <b>Format</b>: PDF
        </div>
        <div class="project-last-update">
            <b>Last Updated</b>: 5/16/2022
        </div>
        <div class="project-associated-data">
            <b>Associated Data</b>: 5/16/2022
        </div>
      </td>
    </tr>
  </tbody>
</table>

And here’s my javascript for filtering the table using the dropdowns:

$('.container').on("change", 'select', function() {
    console.log("changin")
  var category = $('#categoryDropdown').val().toLowerCase(),
    format = $('#formatDropdown').val().toLowerCase(),
    associate = $('#associateStatusDropdown').val().toLowerCase();

  var table = $("#download-forms-table-tbody");
  var trs = table.find('tr');
  trs.hide();

  var filtered = trs.filter(function(index, elem) {
    var tds_category = $(elem).find('td > div:nth-of-type(3)'); //get the category
    var tds_format = $(elem).find('td > div:nth-of-type(4)'); //get the format
    var all_tds = $(elem).find('td'); //get all td
    //console.log(tds.text())
    console.log(tds_format.text())
    //console.log(tds.eq(1).innerHTML)
    if (category !== "all" && tds_category.text().trim().toLowerCase() !== category) {
      return false;
    }
    if (format !== "all" && tds_format.text().trim().toLowerCase() !== format) {
      return false;
    }
    if (associate !== "all" && all_tds.eq(3).text().trim().toLowerCase() !== associate) {
      return false;
    }
    return true;
  })

  filtered.show();

  if (filtered.length == 0) {
    alert("No Records Found!!!");
  }

});

When the user clicks on a card on the first HTML page, I want that event to set the dropdown filter to a certain value. In this example, when the user clicks on the card, I want the dropdown to be set to value="Category: Arrest Data".

I’ve tried:

$('#arrest-data').click(function(){
    $('#categoryDropdown').val('Category: Arrest Data');
})

But no luck.

Can anyone help me with what is best practice for having an event listener on one HTML page do an action on a different HTML page, like in this scenario?

Thanks!

Accessing a class by proxing a function called by its constructor

I’m writing a short game hacking project. As such, I need a way to retrieve a class that is wrapped in an anonymous function without any global references. The simplified class layout looks like this:

class n {
  constructor() {
    this.test = localStorage.getItem("test");
  }
}

My approach is to proxy the localStorage.getItem function called inside the constructor.
The issue appears when I access the caller: it returns null. My code is as following:

class n {
  constructor() {
    this.test = localStorage.getItem("test");
  }
}

localStorage.getItem = new Proxy(localStorage.getItem, {
  apply: function(target, that, args) {
    console.log(arguments.callee.caller);
  }
})

const l = new n();

Reassigning a global variable within a function without passing variable name – JavaScript [closed]

I want to reassign a global variable within a function but use a parameter’s value instead of passing the global variable’s name.

Well, as if directly calling the name, the following code works fine:

let us = {
    Alabama: ["Alexander City", "Andalusia", "Anniston", "Athens"],
};
function addCity(country = us, stateName, inputCity) {
    country[stateName] = [...country[stateName], inputCity];
}

addCity(us, "Alabama", "New City");

But, I want to make the function reproducible to add the ability to use it for the other objects(here countries) without having to change the body of the function for every new country.

I’ve read other topics but they do not provide any answer for this question they instead clarify how things work.

With redux form how can I normalize and allow only positive integers on an input type number?

I am on 8.3.7 version of redux-form, I am using the Field which should be allowed to accept ONLY positive integers between the range 0-9999.

const REGEX_SPECIAL_CHARACTERS = /[@-_!#$%.&]/;

<Field
    mandatory
    step={1}
    name="fieldName"
    type="number"
    min={0}
    max={9999}
    normalize={(value) => {
        console.log({value});
        return value?.split(REGEX_SPECIAL_CHARACTERS, 1).join('');
    }}
>
    Text
</Field>

I am using the normalize prop to validate this. If I enter 1.9, on blur it will set 1 which is ok. If I do -0 or -1 or just -n (n = any number) it just removes the entire value leaving an empty field and I need it to be ALWAYS 0 if there is whatever value going less than 0.

I do not know if maybe using the format prop but IDK how to use it => https://redux-form.com/8.3.0/docs/api/field.md/#-code-format-value-name-gt-formattedvalue-code-optional-

So any ideas on how I can fix this?

Why React defaultProps isn’t getting values

import { memo } from 'react';
import classNames from 'classnames/bind';
import styles from './Button.module.scss';

const cn = classNames.bind(styles);

const Button = memo(
  ({ design: { size, color, outline, hover }, content, type, onClick }) => (
    <button
      type={type}
      className={cn('button', size, color, { outline }, { hover })}
      onClick={onClick}
    >
      {content}
    </button>
  )
);

Button.defaultProps = {
  size: 'md',
  color: 'black',
};

export default Button;

defaultProps doesn’t work in this case. If I set default value when destructuring props like

{ design: { size='md', color='black', outline, hover }, content, type, onClick }, it works.

I passed the props like

            <Button
              design={{ size: 'sm', outline: true }}
              content="Edit"
              onClick={onEditClick}
            />

What’s wrong here?

Why do It needs parentheses around arrow function regardingless the eslint configuration rules?

I set up the .eslintrc.json file in my react project as follow.

{
"env": {
    "browser": true,
    "commonjs": true,
    "es2021": true,
    "node": true,
    "jest": true
  },
  "extends": [
    "airbnb-base",
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module",
    "ecmaVersion": "latest"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "react/display-name": [
      "off"
    ],
    "no-console": [
      "warn",
      {
        "allow": [
          "clear",
          "infor",
          "error",
          "dir",
          "trace"
        ]
      }
    ],
    "no-useless-return": "error",
    "linebreak-style": [
      "error",
      "unix"
    ],
    "quotes": [
      "error",
      "single"
    ],
    "indent": [
      "error",
      2
    ],
    "semi": [
      "error",
      "always"
    ],
    "arrow-parens": ["error", "as-needed"],
    "comma-dangle": [
      "error",
      "never"
    ]
  }
}

But I run my application and then get below error from eslint.

This stands like a syntax error.

Please help me with how do I have to change my eslint rule or code base.

I was referred from this link.

Javascript remove the first line of a string just before the line break

I have a variable that contains a string with lots of line breaks.

myvariable = '
1234556788,3434343434n
1244556788,7234343834n
1234556788,4434343434n
1234556784,8434343434n
1234556782,9444343434n
';

I need some way of removing just the first one without leaving a blank first line if possible.

So that this:

1234556788,3434343434n
1244556788,7234343834n
1234556788,4434343434n
1234556784,8434343434n
1234556782,9444343434n

turns into this:

1244556788,7234343834n
1234556788,4434343434n
1234556784,8434343434n
1234556782,9444343434n

So it would remove the first line after the n

How can I do this?

How to iterate over the result of strapi.db.query?

I have a simple findMany query in my controller:

const appointments = strapi.db.query("api::appointment.appointment").findMany({
    select: ["date", "startTime", "endTime"],
    where: {
        mentorId: mentorId,
        status: [1, 2, 4]
    }
});

It returns the following, such structure made me think that the result returned is iterable.

[
    {
        "date":"2022-04-27",
        "startTime":"08:00:00.000",
        "endTime":"10:00:00.000"
    },
    {
        "date":"2022-04-27",
        "startTime":"10:00:00.000",
        "endTime":"12:00:00.000"
    }
]

However, when I use a for loop, I can tell that it didn’t even enter since there’s no output.

for (let appointment in appointments)
    console.log("I entered");

When I used foreach, I got error: appointments.foreach is not a function.

appointments.foreach(function(appointment) {
    console.log(appointment.date);
});

So, I then checked if it is iterable using Symbol.iterator in Object(appointments), but it returns false. Array.isArray(appointments) also returns false which is weird, because the result definitely looked like an array to me.

Is there any workaround for this? I need to loop through each object, and access its fields.

Undefined variable $rs in C:xampphtdocstourismbook_form.php on line 43 0 I GOT THIS ERROR?

I WANT TO CLACULATE PER PERSON PRICE WHILE USER ENTERED THE NUMBER OF THE PERSON THEN THE AMOUNT IS AUTO CALCULATED.

THE COST IS DATABASE COLUMN AND I WANT TO ACCESS THAT COLUMN BUT I DONT KHOW WHAT IS THE ISSUE WHEN I DEFINE THE VARIABLE SHOW THE DATATYE ERROR.

BUT I FOUND THIS ERROR :Undefined variable $rs in C:xampphtdocstourismbook_form.php on line 43
0

HERE IS THE CODE

book_form.php

<?php 
if(isset($_GET['id'])){
    $packages = $conn->query("SELECT * FROM `packages` where md5(id) = '{$_GET['id']}',
        md5(cost)='{$_POST['cost']}'");
    if($packages->num_rows > 0){
       
        foreach($packages->fetch_assoc() as $k => $v){
            $k = $v;
            global $cost;
            $rs=print_r($row['Number_guest']*$row['cost']);
        }
        }       
    }
?>
   


 
<div class="container-fluid">
    <form action="#" id="book-form">
        <div class="form-group">
            <input name="package_id" type="hidden" value="<?php echo $_GET['package_id'] ?>" >

            <input name="cost" type="hidden" value="<?php echo $_GET['cost'] ?>" >

            <b>Check in Date</b> <input type="date"class="form form-control" name="Check_in_date" 
            id="checkin" required="ture"/>

            <b>Check out Date </b><input type="date"class="form form-control" name="Check_out_date" id="checkout" required="ture" />

            <b>MobileNumber</b><input type="tel"class="form form-control" name="MobileNumber" pattern="[1-9]{1}[0-9]{9}" title="error message" id="mobil.no" required="ture" />

            <b>Email </b><input type="email" class="form form-control" name="Email" id="email" required="" />

            <!--new code-->

            
            <b>Number of Persons</b><input type="hidden" name="Number_guest" value="<?php echo $row['Number_guest'];?>"/>
                <input type="number" required tile="Number of Person" max="500" min="0" 
                name="Number_guest" class="form-control" value="1" style="text-align:center" id="Number of Guest"/>
                <input type="hidden" name="payment" id="price" 
                value="<?php echo number_format($cost) ?>"/>
               
            
            <br>

                  <span class="rounded-0 btn-flat btn-sm btn-primary d-flex align-items-center justify-content-between"><i class="fa fa-tag"></i> <span class="ml-1">
                  <?php echo number_format($rs) ?></span></span>
                        
            <!--<b>Number of Persons</b> <input type="number" class="form form-control" name=
            "Number_guest" id="no.person" required="ture" />style="font-weight:bold;font-size:18px
            <b>Ammount To Be Pay </b> <input type="text" class="form form-control" name="payment"
            value=">">-->

            <input type="submit" name="save" id="save" value="Save" class="form form-control" font-color="fff"/>

        </div>
    </form>
</div> 
<script>


    $(function(){
        
        $('#book-form').submit(function(e){
            e.preventDefault();
            start_loader()
            $.ajax({
                url:_base_url_+"classes/Master.php?f=book_tour",
                method:"POST",
                data:$(this).serialize(),
                dataType:"json",
                error:err=>{
                    console.log(err)
                    alert_toast("an error occured",'error')
                    end_loader()
                },
                success:function(resp){
                    if(typeof resp == 'object' && resp.status == 'success'){
                        alert_toast("Book Request Successfully sent.")
                        $('.modal').modal('hide')
                    }else{
                        console.log(resp)
                        alert_toast("an error occured",'error')
                    }
                    end_loader()
                }
            })
        })
    })
</script>

What is the use of the method: public boolean equals(Object otherObject)

currently we are in a lesson about Java Generics.

I am currently working on two (2) examples/java classes given by the prof. We were instructed to test out and study the program and I can’t seem to understand or read the code block below in “simple english”

public boolean equals(Object otherObject) {
    if (otherObject == null) {
        return false;
    } else if (getClass() != otherObject.getClass()) {
        return false;
    } else {
        Pair<T> otherPair = (Pair<T>) otherObject;
        return (first.equals(otherPair.first) && second.equals(otherPair.second));
    }

}

I’ve looked around the internet and found some useful information but I can only tell that the method above is used to check if the field values are the same.

Link where I read about it: https://ecs.wgtn.ac.nz/foswiki/pub/Courses/COMP103_2018T2/Schedule/week4-4up.pdf

The program extracts two inputs of Data Type String , the user must guess the two secret words correctly, in the case of getting the correct answer, the program will let the user know about their answers.

Here’s the two classes (Class Definition With Type Parameter) with the class that has the main method:

GenericPairDemo Class:

import java.util.Scanner;

public class GenericPairDemo {

    public static void main (String []args){

        Pair<String> secretPair = new Pair<>("Happy", "Day");


        Scanner kbd = new Scanner(System.in);


        System.out.println("Enter two words:");
        String word1 = kbd.next();
        String word2 = kbd.next();

        Pair<String> inputPair = new Pair<String>(word1, word2);

        if (inputPair.equals(secretPair)){
            System.out.println("You guessed the secret words");
            System.out.println("in the correct order!");
        } else {

            System.out.println("You guessed incorrectly");
            System.out.println("You guessed: ");
            System.out.println(inputPair);
            System.out.println("The secret words are: ");
            System.out.println(secretPair);

        }

    } // end of main
}

Pair Class:

public class Pair <T> {

    private T first;
    private T second;


    // constructor
    public Pair(T firstItem, T secondItem){
        this.first = firstItem;
        this.second = secondItem;
    }


    // getters and setters
    public T getFirst() {
        return first;
    }

    public T getSecond() {
        return second;
    }

    public void setFirst(T first) {
        this.first = first;
    }

    public void setSecond(T second) {
        this.second = second;
    }

    // printing
    public String toString(){
        return ("First: " + first.toString() + "n" + "Second: " + second.toString());
    }


    public boolean equals(Object otherObject) {
        if (otherObject == null) {
            return false;
        } else if (getClass() != otherObject.getClass()) {
            return false;
        } else {
            Pair<T> otherPair = (Pair<T>) otherObject;
            return (first.equals(otherPair.first) && second.equals(otherPair.second));
        }

    }


}

Would also appreciate if someone could explain how the else statement works:

} else {
            Pair<T> otherPair = (Pair<T>) otherObject;
            return (first.equals(otherPair.first) && second.equals(otherPair.second));
        }

GPU Memory in Chrome Task Manager: GPU Process vs. Tab

While trying to debug a GPU memory leak in my Three.js app, i’m confused which value for the ‘GPU Memory’ column is relevant for my app:

The GPU Memory eaten by the GPU Process or the GPU Memory eaten by the tab, where my app is loaded?

Some cleaning up in my Three.js code definitely decreased the GPU Memory footprint of my tab in the Task Manager, but i suspect having another leak, which only impacts the footprint of the GPU process.

The relevant rows of my Chrome Task Manager