Can I simplify this code to avoid the type error for reading properties?

I am writing this code to scrape a webpage. I need to get specific information from the website and there is a lot of information needed to be scraped.

The code that I write works but when do it repeatedly it encounters error on some of the line, e.g. line 20, line 24.

Below is the code

const browser = await puppeteer.launch()
const page = await browser.newPage();

await page.goto("https://startupjobs.asia/job/search?q=&job-list-dpl-page=1", {timeout: 3000000})

const b = (await page.$x("/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[1]/div/div[1]/div/h5/a"))[0]
b.click()

//const elm = await page.$('//*[@id="suj-single-jobdetail-wrapper"]/div[1]/div[1]/h5');
//const text = await page.evaluate(elm => elm.textContent, elm[0]);

const [el1] = await page.$x('//*[@id="suj-single-jobdetail-wrapper"]/div[1]/div[1]/h5');
const job_name = await (await el1.getProperty('textContent')).jsonValue();

const [el2] = await page.$x('//*[@id="suj-single-jobdetail-wrapper"]/div[1]/div[2]/div/h6[1]/a');
const company = await (await el2.getProperty('textContent')).jsonValue();

const [el3] = await page.$x('/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[3]/p');
const job_type= await (await el3.getProperty('textContent')).jsonValue();

const [el4] = await page.$x('/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/p');
const salary = await (await el4.getProperty('textContent')).jsonValue();

const [el5] = await page.$x('/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[4]/p');
const skills = await (await el5.getProperty('textContent')).jsonValue();

There are like 13 data I need to scrape.

The error that I got is

const salary = await (await el4.getProperty(‘textContent’)).jsonValue();
TypeError: Cannot read properties of undefined (reading ‘getProperty’)

Getting all possible k-length strings from given list of characters using generator

I want to get all k-length strings from given list of characters. I already wrote recursive function and it works well. But my generator version doesn’t work at all. How can I fix my second function? Many thanks.

// recursive version
function product_rec(arr, k, result) {
    if (k == 1) return arr;
    let res = [];
    for (const elem of arr) {
        for (const s of product_rec(arr, k - 1)) {
            res.push(elem + s);
        }
    }
    return res;
}

var p = product_rec(['0', '1'], 2);
console.log(p);  // [ '00', '01', '10', '11' ]


// RangeError: Maximum call stack size exceeded
function* product_rec_gen(arr, k, result) {
    if (k == 1) {
        for (const elem of arr) yield elem;
    }
    for (const elem of arr) {  
        for (const s of product_rec_gen(arr, k - 1)) {
            yield elem + s;
        }
    }
}

var p = product_rec_gen(['0', '1'], 2);
console.log(p);  // RangeError: Maximum call stack size exceeded 

Using Svelte, Fable and Tauri

I’m creating a Tauri app that uses Fable to compile F# to JS. And I want to use Svelte with it, too. So far, I have compiled my F# file to a .js file. I’ve created a .svelte file with the following contents (named App.svelte)

<script>
    import './App.fs.js'
</script>

<main>
    <p>{msg}</p>
</main>
<style></style>

My index.html:

<body>
    <script src="main.mjs"></script>
</body>

And my main.mjs:

import App from './App.svelte';

const app = new App({
    target: document.body,
    props: {
        name: 'world'
    }
});

export default app;

I run the program with npm run build. This compiles my F# files and they become ready.
I run npm run tauri build -- --debug to compile my whole Tauri app and open it.

I do this, and nothing shows on screen. But when I look at the console, it says main.mjs
cannot import.

Supposedly, I need to compile the Svelte files. But Svelte uses rollup and I think I need to use webpack to be compatible with Fable or Tauri.

All these files are in project/src.

I need to compile and use a Svelte file in an index.html

Dynamic Multiple Calculate Average JQuery

hello here I want to get the average value of the NA field to be displayed in the NPF field, but the divisor of the average value is the number of NA columns that are filled so that the divisor value will continue to grow and be used as a division in the second row and so on, can anyone helped me thanks, here is the html and javascript code with reference from dynamic forms multiple input fields calculate

