for loop id with CKEditor [duplicate]

I have many same blocks of Javascript code with only difference is the id.

if(numEduIndex == 1){
    var editorEduDes = CKEDITOR.instances.edu_description_1;
    editorEduDes.on('paste', function (evt) {copyPasteCkeditor(evt)});
}
if(numEduIndex == 2){
    var editorEduDes = CKEDITOR.instances.edu_description_2;
    editorEduDes.on('paste', function (evt) {copyPasteCkeditor(evt)});
}
if(numEduIndex == 3){
    var editorEduDes = CKEDITOR.instances.edu_description_3;
    editorEduDes.on('paste', function (evt) {copyPasteCkeditor(evt)});
}

I want to use for loop to clean code, like this:

for (let i = 1; i <= 31; i++) {
   if(numEduIndex == i){
      var editorEduDes = CKEDITOR.instances.edu_description_ + i;
      editorEduDes.on('paste', function (evt) {copyPasteCkeditor(evt)});
   }
}

The problem I have is I can not concat i to the id edu_description.
Is there anyway I can do this with for loop?

Thank you all!

I was rotating 4 images around a circle border and stopping one image at 90 degrees and showing its content and increase size of that image

I was able to rotate 4 images around a circle border and able to stop one image at every 45 degrees. But I cant increase the size of that image which stops at 90 degrees to website and should be able to show the content of respective image when they come at 90 degrees. give me a answer to get out of this using html, css and JavaScript.

HTML Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./rotate.css">
    <script src="./rotate.js"></script>
</head>

<body>

    <div id="parent-circle">
        <div class="circle blue">vinay</div>
        <div class="circle pink">vinay</div>
        <div class="circle lime">vinay</div>
        <div class="circle orange">vinay</div>
    </div>
    <div class="mt-5 content  pt-2 ">
        <h1>Health Record</h1>
        <p class="w-75">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Dolorum, doloremque!</p>
    </div>

</body>

</html>

CSS Code

body {
  width: 90vw;
  height: 90vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

body #parent-circle {
  position: relative;
  width: 20vw;
  height: 20vw;
  border: 0.4vw solid rgba(0, 0, 0, 0.4);
  border-radius: 50%;
  transform: rotate(0deg);
  transition: transform 0.7s linear;
  animation: rotate 14s infinite linear;
}
body #parent-circle .circle {
  display: block;
  position: absolute;
  width: 30%;
  height: 30%;
  margin: -14%;
  border-radius: 50%;
  top: 50%;
  left: 50%;
}
body #parent-circle .circle.blue {
  background-color: #416ba9;
  transform: translate(10vw);
}
body #parent-circle .circle.pink {
  background-color: #e6427a;
  transform: rotate(90deg) translate(10vw) rotate(-90deg);
}
body #parent-circle .circle.lime {
  background-color: #cddb00;
  transform: rotate(180deg) translate(10vw) rotate(-180deg);
}
body #parent-circle .circle.orange {
  background-color: #e0592a;
  transform: rotate(270deg) translate(10vw) rotate(-270deg);
}
.content {
  margin-left: 20%;
}

@keyframes example {
  0% {
    width: 30%;
    height: 30%;
  }

  100% {
    width: 60%;
    height: 60%;
  }
}
@keyframes rotate {
  0% {
    -webkit-transform: rotate(0deg);
  }
  12.5% {
    -webkit-transform: rotate(90deg);
  }
  25% {
    -webkit-transform: rotate(90deg);
  }
  37.5% {
    -webkit-transform: rotate(180deg);
  }
  50% {
    -webkit-transform: rotate(180deg);
  }
  62.5% {
    -webkit-transform: rotate(270deg);
  }
  75% {
    -webkit-transform: rotate(270deg);
  }
  87.5% {
    -webkit-transform: rotate(360deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

This is what I was getting

This is what want

react-table not rendering rows

react-table does not show data in rows.

import React, { useEffect, useState, useMemo } from "react";
import "../../custom.css";
import {COLUMNS} from './columns';
import { useTable } from "react-table";

//some code

const columns = useMemo(() => COLUMNS, [])

  const data = useMemo(() => {
    console.log(childrens);
    return childrens;
  }, [childrens])

const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  })

//and more code here 

<table {...getTableProps()}>
        <thead>
          {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <th {...column.getHeaderProps()}>{column.render('Header')}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map(row => {
            prepareRow(row)
            console.log(row)
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
          ))}
              </tr>
            )
          })}
        </tbody>
      </table>

