javascript array sort by two specific names first

I have table columns that I have sorted to have column key ‘status’ always on first order, then later i realized that i need to put checkbox before it, so now i have three conditions:

If only ‘status’ then it is first, if ‘status’ and ‘checkbox’ then status becomes second order, else if only ‘checkbox’ then first.

I have tried to add to my current working sort on ‘status’ but i haven’t quite understood how exactly that sort compare works on two specific names:

 config.tableColumns.sort((a, b) => {
  if ((a.Key.toLowerCase() == 'checkbox' && a.Key.toLowerCase() != 'status') 
  || (a.Key.toLowerCase() != 'checkbox' && a.Key.toLowerCase() == 'status')) {
    return -1;
  }
  if (a.Key.toLowerCase() != 'checkbox' && a.Key.toLowerCase() != 'status') {
    return 1;
  }
  const nameA = a.Key || '';
  const nameB = b.Key || '';
  return nameA.localeCompare(nameB);
});

any help would be appreciated.
Thanks.

Updating and draw new line Datatable

I have a Javascript function that allows me to update a row (contained in a datatable) It opens several popup/modals and then I can modify row and send new values to my backend. The problem is the row is not updated directly in Datatable and I need new value without refreshing the entire page. Here is my entire logic :

    function updateImprimante(imprimanteId, updatedData) {
        $.ajax({
            type: 'PATCH', // Ou PATCH, selon votre configuration de route Rails
            url: '/imprimantes/' + imprimanteId, // URL pour la mise à jour (à adapter)
            dataType: 'json', // Set the expected response data type
                headers: {
                    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content'),
                    'Accept': 'application/json' // Set the Accept header to indicate JSON response
                },
            data: { 
                imprimante: updatedData 
                },
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
            },
            success: function(response) 
            {
                console.log('Mise à jour réussie', response);
                console.log(response)
                if(response.updatedImprimante) {
                    updateRowInDataTable(response.updatedImprimante.id, response.updatedImprimante);
                } else {
                    console.error('Updated data is missing in response');
                }
            },
            error: function(error) {
                console.error('Erreur lors de la mise à jour', error);
            }
        });
    }

    function updateRowInDataTable(imprimanteId, updatedData) {
        var idToUpdate = parseInt(imprimanteId);            
        var row = table.rows(function(idx, data, node) {
            return $(node).find('.edit-imprimante-btn').data('imprimante-id') == idToUpdate;
        });

        if (row.any()) {
            row.data([
                updatedData.modele_ref,
                ...
            ]).draw();
        }
    }

How can I fix that ?

How to resize an image used inside a javascript code?

I made a clickable image that plays a sound when you click it using a code I found here in SO.

This works just fine, but I want to place the image in another part of the screen and resize it.

I want the image to have width="300" height="210" style="margin-left: 1300px;">, but I don’t know how to implement it into the JS code, or if i should do something else to fix this.

Any suggestions? I haven’t tried anything to fix it just yet because I have no idea of just what should I do, since my knowledge is still very basic

<div>
    <script>
        var audio = new Audio("https://files.catbox.moe/23r8yv.mp3");
        audio.oncanplaythrough = function ( ) { }
        audio.onended = function ( ) { }
     </script>
    <input type="image" src="https://felizcumpleanos.neocities.org/cosas%20para%20cumplea%C3%B1os/mewo%20fondo%20mimi.png" onclick="audio.play ( )">
</div>  

Why my HTML code adds a special character (‘>) on runtime whereas no such thing is introduced in the code? [closed]

I have my code as below:

