Attempted to assign to readonly property Error when using redux

my slice and reducer :

import { createSlice } from '@reduxjs/toolkit'

export const TransactionsListSlice = createSlice({
  name: 'transactions_list',
  initialState: {
    value: []
  },
  reducers: {
    saveTransactionsList: (state, action) => {
      state.value = action.payload
    }
  }
})

export const { saveTransactionsList } = TransactionsListSlice.actions

export default TransactionsListSlice.reducer
let transactions_list = useSelector(state => state.transactions_list.value);

when trying to update my transactions_list with new data i have the below error:
Attempted to assign to readonly property.what is wrong?

Shortkey doesn’t work when v-textarea is focused

I have a small problem. The shortkey (plugin) cannot be executed on the buttons once textarea has focus.

… => Non-relevant content

<template>
    <div>
        <v-textarea ... />
        <div>
            <v-btn
             v-shortkey="['esc']"
             @shortkey="abort"
            >
            ...
            </v-btn>
             <v-btn
              v-shortcut="['alt', 'enter']"
              @shortkey="confirm"
             >
             </v-btn>
        </div>
    </div>
</template>
<script>
    methods: {
        abort() {
            console.log('aborted')
        }

        confirm() {
            console.log('confirmed')
        }
    }
</script>

Both methods never executed when you are focused. Does anybody have a solution?

I want to execute confirm method if you click ‘alt’ and ‘enter’, even focused on textarea.
I want to execute abort method if you click ‘esc’, even focused on textarea.

I’m getting this error: “Cross origin requests are only supported for protocol schemes”

Total error message:
Access to script at ‘file:///C:/Users/sain0/Documents/HTML/Assignmentd/as8.js’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

My HTML Code

I tried sending a list through the files

Exporting

Importing

I got the error, What are the solutions for this error?

I tried using modules and also tried defining module.

How can I fix this error for my discord bot I’m trying to make?

I’m trying to create a discord bot in javascript that plays a specified sound for each specific person that joins the voice channel. Kind of like an intro sound/song thing.

I’m getting this error when I tried to test it out. It outputs this in the terminal when I join the voice channel and the bot doesn’t join the voice channel to play the sound.

PS C:javacodeDiscord Audio Bot> node Audio.js
On
C:javacodeDiscord Audio BotAudio.js:29
  } else if (newState.channel.members.size = 1) {
                              ^

TypeError: Cannot read properties of null (reading 'members')
    at Client.<anonymous> (C:javacodeDiscord Audio BotAudio.js:29:31)
    at Client.emit (node:events:513:28)
    at VoiceStateUpdate.handle (C:javacodeDiscord Audio Botnode_modulesdiscord.jssrcclientactionsVoiceStateUpdate.js:38:14)
    at module.exports [as VOICE_STATE_UPDATE] (C:javacodeDiscord Audio Botnode_modulesdiscord.jssrcclientwebsockethandlersVOICE_STATE_UPDATE.js:4:35)
    at WebSocketManager.handlePacket (C:javacodeDiscord Audio Botnode_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:352:31)
    at WebSocketShard.onPacket (C:javacodeDiscord Audio Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:489:22)
    at WebSocketShard.onMessage (C:javacodeDiscord Audio Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:328:10)
    at callListener (C:javacodeDiscord Audio Botnode_moduleswslibevent-target.js:290:14)
    at WebSocket.onMessage (C:javacodeDiscord Audio Botnode_moduleswslibevent-target.js:209:9)
    at WebSocket.emit (node:events:513:28)

This is my code below. Also, how would I go about doing this so that each user has their own different sound?

console.log('On');
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.GuildVoiceStates,
    GatewayIntentBits.GuildMembers
  ]

});

client.on('voiceStateUpdate', (_oldState, newState) => {
  // Check if the user who joined is the specific user we want
  if (newState.member.id === 'STtheGamer') {
      // Check if the user joined a voice channel
      if (newState.channel) {
          // Join the voice channel and play the specific sound
          newState.channel.join()
              .then(connection => {
                  // Replace 'song.mp3' with the path to the audio file you want to play
                  const dispatcher = connection.play('C:UsersstorrMusicbotsoundsswtheme.mp3');

                  // Leave the voice channel after the sound is played
                  dispatcher.on('finish', () => {
                      newState.channel.leave();
                  });
              })
              .catch(console.error);
      }
  } else if (newState.channel.members.size = 1) {
      if (newState.channel) {
          newState.channel.leave()
              .catch(console.error);
      }
  }

});

  client.login('botkey here');

