Firebase V9 addDoc not returning success or failiure or writing to database

Auth related functions work, but with firestore I cant get anything to happen. No errors no successes returned by try catch. I have created the firestore in the firebase console, The created accounts show successfully from auth, but I just can’t get anything to happen in firestore database

export const myApp = initializeApp(firebaseConfig);
// firebase.firestore().settings({ experimentalForceLongPolling: true });

export const db = getFirestore(myApp);
export const auth = getAuth(myApp);
export const logout = signOut;

// const dbInstance = collection(database, 'users');

export const addUser = async () => {
  try {
    console.log("Firing add function");
    const docRef = await addDoc(collection(db, "users"), {
      first: "Ada",
      last: "Lovelace",
      born: 1815,
    });
    console.log("Document written with ID: ", docRef);
    // console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }
};

Count number of specific char appeared in a number of lines in csv file

I have those lines of data:

1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234

I want to count how much time the letter A appeared in those lines it sould print 5.

So what I have a file with 19 lines and all those lines has letter A when I tried this snipped of code it returns to me just 12. here is the image for demonstration:
enter image description here

I tried this code:

for (let i = 0, n = this.csvRecords.length; i <= n; ++i) {
  if (this.csvRecords[i] === 'n') {
    ++nLines;
  }
  console.log("number of lines in the file is: " , this.csvRecords.length)
  
}
console.log( "showing u[10] is: " , this.csvRecords[10].length);

So console.log( "showing u[10] is: " , this.csvRecords[10].length); is printing me the 10th line and it counts data with deliminer and that’s not what i want I want how much it appeared in all the lines.

Adobe Acrobat Date Picker/Field Returns an Error Every Time on One Specific Form But Works on All Other Forms

The date picker/field on one specific form returns an error every time but works on all other forms. Even when I manually try to enter it using the correct formatting, it still returns an error. Below is the code attached to the field. The first piece of code is attached to the exit event and contains the error message returned while the second piece of code is attached to the change event. Is this caused by a bug with my version of Adobe or is my code causing this issue? I know there were issues with the date picker in previous versions of Adobe. Please let me know if you need any other information.

Exit Event:

if((!this.isNull) && (!this.execValidate()))
{
    xfa.host.messageBox("You have entered an invalid date. Please select a date from the date picker.");
    this.rawValue = null;
})

Change Event:

if (xfa.event.newText.match(/[^0-9/]/)) 
{  
    xfa.event.change = "";  
}

Loop to workaround 100 message fetch limit no longer working after 1 day

I created a discord bot yesterday from this post to export fields from embeds and it was working fine but it’s not working today. The error I’m getting is TypeError: messages.array is not a function I tried uninstalling node and reinstalling but to no avail. I sent the file to a friend to run and it worked perfectly so it seems to be a problem with my machine. I also tried to run it on my windows server and I did not see any errors but the bot failed at exporting the fields (I don’t intend on using my server to run the bot, just used for troubleshooting). Has anyone seen this error before and/or have a solution?

More detailed Error (One message):

“xxxx@xxxx-mbp embed bot % node main
/Users/xxxx/Downloads/embed bot/main.js:24
sum_messages.push(…messages.array());
^

TypeError: messages.array is not a function
at lots_of_messages_getter (/Users/xxxx/Downloads/embed bot/main.js:24:39)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Client. (/Users/xxxx/Downloads/embed bot/main.js:36:20)”

async function lots_of_messages_getter(channel, limit = 10000) {
const sum_messages = [];
let last_id;

while (true) {
    const options = { limit: 100 };
    if (last_id) {
        options.before = last_id;
    }

    const messages = await channel.messages.fetch(options);
    sum_messages.push(...messages.array());
    last_id = messages.last().id;

    if (messages.size != 100 || sum_messages >= limit) {
        break;
    }
}

return sum_messages;

}

Using one input form and using localStorage on 2 buttons

I have an html code that houses both an input with a search button and a div with a type button, there are duplicates of each set since it’s a comparing site. The input function runs to both forms using id’s of #form1 and #form2, however I can’t seem to manage on how I would be able to store both results to localStorage I have only get form1 to store.

        <form id="form1">
          <label>
            <h4>Destination One</h4>
            <input
              type="text"
              name="cityName"
              placeholder="Enter a destination"
              id="input"
            />
          </label>
          <button type="submit" class="primary button search-button">
            search
          </button>
          <div type="button" class="button button-like" id="liked1">
            <i class="fa fa-heart"></i>
          </div>
        </form>
          function saveData() {
            var input = document.getElementById("input").value;
            document.getElementById("input").value = localStorage.getItem("cityName");
            localStorage.setItem("cityName", input);
          }
        
          liked1.on("click", saveData);
          liked2.on("click", saveData);
        });

