Question: Retain the location of an image even when resized

I have an image, at a fixed dimensions, where when clicked we get the location. That location is used as a dot as in image:

enter image description here

When the image is clicked, we get the location and move the marker as the user clicks the image:


// onClick function:
setPoint = (e) => {
    // If things look weird, I'm using Stimulusjs
    // but should be straight forward to show as an
    // example.

    // These "var"s you see was a quick copy/paste from a legacy
    // code base.
    
    var X_OFF_SET = 1;
    var Y_OFF_SET = 1;

    var X_IMAGE_OFFSET = 8;
    var Y_IMAGE_OFFSET = 8;

    let device = document.head.dataset.device // desktop or mobile

    console.log(device === 'desktop')
    
    // Things work weird on iOS webview so I use e.pageX/Y
    let x = device === 'desktop' ? e.clientX : e.pageX; // or pageX
    let y = device === 'desktop' ? e.clientY : e.pageY;

    // this.planViewTarget is the image DOM element
    var intXPos = x - this.findPosX(this.planViewTarget) - X_IMAGE_OFFSET;
    var intYPos = y - this.findPosY(this.planViewTarget) - Y_IMAGE_OFFSET;

    console.log( (intXPos + X_OFF_SET),  intYPos + Y_OFF_SET);

    //this.xCoordinateTarget.value = intXPos + X_OFF_SET
    //this.yCoordinateTarget.value = intYPos + Y_OFF_SET

    // this.defaultPointTarget is the DOM element (the marker on the image)
    this.defaultPointTarget.style.left =  (intXPos + X_OFF_SET) + "px";
    this.defaultPointTarget.style.top = (intYPos + Y_OFF_SET) + "px";

// Legacy code that seems to work well:
findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}


}

With the above code is what I’ve inherited which does the work.

What I’m now tasked with is, if the image is resized, the points should be at the same location on the image but instead, the points (markers) are fixed on the screen.

Is it possible to change the code so that the markers move when the image is resized? If not possible, I could explain why it’s not possible?

Thanks

Delete cache in iframe (3rd party website)

Hi i wanted to clear cache in my iframe, but still the old content still there and the account still connect and not the new one.

Can anyone help me? Thank you

This is the code:

<head>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
</head>

<div>
    <iframe id="partner-browser-iframe" style="display: block; overflow: hidden; background: #0000; border: none"
        width="1000" height="1000" src="url" frameborder="0"></iframe>
</div>


<script>
    var myFrame = document.querySelector('iframe');

    var myButton = document.querySelector('button');

    myButton.onclick = function (evt) {
        myFrame.contentWindow.location.reload(true);

    }
</script>

How to insert row in table through Javascript function

I am trying to insert another row into a table with footer.

Here is my code:

function submit(){
        /* Some code here with declarations & value assignings*/

        let tble = document.getElementById("tabl");
        
        let newEl = document.createElement("tr");
        newEl.innerHTML="<td>"+nowSr+"</td> <td>"+taskForm+"</td> <td>"+tagForm+"</td> <td>Rs. "+amountForm+"</td>";

        tble.appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
       }

My function gives me below result:
enter image description here
enter image description here

As you can see (IN INSPECT ELEMENTS WINDOW) the new row is inserted after the footer. How to add it properly

  • after the last row in the table?

Cannot connect to Flask application due to CORS error

I have a Flask application that is behind an Apache server. I need to connect to it from a frontend that will be on
another host (and currently is on localhost).

In Flask I’ve added the following line to support CORS:

CORS(app, origins=["http://localhost:3000"], supports_credentials=True)

In httpd.conf I’ve also set the headers with the following code:

Header always set Access-Control-Allow-Origin "http://localhost:3000"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
Header always set Access-Control-Allow-Credentials "true"


# lines below wasn't added now, but I can't get rid of them
AuthType Basic
AuthName "Apache2 QA authorization"
AuthBasicProvider file
AuthUserFile /root/htpasswd
Require valid-use

My Javascript looks as follows:

fetch("https://my-app.com/api/v1/basic/", {
    headers: {
        'Authorization': 'Basic base64-credentials',
    },
    mode: "cors",
    method: "get"
})
    .then(response => response.json())
    .then(data => {
        console.log(data);
    }).catch(error => {
    console.log(error);
    return [];
});

When I run the code in browser (Firefox), I get the following error:

CORS Allow Origin Not Matching Origin
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-app.com/api/v1/basic/. (Reason: CORS preflight response did not succeed). Status code: 401.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-app.com/api/v1/basic/. (Reason: CORS request did not succeed). Status code: (null).

The request headers are:

OPTIONS /api/v1/basic/ HTTP/1.1
Host: my-app.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:99.0) Gecko/20100101 Firefox/99.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Referer: http://localhost:3000/
Origin: http://localhost:3000
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Pragma: no-cache
Cache-Control: no-cache

