Laravel Yajra datatables user input values updating database values

im working on a databtable thats displaying data from my sql table. so far everything is displaying great however one of my fields needs to be able to be edited by the user and have that value updated in the database accordingly. I’ve been looking into multiple ways to do this but they havent been working. I’ve looked into form inputs,cell().edit() and onBlur from https://datatables.net but havent been able to get them to work. currently i have this for my script.

$(document).ready(function () { 
var table = $('#example').DataTable({
            serverSide: false,
            language: {
                searchBuilder: {
                    title: 'Custom Filter'
                }
            },
           dom: 'Q<"pull-left"f><"pull-right"l>rtip',
           ajax: {
                url: "{{ url('/test') }}",
                type: "GET",
                datatype: "text",
                data: {
                    q:"select * from exampleTable",
                    filename:"examplefile.json",
                    cacheInterval: 1
                }
            },
         columns: [
                {data: 'column1',title: 'column1'},
                {data: 'column2',title: 'column2'},
                {data: 'column3',title: 'column3'
               "fnCreatedCell": function (nTd, oData) {
               $(nTd).html("<input class='form-control' id='userInput' value='"+ oData.column3 +"'>");
                }},
         ],
         order: [
             [0, 'asc']
         ],

column3 in this case would be the one that shows as form field showing the current data already filled as default but can be changed.
my html is in a separate blade with this.

<div class="card">
    <div class="card-header">Test Table</div>
    <div class="card-body">
        <button class="updatebutton"type="submit">Submit</button>
        <table id="example" class="table table-striped">
        </table>
    </div>
</div>

preferably It works like onBlur where they edit the line and as soon as they click off it updates the cell however I’ll also take updating off the button click.

java script countdown won’t display on webpage issue/problem

I’m doing a new year’s countdown and for some reason my java script code wont display on the page. I am aware that it’s working as it should because when I console.log the d, h, or m const it shows the timers going down. However, it’s not displaying the timers on the webpage.

const days = document.querySelectorAll('days')
const hours = document.querySelectorAll('hours')
const minutes = document.querySelectorAll('minutes')
const seconds =  document.querySelectorAll('seconds')


const currentYear = new Date().getFullYear();

const newYearTime = new Date('january 1 2023 00:00:00');


function updateCountdown() {
    const currentTime = new Date();
    const diff = newYearTime - currentTime;
    
    const d = Math.floor(diff / 1000 / 60 / 60 / 24);
    const h = Math.floor(diff / 1000 / 60 / 60) % 24;
    const m = Math.floor(diff / 1000 / 60) % 60;
    const s = Math.floor(diff / 1000) % 60;
    
   days.innerHTML = d;
   hours.innerHTML = h < 10 ? '0' + h : h;
   minutes.innerHTML = m < 10 ? '0' + m : m;
   seconds.innerHTML = s < 10 ? '0' + s : s; 
}


setInterval(updateCountdown, 1000); 
@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap');

*{
    box-sizing: border-box;
}

body {
    background-image: url(joanna-kosinska-0CQfTLOVTPU-unsplash.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    background-attachment: fixed;
    font-family: "Bebas Neue", sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0%;
    overflow: hidden;
}

h1 {
    font-weight: normal;
    font-size: 80px;
    margin: 90px;
    text-shadow: rgb(255, 180, 238) 5px 5px 15px, black 2px 2px 6px;
}

.countdown {
    display: flex;
    transform: scale(2.5);
}

.time {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 15px;
    text-shadow: rgb(255, 180, 238) 4px 4px 15px, black 1px 1px 6px;
}

.time h2 {
    font-size: 28px;
    margin: 0 0 5px;
}

@media screen and (max-width: 800px) {
    h1 {
        font-size: 60px;
    }
    .time {
        margin: 5px;
    }
    .time h2 {
        font-size: 24px;
        margin: 0 0 10px
        ;
    }
}

@media screen and (max-width: 650px) {
    h1 {
        font-size: 40px;
    }
    .time {
        margin: 5px;
    }
    .time h2 {
        font-size: 20px;
        margin: 0 0 10px
        ;
    }
}
<!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">
    <link rel="stylesheet" href="style.css">
    <title>Countdown</title>
</head>
<body>

    <h1>New Years Countdown</h1>

    <div id="countdown" class="countdown">

        <div class="time">
            <h2 id="days"></h2>
            <small>Days</small>
        </div>
        
        <div class="time">
            <h2 id="hours"></h2>
            <small>Hours</small>
        </div>
        
        <div class="time">
            <h2 id="minutes"></h2>
            <small>Minutes</small>
        </div>
        
        <div class="time">
            <h2 id="seconds"></h2>
            <small>Seconds</small>
        </div>

    </div>






 <script src="scripts.js"></script>   
</body>
</html>

Merge Sort, sorting dates properly but not integer values

I am doing a coding challenge trying to learn merge sort and I have gotten my merge sort to handle dates properly but not an integer value. Currently it seems to outputting data at random.

I am assuming that I have a logic error but cannot put my finger on what it might be.

My Merge Sort Function:

function sortBy(array, key, descending = false) {
  const length = array.length;
  if (length === 1) {
    return array;
  } else if (length === 2) {
    const aValue = array[0][key];
    const bValue = array[1][key];
    if (bValue > aValue) {
      return array;
    }
    return [
      array[0],
      array[1],
    ];
  }

  const mid = Math.floor(length / 2);
  const firstHalf = array.slice(0, mid);
  const secondHalf = array.slice(mid, length);

  const arrayOne = sortBy(firstHalf, key);
  const arrayTwo = sortBy(secondHalf, key);

  const merged = [];
  while (arrayOne.length || arrayTwo.length) {
    if (!arrayOne.length) {
      merged.push(arrayTwo.shift());
      continue;
    }

    if (!arrayTwo.length) {
      merged.push(arrayOne.shift());
      continue;
    }

    const valueOne = arrayOne[0][key];
    const valueTwo = arrayTwo[0][key];
    if (valueOne <= valueTwo) {
      merged.push(arrayOne.shift());
    } else if (valueTwo < valueOne) {
      merged.push(arrayTwo.shift());
    }
  }

  return descending ? merged.reverse() : merged;
}

Sample Data

    [{
    created: '2016-03-07T05:24:40.340Z',
    details: 'Right now we only support single backticks. Would be nice to do triple as well... Consider supporting more or all of markdown but I'm not sure that's the right direction.',
    title: 'Support triple backtick codeblocks',
    votes: 17,
  },]

Need help figuring this out

can someone help me figure out why I’m getting this error

1) "before all" hook in "{root}":

         TypeError: jsdom.createVirtualConsole is not a function
          at Context.<anonymous> (test/root.js:18:27)
          at process.processImmediate (node:internal/timers:471:21)



    whenever I try to npm test

function introductionWithLanguageOptional(name, language = "Javascript") { 
    console.log(`Hi, my name is ${name} and I am learning to program in ${language}.`)

Check if no unicode character is associated with a number Javascript

I am making a base converter that can convert any number in any base to the same number in any other base. Since the bases could be any number the result could have digits that represent a number greater than 10. In order to have only one character correspond to each digit in the final result, I plan to assign Unicode characters to each digit corresponding to a value greater than 10 by using String.fromCharCode(Base 10 number digit represents). However, I noticed that there was a problem with this method; It seems as if a lot of the values are blank when outputted onto the HTML webpage or only output an empty box that looks like this: ⯣. When I tried to see if the value of the Unicode character equaled the empty box or an empty string by using an if statement, it always seemed to return false, even when the Unicode character associated with the digit returned the same empty box. Please may you help me understand why this is, and how I can construct the if statement such that it will work like I want it to?

equivalent of python’s array.pop() in javascript

I wonder if there’s an easy to implement equivalent to python’s array.pop() which returns the deleted element while deleting it from the array in parallel in javascript.

let nums = [2, 1, 3, 4, 5, 6];

function sortArray(nums) {
  let arr = new Array();
  let smallest_index;
  for (let j = 0; j < nums.length; j++) {
    smallest_index = find_smallest(nums);
    console.log("smallest", smallest_index);
    arr.push(nums.splice(smallest_index, 1).join(""));
  }

  return arr;
}

function find_smallest(arr) {
  let smallest = arr[0];
  let smallest_index = 0;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < smallest) {
      //   console.log("this");
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index;
}

it seems that if I replace javascript’s (nums.splice(smallest_index, 1).join()) with python’s (arr.append(nums.pop(smallest_index)) I would get a perfectly sorted array. is there a similar straightforward solution in javascript as well ?

React-Bootstrap “Option was not found”

Trying to add a dropdown menu in a signup form.

import React from 'react';
import { Container, Col, Row, Form, Option } from 'react-bootstrap';

function Signup() {
  return (
    <Container>
        <Row>
            <Col>
                <Form>
                    <Form.Group className='mb-3' controlId='firstName'>
                        <Form.Label>First Name</Form.Label>
                        <Form.Control type='firstName' placeholder='First name' required />
                    </Form.Group>
                    <Form.Group className='mb-3' controlId='lastName'>
                        <Form.Label>Last Name</Form.Label>
                        <Form.Control type='firstName' placeholder='Last name' required />
                    </Form.Group>
                    <Form.Group className='mb-3' controlId='email'>
                        <Form.Label>Email</Form.Label>
                        <Form.Control type='email' placeholder='Email address' required />
                    </Form.Group>
                    <Form.Select aria-label='TeamSelect'>
                        <Option>Select your team</Option>
                        <Option value='1'>Team One</Option>
                        <Option value='2'>Team Two</Option>
                    </Form.Select>
                </Form>
            </Col>
        </Row>
    </Container>
  )
}

export default Signup

If I leave it as this then I get an error

ERROR in ./src/components/pages/Signup.js 156:43-49
export 'Option' (imported as 'Option') was not found in 'react-bootstrap/Form' (possible exports: default)

But If I leave ‘Option’ out of the import then I get an undefined error.
What am I missing here?

How to receive a variable in javascript from c#?

So I’m trying to open up an htm file throw a WPF UI(XAML) hyperlink and pass some coordinates to the htm file, which uses javascript to create a map that centers around, hopefully, the coordinates I’m trying to pass. coord1 and coord2 are doubles.

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        String coords = coord1 + " " + coord2;
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri, coords));
        e.Handled = true;
    }

This is the javascript end where I’m trying to receive the variable coords:

<script type='text/javascript'>
    var map;
    var coords = '<%=coords%>';

   function GetMap() {

    map = new Microsoft.Maps.Map('#myMap', {center: new Microsoft.Maps.Location(55, 0)});
    ...

I got ‘<%=coords%>’ from online but it literally just returns <%=coords>. I’m trying to take the two coordinate points to replace the 55 and 0.

I didn’t post the XAML code, but the C# code opens up the htm file when a hyperlink is clicked and I believe the string “coords” is being passed with the data, but I just don’t know how to receive it.

How to make sql sequelize query with nested relations where clause

Im currently working on a budget tracking web app that has the corresponding database setup

enter image description here

So basically i have multiple transactions reladed to a single account, as well as multiple accounts related to a single user

i want to come up with a sequelize query that allows me to view every transaction done by any account corresponding to a single user

License Keygen in javascript

So I saw another solution on here with a problem I was having. Though the problem isn’t completely solved for me.

This is the code that I found on here.

function makeid(length) {
  var result = "";
  var characters = '0123456789';
  for (var i = 0; i < length; i++) {
    result += characters[Math.floor(Math.random() * characters.length)];
  }
  result = result.match(/d{1,4}/g).join("-");
  return result;
}

console.log(makeid(16));

And this is the current code I have now.

function makeid(length) {
  var result = "";
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  for (var i = 0; i < length; i++) {
    result += characters[Math.floor(Math.random() * characters.length)];
  }
  result = result.match(/d{1,4}/g).join("-");
  return result;
}

console.log(makeid(16));

The output is not want I want. I want the output to be in both Letters and Numbers and I’m not sure why it won’t do both!

Why my custom React functional toast component behaving so strangely upon attempting to automatically dismiss notification pop-ups?

My custom react toast component was working well until I tried to implement automatic dismissal of notifications after a set time.

I am trying to make it so that after a set time, the pop-up “toast” notifications will have a CSS fade-out animation play and then be deleted — unless the user is hovering over that notification, in which case it will hold off on dismissing that one until the user moves their mouse off of it.

Sometimes it works properly, other times it stops displaying anything and adds the notifications back one by one, other times it… well, it just behaves in a very strange and unexpected manner.

Here is my code:

Toast.css

.toast-container {
    font-size: 24px;
    box-sizing: border-box;
    position: fixed;
    z-index: 10;
}

.toast-popup {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 500px;
    border: solid #f2f2f2;
    border-radius: 8px;
    box-shadow: 0 0 10px #999;
    margin-bottom: 1rem;
    opacity: 0.9;
}
.toast-popup:hover {
    box-shadow: 0 0 12px deepskyblue;
    opacity: 1 !important;
    animation-play-state: paused;
}

.success {
    background-color: #5cb85c;
}
.info {
    background-color: #5bc0de;
}
.warning {
    background-color: #f0ad4e;
}
.danger {
    background-color: #d9534f;
}

.toast-text {
    justify-self: flex-start;
    width: 100%;
    padding: 6px 0 6px 6px;
    opacity: 0.9;
}
.toast-title {
    font-weight: 700;
    font-size: 32px;
    text-align: left;
    padding-bottom: 0px;
    color: #f2f2f2;
}

.toast-message {
    padding-top: 0px;
    text-align: left;
    color: #f2f2f2;
}

.toast-icon {
    float: left;
    margin: 0 20px 0 10px;
    opacity: 0.9;
}
.toast-icon img {
    width: 50px;
    height: 50px;
    fill: #f2f2f2;
    opacity: 0.9;
}

.close-button {
    float: right;
    align-self: flex-start;
    font-weight: 600;
    color: #f2f2f2;
    background: none;
    border: none;
    opacity: 0.9;
    cursor: pointer;
}

.top-right {
    top: 2rem;
    right: 2rem;
}
.top-right-slide {
    top: 2rem;
    right: 2rem;
    transition: transform .6s ease-in-out;
    animation: toast-in-right .7s;
}

.bottom-right {
    bottom: 2rem;
    right: 2rem;
}
.bottom-right-slide {
    bottom: 2rem;
    right: 2rem;
    transition: transform .6s ease-in-out;
    animation: toast-in-right .7s;
}

.top-left {
    top: 2rem;
    left: 2rem;
}
.top-left-slide {
    top: 2rem;
    left: 2rem;
    transition: transform .6s ease-in;
    animation: toast-in-left .7s;
}

.bottom-left {
    bottom: 2rem;
    left: 2rem;
}
.bottom-left-slide {
    bottom: 2rem;
    left: 2rem;
    transition: transform .6s ease-in;
    animation: toast-in-left .7s;
}

.fadeout {
    animation: 4s linear 5s 1 normal forwards running toast-fadeout;
}

@keyframes toast-in-right {
    from { transform: translateX(100%); }
    to { transform: translateX(0); }
}

@keyframes toast-in-left {
    from { transform: translateX(-100%); }
    to { transform: translateX(0); }
}

@keyframes toast-fadeout {
    from { opacity: 0.9; }
    to { opacity: 0; }
}

Toast.js – Please excuse the generous peppering of console.logs…

import React, {useEffect, useState} from 'react';
import icon_success from './icons/feathericons/check-circle.svg';
import icon_info from './icons/feathericons/info.svg';
import icon_warning from './icons/feathericons/alert-triangle.svg';
import icon_danger from './icons/feathericons/alert-octagon.svg';
import './Toast.css';

const Toast = (props) => {
    const {toastList, position} = props;
    const [list, setList] = useState(toastList);
    const [prevId, setPrevId] = useState(0);

    // This useEffect updates the list of toasts to display
    useEffect(() => {
        console.log('useEffect()');
        console.log('useEffect() toastList:');
        console.log(toastList);
        setList([...toastList]);
    }, [toastList]);

    const markForDeletion = (toast) => {
        if( toast.isDeleting ) {
            return;
        }
        console.log(`toast ${toast.id} marked for deletion`)
        toast.isDeleting = true;
        setTimeout(() => {attemptDeletion(toast)}, 5000);
    }

    const attemptDeletion = (toast) => {
        console.log(`attempting to delete toast ${toast.id}. canDelete = ${toast.canDelete}`);
        if( toast.canDelete ) {
            deleteToast(toast.id);
        }
        else {
            console.log(`cannot delete toast ${toast.id}. `);
        }
    }

    const getIcon = (variant) => {
        switch( variant ) {
            case 'success':
                return icon_success;
                break;
            case 'info':
                return icon_info;
                break;
            case 'warning':
                return icon_warning;
                break;
            case 'danger':
                return icon_danger;
                break;
        }
    }

    const generateId = (toast) => {
        if( typeof(toast.id) === 'number' ) {
            return toast.id;
        }
        toast.id = prevId + 1;
        setPrevId(toast.id);
        return toast.id;
    }

    const deleteToast = (id) => {
        console.log(`deleting toast ${id}`);
        const deletionIdxList = list.findIndex(e => e.id === id);
        const deletionIdxToastList = toastList.findIndex(e => e.id === id);
        console.log(`deletionIdxToastList: ${deletionIdxToastList}`);
        if(deletionIdxList == null || deletionIdxList === -1) {
            console.log(`cannot find list idx of id ${id}`);
            console.log('list:');
            console.log(list);
            return;
        }
        if(deletionIdxToastList == null || deletionIdxToastList === -1) {
            console.log(`cannot find toastList idx of id ${id}`);
            console.log('toastList:');
            console.log(toastList);
            return;
        }
        
        console.log('list before deletion:');
        console.log(list);
        console.log('toastList before deletion:');
        console.log(toastList);
        console.log('list[deletionIdxList]:');
        console.log(list[deletionIdxList]);
        list.splice(deletionIdxList, 1);
        console.log('toastList[deletionIdxToastList]:');
        console.log(toastList[deletionIdxToastList]);
        toastList.splice(deletionIdxToastList, 1);
        setList([...list]);
        console.log(`toast ${id} deleted successfully`);
        console.log('list after deletion:');
        console.log(list);
        console.log('toastList after deletion:');
        console.log(toastList);
    }

    const getToastClass = (toast) => {
        return `toast-popup ${toast.variant} ${position} ${toast.isDeleting? 'fadeout' : ''}`;
    }

    return (
        <>
            <div className={`toast-container ${position}`} >
                {
                    list.map((toast, i) => (
                        <div
                            key={i}
                            className={`toast-popup ${toast.variant} ${toast.isDeleting ? (position + ' fadeout') : (position + '-slide')}`}
                            onLoad={() => {
                                if( !toast.isLoaded ) {
                                    toast.Id = generateId(toast);
                                    toast.canDelete = true;
                                    toast.isDeleting = false;
                                    toast.isLoaded = true;
                                    console.log(`on load ${toast.id}`);
                                    setTimeout(() => markForDeletion(toast), 500);
                                }
                            }}
                            onMouseOver={() => {
                                toast.canDelete === true ? toast.canDelete = false : null;
                                toast.isDeleting === true ? toast.isDeleting = false : null;
                                console.log(`mouse over ${toast.id}`);
                            }}
                            onMouseLeave={() => {
                                toast.canDelete === false ? toast.canDelete = true : null;
                                markForDeletion(toast);
                                console.log(`mouse leave ${toast.id}`);
                            }}
                        >
                            <div className={'toast-icon'}>
                                <img src={getIcon(toast.variant)} />
                            </div>
                            <div className={'toast-text'}>
                                <div className={'toast-title'}>
                                    {toast.variant.charAt(0).toUpperCase() + toast.variant.slice(1)}
                                </div>
                                <div className={'toast-message'}>{toast.message}</div>
                            </div>
                            <button
                                className={'close-button'}
                                onClick={() => {
                                    toast.canDelete = true;
                                    deleteToast(toast.id)
                                }
                            }>
                                X
                            </button>
                        </div>
                    ))
                }
            </div>
        </>
    )
}

Toast.defaultProps = {
    position: 'bottom-right'
}

export default Toast;

Snippet of Home.js where I am testing this new Toast component – A class component as I’m working on updating a pre-existing application to remove dependency on the react-toastify library

// Leaving out constructor and other irrelevant code...
  toastSuccess() {
    const newToast = {
      variant: 'success',
      message: 'This is a test of the success variant toast pop-up.'
    }
    this.setState({
      toastList: [...this.state.toastList, newToast]
    });
  }
  toastInfo() {
    const newToast = {
      variant: 'info',
      message: 'This is a test of the info variant toast pop-up.'
    }
    this.setState({
      toastList: [...this.state.toastList, newToast]
    });
  }
  toastWarning() {
    const newToast = {
      variant: 'warning',
      message: 'This is a test of the warning variant toast pop-up.'
    }
    this.setState({
      toastList: [...this.state.toastList, newToast]
    });
  }
  toastDanger() {
    const newToast = {
      variant: 'danger',
      message: 'This is a test of the danger variant toast pop-up.'
    }
    this.setState({
      toastList: [...this.state.toastList, newToast]
    });
  }

render() {
    return (
      <div className="Home" style={{height:'100%'}}>
        <Toast
            toastList={this.state.toastList}
            position={'bottom-right'}
        />
        <div style={{display:'flex', justifyContent:'center'}}>
          <Button onClick={() => this.toastSuccess()}>Success</Button>
          <Button onClick={() => this.toastInfo()}>Info</Button>
          <Button onClick={() => this.toastWarning()}>Warning</Button>
          <Button onClick={() => this.toastDanger()}>Danger</Button>
        </div>
        {// ...}
      </div>
    );
  }

Let me know if there’s a way to get this code running here on StackOverflow using that Code Snippet feature, as that would be really helpful so that you readers can see the issue first-hand. Unfortunately I’ve never had any luck getting it to work, but I’ll keep trying for a bit to see if I can figure it out.

Struggle to commit more than 500 document in firestore batch

I spent the last 2 days trying to find a way to modify a virtually unlimited amount of data in my cloud function.
I am aware it’s a topic already heavily discussed but despite trying every single solution I found, I always end up with a similar scenario so I guess it’s not only the way iI treat my batches.

The goal here is to be able to scale up our activity and anticipate the growth of users so I’m running some stress tests.

I’m skipping the entire app idea because it would take a while but here is the problem :

1) I am feeding an array with the list of the desired actions for the batch :

   tempFeeObject["star"]=FieldValue.increment(restartFee)
    let docRefFees = db.collection(collectedFeesDb).doc(element); // log action
    finalArray.push([docRefFees,tempFeeObject,"set"])

2) I try to resolve all the final arrays. In this case, for the stress test, we talk about 6006 documents.
Here is the code for it :

    try 
     {  
       const batches = []       
       finalArray.forEach((data, i) => {
       if (i % 400 === 0) {
         let newBatch = db.batch();
         batches.push(newBatch)
        }
        const batch = batches[batches.length - 1]
          let tempCommit = {...data[1]}
          Object.keys(tempCommit).forEach(key => {
            if(data[1][key] && data[1][key].seconds && !Number.isNaN(data[1][key].seconds)){
              let sec = 0
              let nano = 0
              if(Object.keys(data[1][key])[1].includes("nano")){
                sec = parseInt(data[1][key][Object.keys(data[1][key])[0]],10)
                nano = parseInt(data[1][key][Object.keys(data[1][key])[1]],10)
              }else{
                sec = parseInt(data[1][key][Object.keys(data[1][key])[1]],10)
                nano = parseInt(data[1][key][Object.keys(data[1][key])[0]],10)
              }
                let milliseconds = (sec*1000)+(nano/1000000)
                tempCommit[key] = admin.firestore.Timestamp.fromMillis(milliseconds) 
              }
          });
          if(data[2]==="set"){
            batch.set(data[0], tempCommit, {merge: true});  
          }else  if(data[2]==="delete"){
            batch.delete(data[0]);  
          }
        })
        await Promise.all(batches.map(batch => batch.commit()))
        console.log(`${finalArray.length} documents updated`)
        return {
                  result:"success"
                }
      }
      catch (error) {
        console.log(`***ERROR: ${error}`)
        return {
                  result:"error"
                }
      }

The middle part might seem confusing but it is made to recreate the timestamp (i had errors when instead of a timestamp I had the array of values instead. And I test the array to find the seconds and nanoseconds because I also had cases where my script found seconds either in the first or second position).
So my script checks each key of the committed document and recreates the timestamp if he finds one.

3) Results :

The results are my main problem :
On one side it is working since my database is being updated with the correct values.
But it is not happening the way it should.

Here are the function logs :

4:04:01.790 PM
autoStationEpochMakerTestNet
Function execution started    <=== Function START
4:04:02.576 PM
autoStationEpochMakerTestNet
Auto epoch function treating : 1 actions
4:04:02.577 PM
autoStationEpochMakerTestNet
atation : Arcturian Space Station has 1 actions
4:04:02.582 PM
autoStationEpochMakerTestNet
Function execution took 791 ms. Finished with status: ok  <== function END
4:04:02.682 PM
autoStationEpochMakerTestNet
list used : 1      <== But the functions called by the previous one are still printing
4:04:04.926 PM
autoStationEpochMakerTestNet
***ERROR: Error: 4 DEADLINE_EXCEEDED: Deadline exceeded
4:04:05.726 PM
autoStationEpochMakerTestNet
result : { result: 'error' }
4:04:05.726 PM
autoStationEpochMakerTestNet
Arcturian Space Station function epoch generator failed. testmode = true
4:07:02.107 PM
autoStationEpochMakerTestNet
Function execution started  <== Second function Trigger START
4:07:02.156 PM
autoStationEpochMakerTestNet
6006 documents updated    <== Receiving logs from what i assume is the previous function trigger
4:07:02.158 PM
autoStationEpochMakerTestNet
result : { result: 'success' }
4:07:02.210 PM
autoStationEpochMakerTestNet
Auto epoch function treating : 0 actions  <== As expected there is no more action to treat since it was actually processed on the previous call
4:07:02.212 PM
autoStationEpochMakerTestNet
Function execution took 104 ms. Finished with status: ok

So my comprehension of what is happening is as follows :

The function triggers and builds the batches but is somehow instantly finished without waiting for the function or returning anything.
Meantimes there are still logs coming from the function including this one :
***ERROR: Error: 4 DEADLINE_EXCEEDED: Deadline exceeded

So I feel my batch array isn’t working as expected.
Then on the following function triggers (scheduled function, every 3 min). All the functions seem to finish to execute properly.
Once again, my database is being updated as it should be.

A few elements might be noticing:

  • Some of the data being committed are timestamps which I think counts for more than 1 action ?
  • In this case, one document has more than 2000 fields updated (simple int value)
  • await promise.all() is new to me so it’s also one of my leads.
  • I set the function ram at 2Go and timeout at 540sec.

Also here is the code for the main function (the scheduled one, which is here to dispatch actions and wait for the answer) :


Object.keys(finalObject).forEach(async (stationName) => {
      if(finalObject[stationName].finalList.length>0){
        let epochDbUsed = stationsEpochDb[stationName]
        let resultGenerator = await generateEpochsForStation(finalObject[stationName].finalList,finalObject[stationName].actionsToRemove,actionsDb,epochDbUsed,testMode)
    
        if(resultGenerator.result==="success"){
          await db.collection(logsDb).add({
            "user":"cloudFunction",
            "type": `createdEpochs${stationName}`,
            "station":stationName,
            "testMode":testMode,
            "actionQty":actionCount,
            "note":`New epoch has been created on ${stationName}. testmode : ${testMode}`,
            "date":FieldValue.serverTimestamp()
          });
        }else{
          console.log(`${stationName} function epoch generator failed. testmode = ${testMode}`)
          await db.collection(logsDb).add({
            "user":"cloudFunction",
            "type": `createdEpochs${stationName}Failure`,
            "station":stationName,
            "testMode":testMode,
            "actionQty":actionCount,
            "note":`New epoch has been created on ${stationName}. testmode : ${testMode}, FAILED`,
            "date":FieldValue.serverTimestamp()
          });
        }  
      }
    });
    return null

I am not sure if the return null at the end could mess things up, since its a scheduled function, I’m not sure what I’m supposed to return (actually never really thought of that, and realizing as I write, I’m going to look that up after posting that 🙂 ).

Well, I think this is enough data to understand the situation, feel free to ask any more details of course.

Thanks a lot to whoever will take the time to help 🙂

ReactJS navbar will not load 100%

I am trying to add a navbar to my ReactJS website and I am trying to add a navbar to my website.
It need the navbar to be on 100% width. I tried using ‘width: 100%;’. But it will not make the header 100% .
Here is my Code:

ReactJS:

import React from 'react';

import './Header.css';

function Header() {
    return (
        <nav className="header">
            <a href="#">Home</a>
            <p>   </p>
            <a href="#">About</a>
            <p>   </p>
            <a href="#">Projects</a>
            <p>   </p>
            <a href="#">Resume</a>
       </nav>
    )
}

export default Header;

CSS:

.header > a {
  background-color: #171A25;
  text-decoration: none;
  color: white;
  text-align: center;
  word-spacing: 33px;
}
.header {
    background-color: #171A25;
    align-items: center;
    word-spacing: 33px;
    padding: 1em 1.5em;
}