What exactly does the while loop do here in insertion sort?

function insertionSort(arr)
{
    // Two loops, outer to look at each element, and inner to shift elements

    // Outer loop
    for (let i = 1; i < arr.length; i++) // i starts at 1 because we don't need to sort the first element
    {
        let key = arr[i];
        let j = i - 1;

        // Inner loop
        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

const arr = [8, 20, -2, 4, -6];
insertionSort(arr);
console.log(arr); // [-6, -2, 4, 8, 20]

It’s working fine I just don’t understand it and I can implement it all on my own except for the while loop. I’m a beginner so please bear with me

Rendering Problem from server to client and client to server

This is main.js where my landing page is render and this is here

let posts = [
    {
        title: "Hello World!",
        content: "Hello World!",
        date: "01klfljs",
    }
];

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.use(bodyParser.json());

app.get("/", (req,res) => {
    res.render("index.ejs");
});

app.get("/myblog", (req,res) => {
    res.render("myblog.ejs", {
        posts
    });
});

app.post("/myblog", (req,res) => {
    const post = {
        title: req.body.title,
        content: req.body.content,
        date: new Date(),
    }
    posts.push(post);
});

This is myblog.js where I want to add this to main.js

const api_url = "http://localhost:3000";

app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.get("/", async(req,res) => {
    try{
        const {posts} = req.body;
        const response = await axios.get(`${api_url}/myblog`);
        res.render("backend.ejs",{
            posts: response.data,
        });
    }
    catch(error){
        res.status(500);
    }
});

This is backend.ejs, where all file will upload, edit

<body>
    <a href="/new">Create a New Post</a>
    <div>
       <ul>
        <% post.forEach(post => {%>
          <li>
            <h2><%= post.title %></h2>
            <h3><%= post.content %></h3>
            <h4><%= post.date %>/h4>
          </li>
          <% }); %>
       </ul>
    </div>

This is myblog.ejs where all file to be shown from backend.js

<body>
    <ul>
        <% posts.forEach(post => { %>
            <li>
                <h2><%= post.title %></h2>
                <h3><%= post.content %></h3>
                <h4><%= post.date %></h4>
            </li>
            <% }); %>
    </ul>
</body>

I want render data from myblog.ejs to backend.ejs
where is the problem ?

What exactly does {} mean in TypeScript?

I saw the following viewpoint on the React TypeScript Cheatsheet website: “An empty interface, {} and Object all represent “any non-nullish value”—not “an empty object” as you might think.”

For example:

let value: {};

value = 1;
value = "foo";
value = () => alert("foo");
value = {};
value = { foo: "bar" };

value = undefined; // Error Type
value = null;  // Error Type

But it doesn’t seem to work that way in React.

As shown in the code below, if {} means non-empty values, it would imply that the Child component’s props could accept any non-empty parameters. However, when I tried to pass an id to the Child component, it resulted in an error.

const Child:FC<{}> = (props) => {
  return (
    <div>
      Child
    </div>
  )
}

const App = () => {
  return (
    {/**Error: Type '{ id: string; }' is not assignable to type 'IntrinsicAttributes'.**/}
    <Child id={'111'}/>
  );
}

I would like to receive a fundamental explanation.

JavaScript capture data from input field & post it to output field in a multiple row app

I want to input data to a div (column headed ‘Result’) from an input (columnd headed ‘Edit/Update’) field using a button (named ‘Update’) to trigger the event. I can grab the data from the input field and I can identify which button is clicked. I can’t seem to combine the 2 functions to get the data transferred from the input to the output div.

the form with the fields in question
This is my JS code:

// select the parent element
const formGroup = document.getElementById('table');
// select input field
const addData = document.getElementById('input');
// select output field
const output = document.getElementById('output');

// identify which button is clicked
const buttonClicked = (e) => {
const isButton = e.target.nodeName === 'BUTTON';

if (!isButton) {
return;
}
console.log(e.target.id);
};
formGroup.addEventListener('click', buttonClicked);

// Get data from input and display to output element
addData.addEventListener('submit', (e) => {
e.preventDefault();
const data = addData.res.value.trim();
if (data.length) {
document.getElementById('output').innerHTML = data;
addData.reset();
}
// console.log(data);
});

**This is my HTML:**
<div id="table">
    <div id="title" class="row">
      <div>
        <div class="header">Round #</div>
          </div>
          <div>
            <div class="header">Date</div>
          </div>
          <div>
            <div class="header">Versus</div>
          </div>
          <div>
            <div class="header">Ground</div>
          </div>
          <div>
           <div class="header">Result</div>
          </div>
          <div>
            <div class="header">Edit/Update</div>
          </div>
        </div>
        <div id="line1" class="row">
          <div>
            <div class="header">1.</div>
          </div>
          <div>
            <div class="header">17/08/2024</div>
          </div>
          <div>
            <div class="header">Ipswich</div>
          </div>
          <div>
            <div class="header">Portman Road</div>
          </div>
          <div>
            <div id="output" class="header"></div>
          </div>
          <div class="form-group">
            <input
              id="input"
              class="data"
              placeholder="Enter/Edit Result"
              name="res"
            />
            <button id="button-1" class="btn btn-success" type="button">
              Update
            </button>
          </div>
        </div>
        <div id="line2" class="row">
          <div>
            <div class="header">2.</div>
          </div>
          <div>
            <div class="header">25/08/2024</div>
          </div>
          <div>
            <div class="header">Brentford</div>
          </div>
          <div>
            <div class="header">Anfield</div>
          </div>
          <div>
            <div id="output" class="header"></div>
          </div>
          <div class="form-group">
            <input
              id="input"
              class="data"
              placeholder="Enter/Edit Result"
              name="res"
            />
            <button id="button-2" class="btn btn-success" type="button">
              Update
            </button>
          </div>
        </div>
      </div>
    </div>

Ant design timepicker component does not update on change

I am using Ant Design’s timepicker component on a project of mine, to set the shift start and end time of a user. When a user is created, the start and end shift times are mandatory. And the user is able to see what time they have selected as a preview in the timepicker component (default expected behaviour), when they change the time in the timepicker.

However, when the user decides the change the shift time, a problem arises. They are not able to see the newly chosen time whenever they change the time. Only when they submit the form, and open it again, they are able to see the changed time. However, if they clear the timepicker and set an new time, or if they select the Now option in the timepicker, they are able to see the changes even if they change the time again normally after that.

To put it clearly, users are not able to see the changed time preview whenever they change the time. And it works normally when the field is cleared or the time is set to Now and the changed again.

I don’t know why this happens, please help me out.

      <Form.Item
        name="shift_start"
        label="Shift Start Time"
        rules={[
          { required: true, message: "Please select the shift start time." },
        ]}
      >
        <TimePicker
          format="HH:mm"
          use12Hours={false} // Ensure 24-hour format
          defaultValue={moment("00:00", "HH:mm")}
          value={moment(shiftStartTime, "HH:mm")}
          onChange={(time, timeString) => {
            console.log("Selected shift start time:", time, timeString);
            setShiftStartTime(timeString);
          }}
        />
      </Form.Item>

This is the form item with the shift start time.

Are there easy methods than this js code for activating dark mode?

I have written some code to switch between Dark and Light modes in a website. But I had to write very big css file for that. I’ve used Java script for my switcher.

I’ve written tis code


function darkMode() 
{
var element = document.body;
var content = document.getElementById("DarkModetext");
element.className = "dark-mode";
content.innerText = "Dark Mode is ON";
}
function lightMode() 
{
var element = document.body;
var content = document.getElementById("DarkModetext");
element.className = "light-mode";
content.innerText = "Dark Mode is OFF";
}

Help me plese with another method for switching modes.

And the css file is too large for here.

Google Places Autocomplete Not Working for Address Input Field

I’m implementing Google Places Autocomplete on an address input field in my form. Despite setting up the autocomplete functionality, it does not seem to be working as expected. The input field does not display any address suggestions.

I have set up Google Places Autocomplete for my address input field, but it does not provide suggestions or complete addresses. The functionality seems to be missing, and I’m not seeing any errors in the console related to this.

HTML STRUCTURE

 <section
        class="hero min-h-[640px] xl:min-h-[840px] bg-hero bg-center lg:bg-cover bg-no-repeat bg-fixed xl:rounded-bl-[290px] relative z-20" id="Home"
      >
        <div class="container mx-auto">
          <!-- text -->
          <div
            class="hero__text md:w-[567px] flex flex-col items-center text-center xl:text-left lg:items-start"
          >
          <div>
            <h1 class="h1 custom-gradient mb-8 break-words">
              Instant Cash Offer for Your Home
            </h1>
            <p class="mb-8 text-first-onPrimary">
              Sell Fast, No Fees or Commissions. We Buy in Any Condition!
            </p>
          </div>
            <form
              action="/submit"
              method="POST"
              class="flex flex-col lg:flex-row gap-4 min-w-[200px]"
            >
              <!-- Property Address Input -->
              <div class="mb-8 mx-auto xl:mx-0 inline-flex items-center">
                <div class="relative">
                  <label for="search_input" class="sr-only" 
                    >Enter Property Address</label
                  >
                  <i
                    class="ri-home-line absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400"
                  ></i>
                  <input
                    type="text"
                    id="search_input"
                    name="Property Address"
                    placeholder="Enter Property Address"
                    class="btn btn-secondary ring-1 ring-gray-200 outline-none focus:ring-8 focus:ring-first-onPrimary focus:text-second-secondary"
                    onfocus="this.previousElementSibling.style.display='none';"
                    onblur="if(this.value===''){this.previousElementSibling.style.display='block';}"
                  />
                </div>
              </div>

              <!-- Phone Input -->
              <div class="mb-8 mx-auto xl:mx-0 inline-flex items-center">
                <div class="relative">
                  <label for="phone" class="sr-only">Phone</label>
                  <i
                    class="ri-smartphone-line absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400"
                  ></i>
                  <input
                    type="number"
                    id="phone"
                    name="Phone Number"
                    placeholder="Phone"
                    autocomplete="street-address"
                    class="btn btn-secondary ring-gray-200 outline-none focus:ring-8 focus:ring-first-onPrimary focus:text-second-secondary"
                    onfocus="this.previousElementSibling.style.display='none';"
                    onblur="if(this.value===''){this.previousElementSibling.style.display='block';}"
                  />
                </div>
              </div>

              <!-- Submit Button -->
              <button
                type="submit"
                class="btn btn-primary inline-flex mx-auto xl:mx-0 items-center"
              >
                GET FREE OFFER
                <i class="ri-arrow-right-line text-first-onPrimary"></i>
              </button>
            </form>
          </div>
        </div>
      </section>

JAVASCRIPT FILE


document.addEventListener('DOMContentLoaded', () => {


const apiKey = import.meta.env.VITE_GOOGLE_MAP_KEY


// API key in Google Maps script
const script = document.createElement('script');
// Template Literals
script.src =  `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`;
script.async = true;
script.defer = true;
document.head.appendChild(script);

})





function initMap() {
    var searchInput = 'search_input';

    // Executes only after the DOM is fully loaded
    $(document).ready(function () {
        // Ensure that the element exists before proceeding
        var searchInputElement = document.querySelector('#' + searchInput);

        // Log the selcted element to the console
        console.log("Selected ELement using querySelector:". searchInputElement);

        if (searchInputElement) {
            // Initialize autocomplete only if the element exists
            var autocomplete = new google.maps.places.Autocomplete(searchInputElement, {
                types: ['geocode'] // Filters to include only geocoded locations
            });

            // Place Changed Event Listener
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var near_place = autocomplete.getPlace();
                console.log(near_place);
            });
        } else {
            console.error("Element with ID '" + searchInput + "' not found.");
        }
    });
}

