axios and msgpack decoding

There’s not much of answer from this: https://stackoverflow.com/search?q=axios+msgpack
and also not much to find using googlefu.

I’m trying to decode response data with msgpack using axios but having error with TypeError: stream.getReader is not a function. However, if I use fetch, it works.

Using fetch:

async request = postData => {
  let response = await fetch("/api/filter-genes-by-organ", {
    method: "POST",
    body: JSON.stringify(_data),
    headers: { "Content-type": "application/json" },
  });
  return decodeAsync(response.body);
}

Using axios:

async request = postData => {
let headers = { "Content-Type": "application/json" };
  let response = await axios.post(`/api/${endpoint}`, postData, { headers }, {responseType: 'text' });
  return decodeAsync(response.data)
}

I’m still doing some tests and if i find a solution I will update this question, thank you.

Using toggle function to highlight one element when clicked

I have a couple of li elements imported from an API. When clicked on one of the elements, that element should change background color and stay that color until another element is clicked on. At that point the new element will change color and the old one go back to its original color. I was trying to make this work a few different ways but can’t make it work. Can anyone help? thank you.

       axios
  .get(showUrl + "?api_key=" + apiKey)
 .then((response) => {
  showsArray = response.data;
 showsArray.forEach((show) => {
 displayShows(show);

})
})
 .catch(error => {
console.log(error);
})



  function displayShows(arr) {
    
    let show = document.createElement("li")
    show.classList.add("shows__table")

    let dateHeading = document.createElement('h5');
    dateHeading.innerText = "Date";

    let dateNum = document.createElement("h3");
    dateNum.innerText = new Date(Number(arr.date)).toDateString();

    let venueHeading = document.createElement('h5');
    venueHeading.innerText = "Venue"

    let venueName = document.createElement('p');
    venueName.innerText = arr.place;  
    
    let locationHeading = document.createElement('h5');
    locationHeading.innerText = "Location";

    let locationName = document.createElement('p');
    locationName.innerText = arr.location;

    let button = document.createElement('button');
    button.innerText = "Buy Tickets";
    // button.addEventListener('click', () => {
    //     console.log("hit")
    // })
    
    showsList.appendChild(show);
    show.appendChild(dateHeading);
    show.appendChild(dateNum);
    show.appendChild(venueHeading);
    show.appendChild(venueName);
    show.appendChild(locationHeading);
    show.appendChild(locationName);
    show.appendChild(button);
 }

  // first option:
  // let listItem = document.querySelectorAll(".shows__table");


   // listItem.addEventListener('click', (e) => {

   //     listItem.classList.toggle(".shows__table--active")
  // })

   //second option :
   // document.querySelectorAll('.shows__table').addEventListener('click', changeColor);
  // function changeColor() {
  //     this.style.backgroundColor = "red";
  //     return false
  // }
  //third option :
  // let listItem = document.querySelectorAll(".shows__table")
  // listItem.forEach((listItem) => {
   //     listItem.addEventListener('click', (e) => {
  //         listItem.classList.toggle(".shows__table--active")
  //     })
 // })

 // 4th option
 // let listItem = document.querySelectorAll(".shows__table");
  //   for (let i = 0; i < listItem.length; i++) {
  //     listItem[i].addEventListener('dblclick', function (e) {
 //       e.preventDefault();
 //       listItem[i].classList.toggle("shows__table--active");
  //       console.log("clicked");
 //     });
  // }

React how to render only parts of an array?

I am still a bit new to react and how it works. I have a projects.js file with a list of objects that look like this:

id: 0,
    name: "Placeholder Project 1",
    description: "Project description",
    image: "./assets/images/placeholder-01.png"

There are 6 objects in this array. I am trying to render only 3 project objects at a time, and then include a button that will “load more” projects later. However, I am having trouble with just the rendering part. My component looks like this:

import React, { Component } from "react";
import NavTab from "./NavTab";
import { Card } from "react-bootstrap";
import { PROJECTS } from "../shared/projects";

