webcam barcode reader for javascript p5js

I'd like to combine two codes.

first code ————————————–
“””

barcode

Barcode: …


let image = new Image();
image.crossOrigin = “Anonymous”;
image.src = “https://finlandbarcodes.com/wp-content/uploads/sites/197/2013/09/07-EAN-13-Standard-300×196.jpg”;
image.onload = function () {
javascriptBarcodeReader({
image: image,
barcode: “ean-13”
// barcodeType: “interleaved”
})
.then((result) => {
document.getElementById(“barcode-title”).innerHTML = result;
})
.catch(console.log);
}

“””

second code ———————————

"""
<!DOCTYPE html>
<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>cam</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>
</head>
<body>
    <script>
        let cam;
        function setup() {
            createCanvas(400, 300);
            cam = createCapture(VIDEO);
            cam.size(400, 300);
            cam.hide();
        }

        function draw() {
            image(cam, 0, 0);
        }
    </script>
</body>
</html>
"""

**first code was https://www.npmjs.com/package/javascript-barcode-reader**      

*second code was p5js*        

*I'd like to combine two codes.*      

How to render a EJB in Angular from Node API

I have a ejb file and I’m rendering that file from Node.js Express API. I am trying to render that response in Angular. But I’m getting empty page while rendering the response. I have consoled the response where I could see the ejb code as response.

Code

Node.js

app.set('view engine', 'ejs')
app.get('/',function(req,res){    
  res.render('index')
});

Angular

Service

  getHomepage(): Observable<any> {
    return this.http.get('http://localhost:3000', { responseType: 'text' });
  }

TS

ngOnInit() {
    this.userService.getHomepage().subscribe(
      (data:(any)) => this.library = data 

    );
}

HTML

<div [innerHTML]="library"></div>

Getting this error in Next.js: “BSONTypeError: Argument passed in does not match the accepted types”

While getting the static props from mongodb using the findone method, the error gets shown:
“BSONTypeError: Argument passed in does not match the accepted types”
Why so?

import { MongoClient, ObjectId } from "mongodb";

import MeetupDetail from "../../components/meetups/MeetupDetail";

export default function MeetupDetails(props) {
  ...
}

export async function getStaticPaths() {
 ....
}

export async function getStaticProps(context) {
  const meetupId = context.params;

  const client = await MongoClient.connect(
    "mongodb://localhost:27017/academind_tutorial"
  );
  const db = client.db();

  const meetupsCollections = db.collection("meetups");

  const selectedMeetup = await meetupsCollections.findOne({ _id: ObjectId(meetupId) }); // the error shows on this line

  client.close();

  return {
    props: {
      meetupData: {
        id: selectedMeetup._id.toString(),
        title: selectedMeetup.title,
        address: selectedMeetup.address,
        image: selectedMeetup.image,
        description: selectedMeetup.description
      }
    },
  };
}

how to get server cpu and memory and disk percentage in node.js

var os  = require('os-utils');
os.cpuUsage(function(v){
    console.log( 'os-utils CPU Usage (%): ' + v ); 
    // os-utils CPU Usage (%): 0.11180382377389864
});
os.cpuFree(function(v){
    console.log( 'os-utils CPU Free:' + v );
    // os-utils CPU Free:0.8876135425268373
});

var osu = require('node-os-utils')
var cpu = osu.cpu
cpu.usage()
.then(info => {
    console.log('node-os-utils cpu.usage '+info)
    // node-os-utils cpu.usage 11.53
})
cpu.free()
.then(info => {
    console.log('node-os-utils cpu.free '+ info)
    // node-os-utils cpu.free 88.47
})

it’s so annoying.
Why is the os-utils value different from the node-os-utils value?
I need the CPU and disk memory values ​​of the server currently running node.js
-Current CPU usage** (percent)
-Available memory* (free/total)
-Available disk space (free/total)

Algorithm to find binary value of all cells in (n x n) Tic-tac-toe board?

I found this great answer by Gary C, which uses bitwise operators and minimal number of comparisons to check for a win in Tic-tac-toe. The only issue is that the value of each cell needs to be hardcoded at the start.