I do not see any specific error messages related to the Google Places Autocomplete functionality. However, I have checked the console for errors and verified that the Google Maps API is loading correctly.

I have tried:

  • Verifying that the Google Maps JavaScript API key is correct and has the Places API enabled.
  • Checking for typos in the id and for attributes.
  • Ensuring that the initMap function is correctly loaded and executed.
  • Trying different Google Maps API keys.

Additional Information:

  1. I am using tailwind css for styling

  2. Vite as my build tool

  3. Javascript and Jquery for functionality and interactivity

Can anyone help me troubleshoot why the Google Places Autocomplete is not working for my address input field? Are there specific issues or common mistakes in the setup that I should be aware of?

Thank you for your assistance. I appreciate any help or suggestions you can provide to resolve this issue.

Why is req.body undefined in Next.js? [duplicate]

I am logging out request.body and it says that it is undefined.

Here is the code of api/generateFlashcards/page.ts

export default async function POST(request: NextApiRequest) {
  const data = request.body;
  console.log(data)
}

And Here is where I am trying to fetch it. (description is a string just in case):

fetch('/api/generateFlashcards', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({description}),  
}).then(res => {
    console.log(res);
})

I tried changing the type of request to request: Request. Also, tried request.json() which gave an error:

TypeError: request.json is not a function
    at POST (./app/api/generateFlashcards/page.ts:39:25)
    at stringify (<anonymous>)

