How to make HTTPS POST and DELETE in JavaScript?

Just wondering, how could I make HTTPS POST and DELETE in JavaScript?

I have the following code working for my HTTP POST in JavaScript but not for HTTPS POST:

    var client = new HttpClientBuilder.create().build();            
    var httpPost = new HttpPost("http://api.com/test");

    httpPost.addHeader("Content-Type", 'application/json');
    httpPost.addHeader("Accept", 'application/json');
    httpPost.addHeader("Authorization", 'Bearer xxxxxx');
    
    entity = new StringEntity("{url: https://localhost/Inbound/}");
    
    httpPost.setEntity(entity);
            
    var resp = client.execute(httpPost);

Does anyone know to make it work for HTTPS POST and DELETE?

How to reduce to find lowest date for each year from section of dates

Right now I have a for-loop going over the dates. I first sort the order and then pluck the first date of each year, but I feel like this could be used with .reduce() instead and converting the results with Object.entries(result) would return me the array or 3 dates.

Reducing with one tenerary would get me the lowest overall date. But I am stuck where I need to return the lowest date from each year within the section.

.reduce((a,b) =>
a = moment(a) < moment(a) ? a : b
return a
)

If there are better ways to achive the end result I am all ears.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  firstDatesOfYear = [];

  data = [
    '2022-02-14T00:00:00',
    '2021-06-14T00:00:00',
    '2021-06-21T00:00:00',
    '2021-11-01T00:00:00',
    '2022-01-10T00:00:00',
    '2022-01-03T00:00:00',
    '2020-07-20T00:00:00',
    '2020-08-31T00:00:00',
    '2020-09-07T00:00:00',
    '2021-02-22T00:00:00',
    '2021-06-07T00:00:00',
    '2022-01-17T00:00:00',
    '2022-01-24T00:00:00',
    '2022-01-31T00:00:00',
  ];

  // find first date of each year from non sorted list of ISO dates
  // result should be ["2020-07-20T00:00:00", "2021-02-22T00:00:00", "2022-01-03T00:00:00"]

  constructor() {
    let temp = this.data
      .map((day) => moment(day))
      .sort((a, b) => a.unix() - b.unix());
    // stuck here, instead of doing the whole following below - should use .reduce()?

    console.log(temp);

    for (let i = 0; i < temp.length; i++) {
      if (i == 0) {
        this.firstDatesOfYear.push(temp[i]);
      } else if (moment(temp[i]).year() != moment(temp[i + 1]).year()) {
        this.firstDatesOfYear.push(temp[i + 1]);
      }
    }
  }
}

Problem: https://stackblitz.com/edit/angular-moment-example-z7m92c?file=app%2Fapp.component.ts

How can I use a loop to make this React component more DRY?

I’m trying to make an audio mixer using the web audio api. I’m having trouble figuring out how to name the refs. How can I create this component without hard coding every track?

import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import { initialTracks } from "./initialTracks";