Javascript Tic Tac Toe doesn’t work at all

I’m new to JavaScript and I’m trying to make a tic tac toe game, but it’s not even doing anything, and I don’t know why. I tried to find solution, but I couldn’t.

I tried changing the content in “cellItems.forEach” in several ways but it didn’t work out.

const cellItems = document.querySelectorAll('.cell');

const winner = document.getElementById("winner");
let nextTurn = false;

let winningConditions = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
];

cellItems.forEach(cell => {
  cell.addEventListener('click', function() {
    turn(cell)
    checkWin();
  }, {
    once: true
  });
});

function turn() {
  if (nextTurn === false) {
    cell = 'X';
    nextTurn = true;
  } else if (nextTurn === true) {
    cell = 'O';
    nextTurn = false;
  }
};

function checkWin() {
  for (let winCondition of winningConditions) {
    if (winCondition.every(i => cellItems[i].innerHTML == "X")) {
      winner.innerHTML = "X won";
    } else if (winCondition.every(i => cellItems[i].innerHTML == "O")) {
      winner.innerHTML = "O won";
    } else {
      winner.innerHTML = "DRAW";
    }
  }
};

CANVAS: It is not possible to completely delete arc if using ctx.globalCompositeOperation

First, I draw an arc with diameter at any position. I would then delete a circular area in another position so that it could cut the first arc, using ctx.globalCompositeOperation = ‘destination-out’ and draw an arc and then set ctx.globalCompositeOperation = ‘source- over’. I’ll end up drawing a similar arc at the exact spot I just deleted.
Its two func i used to:

const eraseDot = (ctx, { x, y, size }) => {
    ctx.globalCompositeOperation = 'destination-out';
    drawDot(ctx, { x, y, size:size+1, color: 'white' });
    ctx.globalCompositeOperation = 'source-over';
}
const drawDot = (ctx, { x, y, size, color }) => {
    ctx.beginPath();
    ctx.arc(x, y, size / 2, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fillStyle = color;
    ctx.fill();
};

My desired result is to draw 2 intersecting arcs (like how to draw 2 normal arcs but I want to clear the image area before drawing the 2nd arc). But it appears that there is a gap between the intersection of the 2 arcs:
enter image description here

this means different erase and draw area sizes. please tell me the reason of this and how to solve it , thanks :

callback function in factory function [duplicate]

I’m trying to write a code that iterates through an array. If a callback function is passed as an argument the item should be passed as an argument to the callback function. If no callback function is called, the function should return items in an array.

const myFunction = (callback) => {
    let array = [1,2,3,4];
    let result = [];
    for(let i in array){
        callback ? callback(i) : result.unshift(array[i]);
    }
    return {result, callback}
}

const print = (val) => {
    console.log(val)
}

myFunction(print())

but what I get in the console is this: undefined.
So, my question is, why is callback undefined? and how can I solve this problem?

Error handling Karate — jbang.exec() (Node-npm)

I have a question here, that we are presenting in our project.

We need to be able to control when KARATE gives an OK or a KO, right now this function always returns 0 regardless of whether a test fails or not..

KARATE OUT

This is a function:

karate.executable = function () {
    let prefix = karate.config.dir ? '-Dkarate.config.dir=' + karate.config.dir + ' '  : '';
    return prefix + 'com.intuit.karate:karate-core:' + karate.version + ':all';
};
karate.exec = function (args) {
    if (!args) {
        var args = process.argv.slice(2).join(' ');
        console.log("ARGUMENT " + args)
    }
    process.env['KARATE_META'] = 'npm:' + process.env.npm_package_version;
    var error = jbang.exec(karate.executable() + ' ' + args);
    console.log("OUT " + error)
};
module.exports = karate;

I tried modifying the function, but it generates errors

I expect karate.exec to return a 1 if the test fails and a 0 if everything goes OK

Dynamic routing in ASP .NET Core based on data received from frontend

I am working on CMS which contains many domains (so our URLs can look like www.example.com/group or www.example.com/de). I want to make a call from frontend based on current domain:

window.addEventListener('CookiebotOnAccept', (e) => {
    const domain = window.location.pathname.replace(/^/([^/]*).*$/, '$1');
    const URL = `${window.location.protocol}//${window.location.host}//${domain}/UpdateCookies`;
    console.log(domain)
    fetch(URL, {credentials: 'include'})
    .then((response) => {
        if (!response.ok) {
            throw new Error("Cookie consent update was not succesful")
        }
    })
    .catch((error) => {
        console.error('There has been a problem with your fetch operation: ', error)
    })
}, false)

…and then I need to be able to send it to a endpoint in the backend, which needs to have a dynamic routing based on domain it currently receives request from.
Backend endpoint:

[Route("CookieHandler")]
    public class CookieHandlerController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICookieService _cookieService;

        public CookieHandlerController(IHttpContextAccessor httpContextAccessor, ICookieService cookieService)
        {
            _httpContextAccessor = httpContextAccessor;
            _cookieService = cookieService;
        }

        [HttpGet]
        [Route("UpdateCookies")]
        public IActionResult UpdateCookies()
        {
            var requestCookies = _httpContextAccessor.HttpContext?.Request.Cookies;

            foreach (var cookie in requestCookies)
            {
                    _cookieService.UpdateCookiesAccordingToConsent(cookie.Key);
            }

            return Ok();
        }
    }

