How to make a new Array of Object using data from backend which is array of objects?

Hi I am new to Angular and I want to bind my dropdown options with value as

[ { label: "name", value: "id"} ]

as in label should have the below names and the values as the below IDs ( in the image )

I have my backend data as

enter image description here

I want the id and name as my options value for the dropdown.
Please if anyone could guide me

p.s I tried using map function but all I am getting in the options is [object object]

How do I link a csv file to flask?

I have a CSV file of readings from a sensor that I would like to graph with chart.js on a flask server, however I am getting 404 errors when trying to access the CSV file, since I am getting 404 errors I am assuming that I need to actually path the CSV file in flask, but I cant figure out how to do this, I’m coming across a lot of irrelevant information about using flask to make and fill a database but I need to pass the database to an html page to parse for graphing.

Could someone please help me learn how to do this?

Code that I’m testing and playing around with for reading CSV files in JavaScript. Has the route specified in flask code below!

<script>
    //path is from html file location to db location is this right?
    d3.csv("../db/test.csv", function(data) {
        for (var i = 0; i < data.length; i++) {
            console.log(data[i].Test1);
            console.log(data[i].Test2);
            console.log(data[i].Test3);
        }
    });
</script>

Test CSV file.

Test1, Test2, Test3
1, 2, 3

404 Error Details

Any help to better understand how to do this is much appreciated!

forgot my flask code!

@app.route('/test')
def test():
    #every thing that links the csv to flask would go here? Or would I need a more specific function for the csv file?
    return render_template('test.html'), 201

How to connect local storage to button?

I am a beginner and learning by working on tutorials.
I am using the NASA API and displaying the images using a modal. The modals have a button, however, I don’t know how to connect it to the local storage and save it to the favourites section.
Appreciate any help, thanks.

https://jsfiddle.net/neg4byd5

  <!-- The Modal -->
  <div id="myModal" class="modal">
    <span class="close">&times;</span>
    <img class="modal-content" id="img01">
    <span><button>Add To Favourites</button></span>
    <div id="caption"></div>
  </div>


    // Save Text
    const saveText = document.createElement("p");
    saveText.classList.add("clickable");
    if (page === "results") {
      saveText.textContent = "Add To Favorites";
      saveText.setAttribute("onclick", `saveFavorite('${result.url}')`);
    } else {
      saveText.textContent = "Remove Favorite";
      saveText.setAttribute("onclick", `removeFavorite('${result.url}')`);
    }


// Update the DOM
function updateDOM(page) {
  // Get favorites from local storage
  if (localStorage.getItem("nasaFavorites")) {
    favorites = JSON.parse(localStorage.getItem("nasaFavorites"));
  }
  imagesContainer.textContent = "";
  createDOMNodes(page);
  showContent(page);
}


// Add result to favorites
function saveFavorite(itemUrl) {
  // Loop through the results array to select favorite
  resultsArray.forEach((item) => {
    if (item.url.includes(itemUrl) && !favorites[itemUrl]) {
      favorites[itemUrl] = item;
      // Show save confirmation for 2 seconds
      saveConfirmed.hidden = false;
      setTimeout(() => {
        saveConfirmed.hidden = true;
      }, 2000);
      // Set Favorites in Local Storage
      localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    }
  });
}

// Remove item from favorites
function removeFavorite(itemUrl) {
  if (favorites[itemUrl]) {
    delete favorites[itemUrl];
    localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    updateDOM("favorites");
  }
}

// On Load
getNasaPictures();

Link target unrecognized in iframe; opens in new tab

I’m working on a simple web interface that requires another web interface (that I don’t control) to be embedded, which unless someone has a better solution I’ve been serving via Apache reverse proxy to a sandboxed iframe.

The problem is, that web interface consists of a few frames of its own, and when I click a link in the navbar (<a href="main.htm" id="main.htm" target="main">LINKNAME</a>) targeting the main content frame, it opens in a new tab. If I open the reverse proxy in its own tab everything runs fine, I’ve just been unable to figure out why it’s not working properly in the iframe. At this point my assumption is that the “main” target isn’t being recognized but I don’t know why (the “_self” targets in the top and main frames do work properly).

