Closing the div by changing the form status

In Next.js 14, I have a form

page.tsx

interface MyFormData {
  data: FormData,
  messages: string[],
  showError: boolean,
}

export default function Register() {
  const initialState: MyFormData = {
    data: new FormData(),
    messages: [],
    showError: true
  }

  const [state, formAction] = useFormState<MyFormData>(createRegisterUser, initialState)

In this form, the data is sent to the action

And if there is an error in the validation of the fields in this form, an error message is displayed.

<form action={formAction}>
 ....
{state.showError && state.messages && state.messages.length > 0 && (
    <div className="flex w-full shadow-lg rounded-lg mt-5 border border-l-transparent border-gray-200">
        <div className="bg-red-600 py-4 px-6 rounded-l-lg flex items-center">
          <MdDangerous color="white"/>
        </div>
        <div className="flex flex-col px-4 py-6 bg-white rounded-r-lg justify-between w-full">
          {state.messages && state.messages.map((message, index) => (
            <div key={index} className="pb-2">{message}</div>
          ))} 
        </div>
        <button className="mx-4">
          <IoCloseSharp 
            onClick={() => {
              const newState = { ...state, showError: false }
              formAction(newState)
            }}
          />
        </button>
    </div>
)}
....
      <button type="submit">
        Save
      </button>
    </div>
</form>

The issue is that in the error message, there is a button to close it, and I want that when clicking the button with the IoCloseSharp icon, the state.showError is updated to false, because the action returns true if an error occurs.

However, I’m not able to do it because the formAction doesn’t expect to receive arguments like newState.

Would anyone know how I could close this div?

Serving a webpage content by running a php/python script

I’m trying to set up a RSS for my site. So I would like to make a link that takes in a keyword and produces a RSS feed.

I have a python script (script.py) to generate this xml, but I don’t know how to run it and serve the text to the user when my page is called.

Essentially I would like to have someone visit mysite.com/<keyword> and be served the text generated in script.py

I can make the text appear to the user by simply running javascript, but this isn’t being picked up by the rss.

<html>
<head>
  <title>Run Python Script</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>
<body>
<script>
    $.ajax({
      method: "POST",
      url: "/script.py",
    })
      .done(function( response ) {
        var newXML = document.open("text/xml", "replace"); 
        newXML.write(response); 
        newXML.close(); 
      });
</script>
</body>
</html>

It seams like there should be some way of generating this text and serving it to the user, but I feel like I’m just missing something obvious

I’m using godaddy and cpanel if that helps

NavBar Responsividade Mobile

Estou enfrentando um problema técnico com o meu site e preciso de ajuda. A barra de navegação (navbar) não está aparecendo em telas de menor dimensão, embora funcione perfeitamente em dispositivos móveis. É essencial que ela seja exibida completamente, pois contém botões que servem como links para outras páginas e diversas funções importantes. Alguém poderia me orientar sobre como resolver esse erro para garantir que a navbar seja visível em todos os tipos de dispositivos?

Código css:

a {
    text-decoration: none !important;
    color: #fff;

}

.last-link {
    text-decoration: underline !important;
}

.graficos {
    position: absolute;
    top: 6rem;
    right: 13rem;
}

@media(max-width: 767px) {
    .graficos {
        position: absolute;
        top: 3rem;
        right: 2rem;
    }
}

@media (max-width: 767px) {
    .text-md-left {
        text-align: center;
    }
}

h1 {
    margin-top: 10rem;
    font-size: 4rem;
}

@media(max-width: 767px) {
    h1 {
        margin-top: 5rem;
        font-size: 4rem;
    }
}

.text-md-left {
    line-height: 1.1;
    padding: 0px;
}

#menu {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 1000;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    left: 12px;
    right: 0px;
    align-items: center;
    height: 4rem;
    background-color: #fff;

}

#menu .btn-primary {
    margin-right: 12px;
}

#menu a {
    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
    color: black;

}

.logo-ui {
    position: relative;
    left: 15.5rem;
}