So, basically the endpoint routing needs to look like this:

www.example.com/group/updatecookies

or

www.example.com/fr/updatecookies

The reason for such strange setup is because there are some Http-only cookies which have their specific path value based on their domain.

creating HTML webpage with basic input text area from node application

I created a simple 3 card poker game that takes in user input and determines a winner via command line using node JS. I need to convert it into a webpage where a user can input info and it will return the winner. I don’t know how to go about this… below is my script.JS file

I expected to be able to just write it and connect it but I have tried a few things but i’m just a bit confused on how to accomplish that given what i’ve written

Here is my JS

import Hand from "./hand.js";
import prompt from "prompt-sync";

const players = prompt()("How many players?");
// // console.log(`Hey there ${players}`);
const numberOfPlayers = Number(players);

//aggregate user input
let userInput = [];

for (let i = 0; i < numberOfPlayers; i++) {
  const newPrompt = prompt()(`${i} `);
  userInput.push(newPrompt);
}

let hands = userInput.map((val, i) => new Hand(val, i));

hands.sort((a, b) => b.value - a.value);

let winners = [hands[0].order];
let winningValue = hands[0].value;
for (let i = 1; i < hands.length; i++) {
  if (hands[i].value == winningValue) {
    winners.push(hands[i].order);
  } else {
    break;
  }
}

console.log(winners.join(", "));

And here is my hand.JS file…

const SUITS = ["h", "s", "d", "c"];
const RANKS = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"];

const RANK_TO_VALUE = {
  2: 2,
  3: 3,
  4: 4,
  5: 5,
  6: 6,
  7: 7,
  8: 8,
  9: 9,
  T: 10,
  J: 10,
  Q: 10,
  K: 10,
  A: 11,
};

//fresh card Hand
export default class Hand {
  constructor(cards = "", order = 0) {
    this.cards = cards.split(" ").map((c) => new Card(c));
    this.value = this.getHandValue();
    this.order = order;
  }
  //straight flush outcome
  hasStraightFlush() {
    return 100000 * (this.hasStraight() && this.hasFlush());
  }
  //three of a kind outcome
  hasThreeOfKind() {
    return (
      10000 *
      (this.cards[0].rank == this.cards[1].rank &&
        this.cards[2].rank == this.cards[1].rank)
    );
  }
  //straight outcome
  hasStraight() {
    let ranks = this.cards.map((c) => c.order);
    ranks.sort();

    return 1000 * (ranks[0] + 2 == ranks[1] + 1 && ranks[1] + 1 == ranks[2]);
  }
  //flush outcome
  hasFlush() {
    return (
      100 *
      (this.cards[0].suit == this.cards[1].suit &&
        this.cards[2].suit == this.cards[1].suit)
    );
  }
  //pair outcome
  hasPair() {
    return (
      20 *
      ((this.cards[0].rank == this.cards[1].rank ||
        this.cards[2].rank == this.cards[1].rank) &&
        !(
          this.cards[0].rank == this.cards[1].rank &&
          this.cards[2].rank == this.cards[1].rank
        ))
    );
  }
  //high card outcome
  hasHighCard() {
    const vals = this.cards.map((c) => c.value);
    vals.sort((a, b) => a - b);
    return vals[vals.length - 1];
  }

