How can I setting Dynamic Serialport parameters? NodeJS

I’m using Node.js serialport for electron in raspberrypi4
https://serialport.io/docs/
but I can’t setting Dynamic parameters for serialport

Here is my code

var portname, baudrate, databits, stopbits, Parity, RTSCTS;
var portOpen = false;

const port = new serialport('COM4', {
    baudRate: baudrate,
    dataBits: databits,
    stopBits: stopbits,
    parity: Parity,
    rtscts: RTSCTS,
    autoOpen: false,
})

This code is error in electron “TypeError: “baudRate” must be a number: undefined at new SerialPort”

Baudrate is using port.update() for dynamic parameter,
but other things is not available.
Please help me

How do I backup or clone an array of objects in typescript? [closed]

I have tried all the examples listed here, and no matter which one I take including the JSON parse / stringify, when I modify an element in the original array, it is automatically reflected in the backup as is the case in a copy by reference. I need to find a way to break the link and reliably back up by value.

        this.backupPersons = JSON.parse(JSON.stringify(this.persons));
        this.backupPersons = this.persons.slice(0);
        this.backupPersons = this.persons.concat();
        this.backupPersons.concat(this.persons);
        this.backupPersons = angular.copy(this.persons);
        for (var i in this.persons) {
            this.backupPersons.concat(this.persons[i]);
        }
        this.persons.forEach(function (arrayItem) {
            this.backupPersons.concat(arrayItem);
        });
        for (const element of this.persons) {
            this.backupPersons.push(element);
          }

NodeJs calculation gone wrong

I have if statement like:

if((gotPrice * price.value).toFixed(0) >= answers.MINIMUM_BUY_AMOUNT) {
   ...
}

Results are

(gotPrice * price.value).toFixed(0) = 0

and

answers.MINIMUM_BUY_AMOUNT = 200

Then it fall to true! not sure in what world 0 is greater or equal to 200!!

I also tried this way but results was the same

if((gotPrice * price.value).toFixed(0) >= Number(answers.MINIMUM_BUY_AMOUNT).toFixed(0)) {
   ...
}

sample:

var x = 0.3431;
var y = 1.5467;
var z = '200';
console.log((x * y).toFixed(0) >= z); // false (but in my case says true!)

Any suggestions?

Encrypt and decrypt function from nodejs to java

i have a function like this write with javascript, how to i rewrite with JAVA ? i have try many function but still not working

const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const iv = Buffer.from('c080b0f7c7f8e7fbadfa74cda8ac0c29', "hex");
const key = crypto.createHash('sha256').update(String(process.env.ENCRYPTION_KEY)).digest('base64');
const key_in_bytes = Buffer.from(key, 'base64')

const controller = {}

controller.encrypt = (text) => {

    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key_in_bytes), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return encrypted.toString('hex').toString();
}

controller.decrypt = (text) => {
    let encryptedText = Buffer.from(text, 'hex');
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key_in_bytes), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

module.exports = controller

Compare an Array to a Array in an Array

I Wish to Compare array A with Array C but Array C is inside of Array B.

I have tried doing something like this but the results vary:

a.forEach(var => {
 if(var.C.includes(A)){
 //Do Something
 }
});

Minor Idea of what the Arrays look like:

A = day: "10"; 

B= {
someRandom: "Something",

C: [{
 day: "15"
}]
}

What is a right way to work with classes and OOP

I am working with classes right now and I got curious about the way the work with them should look like.

Maybe if you can recommend some good and descriptive books on the topic it would be great!

Questions:

  1. Now I am working on the backend and I am trying to use classes everywhere I find it appropriate – services, endpoints, others. I have some Angular experience and there I always provide new services or whatsoever it is via constructor making kinda injection into the class. Is that the pattern I should always inject the stuff into the class using the constructor?

  2. Let’s say I’ve got a very simple class imageService:

import { PutObjectRequest } from "@aws-sdk/client-s3"
import { Upload } from "@aws-sdk/lib-storage"
import { Types } from "mongoose"
import env from "../env"
import { logMethod } from "../helpers"
import { debug } from "../utils/debug"
import { S3Client } from '@aws-sdk/client-s3'