var ipAddress = "2a03:2880:f126:83:face:b00c:0:25de";
     dataItem.URL = `
     <a href="http://godboh.db-ip.com/v2/free/${ipAddress}" target="popup" onclick="window.location.open(this.href,'_blank', 'width=500,height=500');return false;">${ipAddress}</a>

The code generates the below HTML on runtime:

<td class="clickable-cell" role="gridcell"><a target="_blank" href="
     <a href=&quot;http://godboh.db-ip.com/v2/free/2a03:2880:f126:83:face:b00c:0:25de&quot; target=&quot;popup&quot; onclick=&quot;window.open(this.href," _blank',="" 'width="500,height=500');" return="" false;"="">2a03:2880:f126:83:face:b00c:0:25de</a>
     '&gt;
     <a href="http://api.db-ip.com/v2/free/2a03:2880:f126:83:face:b00c:0:25de" target="popup" onclick="window.open(this.href,'_blank', 'width=500,height=500'); return false;">2a03:2880:f126:83:face:b00c:0:25de</a>
     </td>

It adds a ‘> special character and displays Output as : 2a03:2880:f126:83:face:b00c:0:25de’> 2a03:2880:f126:83:face:b00c:0:25de..Why it is generating output like this ?

I am expecting the below output :
URL : 2a03:2880:f126:83:face:b00c:0:25de

How do I use the an array of keys as a filter to sanitize an array of objects?

I have an array of objects that I call daysArray. This array represents 2 days as illustrated below:

console.log(daysArray)

Which logs out:

(2) [{…}, {…}]

…revealing an array of objects. When further expanded it reveals:

(2) [{…}, {…}]
   0: {Wednesdays: Array(4)}
   1: {Fridays: Array(4)}

…it reveals that the objects are two days. Lets further expand:

0: 
   Wednesdays: Array(4)
      0: {T_04:00_Start: 1703034000, T_08:00_End: 1703048400}
      1: {T_12:00_Start: 1703062800, T_16:00_End: 1703077200}
      2: {T_16:00_Start: 1703077200, T_20:00_End: 1703091600}
      3: {T_20:00_Start: 1703091600, T_00:00_End: 1703106000}
1: 
   Fridays: Array(4)
      0: {T_04:00_Start: 1703206800, T_08:00_End: 1703221200}
      1: {T_12:00_Start: 1703235600, T_16:00_End: 1703250000}
      2: {T_16:00_Start: 1703250000, T_20:00_End: 1703264400}
      3: {T_20:00_Start: 1703264400, T_00:00_End: 1703278800}

…it reveals that each day holds 4 time ranges. Each time range has a start time KEY and a timestamp associated to it and an end time KEY and a timestamp associated to it.

Note that the time range KEYS for both days (Fridays and Wednesdays) are all the same.

  0: {T_04:00_Start: T_08:00_End:}
  1: {T_12:00_Start: T_16:00_End:}
  2: {T_16:00_Start: T_20:00_End:}
  3: {T_20:00_Start: T_00:00_End:}

The following code is supposed to add an additional day to the daysArray array called Tuesdays, and most importantly, make sure that it only holds the following time ranges to keep it uniformed to the days already existing in the daysArray array being Wednesday and Fridays.

In the code, it is supposed to use the time ranges values in the removedKeys array to filter out (remove) the unwanted time ranges.

Find below my code:

const elementToInsert = "Tuesdays";

// Check if "Tuesdays" is not already in daysArray before proceeding
if (!daysArray.some(obj => Object.keys(obj)[0] === elementToInsert)) {
// Extract time range keys from tempRemovedTimeRanges for Tuesdays
const removedKeys = [...new Set(tempRemovedTimeRanges.flatMap(Object.values).flat().flatMap(Object.keys))];

console.log(removedKeys);


// Iterate through tempRemovedTimeRanges and remove corresponding time ranges from Tuesdays
for (const removedRangeKey of removedKeys) {
  const dayObj = daysArray.find(obj => obj.hasOwnProperty(elementToInsert));
  if (dayObj) {
    const originalLength = dayObj[elementToInsert].length;

    dayObj[elementToInsert] = dayObj[elementToInsert].filter(existingRange =>
      !removedKeys.includes(removedRangeKey) ||
      !Object.entries(existingRange).some(([key, value]) =>
        removedRangeKey === key
      )
    );

    const removedCount = originalLength - dayObj[elementToInsert].length;

    console.log(`Removed ${removedCount} time ranges from ${elementToInsert}: `, removedRangeKey);
    console.log(`Updated ${elementToInsert}: `, dayObj[elementToInsert]);
  } else {
    console.log(`${elementToInsert} not found in daysArray.`);
  }
}



// Add "Tuesdays" along with its content back to daysArray
daysArray.push(...tempRemovedTuesdays);
console.log('Restored Tuesdays to daysArray: ', daysArray);

// Clear tempRemovedTuesdays after adding back to daysArray
tempRemovedTuesdays.length = 0;

// Check the everyday checkbox if all the checkboxes are checked!
if (daysArray.length === 7) {
  const checkbox = document.getElementById("_EverydayEveryDay");
  checkbox.checked = true;
  checkbox.disabled = true;
}
} else {
console.log(`${elementToInsert} is already in daysArray.`);
}

The following logs out:

(4) ['T_00:00_Start', 'T_04:00_End', 'T_08:00_Start', 'T_12:00_End']
Tuesdays not found in daysArray.
Restored Tuesdays to daysArray:  (3) [{…}, {…}, {…}]

Expanding on the daysArray reveals that Tuesdays was added:

(3) [{…}, {…}, {…}]
  0: {Wednesdays: Array(4)}
  1: {Fridays: Array(4)}
  2: {Tuesdays: Array(6)}

However that the time ranges aren’t uniformed. Lets further expand

Fridays: Array(4)
   0: {T_04:00_Start: 1703206800, T_08:00_End: 1703221200}
   1: {T_12:00_Start: 1703235600, T_16:00_End: 1703250000}
   2: {T_16:00_Start: 1703250000, T_20:00_End: 1703264400}
   3: {T_20:00_Start: 1703264400, T_00:00_End: 1703278800}

2: 
  Tuesdays: Array(6)
   0: {T_00:00_Start: 1702933200, T_04:00_End: 1702947600}
   1: {T_04:00_Start: 1702947600, T_08:00_End: 1702962000}
   2: {T_08:00_Start: 1702962000, T_12:00_End: 1702976400}
   3: {T_12:00_Start: 1702976400, T_16:00_End: 1702990800}
   4: {T_16:00_Start: 1702990800, T_20:00_End: 1703005200}
   5: {T_20:00_Start: 1703005200, T_00:00_End: 1703019600}

The desired out come for ‘Tuesdays’ should be:

  Tuesdays: Array(4)
   0: {T_04:00_Start: 1702947600, T_08:00_End: 1702962000}
   1: {T_12:00_Start: 1702976400, T_16:00_End: 1702990800}
   2: {T_16:00_Start: 1702990800, T_20:00_End: 1703005200}
   3: {T_20:00_Start: 1703005200, T_00:00_End: 1703019600}

Refs not updating during interval (react JS)

In my code, I have a function that simulates the typing action of a bot (think chatGPT), I want to add a button that will stop the typing midway and finish it instantly, I am using a useEffect to check for updates in a ref that is tied to a button, but the value never seems to update until the interval itself is finished. In fact, no variable in my entire component updates until the interval is finished running.

  const [currentText, setCurrentText] = useState("");
  const [currentlyTyping, setCurrentlyTyping] = useState(false);
  const stopTypingRef = useRef(false);
  const intervalIdRef = useRef(null);

  useEffect(() => {
    console.log('ref updated')
    if (stopTypingRef.current) {
      clearInterval(intervalIdRef.current);
      textFinish();
    }
  }, [stopTypingRef.current]);

  const chatImitate = (textToType, move) => {
    let currentIndex = 1;
    setCurrentText(textToType.split(" ")[0]);
    textToType1 = textToType;


    intervalIdRef.current = setInterval(() => {
      if (currentIndex < textToType.length && move !== "instant") {
    
        setCurrentlyTyping(true);

        // Split the text into an array of words
        let words = textToType.split(" ");

        // Add the current word to currentText

        setCurrentText(prevText => prevText + " " + words[currentIndex - 1]);

        // Increment currentIndex after adding the word
        currentIndex++;

        if (currentIndex === words.length) {
          // If all words are typed, clear the interval
          clearInterval(intervalIdRef.current);
          textFinish();
        }
  }, 130);

return () => {
      clearInterval(intervalIdRef.current);
    };
};

      <button
        className="down-arrow absolute bottom-[20vh] right-[6vw]"
        onClick={() => {
          stopTypingRef.current = true;
        }}
      >
        Stop typing
      </button>

The ref in this button does not seem to trigger the UseEffect nor does it update anywhere in my code except for when the interval has finished running:

I have tried every solution chatGPT seems to give me but none of them are working. I believe some use of async may fix this issue? I am quite new to react Javascript so any insight into this issue will be much appreciated.

For dynamically customized forms, how can python scripts implement auto-selection?

I would like to implement this form auto-selection in python language, but for the options of the drop-down form, I can’t find the corresponding element to locate it by element. As shown in the screenshot, the element that contains the content of the option is changing as I click on different options on the screen.

`enter image description here
enter image description here
enter image description here