How to make axios request with multipartfile to @ModalAttribute Spring Boot App?

I am able to send request with multipartfile via Postman whereas my frontend application cannot send.

My backend code:

@PostMapping(consumes = {"multipart/form-data"})
public ResponseEntity<File> uploadFile(@ModelAttribute @RequestBody FileAddRequestDto request) {

    //do some stuff

}

And dto is:

@Data
public class FileAddRequestDto {
    private Integer userId;
    private Integer customerId;
    private MultipartFile multipartFile;
}

Above backend code is working with postman but not working with the following axios code with react:

export async function addFile(userId, customerId, file) {

    var bodyFormData = new FormData();
    bodyFormData.append("userId", userId); //integer
    bodyFormData.append("customerId", customerId); //integer
    bodyFormData.append("multipartFile", file); //file


    return await axios({
        method: "post",
        url: "http://localhost:8080/file",
        data: bodyFormData,
        enctype: "multipart/form-data",
        headers: {
            Accept: "application/json",
        },
        processData: false, // Important!
        contentType: false,
        cache: false,
    })

Above function is called by the react method:

    const addNewFile = async (userId, customerId, file) => {
        await service.addFile(userId, customerId, file);
    }

    return (
        <>
            <input type="text" placeholder="userId" value={userId} onChange={e => setUserId(e.target.value)}></input>
            <input type="text" placeholder="customerId" value={customerId} onChange={e => setCustomerId(e.target.value)}></input>
            <input type="file" value={file} onChange={e => setFile(e.target.value)}></input>
            <Button onClick={() => addNewFile(userId, customerId, file)} className='addButton'>Add</Button>
        </>
    );
}

Here is the backend response:

message: "org.springframework.validation.BeanPropertyBindingResult: 1 errorsnField error in object 'fileAddRequestDto' on field 'multipartFile': rejected value ["C:\\fakepath\\Screen Shot 2022-04-14 at 11.55.46.png"]; codes [typeMismatch.fileAddRequestDto.multipartFile,typeMismatch.multipartFile,typeMismatch.org.springframework.web.multipart.MultipartFile,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [fileAddRequestDto.multipartFile,multipartFile]; arguments []; default message [multipartFile]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'multipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'multipartFile': no matching editors or conversion strategy found]"

How can I send request properly from frontend ?

How to convert Ajax (Jquery) into fetch async

