We have our BrightSign device that is connected to a display and running our custom node application. This node application is listening for messages from our website. Our users will have a dashboard for viewing all of their devices. From this page, they can send a message to power the display ON or OFF. Our Node application will receive the message from our website. We would like to use this node application to send serial commands to turn the display on and off when these messages are received. The only piece of all this I need help with is the sending of the serial commands from Node.
Thanks
Category: javascript
Category Added in a WPeMatico Campaign
Using filter() to implemnt curriable() in javascript is fial , however, uisng map() is work, why?
I’m trying to implement the curry() with placeholder support, that is curriable. curriable provides a high performance and small footprint curry method. The version1 is the working code
is using map in the recursion function. However, I tried to use filter to filter the placeholder in the version2! Using filter is good for most cases, but not will fail with case curriedJoin(_,_,3,4)(1,_)(2,5), can any one tell me why?
version 1
/**
* @param { (...args: any[]) => any } fn
* @returns { (...args: any[]) => any }
*/
// function curry(fn) {
// // your code here
// }
function curry(func) {
return function curried(...args) {
const complete = args.length >= func.length && !args.slice(0, func.length).includes(curry.placeholder);
if(complete) {
args.length=3
args.sort((a,b)=>a-b)
return func.apply(this, args)
}
return function(...newArgs) {
// replace placeholders in args with values from newArgs using map
const res = args.map(arg => arg === curry.placeholder && newArgs.length ? newArgs.shift() : arg);
return curried(...res, ...newArgs);
}
}
}
const join = (a, b, c) => {
return `${a}_${b}_${c}`
}
curry.placeholder = Symbol()
const curriedJoin = curry(join)
const _ = curry.placeholder
console.log(curriedJoin(1, 2, 3)) // '1_2_3'
console.log(curriedJoin(_, 2)(1, 3)) // '1_2_3'
console.log(curriedJoin(_, _, _)(1)(_, 3)(2)) // '1_2_3'
console.log(curriedJoin(_,_,3,4)(1,_)(2,5))// '1_2_3'
Version2
/**
* @param { (...args: any[]) => any } fn
* @returns { (...args: any[]) => any }
*/
// function curry(fn) {
// // your code here
// }
function curry(func) {
return function curried(...args) {
const complete = args.length >= func.length && !args.slice(0, func.length).includes(curry.placeholder);
if(complete) {
args.length=3
args.sort((a,b)=>a-b)
return func.apply(this, args)
}
return function(...newArgs) {
// replace placeholders in args with values from newArgs
const res = [...args].filter(element=> element!== curry.placeholder);
return curried(...res, ...newArgs);
}
}
}
const join = (a, b, c) => {
return `${a}_${b}_${c}`
}
curry.placeholder = Symbol()
const curriedJoin = curry(join)
const _ = curry.placeholder
console.log(curriedJoin(1, 2, 3)) // '1_2_3'
console.log(curriedJoin(_, 2)(1, 3)) // '1_2_3'
console.log(curriedJoin(_, _, _)(1)(_, 3)(2)) // '1_2_3'
console.log(curriedJoin(_,_,3,4)(1,_)(2,5)) //Fail, because "Uncaught TypeError: curriedJoin(...)(...) is not a function"
Extract values from JSON to array format using javascript [duplicate]
I have a JSON file and I need to extract the values of playername to an array, How do I efficiently extract and have the results in this format below
[“player1″,”player2″,”player3″,”player4”]
[
{
"rank": 96,
"season": 11,
"playername": "player1",
"rating": 1503,
"games": 106,
"wins": 79,
"longest_streak": 14,
"max_rating": 1547,
"league": 1,
"max_league": 1,
"reward": null,
"group_id": null,
"group_name": null,
"group_data": null,
"profile_id": 0,
"display_name": null,
"rank_pre": null,
"rank_post": null
},
{
"rank": 98,
"season": 11,
"playername": "player2",
"rating": 1502,
"games": 224,
"wins": 134,
"longest_streak": 11,
"max_rating": 1607,
"league": 1,
"max_league": 3,
"reward": null,
"group_id": null,
"group_name": null,
"group_data": null,
"profile_id": 0,
"display_name": null,
"rank_pre": null,
"rank_post": null
}
]
How do i achieve this?
How to send jpg to backend though to cloudinary?
I have the following:
fil = file:///storage/emulated/0/Android/data/com.test/files/Pictures/7601d776-7ca4-44b0-99cf-d8c0bb4c14e9.jpg , (Image.path for android Generated by react-native-image-crop-picker . when I use the below code to send this to the backend, it has an error with cloudinary while the Image.path for IOS fil = /Users/test/Library/Developer/CoreSimulator/Devices/.../data/Containers/Data/Application/.../tmp/react-native-image-crop-picker/.../.jpg does not have an error. Why is this the cases since they are both grabbed from Image.path for react-native-image-crop-picker ?
const res = await client.post('/upload-avatar',{fil},{headers:{
Accept : 'application/json',
authorization: 'some JWT'
}})
back end:
try{
const upload_result = await cloudinary.uploader.upload(req.body.fil, {
public_id: `${user._id}_profile`,
width:500,
height:500,
crop: 'fill'
})
res.status(201).json({success:true,message: "good"})
}catch (error){
res.status(500).json({success:false,message: "Error"})
}
Flatten and combining an Array of Objects
I have an array of objects like so
[
{
"id":1,
"name":"Competition One",
"entrants": [
{
"id":1,
"competitionId":1,
"duration":"3 minutes",
},
{
"id":2,
"competitionId":1,
"duration":"2 hours",
},
]
},
{
"id":2,
"name":"Competition Two",
"entrants": [
{
"id":3,
"competitionId":2,
"duration":"5 hours",
},
]
},
]
What I am trying to do is get a flat array containing only the entrants, as such I am doing this
const entrants = competitions.flatMap((comp) => {
return comp.entrants;
});
This seems to do the job. I now have the following
[
{
"id":1,
"competitionId":1,
"duration":"3 minutes",
},
{
"id":2,
"competitionId":1,
"duration":"2 hours",
},
{
"id":3,
"competitionId":2,
"duration":"5 hours",
}
]
However, what I can’t figure out is how to add a new field within the above data that contains the name of the competition. So what I am after is this
[
{
"id":1,
"competitionId":1,
"name": "Competition One"
"duration":"3 minutes",
},
{
"id":2,
"competitionId":1,
"name": "Competition One"
"duration":"2 hours",
},
{
"id":3,
"competitionId":2,
"name": "Competition Two"
"duration":"5 hours",
}
]
How can this be achieved? I know how to do this with conventional loops, but trying to force myself to learn the ES6 way of doing things. Is this where a reduce could come in handy?
Any advice appreciated.
Thanks
How can I access the variable declared inside then function outside?
I want to access the input value given/already present in the input field. I am trying the below solution but I can’t access it outside the then function.
let name
cy.visit('/')
cy.get('[id=username]').type("Kanye")
cy.get('[id=username]').then((input) => {
age = input.val()
cy.log(name) # Works here
})
cy.log(name) #Does not work here
Can you help me modify this function? Or suggest me any alternative I can use.
Render multiple ApexCharts with JS in one file
Good evening,
in order not to insert single scripts on each page, I would like to merge all the JS rendering graphics into one file.
ApexCharts uses the following code to render a single chart.
var options = {
series: [3, 5],
labels: ['Item1', 'Item2'],
colors: ['#747679', '#e83323'],
chart: {
type: 'donut',
height: 200,
width: 200
}
}
var chart = new ApexCharts(document.querySelector("#apexchart1"), options);
chart.render();
How can I change it?
How can i sort an array of objects? [duplicate]
i have the following array:
mVetor [
{ nome: 'will', idade: 18 },
{ nome: 'marcos', idade: 19 },
{ nome: 'maria', idade: 20 },
{ nome: 'bia', idade: 21 },
{ nome: 'jose', idade: 22 },
{ nome: 'clara', idade: 23 },
{ nome: 'isa', idade: 33 },
{ nome: 'pedro', idade: 38 },
{ nome: 'gabriel', idade: 19 },
{ nome: 'ana', idade: 26 }
]
And i want to know how can i organize and order the array by name(nome) and then age(idade) but i don’t know how
Print a bill using TM-T20III
I have an epson tm-t20iii printer and I want to make a program that allows me to print a bill using it.
I looked a lot about python solutions and javascript solutions, but didn’t succeed.
I don’t have any programming language preference whether it’s javascript, php, python or java, the goal is being able to make that application listen into requests, it could be an app that gets installed on a Windows machine, and listens on events coming from an electron application or python tkinter app. I just need to figure out a way to do it. (preferable USB not network)
Any ideas please ?
POST Route Is Giving CryptoJS Malformed Data Error
I’m learning Crypto.JS and Node.JS, and am currently struggling with a Malformed UTF-8 data error when accessing the login endpoint with Postman. I know that the login credentials are correct, but when I send the POST request to the endpoint, it throws me with that error. Is there a simple fix for this?
const router = require('express').Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
router.post("/register", async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJS.AES.encrypt(req.body.password, process.env.SECRET_PASSPHRASE).toString()
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json(err);
}
});
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username })
!user && res.status(401).json("Invalid username or password");
const hashedPassword = CryptoJS.AES.decrypt(user.password, process.env.SECRET_PASSPHRASE);
const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
originalPassword !== req.body.password && res.status(401).json("Invalid username or password");
const accessToken = jwt.sign(
{
id: user._id,
isAdmin: user.isAdmin
},
process.env.ACCESS_TOKEN_SECRET,
{expiresIn: "3d"}
);
const { password, ...others } = user._doc;
res.status(200).json(others, accessToken);
} catch(err) {
console.log(err);
res.status(500).json(err);
}
});
module.exports = router;
rectangle element with image background in svg
Is there any way to put multiple images into SVG?
The best solution for me seems to be placing a RECT object that will have a photo as a backgrund but its not working.
example:
<svg width="500" height="500">
<rect width="100" height="100" class="img1" />
<rect width="100" height="100" class="img2" />
</svg>
and
.img1 {
background-image: url("../assets/panel.svg");
}
JavaScript Add onclick functions with row number as parameter to dynamically generated rows
The Problem
Hi, I am making a table in which I have two buttons, View and Update for each row. I am generating the rows in one for loop. Since I am using innerHTML, Instead of adding the onclick listeners there, I make another for loop after the first one and add the event listeners there. The event listeners are added to all rows. However, the parameter( Row number) passed in functions for all rows is the number for the last row.
Not sure why this is happening, any clues or advice will be helpful. I will leave the relevant code and debugging results below.
The Code
Adding New Rows
table.innerHTML="";
var count=1;
querySnapshot.forEach((doc) => {
var innerhtml='<tr id="row">.....</tr>';
//Append the new row
table.innerHtML=table.innerHTML+innerhtml;
//Assign new ID to row
document.getElementById("row").id=count.toString()+"row";
//Increment Count for next row/iteration
count=count+i;
});
Adding event Listeners for Each Rows
for(var i=1;i<count;i++){
console.log("Adding functions for row : "+i);
//Get/Generate ID of rows (ID was assigned with same logic)
var cchkid=i.toString()+"chk";
var uupdateid=i.toString()+"update";
console.log("Adding functions for row : "+cchkid + " "+uupdateid);
//Add Listeners for Each button in row i
document.getElementById(cchkid).addEventListener("click", function(){
alert("adding check function for id : "+i);
check(i-1);
});
document.getElementById(uupdateid).addEventListener("click", function(){
alert("adding update function for id : "+i);
update(i-1);
});
}
Debugging by using Console Log & Inspect
Count : 3
Adding functions for row : 1
Adding functions for row : 1chk 1update
Adding functions for row : 2
Adding functions for row : 2chk 2update
Inspect
Using inspect element, I can ensure that all rows have separate id’s