For example as he says that the cell[0][0] would be given the value of

100 0 000 0 000 0 100 0 000 0 000 100 0 000 0

where each group of 3 bits represents

row1 0 row2 0 row3 0 column1 0 column2 0 column3 0 diag 0 antiDiag 0

, and the following 0 acts as a padding (important for the rest of his solution).
This is due to the fact that cell[0][0] occupies the first position of row1, column1 as well as the diagonal.

This task, although cumbersome, is certainly doable for a 3×3 board, however the question arises how to do this for a general nxn board.

I assume that the inputs we will have to go off of are:
a)the row and column index of the cell.
b)the value of n, which tells us that each group must have n bits, and one additional bit for padding.

I understand that this is a very specific scenario in a very specific solution. However his answer is quite brilliant, and one cannot but wonder how to actually implement it all the way.
Half-answers and suggestions are also appreciated, as it will aid the discussion.

Localstorage setItem when click on and keep the content reveal even after reload page

I’m trying to localStorage setItem for this script to continue to show the content inside the DIV tag and keep it open even after refreshing the page. Now I got stuck and don’t know what to do to make it work.

In this code after clicking on the Click Toggle Div link, the content will reveal and I want it to continue to reveal even I reload the page or until I click on the Click Toggle Div link again.

var getTiming = function (elem) {
    var timing = 350;
    if (elem.classList.contains('show-fast')) {
        timing = 100;
    }
    if (elem.classList.contains('show-slow')) {
        timing = 2000;
    }
    return timing;
};

// Show an element
var show = function (elem) {

    // Get the transition timing
    var timing = getTiming(elem);

    // Get the natural height of the element
    var getHeight = function () {
        elem.style.display = 'block'; // Make it visible
        var height = elem.scrollHeight + 'px'; // Get it's height
        elem.style.display = ''; //  Hide it again
        return height;
    };

    var height = getHeight(); // Get the natural height
    elem.classList.add('is-visible'); // Make the element visible
    elem.style.height = height; // Update the max-height

    // Once the transition is complete, remove the inline max-height so the content can scale responsively
    window.setTimeout(function () {
        elem.style.height = '';
    }, timing);

};

// Hide an element
var hide = function (elem) {

    // Get the transition timing
    var timing = getTiming(elem);

    // Give the element a height to change from
    elem.style.height = elem.scrollHeight + 'px';

    // Set the height back to 0
    window.setTimeout(function () {
        elem.style.height = '0';
    }, 1);

    // When the transition is complete, hide it
    window.setTimeout(function () {
        elem.classList.remove('is-visible');
    }, timing);
  
  

};

// Toggle element visibility
var toggle = function (elem, timing) {

    // If the element is visible, hide it
    if (elem.classList.contains('is-visible')) {
        hide(elem);
        return;
    }

    // Otherwise, show it
    show(elem);

};

// Listen for click events
document.addEventListener('click', function (event) {

    // Make sure clicked element is our toggle
    if (!event.target.classList.contains('toggle')) return;

    // Prevent default link behavior
    event.preventDefault();

    // Get the content
    var content = document.querySelector(event.target.hash);
    if (!content) return;

    // Toggle the content
    toggle(content);

}, false);
.toggle-content {
    display: none;
    height: 0;
    opacity: 0;
    overflow: hidden;
    transition: height 350ms ease-in-out, opacity 750ms ease-in-out;
}



.toggle-content.is-visible {
    display: block;
    height: auto;
    opacity: 1;
}
<p>
  <a class="toggle" href="#example">Click Toggle Div</a>
</p>

<div class="toggle-content" id="example">
    This content reveals and setItem localStorage to keep this content revealed even after page reload or until I click on  <a class="toggle" href="#example">Click Toggle Div</a> again.
</div>

Get list of all the keys in an object

