getting rid of to display polygons on top of image with .tif extension

I am working with displaying polygons on an image using d3 svg and as shown below in the javascript code i am creating img tag element and appending it to ‘template’and then appending svg to ‘template’ so that polygons appear on the image.

        var template = document.createElement('div');
         var img = document.createElement('img');
             img.setAttribute("src", images[i].source);
             template.appendChild(img);
       var bb = d3.select(template).append("svg")
                        .attr("width",width)
                        .attr("height",height)
                        .attr("id", "polygons");

…

    <img src="TSU/images/21021.jpg">
        <svg width="1920" height="1080" id="polygons">
          <g><rect x="1296 " y="229 " height="231" width="250" stroke="red"></rect>
      </g>
       </svg>

…

But I have a set of images with .tif extension and I am using seikichi/tiff Library but as shown below in the code the image is appended to an canvas element and that’s how the image is displayed,

but as mentioned above I need ‘img’ tag not ‘canvas’ cause D3 doesnt use the canvas element,it needs the ‘img’ to be able to append svg on top of the image,

and thats why the images are displayed but polygons arent displayed on top of the image.I also tried to manipulate the.toCanvas() to work with svg but it is still not displaying the polygons on top of the image.

            var xhr = new XMLHttpRequest();
            xhr.responseType = 'arraybuffer';
            xhr.open('GET', imagesource);
            xhr.onload = function (e) {
           var tiff = new Tiff({buffer: xhr.response});
           var canvas = tiff.toCanvas();
           template.append(canvas)

           };
          xhr.send();

What can I do to render this EJS template file?

My app does not work. I’ve reduced the code to bare basics trying to find the mistake. Any ideas?

This is the project file structure. There are no other files or folders besides the listed below.

  • Project folder (folder)
    • app.js (file)
    • views (folder)
      • home.ejs (file)

This is the app.js content:

// jshint esversion:6
const express = require(`express`);
const ejs = require(`ejs`);
const app = express();

app.set(`view engine`, `ejs`);

app.get("/", function(req, res) {
  res.render(`home`);
});

app.listen(3000, function() {
  console.log(`The server is now on.`);
});

This is the home.ejs content:

<!DOCTYPE html>
<html lang=`en` dir=`ltr`>

<head>
  <meta charset=`utf-8` />
  <title>Secrets</title>
</head>

<body>
  <h1>Secrets</h1>
</body>

</html>

I ran npm init to create this app and npm i express ejs to install the dependencies.

The error I get is the following:

Error: Failed to lookup view “home” in views directory…full path

Any ideas why this is not running properly?

Uncaught Error: [ProtectedRoute] is not a component [duplicate]

I’m using react router dom v6, and trying to follow a tutorial which uses v5.

my error is Uncaught Error: [ProtectedRoute] is not a component.All component children of must be a or <React.Fragment>

This is my protectedRoute.js, I replaced Redirect with Navigate

import React, { Fragment } from "react";
import { useSelector } from "react-redux";
import { Navigate, Route } from "react-router-dom";

const ProtectedRoute = ({ isAdmin, component: Component, ...rest }) => {
const { loading, isAuthenticated, user } = useSelector((state) => state.user);

return (
<Fragment>
  {loading === false && (
    <Route
      {...rest}
      render={(props) => {
        if (isAuthenticated === false) {
             return <Navigate to="/login" />;
         }

        if (isAdmin === true && user.role !== "admin") {
          return <Navigate to="/login" />;
         }

           return <Component {...props} />;
        }}
    />
    )}
  </Fragment>
);
 };

export default ProtectedRoute;

and this is my app.js, i’m using element instead of component, I dont know where should I change that in the ProtectedRoute.js

import './App.css';
 import Header from "./components/layout/Header/Header"
 import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'
 import React from "react";
 import WebFont from 'webfontloader';
 import Footer from "./components/layout/Footer/Footer"
 import Home from "./components/Home/Home";
 import ProductDetails from "./components/Product/ProductDetails"
 import Products from "./components/Product/Products"
 import Search from "./components/Product/Search"
 import LoginSignUp from './components/User/LoginSignUp';
 import store from "./store"
 import { loadUser } from './actions/userAction';
 import UserOptions from "./components/layout/Header/UserOptions"
 import { useSelector } from 'react-redux';
 import Profile from "./components/User/Profile"
import ProtectedRoute from './components/Route/ProtectedRoute';