How can I use Logged in user id in another page?

I’m new to using Vue and Pinia
I want to show logged in user first_name & last_name, but when I want to access the user id after logged in, it returns undefined
could you please help me to fix this problem
actually I can access these infomations on the login page, but I want to access them right after login, when redirect to home page and go to other pages

here is my pinia login store:

import { defineStore } from 'pinia'
import { axiosAPI } from '../axios'

export default defineStore('login', {
  state: () => ({
    user: [],
    isLoading: false,
    isuserLoggedIn: false,
    token: '',
    userInfo: [],
    isRedirect: false,
    userId: '',
  }),
  actions: {
    async loginUser(values) {
      this.isLoading = true
      await axiosAPI
        .post('user/login', values)
        .then((response) => {
          console.log(response)
          this.isLoading = false
          const data = response.data.data.payload
          if (data) {
            this.user = data
            this.isuserLoggedIn = true
            this.token = data.token
            localStorage.setItem('token', this.token)
            this.userId = this.user.id
            this.isRedirect = true
            setTimeout(() => {
              window.location.href = '/home'
              this.isRedirect = false
            }, 20000)
          }
        })
        .catch((error) => {
          this.isLoading = false
        })
        this.getInfo(this.userId)
    },
  },
  persist: true
})

here is my profile component:

<template>
      <p
        class="sm:text-neutral-950 sm:block hidden sm:text-sm sm:font-light pl-4"
        :class="userProfile"
      ></p>
      {{ userProfile }}
</template>
<script>

import useLoginStore from '../stores/login'
import { mapStores } from 'pinia'
export default {
  name: 'Profile',
  data() {
    return {
      usr: useLoginStore(),
    }
  },
  computed: {
    ...mapStores(useLoginStore),
    userProfile() {
      return `${this.usr.userInfo.first_name} ${this.usr.userInfo.last_name}`
    }
  },
  }
}
</script>

How can I select a DOM element, which name is changing

I have this DOM elelement, where the part of the name of the menu [ v15rco8kc2 ] is changing for every call of the document. How Could I use a joker in the QuerySelector?

document.querySelector("#menu-v15rco8kc2 > div:nth-child(1) > button > span.Typography-module__lVnit.Typography-module__Nfgvc.Button-module__Imdmt")

Laravel Filament, Need suggestion to create customizable Dashboard

I am using laravel Filament 3, currently this is my code for the admin panel,
but I am trying to create a dashboard where user able to add and remove the widget in the dashboard

->viteTheme('resources/css/filament/admin/theme.css')
            ->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources')
            ->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
            ->pages([
                PagesDashboard::class,
            ])
            ->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\Filament\Widgets')
            ->widgets([
                WidgetsAccountWidget::class,
                // WidgetsFilamentInfoWidget::class,
            ])

Why Fabric dose not re-render the Circle when I change its location and size through customized control?

I read the Fabric offical document and demos, then customized two controls to scale the Cricle. The Circle container size and controls’ position will change, but I found Fabric did not re-render the Circle.

I want to know why this will happen? Thanks for any help!

Here is my codepen: https://codepen.io/cactusxx/pen/xxMoRXZ

