export json data as csv in react

Hey guys I’m trying to add a download button in order to export some Json data as csv but this is not working for me. The data i want to export is inside shareFilterHead and shareFilterRows and the data is in Json. I’m using the CsvDownloader from ‘react-csv-downloader’.

import React, {Component} from "react";
import DynamicTable from '@atlaskit/dynamic-table';
import styled from 'styled-components';
import CsvDownloader from 'react-csv-downloader';

export default class ShareFilter extends Component {

constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      shareFilterRows: []
    };
  }

componentDidMount() {
    fetch(AJS.contextPath() + "/rest/securityrestresource/1.0/results?check=ShareFilter")
    .then((res)=>{
        if(res.ok) {
            return res.json();
        }
    }).then((res)=>{
  this.setState({
    isLoaded: true,
    shareFilterRows: res.map((row, index) => ({
      key: `row-${index}-${row.filterID}`,
      cells: [{
        key: `${row.filterID}`,
        content: row.filterID,
        },
        {
        key: `${row.author}`,
        content: row.author,
        },
        {
        key: `${row.filtername}`,
        content: row.filtername,
        },
        {
        key: `${row.jql}`,
        content: row.jql,
        },]}))
  })
  })
  }

render() {
const { error, isLoaded, shareFilterRows } = this.state;
if (error) {
  return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
  return <div>Loading Shared Filters...</div>;
} else {
  return (<Wrapper>
    <div>
    <DynamicTable
      head={shareFilterHead}
      rows={shareFilterRows}
      rowsPerPage={10}
      defaultPage={1}
      loadingSpinnerSize="large"
      isLoading={false}
      isFixedSize
      defaultSortKey="filterID"
      defaultSortOrder="ASC"
      onSort={() => console.log('onSort')}
      onSetPage={() => console.log('onSetPage')}
      
      />
  </div>
  </Wrapper>
  );
  }
}
}

AJS.$(document).on("click", "#downloadShareFilterCheck", function(){

    <CsvDownloader
    filename="myfile"
    extension=".csv"
    separator=";"
    wrapColumnChar="'"
    columns={shareFilterHead}
    datas={shareFilterRows}
    text="DOWNLOAD" />


}); 

PurgeCSS: how to match css with backslash

I am using csspurge using the config file. I have css written as
lg:right-40 and in js it is referred as lg:right-40.
in js backslash is escaped hence purgecss is not able identify all the that contain

cssfile

.lg:right-40 {
    right: 10rem;
}
.lg:right-44 {
    right: 11rem;
}
.lg:right-48 {
    right: 12rem;
}
.lg:right-52 {
    right: 13rem;
}
.lg:right-56 {
    right: 14rem;
}

purgecss.config.js

   const TailwindExtractor = (content) => {
  // Treat every word in the bundle as a CSS selector
  return content.match(/[w-/\:]+(?<!:)/g) || []
}
    new PurgeCSS().purge({
      content: ['./src/**/*.jsx', './src/**/*.js'],
      css: ['./src/login/tailwind_backup.css'],
      safelist:{
        greedy:[/\/]
      },
      extractors: [{
        extractor: TailwindExtractor,
        extensions: ['js', 'jsx'],
      }],
      output: './src/login/tailwind.css'
    })

I want to match css classes with with js classes without

rrestrict the direct url file name with javascript?

hello I’m new to javascript

I just created my first website with 2 pages, eg page1.html and page2.html

if the user is not logged in (page1.html) still they can have access to other pages (page2.html) through URL

I want to stop url access with javascript

Please suggest me how to do it

Click event not working when using arrow functions (jQuery) [duplicate]

I want to add a class to an <h1> element when I click on it. I am using an arrow function, but it is not working.

Here is my code:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.min.js"></script>
        <link rel="stylesheet" href="css/style.css">
        <title>Test</title>
    </head>
    <body>
        <h1>Click me!</h1>
        <script src="js/script.js"></script>
    </body>
</html>
$(document).ready(start)

function start(){
    $('h1').click(()=>{
        $(this).toggleClass('h1-click')
    })
}

How can I run a function inside of a function in NodeJS? [duplicate]