function RenderProject({projects, projectsDisplayArray}) {
    const tempArray = projectsDisplayArray;
    return( 
        <div className="row">
            {                 
                projects.map(project => {
                    tempArray.indexOf(project) > -1 ? console.log('in array already') : tempArray.push(project) 
                    console.log(tempArray.length)
                    if (tempArray.length >= 3){
                        console.log('in the if')
                        return (
                            <Card key={project.id}>
                                <Card.Img variant="top" src={project.image} />
                                <Card.Body>
                                    <Card.Title>{project.name}</Card.Title>
                                    <Card.Text>
                                        {project.description}
                                    </Card.Text>
                                    
                                </Card.Body>
                                <button className="btn align-self-center">Go somewhere</button>
                            </Card>

                        )
                    }
                    else {
                        return(<div>Else return div</div>)
                    }
                })
            }
        </div>
    )
}

export default class Projects extends Component {
    
    constructor(props){
        super(props);
        this.state = {
            projectsPerScreen: 3,
            currentPage: 0,
            projects: PROJECTS,
            projectsDisplayArray: []
        }
    }
    modifyProjectsDisplayArray = props => {
        this.setState({projectsDisplayArray: [...this.state.projectsDisplayArray, props]})
    }
    render() {
        let i = 0;
        return(
            <React.Fragment>
                <NavTab/>
                <div className="projects">
                    <div className="container">
                        <button type="button" className="btn">Click</button>
                        <h1>Projects: </h1>
                        <RenderProject projects={this.state.projects} projectsDisplayArray={this.state.projectsDisplayArray} />
                        <button type="button" className="btn" onClick={() => console.log(this.state.projectsDisplayArray)}>console log</button>
                    </div>
                </div>
            </React.Fragment>
        )
    
    }
}

I am very confused on how the return method for RenderProject is working. When I begin the mapping process, I want to add each project to an array so I can keep track of how many and what projects are being rendered. When the array length hits three, I want it to stop rendering. But whenever I do this, my line if (tempArray.length <= 3) behaves in a way I don’t expect it to. With how it is now, it won’t return the <Card> and will instead return the else <div> for all 6 objects. But if I change the if statement to be if (tempArray.length >= 3) it will render all 6 objects inside of the array and no else <div>s. What should I be doing instead?

Why do we need to have two same ids in alert-component and alert-service

I am trying to implement alerts on my webpage. I have found some guides that go through how to create alerts in angular. Most of them are implementing it in the same way which makes me believe it’s the way to go. What I don’t understand is that all of those guides have an id in the alertComponent with the annotation @input

Alert-component.ts

@Input() id = 'default-alert';

Then we call the onAlert method and provide the id as an argument

this.alertSubscription = this.alertService.onAlert(this.id)

The alert-service.ts class have also a field called defaultId with the same value as alert-component

alert-service.ts

private defaultId = 'default-alert';

Then in the implementation of OnAlert method in alert-service we take the id we recieve in as an argument and assign it to the default id ? is this a common thing in angular? I don’t understand

onAlert(id = this.defaultId): Observable<Alert> {
        return this.subject.asObservable().pipe(filter(x => x && x.id === id));
    }

I would appricate yours answers to help me understand. Thanks!

unable to call javascript function from angular 13 component

There is a recent change introduced in Angular 13 where the old way of calling javascript functions from angular components isn’t working anymore.

I am facing an issue with calling a javascript function from a specific component.

I already tried the usual way and here is my approach.

FILE: srcassetsjsmain.js

(function($) {
"use strict";
function animatedProgressBar () {
    $(".progress").each(function() {
        var skillValue = $(this).find(".skill-lavel").attr("data-skill-value");
        $(this).find(".bar").animate({
            width: skillValue
        }, 1500, "easeInOutExpo");
        $(this).find(".skill-lavel").text(skillValue);
    });
}
})(jQuery);