And the response headers:

HTTP/1.1 401 Unauthorized
Date: Fri, 22 Apr 2022 11:40:46 GMT
Server: Apache
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Headers: x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Expose-Headers: Content-Security-Policy, Location
Access-Control-Allow-Credentials: true
WWW-Authenticate: Basic realm="Apache2 QA authorization"
Content-Length: 381
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1

The /basic endpoint is very simple, and requires no auth from Flask (Apache has its separate auth requirement):

@api.route("/basic")
class SimpleResponse(Resource):
    def get(self):
        return {"message": "OK"} 

I don’t understand what’s wrong here. The request origin matches Access-Control-Allow-Origin, but still gets rejected.
Also, I have no idea why the Authorization header is not sent with the request. What am I doing wrong?

Can’t get src of img (JS, Jquery)

I have some table.

            <table>                
            <tr>
                <td>1</td>
                <td><img src="uploads/0/58.gif"></td>
                <td>Name 1</td>
                <td>8</td>
            </tr>
            
            <tr>
                <td>2</td>
                <td><img src="uploads/0/25.gif"></td>
                <td>Name2</td>
                <td>5</td>
            </tr>
            </table>

Need to get src of all images from table. I’m doing some replaces in table, so
var tbl = $(‘table’).html();

After replaces, I need to get src-s:
I really don’t know how to write it, like $(tbl + ‘tr’).each….
So I write:

       $('table tr').each(function(index){ 
            let tds = $(this).find('td'); // get array td-s
            console.log(typeof(tds.html())) // Object
            console.log(tds[1]) // <td><img src="uploads/0/58.gif"></td>
            //$('img').src // error
            //$('img').getAttribute('src') // error,
            //$(this).find('img').src // error
            //ets...
        }); 

I try somethink like

or $(this).find(‘img) // == Object, i can’t get src from

Automatically create whatsapp groups from given database records and respective invitation links

I have stored a bunch of locations on a DB.

I’m looking forward to create a whatsapp group for each location automatically with minimum contacts at first and generate the respective invitation link.

The idea is within a map where all those locations are mapped, users can sign into each location specific whatsapp group chat via invitation link.

Is it possible to do it with a certain level of automation? What would be the most effective way to achieve such?

How do I start an animation for a certain time?

I have the main loop of the program looped using requestAnimationFrame As for example after the character crashed, disable the collision for him for 3 seconds and blink at the same speed? At the same time, the entire gameplay will continue to animate at a different speed

How can I run another animation at a different speed and for a time during one animation?

The code I think is not required here, a standard animation loop using requestAnimationFrame:

function loop() {
    requestAnimationFrame(loop)

    let now = new Date().getTime(),
        dt = now - (time || now)

    time = now

    game.step(dt)
    game.render()
}

thanks

How to import component as a button in Nextjs?

I have this component with an internal link which is used in multiple pages

component

when I try to import it as a button in the Nextjs application I get this result, it renders both the styled anchor link and the button in the background

enter image description here

enter image description here

With the exact same code in the React application I get the desired result enter image description here

It looks like the prop “as” for some reason is not working in the Nextjs version of the application

Html template to javascript

I am working on a website that is very dyanmic, so in order to not create every element using javascript, I am using HTML templates.
I want to somehow convert the content of the template tag to a js file acting as a module, so my code can get a lot cleaner.
The solution I am using right now is this :

    const about_item_template = ()=>{ 
    let temp = document.createElement("template");
    temp.innerHTML = 
    `<div class="about-item" style="height: 280px;">
<div class="about-slide-image" style="text-align: center;height: 200px;display: flex;justify-content: center;">
    <img src="/uploads/13-image-a66c8e53-9bef-4dc6-a4f7-a0a566baf078.png" alt="image" style="max-height: 200px;width: auto">
</div>
<div class="about-text">
    <h3>text</h3>
</div>
</div>`;

return temp.content.cloneNode(true);
}

Basically i am just creating a function for each template I am using and just import the ones I need in a html file. For example, when a users visits cart.html, only the cart templates would be loaded and so on. But I think this solution is not so memory-friendly, because I am creating a document Element every time I call the function for a specific template. Does the document.createElement() affect the memory?
My question is if this solution is good (in terms of memory / optimisation). What other approach should I use?
P.S.: I would like a pure js solution, without libraries like jQuery or React.

Get Unique Device ID from browser

I wanted recongnize the device as unique, even if we are using multiple browser how can we generate or get an same unique deivceID in browser with javascript.

Yes we cannot get MAC address and CPU serial number through javascript because it’s an very high level language.

so is there any work around to get an unique device ID.

How can I access inside an object? [duplicate]

Hello I know this is a simple question but Im having trouble accesing just the email from my object.

This are the console logs that Im trying