I tried to look at other’s solutions but they didn’t work.

Is there Java Script Code to handle checkbox plugin(Pretius Smart Checkbox Column) in Oracle APEX?

checkbox column

i’ve interactive report that have checkbox column from plugin (Pretius Smart Checkbox Column) i used this plugin in dynamic action, you can look at image above. References from that image if i checked(True) at Terima Column, will Unchecked(False) in Tidak Column and if i want to checked(True) at Tidak Column will uncheked(false) at Terima Column. is there javascript code to handle this checkbox plugin(Pretius Smart Checkbox Column)?

i expected have expression javascript code to handle plugin

I can’t run the app after installing react-native-maps

I use a simple code of map but after running always i receive this errors :

enter image description here

I try to install other veriosn of react-native-maps but nothing change

this is the code :

import React from 'react';
import MapView from 'react-native-maps';
import { StyleSheet, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <MapView style={styles.map} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    width: '100%',
    height: '100%',
  },
});

Mongoose findByIdAndUpdate() Casting Error When Updating Posts with HTML Content

I’m currently learning Mongoose and ran into an issue with the findByIdAndUpdate() method. I have a form where I enter data, and this data is stored in a MongoDB database using Mongoose. Everything works fine when I manually enter the content and update it via the API.

However, when I copy and paste content from the web that contains HTML tags such as