function App() {
  const [tracks, setTracks] = useState(initialTracks);
  const [isPlaying, setIsPlaying] = useState(true);
  const trackRef0 = useRef();
  const trackRef1 = useRef();
  const trackRef2 = useRef();
  const trackRef3 = useRef();
  const trackRef4 = useRef();
  const trackRef5 = useRef();
  const trackRef6 = useRef();
  const trackRef7 = useRef();
  const trackRef8 = useRef();
  const trackRef9 = useRef();
  const trackRef10 = useRef();
  const trackRef11 = useRef();

  console.log("length", tracks.length);

  useEffect(() => {
    const audioElement0 = trackRef0.current;
    const audioElement1 = trackRef1.current;
    const audioElement2 = trackRef2.current;
    const audioElement3 = trackRef3.current;
    const audioElement4 = trackRef4.current;
    const audioElement5 = trackRef5.current;
    const audioElement6 = trackRef6.current;
    const audioElement7 = trackRef7.current;
    const audioElement8 = trackRef8.current;
    const audioElement9 = trackRef9.current;
    const audioElement10 = trackRef10.current;
    const audioElement11 = trackRef11.current;
    const AudioContext = window.AudioContext || window.webkitAudioContext;
    const audioContext = new AudioContext();

    const track0 = audioContext.createMediaElementSource(audioElement0);
    const track1 = audioContext.createMediaElementSource(audioElement1);
    const track2 = audioContext.createMediaElementSource(audioElement2);
    const track3 = audioContext.createMediaElementSource(audioElement3);
    const track4 = audioContext.createMediaElementSource(audioElement4);
    const track5 = audioContext.createMediaElementSource(audioElement5);
    const track6 = audioContext.createMediaElementSource(audioElement6);
    const track7 = audioContext.createMediaElementSource(audioElement7);
    const track8 = audioContext.createMediaElementSource(audioElement8);
    const track9 = audioContext.createMediaElementSource(audioElement9);
    const track10 = audioContext.createMediaElementSource(audioElement10);
    const track11 = audioContext.createMediaElementSource(audioElement11);

    track0.connect(audioContext.destination);
    track1.connect(audioContext.destination);
    track2.connect(audioContext.destination);
    track3.connect(audioContext.destination);
    track4.connect(audioContext.destination);
    track5.connect(audioContext.destination);
    track6.connect(audioContext.destination);
    track7.connect(audioContext.destination);
    track8.connect(audioContext.destination);
    track9.connect(audioContext.destination);
    track10.connect(audioContext.destination);
    track11.connect(audioContext.destination);
    audioContext.resume();
  }, []);

  useEffect(() => {
    const audioElement0 = trackRef0.current;
    const audioElement1 = trackRef1.current;
    const audioElement2 = trackRef2.current;
    const audioElement3 = trackRef3.current;
    const audioElement4 = trackRef4.current;
    const audioElement5 = trackRef5.current;
    const audioElement6 = trackRef6.current;
    const audioElement7 = trackRef7.current;
    const audioElement8 = trackRef8.current;
    const audioElement9 = trackRef9.current;
    const audioElement10 = trackRef10.current;
    const audioElement11 = trackRef11.current;

    if (isPlaying) {
      audioElement0.pause();
      audioElement1.pause();
      audioElement2.pause();
      audioElement3.pause();
      audioElement4.pause();
      audioElement5.pause();
      audioElement6.pause();
      audioElement7.pause();
      audioElement8.pause();
      audioElement9.pause();
      audioElement10.pause();
      audioElement11.pause();
    } else {
      audioElement0.play();
      audioElement1.play();
      audioElement2.play();
      audioElement3.play();
      audioElement4.play();
      audioElement5.play();
      audioElement6.play();
      audioElement7.play();
      audioElement8.play();
      audioElement9.play();
      audioElement10.play();
      audioElement11.play();
    }
  }, [isPlaying]);

  const channels = tracks.map((track, i) => {
    return (
      <div key={track.path}>
        <audio ref={trackRef0} src={tracks[0].path}></audio>
        <audio ref={trackRef1} src={tracks[1].path}></audio>
        <audio ref={trackRef2} src={tracks[2].path}></audio>
        <audio ref={trackRef3} src={tracks[3].path}></audio>
        <audio ref={trackRef4} src={tracks[4].path}></audio>
        <audio ref={trackRef5} src={tracks[5].path}></audio>
        <audio ref={trackRef6} src={tracks[6].path}></audio>
        <audio ref={trackRef7} src={tracks[7].path}></audio>
        <audio ref={trackRef8} src={tracks[8].path}></audio>
        <audio ref={trackRef9} src={tracks[9].path}></audio>
        <audio ref={trackRef10} src={tracks[10].path}></audio>
        <audio ref={trackRef11} src={tracks[11].path}></audio>
      </div>
    );
  });
  console.log("channels", channels);

  return (
    <div>
      <h1>Audio Mixer</h1>
      <button onClick={() => setIsPlaying(!isPlaying)}>play</button>
      {channels}
    </div>
  );
}

export default App;

Hi. I’m trying to make an audio mixer using the web audio api. I’m having trouble figuring out how to name the refs. How can I create this component without hard coding every track?

In React, how to divert the scrolling to another element?

My APP has 3 divs: side, middle, and right.

The middle section will contain the content list of arbitrary number of items. It is set to the length of the vh. Thus, it will need to scroll when too many items are present.

The problem is when the user scroll over the side or right divs, nothing happens.

To solve, the problem, all scrolling should be diverted to the middle div, no matter where the pointer is hovering.

How can this be done in React?

Rails API – how to send especific information with action cable for front-end

I’m trying to send for front-end an especific information (how many registers I have, with a colunm null in database), with ActionCable, but I’m using Rails Api mode.

I’m generate a channel, and don’t create a authentication code (all can access), and create a method subscribed:

  def subscribed
    stream_from "password_channel"
  end

Configured CORS and WebSocket access.
After I call the channel with this code in controller, to send a message for subscribed clients.

PasswordChannel.broadcast_to("password_channel", { title: "Oi" })

And create this js for consume informations in WebSockets

let webSocket = new WebSocket("ws://localhost:3000/cable")

webSocket.addEventListener("message", function(event) {
    console.log(event)
})

This js return this object:

Object

