console not logging post example

view html page, where i want to add functionality to add list

 <div class="centered-content">
    <div class="task-manager-container">
        <div class="sidebar">
            <h1 class="title has-text-primary">
                Lists
            </h1>

            <div class="list-menu">
                <a class="list-menu-item">
                    <p>List 1#</p>
                </a>
                <a class="list-menu-item">
                    <p>List 2#</p>
                </a>
                <a class="list-menu-item">
                    <p>List 3#</p>
                </a>
            </div>

            <button class="button is-primary" (click)="createNewList()">+ New List</button>
        </div>
        <div class="task-list-container has-background-light">
            <h1 class="title has-text-primary">
                Tasks
            </h1>

            <div class="task">
                <p>This is something i have to do :) </p>
            </div>
            <div class="task">
                <p>This is something i have to do :) </p>
            </div>
            <div class="task complete">
                <p>This is something i have to do :) </p>
            </div>

        </div>
    </div>
</div>

this createNewList method is in task-service as:

   import { Injectable } from '@angular/core';
import { WebRequestService } from './web-request.service';

@Injectable({
  providedIn: 'root'
})
export class TaskService {

  constructor(private webReqService: WebRequestService) { }

  createList(title: string) {
    return this.webReqService.post('lists', { title });

  }
}

this is method in task-view-component.ts

import { Component, OnInit } from '@angular/core';

import { TaskService } from 'src/app/task.service';

@Component({
  selector: 'app-task-view',
  templateUrl: './task-view.component.html',
  styleUrls: ['./task-view.component.scss']
})
export class TaskViewComponent implements OnInit {

  constructor(private taskService: TaskService) { }

  ngOnInit(): void {
  }

  createNewList() {
    this.taskService.createList('Testing').subscribe( (response: any) => {
      console.log(response);
    })

  }
}

i imported httpClientModule in app.module, and the console is not logging ANYTHING (not even 404 or any error…) “Testing” which should be the body (title) of my task.
if you need any additional info to help me please say so… thank you for all of your help!

also this is in web-request-service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WebRequestService {

  readonly ROOT_URL;

  constructor( private http: HttpClient) { 
    this.ROOT_URL = 'http://localhost:3000';
  }

  get(uri: string) {
   return this.http.get(`${this.ROOT_URL}/${uri}`);
  }

  post(uri: string, payload: Object) {
    return this.http.post(`${this.ROOT_URL}/${uri}`, payload);
  }

  patch(uri: string, payload: Object) {
    return this.http.patch(`${this.ROOT_URL}/${uri}`, payload);
  }

  delete(uri: string) {
    return this.http.delete(`${this.ROOT_URL}/${uri}`);
  }
}

TypeError: member.roles.add is not a function

I’m working on a bot that needs to check some things before giving/removing a role from a user, but for some reason, the .has(), .some(), .add() and, .remove() functions don’t work.

Here’s my code:

const Permissions = require('discord.js');

function isAdmin(member) {
    return member.permissions.has(Permissions.FLAGS.ADMINISTRATOR);
}

function hasRole(member, roleID) {
    return member.roles.some(role => role.id === roleID);
}

function giveRole(member, role) {
    member.roles.add(role)
}

function removeRole(member, role) {
    member.roles.remove(role);
}

Here’s the full error that I get:

TypeError: member.roles.add is not a function
    at Object.giveRole (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTutil.js:101:30)
    at Object.buttonClicked (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTcommandsbuttonRoleexecute.js:23:14)
    at WebSocketManager.<anonymous> (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTindex.js:101:28)
    at WebSocketManager.emit (node:events:390:28)
    at WebSocketShard.onMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:300:54)
    at WebSocket.onMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibevent-target.js:199:18)
    at WebSocket.emit (node:events:390:28)
    at Receiver.receiverOnMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibwebsocket.js:1137:20)
    at Receiver.emit (node:events:390:28)
    at Receiver.dataMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:528:14)
    at Receiver.getData (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:446:17)
    at Receiver.startLoop (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:148:22)
    at Receiver._write (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:83:10)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Receiver.Writable.write (node:internal/streams/writable:334:10)
    at TLSSocket.socketOnData (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibwebsocket.js:1231:35)
    at TLSSocket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10)
    at TLSWrap.onStreamRead (node:internal/stream_base_commons:199:23)

How to make js function delete one element from array and add another instead?