function App() {

 const {isAuthenticated, user} = useSelector(state=>state.user)
 React.useEffect(() => {

  WebFont.load({
  google:{
    families: [ "Droid Sans", "Chilanka"],
  },
  });

 store.dispatch(loadUser())
 }, []);

 return (
   <Router>
  <Header/>
   {isAuthenticated && <UserOptions user={user} />}
  <Routes>
    <Route exact path="/" element={<Home/>}/>
    <Route exact path="/product/:id" element={<ProductDetails/>}/>
    <Route exact path="/products" element={<Products/>}/>
    <Route path="/products/:keyword" element={<Products/>}/>
    <Route exact path="/search" element={<Search/>}/>
    <ProtectedRoute exact path="/account" element={<Profile/>}/>
    <Route exact path="/login" element={<LoginSignUp/>}/>
  </Routes>
<Footer/>
 </Router>
 );
 }

 export default App;

OpenStreetMap vanishes and popups are visible in wrong geolocations

I’m making a website using leafletjs and openstreetmap. I am populating the markers using jeojson format. However I see that map is greyed out and markers appear in improper locations. And when I click on the markers I get proper popups.I’m new to javascript and openstreetmaps, can anyone help me solve this issue?

Json file :

var url = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "name": "Bicycle",
                "Area": "Helsinki",
                "Price": `<p> "Costco": "$80"<br/>
                          "Target": "$95"<br/>
                          </p>`
            },
            "geometry": {
                "type": "Point",
                "coordinates": [60.1699, 24.9384]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "name": "ToyCar",
                "Area": "Tokyo",
                "Price": `<p>"Regular": "$20"<br/>
                            "Premium": "$30"<br/>
                            </p>`
            },
            "geometry": {
                "type": "Point",
                "coordinates": [35.6762, 139.6503]
            }
        }
    ]
      
};  

var map = L.map('Map');
var osmTiles = L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18
}).addTo(map);
var baseLayer = {
        "Open Street Map": osmTiles
};
    
var featureLayer = new L.geoJSON(url, {
    onEachFeature: function (feature, layer) {
        var popupContent = [];
        // render properties
        for (var key in feature.properties) {
            popupContent.push(key + ": " + feature.properties[key]);
        }
       // render coordinates
        if(feature.geometry.type === "Point")
        {
            popupContent.push("Latitude: " + feature.geometry.coordinates[1]);
            popupContent.push("Longitude: " + feature.geometry.coordinates[0]);
        }
        layer.bindPopup(popupContent.join("<br/>"));
}}).addTo(map); 
map.fitBounds(featureLayer.getBounds()).zoomOut(2);
var overlay = {
    "Features": featureLayer
}
var layerControl = new L.control.layers(baseLayer, overlay, {
    collapsed: false
});
map.addControl(layerControl);

HTML code:

<!DOCTYPE html>
<html lan="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="./CSS/style.css" />
    <link
      rel="stylesheet"
      href="https://unpkg.com/[email protected]/dist/leaflet.css"
      integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
      crossorigin=""
    />
    <title>Price</title>
  <body>
    <div id="Map"></div>

    <script
      src="https://unpkg.com/[email protected]/dist/leaflet.js"
      integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
      crossorigin=""
    ></script>

    <script src="./Javascript/test.js"></script>
  </body>
</html>

Output:

enter image description here

replace duplicates in an array with new values from object

I’m trying to “flatten” an array that has multiple duplicate values. The array is created from a CSV that I’m then trying to run API requests on.
The format of the CSV is as follows:

Posts | Comments | 
post1   comment1
post1   comment2
post1   comment3
post2   comment1
post2   comment2
post2   comment3

I’m using Papaparse which returns:

[{Post: 'post1', Comment: 'comment1'}, {Post: 'post1', Comment: 'comment2'}, ...]

So I thought I would try to flatten them to where it would look like:

[{Post: 'post1', {Comment: 'comment1'}, {Comment: 'comment2'}}]

I tried using a .map and referencing the index to check if the previous Post was the same as the current Post if it is then .push to the previous index which I can’t do using .map

What would be the correct way of doing this?

React – matching data from an object and passing it as props to another component that display dynamically

I am storing my data in JS array. After that I am using map function to display components with specific data. Until then, everything works.
After I click component I want to display a PopUp component that display more specific data from the data.js file. How can I pass it as props and match correct data to correct component? At this moment after I click it always shows me the same text.

My data.js file:

export const data = {
  projects: [
    {
      name: "Project1",
      image: require("../assets/img/Project1.PNG"),
      description: "Set number 1",
      technologies: "REACT",
      link: "github.com",
    },
    {
      name: "Project2",
      image: require("../assets/img/Project2.PNG"),
      description: "Project number 2 - description",
      technologies: "C#",
      link: "github.com",
    },

This is my PopUp.js that should display more specific data:

function Popup({ project, description }) {
  return (
    <Wrapper>
      <p>Project name is: {project}</p>
      <p>Description is: {description}</p>
    </Wrapper>
  );
}

And here I map my data and here is the problem.
How can I pass it?

function Projects() {
  const [isOpen, setIsOpen] = useState(false);

  const togglePopup = () => {
    setIsOpen(!isOpen);
  };

  return (
    <Wrapper>
      {data.projects.map((proj) => (
        <ProjectContainer background={proj.image} onClick={togglePopup}>
          {isOpen && (
            <Popup project={proj.name} description={proj.description} />
          )}
        </ProjectContainer>
      ))}
    </Wrapper>
  );
}

Really thanks for all of the answers!

send image ad a field of json with fetch – javascript

i have a payload for fetch body that is like below

{
"name": "test",
"description": "test",
"images": {}
}

the problem is the images field is actually an image that uploaded by user but when i use JSON.stringify to send proper json to api, images field is turn to empty object {} and actual image is gone.
what should i do right now?

search form input should show data entries form databank

I have some issues with my “search input form”. I want to search via input some entries in my databank. The problem is if I click on the button only one entries is shown, instead of two entries? If I print $row, one row from the databank is displayed instead of 2 => The query is correct(I believe;)

Thank you very much

<?php
if(isset($_POST["search_EEG"])){
    
                
    $u_search_EEG = filter_var($_POST["search_EEG_i"], FILTER_SANITIZE_STRING);     
    if (empty($u_search_EEG)){
    }else
    {
    if ($con->connect_error) {
        die('Error : ('. $con->connect_errno .') '. $con->connect_error);
    }
    $sql = "SELECT * FROM `registered_EEG` WHERE `operator_villages` LIKE '%$u_search_EEG%'";  
    $result = mysqli_query($con, $sql);  
    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);  
    
        echo $row["model_type"]; 
        echo "<br>";
    
    }
 
}
?>

Why Is My Ref(Worklist) Data Table Not Updating With WatchEffect? Vue 3/Javascript

(Using Pinia, Vue 3 Composition API, with Script Setup tag)

I’m using a Pinia store to contain a Ref array called worklists

worklists: ref([]) as Ref<Worklist[]>

In the store, I have a getWorklists method which does a fetch GET to my .NET API. I first clear the worklists array, then repopulate it with the results form the GET as shown below.

  getWorklists(): void
  {
    //Clear values from store before repopulating with results from new GET
    this.worklists = [];
    this.worklistMenuItems.splice(0);

    fetch(apiURL + 'Worklists',
    {
      headers:
      {
        "Accept": "application/json",
        "Content-Type": 'application/json'
      }
    })
    .then(response => 
      {
        return response.json();
      })
    .then(data =>
      {
        data.forEach((worklist: Worklist) =>
        {
          const wl = new Worklist(worklist.id, worklist.worklistName);
          this.worklists.push(wl);
          
          //Dynamically adding items to View Worklist MenuBar Item
          //Adds an icon for each, displays worklist name and creates a page route to /worklistname
          const wlItem = ref(
            {
              label: worklist.worklistName,
              icon:'pi pi-fw pi-file',
              to: `/worklist/${worklist.worklistName}`
            }) as Ref<object>;

          this.worklistMenuItems.push(wlItem.value);
        })
      })
  },

I have a DataTable PrimeVue component which displays the worklists stored in the worklists ref.

            <DataTable 
                ref="dataTable" 
                :value="store.worklists" 
                v-model="store.worklists"
                dataKey="worklistName"
                :paginator="true" :rows="5" :filters="filters"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 25, 100]"
                currentPageReportTemplate="Showing {first} to {last} of {totalRecords} worklists"
                responsiveLayout="scroll" 
                class="p-datatable-sm dataTable ml-3 mr-3 pl-4">

                <template #header>
                    <div class="flex items-center justify-between p-d-flex p-flex-column p-flex-md-row p-jc-md-between">
                        <h5 class="p-mb-2 p-m-md-0 p-as-md-center"> Manage Worklists </h5>
                        <span class="p-input-icon-left">
                            <i class="pi pi-search" />
                            <InputText v-model="filters['global'].value" placeholder="Search..." />
                        </span>
                    </div>
                </template>

                <Column 
                    field="worklistName" 
                    header="Worklist Name" 
                    style="width:100%">
                </Column>

                <Column>
                    <template #body="slotProps">
                        <div class="flex gap-2">
                            <!-- <Button 
                                icon="pi pi-pencil" 
                                class="p-button-rounded p-button-success p-mr-2"
                                @click="editWorklistItem(slotProps.data)" /> -->

                            <Button 
                                icon="pi pi-trash" 
                                class="p-button-rounded p-button-danger p-ml-2"
                                @click="confirmDeleteWorklistItem(slotProps.data)" />
                        </div>
                    </template>
                </Column>
            </DataTable>