How to get a list of all the keys available in a JSON with a nested array.

    var data = {
        "Key1" : "Data1",
        "Key2" : "Data2",
        "Key3" : [
            {
                "Key3a" : "Data3a",
                "Key3b" : "Data3b"
            },
            {
                "Key3a" : "Data3a",
                "Key3b" : "Data3b"
            }
          ]
    }

As of now I’m getting all the keys without the index:

    (5) ['Key1', 'Key2', 'Key3', 'Key3.Key3a', 'Key3.Key3b']

But I want it like:

    (7) ['Key1', 'Key2', 'Key3', 'Key3[0].Key3a', 'Key3[0].Key3b', 'Key3[1].Key3a', 'Key3[1].Key3b']

Can anyone help me out here?

How can i get the values of Nouislider min and max range

How can i get the values of the min and max price? I tried using aria-valuenow and aria-valuemax but when i ddump my request nothing is being added? And i get this error:

count(): Argument #1 ($value) must be of type Countable|array, null given

My form

       <form method="POST" action="{{action('AppHttpControllersShoppageController@indexproduct')}}">
                               @csrf
                               <div id="slider-margin"></div>
                               <div class="d-flex">
                                   <div class="me-5"  id="slider-margin-value-min" aria-valuenow="min_price"></div>
                                   <div id="slider-margin-value-max"  aria-valuemax="max_price"></div>

                               </div>
                               <button type="submit">filter</button>
                           </form>

function in shoppagecontroller

public function indexproduct(Request $request) {
   // dd($request);
    $categories = Category::all();
    $brands = Brand::all();
    $sizes = Size::all();
    $query = Product::all();
    if($request->min_price && $request->max_price){

        $query = $query->where('price','>=',$request->min_price);
        $query = $query->where('price','<=',$request->max_price);
    }

    return view('frontend.shop', compact(['query','sizes','brands','categories']));
}

script nouislider

var marginSlider = document.getElementById('slider-margin');

noUiSlider.create(marginSlider, {
    start: [0, 2500],
    margin: 0,
    range: {
        'min': 0,
        'max': 2500
    }
});

var marginMin = document.getElementById('slider-margin-value-min'),
    marginMax = document.getElementById('slider-margin-value-max');

marginSlider.noUiSlider.on('update', function (values, handle) {
    if (handle) {
        marginMax.innerHTML = values[handle];
    } else {
        marginMin.innerHTML = values[handle];
    }
});

Change the H3 text color depends on value from database using Javascript

So, this is the line from the code.

PHP:

<div class="col">
    <h3 class="text-start name" style="font-size: 12px;color: var(--bs-secondary);" id="bizApproval"><?php echo $bizApproval ;?></h3>
</div>

which <?php echo $bizApproval ;?> this will get the value from database which either Pending, Approved, Banned but what I want is if its Pending the text color yellow, if Approved text color green and if Banned text color red.

pass parameter to click event of a class

I have this code

 <div style="float:left">
            <div class="d-inline "><i id="reply@{@item.Id}" class="bi bi-reply icon-cursor test-comment" onclick="CommentReply(@item.Id)"></i> </div>                            
        </div>

and js

 function CommentReply(id)
 {
    //to do something
 }

but I want to change to

  $(".test-comment").click(function () {
    //to do something

    // I need Id in here
})

how can I pass the Id paramter to test-comment click event?

Dynamically get variable and not data

I’ve encountered a problem that i don’t entirely know how to solve.
I have a function that returns an object, but i currently don’t know how to change the variable the object comes from.

My code currently looks like this:

    insert(path, data) {
        let validPath = this.valPath(path); // Returns an object
        // ...
        // Other code...
        // ...
        validPath  = new Map(left.concat([data], right));
    }

The last line in this function produces the error “Invalid assignment left hand side”
If i hardcode the variable into the command like so: this.renderList = new Map(left.concat([data], right));, it works fine. This poses the problem that the variable validPath isn’t always equal to the same variable.