class TestClass {
    async profile() {
        await ClientData (BASE_URL, function Data (response) { // ClientData is using `export async function` in another file that has function for getting body from a website url
            return response
        })
    }
}

const Client = new TestClass();
async function test() {
    console.log(await Client.profile().Data());
}

test();

It always give an output (node:5424) UnhandledPromiseRejectionWarning: TypeError: Client.run(...).Data is not a function, I do tried one thing previously with this:

async function test() {
    console.log(await Client.profile().Data);
}

test();

Instead of getting the output, it just gives me output undefined

How to display different data types in radial stacked chart using D3?

I’m trying to display data in a radial chart/donut chart where there is a threshold and an overshoot. The data I am displaying is in percent, tonnes, kg per capita, scale(0-1). I’m guessing I would have to convert the data to a common type like percent, but I’m unsure how to go about it.

The chart is supposed to look like this

Another example

Here is a snippet of the data:

Planetary Boundry Threshold Overshoot
Climate Change – 2.35 tonnes CO2 equivalent per capita yearly 18.95 tonnes CO2 equivalent per capita (2020)
Ocean acidification – 1.59 tonnes CO2 per capita yearly (until 2055) 15.33 tonnes CO2 per capita (2020)
Nitrogen 100% good or very good ecological condition (limit between moderate and good = 250-775 µg/L) 72.7%
Biodiversity / land use 0.6 (scale 0-1) 0.45

Ramda JS – Pass optional argument to the second function of a pipe

I am trying to refactor this code:

async function getUserDataByUsername(username, cached = true) {
  const usernameRef = firestore
    .collection("usernames")
    .doc(username.toLowerCase());

  const usernameDoc = await usernameRef.get();

  if (!usernameDoc.exists) {
    throw userErrors.userNotFound();
  }

  const { userId } = usernameDoc.data();

  return memoizedGetUserData(userId, cached);
}

For that, I have thought to split it in smaller parts, as follows:

function memoizedGetUserData(userId, cached = true) { 
  ... Fetching from LRU or DB ... 
}

async function getUserId(username) {
  const usernameRef = firestore
    .collection("usernames")
    .doc(username.toLowerCase());

  const usernameDoc = await usernameRef.get();

  if (!usernameDoc.exists) {
    throw userErrors.userNotFound();
  }

  const { userId } = usernameDoc.data();

  return userId;
}

async function getUserDataByUsername(username, cached = true) {
  const userId = await getUserId(username);

  return memoizedGetUserData(userId, cached);
}

Now, I want to apply Ramda to this module. I have never used this library before, but I have read that it is really cool, and makes the code easier to understand with some of it utilities.

What I am trying is to refactor the original method using the pipeline style, as follows:

import R from "ramda";

...

const getUserDataByUsername = R.pipeP(getUserId, memoizedGetUserData);

But… how can I pass the second optional parameter “cached”, only to the second argument of my pipe??

How to split object into multiple objects by props names in JS

I am trying to split object into multiple objects. Here is how it looks. It is actually array of objects.

[
  {
    interval_9_gun_time_milliseconds: 0,
    interval_9_net_time_milliseconds: 0,
    interval_9_gun_pace: '00:07:04',
    interval_8_gun_time_milliseconds: 0,
    interval_8_net_time_milliseconds: 0,
    interval_8_gun_pace: '00:07:04',
    entry_id: 200
  },
  {
    interval_9_gun_time_milliseconds: 0,
    interval_9_net_time_milliseconds: 0,
    interval_9_gun_pace: '00:02:04',
    interval_8_gun_time_milliseconds: 0,
    interval_8_net_time_milliseconds: 0,
    interval_8_gun_pace: '00:04:04',
    entry_id: 404
  },
  {
     entry_id: 1
  }
]

So expected result should be:

 [
      {
        interval_9_gun_time_milliseconds: 0,
        interval_9_net_time_milliseconds: 0,
        interval_9_gun_pace: '00:07:04',
        entry_id: 200
      },
      {
        interval_8_gun_time_milliseconds: 0,
        interval_8_net_time_milliseconds: 0,
        interval_8_gun_pace: '00:07:04',
        entry_id: 200
      },
      {
        interval_9_gun_time_milliseconds: 0,
        interval_9_net_time_milliseconds: 0,
        interval_9_gun_pace: '00:02:04',
        entry_id: 404
      },
      {
        interval_8_gun_time_milliseconds: 0,
        interval_8_net_time_milliseconds: 0,
        interval_8_gun_pace: '00:04:04',
        entry_id: 404
      }
    ]

