Port is already in use

I was working on a Node.js application. During development, it was running on the local server. Whenever I made changes to the application and tried to run it again, it would not run on the specified port number. Each time, I had to change the port number, even after a minor modification. Can anyone explain why this is happening?

How do I extract the URL element from V8 script object

I’ve modified v8 slightly to print the URL JS originates from before it’s parsed.

Background: I’m also printing the JS itself so as to deobfuscate potential malicious JS step-by-step. jmrk kindly showed me how to do that.

What works
Chromium prints object containing the JS URL to stdout: Name: 0x2357009098e1 <String[55]: e”chrome://… module_proxy.js”>

What doesn’t work
How do I reference/extract the URL string in the object: “chrome://…” It’s probably simple but my c++ skills are limited?

Code excerpt (v8/src/parsing/parsing.cc)

@@ -16,6 +16,14 @@
  #include "src/parsing/scanner-character-streams.h"
  #include "src/zone/zone-list-inl.h"  // crbug.com/v8/8816
 
+ #include <string>
+ #include <iostream>
+ #include <stdio.h>
+ #include "src/objects/script.h"
+ #include "src/objects/call-site-info.h"
+
  namespace v8 {
  namespace internal {
  namespace parsing {
@@ -50,6 +58,11 @@ bool ParseProgram(ParseInfo* info, Handle<Script> script,
        ScannerStream::For(isolate, source));
    info->set_character_stream(std::move(stream));
 
+  if (script->HasValidSource()) {
+    Handle<Object> source_url(script->GetNameOrSourceURL(), isolate);
+    std::cout << source_url << std::endl;
+  }
+
   Parser parser(isolate->main_thread_local_isolate(), info, script);

Thank you.

Opengraph doesn’t show

So I want my website to have an opengraph preview. For that I coded a new system in my index.html file which goes like this:

$(document).ready(function(){
  $("#navbar").load("navbar.html");
  $("#header").load("header.html");
});

And then the navbar loads here in a div:

<div id="navbar"></div>

The navbar works fine, but the header is having some issues.
I put the header here before the <head> ends:

<div id="header"></div>

I tried doing this as the code for the header:

<!-- HTML Meta Tags -->
<title>M100</title>
<meta name="description" content="Thing">

<!-- Facebook Meta Tags -->
<meta property="og:url" content="https://micamaster100.github.io/">
<meta property="og:type" content="website">
<meta property="og:title" content="M100">
<meta property="og:description" content="Thing">
<meta property="og:image" content="https://opengraph.b-cdn.net/production/images/6956cfb8-f271-4cc5-bea6-965c7ce33b70.png?token=UTylE3SBRlkQmuQGqlHtvBVjJSbd8Wh6iZV5TvXLWF0&height=675&width=1200&expires=33258560618">

<!-- Twitter Meta Tags -->
<meta name="twitter:card" content="summary_large_image">
<meta property="twitter:domain" content="micamaster100.github.io">
<meta property="twitter:url" content="https://micamaster100.github.io/">
<meta name="twitter:title" content="M100">
<meta name="twitter:description" content="Thing">
<meta name="twitter:image" content="https://opengraph.b-cdn.net/production/images/6956cfb8-f271-4cc5-bea6-965c7ce33b70.png?token=UTylE3SBRlkQmuQGqlHtvBVjJSbd8Wh6iZV5TvXLWF0&height=675&width=1200&expires=33258560618">

<!-- Meta Tags Generated via https://www.opengraph.xyz -->

and only get the title but not the social media preview.

Сonvert file to base64 in JavaScript just by function [duplicate]

I’m new to java script and I can’t understand:

Why this print base64 from file:

function getBase64(file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        console.log(reader.result); // base64string exist only here
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
}

But almost same:

function toBase64 (file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    return reader.result;
}

Return null

I don’t understand what’s going

How can I simply convert a file to a string without any extra expressions (like promises), just call -> return, like python? Like that:

var justBase64String = justConvertFileToBase64(file)

P.S. i get my file from input:

var file = document.getElementById('face-input').files[0]

GA pageTracker is undefined

I am trying to download drivers from Dynabook, but there seems to be a GA-related issue.
The console provides the following errors:

pageTracker is undefined

and

pageTracker._trackEvent is not a function

It seems like the GA JS is failing to load and that is blocking the rest of the website JS from running. Is there a way around this?

boolean evaluator in Javascript?

I’m trying to avoid writing this from scratch and would love if anyone has an idea

const testCases = [
    { text: "keyword1 is present but keyword4 is not here", boolExpr: "(keyword1 OR keyword2) AND (keyword3 OR keyword4)", expected: false },
    { text: "keyword1 and keyword3 are both present", boolExpr: "(keyword1 OR keyword2) AND (keyword3 OR keyword4)", expected: true },
    { text: "keyword1 and keyword3 are present, but keyword5 is also here", boolExpr: "(keyword1 OR keyword2) AND (keyword3 OR keyword4) AND NOT (keyword5 OR keyword6)", expected: false },
    { text: "keyword1 and keyword3 are present, without keyword5", boolExpr: "(keyword1 OR keyword2) AND (keyword3 OR keyword4) AND NOT (keyword5 OR keyword6)", expected: true },
    { text: 'The "phrase 1" and "phrase 2" are present', boolExpr: '("phrase 1" OR keyword1) AND ("phrase 2" OR keyword2) AND NOT ("phrase 3" OR keyword3)', expected: true },
    { text: 'The "phrase 1" is here but not "phrase 2"', boolExpr: '("phrase 1" OR keyword1) AND ("phrase 2" OR keyword2) AND NOT ("phrase 3" OR keyword3)', expected: false },
    { text: 'The "phrase 1" and "phrase 2" are here, but also "phrase 3"', boolExpr: '("phrase 1" OR keyword1) AND ("phrase 2" OR keyword2) AND NOT ("phrase 3" OR keyword3)', expected: false },
    { text: 'keyword1, keyword3 and keyword6 are all here', boolExpr: "(keyword1 OR keyword2) AND (keyword3 OR keyword4) AND NOT (keyword5 OR keyword6)", expected: false },
];

Unfortunately I can’t use eval() 🙁

any thoughts?

OnClick EventListener not working in my code

I am trying to execute code when a button is pressed. I currently have the “catch all” alert set up.

My code

$(document).ready(function() {
  //bulk submit handler This section works when this form is shown.  In this instance, I have the form
  //I currently have the form hidden
  $("#bulkSubmit").submit(function(e) {
    e.preventDefault();

    var form = $(this);
    var frmUrl = form.attr('action')

    $.ajax({
      type: "POST",
      url: frmUrl,
      data: form.serialize()
    });
  });
});

addButton = document.getElementById('btnCheckInSubmit');
addButton.addEventListener("click", function() {
  alert("clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="addCustomerMain main">
  <h1>Add Customer</h1>
  <hr>
  <form method="post" id="addCustomer">
    <div class="formContent">
      <div class="formElement">
        <label for="custName">Name</label>
        <input class="txtLarge" type="text" name="custName" id="custName">
      </div>
    </div>
    <div class="formContent">
      <div class="formElement">
        <label for="custAddress">Address</label>
        <input class="txtLarge" type="text" name="custAddress" id="custAddress">
      </div>
    </div>
    <div class="formContent">
      <div class="formElement">
        <label for="custCity">City</label>
        <input class="txtSmall" type="text" name="custCity" id="custCity">
      </div>
      <div class="formElement">
        <label for="custState">State</label>
        <input class="txtXSmall" type="text" name="custState" id="custState">
      </div>
      <div class="formElement">
        <label for="custZip">Zip</label>
        <input class="txtXSmall" type="text" name="custZip" id="custZip">
      </div>
    </div>
    <div class="formContent">
      <div class="formElement">
        <label for="custPhone">Phone</label>
        <input type="text" name="custPhone" id="custPhone" class="txtLarge">
      </div>
    </div>
  </form>
  <div class="formContent" id="divCheckInSubmit">
    <div class="formElement">
      <button id="btnCheckInSubmit" class="btnSubmit">Add Customer</button>
    </div>
  </div>
</div>
<!-- the script is included here -->
<!-- <script src="../js/addCustomer.js" defer></script> -->

The code I want to work, works if I comment out the JQuery for the bulksubmit, but if it is still in there, the checkinsubmit button’s eventlister for “click” does not fire.

Cannot import JS library opus-recorder in TypeScript project

In my Vite TypeScript React application I’m trying to import the Opus Recorder library (https://www.npmjs.com/package/opus-recorder).

I have set this flag in tsconfig.json:

  "compilerOptions": {

    "allowJs": true,

and imported this library in my index.tsx in this way:

import * as opus from '../../../node_modules/opus-recorder/dist/recorder.min.js';

but when I try to invoke the constructor:

const recorder = new opus.Recorder({ encoderSampleRate: 44100 });

I get TypeError: opus.Recorder is not a constructor.

I also created a type declaration file in types/index.d.ts:

declare module 'opus-recorder' {
  // Recorder Configuration Interface
  interface RecorderConfig {
    bufferLength?: number;
    encoderApplication?: number;
    encoderFrameSize?: number;
    encoderPath?: string;
    encoderSampleRate?: number;
    maxFramesPerPage?: number;
    mediaTrackConstraints?: boolean | MediaTrackConstraints; // Allow flexible input
    monitorGain?: number;
    numberOfChannels?: number;
    recordingGain?: number;
    resampleQuality?: number;
    streamPages?: boolean;
    wavBitDepth?: number;
    sourceNode?: { context: AudioContext | null } | MediaStreamAudioSourceNode;
  }

  // Recorder Class
  class Recorder {
    // Static Methods
    static isRecordingSupported(): boolean;

    // Constructor
    constructor(config?: RecorderConfig);

    // Instance Properties
    state: "inactive" | "loading" | "recording" | "paused";  // Possible states
    config: RecorderConfig;
    encodedSamplePosition: number;

    // Instance Methods (simplified for brevity)
    initAudioContext(): void;
    initWorklet(): Promise<void>;
    initEncoder(): Promise<void>;
    initialize: Promise<void>; // Combined promise for initWorklet & initEncoder
  }

  export default Recorder;
}

but I get the same error.
Can someone please help me?

Allowing once to use the microphone on Google Chrome multiple times

I have the following piece of code that has two textareas and two buttons. Each button controls its own text area. Once started, the script listen to the audio and when finished fills the textarea with the transcription of the audio listened. The problem is: every time the button is clicked, Google Chrome asks for permission to use the microphone. Is there a way to make this request happen only once?

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transcrição de Áudio</title>
    <style>
        textarea {
            width: 100%;
            height: 150px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <textarea id="transcription1" placeholder="A transcrição aparecerá aqui"></textarea>
    <button id="startStopBtn1">Iniciar/Parar Transcrição 1</button>
    <textarea id="transcription2" placeholder="A transcrição aparecerá aqui"></textarea>
    <button id="startStopBtn2">Iniciar/Parar Transcrição 2</button>

    <script>
        let isRecording1 = false;
        let isRecording2 = false;
        let recognition1;
        let recognition2;
        let silenceTimer1;
        let silenceTimer2;
        let hasPermission1 = false;
        let hasPermission2 = false;

        const startStopBtn1 = document.getElementById('startStopBtn1');
        const transcriptionInput1 = document.getElementById('transcription1');
        const startStopBtn2 = document.getElementById('startStopBtn2');
        const transcriptionInput2 = document.getElementById('transcription2');

        // Função para inicializar o reconhecimento de fala
        function initRecognition(recognition, transcriptionInput, silenceTimer) {
            recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
            recognition.continuous = true;
            recognition.interimResults = true;
            recognition.lang = 'pt-BR';

            recognition.onresult = (event) => {
                clearTimeout(silenceTimer);
                let interimTranscript = '';
                for (let i = event.resultIndex; i < event.results.length; ++i) {
                    if (event.results[i].isFinal) {
                        transcriptionInput.value += event.results[i][0].transcript + 'n';
                    } else {
                        interimTranscript += event.results[i][0].transcript;
                    }
                }
            };

            recognition.onspeechend = () => {
                resetSilenceTimer(recognition, silenceTimer);
            };

            recognition.onerror = (event) => {
                console.error('Erro no reconhecimento de fala:', event.error);
                stopRecording(recognition, silenceTimer);
            };

            return recognition;
        }

        // Inicializar reconhecimento de fala ao clicar no botão pela primeira vez
        startStopBtn1.addEventListener('click', () => {
            if (!hasPermission1) {
                hasPermission1 = true;
                recognition1 = initRecognition(recognition1, transcriptionInput1, silenceTimer1);
            }
            toggleRecording(recognition1, startStopBtn1, transcriptionInput1, silenceTimer1, isRecording1);
        });

        startStopBtn2.addEventListener('click', () => {
            if (!hasPermission2) {
                hasPermission2 = true;
                recognition2 = initRecognition(recognition2, transcriptionInput2, silenceTimer2);
            }
            toggleRecording(recognition2, startStopBtn2, transcriptionInput2, silenceTimer2, isRecording2);
        });

        function toggleRecording(recognition, button, transcriptionInput, silenceTimer, isRecording) {
            if (isRecording) {
                stopRecording(recognition, silenceTimer);
                button.textContent = "Iniciar Transcrição";
            } else {
                startRecording(recognition, button, transcriptionInput, silenceTimer);
                button.textContent = "Parar Transcrição";
            }
            isRecording = !isRecording;
        }

        function startRecording(recognition, button, transcriptionInput, silenceTimer) {
            recognition.start();
            resetSilenceTimer(recognition, silenceTimer);
        }

        function stopRecording(recognition, silenceTimer) {
            recognition.stop();
            clearTimeout(silenceTimer);
        }

        function resetSilenceTimer(recognition, silenceTimer) {
            clearTimeout(silenceTimer);
            silenceTimer = setTimeout(() => {
                stopRecording(recognition, silenceTimer);
            }, 5000);
        }
    </script>
</body>
</html>

I have no idea on how to deal with that problem. I’d like to allow only once and somehow keep the permission valid

React UI not updating when React a property of React object state changes

I have a component that uses an object as the state. The object is passed in as a prop. The problem is, I have an input field where there is a cancel button. When the user clicks on the cancel button, I discard all the handleChange events which is saved on the local component state, then just reuse the original prop that was passed in. The text in the input field however, does not reset to the original value and keeps the value that was with the change event.

// Prop structure myObjProp
{id: '', inputText: 'Original String Val'}

const MyComponent = ({myObjProp}) => {
  const [objState, setObjState] = useState({...myObjProp})
  const {id, inputText} = objState

  const handleChange = (e) => setObjState({...objState, inputText: e.target.value})
   
  const handleCancel = () => setObjState(myObjProp) // Should reset `inputText` back to `Original String Val`
  

  return (
    <div>
      <input onChange={handleChange} />
      <button onClick={handleCancel} defaultValue={inputText} >Cancel</button>
    </div>
  )
}

As an example, when the component first loads, the text in the input will be Original String Val. When I then start typing and the input value is something like Original String Val Changed, after I click the Cancel button, the text in the input should be Original String Val which is the original value from the prop and I set in the cancel handler, but text does not revert back and stays as the new text I just typed Original String Val Changed

Batch converting 1000’s of .fla files to .png in Adobe Animate

I need to convert thousands of assets from .fla to .png the bulk of which are not animated (id like to do the animated ones as png spritesheets if possible). Is there any way to automate this process in Adobe Animate so I don’t have to do this manually?

I have searched a ton but the closest I’ve found is a code snippet on the adobe help website from 2017 for doing a similar thing with SVGs but I’m not sure how to implement it or modify this as I don’t know javascript.

Puppetter – Read the value of CDPJSHandle {}

I am just trying to scrap something from a website.

I am running into a problem when trying to access the value of a property that is on an element. The value returns CDPJSHandle {} instead of the object that I expect.

    const element = await page.$('canvas');
    const properties = await element.getProperties();
    const [firstKey]  = await properties.keys();
    const propertyValue = await element.getProperty(firstKey);

    console.log({
      element,        // CDPElementHandle { handle: CDPJSHandle {} },
      properties,     // Map(1) { 'jQuery3700346878389459100542' => CDPJSHandle {} },
      firstKey,       // 'jQuery3700346878389459100542',
      propertyValue,  // CDPJSHandle {}
    });

This jQuery3700346878389459100542 is a custom property attached to this html element. I can access the property via the browser with document.querySelector('canvas').jQuery370058052487285485872; which returns the object that I expect.

I know that a similar question has been asked here, which will work if I’m referencing a native HTML element property. However my scenario differs as I’m looking for a custom property.

const evaluatedValue = await element?.evaluate((el, firstKey) => el[firstKey], firstKey);
const evaluatedTextValue = await element.evaluate(el => el.id);

console.log({
  evaluatedValue, // undefined
  evaluatedTextValue, // 'n                        '
});

How can I access this property correctly?

How to use a inject button inside of a chrome extension to inject code into the current tab?

I’ve tried a lot of resources to fix my issue, but everything I’ve found is about instantly injecting the code once the user has entered the site; not when a button is pressed to inject the code.

I tried videos, posts and research – nothing worked. I was expecting for my inject button to run the code entered into a textbox e.g. ‘console.log(‘demo’);’.

Why do Bootstrap Table extensions use class inheritance instead of modifying the prototype?

I’m currently studying the jQuery bootstrap-table plugin and I’ve noticed something that I don’t fully understand. In the main bootstrap-table.js file, they instantiate a BootstrapTable class and assign it to $.BootstrapTable, which makes sense to me.

However, for extensions, they do the following:

$.BootstrapTable = class extends $.BootstrapTable {
  // extension code
}

This creates a new JavaScript file with the entire BootstrapTable class and the additional extension code. This approach seems to create two large JavaScript files with duplicate definitions of the class.

Wouldn’t it be more efficient to modify the prototype of the class directly to avoid code duplication? For example:

BootstrapTable.prototype.newFunction = function() {
  // new function code
}

Additionally, by storing the old method in a variable and calling it within the new function, we can preserve the extensions that precede us. For example:

const oldExistFunction = $.BootstrapTable.prototype.existFunction;
$.BootstrapTable.prototype.existFunction = function() {
  oldExistFunction.call(this);
  console.log('This is the new existFunction.');
}

By doing this, we wouldn’t have duplicated class definitions. Are there specific reasons for choosing class inheritance over prototype modification in this context? What are the advantages and disadvantages of each approach?

I appreciate any insights or explanations you can provide. Thank you!

What I tried:
I tried modifying the prototype directly and storing the old method in a variable before redefining it. I expected this to avoid code duplication and maintain the previous extensions’ functionality.

What I expected:
I expected that modifying the prototype directly would be a more efficient way to add new functionality without duplicating the entire class definition.

What actually happened:
While modifying the prototype worked as expected in my tests, I’m wondering if there are specific reasons why the bootstrap-table plugin developers chose to use class inheritance instead. Are there particular advantages or use cases that make inheritance a better choice in this context?