Scrapping web site

How can I get with email, I get null

I need to output an email to the console

const Nightmare = require('nightmare')
const nightmare = Nightmare({show: false})


nightmare
    .goto("https://www.experte.com/spam-checker")
    .evaluate(
        () => document.querySelector("#\36 76779091 > spam-checker > div > div > div > div:nth-child(1) > div.card.border.border-neutral-300.rounded.flex.align-middle.w-80.mt-4 > input")
    )
    .end()
    .then(res => {
        console.log(res);
    })
    .catch(e => {
        console.error(e);
    });

Delayed read performance when using navigator.serial for serial communication

I’ve been trying out the web serial API in chrome (https://web.dev/serial/) to do some basic communication with an Arduino board. I’ve noticed quite a substantial delay when reading data from the serial port however. This same issue is present in some demos, but not all.

For instance, using the WebSerial demo linked towards the bottom has a near instantaneous read:

enter image description here

While using the Serial Terminal example results in a read delay. (note the write is triggered at the moment of a character being entered on the keyboard):

enter image description here

WebSerial being open source allows for me to check for differences between my own implementation, however I am seeing performance much like the second example.

As for the relevant code:

this.port = await navigator.serial.requestPort({ filters });

await this.port.open({ baudRate: 115200, bufferSize: 255, dataBits: 8, flowControl: 'none', parity: 'none', stopBits: 1 });
this.open = true;
this.monitor();

private monitor = async () => {
    const dataEndFlag = new Uint8Array([4, 3]);
    while (this.open && this.port?.readable) {
        this.open = true;
        const reader = this.port.readable.getReader();
        try {
            let data: Uint8Array = new Uint8Array([]);
            while (this.open) {
                const { value, done } = await reader.read();
                if (done) {
                    this.open = false;
                    break;
                }
                if (value) {
                    data = Uint8Array.of(...data, ...value);
                }
                if (data.slice(-2).every((val, idx) => val === dataEndFlag[idx])) {
                    const decoded = this.decoder.decode(data);
                    this.messages.push(decoded);
                    data = new Uint8Array([]);
                }
            }
        } catch {
        }
    }
}

public write = async (data: string) => {
    if (this.port?.writable) {
        const writer = this.port.writable.getWriter();
        await writer.write(this.encoder.encode(data));
        writer.releaseLock();
    }
}

The equivalent WebSerial code can be found here, this is pretty much an exact replica. From what I can observe, it seems to hang at await reader.read(); for a brief period of time.

Has anyone experienced this same scenario?

Merge Sort solution with a for loop that is not O(n2) – JavaScript

The solution that I came up with for merge sort uses while loops, because I know it will avoid the time complexity of O(n2). I’ve also seen that a lot of the solutions that have the best time complexity uses the while loop.

I wanted to know if there’s a solution where you can avoid the O(n2) time complexity using the for loop instead of the while loop.

Thanks!

Extracting data from multipart/x-mixed-replace content-type

If I do have the velow html5 element:

<div>
    Counter: <span id="content"></span>
</div>

And my server is returning a counter, I can listen to this counter, and display it at the above element as:

var source = new EventSource("http://localhost:8080/counter");
   source.onmessage = function (event) {
   var data = JSON.parse(event.data);
   document.getElementById("content").innerHTML = counter;
}

But what if the server is sending me a multipart/x-mixed-replace, how can I receive it in the JavaScript code, and display its content in a div or ‘objector evenimage`, the server is expected to send me multiple images that can be displayed as video streaming.

I saw this but could not understand how to do it in JavaScript at browser.

Pure JavaScript please.

Note: I was able to do it as:

<object data="http://localhost:8080/camera" width="300" height="200" alt="Cam streaming"></object>

But I prefer using SSE (Server-Sent-Event) to do it.

How to make sure my database object is created and available before anything else?

I’m using rxdb to store my data and would like to use databaseController.ts which creates the database object and export query methods which the React components can use. To achieve that I must assure that the database object has been created before anything else. Because right now I get the error TypeError: Cannot read properties of undefined (reading 'contracts') if I try to use getAllNewContractsQuery(). How can I make sure that my database object is available?

databaseController.ts

/* omitted imports etc. */

let db;

export async function initDB() {

  await createDatabase();
    await db.addCollections({
      contracts: {
        schema: contractsSchema,
        methods: contractDocMethods,
        statics: contractsCollectionMethods,
      },
    });

  return db;
}

async function createDatabase() {

  db = await createRxDatabase<DatabaseCollections>({
    name: 'contractsdb',
    storage: getRxStoragePouch('idb'),
    multiInstance: true,
    ignoreDuplicate: false
  });

}

export async function getAllNewContractsQuery() {
  const query = await db.contracts.find().where('customerName').eq('Luke Cage')
  console.log(await query.exec())
}

export { db }

App.tsx

/* omitted imports etc. */

export default function App() {

  useEffect(() => {
    const initDBEffect = async () => {
        await initDB()
    }
    initDBEffect()

  }, [])

  return (
    <Provider store={store}>
      <Router>
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route index element={<ContractManager />} />
          </Route>
        </Routes>
      </Router>
    </Provider>
  );
}

contractManager.tsx

const ContractManager = () => {
  
  useEffect(() => {
    const newContracts = async () => {
      await getAllNewContractsQuery()
    }

    newContracts()
  }, [])

  /* omitted code */
}

How to Push React-App to Github with a Different Port

I am having a difficulty pushing my react app to its own repo on github. I have a project that runs on localhost:5000 and when I push it to github, its shares the same folder with another project with localhost:3000 (The default port for react is 3000. The app on port:5000 ends up sharing the same repo/folder with the app on port:3000), and when I publish to github pages, the other project originally on localhost:3000 shows up.

How do I make the project on port:5000 exist as a repo (not share the same folder as the project on post:3000)

Any help will do

Jest coverage – folder report and cli table

My coverage settings create a coverage folder but doesn’t create a coverage synopsis on the terminal at the end of the run. How do I get both the full coverage folder and the synopsis on the CLI?

// jest.config.ts
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  clearMocks: true,
  moduleFileExtensions: ["js", "ts", "json", "node"],
  roots: ["./"],
  testMatch: ["./**/*.test.ts"],
  preset: "ts-jest",
  testEnvironment: "node",
  runInBand: true,
  detectOpenHandles: true,
  testTimeout:20000,
  forceExit: true,
  verbose: true,
  json: true,
  outputFile: "./test-log/jest-log.json",
  transform: {
    "^.+\.ts?$": "ts-jest",
  },
  transformIgnorePatterns: [
    "./node_modules/",
    "./dist/",
    "./files/",
    "./public/",
  ],
  extensionsToTreatAsEsm: [".ts"],
  globals: {
    "ts-jest": {
      tsconfig: "./tsconfig.json",
      useESM: true,
    },
  },
  collectCoverage: true,
  collectCoverageFrom: ["./src/**"],
  coverageThreshold: {
    global: {
      lines: 30
    }
  },
  coverageReporters: ["json", "html"],
};
//package.json test script
"test": "npm run clear && cross-env-shell TS_JEST_LOG=test-log/ts-jest.log NODE_OPTIONS=--experimental-vm-modules jest",

How to print the selected checkbox values after submit

Here is the my checkbox list and the button which I need to submit the data..

<label>Access Locations </label>
     <br />


     <input type="checkbox" name="chk[]" id="check1" class="pl" value="INT" /> dummy1
     <input type="checkbox" name="chk[]" id="check2" class="pl" value="MV" /> dummy2
     <input type="checkbox" name="chk[]" id="check3" class="pl" value="FV" /> dummy3
     <input type="checkbox" name="chk[]" id="check4" class="pl" value="PS" /> dummy4

     <br />
     <h4 name ="checkboxvalues" style="color:green" id="result_checkbox"></h4>  
    
     <input type="hidden" name="employee_id_update" id="employee_id_update" />
     <input onclick="getCheckboxValue()" type="submit" name="insert" id="insert" value="Update" class="btn btn-success" />

I am using below class when button clicked..

function getCheckboxValue() {

var l1 = document.getElementById("check1");
var l2 = document.getElementById("check2");
var l3 = document.getElementById("check3");
var l4 = document.getElementById("check4");

 
var res=" "; 
if (l1.checked == true){
  var pl1 = document.getElementById("check1").value;
  res = pl1 + ","; 
} 
else if (l2.checked == true ){
  var pl2 = document.getElementById("check2").value;
  res = res + pl2 + ","; 
}
else if (l3.checked == true){
document.write(res);
  var pl3 = document.getElementById("check3").value;
  res = res + pl3 + ","; 
}
else if (l4.checked == true){
  var pl4 = document.getElementById("check4").value;
  res = res + pl4 + ","; 
}

return document.getElementById("result_checkbox").innerHTML = "You have selected " + res ;

}

From above method I could see only one value in checkboxvalues as in the image when button clicked eventhough I have checked several checkboxes.

enter image description here

Can someone show me how to improve my code to show all the values when I checked several checkboxes?

If both check1 and check2 selected output should be

Output:

 You have selected INT,MV

how to upload a safari extension to app store

This is my first time uploading anything to the apple store and i might be missing something because I am building a safari extension and while using xcode and after creating the archive, when i click on upload to app store i get the following error:

enter image description here

(My developer account is currently active and paid)

I read online that some configuration need to be done on the profile and certificate.

I created:

  • a certificate but its not linked to my keychain on the computer (is this required?)
  • an identifier and thats the one that i am using on xcode as bundle identifier.
  • an app on app store connect with all the details needed for the extension.

is there something that i am missing in the process and if anyone is familiar with the error attached, how can i possibly upload my extension to the apple store?

Infinite loop of useEffect with empty dependency array

code running correctly while in fulfilled case of extraReducer isLoading’s state is not used

const fetchMovies = createAsyncThunk(
  'movies/fetchMovies',
  async (movieTitle) => {
    const newMovies = await searchApi.findMovie(movieTitle)
    return newMovies
  }
)

extraReducers: (builder) => {
    builder
      .addCase(fetchMovies.pending, (state, action) => {
        state.isLoading = true
      })
      .addCase(fetchMovies.fulfilled, (state, action) => {
        state.isLoading = false // running an infinite loop
        }
      })
useEffect( () => {
    dispatch(fetchMovies(movieTitle))
  }, [])

How to auto update cryptocurrency prices using coingecko api in react js

I’m new to react and want to create a crypto price tracker using coingecko api. I fetched the data and displayed it correctly but it don’t update on it’s own. When I reload the page then the data is updated. So, I used this code I found on internet

<meta http-equiv="refresh" content="30">

This code works fine but the user experience is so bad with this.

Is there any way I can fix it. I want it to work just like we usually see in crypto exchange app.

html/css: Making a table element inside of a button selectable

I have an element that looks as following (https://jsfiddle.net/e176dosp/1/):

<button>
  My Button
  <table>
    <thead align="left">
    <tr>
      <th>Category</th>
      <th>Value</th>
    </tr>
    </thead>
    <tbody align="left">
    <tr>
      <td>Soil group</td>
      <td>Cambisols</td>
    </tr>
    </tbody>
  </table>
</button>

I would like to be able to have the table element be separate from the button, meaning that I can click on the My Button text to press the button but also select the text from the table below, while still having the table be part of the button class. I have tried to find ways with javascript and css to “undo” the button class in the table element, or to find classes that override the button onclick behaviour but only found solutions on how to remove css classes that are not inbuilt, such as button or table.

for of loop return same item multiple times api double fetch

In the first for of loop I get 10 different results as expected. in the second for loop when i call it it gives me 10 times the same result.
why this happens and how do i fix it?

 const inputValue = document.getElementById("searchbarInput").value;
 const searchUrl = `https://stock-exchange-dot-full-stack-course-services.ew.r.appspot.com/api/v3/search?query=${inputValue}&limit=10&exchange=NASDAQ`;

const options = {
filter: '',
sort: 1}
async function displaydata() {
let url = searchUrl;
let response = await fetch(url);
let data = await response.json();

//log company info

const mappedList = data.map((x) => ({
    name: x.name,
    symbol: x.symbol,
    ceo: x.ceo
}))


for (let info of mappedList) {
    const companyInfo = await fetchMoreInfo(info.symbol);
    ceo = companyInfo.profile.ceo; // here returns a 10 different items
}

document.getElementById('root').replaceChildren();

for (comp of mappedList) {
    const div = document.createElement('div');
    div.innerHTML = `<a href="/company.html?symbol=${comp.symbol}">${ceo} ${comp.name}(${comp.symbol})</a>` + "<br>";
    document.getElementById('root').appendChild(div); //here it gives me the same  10 itmes}}

const fetchMoreInfo = async(companySymbol) => {
let url = `https://stock-exchange-dot-full-stack-course-services.ew.r.appspot.com/api/v3/company/profile/${companySymbol}`;
let response = await fetch(url);
let compData = await response.json();
return compData;

}