router.get('/matchs', async (req, res) => {
    const match = await Match.find()
    res.json(match)
//1
    console.log(match)
//2
    console.log(match[1])
//3
    console.log(match.Data)
//4
    console.log(match[1].Email)
});

This is what they’re returning:

//1
[
  { Data: [ [Object], [Object] ], Total: 2 },
  { Data: [ [Object], [Object] ], Total: 2 }
]
//2
{
  Data: [
    {
      Name: 'Lucas',
      Surname: 'Torreira',
      Email: '******@gmail.com',
      Number: 3154009595,
      Date: '2022-04-27',
      Time: '03:00',
      Place: 'Chapinero'
    },
    {
      Name: 'Antonio',
      Surname: 'Martin',
      Email: '*****@gmail.com',
      Number: 3119996545,
      Date: '2022-04-27',
      Time: '03:00',
      Place: 'Chapinero'
    }
  ],
  Total: 2
}
//3
undefined
//4
undefined

I also have tried suttf like match[1].Data?.Email, match[1].Data[1] but my attempts to get further in the object have failed also just in case everything but the email is dumb data.

Thank you for any help

Capturing Javascript Objects Firefox Console

I am trying to built a Webscraper using Selenium in python for gathering data for a University project.

Currently the data comes though in an encoded base 64 string through the websocket which I haven been unable to decode accurately in python.

The data I want is decoded by firefox into an object and posted in the console as a debug message. Is there any way to catch these objects from the console. Other browsers such as chrome are unable to decode this data either.

I have tried methods such as in
How to read from Chrome’s console in JavaScript

But have been unable to make any headway.

If there is no other method. Would it be possible to make a browser extension for this?

Thanks

Convert Hexadecimal IEEE754 to Float in Javascript

I Want to convert Hexadecimal to Float 32. I have used below mention code but it didn’t help me proper as I try to convert 0x4145851f this value to float32 it comes as a 12.345000267028809 But actually the value is 12.345 so I want to ignore extra digits. not rounding off, need proper output.

const HexToFloat32 = (str) => {
  var int = parseInt(str, 16);
  if (int > 0 || int < 0) {
    var sign = int >>> 31 ? -1 : 1;
    var exp = ((int >>> 23) & 0xff) - 127;
    var mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
    var float32 = 0;
    for (let i = 0; i < mantissa.length; i += 1) {
      float32 += parseInt(mantissa[i]) ? Math.pow(2, exp) : 0;
      exp--;
    }
    return float32 * sign;
  } else return 0;
};

console.log(HexToFloat32("0x41200000"));

I already go through with below mention Stack URL:

stackoverflow.com/questions/5055723/converting-hexadecimal-to-float-in-javascript

Double service worker

I am developing an extension on manifest 3 clapping

I don’t understand how, but I very rarely get to freeze the service worker, sometimes it just doesn’t wake up (service worker (inactive)) on call, and sometimes it’s somehow duplicated(service worker n service worker) – and in both situation only update btn via chrome://ext helps…


  • I’m init bg by: "background": {"service_worker": "js/background.js"},

  • In bg, it has only one import at 1 line: importScripts('./basic_script.js');

  • I’m still using bg as a request manager and handler for most stuff

  • 90 percent of the code is async

  • basic_script.js is used in almost all js files (I see that the bg page for some reason writes its console logs to the devtools opened from the exts local html === maybe this is the issue?)

  • basic_script.js has const request=(data)=>{return new Promise((done)=>{ with AbortController() + fetch.then.catch combo-wombo


I can’t get repeatability, once this chrome bug(?) met me after a while, today I got it almost immediately… I just update the local pages(chrome), and the background dies completely and turns off the main ability of my extension 🙁

I can’t google/find any, because I’m stupid

Weird issue with Vue / Javascript variables

I honestly don’t even know how to search for this question (what search param to write) but either way its bit weird issue and I am desperate for help.

So I am trying to do something simple, event sends “form-change” and when it does, we set new value in “this.data” object. Fairly simple. I don’t expect this.data to be reactive I just want to update it.

// Find our data object which we want to update/change
if (form.field.includes('.')) {

    let find = form.field.split('.'), level = this.data;
    for (let index = 0; index < find.length; index++) {

        if (level[find[index]] !== undefined) {

            level = level[find[index]];

        } else {

            level = undefined;

        }

    }

    if (level !== undefined)
        level = setFieldData();

}

This is fairly simple, we have name of field “inspect.book” and when update comes (Event) we just use dots to split into multi tree and update “this.data.inspect.book” to new value. But it does not work. Value does not change.

But the value from actual this.data.inspect.book comes out just fine using:

console.log(level);

However, if I do this:

this.data[ form.field.split( '.' )[ 0 ] ][ form.field.split( '.' )[ 1 ] ] = setFieldData();

It works fine. So “reference” to variable does not work… how is this possible? Looks like a bug in javascript or is it something with vue/reactivity?

Does anyone have better idea how to get this to work?