, , etc., into the form and save it, the data is saved correctly to the database. But when I try to update this specific post, I encounter the following error:

Cast to ObjectId failed for value “undefined” (type string) at path “_id” for model “Post”.

I logged the formData._id and currentUser._id in the console, and it appears that formData._id is undefined, even though the post was saved in the database with a valid _id generated by MongoDB. This issue only happens with posts that contain HTML content, while others update without any problem.

Here’s the relevant part of code:

import { FileInput, Select, TextInput, Button, Alert } from 'flowbite-react'
import React, { useEffect, useState } from 'react'
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import {getDownloadURL, getStorage, ref, uploadBytesResumable} from 'firebase/storage';
import { app } from '../firebase';
import {CircularProgressbar} from 'react-circular-progressbar' ;
import 'react-circular-progressbar/dist/styles.css';
import { useNavigate, useParams } from 'react-router-dom';
import { useSelector } from 'react-redux';



export default function UpdatePost() {
    const [file, setFile] = useState(null);
    const [imageUploadProgress, setImageUploadProgress] = useState(null);
    const [imageUploadError, setImageUploadError] = useState(null);
    const [formData, setFormdata] = useState({});
    const [publishError, setPublishError] = useState(null);
    const {postId} = useParams();


    const navigate = useNavigate();
    const {currentUser} = useSelector(state => state.user);

    useEffect(() =>{
        try {
            const fetchPost = async () => {
                const res = await fetch(`/api/post/getposts?postId=${postId}`);
                const data = await res.json();
                
                if(!res.ok){
                    console.log(data.message);
                    setPublishError(data.message);
                    return;
                }
                if(res.ok) {
                    setPublishError(null);
                    setFormdata(data.posts[0]);
                    console.log("Fetched post data:", data.posts[0]);
                }
            };
            fetchPost();
        } catch (error) {
            console.log(error.message);
        }
    }, [postId])
    
    const handleUploadImage = async () => {
        try {
            if(!file){
                setImageUploadError('Please select an image');
                return;
            }
            setImageUploadError(null);
            const storage = getStorage(app)
            const fileName = new Date().getTime() + '-' + file.name;
            const storageRef = ref(storage, fileName);
            const uploadTask = uploadBytesResumable(storageRef, file);
            
            uploadTask.on('state_changed', (snapshot) => {
                const progress = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
                setImageUploadProgress(progress.toFixed(0));
            }, (error) => {
                    setImageUploadError('Image upload fail!');
                    setImageUploadProgress(null);
                },
            () => {
                    getDownloadURL(uploadTask.snapshot.ref).then((DownloadURL) => {
                        setImageUploadProgress(null);
                        setImageUploadError(null);
                        setFormdata({...formData, image: DownloadURL});
                    });
                }
            );
        } catch (error) {
            setImageUploadError('Image upload failed');
            setImageUploadProgress(null);
            console.log(">>> Check error: ", error);
        }
    };
    
    const handleSubmit = async (event) => {
        event.preventDefault();
        console.log(">>> form data id: ",formData._id)
        console.log(">>> currentUser id: ", currentUser._id);
        try {
            const res = await fetch(`/api/post/updatepost/${formData._id}/${currentUser._id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData),
            });
            const data = await res.json();
            if(!res.ok){
                setPublishError(data.message);
                return;
            }
            
            if(res.ok){
                setPublishError(null);
                navigate(`/post/${data.slug}`);
            }

        } catch (error) {
            setPublishError('Something went wrong');
        }
    }
  return (
    <div className='p-3 max-w-3xl mx-auto min-h-screen'>
        <h1 className='text-center text-3xl my-7 font-semibold '> 
            UPDATE YOUR POST
        </h1>
        <form className='flex flex-col gap-4 ' onSubmit={handleSubmit}>
            <div className="flex flex-col gap-4 sm:flex-row justify-between">
                <TextInput type='text' placeholder='Title' required id='title' className='flex-1'
                    onChange={(event) => setFormdata({...formData, title: event.target.value})}
                    value={formData.title}
                />
                <Select value={formData.category} onChange={(event) => setFormdata({...formData, category: event.target.value})}>
                    <option value='uncategorized'>Select a category</option>
                    <option value='javascript'>JavaScript</option>
                    <option value='reactjs'>React.js</option>
                    <option value='nextjs'>Next.js</option>

                </Select>
            </div>
            <div className="flex gap-4 items-center justify-between border-4 border-teal-300 border-dashed p-3">
                <FileInput type='file' accept='image/*' onChange={(event)=>setFile(event.target.files[0])}/>
                <Button type='button' gradientDuoTone='purpleToBlue' size='sm' outline onClick={handleUploadImage} disabled={imageUploadProgress}>
                    {
                        imageUploadProgress ? 
                            <div className="w-16 h-16">
                                <CircularProgressbar value={imageUploadProgress} text={`${imageUploadProgress||0}%`}/>
                            </div> :
                       ( 'Upload Image')
                    }
                </Button>
            </div>
                {
                    imageUploadError && (
                        <Alert color='failure'>
                            {imageUploadError}
                        </Alert>
                    )
                }
                {formData.image && (
                    <img src={formData.image} alt="upload" className='w-full h-72 object-cover'/>
                )}
                <ReactQuill required 
                            value={formData.content}
                            theme='snow' 
                            placeholder='Write something in your mind . . .' 
                            className='h-72 mb-12'
                            onChange={(value) => setFormdata({...formData, content: value})}            
                />
                <Button type='submit' gradientDuoTone='tealToLime'><div className="text-lg text-purple-800">Update</div></Button>
                {
                    publishError && <Alert color='failure' className='mt-5'>{publishError}</Alert>
                }
        </form>
    </div>
  )
}

My model:

import mongoose from "mongoose";


const postChema = new mongoose.Schema({
    userId: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true,
    } ,
    title: {
        type: String,
        required: true,
        unique: true
    },
    image: {
        type: String,
        default: 'https://bs-uploads.toptal.io/blackfish-uploads/components/blog_post_page/8969409/cover_image/optimized/unnamed-76880e314ca9bcaa0e0e19be57d2e75d.png'
    },
    category: {
        type: String,
        default: 'uncategorized',
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
}, {timestamps:true});

const Post = mongoose.model('Post', postChema);
export default Post;

I also came across a solution where it’s suggested to use mongoose.Types.ObjectId to handle such issues, but I’m unsure how to apply this to my case, especially when dealing with data that includes HTML content.

My question is:

Why is formData._id becoming undefined when the post includes HTML content?
How can I correctly update such posts without encountering this casting error?

Vue.js Request Returns Empty Array in created Hook, But Works on Button Click

I’m trying to fetch new notifications when my component is created, but the response data is empty. However, when I trigger the same logic with a button click, the API returns the correct data.

Here’s part of my Vue.js component:

export default {
  data() {
    return {
      showNotification: true,
      notificationsQueue: [],
      currentNotification: null
    }
  },
  created() {
    this.checkForNotifications()
  },
  methods: {checkForNotifications() {
      console.log('call hook')
      this.$http.get('/notifications/').then(response => {
        console.log('This should succeed from hook', response)
        console.log('This should succeed from hook', response.data)
        this.notificationsQueue = response.data
        this.showNextNotification()
      })
      .catch(error => {
        console.error('Error captured:', error)
      })
    },
...

Here’s the output from the console.log() when the request is made in the created hook:

This should succeed from hook [{…}]length: 0[[Prototype]]: Array(0)

However, when I make the same request by clicking a button, the response data is correct:

<button @click="getNotif">Get new notifi</button>

      getNotif() {
        this.$http.get('/notifications/').then(response => {
            console.log('This should succeed', response.data)
        })
        .catch(error => {
          console.error('Error captured:', error)
        })
      }

Here’s the console.log() output from the button click:

This should succeed [{…}]0: {id: 2, message: 'test first notification', created_at: '2024-08-29 07:48'}length: 1[[Prototype]]: Array(0)

On the Django side, the API seems to work fine:

class BusinessNotificationView(APIView):
    permission_classes = [IsAuthenticated]
    serializer_class = NotificationSerializer

    def get(self, request, *args, **kwargs):
        notifications = Notification.objects.filter(user=request.user, is_read=False)
        serializer = self.serializer_class(notifications, many=True)
        print('return : ', serializer.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

And the Django console output:

return :  [{'id': 2, 'message': 'test first notification', 'created_at': '2024-08-29 07:48'}]

Why is the created hook returning an empty array while the button click fetches the correct data?

Any ideas on what might be causing this behavior?

Only execute a function when specific page go to the page

I am trying to make a popup screen to show up after the page loaded, but the task required only A page moves to B page then the popup showed, if C page or D page can move to B page then the popup won’t show up:

A —> B (popup)

C / D —> B (nothing happened)

may I know are there any ways to perform such thing? Thank you!