How to know which file called index.js?

I’ve three html files a.html,b.html & c.html

All of them call index.js.

Inside index.js, I’m importing a variable from a.js,b.js & c.js. Based on which html file called index.js , I want to use the variable from the corresponding js file inside index.js.

pic

It’s not possible for me to remove index.js as it contains logic, which is needed for some other tasks.

POST (Method Not Allowed): JavaScript Express Problem

Not sure why I keep getting a 405 error. My post request is getting rejected every time.

SERVER CODE

// getting datastores
const datastore = require('nedb');
const customerRecordsdb = new datastore('CustomerRecords.db');
customerRecordsdb.loadDatabase();

// importing express
const port        = 5500;
const express     = require('express');
const application = express();

application.listen(port, () => console.log("Listening at " + port));
application.use(express.static('public'));
application.use(express.json( {limit: '1mb'} ));
 
// CUSTOMER RECORD FUNCTIONS
application.get('/RetrieveCustomerInformation', (request, response) => {
    console.log(request, response)
    customerRecordsdb.find({}, (error, data) => {
        if (error) {
            response.end();
            return;
        }
        response.json(data);
    })
})

CLIENT CODE

function onFormSubmit() {
    let formData = readFormData();

    console.log("got here");

    if (selectedRow != null) { return }

    if (confirm("Are you sure you want to add this record to the database?:")) {
        insertNewRecord(formData);
        const options = {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(formData)
        }

        fetch('/RetrieveCustomerInformation', options)
        
    } else {
        if (confirm("Are you sure you want to edit this record?:")) {
            updateRecord(formData);
        }
     }
    resetForm();
}

DIRECTORY HIERARCHY
https://i.stack.imgur.com/fNSOh.png

ERROR
When I try to submit the post request to the server:
‘customerrecords.js:21 POST http://127.0.0.1:5500/RetrieveCustomerInformation net::ERR_ABORTED 405 (Method Not Allowed)’

React component taking more than 40 seconds to render

I’m trying to create a library to generate skeleton-loading components on the fly. I like those skeletons components with a shimmer effect, but I don’t want to create them manually. So my idea is something like this:
I create a component which receives the component that I want to load as a children
while loading, I render a copy of this component, but invisible
I iterate through the component elements, and render a skeleton component based on that
I’ve already made some progress so far, I created a nextjs boilerplate just for testing purposes, I’m new at opensource, and I will create a library with typescript and rollup when I’m done testing.
My code by now is in this repository: https://github.com/FilipePfluck/skeleton-lib-test
here is the core component:

const Shimmer = ({ children, isLoading, component: Component, exampleProps }) => {
    const fakeComponentRef = useRef(null)

    useEffect(()=>{
        console.log(fakeComponentRef.current.children)
    },[fakeComponentRef])
    
    const texts = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strong']
    const contents = ['img', 'video', 'button']

    const styleProps = ['borderRadius', 'padding', 'margin', 'marginRight', 'marginLeft', 'marginTop', 'marginBottom', 'paddingTop', 'paddingBottom', 'paddingLeft', 'paddingRight', 'display', 'alignItems', 'justifyContent', 'flexDirection']

    const renderElement = (element) => {
        console.log('renderElement')

        const object = {}
        styleProps.forEach(s => Object.assign(object, {[s]: element.style[s]}))

        if(texts.includes(element.localName)){
            const fontSize = +document.defaultView.getComputedStyle(element, null)["fontSize"].replace('px','')
            const lineHeight = +document.defaultView.getComputedStyle(element, null)["lineHeight"].replace('px','') | fontSize * 1.2
            const numberOfLines = Math.round(element.offsetHeight / lineHeight)
            const lineMarginBottom = lineHeight - fontSize

            const lines = []

            for(let i=0; i<numberOfLines; i++){
                lines.push(i)
            }

            return(
                <div style={{display: 'flex', flexDirection: 'column'}}>
                    {lines.map(line => (
                        <div 
                        style={{
                            width: element.offsetWidth,
                            ...object,
                            height: fontSize,
                            marginBottom: lineMarginBottom
                        }}
                        className="shimmer"
                        key={"line"+line}
                    />))}
                </div>  
            )
        }

        if(contents.includes(element.localName)){
            return (
                <div 
                    style={{
                        width: element.offsetWidth,
                        height: element.offsetHeight,
                        ...object
                    }}
                    className={'shimmer'}
                />
            )
        }

        return (
            <div 
                style={{
                    width: element.offsetWidth,
                    height: element.offsetHeight,
                    display: element.style.display,
                    alignItems: element.style.alignItems,
                    justifyContent: element.style.justifyContent,
                    flexDirection: element.style.flexDirection,
                    padding: element.style.padding,
                    margin: element.style.margin
                }}
            >
                {!!element.children 
                    ? [...element.children]
                        .map(child => renderElement(child))
                    : null
                } 
            </div>
        )
    }

    return isLoading ? (
        <>
        <div style={{visibility: 'hidden', position: 'absolute'}} ref={fakeComponentRef}>
        <Component {...exampleProps}/>
        </div>
        {fakeComponentRef?.current && renderElement(fakeComponentRef.current)}
        </>
    ) : children
}