I wrote this code and it’s works perfect for me.
But when i try to convert it to fetch, dosen’t work because return a promise.
I don’t know how to use it as a async false on fetch.

            'getProjectConstants': function(constArray)
            {
                var result='';
                $.ajax({
                type:       "GET",
                url:        `${constProjectBaseUrl}/ajax/getProjectConstants/${constArray}`,
                async:      false,
                dataType:   "json",
                success: function(data) {
                result = data
            }
        });
        return result

I tried to do like this, but dosen’t work

        fetch(`${constProjectBaseUrl}/ajax/getProjectConstants/${constArray}`)
        .then((response) => response.json())
        .then((response) => {
             // console.log(response)
             return response
        }) // end of .then((response) => {
        .catch(error => {
             console.log("[ajax.getProjectConstants] Error => " + error);
        }); // end of .catch(error => {

D3: tooltip displaying [object,Object]. Not able to access values to display in tooltip

I’m trying to display values from a dictionary in d3. I’m using two different datasets. One for constructing a Treemap, and the other for displaying information in a hovering tooltip. I’ve gotten to where the user can hover over the treemap and the display() function can access the object using an element id. But when I run index.html the display shows [Object,object] for each of the 5 values in the key.

Treemap

The data I want to display in the tooltip is shown in the console
Console

How can I access the values from this dictionary to display in the tooltip?

function main() {


    // set dimensions and margins of the graph
    var margin = {top: 10, right: 10, bottom: 10, left: 10},
        width = 645 - margin.left - margin.right,
        height = 645 - margin.top - margin.bottom;


    // append the svg object to the body of the page
    var svg = d3.select("#my_dataviz")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform",
            "translate(" + margin.left + "," + margin.top + ")");



    d3.queue()
        .defer(d3.csv, "data/Genre Average Score Treemap Data.csv")
        .defer(d3.csv, "data/Top Five Albums Each Genre.csv")
        .await(function(error, file1, file2) {
            if (error) {
                console.error('Oh dear, something went wrong: ' + error);
            }
            else {
                makeTreemap(file1,file2);
            }
        });


    function makeTreemap(treeData,toolData) {


        // stratify the data: reformatting for d3.js
        var root = d3.stratify()
            .id(function(d) { return d.genre; })  // name of the entity
            .parentId(function(d) { return d.parent; }) // name of the parent (column name is parent in csv)
            (treeData);
        root.sum(function(d) { return +d.score })   // compute the numeric value for each entity


        // d3.treemap computes the position of each element of the hierarchy
        // the coordinates are added to the root object above
        d3.treemap()
            .size([width, height])
            .padding(4)
            (root)


        let leafs = root.leaves()

        var entries = d3.nest()
            .key(function(d) { return d.genre; })
            .entries(toolData);

        // d.id to get genre name
        // console.log(leafs);

        // mapped each key from each object in nested array
        var eachKey = d3.values(entries).map(function(d){ return d.values[0].genre });

        // mapped each values from each object in the nested array
        var eachValues = d3.values(entries).map(function(d){ return d.values });


        function makeDict(keys, values) {

            let x = {}
            for (let i=0; i < keys.length; i++){
                tools[keys[i]] = values[i];
            }
            return x;
        }

        const toolDisplay = makeDict(eachKey, eachValues);


        function display(elem) {

            // elem.id to get genre string
            // console.log(elem.id)
            // toolDisplay which gives the values from each genre
            console.log(toolDisplay[elem.id]);

            return toolDisplay[elem.id];

        }

        // use the above information to add rectangles:
        svg
            .selectAll("rect")
            .data(leafs)
            .enter()
            .append("rect")
            .attr('x', function(d) {return d.x0; })
            .attr('y', function(d) {return d.y0; })
            .attr('width', function(d) {return d.x1 - d.x0; })
            .attr('height', function(d) {return d.y1 - d.y0; })
            .style("stroke", "black")
            .style("fill", "#FBFFF1")
            .on('mouseover', function(d) {
                d3.select(this)
                    .style("fill", "#DE9E36")
                    display(d);
            })
            .on("mouseout", function() {
                d3.select(this)
                    .style("fill", "#FBFFF1");
            });



        // create variable for rounding review score 2 decimal places
        const f = d3.format(".2f");

        // add text labels
        svg
            .selectAll("text")
            .data(root.leaves())
            .enter()
            .append("text")
            .attr('x', function(d) { return d.x0+10 }) // +10 to adjust position (more right)
            .attr('y', function(d) { return d.y0+20 }) // +20 to adjust position (lower)
            .text(function(d){ return d.data.genre + "rn " + f(+d.data.score)
            })
            .attr("font-size", "16px")
            .attr("fill", "black")


    }

}


main()
<!DOCTYPE html>
<meta charset="utf-8">

<!-- load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/queue.v1.min.js" type="text/javascript"></script>
<!-- Create div where the graph takes place -->
<div id="my_dataviz"></div>


<body>

<script src="treemap2.js"></script>


</body>

Can I use class field without declaring them?

Can I have a class like this?

class Human {
  constructor(name) {
    this.name = name;
  }
  someMethod() {
    this.hasBrain = true;
    console.warn(this.hasBrain);
  }
}

This is working and not throwing any error.
My question is, now, is hasBrain a class property or it is a class field? if it is a class field, Does it have to be declared?

React js 18.0 Router changes URL but not loading the page

I have a problem, I’m using reactJS V18.0, BrowserRouter, Link and Switch to manage my website routing, my problem is that when I click on a link it changes on URL but not in view, however when I refresh the page it works.

This is my App.js page:

import React from "react";
import './App.css';
import Header from "./Header";
import Home from "./Home";
import Checkout from "./Checkout"
import "react-router-dom"
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {
  return (
    <Router>
      <div className="app">
        <Header />
        <Switch>

          <Route path='/checkout'>
            <Checkout />
          </Route>

          <Route path='/'>
            <Home />
          </Route>

        </Switch>
      </div>
    </Router>
    
    

  );
}

export default App;

This is my Header.js page:

import React from 'react'
import './Header.css'
import SearchIcon from '@mui/icons-material/Search'
import ShoppingBasketIcon from '@mui/icons-material/ShoppingBasket'
import { Link } from 'react-router-dom'

function Header() {
  return (
    <div className='header'>
        <Link to="/">
            <img className='header__logo' 
                src="https://pngimg.com/uploads/amazon/amazon_PNG11.png" 
                alt='No-pic'/>
        </Link>
    </div>
  )
}

export default Header

This is my Home.js page:

import React from 'react'
import './Home.css'
import Product from './Product'