export interface ImageUploadParams {
    Body: PutObjectRequest["Body"],
    Key: string,
    ContentType: string,
    Bucket?: string,
    ACL?: string,
}

class ImageService {

    private readonly s3: S3Client

    constructor() {

        this.s3 = new S3Client({
            credentials: {
                accessKeyId: env.s3.accessKeyId,
                secretAccessKey: env.s3.secretAccessKey,
            },
            region: env.s3.region,
        })

    }

    private readonly allowedTypes: string[] = [
        'image/jpeg',
        'image/png',
    ]

    private generateName({ id, prefix }: { id: string | Types.ObjectId, prefix?: string }) {
        return `${prefix ? prefix + '-' : ''}image-${id}-${Date.now()}`
    }

    generate({ id, prefix }: { id: string | Types.ObjectId, prefix?: string }) {
        const name = this.generateName({ id, prefix })

        return {
            key: name,
            link: `https://${env.s3.bucket}.s3.${env.s3.region}.amazonaws.com/${name}`
        }
    }

    extractKey(link: string) {
        return link.split('/').pop()
    }

    checkType(mimetype: string) {
        return this.allowedTypes.includes(mimetype)
    }

    @logMethod
    async uploadImage({ Body, Key, ContentType, Bucket, ACL }: ImageUploadParams) {

        const upload = new Upload({
            client: this.s3,
            params: {
                Body,
                Key,
                ContentType,
                Bucket: Bucket ?? env.s3.bucket,
                ACL: ACL ?? 'public-read',
            },
        })

       if(!env.isProd) {
            upload.on("httpUploadProgress", (progress) => {
                if(progress && progress.loaded && progress.total) {
                    const percent = (progress.loaded / progress.total) * 100
                    debug(`image '${Key}' uploaded: ${percent}%`)
                }
            })
       }

        await upload.done()
    }
}

export const imageService = new ImageService()

As you can see I am always instantiating the class and exporting outside (making it available for others). Is it a good practice to use classes like this? Or there is some kind of other flows or technics to make classes available?

  1. Every method in a class should encapsulate some unit logic. What about the way of working with the class. Let’s say I am using the class above and I need to upload an image and I should interact with the class imageService making three different requests – imageService.generate, imageService.checkType, imageService.uploadImage, and so on, and putting all the things together in the class it requires all of that. Am I right? So the class provides the abstractions the little unit tools you can cooperate with and put up some own stuff, without anything concrete like the whole operation from a to z. Maybe there are some principals or something

  2. What about errors? Let’s say I am checking the image type and it is not valid. Should I throw an Error right away, or in this pattern I should just return the error to the class that invoked the method and it should decide what to do? If the last, there is a change of a bug or something. Do classes responsible for throwing errors, or just responding and delegating that on the classes that invoked them?

The questions must be very silly and vague, but any thoughts are welcomed

NextJS: 404 page not rendered for [store]/account/details route

I’m trying to implement 404 pages in my react-next project,
i have a route [store]/account where [store] is dynamic. till the account page the 404 is properly thrown, but when i try to load [store]/account/asdasdasd(random page to trigger 404) the screen is blank and shows nothing.

note: i have handled 404 in the getStaticProps for both [store],/account page.

Please help with this, stuck on this for quite sometime.

Scroll to the end of h1 tag thats overflow is hidden in reactjs

So i have an h1 tag which has its overflow hidden and what i want to do is make it so it auto scrolls to the end of the text without showing the scroll bar. I’ve tried a lot of ways but I couldn’t find any suitable for me.
I tried using refs

myref.current.scrollIntoView()

It didn’t work then I tried

myref.current.scrollTo(1000)

but that didn’t do anything it just showed an error in the console.

Unable to detect Canvas tag inside ngfor iteration – Angular

I want to work with Canvas tag inside ngfor but every times it showing undefined or null. I tried in many ways but not worked. Please help me.

HTML:

<div class="col-sm-6 col-lg-4 pb-30 blog-parent" *ngFor="let item of blogList; let i = index;">
    <div class="blog-item">
        <a href="#">
            <div class="blog-item-figure">
                <canvas class="blog-canvas" id="canvas"></canvas>
            </div>
        </a>
    </div>