var canvas = (this.__canvas = new fabric.Canvas("c"));
// create a rect object
function Add() {
  var newRect = new fabric.Rect({
    left: 100,
    top: 50,
    fill: "yellow",
    width: 200,
    height: 100,
    objectCaching: false,
    stroke: "lightgreen",
    strokeWidth: 4
  });
  canvas.add(newRect);
}

var circle = new fabric.Circle({
  radius: 100,
  fill: "#f55",
  top: 100,
  left: 100
  // visible: false
});

circle.set({
  borderColor: "red",
  cornerColor: "green",
  cornerSize: 12,
  cornerStyle: "circle",
  transparentCorners: false
});

canvas.add(circle);
canvas.setActiveObject(circle);
circle.controls = updateControls();

function updateControls() {
  return {
    mt: new fabric.Control({
      x: 0,
      y: -0.5,
      cursorStyle: "not-allowed",
      render: renderNotAllowed
    }),
    mr: new fabric.Control({
      x: 0.5,
      y: 0,
      cursorStyle: "not-allowed",
      render: renderNotAllowed
    }),
    ml: new fabric.Control({
      x: -0.5,
      y: 0,
      cursorStyle: "not-allowed",
      render: renderNotAllowed
    }),
    mb: new fabric.Control({
      x: 0,
      y: 0.5,
      cursorStyle: "not-allowed",
      render: renderNotAllowed
    }),
    br: new fabric.Control({
      x: 0.5,
      y: 0.5,
      cursorStyle: "crosshair",
      actionHandler: scaleObject
    }),
    tr: new fabric.Control({
      x: 0.5,
      y: -0.5,
      cursorStyle: "crosshair",
      actionHandler: scaleObject
    })
  };
}

function scaleObject(eventData, transform, x, y) {
  var circleObject = transform.target;
  var xOff = 0,
    yOff = 0,
    diff = 0;
  if (circleObject.__corner === "tr") {
    // console.log("tr");
    var trX = circleObject["left"];
    var trY = circleObject["top"] + 2 * circleObject["radius"];
    xOff = x - trX;
    yOff = trY - y;
    diff = Math.max(xOff, yOff, 0);
    circleObject["top"] = trY - diff;
    circleObject["left"] = trX;
  } else if (circleObject.__corner === "br") {
    var brX = circleObject["left"];
    var brY = circleObject["top"];
    xOff = x - brX;
    yOff = y - brY;
    diff = Math.max(xOff, yOff, 0);
  }
  var newRadius = Math.round(diff / 2);
  circleObject["radius"] = newRadius;
  circleObject["height"] = 2 * newRadius;
  circleObject["width"] = 2 * newRadius;
  // console.log(xOff, yOff, diff);
  // console.log(circleObject);
  // Update Object
  circleObject.setCoords();
  canvas.requestRenderAll();
}

function renderNotAllowed(ctx, left, top, styleOverride, fabricObject) {
  ctx.beginPath();
  ctx.arc(left, top, 6, 0, 2 * Math.PI, false);
  ctx.fillStyle = "gray";
  ctx.fill();
  ctx.lineWidth = 1;
  ctx.strokeStyle = "white";
  ctx.stroke();
}
.controls {
  display: inline-block;
}
<script src="https://unpkg.com/fabric@latest/dist/fabric.js"></script>
<div class="controls">
  <p>
    <button id="add" onclick="Add()">Add a rectangle</button>
  </p>
</div>
<canvas id="c" width="500" height="500" style="border:1px solid #ccc"></canvas>

Unit test code fails by stating UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object in node js with mocha chai

index .js

module.exports = {
  
  addDetails: function() {
    let data =[]
    data.push("one");
    return data
  },

  deleteDetails: function() {
    let data =["one" , "two"]
    data.splice(0 , 1)
    return data
  },

  editDetails: function() {
    let data =["one"]
    data.splice(0 , 1 , "three")
    return data
  },

  updateDetails: function() {
    let data = ["one" , "three"]
    data.splice(1 , 0 , "two")
    return data
  },

  detailsPop: function() {
    let numb = ["one" , "two"]
    numb.pop()
    return numb
  },

  concatData: function() {
    let data1 = ["one"]
    let data2 = ["two"]
    let result = data1.concat(data2)
    return result
  }
 }