so I want to make JS function, that adds random string from my array to HTML, then remove it and add another instead of it. My code now does everything I want to, it just doesn’t remove past element and adds another one instead.

In other words – I just want a simple text slide.

MY HTML:

 <section style="height: 100vh;" class="">
      <div class="container pt-2 pb-2">
        <div class="row">
          <div class="col d-flex justify-content-center text-uppercase">
            <div>
              <h1>
                Mes teikiame
              </h1>
                <div class="scroller">
                  <span>
                  </span>
                </div>
              <h1>
                Paslaugas
              </h1>
            </div>
          </div>
        </div>
      </div>
    </section>

MY JS:

// Selecting elements
let scrollerSpan = document.querySelector('.scroller > span')
// Creating elements
let textInsideScroller = document.createElement('span')
// Class add
textInsideScroller.classList.add('text-inside-scroller')

// Function generating service name in random order for scroller
const dynamicServiceNames = () => {
    const serviceNames = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6', 'example7'];
    const randomName = serviceNames[rand(0, serviceNames.length)];
    textInsideScroller.append(randomName)
    scrollerSpan.append(textInsideScroller)    
};


// Executing my function

let i = 1;
setInterval(function()
{
    dynamicServiceNames(i++);
}, 1000)

UPDATE:
Tried to solve this issue by adding this to the function:

// Function generating service name in random order for scroller
const dynamicServiceNames = () => {
    const serviceNames = ['grožio', 'voljerų gaminimo', 'apskaitos priežiūros', 'kasinėjimo', 'metinių ataskaitų teikimo', 'deklaracijų ruošimo', 'barščių virimo'];
    const randomName = serviceNames[rand(0, serviceNames.length)];
    textInsideScroller.append(randomName)

    if (scrollerSpan.contains(textInsideScroller)){
        scrollerSpan.remove(textInsideScroller)
    }
    else{
    scrollerSpan.append(textInsideScroller)
    }
    
};

But this didn’t helped. Now the random string comes from array, but only one time — I need to refresh the page in order to get another random string….

javascript: Create variables/const for all elements in qureySelectorAll

I’m trying to querySelectorAll a bunch of things in my HTML document.
I then want to create a variable for each of them.

Individually, I would do the following to establish it, and then update it.

const workersOutput = document.getElementById('workersOutput');
workersOutput.textContent = `${workers}`;

This is really messy though when I’ll have many of these to do.

Using querySelectorAll, I can make some hybrid version, but it’s not exactly readable or easy to use.

const outputs = document.querySelectorAll('.output');
outputs[2].textContent = `${workers}`;

Couldn’t I use maybe forEach to create a variable using the ID or something along the lines of (I know that’s not how that works, but I want to get the idea across:

const outputs = document.querySelectorAll('.output');

outputs.forEach((output) => {
    const outputs[2] = document.getElementById(output.id);
});

I could also be way off on how to accomplish this the “right way”, I’m newish to coding.

Capture payment method used to pay with PayPal Checkout/Orders API

I’m using the Standard Integration of PayPal Checkout (via the Orders API), and want to capture the actual payment method – which I believe PayPal calls a “funding source” – that the customer paid with, so that I can pass this value to my server and persist it to my database.

What API object do I need to call to get this information?

How to add object with relationship in the DB with redux

I have a billingCycle object with have a list of credits and debts objects that the state would looks like this:

billingCycle: {
  id: 1,
  name: 'March',
  month: 3,
  year: 2022,
  credits: [
    {
      id: 1,
      name: 'Salary',
      value: 3700
    }
  ],
  debts: [
    {
      id: 1,
      name: 'Car fix',
      value: 450
    }
  ]
 }

But I read in Redux docs that this is a bad practice and it’s recommended to use normalized states. So my reducers looks like this:

const INITIAL_STATE = { list: [], billingCycle: {}, credits: [], debts: [] };


export default function (state = INITIAL_STATE, action) {
  switch (action.type) {
    case "BILLING_CYCLES_FETCHED":
      return { ...state, list: action.payload };
    case "BILLING_CYCLES_CREATED":
      return { ...state, billingCycle: action.payload };
    case "BILLING_CYCLES_READED":
      return { ...state, billingCycle: action.payload };
    case "BILLING_CYCLES_UPDATED":
      return { ...state };
    case "BILLING_CYCLES_REMOVED":
      return { ...state };
    case "CREDIT_ADDED":
      return { ...state, credits: state.credits.concat(action.payload) };
    case "CREDIT_REMOVED":
      return { ...state, credits: state.credits.splice(action.payload, 1) };
    case "DEBT_ADDED":
      return { ...state, debts: state.debts.concat(action.payload) };
    case "DEBT_REMOVED":
      return { ...state, debts: state.debts.splice(action.payload, 1) };
    case "RETURN_STATE":
      return { ...state };
    default:
      return state;
  }
}

And this is my create action:

export function create(billingCycle) {
  axios.post(`${BASE_URL}/billingCycles`, billingCycle);
  return {
    type: "BILLING_CYCLES_CREATED",
    payload: billingCycle
  };
}

My question is: how can I send a billingCycle object to the API call with credits and debts with it? The create method only add the billingCycle without it. How can I map the respective objects related with it to the object? Where in my code I do this integration?

Unexpected token when running grunt build

I’m trying to execute the following command grunt build but when trying it the below error message appear

PS C:UsersEDMADocumentsTutenlabsBitbuckettuten-macarena-backoffice-web> grunt build
C:UsersEDMAAppDataRoamingnvmv6.16.0node_modulesgrunt-clinode_modulesmicromatchindex.js:44
    let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
                                                   ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:UsersEDMAAppDataRoamingnvmv6.16.0node_modulesgrunt-clinode_modulesfindup-syncindex.js:12:10)