Basically I’m doing a recursive function to render the skeleton component. But I got a problem: the loading component is taking too long to render. Sometimes it takes over 40 seconds. And this is a massive problem, a loading component should not take longer to render then the loading itself. But I have no clue why is it taking so long. Also, I know that there is a lot of other problems, but my first goal was to render the component on the screen. I’d be pleased if any of you wanted to contribute to my project

Uncaught error: listen EADDRINUSE: address already in use :::3500 (chai, chaihttp)

I am starting making unit tests to my restapi using chai but I am getting Uncaught Error from console. Testing manually is working fine but I dont understand why is giving me this errors when I run the unit test.

index.js

import express from 'express';
import ip from 'ip';
import dotenv from 'dotenv';
import cors from 'cors';
import Response from './domain/response.js';
import HttpStatus from './config/http.config.js';
import artistRoutes from './route/artist.route.js';
import albumRoutes from './route/album.route.js';
import trackRoutes from './route/track.route.js';
import albumxtrackRoutes from './route/albumxtrack.route.js';
import artistxtrackRoutes from './route/artistxtrack.route.js';
import logger from './util/logger.js';

dotenv.config();

const PORT = process.env.APP_PORT || 3050;
const app = express();

app.use('/artists', artistRoutes);
app.use('/albums', albumRoutes;
app.use('/songs', trackRoutes);
app.use('/albums/relation/', albumxtrackRoutes);
app.use('/artists/relation/', artistxtrackRoutes);
app.get('/', (req, res) => res.send(new Response(HttpStatus.OK.code, HttpStatus.OK.status, `Basic request message!`)));
app.all('*', (req, res) => res.status(HttpStatus.NOT_FOUND.code)
  .send(new Response(HttpStatus.NOT_FOUND.code, HttpStatus.NOT_FOUND.status, `Not existing route`)));

var server = app.listen(PORT, () => logger.info(`Server running on: ${ip.address():${PORT}`));

export default server;

And this is my index.test.js

import server from '../src/index.js';
import chai from 'chai';
import chaiHttp from 'chaihttp';

chai.should();
chai.use(chaiHttp);

describe("Testing RESTAPI", () => {
  
  describe("Testing Basic Request", () => {
    it ("Should return an ok message", (done) => {
      chai.request(server)
        .get('/')
        .end((err, response) => {
          response.should.have.status(200);
          done();
        });
    });
  });
});

And the message I got from console is like this:

1) Uncaught error outside test suite:
   Uncaught Error: listen EADDRINUSE: address already in use :::3050

I would appreciate any response, thank you!

Input Text unfocuses after each character is typed in, but it seems to be a target issue within React

I am creating a table using Material UI Table. I want to populate by fetching from api, which seems fine. Now, each row should display two buttons, one for removing that row by using the filter() method. And the other to modify the title.

For removing the row, I’m targeting the button’s parent ID which (the TableRow ID) and I’m filtering all the elements of the array whose index does not match the TableRow ID, this seems to be working fine, only thing is I have to use id - 1 so it matches the index number. That seems to be working fine.

For the editing of the title I’m having some issues. Here’s the step by step process:

  1. The Edit button toggles the disable value in the input so it becomes ‘editable’. The handleClickEdit function sets new state for data so the input is enabled.

  2. The input’s onChange runs the handleChange() function, this creates a new array and based on the id - 1 (like on the remove function) as an the index, it sets the title property of that object and then sets that new Array as the new state value for data. **One issue here is that on any character input the input field is unfocused and you have to click again to continue typing. Note that this doesn’t happen if I use id instead of id - 1, but it changes the field below. **

  3. The value is stored on state and when Done button is clicked, the handleDone function toggles the input field to disabled again.

  4. An extra and annoying issue of this approach is that if you remove a row, and then want to edit a row below the one that was removed, the edit targets the row below instead of that actual row.