$(document).ready(function() {
      var i = 0;
      $("#kd1ns-" + i).change(function() {
        upd_art(i)
      });
      $("#kd1r-" + i).change(function() {
        upd_art(i)
      });
      $("#kd2ns-" + i).change(function() {
        upd_art(i)
      });
      $("#kd2r-" + i).change(function() {
        upd_art(i)
      });
      $("#kd3ns-" + i).change(function() {
        upd_art(i)
      });
      $("#kd3r-" + i).change(function() {
        upd_art(i)
      });
      $("#kd4ns-" + i).change(function() {
        upd_art(i)
      });
      $("#kd4r-" + i).change(function() {
        upd_art(i)
      });
      $("#kd5ns-" + i).change(function() {
        upd_art(i)
      });
      $("#kd5r-" + i).change(function() {
        upd_art(i)
      });
      $("#kd6ns-" + i).change(function() {
        upd_art(i)
      });
      $("#kd6r-" + i).change(function() {
        upd_art(i)
      });

      $('#add').click(function() {
          i++;
          valid_labels = 0;
          $('#articles').append(
          '<tr id="row' + i + '"><td><input type="number" id="kd1r-' + i + '" name="kd1r[]" placeholder="kd1r" class="form-control name_list" /></td><td><input type="number" id="kd1ns-' + i + '" name="kd1ns[]" placeholder="kd1ns" class="form-control name_list" /></td><td><input type="number" id="kd1-' + i + '" name="kd1[]" placeholder="kd1" class="form-control kd" /></td><td><input type="number" id="kd2r-' + i + '" name="kd2r[]" placeholder="kd2r" class="form-control name_list" /></td><td><input type="number" id="kd2ns-' + i + '" name="kd2ns[]" placeholder="kd2ns" class="form-control name_list" /></td><td><input type="number" id="kd2-' + i + '" name="kd2[]" placeholder="kd2" class="form-control kd" /></td><td><input type="number" id="kd3r-' + i + '" name="kd3r[]" placeholder="kd3r" class="form-control name_list" /></td><td><input type="number" id="kd3ns-' + i + '" name="kd3ns[]" placeholder="kd3ns" class="form-control name_list" /></td><td><input type="number" id="kd3-' + i + '" name="kd3[]" placeholder="kd3" class="form-control kd" /></td><td><input type="number" id="kd4r-' + i + '" name="kd4r[]" placeholder="kd4r" class="form-control name_list" /></td><td><input type="number" id="kd4ns-' + i + '" name="kd4ns[]" placeholder="kd4ns" class="form-control name_list" /></td><td><input type="number" id="kd4-' + i + '" name="kd4[]" placeholder="kd4" class="form-control kd" /></td><td><input type="number" id="kd5r-' + i + '" name="kd5r[]" placeholder="kd5r" class="form-control name_list" /></td><td><input type="number" id="kd5ns-' + i + '" name="kd5ns[]" placeholder="kd5ns" class="form-control name_list" /></td><td><input type="number"id="kd5-' + i + '" name="kd5[]" placeholder="kd5" class="form-control kd" /></td><td><input type="number" id="kd6r-' + i + '" name="kd6r[]" placeholder="kd6r" class="form-control name_list" /></td><td><input type="number" id="kd6ns-' + i + '" name="kd6ns[]" placeholder="kd6ns" class="form-control name_list" /></td><td><input type="number" id="kd6-' + i + '" name="kd6[]" placeholder="kd6" class="form-control kd" /></td><td><input type="number" id="uts-' + i + '" name="uts[]" placeholder="total" class="form-control name_list" readonly /></td> <td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');

          $("#kd1r-" + i).change(function() {
            upd_art(i)
          });
          $("#kd1ns-" + i).change(function() {
            upd_art(i)
          });
          $("#kd2r-" + i).change(function() {
            upd_art(i)
          });
          $("#kd2ns-" + i).change(function() {
            upd_art(i)
          });
          $("#kd3r-" + i).change(function() {
            upd_art(i)
          });
          $("#kd3ns-" + i).change(function() {
            upd_art(i)
          });
          $("#kd4r-" + i).change(function() {
            upd_art(i)
          });
          $("#kd4ns-" + i).change(function() {
            upd_art(i)
          });
          $("#kd5r-" + i).change(function() {
            upd_art(i)
          });
          $("#kd5ns-" + i).change(function() {
            upd_art(i)
          });
          $("#kd6r-" + i).change(function() {
            upd_art(i)
          });
          $("#kd6ns-" + i).change(function() {
            upd_art(i)
          });
      });

      $(document).on('click', '.btn_remove', function() {
        var button_id = $(this).attr("id");
        $('#row' + button_id + '').remove();
      });

  $('#submit').click(function() {
    alert($('#add_name').serialize()); //alerts all values           
    $.ajax({
      url: "wwwdb.php",
      method: "POST",
      data: $('#add_name').serialize(),
      success: function(data) {
        $('#add_name')[0].reset();
      }
    });
  });

  function upd_art(i) {
    var kd1ns = $('#kd1ns-' + i).val();     
    var kd1r = $('#kd1r-' + i).val(); 
    var kd2ns = $('#kd2ns-' + i).val();     
    var kd2r = $('#kd2r-' + i).val();
    var kd3ns = $('#kd3ns-' + i).val();     
    var kd3r = $('#kd3r-' + i).val();
    var kd4ns = $('#kd4ns-' + i).val();     
    var kd4r = $('#kd4r-' + i).val();
    var kd5ns = $('#kd5ns-' + i).val();     
    var kd5r = $('#kd5r-' + i).val();
    var kd6ns = $('#kd6ns-' + i).val();     
    var kd6r = $('#kd6r-' + i).val();
    var kd1 = Math.max(kd1ns,kd1r);
    $('#kd1-' + i).val(kd1);
    console.log("NS",kd1ns)
    console.log("R",kd1r)    
    console.log("KD1NA",kd1)

    var kd2 = Math.max(kd2ns,kd2r);
    $('#kd2-' + i).val(kd2);
    console.log("NS2",kd2ns)
    console.log("R2",kd2r)    
    console.log("KD2NA",kd2)
    
    var kd3 = Math.max(kd3ns,kd3r);
    $('#kd3-' + i).val(kd3);
    console.log("NS3",kd3ns)
    console.log("R3",kd3r)    
    console.log("KD3NA",kd3)

    var kd4 = Math.max(kd4ns,kd4r);
    $('#kd4-' + i).val(kd4);
    console.log("NS4",kd4ns)
    console.log("R4",kd4r)    
    console.log("KD4NA",kd4)    
    
    var kd5 = Math.max(kd5ns,kd5r);
    $('#kd5-' + i).val(kd5);
    console.log("NS5",kd5ns)
    console.log("R5",kd5r)    
    console.log("KD5NA",kd5)

    var kd6 = Math.max(kd6ns,kd6r);
    $('#kd6-' + i).val(kd6);
        console.log("NS6",kd6ns)
    console.log("R6",kd6r)    
    console.log("KD6NA",kd6)
    
    var total = 0,
        valid_labels = 0,
        average;

    $('.kd').each(function () {
        var val = parseInt($(this).val(), 10);
        if (val!=0) {
            valid_labels += 1;
            total = kd1 + kd2 + kd3 + kd4 + kd5 + kd6;
        }
    });

        console.log(total)    
    console.log(valid_labels)

    var uts = total / valid_labels;
   /*  $('#uts-').val(uts); */
   $('#uts-' + i).val(uts);
   console.log(uts)
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
      <br />
      <br />
      <div class="form-group">
        <form name="add_name" id="add_name">
          <div class="table-responsive">
            <table class="table table-bordered" id="articles">
            <thead>
              <th scope="col">NS</th>
                                <th scope="col">R</th>
                                <th scope="col" style="background-color: blue;">NA</th>
                                <th scope="col" >NS</th>
                                <th scope="col">R</th>
                                <th scope="col" style="background-color: blue;">NA</th>
                                <th scope="col">NS</th>
                                <th scope="col">R</th>
                                <th scope="col" style="background-color: blue;">NA</th>
                                <th scope="col">NS</th>
                                <th scope="col">R</th>
                                <th scope="col" style="background-color: blue;">NA</th>
                                <th scope="col">NS</th>
                                <th scope="col">R</th>
                                <th scope="col" style="background-color: blue;">NA</th>
                                <th scope="col">NS</th>
                                <th scope="col">R</th>
                                <th scope="col" style="background-color: blue;">NA</th>                              
                                <th scope="col" style="background-color: blue;">UTS</th>
            </thead>
              <tr>
                <td><input type="text" id="kd1ns-0" name="kd1ns[]" placeholder="kd1ns" class="form-control name_list" /></td>
                <td><input type="text" id="kd1r-0" name="kd1r[]" placeholder="kd1r" class="form-control name_list" /></td>
                <td><input type="text" id="kd1-0" name="kd1[]" placeholder="kd1" class="form-control kd" /></td>
                <td><input type="text" id="kd2ns-0" name="kd2ns[]" placeholder="kd2ns" class="form-control name_list" /></td>
                <td><input type="text" id="kd2r-0" name="kd2r[]" placeholder="kd2r" class="form-control name_list" /></td>
                <td><input type="text" id="kd2-0" name="kd2[]" placeholder="kd2" class="form-control kd" /></td>
                <td><input type="text" id="kd3ns-0" name="kd3ns[]" placeholder="kd3ns" class="form-control name_list" /></td>
                <td><input type="text" id="kd3r-0" name="kd3r[]" placeholder="kd3r" class="form-control name_list" /></td>
                <td><input type="text" id="kd3-0" name="kd3[]" placeholder="kd3" class="form-control kd" /></td>
                <td><input type="text" id="kd4ns-0" name="kd4ns[]" placeholder="kd4ns" class="form-control name_list" /></td>
                <td><input type="text" id="kd4r-0" name="kd4r[]" placeholder="kd4r" class="form-control name_list" /></td>
                <td><input type="text" id="kd4-0" name="kd4[]" placeholder="kd4" class="form-control kd" /></td>
                <td><input type="text" id="kd5ns-0" name="kd1ns[]" placeholder="kd5ns" class="form-control name_list" /></td>
                <td><input type="text" id="kd5r-0" name="kd5r[]" placeholder="kd5r" class="form-control name_list" /></td>
                <td><input type="text" id="kd5-0" name="kd5[]" placeholder="kd5" class="form-control kd" /></td>
                <td><input type="text" id="kd6ns-0" name="kd6ns[]" placeholder="kd6ns" class="form-control name_list" /></td>
                <td><input type="text" id="kd6r-0" name="kd6r[]" placeholder="kd6r" class="form-control name_list" /></td>
                <td><input type="text" id="kd6-0" name="kd6[]" placeholder="kd6" class="form-control kd" /></td>

                <td><input type="text" id="uts-0" name="uts[]" placeholder="uts" class="form-control name_list" readonly /></td>
                <td><button type="button" name="add" id="add" class="btn btn-success">Add new</button></td>
              </tr>
            </table>
            <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
          </div>
        </form>
      </div>
    </div>
</body>
</html>

Thank you for your time

Javascript : duplicate and update object array [closed]

I have this object array:

userInterest = [
   { place: `outside`, category: `sport`, type: `Football`, rank:`4` }
];

I want once I press a button I want it to add 2 more objects at the beginning of this array with exact same values except for the “type” and the “rank”

it should looks like:

userInterest = [
   { place: `outside`, category: `sport`, type: `Swimming`, rank:`10` },
   { place: `outside`, category: `sport`, type: `Running`, rank:`1` },
   { place: `outside`, category: `sport`, type: `Football`, rank:`4` }
];

notice that:

  1. the new objects placed on top of the original object.
  2. the values of “place” and “category” remains the same.
  3. the values of “type” and “rank” have changed.

thank you,

is there to get (if generated) 2+ consecutive numbers from an random number array?

Just to be clear what im trying to make is an bot that will play video poker and will look for an straight (5 cards in sequence e.g 4,5,6,7,8) all the cards are in string format like “8” “A” etc, i know that i could set each string to it respective value like “A”=1, “K”=13 and so on, if i do that is there an way to check if there is any consecutive numbers? the video poker app generates 5 random cards and you can hold them to try to increase your odds, lets say for example i was given an (“A”,”3″,”4″,”8″,”10″) is there an way to detect that the 3 and the 4 are consecutive cards so i can hold them and go after the straight? thanks (I’m using javascript but its not necessary for the reply to be in it, i can just convert to js later)

How do I run a PHP function when a div is clicked

So I have some <a> set up as onclick links to show/hide div using JQuery as so:

HTML/PHP

<div id='calendarSubMenu' class='menuBar'>
    <a onclick="currentCal()" class='menuItem'>
        <div>Current Calendar</div>
    </a>
    <a onclick="priorCal()" class='menuItem'>
        <div>Prior Calendar</div>
    </a>
    <a onclick="nextCal()" class='menuItem'>
        <div>Next Calendar</div>
    </a>
    <a onclick="buildCal()" class='menuItem'>
        <div>The Build Calendar</div>
    </a>
</div>

JQUERY

$(window).on('load', function() {
    $("#currentCalendar").show();
    $("#nextCalendar").hide();
    $("#buildCalendar").hide();
    $("#priorCalendar").hide();
});

function priorCal() {
    $("#priorCalendar").show()
    $("#currentCalendar").hide();
    $("#nextCalendar").hide();
    $("#buildCalendar").hide();
}

function currentCal() {
    $("#currentCalendar").show();
    $("#nextCalendar").hide();
    $("#buildCalendar").hide();
    $("#priorCalendar").hide();
}

function nextCal() {
    $("#currentCalendar").hide();
    $("#nextCalendar").show();
    $("#buildCalendar").hide();
    $("#priorCalendar").hide();
}

function buildCal() {
    $("#currentCalendar").hide();
    $("#nextCalendar").hide();
    $("#buildCalendar").show();
    $("#priorCalendar").hide();
}

This all works hunky dory (yes that’s my technical term).

The initial issue I’m trying to solve is that when the page is refreshed, it triggers the window.onload and resets to ‘#currentCalendar’ being shown.

I’m trying to create a PHP cookie using AJAX so that when the page is refreshed, it knows what the last div viewed was..

I tested by changing one of the JS functions to this:

function priorCal() {
    $("#priorCalendar").show()
    $("#currentCalendar").hide();
    $("#nextCalendar").hide();
    $("#buildCalendar").hide();
    $.post("cookie.php", {
        calendar: "prior"
    });
}

with a new page of cookie.php that has this:

$set_cookie = $_POST['calendar'];
try {
    setcookie("lastScreen", $set_cookie, time() + (86400 * 30), "/");
    $echo = ($_COOKIE['lastScreen']) ?? "FAIL";
    echo "<script>alert('$echo')</script>";
} catch (RuntimeException $e) {
    echo "<script>console.log('$e')</script>";
}

I am receiving no errors (console, alert, or otherwise), but I am also not receiving an output as designed with the echo.

I also took out the “makeshift Javascript” with the alert() and did just plain echo. Still nothing.

Is there a better way to be doing this?

How to sort array by date?

I have following data:

const data = 
[{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44},
{date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53},
{date: "2022-05-10 13:34:00", open: 154.97, low: 154.96, high: 155.29, close: 155.22}];

I am using following code to sort the data by date (oldest to newest):

const data = 
[{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44},
{date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53},
{date: "2022-05-10 13:34:00", open: 154.97, low: 154.96, high: 155.29, close: 155.22}];
console.log(Object.entries(data).sort((([, a], [, b]) => {
    return new Date(a.date) - new Date(b.date)
  })).map(i=>{ return i[1]}))

In chrome, it renders pretty well, but on safari, it will not work and will maintain the original order.

My question is what makes this difference and how to make the sort algorithem work in all broswer?

Thanks!

P.S. I do check this question, Chrome and Safari javascript .sort() method works differently, but the answers indicated that The sort is not necessarily stable, but according to mdn now:

Since version 10 (or EcmaScript 2019), the specification dictates that Array.prototype.sort is stable.

What I am missing?

How can the route files access libraries defined in index.js

I have an index.js file and a route folder that contains a file called genres.js. The first few lines of my index.js file are:

const Joi = require('joi');
const express = require('express');
const genres = require('./routes/genres');

yet when I use Joi in genres.js I get an error that Joi is not defined. I am wondering how I can make Joi visible to all of the route files so that I don’t need to require each library in every route file I create.

I have been following a tutorial and in the tutorial this was sufficient but is not working for me.

Javascript Grouping Duplicate Name

I am writing a program where I need to find the duplicates name in the JSON and Put it into different array called resultedMarketsGrouped and also hasMore attribute if duplicates exist

Example

{
    "resultedEvents": [
        {
            "categoryName": "Football",
            "name": "Arsenal vs Aston Villa",
            "resultedMarkets": [{
                    "name": "Asian Handicap",
                },{
                    "name": "Asian Handicap",
                }
            ]
        },
        {
            "categoryName": "Football",
            "name": "Arsenal vs Aston Villa (Live)",
            "resultedMarkets": [{
                    "name": "Asian Handicap (0-1)",
                },{
                    "name": "Asian Handicap (1-1)",
                },{
                    "name": "Asian Handicap (1-1)",
                },{
                    "name": "Asian Handicap (1-3)",
                }
            ]
        }
    ]
}

If you take a look on above JSON

"name": "Asian Handicap , "name": "Asian Handicap (1-1)" are duplicates

I want to transform into following example

Expected

{
    "resultedEvents": [
        {
            "categoryName": "Football",
            "name": "Arsenal vs Aston Villa",
            "resultedMarketsGrouped": [{
                  "name": "Asian Handicap",
                }
            ],
            "resultedMarkets": [{
                    "name": "Asian Handicap",
                    "hasMore": true
                },{
                    "name": "Asian Handicap",
                    "hasMore": true
                }
            ]
        },
        {
            "categoryName": "Football",
            "name": "Arsenal vs Aston Villa (Live)",
            "resultedMarketsGrouped": [{
                  "name": "Asian Handicap (1-1)",
                }
            ],
            "resultedMarkets": [{
                    "name": "Asian Handicap (0-1)",
                    "hasMore": false
                },{
                    "name": "Asian Handicap (1-1)",
                    "hasMore": true
                },{
                    "name": "Asian Handicap (1-1)",
                    "hasMore": true
                },{
                    "name": "Asian Handicap (1-3)",
                    "hasMore": false
                }
            ]
        }
    ]
}

Please help me I’m very new to coding thanks

Un-overwrite a JavaScript function

In a nutshell, I make UserScripts and ive been stuck.
Inside of the HTML theres a script tag and inside theres this:

<script>
setTimeout = function(){}
</script>

And theres no way to use the function, its completely useless.
What would be the best solution to recover?
What i was thinking was using a way to set the function like main = setTimeout() and i can reset it after the script is loaded. Back to like setTimeout = main.
I am also trying to stay (mostly) undetected unlike running all of the code in a different environment like a iframe. ALSO yes I do know you can just use setInterval and then break the loop but this is just an example. Thanks in advanced!

StencilJS: How to prevent “flickering” when loading component in a page

A group of volunteers has created a single/multi-select component using StencilJS: https://github.com/NothingAG/adg-components

Now we want to hand it over to the client so they can use it in their project. But we notice that loading the component seems to take some time after the page itself loaded, so some flickering appears (when the loaded component claims its horizontal space):

enter image description here

Is this normal behaviour of such a component? Or how can we allocate the needed space when the browser is rendering? We could try to simply use min-height or something with a fixed value, but this feels like a hack and may change over time.

Thanks a lot for help.

Chrome extension: How to save any data from a page?

maybe someone can explain me how to resolve this problem:

For example I have this code:

let btn = document.getElementById('defbtn');

if (btn != null) {
    btn.onclick =  function(el) {
        chrome.tabs.query({active:true, currentWindow: true}, function(tabs) {
            chrome.tabs.executeScript(
                tabs[0].id,
                {code: "var textP = document.evaluate( 'any_xpath_here', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue.innerHTML;"}
            );
        });
        
        // How to get value from textP? To execute for example     alert(textP);
    }
}

How can I access textP value from chrome extension or how can I save textP in a chrome extension variable?

StencilJS: How to prevent CSS from being auto-appended to bottom of

A group of volunteers has created a single/multi-select component using StencilJS: https://github.com/NothingAG/adg-components

Now we want to hand it over to the client so they can use it in their project. They do it like this:

<script type="module" src="/build/adg-components.esm.js"></script>
<script nomodule src="/build/adg-components.js"></script>

<adg-combobox
  id="hobbies"
  name="hobbies"
  label="Please select your hobbies"
  optionslabel="Hobbies"
  multi="true"
  lang="de"
></adg-combobox>

What they experience though is that the CSS is auto-attached to the very bottom of <head>, after any other styles:

enter image description here

This makes is very hard to override specific styles. Is there a way to prevent that? For example, it would make much more sense in our case that the styles are added right after <script type="module" src="/build/adg-components.esm.js"></script>, so any following <style> would take precedence.

One other workaround I can think of is to remove the styles altogether when running $ npm run build, and then let the client import the styles manually. But this doesn’t feel like the right way to do it.

Any help is highly appreciated. Thank you.

I have a question about nail recognition with Python openencv when using a client cam

Currently, js sends the video to Python opencv through the client cam, recognizes the nails, and synthesizes the nail art image on the nails. Afterwards, the processed video is sent back to js by websocket to show a video with nails on it, and the post-processed video is gradually slowing down. May I know what the problem is?

python opencv code


@app.get("/client")
async def client(request: Request):
    # /templates/client.html파일을 response함
    print("request : " ,request)
    return templates.TemplateResponse("client.html", {"request":request})

# 웹소켓 설정 ws://127.0.0.1:8000/ws 로 접속할 수 있음
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    # print(f"client connected : {websocket.client}")
    await websocket.accept() # client의 websocket접속 허용
    await websocket.send_text(f"Welcome client : {websocket.client}")
    i = 0

    mp_drawing = mp.solutions.drawing_utils
    mp_drawing_styles = mp.solutions.drawing_styles
    mp_hands = mp.solutions.hands
    # print(f'{mp_hands} 일단 선언?')
    args = {
        "model": "./model/export_model_008/frozen_inference_graph.pb",
        # "model":"/media/todd/38714CA0C89E958E/147/yl_tmp/readingbook/model/export_model_015/frozen_inference_graph.pb",
        "labels": "./record/classes.pbtxt",
        # "labels":"record/classes.pbtxt" ,
        "num_classes": 1,
        "min_confidence": 0.6,
        "class_model": "../model/class_model/p_class_model_1552620432_.h5"}
    # print(args)
    COLORS = np.random.uniform(0, 255, size=(args["num_classes"], 3))
    # print(COLORS)
    print('1 : 모델 생성')
    model = tf.Graph()
    with model.as_default():
        print("> ====== loading NAIL frozen graph into memory")
        graphDef = tf.GraphDef()

        with tf.gfile.GFile(args["model"], "rb") as f:
            serializedGraph = f.read()
            graphDef.ParseFromString(serializedGraph)
            tf.import_graph_def(graphDef, name="")
        # sess = tf.Session(graph=graphDef)
        print(">  ====== NAIL Inference graph loaded.")
        # return graphDef, sess
    

    with mp_hands.Hands(min_detection_confidence=0.8,min_tracking_confidence=0.5) as hands:
   
        with model.as_default():
            with tf.Session(graph=model) as sess:
                print('2 : 텐서플로우 실행')
                imageTensor = model.get_tensor_by_name("image_tensor:0")
                boxesTensor = model.get_tensor_by_name("detection_boxes:0")

            
                scoresTensor = model.get_tensor_by_name("detection_scores:0")
                classesTensor = model.get_tensor_by_name("detection_classes:0")
                numDetections = model.get_tensor_by_name("num_detections:0")
                drawboxes = []
                


                
                while True:
                    print('3 : 캠읽음')
                    data = await websocket.receive_text()  # client 메시지 수신대기
                    
                    data = data.split(',')[1]

                    imgtest = imread(io.BytesIO(base64.b64decode(data)))
                    # print(imgtest)
                    img = cv2.imread("sss.png")
                    frame = cv2.flip(imgtest, 1)
                    image = frame
                    (H, W) = image.shape[:2]
                    # print("H,W:", (H, W))
                   
                    output = image.copy()
                
                    # output[0:450, 0:450] = img
                    img_ff, bin_mask, res = ff.find_hand_old(image.copy())
                    image = cv2.cvtColor(res, cv2.COLOR_BGR2RGB)
                    image_2 = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
                    results = hands.process(image_2)
                   
                    image = np.expand_dims(image, axis=0)
                    image_2 = cv2.cvtColor(image_2, cv2.COLOR_RGB2BGR)
                    imageHeight, imageWidth, _ = image_2.shape
                    # print('여기까진 옴')
                    if results.multi_hand_landmarks:
                        for num, hand in enumerate(results.multi_hand_landmarks):
                           
                            normalizedLandmark = hand.landmark[12]
                            normalizedLandmark_2 = hand.landmark[11]
                            pixelCoordinatesLandmark = mp_drawing._normalized_to_pixel_coordinates(normalizedLandmark.x, normalizedLandmark.y, imageWidth, imageHeight)
                            pixelCoordinatesLandmark_2 = mp_drawing._normalized_to_pixel_coordinates(normalizedLandmark_2.x, normalizedLandmark_2.y, imageWidth, imageHeight)
                            
                            tanTheta = ((pixelCoordinatesLandmark_2[0]-pixelCoordinatesLandmark[0]))/((pixelCoordinatesLandmark_2[1]-pixelCoordinatesLandmark[1]))
                            theta = np.arctan(tanTheta)
                            try:
                                angle = theta*180/math.pi
                            except:
                                print('수평')
                            
                                
                           
                            
                    # cv2.imshow('Output',image_2)

                            (boxes, scores, labels, N) = sess.run(
                                [boxesTensor, scoresTensor, classesTensor, numDetections],
                                feed_dict={imageTensor: image})
                            boxes = np.squeeze(boxes)
                            scores = np.squeeze(scores)
                            labels = np.squeeze(labels)
                            boxnum = 0
                            box_mid = (0, 0)
                            
                            for (box, score, label) in zip(boxes, scores, labels):
                            
                                if score < args["min_confidence"]:
                                    continue
                                # scale the bounding box from the range [0, 1] to [W, H]
                                boxnum = boxnum + 1
                                (startY, startX, endY, endX) = box
                                startX = int(startX * W)
                                startY = int(startY * H)
                                endX = int(endX * W)
                                endY = int(endY * H)
                                # print(startX,startY,endX,endY)
                                X_mid = startX + int(abs(endX - startX) / 2)
                                Y_mid = startY + int(abs(endY - startY) / 2)
                                box_mid = (X_mid, Y_mid)
                                # draw the prediction on the output image
                                label_name = 'nail'
                                # idx = int(label["id"]) - 1
                                idx = 0
                                
                                
                                

                                # x = 가로 y = 세로 점
                                # print(startX,startY,endX,endY)
                                startX = startX -20
                                startY = startY -20
                                endX = endX +20
                                endY = endY +20
                                wi = int(abs(endY-startY))
                                he = int(abs(endX-startX))
                                cat_sticker = cv2.resize(img,(wi,he))
                                # print(cat_sticker.shape)

                                # 회전
                                img_rotate = ff.rotate_image(cat_sticker,angle)
                                # print('회전된 이미지 shape : ' ,img_rotate.shape)
                                


                                xx = X_mid -wi // 2
                                yy = Y_mid - he // 2
                                if xx < 0:
                                    cat_sticer = cat_sticker[:,xx:]
                                if yy < 0:
                                    cat_sticker = cat_sticker[-yy:,:]
                                
                                try :
                                    sticker_area = image_2[yy:yy+img_rotate.shape[0],xx:xx+img_rotate.shape[1]]
                                    image_2[yy:yy+img_rotate.shape[0], xx:xx+img_rotate.shape[1]] = np.where(img_rotate==0,sticker_area,img_rotate).astype(np.uint8)
                                except :
                                    print('에러')

                                


                    
                   
                    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 65]
                    buffer = cv2.imencode('.jpg', image_2,encode_param)[1]
                   
                    image_2 = buffer.tobytes()
                    
                    await websocket.send_text(buffer.tobytes())

client code

<html>
<head>
    <title>Hello</title>
</head>
<script async src="https://docs.opencv.org/3.4/opencv.js"></script>
<!--script async src="./opencv.js"></script-->
<body>
    <video id="videoInput" style="display:none"></video>
  <canvas id="videoOutput"></canvas>
  <button onclick=stream()>Send</button>
  <canvas id="testt" width="300" height="200" style="border: 1px solid red"></canvas>
  <div id="status">
    Connection failed. Somebody may be using the socket.
  </div>
  <video id=""video></video>
</body>
<script>

  var w = 640, h = 480;
    var url = "ws://localhost:8000/ws"
    var ws = new WebSocket(url);
  let testt = document.getElementById("testt");
  testt.width = w;
  testt.height = h;
  ws.addEventListener('open', (e) => {
    // console.log('ㅇㅇㅇㅇㄹㄴㅇㅁㄹㄴㅁ래제머ㅏ레ㅐㅈ머')
    document.getElementById("status").innerHTML = "Opened";
  });

  ws.addEventListener('message', (e) => {
    console.log(e.data)
    let ctx = testt.getContext("2d");
    let image = new Image();
    URL.revokeObjectURL( oldObjectUrl );
    try {
    image.src = URL.createObjectURL(e.data);
    
    }
    catch {
      // console.log('여기로?')
      image.srcObject = e.data
    }
    console.log(image)
    image.addEventListener("load", (e) => {
        // console.log('들어옴ㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁ')
        ctx.drawImage(image, 0, 0, testt.width, testt.height);
    });
  });


    ws.onopen = function(){
        console.log("Websocket is connected.");
   
    }
  

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  var constraints = {audio: false, video: true};
  var video = document.getElementById("videoInput");
  video.width = w;
  video.height = h;
  function successCallback(stream){
    console.log('엥들어옴')
    video.srcObject = stream;
    video.play();
  }
  
  function errorCallback(error){
    console.log(error);
  }
  navigator.getUserMedia(constraints, successCallback, errorCallback);
    var canvas = document.getElementById("videoOutput");
  canvas.width = w;
  canvas.height = h;
  var ctx = canvas.getContext("2d");
  function processImage(){
        ctx.drawImage(video, 0, 0, w, h);
        setTimeout(processImage, 1);
  }
  processImage();

  function stream(){
    setInterval(sendImage, 30);
  }

  function sendImage(){
    var rawData = canvas.toDataURL("image/jpeg", 3);
    // console.log(rawData)
    ws.send(rawData);
  }





  
</script>
</html>