I navigate to C:UsersEDMAAppDataRoamingnvmv6.16.0node_modulesgrunt-clinode_modulesmicromatchindex.js:44 path and looked for index.js file to check whether there’s an error or not, but the strange thing is there isn’t. Any idea what’s going on here?

Aditionally, this is AngularJS.

Use async iterator to a custom function that calls next

What I want to do is to create an iterator, which is only triggered when an external function is called, say an external event.

function createIteratorWithFunction() {
  var thingThatResolves;
  var asyncIterable = {
    thingThatResolves,
    [Symbol.asyncIterator]() {
      return {
        next() {
          return (new Promise((resolve, reject) => asyncIterable.thingThatResolves = (resolve))).then(_ => ({
            value: _,
            done: false
          }));

        },
        return () {
          return {
            done: true
          }
        }
      };
    }
  };
  return asyncIterable;

}

iter = createIteratorWithFunction();
(async function() {
  for await (let val of iter) {
    console.log(val);
  }
})()
<button onclick="iter.thingThatResolves('execute');iter.thingThatResolves(3)">execute next!</button>

As you can see, it only resolves ‘execute’, but not 3, of course because promises can’t be resolved more than once, and it only is updated asynchronously, I understand this, but since the iterator is async, how would I create a queue, so that any values that could’ve synchronously been triggered are called by next(), as well?

“DiscordAPIError: Unknown interaction” after a few button press

So i have a bot with one single command “/fight” and it take in another user as it argument. If you run that command it will prompt the user in that command I will call it “player 2” or “p2” for short to press a button attach to the reply the bot send to accept to fight player 1 or p1 (The person who call the command). I need p2 to press the button cus I need that player interaction to be able to send 2 hidden message. So I do all that in this code:

const p1Interaction = interaction // getting p1 interaction
var p2User = options.getUser("player")
var p2Interaction
const button = new MessageActionRow().addComponents(
    new MessageButton()
        .setCustomId("fight_accept")
        .setStyle("SUCCESS")
        .setLabel("Accept")
)

const Player2Filter = (i) => { return i.user.id === p2User.id }

// send the broad message with the accept button
const broadMessage = await interaction.reply({
    content: `<@${p2User.id}> Please press accept to start the fight`,
    components: [button],
    fetchReply: true
})

// getting the button press and turn that interaction into p2 interaction
await broadMessage.awaitMessageComponent({ filter: Player2Filter, componentType: "BUTTON", max: 1, time: 60000, errors: ['time'], })
    .then(async i => {
        p2Interaction = i
    })
    .catch(collected => {
        console.log("Error")
    })
So after getting p1Interaction and p2Interaction, the bot send 2 hidden message to both of them and this message is call the control panel for them to input stuff to use the bot. And it look like this:

const p1ControlPanelMessage = await p1Interaction.followUp({
    embeds: [controlPanelEmbed],
    ephemeral: true,
    components: [controlPanelActionRow1, controlPanelActionRow2]
})

const p2ControlPanelMessage = await p2Interaction.reply({
    embeds: [controlPanelEmbed
        .setColor("RED")],
    ephemeral: true,
    components: [controlPanelActionRow1, controlPanelActionRow2],
    fetchReply: true
})

