Exit $(‘input[name^=”myname”]’).each( function() {

I need to exit the javascript but am getting something odd.

There is an array of inputs that this uses.

When the “if” statement is true and “return true” or “return false” is to run, the alert(‘something’) runs and I see the pop-up.

The script continues to execute.

I don’t know if it stills executes the “..each” loop. Do you?

This needs to exit the .each loop and script entirely.

If no checkbox is false, then run the alert code outside the …each(function()…

<input type="checkbox" id="a" name="test[]" onclick="myfunction('a');" />
<input type="checkbox" id="b" name="test[]" onclick="myfunction('b');" />
<input type="checkbox" id="c" name="test[]" onclick="myfunction('c');" />

and the script…

<script>
function myfunction(instuff) {
    $('input[name^="test"]').each(function() {
        if ($(this).prop('checked')  == false) {
            //...run code...
            return true; //return false; acts the same.
        }
    )}
    //...run other code...
    alert('something');
}
</script>

Any suggestions is appreciated.

Can I use mix-blend-mode: color-dodge css property to manipulate redrawed image in CANVAS using javascript?

Hi so I’m trying to convert an image to sketch-like-image before uploading it to the server, the uploading part is not the problem, the conversion of image to sketch-like-image is. I failed to search a js library that will help me achieve this, and then I found this https://www.freecodecamp.org/news/sketchify-turn-any-image-into-a-pencil-sketch-with-10-lines-of-code-cf67fa4f68ce sample code in python then tried to recreate it using CSS only and I got it correctly using the CSS code below

filter: grayscale(100%) invert(100%) blur(5px);
mix-blend-mode: color-dodge;

Then after that I tried to recreate it in Vanilla Javascript using CANVAS API because I needed the image to be uploaded in the server that looks like a sketch-like-image, but got stuck in the process here are the stages of the conversion I’m doing see image below enter image description here

I got stuck in the stage 4, I can’t proceed with the stage 5, which is globalCompositeOperation = 'color-dodge'; when color-dodge applied to CANVAS API, to remove the blur and make it look like an sketch-image

  • stage 1 is the raw image
  • stage 2 is grayscale(100%) working in javascript CANVAS API
  • stage 3 is invert(100%) working in javascript CANVAS API
  • stage 4 is blur(5px) working in javascript CANVAS API
  • stage 5 globalCompositeOperation = 'color-dodge' which is equivalent of CSS’ mix-blend-mode: color-dodge; not working in javascript CANVAS API

and here’s my Javascript code below

  let img = document.createElement('img');
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d');
  ctx.filter = 'grayscale(100%) invert(100%) blur(5px)'; // stages 2,3,4 is working
  ctx.globalCompositeOperation = 'color-dodge'; // stage 5 not working
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

Ok so I think that’s a lot so here’s a snippet of it for you guys to test it out. https://codepen.io/ohyeahhu/pen/MWQRweP

also if you guys know a JS library or tools that might help me achieve this feat, I’m very open to any suggestions.

note: only in javascript or any js library

Twitch Prime Gaming API

I’m developing a Discord bot using Typescript. I implemented a command to get Epic Games free games of the week (and next one) thanks to this NPM package. I was wondering if there is some npm package for Twitch Prime Gaming, which has some free games periodically. I just see Twitch API to let people when you go live, for the chat and whatever, but couldn’t find anything about Prime Games. Have you any suggestions to get those games using API?

Calling Javascript function Error function is not defiend [closed]

I have this app that uses OCR to read image text and convert it to JSON array then write it to an HTML table and export it as an Excel Worksheet by using phpspreedsheet the app was working so far so good until I played around it and missed up something after that Javascript function is not working anymore so it should work to write the table content to an Excel file by [Change.php]

prepare.js

function readFile(fileName) {
  console.log({ fileName });

  return await Tesseract.recognize(fileName, 'ara', {
  
    logger: m => console.log(m)
  });

}
function parseDataFromTextAndPropertyNames(text, propertyNames) {
  console.log({ text, propertyNames });

  return propertyNames
    .reduce((table, key) =>
      Object.assign(table, {

        [ key ]: RegExp(`${ key }\W+(\w+)`)
          .exec(text)?.[1] ?? ''

      }), {});
}
function writeParsedTextDataAsJSON(fileName, table) {
  console.log({ table });
   JSON.stringify({ table });

  // fake it ...
  return (await new Promise(resolve =>
    setTimeout(() => {

      console.log({ fileName, json: JSON.stringify({ table }) });
      resolve({ success: true });

    }, 1500)
  ));
}

console.log('... running ...');

function start(filenames) {
  const { data: { text } } = await readFile(filenames);

  const data = await
    parseDataFromTextAndPropertyNames(text, ['نقطة الخدمة', 'رقم العداد']);
 document.getElementById("dvjson").innerHTML = JSON.stringify(data, undefined, 4);
 const final = [JSON.stringify(data)];
 const ff = [JSON.parse(final)];
 constructTable('#table',ff);
 htmlstring = getElementById('table').innerHTML();
$.post('change.php', {string:htmlstring}).done(function(response){
      alert("done");
});
  console.log({ result });
}

prepare.php

<script src='scriptsprepare.js'></script>
<?php
if (!empty($target_file)){
    echo '<script>start("'.$target_file.'")</script>';
}
?>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.2/xlsx.full.min.js"></script>
    <script src='https://unpkg.com/[email protected]/dist/tesseract.min.js'></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
    <link rel="stylesheet" href="stylemain.css">
    <script src="https://kit.fontawesome.com/bd514e8cb4.js" crossorigin="anonymous"></script>
    <script src='excelexportjs.js'></script>
</head>

<body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
    <center>
        <div id="loadspinne" style="width: 12rem; height: 12rem; color:#0A9ACD;" class="spinner-border" role="status"></div>
        </div>
        <div class="animate__animated animate__backInDown mx-auto d-block" style="display:none !important;" id="message">
        <h4 style="font-family:Hana; font-size:32px; font-weight:bold;">تم تكوين كشف بنجاح</h4>
        </div>
    </center>
    <div class="container mt-5 ">
    <div style="display:none;" id="dvjson"></div>
    <table align="center" id="table"  border="1" style="display:none;"></table>
    </div>
</body>
</html>

change.php

<?php
require 'vendor/autoload.php';

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
use PhpOfficePhpSpreadsheetReaderIReader;
$htmlString = $_GET['htmlstring'];

$reader = new PhpOfficePhpSpreadsheetReaderHtml();
$spreadsheet = $reader->loadFromString($htmlString);

$writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('ddd.xls'); 

$spreadsheet = PhpOfficePhpSpreadsheetIOFactory::load("ddd.xls");

$sheet = $spreadsheet->getActiveSheet();
$sheet->getColumnDimension('A')->setAutoSize(false);
$sheet->getColumnDimension('B')->setAutoSize(false);
$sheet->getColumnDimension('A')->setWidth(16);
$sheet->getColumnDimension('B')->setWidth(13);

$sheet->getStyle('A1:B1')->getFont()
    ->setName('Arial')
    ->setSize(14)
    ->setBold(true);
$writer = new Xlsx($spreadsheet);
$writer->save('ddd.xlsx');
// header('Location: ddd.xlsx');
?>

Import function only (not entire file stack) into Angular from vanilla JavaScript

The Challenge

I am working on an Electron/Angular app that will display an emergency message to multiple computers in the event of a tornado or other incident. To accomplish this, I am using a WebSocket protocol (Signral R) on the backend to send the alert, which then triggers Electron’s main.js (running in the background) to launch a window on any devices running the app.

The arrival of the message triggers the window to launch, but I also need to use the message in the Angular part of the app (which does not initialize until after the window is open) to indicate the nature of the emergency. To avoid timing problems, I planned to import a function into my app.component.ts that would be called at ngOnInit to retrieve an emergency variable from main.js.

The Problem

Angular does not like the import from raw JavaScript. Intuitively you would think Angular would only import the exported class. However it appears to try and import Electron as well (generating a conflict with ‘fs’ and ‘path’ that is explained here), generating the following error message:

./node_modules/electron/index.js:1:11-24 - Error: Module not found: Error: Can't resolve 'fs' in 'C:Usersmeelectron-appnode_moduleselectron'

./node_modules/electron/index.js:3:13-28 - Error: Module not found: Error: Can't resolve 'path' in 'C:Usersmeelectron-appnode_moduleselectron'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
        - install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "path": false }

In spite of doing considerable research, I have not found anything approaching a solution. Any ideas for only importing the information I want would be much appreciated. Here are my files:

main.js (simplified somewhat)

const signalR = require("@microsoft/signalr")
const { app, shell, BrowserWindow, Menu, nativeImage, Tray } = require('electron')
const path = require("path");
const url = require("url");

//various setup logic goes here
//...

webSocketConnection.on("EmergencyActivation", (jsonData) => {
    createElectronWindow();
    const emergencyMessage = jsonData
});

module.exports = class Emergency {
    getEmergency() {
        return emergencyMessage
    }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import  { Emergency } from './../../main';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private emergency: Emergency) {}

  ngOnInit() {
    console.log(this.emergency.getEmergency())
  }
}

How do I get uploaded image in next js and save it,

How do I get uploaded image in next.js API route and save it on public folder? I have front end ready. I’m uploading images to an endpoint using plain JavaScript.
here is the onSubmit function for uploading images. Suggest me if I’m doing it wrong here. The main question is how do I retrieve it?

  const onSubmit=async(e)=>{ 
        e.preventDefault();
        const fd=new FormData()
        fd.append('myfile',image.name)
        let res=await fetch(`http://localhost:3000/api/upload`,{
            method: 'POST',
            headers: {
              "Content-Type": "image/jpeg",
            },
            body: fd,
          })
           let response=await res.json(); 

one more bonus question, it’s surely not a good idea to save the uploaded images on public folder. I have save it somewhere on the cloud.

Using the logistic map for a true/false chaotic behaviour

Hi is there any way to use the logistic map in a javascript function to get an unstable chaotic true/false return? I would like to have some function in my code that takes an iteration index as an input and produce a true/false statement following the logisic map behaviour with maybe some config (like r value, so if it’s near 4 you get more unstable behaviour while if you’re near r= 2 you get more stble results). I don’t want it to be a randomic true or false I want it to be cahotic like it follows a pattern that looks random but is not.

If you have any suggestion on how I can use the bifurcation diagram to do that it would be greatly appreciated!

Trying to add string starting from the right going to the left in a specific area

I’ve been trying to figure out how to add period as a string in a certain place, here’s the code

function fixBalance(amount){
  if(amount <= 99999999){
    var amt = "0." + amount.toString().padStart(8, "0");
    return Number(amt);
  } else {
    return false;
  }
}

console.log(fixBalance(1));
console.log(fixBalance(1000));
console.log(fixBalance(10000000));
console.log(fixBalance(1000000000));

Basically, there are 8 spaces to the right of the 0

After it passes 8 numbers, I want numbers to keep going past the period

For example:

1 = 0.00000001

1000 = 0.00001000 or 0.00001

10000000 = 0.10000000 or 0.1

1000000000 = 10.00000000 or 10

If I were to put in 1000000000, it should be 10.00000000 or 10 as a numerical number

Trying to figure out how to do that with the else statement

Thank you!

simplest way to send a message from a browser JS to a phone

I have an unmanned task that is executed in browser, by JS

I would need to know on my phone when it terminates, since I left the browser open maybe for hours and go away.

I don’t care about the specific method: SMS, tweet, alert, telegram would be the same, but it should be:

  • free of charge
  • fast and easy to setup few lines of code, possibly without server side

which solution can I implement?

NOTE: I already know is weird and inefficient to run unmanned tasks in a browser, it should be nicer on server side, but is ok for my circumstances

Unbounce not pre-filling Calendly

I would like to pre-fill the Calendly form in my unbounce thank you page. I am using the Calendly advance embed options but the information is missing.

this is the URL:

https://try.demopage.com/demothankyou/?first_name=john&email=test%40gmail.com

<script>
    const params = (new  URL(window.location)).searchParams

    Calendly.initInlineWidget({
        url: 'https://calendly.com/d/dns-sg1-kc3/try-demo?hide_event_type_details=1&hide_gdpr_banner=1',
        prefill: {
            name: params.get('first_name'),
            email: params.get('email')
        }         
    });
 </script>
<!-- this is inside a HTML box in unbounce -->

<!-- Calendly inline widget begin -->
<div class="calendly-inline-widget" id="my-calendly-embed" data-url="https://calendly.com/d/dns-sg1-kc3/try-demo?hide_event_type_details=1&hide_gdpr_banner=1&email=email&name=first_name" style="min-width:320px;height:830px;"></div>
<script type="text/javascript" src="https://assets.calendly.com/assets/external/widget.js" async></script>
<!-- Calendly inline widget end -->

and I get Calendly not defined in the console

Thanks for any help!

Necesito ayuda con este ejercicio de JavaScript [closed]

const { LinkedList } = require(‘./DS’);
// No modifiques nada arriba de esta linea //

/*
EJERCICIO 2
Agregar el método simplifyList al prototipo de LinkedList. Este método deberá filtrar
los elementos repetidos de nuestra lista enlazada y crear una nueva lista con los elementos
extraídos para finalmente reemplazar la lista original.
Si la lista está vacía, debe retornar false
Ejemplo:
Suponiendo que la lista actual es: Head –> [2] –> [5] –> [1] –> [5] –> [7] –> [2] –> null
lista.simplifyList();
Ahora la lista resultante es: Head –> [2] –> [5] –> [1] –> [7] –> null
ACLARACIÓN: Se debe reemplazar la lista original por la nueva.
Pista: Podes usar el metodo search() ya incorporado dentro del prototype de LinkedList
*/

LinkedList.prototype.simplifyList = function () {
// Tu código aca:

}

ayuda no logro entender la consigna.

Why doesn’t the value of a state change in the same useEffect hook? [duplicate]

Imagine if I have this code:

const [example, setExample] = useState(false);

useEffect(() => {
  setExample(true);
  console.log(example);
}, []);

Why does it print out false instead of true? It also does this when I log it after an interval, e.g.:

setTimeout(() => console.log(example), 1000); // false

I’m sure there must be a reason to this, but I simply do not know that reason, and I can’t find anything about it online.

How to return a JSON object conditionally

Hi I’m working on a web App project and I have the following component that is returned by antd Menu object.

const items = [
        {
          label: <Link to='/register'>Register</Link>,
          key: 'register',
          icon: <UserAddOutlined />,
          style: { marginLeft: 1030},   // problem: hard-coded margin
        },
        {
          label: <Link to='/login'>Login</Link>,
          key: 'login',
          icon: <UserOutlined />,
          style: { marginLeft: 'auto'},
        },               
      ];

return <Menu mode="horizontal" items={items} />;

Now I have an object named user. If user is not null (which means there is a user who is logged in currently), I want to hide register in the above items object; otherwise I want to show ”’register”’ in the Menu. The Menu component will be looked like:
enter image description here

Can anyone help me with that? Thanks!