Bottom line split and group object by interval_{number} and add other props, if object doesn’t have interval remove it.

addeventListener not working on all elements

Hello I mam facing a problem with my script.

I am beginner in JS and I am trying to add event listener to buttons generated by a foreach but only the last button generated is responding to the addeventlistener.

I am also facing a pb of variable range with the getLocation(flight) function which is returning undefined outside the fuction while the console.log in the function is displaying the good variable value.

Can someone help?



let resultatAPIMeteo;

let long;
let lat;
let buttonId;

const URL = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
const TITREMETEO = document.querySelector('.titre-meteo');
const IMG = document.querySelector('.bloc-logo');
const temps = document.querySelector('.temps');
const temperature = document.querySelector('.temperature');
const localisation = document.querySelector('.localisation');
const tbody = document.querySelector(('#body'));

let flights = [];
let table = document.getElementById("tableau");

AppelAPI();

function AppelAPI() {
    fetch(URL)
        .then((response) => {
            return response.json()
        })
        .then((data) => {
            let i = 0;

            getFlights(data);
            console.log(data)
            console.log(flights)

            flights.forEach(flight => {
                let i = flights.indexOf(flight)
                console.log(flight);
                long = flight[5];
                lat = flight[6];

                let city = getLocation(flight);
                console.log("city: " + city);

                let meteoDepart = "test";
                let meteoArrivee = "test";

                /* let newRow = document.createElement('tr');
                let newFlightNumber = document.createElement('td');
                let newflightNumberText = flight[1];
                let newProvenance = document.createElement('td');
                let newProvenanceText = flight[2];
                let newCity = document.createElement('td');
                let newCityText = city;


                tbody.append(newRow);

                newFlightNumber.textContent = newflightNumberText;
                newRow.append(newFlightNumber);

                newProvenance.textContent = newProvenanceText;
                newRow.append(newProvenance);

                newCity.textContent = newCityText;
                newRow.append(newCity); */
                

                if(i % 2 === 0) {
                    table.innerHTML += `<tr class='pair'>n` +
                        "    <td>" + flight[1] + "</td>n" +
                        "    <td>" + flight[2] + "</td>n" +
                        `    <td>${city}</td>n` +
                        `    <td><button id="tr-${i}"  onclick="alert('Bouton cliqué')">Météo</button></td>`+
                        "</tr>n";
                } else {
                    table.innerHTML += `<tr class='pair'>n` +
                        "    <td>" + flight[1] + "</td>n" +
                        "    <td>" + flight[2] + "</td>n" +
                        `    <td>${city}</td>n` +
                        `    <td><button id="tr-${i}"  onclick="alert('Bouton cliqué')">Météo</button></td>`+
                        "</tr>n";
                }
                console.log('tr-'+i);
                let button = document.getElementById('tr-'+i);
                tbody.style.color='white';
                button.style.backgroundColor='orange';

                button.addEventListener('click', (e) => {
                    console.log('from api: click');
                    AppelApiMeteo(flight);
                });
                i++;
            })
        })
}

function AppelApiMeteo(flight) {
    console.log('from apimeteo: click');

    let lattitude = flight[6];
    let longitude = flight[5];
    let URLMeteo = `https://api.openweathermap.org/data/2.5/onecall?lat=${lattitude}&lon=${longitude}&exclude=minutely&units=metric&lang=fr&appid=${CLEAPIMETEO}`;
    console.log(URLMeteo);
    fetch(URLMeteo)
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            resultatAPIMeteo = data;

            TITREMETEO.innerHTML = `Météo du vol ${flight[1]} en provenance de ${flight[2]}`;
            IMG.innerHTML = `<img src="./ressources/jour/${resultatAPIMeteo.current.weather[0].icon}.svg" alt="logo du temps qu'il fait" className="logo-meteo">`;
            temps.innerText = resultatAPIMeteo.current.weather[0].description;
            temperature.innerText = `${Math.trunc(resultatAPIMeteo.current.temp)}°`;
            localisation.innerText = resultatAPIMeteo.timezone;

            console.log('meteo data:' + resultatAPIMeteo.current.weather[0].description);
        })
}