indextest.js

var assert = require("assert");
var crud = require('../src/index');

describe('Crud application', ()=>{
    //write your code here
    it('should add "one" to the array', async() => {
      const result = await crud.addDetails();
      assert.deepEqual(result, ['one']);
    });

    it('should delete the first element from the array', async() => {
      const result = await crud.deleteDetails();
      assert.deepEqual(result, ['two']);
      console.log(2)
    });
  
    it('should replace "one" with "three" in the array', async() => {
      const result = await crud.editDetails();
      assert.deepEqual(result, ['three']);
    });
  
    it('should update the array with "two" between "one" and "three"', async() => {
      const result = await crud.updateDetails();
      assert.deepEqual(result, ['one', 'two', 'three']);
    });
  
    it('should remove the last element from the array', async() => {
      const result = await crud.detailsPop();
      assert.deepEqual(result, ['one']);
    });
  
    it('should concatenate two arrays', async() => {
      const result = await crud.concatData();
      assert.deepEqual(result, ['one', 'two']);
    });
    it("Don't remove this dummy test case as its required for validation", async() => {
        const dummy = [{}];
        dummy.should.have.length(1);
    });
});
mocha --timeout 10000 --reporter mocha-junit-reporter --collectCoverageFrom=src/index.js --exit

The test code always fails by saying

mocha --timeout 10000 --reporter mocha-junit-reporter --collectCoverageFrom=src/index.js --exit

Error :

(node:2059) UnhandledPromiseRejectionWarning: TypeError: Cannot
convert undefined or null to object

v-slot is not compatible with nuxt version 3

Before, I coded nuxt beta + used vuetify’s UI.
This is my custom text-field component

<script setup lang="ts">
</script>

<template>
   <v-text-field class="text-field" v-bind="$attrs" variant="solo">
     <template v-for="(_, name) in $slots" #[name]="slotData">
       <slot :name="name" v-bind="slotData" />
     </template>
   </v-text-field>
</template>

But after I updated the nuxt version to the official nuxt 3 version, it got an error

Element implicitly has an 'any' type because expression of type 'string | number' can't be used to index type 'Readonly<{ message?: ((arg: VMessageSlot) => VNode<RendererNode, RendererElement, { [key: string]: any; }>[]) | undefined; clear?: (() => VNode<...>[]) | undefined; ... 8 more ...; counter?: ((arg: VCounterSlot) => VNode<...>[]) | undefined; }>'.
   No index signature with a parameter of type 'string' was found on type 'Readonly<{ message?: ((arg: VMessageSlot) => VNode<RendererNode, RendererElement, { [key: string]: any; }>[]) | undefined; clear?: (() => VNode<...>[]) | undefined; ... 8 more ...; counter?: ((arg: VCounterSlot) => VNode<...>[]) | undefined; }>'.ts(7053)

in #[name]

Can anyone help me fix this error? Thank you.

Cant get channel with ID – discord.js

//Discord.js 11.6.4 (typescript)

import * as Discord from "discord.js"

const bot = new Discord.Client({
    disableEveryone: true
})

bot.login('token')

//This function get Channel. For send message requires TextChannel.
bot.channels.get('id') //Discord.Channel

//Cache is undefined
bot.channels.cache

//Fetch is undefined
bot.channels.fetch

//Find is undefined :(
bot.channels.find('id')

//Get1, Get2 is undefined
Discord.get(bot.channels.get(), 'id').send()

How to get channel?


//discord.js 11.6.4 (typescript)
let channel: Discord.TextChannel

function sendToDiscord(msg: string): void {
    if (!channel) return
    channel.send(`bot say's: ${msg}`)
}

bot.on('message', (ev) => {
    channel = ev.channel
})

I try this. Its not automatically. Its not for me.

help me please. Its for my project

I use all methods for get channel and send message. All returns message error. I cant install latest aplication version must be [email protected]

I use ts to js compilator