For reference, here’s the valPath function:

 valPath(path) {
    let returnPath;

    if (path.toUpperCase() == 'ROOT') { 
        returnPath = this.renderList
    } else {
        let currNode = this.renderList

        const pathArr = path.split('.')
        pathArr.forEach(node => {
            try {
                currNode = currNode.get(node)
            } catch (error) {
                throw new this.error('path does not exist');
            }
        })
        if (currNode.data.constructor == Map) {
            returnPath = currNode.data;
        }
    }
    return returnPath;
}

Thanks for your feedback in advance.

How to drag points with it’s connecting line in html5 canvas?

Following is my code. I have face issue when I drag a point. The problem is that whenever I drag point all the line connect to one point. I need to have draggable points in a html5 Canvas. But I have a supplementary constraint: the 2 points must be linked by a line. When I drag a point, the line must be dynamically drawn, and still linked to the 2 points.

let points= [];
let drag_point= -1;
let pointSize= 6;
let canvas = document.querySelector("#myCanvas");
let w = canvas.width;
let h = canvas.height;

var ctx = canvas.getContext("2d");

            $("#myCanvas").mousedown(function (e) {
                var pos = getPosition(e);
                drag_point = getPointAt(pos.x, pos.y);
                console.log("pos", drag_point);
                if (drag_point == -1) {
                    // no point at that position, add new point
                    drawlines(pos.x, pos.y);
                    points.push(pos);
                }
            });
            $("#myCanvas").mousemove(function (e) {
                if (drag_point != -1) {
                    // if currently dragging a point...
                    var pos = getPosition(e);
                    //...update that.points position...
                    points[drag_point].x = pos.x;
                    points[drag_point].y = pos.y;
                    redraw(); // ... and redraw myCanvas
                }
            });
            $("#myCanvas").mouseup(function (e) {
                drag_point = -1;
            });
    function getPosition(event) {

                var rect = canvas.getBoundingClientRect();
                var x = event.clientX - rect.left;
                var y = event.clientY - rect.top;
                console.log(x, y);
                return { x: x, y: y };

            }
    function getPointAt(x, y) {
                for (var i = 0; i < points.length; i++) {
                    if (
                        Math.abs(points[i].x - x) < pointSize &&
                        Math.abs(points[i].y - y) < pointSize
                    )
                        // check if x,y is inside points bounding box. replace with pythagoras theorem if you like.
                        return i;
                }
                return -1; // no point at x,y
            }

        function    redraw() {

                ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas

                for (var i = 0; i < points.length; i++) {
                    // draw all points again
                    drawlines(points[i].x, points[i].y);
                }
            }

function drawlines(x, y) {
        
                drawImages(x, y);

                if (points.length > 0) {
                    var last = points[points.length - 1];
                    ctx.beginPath();
                    ctx.moveTo(last.x, last.y);
                    ctx.lineTo(x, y);
                    ctx.strokeStyle = "blue";
                    ctx.stroke();
                }

            }
            function drawImages(x, y) {
                var ctx = document.getElementById("myCanvas").getContext("2d");
                ctx.beginPath();
                ctx.arc(x, y, pointSize, 0, Math.PI * 2, true);
                ctx.strokeStyle = "red";
                ctx.stroke();
            }
      
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas
            id="myCanvas"
            width="1000"
            height="1000"
            style="border: 1px solid #d3d3d3"
        ></canvas>

.

Is there a difference between the two code codes?

First Code

console.log('Start');  // output 1
await axios({
  method: 'post',
  url: '<HTTP_URL>'
  data: <SOME_DATA>,
}).then ((response) => {
  // Do something... It could take a few seconds.
  console.log(response); // output 2
});
console.log('End');  // output 3

Second Code

console.log('Start');  // output 1
await axios({
  method: 'post',
  url: '<HTTP_URL>'
  data: <SOME_DATA>,
}).then (async (response) => {
  // Do something... It could take a few seconds.
  console.log(response); // output 2
});
console.log('End');  // output 3

Can the difference in asynchronous operation be caused by ‘async’ keyword of callback method?

In my test, the both source codes showed the same result.

In the second source code, I thought ‘await’ would guarantee only the call of the async callback.
However, it actually guaranteed the complete of the async callback.

Why if they do the same thing?