function getFlights(data) {
    console.log(data.states);
    data.states.forEach(element =>{
        flights.push(element)
    })
}

function getLocation(flight){
    let lattitude = flight[6];
    let longitude = flight[5];
    let geocoder;
    geocoder = new google.maps.Geocoder();
    let latlng = {
        lat: parseFloat(lattitude),
        lng: parseFloat(longitude),
    };

    geocoder
        .geocode({location: latlng})
        .then((response) => {
            console.log("pos: " + response.results[7].address_components[0].long_name);
            return response.results[7].address_components[0].long_name;
        })
        .catch((e) => window.alert("Geocoder failed due to: " + e));
}
/*
let row = document.createElement('tr')
let columnNum = document.createElement('th');
let columnLat = document.createElement('th');
let columnLong = document.createElement('th');
let columnMeteo = document.createElement('th')

for(let i = 0; i < data.length; i++) {

    columnNum.textContent = resultatsAPI[i].icao24;

    table.appendChild(row);
    row.appendChild(columnNum);
    row.appendChild(columnLat);
    row.appendChild(columnLong);
    row.appendChild(columnMeteo);


    console.log('test:' + resultatsAPI[i].icao24);
}
*/

custom columns selection google script

I’m using a google script to save a google sheet as a csv daily, I would like to only save desired columns (in this case columns 1,2,4,9,14,25,26 and 44).
I tried to modify the range, an if after columns loop, putting only the wanted columns as i value for columns loop… but the script still saves the whole google sheet. Any ideas ? Thanks

/*Sauvegarde de Stylez*/ 

function saveAsCSV_Stylez() {
  // Prompts the user for the file name
  var fileName = "CSV_Stylez"; //Browser.inputBox("Save CSV file as (e.g. myCSVFile):");
  // Add the ".csv" extension to the file name
  fileName = fileName + ".csv";
  delteFile_Stylez(fileName);
  // Convert the range data to CSV format
  var csvFile = convertRangeToCsvFile_Stylez(fileName);
  // Create a file in Drive with the given name, the CSV data and MimeType (file type)
  //DriveApp.createFile(fileName, csvFile, MimeType.CSV);
  var CF = DriveApp.getFolderById('1D5NBqNRb7tdpfiiUyPM18cfMnPzhZHVl').createFile(fileName, csvFile, MimeType.CSV);
}
 
function convertRangeToCsvFile_Stylez(csvFileName) {
  // Get the selected range in the spreadsheet
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('CSV_Stylez'), true);
  spreadsheet.getRange('A1:AR3500').activate();
  var ws = SpreadsheetApp.getActiveSpreadsheet().getActiveSelection();
  try {
    var data = ws.getValues();
    var csvFile = undefined; 
    // Loop through the data in the range and build a string with the CSV data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row++) {
        for (var col = 0; col < data[row].length; col++) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = """ + data[row][col] + """;
          }
        }
 
        // Join each row's columns
        // Add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "rn";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
  }
}


function delteFile_Stylez(myFileName) {
  var allFiles = DriveApp.getFolderById('1D5NBqNRb7tdpfiiUyPM18cfMnPzhZHVl').getFilesByName(myFileName);
  while (allFiles.hasNext()) {
    var thisFile = allFiles.next();
    thisFile.setTrashed(true);
  };
  function convertRangeToCsvFileCSV_LAD(csvFileName) {
  // Get the selected range in the spreadsheet
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('CSV_Stylez'), true);
  spreadsheet.getRange('A1:AR3500').activate();
  var ws = SpreadsheetApp.getActiveSpreadsheet().getActiveSelection();
  try {
    var data = ws.getValues();
    var csvFile = undefined; 
    // Loop through the data in the range and build a string with the CSV data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row++) {
        for (var col = 0; col < data[row].length; col++) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = """ + data[row][col] + """;
          }
        }
         
        // Join each row's columns
        // Add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "rn";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
  }
}
};