@media(max-width: 767px) {
    .logo-ui {
        position: absolute;
        width: 42%;
        margin-top: -2.5rem;
        z-index: 0;
        left: 0px;
    }
}
`

Ela só fica aparecendo na esquerda somente a logo, e ao ir pra telas maiores funciona perfeitamente

How to add an iframe with inline script to my Next.js project?

I have the following iframe to add to my Next.js project.

<iframe
  class="plot"
  aria-label="Map"
  id="datawrapper-chart-${id}"
  src="https://datawrapper.dwcdn.net/${id}/1/"
  style="width: 0; min-width: 100% !important; overflow: scroll; flex-grow: 1"
  data-external="1"
></iframe>
<script type="text/javascript">
  !(function () {
    "use strict";
    window.addEventListener("message", function (a) {
      if (void 0 !== a.data["datawrapper-height"]) {
        var e = document.querySelectorAll("iframe");
        for (var t in a.data["datawrapper-height"])
          for (var r = 0; r < e.length; r++)
            if (e[r].contentWindow === a.source) {
              var i = a.data["datawrapper-height"][t] + "px";
              e[r].style.height = i;
            }
      }
    });
  })();
</script>

I tried using dangerouslySetInnerHTML and it did work, but I wonder if there’s a more “React” way to do it.

The ways below didn’t work.

copy verbatimremove function call

Function to replace button locations after logging in

so basically I have a website with a dropdown menu in the navigation bar, when I press the links in the dropdown menu it redirects me to the login page. I want a code which will make those same buttons in the dropdown menu directly lead me to the user page after logging in.

Thank you in advance!!!!! <33

Moment not giving same values ! (react-native expo)

        var a = moment().toISOString(true)
        var b = moment();
        var c = moment(b.toISOString(true));
        console.log(a);// 2024-04-15T00:09:47.226+01:00 --->here time is one hour ahead
        console.log(b);//"2024-04-14T23:09:47.472Z"
        console.log(c);//"2024-04-14T23:09:47.472Z"

Please help me understand the following

Tensorflow Save and load graph mode locally issue

I want to save a graph model from the service and load it locally sicne I conside the app will use the model offline.
But there is a issue that I cant save the model locally and load it back since it is a graph model.

Here is the code:

import * as tf from “@tensorflow/tfjs”;
import { asyncStorageIO } from “@tensorflow/tfjs-react-native”;

export const loadModel = async () => {

await tf.ready();
const model = await tf.loadGraphModel("https://test_model/model.json");
console.log("Model loaded.");

// Save the model
await model.save('localstorage://my-model-1');
console.log("Model saved");

//Load the model from AsyncStorage
const loadedModel = await tf.loadGraphModel('localstorage://my-model-1/model.json');

return loadedModel;

It will show the error there is no save handler for this code.

If I use the direct location such as ‘/Moblieclient/model/model.json’, it will either show network request fail and can not conect to Metro.

I had test the save and local model by using AsyncStorageIO, but it can only work for sequential model not a graph model.

Solo Full Stack Developer security and career concerns

I’m a freelance developer who built few companies their CRM programs using various JS based frameworks.

Well, I’ve no relevant degree (not in anything really) and development was just a hobby thing until I started implementing a CRM system for the company I was working for in years back.
Ever since, I made CRM for full-time and now that I’ve just finished another project I believe I’m at a point to make a decision whether to continue taking more jobs or to go get a degree, hence I’m asking for advice.

The first thing that’s bugging me in continuing with building more CRM is security. When I’d started on making them, the customer base to be managed was small and I didn’t really worry about malicious attacks. But as of now, when I look at thousands of personal records being managed by the programs I made, it does worry me a lot for a possible data leak that will doom my humble life.

I of course follow and implement the modern and well known security standards in my code but am not so sure if it’s enough.

If I decide to take more jobs, my next one probably will target multiple companies under a certain industry that in total may end up having not thousands but million personal records. I know that I won’t be able to handle such a project by myself as I’ve been doing, so if I do go ahead, I’ll need to hire someone with the right knowledge (CI/CD, scaling, security) to make it happen.

Therefore, back to my original question, do you think I should continue on working or stop and get a degree? Or maybe try to find a job for proper experience?

Your opinions will be much appreciated!

p.s. lemme know if you think I should delete this question for the sake of my apps’ security..

Multiple same JS downloads at once

When checking my website on PageSpeed Insights, i see a list of long tasks as shown on this image. I really have no idea how to fix it. The end of my HTML file is :

<script src="js/jquery-1.11.1.min.js"></script>     
<script src="js/compressed.js"></script>
<script src="js/jquery.mixitup.min.js" async></script>
<script src="js/custom.js" async></script>
<script src="js/output.min.js" async></script>
<script src="contactme/js/contact.js" async></script>

</body>

Screenshot of PSI

Angular 17 nothing showing when calling API observable and subscription

Working on an Angular 17 project and I’m trying to get back the auctions that have auctionParmas or none at all. I can see the data values coming back in the dev tools response tab but when I console.log the data it comes back undefined. I have to be missing a very simple step here. The URL works just fine because I can call it in another browser tab http://localhost:7001/api/auctions. Image below show the response tab in the dev tools.

enter image description here

Auction Interface

export interface Auction {
  reservePrice: number
  seller: string
  winner?: string
  soldAmount: number
  currentHighBid: number
  createdAt: string
  updatedAt: string
  auctionEnd: string
  status: string
  make: string
  model: string
  year: number
  color: string
  mileage: number
  imageUrl: string
  id: string
}

export class Auction implements Auction {}

Pagination Interface:

export interface Pagination<T> {
  pageIndex: number;
  pageSize: number;
  count: number;
  data: T;
}

Service:

  getAuctionsList(auctionParams: AuctionParams) {
    let params = new HttpParams();

    params = params.append('pageIndex', auctionParams.pageNumber);
    params = params.append('pageSize', auctionParams.pageSize);

    return this.http.get<Pagination<Auction[]>>(this.auctionUrl + 'auctions',{params});
   }

Componentn:

  export class AuctionListComponent implements OnInit {

   auctions: Auction[] = [];
   auctionParams = new AuctionParams();
   totalCount = 0;

    constructor(private auctionService: AuctionListService) { }

   ngOnInit(): void {
     this.getAuctions();
   }

     getAuctions() {
      this.auctionService.getAuctionsList(this.auctionParams).subscribe({
      next: response => {
      this.auctions = response.data;
      this.auctionParams.pageNumber = response.pageIndex;
      this.auctionParams.pageSize = response.pageSize;
      this.totalCount = response.count;
     },
     error: error => console.log(error)
    })
   }
 }

html component:

<div class="m-3" *ngFor="let auction of auctions">

<div class="card mb-3" style="max-width: 540px;">
    <div class="row g-0">
        <div class="col-md-4">
        <img src="{{ auction.imageUrl }}" class="img-fluid rounded-start" alt="...">
        </div>
        <div class="col-md-8">
            <div class="card-body">
                <h5 class="card-title">{{ auction.year }} {{ auction.make}} {{auction.model}}</h5>
                <p class="card-text">High bid: {{ auction.currentHighBid }}</p>
                <p class="card-text">Milage: {{ auction.mileage }}</p>
                <p class="card-text">
                        End Date: {{ auction.auctionEnd | date }}    
                </p>                   
                                                            
                <app-timer [childTimer]="auction.auctionEnd"></app-timer>                                         
                
                <p class="card-text"><small class="text-body-secondary">Last updated 3 mins ago</small></p>
            </div>
        </div>
    </div>    
</div>

ckeditor5 re-applying list operations erroring

I’m trying to apply operations to the ckeditor5 editor.
There seem to be operations that increment the baseVersion and operations that don’t.

I recorded the operations created while using the editor.

I gather the operations that have a baseVersion and apply them to the document, as below.

writer.batch.addOperation( op );
this.editor.model.applyOperation( op );
this.setCurrentVersion( operation.data.baseVersion + 1 );

most operations apply without issue – Insert, Split, Attribute.

However, when I try to apply operations involved in making an unordered list,
I apply:

 1. AttributeOperation, key: "listIndent" -- successfully applied
 2. AttributeOperation, key: "listItemId" -- successfully applied
 3. AttributeOperation, key: "listType" -- successfully applied
 4. Insert Operation:
     {
       'baseVersion': 7,
       'position': {
         'root': 'main',
         'path': [0],
         'stickiness': 'toNone'
        },
        'nodes': [
          {
            'attributes': {
              'listIndent': 0,
              'listItemId': 'e82c6ae82a34f6e11f25cbdeaf69f8200',
              'listType': 'bulleted'
             },
             'data': 'o'
          }
        ],
        'shouldReceiveAttributes': true,
        '__className': 'InsertOperation'
     } 
    -- ERRORS as below

Uncaught TypeError: Cannot read properties of null (reading 'parent')
    at removeCustomMarkerElements (converters.js:322:24)
    at DowncastDispatcher.eval (converters.js:273:9)
    at DowncastDispatcher.fire (emittermixin.js:159:47)
    at DowncastDispatcher._testAndFire (downcastdispatcher.js:482:14)
    at DowncastDispatcher._testAndFireAddAttributes (downcastdispatcher.js:499:18)
    at Object.convertAttributes (downcastdispatcher.js:520:45)
    at DowncastDispatcher.eval (downcasthelpers.js:772:23)
    at DowncastDispatcher.fire (emittermixin.js:159:47)
    at DowncastDispatcher._testAndFire (downcastdispatcher.js:482:14)
    at DowncastDispatcher._convertInsert (downcastdispatcher.js:273:18)

The listItemId matches the newly created list.

Although the downcast dispatcher errors and the editor stops updating, further operations continue getting applied to the model as expected.

I notice that immediately preceeding the erroring “Insert” operation are three RootAttributeOperations that mirror AttributeOperations 1-3. I’m unsure of whether these also need applying when I’m replying operations. When I try to apply them in the order they were created using the editor, it still errors

Any idea why this is erroring, when other operations seem to work as expected?

Setting tabindex dynamically in a navigation drawer

I’m trying to ignore the focus when the drawer is closed, but I still can tab through links, even when it’s closed (when showDrawer ref is set to false). I can even still tab if I set tabindex="-1" on the <nav>. The only solution I found is to add :tabindex="showDrawer ? 0 : -1" directly to each of the <router-link> or a <button>, not even the <li>, but the actual element inside of it, otherwise it won’t work. I feel like it’s not the best way to do it. I need to somehow manage to do it using tabindex, because removing the drawer from the DOM when it’s closed is going to add performance implications.

<template>
    <nav class="drawer" :tabindex="showDrawer ? 0 : -1">
        <ul class="drawer__list">
            <li class="drawer__item">
                <router-link
                    to="/"
                    >Home</router-link>
            </li>
            <li class="drawer__item">
                <button
                    About
                </button>
            </li>
            <li class="drawer__item">
                <button
                    Log In
                </button>
            </li>
        </ul>
    </nav>
    <ItemOverlay :class="{ active: showDrawer }" />
</template>

Looking for a possible solution.

React and JSX Error with spread operator Objects are not valid as a React child, If you meant to render a collection of children, use an array instead

( My first post)

I am having an issue with a nested object in react app . I am using a spread operator, relying on what I was taught class and what I’ve seen here.

Some questions have been written on a similar premise. But non helped and i am really stuck

Thank you

The console write : “Objects are not valid as a React child, If you meant to render a collection of childr case
I’m getting an error here:

"STREET": setUser({ ...user, address: { ...user.address, street: e.target.value } });

import { useState, useEffect } from "react";
import { getById, updateItem, deleteItem } from "../utils/utils.js";
import "./css/UserComp.css";

import TodosComp from "./TodosComp.jsx";
function UserComp(props) {
  const userdata = props.userdata;
  const URL_USERS = "https://jsonplaceholder.typicode.com/users";

  const [user, setUser] = useState(userdata);
  const [isHover, setHover] = useState(false);
  const [isExtended, setExtended] = useState(false);

  const updateUser = (e, type) => {
    console.log(user);
    
    switch (type) {
      case "NAME":
        setUser({ ...user, name: e.target.value });
      case "EMAIL":
        setUser({ ...user, email: e.target.value });
      case "STREET":
        setUser({
          ...user,
          address: { ...user.address, street: e.target.value }
        });
        break;
      case "CITY":
        setUser({
          ...user,
          address: { ...user.address, city: e.target.value },
        });
        break;
      case "ZIP":
        setUser({
          ...user,
          address: { ...user.address, zipcode: e.target.value },
        });
        break;

      default:
        break;
    }
    console.log({ _user: user });
  };

  const updateDB = async (e) => {
    let result, status;
    ({ result, status } = await updateItem(URL_USERS, userdata.id, user));
    console.log({ updatUserSTat: result, status });
  };

  const deleteDB = async (e) => {
    let result, status;
    ({ result, status } = await deleteItem(URL_USERS, userdata.id));
    console.log({ updatUserSTat: result, status });
  };
  const setColor = () => {
    const left_container = document.querySelector(".left-container");
    if (left_container.style.backgroundColor === "white" && isExtended)
      left_container.style.backgroundColor = "mistyrose";
    else left_container.style.backgroundColor = "white";
  };

  const addTodoPart = () => {
    const id_button = document.querySelector("#id-button");
    id_button.addEventListener("click", () => {
      setExtended(!isExtended);
    });
    console.log({ extended: isExtended });
  };

  useEffect(() => {
    //on mount
    console.log({ extended: isExtended });
  }, []);

  return (
    //TODOS add color change when presing id
    <div id="main" style={{ width: "600px" }}>
      <div className="flex-container">
        <div className="left-cotainer">
          style=
          {{
            width: "50%",
            margin: "2px",
            float: "left",
            border: "solid 1px black",
          }}
          <button
            onClick={(e) => {
              setExtended(!isExtended);
              setColor();
            }}
          >
            ID:{userdata.id}
          </button>
          <br />
          Name:{" "}
          <input
            type="text"
            defaultValue={userdata.name}
            onChange={(e) => updateUser(e, "NAME")}
          ></input>
          <br />
          Email:{" "}
          <input
            type="text"
            defaultValue={userdata.email}
            onChange={(e) => updateUser(e, "EMAIL")}
          />
          <br></br>
          <button width="2px" onClick={(e) => updateDB(e)}>
            UPDATE
          </button>
          <button width="2px" onClick={(e) => deleteDB(e)}>
            DELETE
          </button>
          {/* address strart */}
          <h6 onMouseOver={() => setHover(!isHover)}>Other Data</h6>
          {isHover && (
            <div id="address">
              Street:
              <input
                type="text"
                defaultValue={userdata.address.street}
                onChange={(e) => updateUser(e, "STREET")}
              />
              <br />
              City:
              <input
                type="text"
                defaultValue={userdata.address.city}
                onChange={(e) => updateUser(e, "CITY")}
              ></input>
              <br />
              Zip Code:
              <input
                type="text"
                defaultValue={userdata.address.zipcode}
                onChange={(e) => updateUser(e, "ZIP")}
              ></input>
            </div>
          )}
        </div>

        {isExtended && (
          <div
            className="right-container"
            style={{
              width: "48%",
              margin: "2px",
              float: "right",
              border: "solid 1px black",
            }}
          >
            {/* <TodosComp data={user.id} /> */}
          </div>
        )}
      </div>
    </div>
  );
}

export default UserComp;

Solving “array rotation leetcode #189” by recursive swap

I am working on the LeetCode problem #189 Rotate Array:

I tried to solve it by starting at element k then replacing every element next on the sequence. It works for some cases but for some others not all elements are reached and then I need to run the same code for k+1 and so on.

Code:

var rotate = function(nums, k) {
    let len = nums.length

    // start with element at index K
    let curr_index = k
    let curr_element = nums[curr_index]

    let target_index = -1

    // stop when a full cycle is completed
    while (target_index !== k) {
        target_index = (curr_index + k) % len
        const target_element = nums[target_index]

        // replace target with current element
        nums[target_index] = curr_element

        // set current to be equal to target
        curr_element = target_element
        curr_index = target_index
    }
};

it works for case [1,2,3,4,5,6,7], k=3 but does not work for case [1,2,3,4], k=2

is there any way of solving this problem with this “brute force” way of doing the rotations for real?