So far everything looks good, However, when console logged inside the said functions, all rows give the same value for the passed parameter.
Console Log after clicking on two different rows
2 Display data for user ID: 1
This should be :
- Display data for user ID: 0 for first row
- Display data for user ID: 1 for second row and so on
I cannot figure out what’s wrong here, kindly help this newbie out. Thanks!
Fast form’s validation with server-side validation
Say for example that I’m building a web application with auth functionalities. How can I display warnings, change the colors of the input, etc. as I type? Client and server-side validation? But client-side validation would be insecure or visible to the client through the google console? Or maybe fetching an endpoint every time that I type?
console not logging post example
view html page, where i want to add functionality to add list
<div class="centered-content">
<div class="task-manager-container">
<div class="sidebar">
<h1 class="title has-text-primary">
Lists
</h1>
<div class="list-menu">
<a class="list-menu-item">
<p>List 1#</p>
</a>
<a class="list-menu-item">
<p>List 2#</p>
</a>
<a class="list-menu-item">
<p>List 3#</p>
</a>
</div>
<button class="button is-primary" (click)="createNewList()">+ New List</button>
</div>
<div class="task-list-container has-background-light">
<h1 class="title has-text-primary">
Tasks
</h1>
<div class="task">
<p>This is something i have to do :) </p>
</div>
<div class="task">
<p>This is something i have to do :) </p>
</div>
<div class="task complete">
<p>This is something i have to do :) </p>
</div>
</div>
</div>
</div>
this createNewList method is in task-service as:
import { Injectable } from '@angular/core';
import { WebRequestService } from './web-request.service';
@Injectable({
providedIn: 'root'
})
export class TaskService {
constructor(private webReqService: WebRequestService) { }
createList(title: string) {
return this.webReqService.post('lists', { title });
}
}
this is method in task-view-component.ts
import { Component, OnInit } from '@angular/core';
import { TaskService } from 'src/app/task.service';
@Component({
selector: 'app-task-view',
templateUrl: './task-view.component.html',
styleUrls: ['./task-view.component.scss']
})
export class TaskViewComponent implements OnInit {
constructor(private taskService: TaskService) { }
ngOnInit(): void {
}
createNewList() {
this.taskService.createList('Testing').subscribe( (response: any) => {
console.log(response);
})
}
}
i imported httpClientModule in app.module, and the console is not logging ANYTHING (not even 404 or any error…) “Testing” which should be the body (title) of my task.
if you need any additional info to help me please say so… thank you for all of your help!
also this is in web-request-service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class WebRequestService {
readonly ROOT_URL;
constructor( private http: HttpClient) {
this.ROOT_URL = 'http://localhost:3000';
}
get(uri: string) {
return this.http.get(`${this.ROOT_URL}/${uri}`);
}
post(uri: string, payload: Object) {
return this.http.post(`${this.ROOT_URL}/${uri}`, payload);
}
patch(uri: string, payload: Object) {
return this.http.patch(`${this.ROOT_URL}/${uri}`, payload);
}
delete(uri: string) {
return this.http.delete(`${this.ROOT_URL}/${uri}`);
}
}
JS this dynamic scoping [duplicate]
When trying to execute the following snippet, I expected the doFoo.call(obj, obj.foo) call to return "inside obj" as the dynamic scope of the previous element in the call stack has a reference to a but the call has the global context instead. What am I missing here?
function foo() {
// debugger
console.log(this, this.a);
}
function doFoo(fn) {
// `fn` is just another reference to `foo`
// debugger
fn()
// <-- call-site!
}
var obj = {
a: 'inside obj',
foo: foo
};
var a = "oops, global"; // `a` also property on global object
doFoo(obj.foo); // "oops, global"
doFoo.call(obj, obj.foo) // "oops, global"```