How to adjust the space between heading, legend and plot area on Plotly?

How can I adjust space between heading, legend and plot area in Plotly? In particularly I need to increase the space between them without one another collide. I’ve attached the current output screenshot and my code snippet as following.

[Current Output of the chart

 <Plot
        data={dataArray}
        layout={{
          barmode: "stack",
          autosize: true,
          title: preHeading + mainTitle,
          margin: {
            t: 135,
            autoexpand: true,
          },
          xaxis: {
            // all "layout.xaxis" attributes: #layout-xaxis
            title: xTitle, // more about "layout.xaxis.title": #layout-xaxis-title
            // dtick: 1,
          },
          yaxis: {
            // all "layout.xaxis" attributes: #layout-xaxis
            title: yTitle, // more about "layout.xaxis.title": #layout-xaxis-title
          },
          font: {
            // family: "Courier New, monospace",
            size: 12,
            color: "#7f7f7f",
          },
          legend: {
            bgcolor: "yellow",
            x: 0,
            y: 1.2,
            xanchor: "auto",
            traceorder: "normal",
            orientation: "h",
          },
          marker: { size: 40 },
        }}
        useResizeHandler
        style={{ width: "100%", height: "100%" }}
      />

]1

How to pass data between users and different browsers in React?

I am learning React and I’m making an app to better learn.
I created an app with Nodejs backend, Postgres DB and React frontend. I have different users and this is the case of what I need to do:

USER 1: Logs in mozilla and clicks a button on a page.
USER 2: Logs in firefox and sees a new button has appeared, because user in mozilla clicked it. Now he clicks this new button.
USER 1: Because USER 2 clicked new button, USER 1 sees something new displayed.

I am running it locally.

NodeJS Streams: Readable.pipe() doesn’t send data immediately

From what I understood about streams, Stream.Readable.pipe() should pipe the data as soon as it receives it.

I am trying to implement my own streams but the output is not as expected.

const { Writable, Readable } = require("stream");

const writable = new Writable();
writable.data = [];
writable._write = (chunk, encoding, next) => {
  writable.data.push(chunk.toString());
  console.log(chunk.toString());
  next();
};

const readable = new Readable({
  read() {},
});

readable.pipe(writable);
readable.push("hi");
writable.write("ho");
writable.write("ho");
console.log(writable.data);

The output of this code is

ho
ho
[ 'ho', 'ho' ]
hi

The pipe is writing to the stream later. What does this mean?

Trying to implement a basic search engine by hiding elements that aren’t results, but my code hides everything instead

I am trying to implement a very basic search engine. I iterate through an array of objects, checking if my search term matches some attributes, and if it does, I push each matching object onto an array. Now, in the rest of my code I have it so each object is represented by an element, and each element has a checkbox. Each checkbox has an ID that matches its object’s ID. So…. when I run the search function, I take the matches, correspond them to a checkbox through the IDs, and then I want to hide the elements that don’t match.

The problem is: it hides ALL the elements, instead of just the non-matchings IDs. Furthermore, it works when I want to manipulate the matches (say, surround them in a white border). Thank you for your time I look forward to your input.

Blake

function search() {
     var results = [];
     userData.forEach(task => {
         if (task.value.toLowerCase().includes(searchBar.value.toLowerCase()) 
             || task.note.toLowerCase().includes(searchBar.value.toLowerCase())) {
                 results.push(task.id);
             }
         })

         const checkboxes = document.querySelectorAll(".checkbox");

         checkboxes.forEach(checkbox => {
              if (!results.includes(checkbox.id)) {
                   checkbox.parentElement.style.display = "none";
              }
          })
     }
}

Do something when Promise outside then finished

Here is the code.

function getPromise():Promise<any> {
    let p = new Promise<any>((resolve, reject) => {
        //some logical
        resolve(data);
    });
    p.finally(()=>{ 
        //I want do something when outside then finished! 
        console.log("finally hit");
    });
    return p;
}

function doPromise():void {
    getPromise().then(data => { console.log("then hit"); });
}

But the finally runs before then. So how can I do something after outside then.

I do not want to add finally after then, because the promise called many places. so I want do it in one place.