Here’s my code:

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

import {
  TablePagination,
  Table,
  TableBody,
  TableFooter,
  TableContainer,
  TableRow,
  TableHead,
} from "@mui/material";

import TableCell from "@mui/material/TableCell";

function App() {
  const [data, setData] = useState([]);
  const [toggleEdit, setToggleEdit] = useState(false);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos?_limit=5")
      .then((res) => res.json())
      .then((data) => {
        setData(data.map((item) => ({ ...item, enableEdit: true })));
      });
  }, []);

  const removeRow = (e) => {
    const { id } = e.target.parentElement;
    let arr = data.filter((elem) => elem.id != id);
    setData(arr);
  };

  const handleClickEdit = (e) => {
    const { id } = e.target.parentElement;
    setToggleEdit(!toggleEdit);
    let newData = [...data];
    newData[id-1].enableEdit = !newData[id-1].enableEdit;
    setData(newData);
  };

  const handleChange = (e) => {
    const { value, id } = e.target;
    let newData = [...data];
    newData[id-1].title = value;
    setData(newData);
  };

  const handleDone = (e) => {
    const { id } = e.target.parentElement;
    let newData = [...data];
    newData[id-1].enableEdit = !newData[id-1].enableEdit;

    setData(newData);
    console.log(data[id-1]);
  };

  return (
    <div>
      <div className="table-container">
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>Album ID</TableCell>
                <TableCell>Title</TableCell>
                {/* <TableCell>Thumbnail</TableCell> */}
                <TableCell>Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {data.map((row) => (
                <TableRow id={row.id} key={row.id}>
                  <TableCell key={row.id + "_id"} id={row.id + "_id"}>
                    {row.id}
                  </TableCell>
                  <TableCell>{row.albumId}</TableCell>
                  <TableCell key={row.title} id={row.title}>
                    <input
                      type="text"
                      disabled={row.enableEdit}
                      className="title"
                      defaultValue={row.title}
                      id={row.id}
                      onChange={(e) => handleChange(e)}
                      name={"title"}
                    />
                  </TableCell>
                  {/* <TableCell><img src={row.thumbnailUrl} /></TableCell> */}
                  <TableCell id={row.id}>
                    <button onClick={(e) => removeRow(e)}>Remove</button>
                    {row.enableEdit && (
                      <button onClick={(e) => handleClickEdit(e)}>Edit</button>
                    )}
                    {row.enableEdit === false && (
                      <button onClick={(e) => handleDone(e)}>Done</button>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
            <TableFooter>
                </TableFooter>
          </Table>
        </TableContainer>
      </div>
    </div>
  );
}

export default App;

Is there a cleaner way to write this ternary statement? [closed]

Here’s a pretty simple function that sets up data that I use later on.

        const tributeDataArray = [];

        for (let i = 0; i < tributes.length; i++) {
            const { user } = tributes[i];

            const tributeObj = {
                name: user.username,
                id: user.id,
                avatar: user.displayAvatarURL({ format: 'png' }),
                alive: true,
                kills: [],
                killedBy: '',
                district: tributes.length === 2 ? i + 1 : Math.ceil((i + 1) / 2)
            };

            tributeDataArray.push(tributeObj);
        }

        return tributeDataArray;
    }

My main annoyance is tributes.length === 2 ? i + 1 : Math.ceil((i + 1) / 2), Is there a cleaner way to achieve this?

Function only grabbing the last index of the array in code.org program

I’m trying to help the kiddo with her AP project, her teacher said she can ask anyone for help, except her teacher. I went through her code but I don’t understand her program, I wanted to know if anyone in here could help out. Thankfully it’s not till May but she wants to do it early in case she runs into issues, and here we are. The website shes using is https://code.org/


I am having difficulty getting my code to grab my desired value from a dataset. I want it to grab a population level based on the location that the code outputs after the user selects their income in a dropdown. Once the user selects a certain income level, the app will provide a location by looking through the list and selecting a random country/territory that matches the income that has been selected.  I am trying to get the computer to grab the location given (after the income is selected and only if the income is selected as “High Income”) and use it to determine the correct population for that location. In other words, I want my append item to pull the population number from the randomly generated location given to the user after they input their income. After appending the item, I want my result to return the correct population for the location.

This is my else statement  
else if (incomeInput == "High Income")     appendItem(filterPopulation, finalDestination);     result = populationLevel[i];

“High income” is an income level option.
filterPopulation filters through my ‘PopulationLevel’ list
finalDestination is the location given after the user selects income
result is the string which I am using, trying to get it to return the population level for the location that the computer randomly selects after the income is given.

the result is currently only grabbing the index which I input into the [], or the last index if I just place [I].

var incomes = getColumn("Countries and Territories", "Income Level");
var populationLevel = getColumn("Countries and Territories", "Population");
var incomeInput = "";
var filterIncomeLevel = [];
var filterCountryName = [];
var filterPopulation = [];
var result = "";
var finalDestination = "";
setProperty("incomeLevelDropdown", "options", getColumn("Countries and Territories", "Income Level"));
hideElement("population");
hideElement("populationLabel");
onEvent("generateButton", "click", function( ) {
  filterIncomeLevel = [];
  filterCountryName = [];
  incomeInput = getText("incomeLevelDropdown");
  incomesList(incomeInput);
  setText("travelLocationOutput", randomLocation(filterCountryName));
});

function incomesList(incomeInput) {
  hideElement("population");
  hideElement("populationLabel");
  for (var i = 0; i < incomes.length; i++) {
  if (incomeInput==incomes[i]) {
      appendItem(filterIncomeLevel, incomes[i]);
      appendItem(filterCountryName, countryName[i]);
    } else if ((incomeInput == "High Income")) {
    showElement("population");
    showElement("populationLabel");
    appendItem(populationLevel, finalDestination);
    result = populationLevel[i];
  }
  }
}

function randomLocation(filterCountryName) {
  finalDestination = filterCountryName[(randomNumber(0,filterCountryName.length-1))];
  return finalDestination;
}


onEvent("dontKnow", "click", function( ) {
  setScreen("doNotKnowIncome");
});

// Found out how to do this from https://studio.code.org/projects/applab/pqdXRVMfu8QWW3-L1DO9FIh2RFQqWEG9O9qmQeRynyY/view
// Website is https://www.pewresearch.org/fact-tank/2020/07/23/are-you-in-the-american-middle-class/
onEvent("findIncomeButton", "click", function( ) {
  open("https://www.pewresearch.org/fact-tank/2020/07/23/are-you-in-the-american-middle-class/");
});

onEvent("backArrow", "click", function( ) {
  setScreen("inputsAndLocations");
});```

I am trying to set this webiste to ejs. but i can not get the css or js to load

Here is my routing page code. Im not really sure on what i have done wrong here. any one know?

// import 
const express = require('express')
const req = require('express/lib/request')
const res = require('express/lib/response')
const app = express()
const port = 3000

//Static Files

app.use(express.static('assests'))
app.use('/css', express.static(__dirname + 'assets/css'))
app.use('/icons', express.static(__dirname + 'assets/icons'))
app.use('/img', express.static(__dirname + 'assets/img'))
app.use('/js', express.static(__dirname + 'assets/js'))

// Set Views
app.set('views', './views')
app.set('view engine', 'ejs')

app.get('',(req, res) => {
    res.render('index')
})

// Listen on port 3000
app.listen(port, () => console.info(`Listing on port ${port}`))

Here is my file set up

Angular streaming audio player

i have been on this problem for a while, haven’t figured a way around it, i was actually building this audio player website and everything seems working well except from the audio player itself, after fetching the resources from my spring boot api, i cant initialize each resource with its specific information, when i click the play button on one resource, the slider moves for all resource… this is a screenshot of my site to get a better understanding…

enter image description here

This is when the page is first loaded, the slider is not initialized to 0.00 which is the start position, and when i play a resource, i get this…

enter image description here

So i got this code online, but the code was made for just one resource, so i was trying to see how i can get it to work for multiple resource but am out of luck, this is my .html code…

<ng-container *ngIf="appState.appData.data.beats['content'].length > 0">
                    <div class="row car-filter">
                        <div class="col-lg-3 col-md-4 col-sm-6 mix"
                            *ngFor="let beat of appState.appData.data.beats['content']; let i=index">
                            <div class="car__item card" style="background-color: black;">
                                <div class="card-body" style="padding: 0;" >
                                    <div class="car__item__pic__slider">
                                        <img [src]='clientApiUrl+"/"+beat?.artWork' alt="artwork"
                                            style="max-width: 300px; border:0;position: relative; object-fit: cover;" height="169px">
                                        <button class="btn shadow-md"
                                            style="position:absolute;left:0; border-radius: 100%;top: 25%;width:100%;" (click)="playStream(clientApiUrl+'/'+beat?.uri)" [disabled]="state?.error">
                                            <i class="fa fa-3x shadow-md fa-play-circle" *ngIf="!(playing$ | async)" style="color: #d5eebb"></i>
                                            <i class="fa fa-3x shadow-md fa-pause-circle" *ngIf="(playing$ | async)" style="color: #5f7a61;"></i>
                                        </button>
                                    </div>
                                    <div style="margin: 0; padding: 4px 8px; color: white;">
                                        <div class="song-slider">
                                            <input type="range" min="0" [max]="state?.duration" step="0.01" [value]="state?.currentTime" (input)="onSliderChangeEnd($event)" [disabled]="state?.error" class="seek-bar">
                                            <div class="d-flex justify-content-between align-items-center">
                     
                                                <span class="current-time">{{ state?.readableCurrentTime }}</span>
                                                <span class="song-duration">{{ state?.readableDuration }}</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-details">
                                        <p class="card-text">{{ beat?.name }}</p>
                                        <small style="color: silver; font-size: 10px;">{{ beat?.genre.name}}</small>
                                        &nbsp; | <small style="color: silver; font-size: 10px;">{{
                                            beat?.mood.name}}</small>
                                        &nbsp; | <small style="color: silver; font-size: 10px;">{{
                                            beat?.beatKey.name}}</small>
                                    </div>
                                    <div id="cartbtns">
                                        <div class="row">
                                            <div class="col-md-6 mp3btn">
                                                <button class="btn btn-block" (click)="addToCart(beat, 'MP3')"
                                                    style="background-color: #5cfe34;border-radius: 0%; position: relative;">
                                                    <i class="fa fa-shopping-cart"
                                                        style="font-size: 15px; color: gray;"></i>&nbsp;
                                                    <span
                                                        style="color: white; font-weight: 500; font-size: 12px;">${{beat?.priceMp3.toFixed(2)}}</span>
                                                    <sup style="position:absolute;right:0;top: 6px;">
                                                        <span class="label label-info"
                                                            style="font-size: 9px; border-color: lightgrey; color: white;padding: 2px;">mp3</span>
                                                    </sup>
                                                </button>
                                            </div>
                                            <div class="col-md-6 wavbtn">
                                                <button class="btn btn-block" (click)="addToCart(beat, 'WAV')"
                                                    style="background-color: #221F1F;border-radius: 0%;position: relative;">
                                                    <i class="fa fa-shopping-cart"
                                                        style="font-size: 15px; color: gray;"></i>&nbsp;
                                                    <span
                                                        style="color: white; font-weight: 500; font-size: 12px;">${{beat?.priceWav.toFixed(2)}}</span>
                                                    <sup style="position:absolute;right:0;top: 6px;">
                                                        <span class="label label-warning"
                                                            style="font-size: 9px;border-color: lightgrey; color: white; padding: 2px;">wav</span>
                                                    </sup>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row align-items-center justify-content-center mt-2">
                        <div class="align-self-baseline pt-2 col-md-12 text-center">
                            <a class="btn btn-light btn-xl js-scroll-trigger text-uppercase" href="beats">Check Out
                                More</a>
                        </div>
                    </div>
                </ng-container>

and the .ts file for this component…

playing: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  playing$ = this.playing.asObservable();
  files: Array<any> = [];
  state :StreamState;
  state$ = this.audioService.getState();
  currentTime: BehaviorSubject<string> = new BehaviorSubject<string>('00.00');
  currentTime$ = this.currentTime.asObservable();
constructor(private beatService: BeatServiceService,
    private cartService: CartServiceService,
    private toastrService: ToastrService,
    private router: Router, private audioService: AudioService) {
    this.cartItem = new CartItem();
    this.search = '';
    this.sortBy = "id";
    this.page = 0;
    this.audioService.getState().subscribe(state => {
      this.state = state;
    });
  }

  ngOnInit(): void {
  }

  playStream(url) {
    this.audioService.playStream(url).subscribe(events => {
      this.playing.next(true);
    });
  }
  pause() {
    this.audioService.pause();
  }
  play() {
    this.audioService.play();
  }
  stop() {
    this.audioService.stop();
  }

  onSliderChangeEnd(change) {
    this.audioService.seekTo(change.value);
  }

And my audio-service.ts is…

export class AudioService {

  private date: Date;
  private stop$ = new Subject();
  private audioObj = new Audio();
  beat: Beat;
  private readonly adminApiServerUrl = environment.apiBaseUrl.admin;
  clientApiServerUrl = environment.apiBaseUrl.client;
  private state: StreamState = {
    playing: false,
    readableCurrentTime: '',
    readableDuration: '',
    duration: undefined,
    currentTime: undefined,
    canplay: false,
    error: false,
  };

  stateChange: BehaviorSubject<StreamState> = new BehaviorSubject(this.state);

  private resetState() {
    this.state = {
      playing: false,
      readableCurrentTime: '',
      readableDuration: '',
      duration: undefined,
      currentTime: undefined,
      canplay: false,
      error: false
    };
  }

  getState(): Observable<StreamState> {
    return this.stateChange.asObservable();
  }

  private updateStateEvents(event: Event): void {
    switch (event.type) {
      case "canplay":
        this.state.duration = this.audioObj.duration;
        this.state.readableDuration = this.formatTime(this.state.duration);
        this.state.canplay = true;
        break;
      case "playing":
        this.state.playing = true;
        break;
      case "pause":
        this.state.playing = false;
        break;
      case "timeupdate":
        this.state.currentTime = this.audioObj.currentTime;
        this.state.readableCurrentTime = this.formatTime(
          this.state.currentTime
        );
        break;
      case "error":
        this.resetState();
        this.state.error = true;
        break;
    }
    this.stateChange.next(this.state);
  }

  constructor() { }

  audioEvents = [
    "ended",
    "error",
    "play",
    "playing",
    "pause",
    "timeupdate",
    "canplay",
    "loadedmetadata",
    "loadstart"
  ];
  
  private streamObservable(url: string) {
    return new Observable(observer => {
      // Play audio
      this.audioObj.src = url;
      this.audioObj.load();
      this.audioObj.play();

      const handler = (event: Event) => {
        this.updateStateEvents(event);
        observer.next(event);
      };

      this.addEvents(this.audioObj, this.audioEvents, handler);
      return () => {
        // Stop Playing
        this.audioObj.pause();
        this.audioObj.currentTime = 0;
        // remove event listeners
        this.removeEvents(this.audioObj, this.audioEvents, handler);
        // reset state
        this.resetState();
      };
    });
  }

  private addEvents(obj, events, handler) {
    events.forEach(event => {
      obj.addEventListener(event, handler);
    });
  }

  private removeEvents(obj, events, handler) {
    events.forEach(event => {
      obj.removeEventListener(event, handler);
    });
  }

  playStream(url) {
    return this.streamObservable(url).pipe(takeUntil(this.stop$));
  }

  play() {
    this.audioObj.play();
  }

  pause() {
    this.audioObj.pause();
  }

  stop() {
    this.stop$.next();
  }

  seekTo(seconds) {
    this.audioObj.currentTime = seconds;
  }

  formatTime(time: number, format: string = "HH:mm:ss") {
    const momentTime = time * 1000;
    return moment.utc(momentTime).format(format);
  }

}

I will really appreciate i can get assisted with this, i know the codes are really lengthy but i didnt want to leave anything out, thank you all…

How to assign audio to text in HTML by JavaScript?

Dear stackoverflow community,

I need your help with being able to create the most simple JavaScript code to add the appropriate audio clip to each line/sentence in a HTML-document. I mean the example document shown here contains sentences between paragraph tags and each sentence has its audio clip („audio_01.mp3”, „audio_02.mp3” … and so on) in an „audio” folder. Please, write me the simplest JS code to play the audio clip in accordance with each sentence by clicking on its text. Thanks for your help in advance.

ENGLISH HOMONYMS

The bandage was wound around the wound.

The farm was used to produce produce.

The dump was so full that it had to refuse more refuse.

We must polish the Polish furniture.

He could lead if he would get the lead out.

The soldier decided to desert his dessert in the desert.

Calculating on objects in recursive function

I’m trying to make a function that calculates the percentage of “completed tasks” in a recursive manner.

Here’s what I have now, but this only calculates the percentage on the parent, not grandparent etc:

const tasks = [
    { id: 1, task: 'Clean apartment', completed: null, parentId: null},
    { id: 2, task: 'Make app', completed: null, parentId: null},
    { id: 3, task: 'Clean bathroom', completed: null, parentId: 1},
    { id: 4, task: 'Clean kitchen', completed: null, parentId: 1},
    { id: 5, task: 'Wash sink', completed: true, parentId: 3},
    { id: 6, task: 'Wash shower', completed: null, parentId: 3},
    { id: 7, task: 'Wash glass panes', completed: null, parentId: 6},
    { id: 8, task: 'Wash floor', completed: null, parentId: 6},
]

function compileTask(tasks, taskId) {
    var task = (typeof taskId === 'number') ? tasks.find(task => task.id === taskId) : taskId;
    var children = tasks.filter(t => t.parentId === task.id);

    task.percent = children.filter(c => c.completed === true).length / children.length * 100


    task.children = children.map(child => compileTask(tasks, child));
    return task
}

console.log(compileTask(tasks, 1))

As you see, task id 3 is 50% completed because one of the two child tasks are marked completed, but task id 1 is 0% completed. If I’m calculating right in my head, task id 1 should return 25% completed.

Any tips?

How to group array of objects by certain property values

I have a two arrays.
One array with strings which contains names

let companies = ['Google', 'Coca Cola,' 'Jonson & Jonson',];

And another array contains objects with people

let employees = [
  {name: 'Alina' company: 'Google', id : 1},
  {name: 'Vika' company: 'Coca Cola', id : 2},
  {name: 'Alex' company: 'Jonson & Jonson', id : 3},
  {name: 'Vlad' company: 'Google', id : 4},
  {name: 'Fibi' company: 'Coca Cola', id : 5},
  {name: 'Joey' company: 'Google', id : 6},
]

And my task is to group those people by names

const groups = [
 {'Google': [
   {name: 'Alina' company: 'Google', id : 1},
   {name: 'Vlad' company: 'Google', id : 4},
 ]},
 'Jonson & Jonso': [
   {name: 'Alex' company: 'Jonson & Jonson', id : 3},
 ]},
 ...
]

Maybe anyone knows how to do it the simplest way and without extra iterations for JS ?
I could use a nested loops but it would be too complicated.
Maybe it’s possible to do with lodash ?
Also please note that string keys for company names may have spaces.
Will be very grateful for any advices.

How should I pass multiple outputs to model.fit()?

I’m working on a simple model with two outputs (image & labels) per input (latent vector.) This is reflected in the model topography with it having one input layer, and then two output points. To describe it briefly it looks roughly like:

const input = tf.input({ shape: [64, 64, 3] })

// multiple convolution and activation layers here. Call them `convolutions`

const imageOutput = tf.layers.conv2dTranspose({ kernelSize: 3, strides: 1, filters: 3 , padding: 'same', activation: 'relu'}).apply(convolutions)

// This is a custom layer I wrote that invokes another model.
const labelLayer = new DiscriminationLayer({ discriminator: this.discriminator }).apply(imageOutput)

this.model = tf.model({ inputs: input, outputs: [genImageOutput, discrimLayer] })
this.model.compile({ optimizer: this.optimizer, loss: ['meanSquaredError', 'binaryCrossentropy'], metrics: ['accuracy'] })

This runs fine and gives no errors. The problem is when I try to call model.fit() to train it. Which I do as so

await this.model.fit(this.getRandomLatentVectors(10), [this.generateTrainingImages(10), tf.ones([10, 1])], {
  batchSize: 2, epochs: 1, validationSplit: 0.1, shuffle: true, verbose: true
})

This keeps generating the following error:

/node_modules/@tensorflow/tfjs-layers/dist/tf-layers.node.js:19223
            if (array.shape.length !== shapes[i].length) {
                            ^

TypeError: Cannot read properties of undefined (reading 'length')

I’ve checked all of the tensors I’m passing in and all have the proper batch and dimension sizes. What is the problem then? Any advice would be appreciated.