FILE: srcappabout-meabout-me.component.ts

import { Component, OnInit } from '@angular/core';
declare function animatedProgressBar(): any;
@Component({
    selector: 'app-about-me',
    templateUrl: './about-me.component.html',
    styleUrls: ['./about-me.component.css']
})

export class AboutMeComponent implements OnInit {
    //declare animatedProgressBar: any;
    constructor() {}
    ngOnInit(): void {
        animatedProgressBar();
    }
}

This code snippet throws an error: ERROR ReferenceError: animatedProgressBar is not defined

I checked the answer on This StackOverflow topic but it didn’t work for me.

Looking forward to some valuable inputs on this issue.

How to push an object coming from postman as a number(validationError)?

My main problem is I cannot push quantity to its respective object. I am posting data in JSON format in postman like this:

  "productId":"621256596fc0c0ef66bc99ca",
  "quantity":10

my schema is:

userOrders:[
            {
                productId:{
                    type: String,
                    required: [true, "ProductId is required"]
                },

                quantity:{
                    type: Number,
                    required: [true, "Quantity is required"]
                }
            }
        ]

my controller is:

module.exports.createOrder =  async (data) => {

    let id = data.userId;
    let product = data.productId;
    let oQuantity = data.quantity;
    return  User.findById(id).then(user =>{

            
            user.userOrders.push({productId:product})
            user.userOrders.push({quantity:oQuantity})  
            return user.save().then((savedOrder, err) => {
              if (savedOrder) {
                  return savedOrder;
            } else {
                 return 'Failed to create order. Please try again';
            }
         }) 
      });

I receive an error like this:

this.$__.validationError = new ValidationError(this);
                               ^

ValidationError: User validation failed: userOrders.0.quantity: Quantity is required

I’ve tried so many things but I still cannot solve it. Any tips?

The items repeat itself in a dynamic multiple slide carousel using Angular

I have a Issue with the carousel that I am creating because the items are repeated after changing the size of the screen. My code base comes from the answer given by Eliseo in this Stackoverflow question where his carousel has the functionality to show/hide the arrow functions after changing the variable noCarousel based on the dimensions of the user’s screen and the amount of items to show, this functionality presents the detail that after hiding the arrows the items are doubled and/or tripled

Code in Stackblitz:

https://stackblitz.com/edit/angular-1vnbxc-zc9fz8?file=src/app/app.component.html

Steps to recreate the Issue (2 ways):

  1. If when opening the code in Stackblitz the carousel has the functionality of the active arrows, expand the sample screen until the arrows disappear.
  2. If when opening the code in Stackblitz the carousel has the inactive arrows functionality, collapse the sample screen until the arrows are activated and then expand it until the arrows disappear.

Image Sample

Expose method creating a web-component using Vue3

I am creating a web-component using VueJS 3, I want to expose a method on the component allowing the user to do something like this:

  <custom-component id="x1" />

  <script>
    var component = document.getElementById("x1");
    
    component.customMethod(); // as focus() method on native elements
  </script>

If I define a method on the component, I can call the method inside the component. But the method is not available when I use it as a web-component.

  //main.ts/js
  import { defineCustomElement } from "vue"
  import component from "./component.ce.vue"

  const element = defineCustomElement(component );

  customElements.define("custom-component ", element);
  //component.ce.vue
  const customMethod = () => { console.log("Exected"); }

How I can indicate to Vue Component Wrapper that the customMethod will be available outside the component?

how do I create a Modal CSS that will work with this JS code

Not sure how to create model for this codes of java script. need to display a list with saved names and then be able to select favorute

function showFavorites() {
    favoritesList = JSON.parse(localStorage.getItem("saveData"));
    fetch(favoritesList[0].url)
      .then(response => response.json())
      .then(data => {
        console.log(data);
      });
  }

        
  function saveFavorites(item) {
    var flag = false;
    for (let i = 0; i < savedLaunches.length; i++) {
      if (savedLaunches[i].url == item.url) {
        flag = true;
      }
    }
    if (flag) {
      return;
    }
    savedLaunches.push(item);
    localStorage.setItem("saveData",JSON.stringify(savedLaunches));
  }

transfer/get json to javascript rest api from rest controller

to me need integrate javascript rest api with app on spring-boot, rest api gets json and making URL. How to call a method in a rest controller in javascript and get json? Help me please

Controller:

@RestController
@RequestMapping("/api/v1/vk-pay")
public class VKPayController {

    private final PaymentService paymentService;

    @Autowired
    public VKPayController(@Qualifier("VKPayServiceImpl") PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @GetMapping("/{id}")
    private Parameters getParams(@PathVariable("id") Long orderId,
                             @AuthenticationPrincipal UserDetails user){
        VKPayPayment payment = paymentService.createOrder("captureUrl", orderId);
        paymentService.save(payment,user.getUsername(),orderId);
        return payment.getParam();
    }
}

javascript:

params = how to get json from restcontroller?
VK.App.open('vkpay', '''params''');

Paste rich text as plain text without HTML markup formatting in Trix editor

I am using Rich Text (Trix editor) with Rails and I want to be able to convert everything that user pastes to sanitized plain text instead of having formatted elements.
Based on Trix documentation I am using this code to convert pasted elements to string.

  element.addEventListener("trix-paste", function(e) {
    element.editor.getDocument().toString()
    console.log(element.editor.getDocument().toString())
  })

In console, it shows correct plain text, but in the editor, all the elements are still formatted.

How can I replace text in the editor to this sanitized text?

Why it doesn’t draw the exponential curve in canvas?

I’m learning the basics of javascript at school, now I’m working on the canvas

This is my code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Funzioni Geometriche</title>

</head>
<body onload="draw()">
    <canvas height="800" width="800" id="myCanvas"></canvas>

    <script src="script.js"></script>
</body>
</html>
canvas = document.getElementById("myCanvas")
ctx = canvas.getContext("2d")
offset = canvas.width/2

function assi(){
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.beginPath()
    ctx.moveTo(offset, 0)
    ctx.lineTo(offset, offset*2)
    ctx.moveTo(0, offset)
    ctx.lineTo(offset*2, offset)
    ctx.stroke()
}

function f(x){
    return Math.pow(2, x)*-1;
}

function draw() {
    assi()
    ctx.beginPath()
    ctx.strokeStyle = "red"

    moveTo(offset, f(0)+offset)
    for (let x = -offset; x < offset; x++) {
        ctx.lineTo(x+offset, f(x)+offset)
    }
    ctx.stroke()
}

This is my question
why in the function f(x) if I leave *-1 it doesn’t draw anything, while if I delete *-1 it draws something?
It draws linear functions, but the exponential function gives problem, and is not Math.pow() the problem, because if I use 1 as base it works (actually draws a line, but is right)

The *-1 is needed to mirror the y-axis of canvas axis system (up to down) into cartesian axis system (down to up)

Typescript: How can I extract the value from JSON objects inside an array with changing property names?

I’m new to typescript and would like to extract the value from JSON objects inside an array with changing property names.

My (simplified) code is as follows:

const data = [
              { names: { "1,2": "Matthew" },
              { names: { "2,3": "Marcus", "3,4": "Bill" }},
              { names: { "4,5": "Joana", "5,6": "Bob" }
             ];

const key = "1,2";

const name = data[0].names[key]; // Results in an error message (see below)
const name = data[0].names["1,2"]; // Works but not dynamic

My goal is to extract each value (e.g. “Matthew”, “Marcus”, etc.).

However, I get the following error message:

Type ‘{ names: { “1,2”: string; “2,3”?: undefined; “3,4”?: undefined; “4,5”?: undefined; “5,6”?: undefined; }; }’ is not assignable to type ‘string’

How can I solve this error?

Thanks a lot for your help!