For debugging, I output each row in the console and there is all the data, there is also an initial data array in the console and everything is also correct there

enter image description here

Pass value from sensor to javascript

My project is to detect available and not available object and show the status at the dashboard. i’m using arduino as my microcontroller. For dashboard interface already completed. Now I’m having problem to pass status from sensor to the dashboard. i’m using ir sensor which is to detect object available or not available. if object detected, green light led will turn on and if object is not detected red light led will turn up.

My idea is when object available the table dashboard will change color to green or if not available the table dashboard will change color to red.

Dynamic position change of a content box on mouse hover

I’ve a section contains some boxes. Each box has a additional content box that is appearing on hover on right of each box. There are enough space to the right of the first three boxes, but not last 2 boxes as well.

My query is how can I change the hover content box position if the right side has enough space of not.

My be you can understand better with this prototype I made. Check Here in Figma

First Box
Last Box

How can I design like this prototype layout that I made for you in figma? Also can you refer to any demo or codebase then It would be better for me.

Thanks.

Handling errors for different response status in React?

I am developing a fullstack app with Spring Boot and React and there are different status codes and bodies for the following situations:

when credentials are wrong: 500

{
    "status": 500,
    "message": "Bad credentials"
}

when there is validation errors: 422

{
    "status": 422,
    "message": "Validation error. Check 'errors' field for details",
    "errors": [
        {
            "field": "password",
            "message": "size must be between 6 and 100"
        }
    ]
}

I display error messages. However, based on the situations, I have to check the response error fields or status codes and I thought to check using ? as shown below:

.catch((error) => {
  error.response.data.errors?.map(e => enqueueSnackbar(e.message, "error"))
  enqueueSnackbar(error.response.data.message?, "error");
});

But I am not sure if there is a more elegant way to handle these 2 different error types. Any idea?

When would a [[Prototype]] refers to a constructor [[Prototype]]: Constructor

While learning prototypical inheritance.I have seen the prototype referring to an Array, an Object or a Empty Function.