function Home() {
  return (
    <div className='home'>
        <div className='home__container'>
            <img className='home__image' src='https://m.media-amazon.com/images/I/61mO1fbqd6L._SX3000_.jpg' alt=''/>
            <div className='home__row'>
                <Product 
                    id="123456"
                    title='The 7 Habits of highly effective people' 
                    price={29.99} 
                    image='https://images-na.ssl-images-amazon.com/images/I/51gq0SK0IUL._SX323_BO1,204,203,200_.jpg'
                    rating={5}/>
                <Product 
                    id="654321"
                    title='Sony PlayStation 5 Édition Standard' 
                    price={299.99} 
                    image='https://m.media-amazon.com/images/I/51zylG5gxfS._AC_SX679_.jpg'
                    rating={4}/>
            </div>
            <div className='home__row'>
                <Product 
                    id="654321"
                    title='Sony PlayStation 5 Édition Standard' 
                    price={299.99} 
                    image='https://m.media-amazon.com/images/I/51zylG5gxfS._AC_SX679_.jpg'
                    rating={4}/>
                <Product 
                    id="123456"
                    title='The 7 Habits of highly effective people' 
                    price={29.99} 
                    image='https://images-na.ssl-images-amazon.com/images/I/51gq0SK0IUL._SX323_BO1,204,203,200_.jpg'
                    rating={5}/>
                <Product 
                    id="654321"
                    title='Sony PlayStation 5 Édition Standard' 
                    price={299.99} 
                    image='https://m.media-amazon.com/images/I/51zylG5gxfS._AC_SX679_.jpg'
                    rating={4}/>
            </div>
            <div className='home__row'>
                <Product 
                    id="654321"
                    title='Sony PlayStation 5 Édition Standard' 
                    price={299.99} 
                    image='https://m.media-amazon.com/images/I/51zylG5gxfS._AC_SX679_.jpg'
                    rating={4}/>
            </div>
        </div>
    </div>
  )
}

export default Home

Thank you a lot in advance for your help.

how to update an object within an array during an asyncThunk.fulfilled action in Redux

I have an AsyncThunk method named likePost when a user clicks like on a post it will send this action via dispatch. The method runs fine, and in my database the Post is updated successfully, but I can’t get Redux to update the Post that is liked during the .fulfilled method.

Here is what I’m currently working with:

// shoes = [{_id: '', title: '', likes: []}, ...{}]
export const likePost = createAsyncThunk(
  'posts/likePost',
  async (payload, { rejectWithValue }) => {
    try {
      const response = await userTokenAxios.post(`/${payload}/like`);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

[likePost.fulfilled]: (state, action) => {
      const post = state.posts.find((post) => post._id === action.payload._id);
      post.likes.push(action.payload.user);
},

Cypress : Uploading File with given directory path

I am trying to upload a xlsx file using fixture and what I want is to automate the process of finding file, select the file from file management (finder) without prompting the finder and manually choose the file.

Is there anyway to make cypress to do all steps by its own?

here is my code:

 cy.fixture('fileName', 'binary').then((fileContent) => {
      cy.get('input[type=file]')
        .upload(
          {
            fileContent,
            fileName: 'fileName',
            mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            encoding: 'utf-8',
          },
          { subjectType: 'input' }
        )

Are the time complexities the same for the two approaches for the same problem?

I have a super simple function that returns a text label for a range of the input

const labelByAmounts = [
  { min: 1, max: 10, label: 'small' },
  { min: 11, max: 20, label: 'medium' },
  { min: 21, max: 30, label: 'large' },
]

function fn2(amount) {
  for (const labelByAmount of labelByAmounts) {
    if (amount >= labelByAmount.min && amount <= labelByAmount.max)
      return labelByAmount.label
  }
}

I wonder what the time complexity of this function is? is it o(1) since the computation doesn’t grow linearly with the growth of input size?

And this is an over-engineered version of the function


const labelByAmounts = [{min: 1, max: 10, label: 'small'}, {min: 11, max: 20, label: 'medium'}, {min: 21, max: 30, label: 'large'}]

function fn2(amount) {
    for(const labelByAmount of labelByAmounts) {
        if(amount >= labelByAmount.min && amount <= labelByAmount.max) return labelByAmount.label
    }
}

Now I wonder what the time complexity of this function is? is it still o(1) or it is actually o(n) since there is a loop involved?

Comparing two arrays if they have the exact same values [duplicate]

I have a first array of objects, inside this array there are objects each containg a members array containing an x amount of userIds
In my second array, I have an array of userIds, I want to create a function that returns true or false if and only if the two arrays have the same entries.
Heres what I have tried:

const compareArrays = () => {
  if (usersConvos.some(convo=> JSON.stringify(convo.members)=== JSON.stringify(membersArray)) {
   return true
  }
  else {
   return false
  }
} 

This doesnt work any idea?