The controlPanelActionRow1 ,controlPanelActionRow2 and controlPanelEmbed are define earlier and removed for abbreviation sake. So after that it define some more variable to be use for handling the game. Then came a while loop, this while is the main game loop and to handle most of the game stuff. So at the start of this while loop it check who turn it is and set some variables accordingly so here the code for that:

while (broadManager.scale < 5 && broadManager.scale > -5) {
    if (broadManager.isP1Turn) {
        controlPanelMessage = p1ControlPanelMessage
        currentPlayer = player1
        currentUsername = p1Interaction.user.username
        currentRow = 1
        currentPlayer.boneToken += 100
    } else {
        controlPanelMessage = p2ControlPanelMessage
        currentPlayer = player2
        currentUsername = p2Interaction.user.username
        currentRow = 0
    }

BroadManager and Player are just object to help me handle the game and it just this.

// blank() is a function that I use to construct blank spaces on the broad
class BroadManager {
    constructor () {
        this.isP1Turn = true
        this.broad = [
            [blank(), blank(), blank(), blank()],
            [blank(), blank(), blank(), blank()],
        ]
        this.scale = 0
    }
}

//Player
class Player {
    constructor (userID = 0, deck = []) {
        this.userID = userID
        this.deck = deck
        this.boneToken = 0
        this.sacMade = 0
        this.misplay = 0
        this.hand = []
        for (let i = 0; i < 4; i++) {
            const c = choices(deck)[0]
            this.hand.push(c)
            this.deck.splice(deck.indexOf(c), 1)
        }
    }
}

After that it take button press from the corresponding player control panel like this.

await controlPanelMessage.awaitMessageComponent({ filter, componentType: "BUTTON", max: 1, time: 3600000, errors: ['time'], })
    .then(async i => {
        int = i // setting this to a variable so I can use it later
        state = i.customId
    })
    .catch(collected => {
        console.log("Error")
    })

So then it go into an if tree (ik it bad but I only have like 4 commands) I will only focus on what branch of that if tree broken rn so let see. It use to placing card down onto the broad. So first it scan the player hand and remove all the duplicate card then add all of those card on an actionRow as button:

// make an action row to attach to message
playCardActionRow = new MessageActionRow()

// cycling through the player hand and remove all duplicate card
var handNoDup = []
currentPlayer.hand.forEach((card) => {
    var item = [card.name, card.portrait]
    var flag = false

    handNoDup.forEach((i) => {
        if (i.join("") == item.join("")) {
            flag = true
        }
    })

    if (!flag) {
        handNoDup.push(item)
    }
})


// then add them to the action row as button for the user to press
handNoDup.forEach((card) => {
    playCardActionRow.addComponents(
        new MessageButton()
            .setStyle("SECONDARY")
            .setCustomId(`fight_play_select_${card[0].toLowerCase()}`)
            .setLabel(`Play ${card[0]}`)
            .setEmoji(card[1])
    )
})

// adding a cancel button
playCardActionRow.addComponents(
    new MessageButton()
        .setStyle("DANGER")
        .setCustomId("fight_play_cancel")
        .setLabel("Cancel")
)

// sending the message to get user input on what card should be place
const cardSelectionMessage = await int.reply({
    content: "Which card do you want to play",
    components: [playCardActionRow],
    fetchReply: true
})

then ofc it will listen for button press using this:

var cardToPlace
var temp
var flag = false

// actually getting the player input and turn it into a cardName
await cardSelectionMessage.awaitMessageComponent({ filter, componentType: "BUTTON", max: 1, time: 60000, errors: ['time'], })
    .then(async i => {
        temp = i
        if (!(i.customId === "fight_play_cancel")) {
            cardToPlace = i.customId.substr(18)
        } else {
            flag = true
        }
    })
    .catch(collected => {
        console.log("Error")
    })

the flag use for canceling the interaction using a continue statement to get out of the if statement and go back to the start of the while loop. Because in my game there a cost to summoning card and those are blood and bone so there some check for that here for the blood cost:

if (getCardByName(cardToPlace).bloodCost > 0) {
    console.log("doing blood cost")
    sacCardActionRow = new MessageActionRow() 
    //there code here for adding 4 option with value from "0" to "3"
    //remove to shorten this code block
    
    //ofc sending a message to get user input
    const sacSelectionMessage = await temp.update({
        content:
            `This card need ${getCardByName(cardToPlace).bloodCost} sacrifice.n` +
            `Please select ${getCardByName(cardToPlace).bloodCost} column to sacrifice creature from`,
        ephemeral: true,
        components: [sacCardActionRow],
        fetchReply: true
    })
    
    //getting the input
    await sacSelectionMessage.awaitMessageComponent({ filter, componentType: "SELECT_MENU", max: 2, time: 60000, errors: ['time'], })
        .then(async i => {
            temp = i
            if (i.customId === "fight_play_select_column_sac") {
                i.values.forEach((t) => {
                    sacCol.push(parseInt(t))
                })
            }
        })
        .catch(collected => {
            console.log(collected)
        })
    
    //make sure user can't sacrifice blank space and break out of to the while loop
//if that the case
    let flag = true
    sacCol.forEach((col) => {
        if (broadManager.broad[currentRow][col].id == blankId) {
            flag = false
        }
    })

    if (!flag) {
        temp.update({
            content:
                "You can't sacrifice a blank space. Please press the play card button again from the Control Paneln" +
                "You can now dismiss this message",
            components: []
        })
        continue
    }

and here for bone cost which is much simpler:

if (getCardByName(cardToPlace).boneCost > 0) {
    if (currentPlayer.boneToken >= getCardByName(cardToPlace).boneCost) {
        useBone = true
    } else {
        await temp.update({
            content:
                "You don't have enough bone token to play this card. Please press the play card button again from the Control Paneln" +
                "You can now dismiss this message",
            components: []
        })
        continue
    }
}

useBone and sacCol are just a bool and a list so that I can use them later. Then it let the player choose a column to play the card onto. So here taht code

colSelectionActionRow = new MessageActionRow().addComponents(
    //adding 4 option with value from "0" to "3"
    //removed to make the code block shorter
)
console.log("message")

// sending the column selection message
const colSelectionMessage = await temp.update({
    content: "Which column do you want to play it in",
    components: [colSelectionActionRow],
    fetchReply: true
})

// taking user input and turn it into useable shit
var placeCol

await colSelectionMessage.awaitMessageComponent({ filter, componentType: "SELECT_MENU", max: 1, time: 60000, errors: ['time'], })
    .then(async i => {
        temp = i
        if (i.customId === "fight_play_select_column") {
            placeCol = parseInt(i.values)
        }
    })
    .catch(collected => {
        console.log(collected)
    })
Then it do some final calculation and place the card down.

if (broadManager.broad[currentRow][placeCol].id != blankId && !sacCol.includes(placeCol)) {
    temp.update({
        content:
            "You can't play that card here, there another card in it place. Please press the play card button again from the Control Paneln" +
            "You can now dismiss this message",
        components: []
    })
    continue
}

//killing all sacrifice card
sacCol.forEach((col) => {
    broadManager.killCard(col, currentRow, currentPlayer)
    //increasing the sacMade stat
    currentPlayer.sacMade++
    currentPlayer.boneToken++
})

if (useBone) {
    currentPlayer.boneToken -= getCardByName(cardToPlace).boneCost
}

//placing the card down
broadManager.placeCard(placeCol, currentRow, cardToPlace)


//send an message to tell the player it done
temp.update({
    content:
        "The card has been place you can now dismiss all messages that have been send to you during this placement process. But not the control panel message of course." +
        "You can now also dismiss this message. The broad also get updated check it out!",
    components: []
})

So that all of my code now let get to the problem. So after placing down 2-3 card the bot starting to slow down and after the 4/5th card it just crash saying this in the log DiscordAPIError: Unknown interaction on line 537 which is this line:

const colSelectionMessage = await temp.update({
    content: "Which column do you want to play it in",
    components: [colSelectionActionRow],
    fetchReply: true
})

Saying that temp is an unknown interaction. idk what wrong, it can this for 4 times in a row then it just crash on the 5th time. No time isn’t an issue cus i try running this using a different button that just a blank button and pressing it for hour and the bot still work just fine. Here all of my code in this github repo. Just create bot application and use this code, if you want to reproduce the bug and get some more info.

If you need more info just dm me (khanhFG#3753) or comment, I will try my best to reply asap. Sorry for some broken English if there any in the question.

How do I make a pagination using existing buttons?

I have a blog page on my website. I took the template from the internet, but I don’t think there’s a javascript for the pagination buttons. Do I need to just make a separate page and link to the buttons?

I want to make sure that I’m doing it in the most efficient way. If it’s not best to create a new page and link it to the numbers and next button, then I would need some guidance.

    <!-- #masthead -->
    <div id="content" class="site-content">
        <div id="primary" class="content-area column full">
            <main id="main" class="site-main">
            <div class="grid portfoliogrid">
                    <!-- leave empty -->

        <!------- NEW ARTICLE ABOVE THIS LINE -------->
                <article class="hentry">
                <header class="entry-header">
                <div class="entry-thumbnail">
                    <a href="../blog/posts/url"><img alt="example" src="../blog/img/top-5-asian-cinema/thumbnail.jpeg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="title"/></a>
                <span style="font-family:candara">16th February, <a href="../blog/tags/2022" rel="category tag">2022</a></span> | <span style="font-family:candara"><i>author: name</i></a></span>
                </div>
                <h2 class="entry-title" style="font-family:corbel"><a href="../blog/posts/url" rel="bookmark"><b>title</b></a></h2>                 
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/list'>list</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/top-5'>top 5</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/asian-cinema'>asian cinema</a>
                </header>
                </article>
        <!------- NEW ARTICLE ABOVE THIS LINE -------->
                <article class="hentry">
                <header class="entry-header">
                <div class="entry-thumbnail">
                    <a href="../blog/posts/url"><img alt="example" src="../blog/img/mary-poppins/thumbnail.jpeg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="title"/></a>
                <span style="font-family:candara">12th February, <a href="../blog/tags/2022" rel="category tag">2022</a></span> | <span style="font-family:candara"><i>author: name</i></a></span>
                </div>
                <h2 class="entry-title" style="font-family:corbel"><a href="../blog/posts/url" rel="bookmark"><b>title</b></a></h2>                 
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/review'>review</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/walt-disney'>walt disney</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/julie-andrews'>julie andrews</a>
                </header>
                </article>
        <!------- NEW ARTICLE ABOVE THIS LINE -------->
                <article class="hentry">
                <header class="entry-header">
                <div class="entry-thumbnail">
                    <a href="../blog/posts/url"><img alt="title" src="../blog/img/charlie-cox-mcu/thumbnail.jpeg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="example"/></a>
                <span style="font-family:candara">11th February, <a href="../blog/tags/2022" rel="category tag">2022</a></span> | <span style="font-family:candara"><i>author: name</i></a></span>
                </div>
                <h2 class="entry-title" style="font-family:corbel"><a href="../blog/posts/url" rel="bookmark"><b>title</b></a></h2>                 
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/opinion'>opinion</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/mcu'>mcu</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/charlie-cox'>charlie cox</a>
                </header>
                </article>
        <!------- NEW ARTICLE ABOVE THIS LINE -------->
                <article class="hentry">
                <header class="entry-header">
                <div class="entry-thumbnail">
                    <a href="../blog/posts/url"><img alt="title" src="../blog/img/gentlemen/thumbnail.jpeg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="title"/></a>
                <span style="font-family:candara">9th February, <a href="../blog/tags/2022" rel="category tag">2022</a></span> | <span style="font-family:candara"><i>author: name</i></a></span>
                </div>
                <h2 class="entry-title" style="font-family:corbel"><a href="../blog/posts/url" rel="bookmark"><b>title</b></a></h2>                 
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/review'>review</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/guy-ritchie'>guy ritchie</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/crime'>crime</a>
                </header>
                </article>                  
        <!------- NEW ARTICLE ABOVE THIS LINE -------->
                <article class="hentry">
                <header class="entry-header">
                <div class="entry-thumbnail">
                    <a href="../blog/posts/title"><img alt="example" src="../blog/img/eternals/eternals thumb.jpeg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="title"/></a>
                <span style="font-family:candara">21st January, <a href="../blog/tags/2022" rel="category tag">2022</a></span> | <span style="font-family:candara"><i>author: name</i></a></span>
                </div>
                <h2 class="entry-title" style="font-family:corbel"><a href="../blog/posts/url" rel="bookmark"><b>title</b></a></h2>                 
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/review'>review</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/mcu'>mcu</a>
                <a class='portfoliotype' style="font-family:candara" href='../blog/tags/chloe-zhao'>chloe zhao</a>
                </header>
                </article>
            </div>
            <!-- .grid -->
            
            <nav class="pagination">
            <span class="page-numbers current">1</span>
            <a class="page-numbers" href="#">2</a>
            <a class="next page-numbers" href="#">Next »</a>
            </nav>
            <br/>

The javascript is mostly just my inclusions. A script to produce random articles from pressing a button. The linked scripts came with the website template, I just placed them in appropriate locations.:

<script src='../blog/js/jquery.js'></script>
<script src='../blog/js/plugins.js'></script>
<script src='../blog/js/scripts.js'></script>
<script src='../blog/js/masonry.pkgd.min.js'></script>
<script>
  function randomlinks(){
    var myrandom=Math.round(Math.random()*4)
    var links=new Array()
    links[0]="url"
    links[1]="url"
    links[2]="url"
    links[3]="url"
    links[4]="url"
 
    window.location=links[myrandom]
}
</script>

Thank you

Cypress: How to spy a method called by a button click

I’m using Vue3 + Vite + Cypress. Using Vue3 script setup SFC syntax. I have a component:

<template>
  <div>
    <button data-cy="testBtn" @click="btnClick()">
      Click
    </button>
  </div>
</template>

<script setup lang="ts">
function btnClick():void {
  console.log('clicked');
}
</script>

How can I spy on btnClick so that I can assert that it has been called when I do cy.get('[data-cy="testBtn"]').click();?
I have tried:

describe('Test', () => {
  it.only(`Test`, () => {
    mount(TestComponent, {
      props: {
        device: TestComponent
      }
    });

    cy.vue().then((wrapper) => {
      const test = cy.spy(wrapper.vm, 'btnClick');
      cy.get('[data-cy="testBtn"]').click();
      expect(test).to.be.called;
    });
  });
});

but I get an error Attempted to wrap undefined property btnClick as function

How can I get a returned object from this function?

his function return an object, i’m just not get value out of this:

function callObject(){
    if(validateInput.test(monthAport)){
      setInputErr(false)
      setResult(true)
      let filtered = simulate.filter(item =>
        item.tipoIndexacao == typeIn && item.tipoRendimento == typeYi )

        return filtered
    }else{
      setInputErr(true)
      }
  }

tks

Dynamic inline importing raw SVG in Vue.js & Vite

So I am trying to import SVG as string into my Vue component using inline import on Vite as follows

<script>
const getSvgIcon = async (name) => {
  const module = await import(`../icons/${name}.svg?raw`)
  return module.default
}

export default {
  props: {
    name: String,
  },
  data() {
    return {
      svg: null,
    }
  },
  watch: {
    name: {
      async handler(name) {
        this.svg = await getSvgIcon(name)
      },
      immediate: true,
    },
  },
}
</script>

<template>
  <div v-html="svg"></div>
</template>

This works just fine when running on npm run dev mode.

However, the issue happens when running npm run build, I end up getting Error: Unknown variable dynamic import apparently because I’m using ?raw suffix.

Is there a solution or is this a handicap by Vite as of now?

Converting classic asp to javascript: How to write or make returned string (json+ld) visible in header of webpage using javascript?

I have this Classic Asp code in header section of webpages:

<%
dim url, param, avgrate, votes, p, s
 url = "https://au2mailer.com/api/a2m-getschemaorg.asp"
 param = "?apikey=fe9fc289c3ff0af142b6d3bead98a923"
 Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
 HttpReq.SetOption(2) = 8192
 HttpReq.open "GET", url & param, false
 HttpReq.setRequestHeader "Content-Type", "application/json"
 HttpReq.Send()
 if (HttpReq.status = 200) Then
   response.write(HttpReq.responseText)
 end if
%>

and it works and is accepted by Google Schema Markup Validator.
Page to check https://carmagic.dk/online-bil-forretning-hvordan.asp
(Danish website)
I need to change the code so that it works whether the page is html, asp, aspx or php and my idea was to change it to javascript.
I have tried this javascript in header section

  <script>
      var request = new XMLHttpRequest();
        request.open('GET', 'https://au2mailer.com/api/a2m-getschemaorg.asp?apikey=fe9fc289c3ff0af142b6d3bead98a923');
        request.send();
        request.onload = ()=>{
          var receivedDom = new DOMParser().parseFromString(request.response, "text/html");
          var jsonstr = receivedDom.body.innerText;
          document.write(jsonstr);
        }
  </script>

The code execute but it does not work as the classic asp code!
Is my classic asp code not possible in javascript?

Thank you in advance and nice weekend

Michael Fiil