(https://i.stack.imgur.com/cdiky.png)

I am new to Java Script programming (prototypical inheritance world) and when debugging SAPUI5 framework i have noticed the prototype is pointing to a constructor.

(https://i.stack.imgur.com/nwiKT.png)

Could you please explain me in which scenario a [[Prototype]] points to a constructor. Can a [[Prototype]] points to any other apart from these 4 ( Array, Object, Empty Function and Constructor )

Why is the main thread blocked when scrolling in some browsers(such as Chrome)

I need to get the DOMRect of an element at each frame when scrolling, but I found that when the scrolling content is complex,the callback function of the scrolling event may need to wait for a long time to trigger, and it seems that the main thread is blocked

In chrome devtools -> performance, I found that there are basically yellow frames during scrolling, These yellow frames are called Partially presented frames

https://developer.chrome.com/en/blog/new-in-devtools-100/#perf

Previously, the Frames timeline visualizes any frames with delayed main-thread work as “dropped frames”. However, there are cases where some frames may still produce visual updates (e.g. scrolling) driven by the compositor thread.

The explanation in the document seems to confirm my guess,In addition, I also log the interval between the execution of requestAnimationFrame

let before = Date.now();
let now = Date.now();

function loop(){
  now = Date.now();
  if (now-before > 50) {
    console.log(now-before)
  }
  before = now;
  requestAnimationFrame(loop);
}

loop()

raf log

But there is no such problem in Firefox. Is it because the performance of Firefox is much better than that of Chrome?

How to Django handle multiple requests send at the same time

In a web application, multiple requests can be sent to the server at the same time. Handling these requests can become a challenging task, especially if the server has to perform complex operations, like making API requests, performing database queries, etc. In this post, we will discuss how Django can handle multiple requests sent at the same time.

    group_name_status = {'name': '', 'status':''}


def tokem_update(access_token):
    try:
        intervalInfo = UserIntervalInfo.objects.first()
        headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
        data = {'client_id': intervalInfo.client_id,
                'client_secret': intervalInfo.client_secret,
                'grant_type': 'password',
                'username': intervalInfo.user_id,
                'password': intervalInfo.user_password
                }
        response_token = requests.post(user_token, headers=headers, data=json.dumps(data))
        data = response_token.text
        tokens = json.loads(data)
        access_token.access_token = tokens['access_token']
        access_token.token_type = tokens['token_type']
        access_token.expires_in = tokens['expires_in']
        access_token.refresh_token = tokens['refresh_token']
        access_token.save()
        return access_token
    except:
        return False


def nema_status(request):
    if request.method == 'POST':
        try:
            group_id = request.POST.get('group_id')
            access_token = API_ACCESS_TOKEN.objects.first()
            current_datetime = timezone.now()
            difference = int((current_datetime - access_token.updated_at).total_seconds() / 3600)
            if difference > 7:
                access_token = tokem_update(access_token)
                if access_token == False:
                    messages.error(request, "Failed update the access token" )
                else:
                    messages.success(request, 'Successfully updated the access token')
            headers = {
                "Accept": "application/json",
                "Content-Type": "application/json",
                "Authorization": f"Bearer {access_token.access_token}"
            }
            if group_id != '0':
                group_name = Group.objects.get(id=group_id)
                if group_name.object_id:
                    par_group_nemas_status = f"https://rpt.tvilight.io/api/status?type=group&q={group_name.object_id}"
                    response_nema_status = requests.get(par_group_nemas_status, headers=headers)
                    if response_nema_status.status_code == 200:
                        datas = response_nema_status.json()
                        nemas = Nema.objects.filter(group=group_name)
                        for data in datas:
                            for nema in nemas:
                                if nema.object_id == data['object_id']:
                                    Nema_status.objects.create(
                                        status = data['status'],
                                        api_created_at= data['created_at'],
                                        message = data['message'],
                                        object_id=data['object_id'],
                                        object_type= data['object_type'],
                                        session_id= data['session_id'],
                                    )
                                    break
                        messages.success(request, f"{group_name.name} name status added successfully")
                    else:
                        messages.error(request, f"Something went wrong. Try again.")
                else:
                    messages.info(request, 'Group object not found.')
            elif group_id == '0':
                all_group = Group.objects.filter(is_delete=False)
                for group_name in all_group: 
                   
                    if group_name.object_id:
                        par_group_nemas_status = f"https://rpt.tvilight.io/api/status?type=group&q={group_name.object_id}"
                        response_nema_status = requests.get(par_group_nemas_status, headers=headers)
                        global group_name_status
                        group_name_status['name'] = group_name.name
                        group_name_status['status'] = response_nema_status.status_code
                        if response_nema_status.status_code == 200:
                            datas = response_nema_status.json()
                            nemas = Nema.objects.filter(group=group_name)
                            for data in datas:
                                for nema in nemas:
                                    if nema.object_id == data['object_id']:
                                        Nema_status.objects.create(
                                            status = data['status'],
                                            api_created_at= data['created_at'],
                                            message = data['message'],
                                            object_id=data['object_id'],
                                            object_type= data['object_type'],
                                            session_id= data['session_id'],
                                        )
                                        break
                messages.success(request, f"All group name status added successfully")
        except:
            messages.error(request, f"Something went wrong. Try again.")
    else:
        messages.error(request, "Something went wrong. Try again.")
    return redirect('nema:view_nema')


def get_group_name(request):
    global group_name_status
    return JsonResponse(group_name_status, status=200)

Request ajax and django url same time:

document.querySelectorAll('.nema-status-group').forEach(item => item.addEventListener('submit', e => {
            for(let i = 0; i < 5000; i++){
                setTimeout(get_table_name, i * 1000)
            }
        })
        );
        function get_table_name(){
            let label = document.querySelector('#lable');
            $.ajax({
                url: "{% url 'nema:group_name_status' %}",
    
                    type: "get",
                    dataType: "json",
                    success : (data) => {
                        if(label.innerHTML != `<b>Group:</b> ${data.name} <b>Status:</b> ${data.status}`){
                            if (data.name != ''){
                                
                                label.classList.add('badge');
                                label.innerHTML = `<b>Group:</b> ${data.name} <b>Status:</b> ${data.status}`;
                                if (data.status == 200){
                                    label.classList.remove('badge-gradient-danger')
                                    label.classList.add('badge-gradient-success');
                                }
                                else{
                                    label.classList.remove('badge-gradient-success');
                                    label.classList.add('badge-gradient-danger');
                                }
                            }
                        }
                    }
            })
        }

How to build output into multiple folders when building with vite and how to change the title for each folder

When my folder is like below,

my-app/ 
├─ package.json 
├─ src/ 
│ ├─ index.html 
│ ├─ main.js 
│ ├─ style.scss

Can I set it to build like below?

my-app/
├─ package.json
├─ src/
│  ├─ index.html
│  ├─ main.js
│  ├─ style.scss
├─ dist/
│  ├─ assets/
│  │  ├─ main.js
│  │  ├─ style.scss
│  ├─ one/
│  │  ├─ index.html
│  ├─ two/
│  │  ├─ index.html

And can I set it differently while building specific text in that folder?

When setting the vite.config.js file as shown below, I was able to confirm that the assets file was also created in each folder.

export default defineConfig({
  base: '',
  root: './src',
  build: {
    outDir: '../build',
    rollupOptions: {
      input: 'src/index.html',
      output: [
        {
          name: 'one',
          dir: path.join(__dirname, 'build/one'),
        },
        {
          name: 'two',
          dir: path.join(__dirname, 'build/two'),
        },
      ],
    },
  },

  plugins: [ViteEjsPlugin()],
});

Laravel 9 website Form data not saving to database and getting server error 500

I have Laravel website, then there have form for passing data to database. But while fill the form and trying to submit the data, I getting server error 500. So after I enable debug value as a ‘true’. Then I saw error like this,
“Illuminate
  
Database
  
QueryException
PHP 8.1.15
9.17.0
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘5’ for key ‘PRIMARY’ (SQL: insert into properties (l_id, p_id, p_name, size, type, status, province, district, city, dic, price, img, updated_at, created_at) values (005, 5, Thalalla – Land, 182,”

app
 / 
Http
 / 
Controllers
 / 
PropertyController
.php

: 50

$newProperty->city = $request->input('city');

$newProperty->dic = $request->input('dic');

$newProperty->price = $request->input('price');

$img = $request->file('img_path');

$path = $img->store('images/resource/property/main/', ['disk' =>   'my_files']);

$newProperty->img = "public/".$path;

    foreach ($salse as $table_data){

        if($name == $table_data->p_name && $district == $table_data->district){

            dump($newProperty);

            $action = "error";

            echo('--------------');

            dd($table_data);

        }

    }

    if($action == "ok"){

        $newProperty->save();

        foreach ($request->file('more_img_path') as $imagefile) {

            $image = new Image;

            $path2 = $imagefile->store('images/resource/property/gallery/', ['disk' =>   'my_files']);

            $image->p_id = $property_id;

            $image->img = "public/".$path2;

            $image->save();

        }



            // **********************activity log************************

            $newLog = new Log();

            $uname;

            $user;

            foreach(session('login_user') as $id => $details){

                $uname = $details['name'];

I’m mention below error screenshot. There showing error “newProperty(save);” code line.
Can someone help me to fix this error? enter image description here

Sequelize : How to Order By before Group By

how do I ORDER BY timestamp before GROUP BY in sequelize ORM?

Sample sequelize Query:

    await this._message.findAll({
        attributes: {
            include: [
                [
                    sequelize.literal(`(
                        SELECT *
                        FROM messages AS messages
                        ORDER BY
                            messages.created_at DESC
                    )`),
                    'messages'
                ],
            ]
        },
        include: [
            {
                required: true,
                model: App,
                as: 'apps',
                where: {
                    id: app.id,
                    user_id: user_id
                }
            },
            {
                required: true,
                model: Contact,
                as: 'contacts',
            },
        ],
        order: [
            ['created_at', 'DESC'],
        ],
        group: ['contact_id'],
    })
        .then(data => {

            ....

        })
        .catch(err => {

            ....

        });

    }

sample MySql Query:

SELECT 
  `messages`.`id`, 
  `messages`.`app_id`, 
  `messages`.`contact_id`, 
  `messages`.`parameters`, 
  `messages`.`wa_message_id`, 
  `messages`.`type`, 
  `messages`.`status`, 
  `messages`.`created_at`, 
  `messages`.`updated_at`, 
  (
    SELECT 
      * 
    FROM 
      messages AS messages 
    ORDER BY 
      messages.created_at DESC
  ) AS `messages`, 
  `apps`.`id` AS `apps.id`, 
  `apps`.`user_id` AS `apps.user_id`, 
  `apps`.`name` AS `apps.name`, 
  `apps`.`application_id` AS `apps.application_id`, 
  `apps`.`wb_account_id` AS `apps.wb_account_id`, 
  `apps`.`access_token` AS `apps.access_token`, 
  `apps`.`created_at` AS `apps.created_at`, 
  `apps`.`updated_at` AS `apps.updated_at`, 
  `contacts`.`id` AS `contacts.id`, 
  `contacts`.`user_id` AS `contacts.user_id`, 
  `contacts`.`country_code_id` AS `contacts.country_code_id`, 
  `contacts`.`first_name` AS `contacts.first_name`, 
  `contacts`.`last_name` AS `contacts.last_name`, 
  `contacts`.`name` AS `contacts.name`, 
  `contacts`.`email` AS `contacts.email`, 
  `contacts`.`phone_number` AS `contacts.phone_number`, 
  `contacts`.`convo_started` AS `contacts.convo_started`, 
  `contacts`.`notes` AS `contacts.notes`, 
  `contacts`.`last_active` AS `contacts.last_active`, 
  `contacts`.`created_at` AS `contacts.created_at`, 
  `contacts`.`updated_at` AS `contacts.updated_at` 
FROM 
  `messages` AS `messages` 
  INNER JOIN `apps` AS `apps` ON `messages`.`app_id` = `apps`.`id` 
  AND `apps`.`id` = 3 
  AND `apps`.`user_id` = 1 
  INNER JOIN `contacts` AS `contacts` ON `messages`.`contact_id` = `contacts`.`id` 
GROUP BY 
  `contact_id` 
ORDER BY 
  `messages`.`created_at` DESC;

Why am I getting the error “Uncaught TypeError: Cannot read properties of null (reading ‘appendChild’)”

I am creating my first ever JS project that is a simple To-Do list. I am creating a button that will add a paragraph of the inputted text into a container using .appendChild().

let addToDoButton = document.getElementById('addToDo');
let toDoContainer = document.getElementById('toDoContainer');
let inputField = document.getElementById('inputField');

/*On click we create a paragraph and append it to toDoContainer*/
addToDoButton.addEventListener('click', function(){
    var paragraph = document.createElement('p');
    toDoContainer.appendChild(paragraph);
})
html, body {
    width: 50%;
    margin: 0 auto;
    font-family: Arial, Helvetica, sans-serif
}

.container {
    width: 360px;
}

#inputField {
    width: 300px;
    height: 46px;
    border: 1px solid black;
    outline: none;
    font-size: 25px;
    vertical-align: middle;
}

#addToDo {
    height: 50px;
    width: 50px;
    border: 1px solid black;
    vertical-align: middle;
    font-size: 30px;
}

.to-dos {
    margin-top: 25px;
}

.paragraph-styling {
    margin: 0;
    cursor: pointer;
    font-size: 20px;
}
<h1>To Do List</h1>
<div class="container">
    <input id="inputField" type="text"><button id="addToDo">+</button>
    <div class="to-dos" id="toDoContainer">
    </div>
</div>

It happens every time I press the button.

I tried tracking all the variables but that didn’t help and I also re-read all of my variable names and they seem to be correct. I also tested the button with and without text inside the textbox.