I also have a POST and DELETE method which are called whenever a worklist is added or deleted to via the worklist DataTable component above.

I am using watchEffect, contained in my app.vue which runs the getWorklists method.

watchEffect(() =>
{
  store.getWorklists();
})

In my understanding, whenever the worklists array from the store value is changed (either by post/delete), the watchEffect should run the getWorklists method again.

This is working, however the worklists DataTable does not update until I go to a different page in my app, or refresh the page. I want it to happen immediately, so when a user adds/deletes an item they can instantly see the data on the page change, and not to have to leave the page/come back.

I can get this working by having the getWorklists method in the watchEffect run on an interval, but it flickers every time the method runs.

Does anyone know why this is happening and how I fix it?

If further information is needed, please let me know

How to check if item already exists in your shopping cart – UseReducer React JS

I had this problem where i needed to make it so that an item can’t be added twice in my shopping cart, then I searched this platform to see if there were any answers.
I found out the question was asked Check if item already exists in cart when adding REACT but there were no sufficient contributions on it.
Eventually i got the problem solved on my own but i wasn’t allowed to contribute in the comments(I’m new here). So i decided to leave this here incase some one needs same.

I use context API and useReducer. Here is was my code

    switch (action.type) {
        case ADD_T0_CART:
        
        return {
                
                ...state, basket: [...state.basket, action.payload]
            }
            ```

After some hours of headache i eventually fixed it using a simple JS find() function.

  ```  export const commerceReducer = (state,action) => {
        switch (action.type) {
            case ADD_T0_CART:
                const itemExists = state.basket.find(
                    (item) => item.id === action.payload.id 
                )
                console.log(itemExists)
              
                if (!itemExists) return {
                    
                    ...state, basket: [...state.basket, action.payload]
                }
            ```
Hope someone finds this helpful.

How to autoplay audio when countdown is finished without pausing other audio on device

I have a countdown timer that plays a sound when it finishes, and I would like the sound to not pause/interfere with existing audio that is playing on the user’s device via another app (like Spotify). On a computer (Macbook Pro), this works across browsers and the alarm sound plays over background music. On a mobile phone (iPhone) background music is paused when the countdown is finished and alarm plays and am required to replay background audio. I don’t have the knowledge to come up with a workaround for this and any help is really appreciated! I modified the code below from this post which helped solve the barrier to autoplay initially:

const audio = new Audio("https://www.fesliyanstudios.com/play-mp3/4385");
let time = ${time};

btn.onclick = e => {
  // mark our audio element as approved by the user
  audio.load();
  countdown();
  btn.disabled = true;
};


function countdown() {
  document.getElementById("pre").style.color ="#12A89E";
  document.getElementById("pre").innerHTML = --time + "s work time";
  if(time === 0) return onend();
  setTimeout(countdown, 1000);
}


function onend() {
  audio.play(); // now we're safe to play it
  document.getElementById("pre").style.color ="#A81248";
  document.getElementById("pre").innerHTML = "NEXT MOVEMENT";
  time = ${time}
  btn.disabled = false;
}

Is there a way to access Timebox Filter for a Report in Rally Custom HTML

I am working on creating custom HTML widgets in Reports for Rally and I’m accessing data by querying the API like so:
https://rally1.rallydev.com/slm/webservice/v2.0/release/?query=((Project.Name%20=%20%22TestProjectName%22)%20and%20(Name%20contains%20%22TestReleaseName%22))&fetch=Name,PlannedVelocity,PlanEstimate
I am trying to find a variable, or function in Javascript that would fetch the name, ID, or some other identifier for the currently selected release at the top of my report so I can query it. I have tried searching through rally’s SDK and googling but have been unable to find a solution. I am able to find the Projcet ID using PROJECT_OID but needed something similar for the selected release on the release filter so I could query only within said release.