</div>

TS:
ngOnInit(): void {
    this.cropImage();
}
cropImage() {
    let canvas: any = document.getElementsByClassName("blog-canvas");
    for (let i = 0; i < this.blogList.length; i++) {
        console.log("canvas: ", canvas[i]);
    }

}

Masking the given number while on typing before clicking on save button

I am developing the SSN number in react native.Now in my code I am masking the number like 123 – 45 – xxxx OR xxx – 45 – 6789 only after clicking the save button.But now I wanted to mask that number like 123 – 45 – xxxx OR xxx – 45 – 6789
while typing the number before any clicking save button.
Note: in my code, I am referring the values of splitby, numOfSplits, pattern, position, mask, length, maskBy through my metadata.

my code

import React from ‘react’;
import {
Controller
} from ‘react-hook-form’;
import {
StyleProp,
ViewStyle
} from ‘react-native’;
import {
useSelector
} from ‘react-redux’;
import {
Icon,
Input,
Layout
} from ‘_atoms’;
import {
Label
} from ‘_organisms’;
import {
fillColor
} from ‘_utils’;
import {
style
} from ‘../style’;

let SystemMask = ({
attribute,
data,
formOptions,
disable
}: any) => {

const {
    name,
    required,
    title,
    info,
    placeHolder,
    validationRegEx,
    defaultValue,
    canUpdate,
    unique,
    splitBy,
    pattern,
    numOfSplits,
    position,
    mask,
    length,
    maskBy,
    ...others
} = attribute;

const {
    control
}: any = formOptions || {};

let regEx = /^(?!(000|666|9))d{3}-?(?!(00))d{2}-?(?!(0000))d{4}$/

const {
    theme
} = useSelector((state: any) => state.app);

let color = fillColor(disable, theme);

const returnSum = (array: any) => {
    let sum = 0;
    array.map((e: any) => {
        sum = sum + e;
    });
    return sum;
};
let total = returnSum(pattern);

let splittedData = "";

// let numOfSplit = pattern.length - 1;

let splitData = (val: any) => {
    let splittedVal = "";
    if (val) {
        let numOfSplits = 0;
        val.split("").map((ele: any) => {
            if (ele === splitBy) {
                numOfSplits++;
            }
        });
        if (val.length <= total + numOfSplits) {
            val.split("").map((each: any, index: any) => {
                let sum = 0;
                pattern.map((e: any, i: any) => {
                    sum = sum + 1 + e;
                    if (index + 1 === sum && each !== splitBy) {
                        splittedVal += "".concat("", splitBy);
                    } else if (index + 1 === sum && each === splitBy) {
                        splittedVal += "".concat("", splitBy);
                    } else if (index + 1 !== sum && each === splitBy) {
                        splittedVal += "".concat("", "");
                    }
                });
                pattern.map((e: any, i: any) => {
                    sum = sum + 1 + e;
                    if (index + 1 !== sum && each === splitBy) {
                        each = "";
                    }
                });
                splittedVal += "".concat("", each !== maskBy ? each : "");
            });
            return splittedVal;
        }
    } else {
        return "";
    }
};

let maskData = (val: any) => {
    let maskedData = "";
    if (val) {
        splittedData = "";
        let numOfSplits = 0;
        val
            .replaceAll(splitBy, "")
            .split("")
            .map((each1: any, index1: any, array1: any) => {
                if (array1[index1 - 1] === splitBy) {
                    numOfSplits++;
                }
                if (
                    index1 + 1 <= length + numOfSplits &&
                    position === ("LEFT" || "left" || "Left") &&
                    each1 !== splitBy
                ) {
                    splittedData += "".concat("", mask ? maskBy : each1);
                } else if (
                    index1 + 1 >
                    val.replaceAll(splitBy, "").length - (length + numOfSplits) &&
                    position === ("RIGHT" || "right" || "Right") &&
                    each1 !== splitBy
                ) {
                    splittedData += "".concat("", mask ? maskBy : each1);
                } else {
                    splittedData += "".concat("", each1);
                }
            });
        splittedData.split("").map((each2, index2) => {
            let sum2 = 1;
            pattern.map((e2: any, i2: any) => {
                sum2 = sum2 + e2;
                if (index2 + 1 === sum2 && each2 !== splitBy) {
                    maskedData += "".concat("", `${splitBy}`);
                }
            });
            maskedData += "".concat("", each2);
        });
        return maskedData;
    } else {
        return "";
    }
};

const handleOnchange = (val: any, onChange: any) => {
    onChange(val);
};

const getMaskValue = (value: any, isDirty: any) => {
    return isDirty ? splitData(value) : maskData(value);
};

return ( <
    Layout style = {
        style.container as StyleProp < ViewStyle >
    } >
    <
    >
    <
    Label isRequired = {
        required
    }
    title = {
        title
    }
    description = {
        info
    }
    /> <
    /> <
    Controller control = {
        control
    }
    name = {
        name
    }
    render = {
        ({
            field,
            fieldState
        }: any) => {
            let {
                onChange,
                value,
                ref
            } = field || {};
            let {
                error,
                isDirty
            } = fieldState || {};
            let {
                message
            } = error || {};

            return ( <
                Input
                // ref={ref}
                placeholder = "123-45-6789"
                testID = {
                    name
                }
                disabled = {
                    disable
                }
                onChangeText = {
                    (value: any) => {
                        onChange(value);
                    }
                }
                // inputProps={{
                //     maxLength: total + numOfSplit,
                //   }}
                onChange = {
                    (val) => handleOnchange(val, onChange)
                }
                value = {
                    getMaskValue(value, isDirty)
                }
                status = {
                    error ? 'danger' : 'primary'
                }
                caption = {
                    error ? message || 'Required' : ''
                }
                accessoryRight = {
                    (props: any) => {
                        if (value) {
                            return ( <
                                Icon {
                                    ...props
                                }
                                fill = {
                                    color
                                }
                                name = {
                                    'close'
                                }
                                disabled = {
                                    disable
                                }
                                onPress = {
                                    () => onChange('')
                                }
                                />
                            );
                        } else return < > < />;
                    }
                }
                />
            )
        }
    }
    rules = {
        {
            required: required,
            pattern: {
                value: validationRegEx || regEx,
                message: 'Enter a valid SSN',
            },
            maxLength: {
                value: 11,
                message: "SSN length should be < 9",
            },
        }
    }
    defaultValue = {
        data || defaultValue || ''
    }
    /> <
    /Layout>
);

};