<frameset framespacing="0" border="0" frameborder="0" rows="54,*"> 
    <frame name="top" noresize="" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" border="no" src="top.htm" target="_self"> 
    <frameset cols="166,*"> 
        <frame name="contents" target="main" src="navbar.htm" scrolling="auto" noresize="" marginwidth="5" marginheight="0"> 
        <frame name="main" src="main.htm" scrolling="auto" noresize="" target="_self" marginwidth="0" marginheight="0"> 
    </frameset> 
</frameset>

I’ve noticed that I get "Unsafe attempt to initiate navigation for frame with URL 'http://.../main.htm' from frame with URL 'http://.../navbar.htm'. The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors." in the console when clicking the links but not sure if it directly relates to the problem. I don’t understand why it considers main.htm to be an ancestor, as they’re both at the same level of the site’s hierarchy. Either way, I’m unable to allow it out of the sandbox, as it will set itself as the top level document by way of if(top!=self){top.location.href=location.href}.

Any thoughts?

why are we retuning a anonymous function in the below from JS [duplicate]

// Debouncing in Javascript
let counter = 0;
const getData = () => {
  // calls an API and gets Data
  console.log("Fetching Data ..", counter++);
}

const debounce = function(fn, d) {
  let timer;
  return function() {
    let context = this,
      args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      getData.apply(context, arguments);
    }, d);
  }
}

const betterFunction = debounce(getData, 300);
<input type="text" onkeyup="betterFunction()" />

how to use showMore showLess for top 20 users in angular

I have 20 top users with ranking by point, I got them from an api rest, so i’m trying to create a button (showMore – showLess).

At first it shows 10 users automatically and when i click showMore it will add the other 10 users that’s mean 20 users. but when i click showLess it will reduce the 10 users to show just the 10 users.

html code :

        <div class="col-md-6  text-center">
            <h2><strong>TOP 20 FANS</strong></h2>

            <div *ngFor="let top of top2" class="rank" style="width: 74%;">
                <div class="data-row">
                    <div class="row-user">
                        <div class="col-lg-4 col-md-7 col-sm-7 col-7">
                            <div class="rank-row">
                                <span class="logo-wrapper ">
                                    <img src={{top.photoUrl}}>
                                </span>
                                <div class="td-wrap"><a class="uni-link">{{top.firstname}} {{top.familyname}}</a>
                                </div>
                                <div class="location "> <img width="10px" src="../assets/localisation.png">
                                    france</div>
                            </div>
                        </div>
                        <div
                            class="col-lg-4 offset-lg-0 col-md-12 offset-md-0 col-sm-11 offset-sm-1 text-center">
                            <span><img width="25px" src="../assets/golden.png"> {{top.point}} PT</span>
                        </div>
                    </div>
                </div>
            </div>

ts code :

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  top2: any;



  constructor(private apiService: ApiService) { }


  ngOnInit() {
    this.getTop2();
  }

  getTop2() {
    this.apiService.gettop2().subscribe(res => {
      this.top2 = res;
      console.log(res)
    });

  }



}

so i’m trying to create array inside an array, and in every array i have 10 users for example :

array : [{ },{ },{ },{ },{ },{ },{ }….] —> [ [ { },{ },{ },{ }] , [ { },{ },{ },{ } ] ]

let data =[ ]

data = t[0]

showMore i++ –> data.push() t[1]

showLess i–

How to call a modal when I return data a partial view from the controller in ASP.NET MVC

I have a controller where I return data in a partial view and I would like to call a modal, how can it be done?

I leave you the details of my controller and view below .

Controller

 [HttpPost]
 public async Task<ActionResult> Items(List<string> items)

  {
             
   var dto = new ItemsDetails();
   dto = items;

  return PartialView($"~/Views/Items/ItemDetails.cshtml", dto);
  (Here I want to call a modal)

}
           
 

View
That is the modal that I want to call.

<!-- Modal -->

@model Application.ItemsDetails