But this object don’t have the information { title: “Oi” }

Here it is github repository

Can anyone help me figure out what I’m doing wrong? =)

Why is all the HTML on my react app so zoomed in?

I created a new react app using create-react-app and copied in a few lines of basic HTML from another project I built. It’s just a couple divs with H1s, buttons and p tags, so nothing crazy. The code and styling is identical, as I copied and pasted it (I did adjust the syntax to fit react). The issue is, on the react app everything is zoomed in SIGNIFICANTLY. I’ll include images though I doubt it’ll be clear in a screenshot aside from the massive text going off screen on react. No errors in the console, and the inspector confirms all styles are the same, but everything is noticeably bigger on the react version. Is this just how react behaves?
Opening the regular HTML file with code in browser

When opening same code with React

Doing something if a user reacts to a message Discord.js

I am trying to make an interactive game with a bot. If you haven’t heard of it, it is called high low. A random number 0-100 is chosen. Another random number is chosen. You are shown the second. You have to guess if the first number is higher, lower, or equal to the second. I want to make three reactions. One is an up arrow, one is down, one is an equal sign. How can I execute 3 unique functions when this happens?

(note that the bot will post a message that needs to have a reaction on it. The bot will react with the three emojis first, so these can not accidentally run the code. Thank you.)

Select2 Dropdown Styling

I’m a technical implementation analyst who works with web environments and I’m trying to implement Select2() in a board for a searchable dropdown list.

Basically, I have a input that uses BoardScript to dynamically add search options. I wanted the ability to type in and search through results so I found Select2 after doing some searching and after following the select2 web guide, my dropdown seems to be functioning properly with search function but the styling is all off. This is what it looks like:

Alpha, Beta, Delta are my three option values. You can see that the results are displayed in two columns for some reason, which is the main issue I’m trying to fix. The search bar is also tiny. I’ve googled everywhere to try to find out how I can edit the styling of the select2 input, but I can’t find what attributes to change even after reading the official docs.

Is there any way to directly style the select2 dropdown so the results are displayed on one column? Thanks.

How to use NPM instead of CDN in javascript? [duplicate]

I’m following three.js tutorial.

On the Manual – Installation from their page, it says that one can install it via NPM. I did. So I replace the CDN version (as shown in the commented out <script ...> in the index.html file below), and I add ES Module import syntax:

import * as THREE from 'three/build/three.module'

I also tried from 'three', but the results are the same:

mycode.js:1 
  Uncaught SyntaxError: Cannot use import statement outside a module

I did add the "type": "module" in the package.json, but it didn’t work too:

{
  "name": "test3",
  "version": "1.0.0",
  "description": "",
  "main": "./js/mycode.js",
  "type": "module",
  "scripts": {
    "dev": "npx live-server",
    "js": "nodemon .",
    "lint": "npx eslint"
  },

How can I loop this function where I decrement the values of a field from firestore?

I wanted to decrement the values of the color upon submitting the form. Now, there are instances where there could be multiple products in one submission. I have these form where the user can choose a product, enter the quantity, and the desired color, and could add another product, and so on.

This is what the data looks like if I will submit it:

enter image description here

And these are the firestore documents for the Shirt and Notebook

enter image description here enter image description here

How can I loop the function so I can decrement those chosen colors of the specific product above? What I did there was just hard coded the document ID of the specific product and then decrement it. Is there a way not to hard code it?

I’ve assumed that the qty is equal to 10 just to see if it really does decrement. And it does. Also, I’m not using any admin SDK.

      const qty = 10;

  async function updateData(color) {
    const docRef = doc(db, "products", "m08YmrlFxhxLxyc3hVjT");
    await updateDoc(docRef, {
      [`colorMap.Black`]: increment(-1 * qty),
      [`colorMap.Gold`]: increment(-1 * qty),
    });

    const docRef2 = doc(db, "products", "nN2w57SiDovbtQ6EBzGb");
    await updateDoc(docRef2, {
      [`colorMap.green`]: increment(-1 * qty),
      [`colorMap.red`]: increment(-1 * qty),
    });
  }

index.js where I submit the data:

import React from "react";
import { useForm } from "react-hook-form";
import FieldArray from "./fieldArray";
import ReactDOM from "react-dom";

import "./styles.css";
import { Button } from "@mui/material";

const defaultValues = {
  test: [
    {
      product: "",
      nestedArray: [{ size: "", color: "", design: "" }]
    }
  ]
};

function App() {
  const {
    control,
    register,
    handleSubmit,
    getValues,
    errors,
    reset,
    setValue
  } = useForm({
    defaultValues
  });
  const onSubmit = (data) => {
    console.log(data);
    try {
      //codes here to submit the data in the another collection
      //then a function to decrement the values.
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h1>Array of Array Fields</h1>
      <p>
        The following example demonstrate the ability of building nested array
        fields.
      </p>

      <FieldArray
        {...{ control, register, defaultValues, getValues, setValue, errors }}
      />

      <button type="button" onClick={() => reset(defaultValues)}>
        Reset
      </button>

      <Button type="submit">Submit</Button>
      {/* <input type="submit" /> */}
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

This is the rest of the forms:
https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-2-efwq6?fbclid=IwAR25MosMKxOk-Lyz23Lp7kbkuZSWaSXPSYSehOG-0L0PRhRGtQeZdzXzILk&file=/src/index.js

code check :i expect IndexPlus is 2 but it seems it becom 1+1=11,why?

enter image description here

description :

i expect the indexPlus 2 but it comes 11,what is wrong? and why?
see it in line 28 .

code:

var inputArr = [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]
console.log('before', inputArr)
var arr = []
//先遍历inputArr确定0的位置
for (key in inputArr) {
  if (inputArr[key] === 0) {
    arr.push(key)
  }
}
//将0移到数组最后面,通过位置交换实现
for (value of arr) {
  for (i = value; i < inputArr.length - 1; i++) {
    swap(i, i + 1)
  }
}

function swap(index, indexPlus) {
  var temp = inputArr[index]
  inputArr[index] = inputArr[indexPlus]
  inputArr[indexPlus] = temp
}
console.log('after', inputArr)

Nested arrays fetch issues react

I’m trying to fetch something from an API using React for my front end however the JSON data has some nested arrays in the main object and fetching them has been a trouble, I know there’s loads of sources regarding this but trust me I’ve been trying for 2 days now and I’ve watched loads of videos.. At this point I’m even doubting the API but its working as I just tested it.

import { isContentEditable } from '@testing-library/user-event/dist/utils';
import React, { useState, useEffect } from 'react'
export default function Posts() {
  const [post, getPost] = useState([])
  const API = '#';
  const fetchPost = () => {
    fetch(API)
      .then((res) => res.json())
      .then((res) => {
        console.log(res)
        getPost(res)
      })
  }
  useEffect(() => {
    fetchPost()
  }, [])
  return (
    <>
      <h2>Past Games</h2>
    
        {post.map((item) => 
          
        <div>{item.name}
        
        <ul>
        {item.winner.map((sub) => 
        <li>{sub.name}</li>
        )}
        </ul>
        </div>


        

        )}
  
    </>
  )
}

The error I get is –

   Uncaught (in promise) TypeError: item.winner.map is not a function

D3 and TypeScript: Instantiating text elements before appending

I need to instantiate several text elements programmatically from given data.
These text elements should be surrounded by a rectangle that has the width of the text element with the largest width. Like this:

enter image description here

Now at the moment I am using a method to create the textnode, that looks like this:

let textnodes = data.map(d => {
  let svgText = document.createElementNS(d3.namespaces['svg'],'text')
  let textNode = document.createTextNode(d.text)

  svgText.appendChild(textNode)
  return svgText
})

and then I compute the width like this and finally apply a maximum function, where getTextWidth is a self-made method :

Math.max(...textnodes.map(t=> {
      return t.firstChild ? this.getTextWidth(
        t.firstChild.nodeValue,
        this.config.attributesFontSize + "px " + this.config.attributesFont ) : 0
    }))

My question now is: Is there a way to create a SVGTextElement instead of using document.createElementNS(...)? The reason I am asking is, that SVGTextElement gives me the possibility to use the getBBox() method that gives me the width property for free. Ideally I would like to instantiate my text nodes like this:

data.map({ d => 
  let text = new SVGTextElement()
  text.setAttribute(...)
  ...
})

However using the constructor like this is permitted.

I don’t see any errors in my Angular code, but when I use the developer tools, the username doesn’t appear due to text interpolation errors

I don’t see any errors in my Angular code, but when I use the developer tools, the username doesn’t appear due to text interpolation errors.you know the answer?

authservice.ts

 public get useraccountValue(): Useraccount{
return this.useraccountSubject.value; }

Useraccount.ts

export class Useraccount{

id:string ='';
username: string='';
name:string='';
password:string='';
email:string=''; }

header.ts

user= this.authservice.useraccountValue;
 constructor(private authservice:AuthService) {
    //this.user
this.authservice.user.subscribe(x => this.user = x);
console.log(this.user);}

header.html

<ul class="info_ul">
    <li>{{user.username}}</li>
    <li><a (click)="logout($event)">logout</a></li>
</ul>