  getHandValue() {
    return Math.max(
      this.hasStraightFlush(),
      this.hasThreeOfKind(),
      this.hasFlush(),
      this.hasStraight(),
      this.hasPair(),
      this.hasHighCard()
    );
  }
}

//creates cards with suits and ranks
class Card {
  constructor(input) {
    this.suit = input.charAt(1);
    this.rank = input.charAt(0);
    this.value = RANK_TO_VALUE[this.rank];
    this.order = RANKS.indexOf(this.rank);
  }

  // constructor(suit, rank) {
  //     this.suit = suit
  //     this.rank = rank
  // }
}

//array of 52 cards as one thanks to flatmap
function freshHand() {
  return SUITS.flatMap((suit) => {
    return RANKS.map((rank) => {
      return new Card(suit, rank);
    });
  });
}

Testing the function in typescript

Hi all i am very new to typescript i have written test cases for the routes in my project

My route.test.ts file

import request from "supertest";
import { app} from "../..";

describe('Virtual Class test',()=>{

    //getting the student with valid id's
    describe('get student',()=>{
        it('it should return student link based on id',async()=>{
            const res=await request(app).get('/api/v1/virtual_class/student?meetingId=12316sa&contactId=0037200000AxrvUAAR');
            expect(res.statusCode).toBe(200)
            
        })
    })

    //getting the student with invalid id's
    describe('get student',()=>{
        it('it should return student link based on id',async()=>{
            const res=await request(app).get('/api/v1/virtual_class/student?meetingId=12316sa&contactId=003720R');
            expect(res.statusCode).toBe(400)
            
        })
    })

      //if the params are missing
      describe('get student',()=>{
        it('it should return student link based on id',async()=>{
            const res=await request(app).get('/api/v1/virtual_class/student?meetingId=12316sa');
            expect(res.statusCode).toBe(422)
        })
    })

    //If we don't have params to fetch faculty link
    describe('get faculty',()=>{
        it('return the faculty based on data we are passing',async()=>{
            const res=await request(app).post('/api/v1/virtual_class/faculty').send({
                redirectUrl: "redirectUrl",
                meetingId: "meetingId",
                meetingName: "meetingName",
                fullName: "fullName",
                contactId: "contactId",
            })
            expect(res.statusCode).toBe(422)
        })
    })


     //get faculty link by passing params
     describe('get faculty',()=>{
        it('return the faculty based on data we are passing',async()=>{
            const res=await request(app).post('/api/v1/virtual_class/faculty').send({
                redirectUrl: "redirectUrl",
                meetingId: "meetingId",
                meetingName: "meetingName",
                fullName: "fullName",
                contactId: "contactId",
                email: "email",
                courseOfferingId: "courseOfferingId",
                startTime: "startTime",
                endTime: "endTime",
                sessionName: "sessionName",
                date: "date",
                sessionId: "sessionId",
            })
            expect(res.statusCode).toBe(200)
        })
    })
})

This is working as expected but is there any way to test the specific function ,all the exported function from a file

My function
static startAttendance = async (
meetingId: string,
req: express.Request,
res: express.Response
) => {
try {
const config: string = await configHelper.getConfigData();
const data = JSON.parse(config);
const configdata: any = JSON.parse(data);
const channel = configdata.virtualClass;
switch (channel) {
case “zoom”:
zoomHelper.processZoomMeeting(req, res);
break;
case “bbb”:
bbbHelper.startBBBAttendance(meetingId);
break;
case “meet”:
meetHelper.generateMeetingLink(req, res);
break;
default:
break;
}
} catch (err) {
console.log(“Error in Start Attendence”, err);
}
};

May be similiar to the function on the top

responsive image with mouse parallax

i have coded in, 3 layers of image with a mouse parallax effect, on full screen the image seems fine, but if i resize the window everything would crumble appart.

`


<!DOCTYPE html>

<html>
  <head>
    <link rel="stylesheet" href="css.css"/>
    <title>Document</title>
  </head>
  <body>
    <section id="main">
      <img src="canyon 3.png"  class="layer" id="c3" value="5" />
      <img src="canyon 2.png" class="layer" id="c2" value="10" />
      <h1 class="text" >bla bla bla bla bla bla bla</h1>
      <img src="canyon 1.png" class="layer" id="c1" value="20" />
    </section>
    <script src="js.js"></script>
  </body>
</html>

section{
  width: 100%;
  height:100vh;
  position: relative;
  justify-content: center;
  align-items: center;
  display: flex;
}

section img{
  position: absolute;
  width:100%;
  height:100%;
  object-fit:cover;
}


#c1{
  position: absolute;
  width:140%;
  height:max-content;
  z-index:4;
}

#c2{
  position: absolute;
  left:100px;
  width:100%;
  height:max-content;

  z-index: 2;
}

#c3{
  position: absolute;
  height:max-content;
  z-index: 1;
}

`
i dont really know anything that i ca do to make it responsive.