<div class="modal fade" id="items" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <tbody>
    @foreach (var item in Model.Items)
    {
    <tr>
        <td class="small">@item.Barcode</td>
        <td class="small">@item.ErrorMsg</td>
        <br>

    </tr>
    }
</tbody>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Using mySQL in order to create a daily command?

still getting into the shift of things with this. So i’m currently using a system to create a discord.js command which can be ran by a player and then will go onto a 24 hour cooldown, however the issue with the system below is I have no real way to store when there cooldown expires. Currently it is using an array of IDs however a user could simply time there command with the refresh of the cache and then claim it twice in quick succession.

So my question is

Is there a way to handle a per user cooldown via mySQL, or should another method be looked into. Any answer is appreciated!

const { SlashCommandBuilder } = require("@discordjs/builders");
const connection = require("../db");

let claimedCache = []

const clearCache = () => {
    claimedCache = []
    setTimeout(clearCache, 1000 * 60 * 60 * 24)
}
clearCache()

module.exports = {
    data: new SlashCommandBuilder()
    .setName('daily')
    .setDescription('Claim your daily points'),

    
    async execute(interaction) {
        if (claimedCache.includes(interaction.user.id)) {
            interaction.reply({
                content: "You have already claimed your daily reward!",
                ephemeral: true
            })
            return
        }
        connection.query(`SELECT * FROM characters WHERE char_owner = '${interaction.user.id}'`, function(err, rows) {
            if (err || !rows.length) {
                interaction.reply({
                    content: "You do not have a character!",
                    epehemeral: true
                })
                return
            }
            const currentPoints = rows[0].char_points
            
            if (interaction.member.roles.cache.has('912680123113832448')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 4}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680385685635092')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 8}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680439095889971')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 12}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680476790120448')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 16}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            } else if (interaction.member.roles.cache.has('912680542091243570')) {
                connection.query(`UPDATE characters SET char_points = '${currentPoints + 16}' WHERE char_owner = '${interaction.user.id}'`)
                interaction.reply({
                    content: "You have claimed your daily reward!",
                    ephemeral: true
                })
                claimedCache.push(interaction.user.id)
                return
            }

            //connection.query(`UPDATE characters SET char_points = '${currentPoints + 4}' WHERE char_owner = '${interaction.user.id}'`)
        })
    }
}```

Webrtc screencapture or capturestream

Is there a way to capture on a specific part of the screen.. getting only the element or tag of HTML… I just want to share the video that is playing. I tried to find a solution. I tried the capturestream but the problem is there is no Output on my client-side. Any suggestion or who tried to stream only the video payer on capturestream?

Anyone who successfully broadcast live of the capturestream with broadcaster and client?

useState not working inside a custom react hook

I am Trying to separate some part of my business logic from view logic for this I am employing the use of custom react hooks which works like a controller.

My Component Structure

  1. Parent that contains toggle to switch between child 1 and child 2
  2. useCustomHook custom react hook that makes an api call and uses a state to add a loader
  3. child2 contains content to be shown which was retrieved from api call and state variable to show loader calls useCustomHook
  4. parent also calls useCustomHook which makes the api call on mount.

Why can’t I see loading on the page inside child 2 no matter how long it takes

I believe useState is setting flag to its default false when custom hook is called again on child 2

What way do i have to make use of useState hook in a custom react hook which is called from more than one place and not have the state reverted back to default value

flag is never true if you open child2

Here is the codesandbox link code

Here is the code

App.js acts as parent

import "./styles.css";
import Child1 from "./Child1";
import Child2 from "./Child2";
import { useEffect, useState } from "react";
import useCustomHook from "./customHook";
import { makeStyles } from "@material-ui/core";

const useStyles = makeStyles((theme) => {
  return {
    parent: {
      padding: "10px"
    },
    toggle: {
      margin: "10px",
      border: "1px solid black",
      display: "flex",
      justifyContent: "space-around"
    },
    child: {
      border: "1px solid black",
      width: "50%"
    }
  };
});

export default function App() {
  const [isChild1, setIsChild1] = useState(true);
  const classes = useStyles();
  const { flag, func } = useCustomHook();

  useEffect(() => {
    func();
  }, []);

  return (
    <div className="App">
      <div className={classes.parent}>Parent</div>
      <div className={classes.toggle}>
        <div
          onClick={() => {
            setIsChild1(true);
          }}
          className={classes.child}
        >
          ch1
        </div>
        <div
          onClick={() => {
            setIsChild1(false);
          }}
          className={classes.child}
        >
          ch2
        </div>
      </div>
      {isChild1 ? <Child1 /> : <Child2 />}
    </div>
  );
}

Child1.js

const Child1 = () => {
  return <div>Child1</div>;
};

export default Child1;

Child2.js

import useCustomHook from "./customHook";

const Child2 = () => {
  const { flag } = useCustomHook();

  console.log('flag ',flag);
  return (
    <div>
      <div>Child2</div>
      <div>{flag ? "loading..." : "content"}</div>
    </div>
  );
};

export default Child2;

CustomHook.js

import { useState } from "react";

const useCustomHook = () => {
  const [flag, setFlag] = useState(false);

  const sleep = async (ms) => {
    console.log("waiting");
    await new Promise((res, rej) => {
      setTimeout(() => {
        console.log("wait over");
      }, ms);
    });
  };
  const func = async () => {
    setFlag(true);

    //do some work like api call
    await sleep(10000);

    setFlag(false);
  };

  return { flag, func };
};

export default useCustomHook;

Typescript: Function accepting 2 Types but property doesn’t exist on one of the types

I have a function that takes 2 types.

handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) {
    e.stopPropagation();

    const newValue = this.computeValuesFromPosition(e.detail.x, e.detail.y, e.detail.variant);

    // other same code
})

the issue is that GridHandleDragEventType does not have a variant as part of the type. In those cases, I don’t mind sending null but I keep getting the TS issue:
Property 'variant' does not exist on type 'GridHandleDragEventType'. Is there a clean way to resolve this?

Eclipse is weird

enter image description here

Here, in this image, I have inserted the value of ‘int’ (number)variable=22, and in the braces beside ‘while’, I have entered (number < 20) and I have asked to print ‘alright’, and even the condition is not true here, the eclipse is printing ‘alright’!!

Highlighting text in Safari on iPad

I am developing an application that allows user to highlight text in a web app. With iOS on iPad many users would like to use their Apple Pencil to highlight text. While it is of course possible to highlight text by double tapping or holding the pencil down, I would like to enable users to activate a mode in which they can just brush over the text to highlight it.

Is there an API in Safari for iOS that enables such behaviour?

How to populate modal form inputs properly onto FullCalendar in javascript?

I am coming to an issue where I am trying to place the form details onto the calendar but I am stuck on this area. For testing purposes when I click on submit I am alerting the form details in that view. However, I just want it to be place on the calendar, similar to Google Calendar. Thank you for the help.
PS: Let me know if you want to see the html form as well.

here is my code:

Javascript:

    document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var myModal = new bootstrap.Modal(document.getElementById('schedule-edit'), {});
    var calendar = new FullCalendar.Calendar(calendarEl, {
        selectable: true,
        initialView: 'dayGridMonth',
        select: function(info, start, end, jsEvent) {
            myModal.show();
                if (info) {
               calendar.addEvent({
               title: title,
               start: info.startStr,
               end: info.endStr
               })
            calendar.unselect();
        },
    });
    calendar.render();
});

 function submitForm() {

        let title = document.getElementById("title").value || "";
        let project = document.getElementById("project").value || "";
        let time = document.getElementById("time").value || "";
        let timeSpent = document.getElementById("timeSpent").value || "";
        let description = document.getElementById("description").value || "";
        let editorS = document.getElementById("sampleeditor").value || "";
        let firstList = document.getElementById("firstList").value || "";
        let startDate = document.getElementById("myDate").value || "";
        let dueDate = document.getElementById("myDue").value || "";



        //for test only
       alert(title + project + time + timeSpent + description + editorS + firstList + startDate + dueDate);


    }