export default SystemMask;

Transform flat json to nested json using javascript

I am trying to transform flat json to nested json using javascript with some sort of relationship. Please see below for the sample json data i am working with:


[{"id":1,"lob":"IT","product":"mobile","title":"64-bit app"}, 
{"id":2,"lob":"SCI","product":"book","title":"a book"},
{"id":3,"lob":"IT","product":"laptop","title":"this is laptop"},  
{"id":4,"lob":"IT","product":"laptop","title":"another laptop"},
{"id":5,"lob":"ENG","product":"stick","title":"a magic stick"},
{"id":6,"lob":"ENG","product":"door","title":"a door"},
{"id":7,"lob":"IT","product":"mobile","title":"32-bit app"}, 
]

and then please see below for the expected output:


[
    {
      lob: "IT",
        product: [
            {
            name: "mobile",
            titles: [
                    {
                        title: "64-bit app",
                    },
                    {
                        title: "32-bit app",
                    }
                ]
            },
            {
                name: "laptop",
                titles: [
                        {
                            title: "this is laptop",
                        },
                        {
                            title: "another laptop",
                        }
                    ]
                }
            
        ]
    },
    {
        lob: "ENG",
          product: [
              {
              name: "stick",
              titles: [
                      {
                          title: "64-bit app",
                      },
                      {
                          title: "32-bit app",
                      }
                  ]
              },
              {
                  name: "laptop",
                  titles: [
                          {
                              title: "a magic stick",
                          },
                          {
                              title: "a door",
                          }
                      ]
                  }
              
          ]
      }

]

How do I achieve this using javascript, or are there any package/library i can use.