Cannot use ‘in’ operator to search for ‘elForm’ in undefined” when used with type “datetime”

I am trying to bring up a datepicker with time options from Element UI.
I am facing this error from within ElementUI component. It works if type option is set as date and throws an error on datetime.
Here is my code and error.

import { cloneDeep } from 'lodash';

export default {
  name: 'actions',
  components: {},
  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      indentData: {
        reported_at: '',
      },
    };
  },
  computed: {
    validToPickerOptions() {
      const endOfDay = new Date(new Date().setHours(23, 59, 59, 999));
      return {
        disabledDate(time) {
          return (time >= endOfDay);
        },
      };
    },
  },
  methods: {
    reportMarkReported() {
      console.log('this.indentData', this.indentData);
      this.$emit('save-report-release', this.indentData);
    },
  },
  created() {
    this.indentData = cloneDeep(this.data);
  },
};
<template>
  <div>
  <div class="action">
    <button @click="reportMarkReported">
      Submit
    </button>
  </div>
  <div>
    <el-date-picker
      v-model="indentData.reported_at"
      type="datetime"
      format="dd MMM 'yy hh:mm A"
      placeholder="Pick a Date"
      size="small"
    />
    </div>
  </div>
</template>

Here is the error I am facing on click on element

vue.esm.js?b66f:1741 TypeError: Cannot use 'in' operator to search for 'elForm' in undefined
    at resolveInject (vue.esm.js?efeb:4649:1)
    at initInjections (vue.esm.js?efeb:4619:1)
    at Vue._init (vue.esm.js?efeb:4710:1)
    at new VueComponent (vue.esm.js?efeb:5836:1)
    at createComponentInstanceForVnode (vue.esm.js?b66f:4310:1)
    at init (vue.esm.js?b66f:4131:1)
    at createComponent (vue.esm.js?b66f:5608:1)
    at createElm (vue.esm.js?b66f:5555:1)
    at createChildren (vue.esm.js?b66f:5682:1)
    at createElm (vue.esm.js?b66f:5584:1)
vue.esm.js?b66f:591 [Vue warn]: Error in nextTick: "TypeError: Cannot read properties of undefined (reading '$el')"
TypeError: Cannot read properties of undefined (reading '$el')
    at Vue.eval (element-ui.common.js?bc95:18396:1)
    at Array.eval (vue.esm.js?b66f:1837:1)
    at flushCallbacks (vue.esm.js?b66f:1758:1)

Why does HTML’s select onchange cause a TypeError on its second change?

This is my first time building a website, so far its almost ready to go, but for some reason when I try to change a dropdown menu to trigger a function, it works as expected on the first time but not the second?

My html code:

<select onchange="list();" id="listSelect">
    <option disabled selected value> -- Select a list -- </option>
    <option value="list1">Item 1</option>
    <option value="list2">Item 2</option>
</select>
    
<p id="randomItem">(choose a list first)</p>
    
<iframe id="list" src="(REDACTED)"></iframe>

And my javascript code:

async function list() {
    list = document.getElementById("listSelect").value;
    if (list.length == 0) {
        alert("You need to choose a list first!");
        return;
    }
    document.getElementById('list').src="(REDACTED)" + list;
    randomItem();
}

async function randomItem() {
    list = document.getElementById("listSelect").value;
    if (list.length == 0) {
        alert("You need to choose a list first!");
        return;
    }
    const response = await fetch("(REDACTED)" + list, {
        method: 'GET',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer',
    });
    const json = await response.json();
    var item = json[Math.floor(Math.random()*json.length)];
    document.getElementById("randomItem").innerHTML = item;
}

Expected outcome: When the select menu’s value has changed, it will update the iframe “list” and update the p “randomItem”
Actual outcome: Expected outcome occurs on the first time the value changes, but throws

Uncaught TypeError: list is not a function
at HTMLSelectElement.onchange ((index):23:50)
onchange @ (index):23

in the console on each consecutive attempt.