Add Vue main component in layout with params from backend

I am creating a single page application with vue 3 and backend on php. When I render start page from php I want to send some parameters to the vue main template by this way:

<body>
  <div id="app">
    <my-app :params="{{params}}" />
  </div>
  <script src="/public/assets/dist/js/chunk-vendors.js"></script>
  <script src="/public/assets/dist/js/app.js"></script>
</body>

chunk-vendors.js and app.js are generated by vue-cli-service build command.
But it doesn’t work like this, so I have to send them in separete script section as global variable:

<body>
  <div id="app">
  </div>
  <script>
      $_data = JSON.parse('{{data}}')
  </script>
  <script src="/public/assets/dist/js/chunk-vendors.js"></script>
  <script src="/public/assets/dist/js/app.js"></script>
</body>

Now my initial vue script main.js looks like:

import { createApp } from 'vue'

import App from './App'

const app = createApp({})

app.component('my-app', App)

app.mount('#app')

I also tried to make it like web component by vue-cli-service build –target wc but in this case there is an error:
Vue 3 support of the web component target is still under development.

Is it possible to do it as I wrote above?

How to download and convert youtube videos using ytdl-core

I have an idea to implement a function in a bot for whatsapp, I’m using the whatsapp-web.js library to make the bot, I managed to implement some things in it, but I wanted to make the function of downloading videos from youtube and transform them into mp3 and send them, but I didn’t reach my goal.
I created this code following the basis of some codes I saw around but it just doesn’t return anything, it doesn’t return an error, or any exception, it just doesn’t work, if anyone has an idea of how I can do or improve this, I’d be grateful.

client.on('message', async message => {
    if (message.body.startsWith('/yt ')) {
      const videoUrl = message.body.slice(4);
      const audioFormat = ytdl.chooseFormat(ytdl.getURLVideoID(videoUrl), { quality: 'highestaudio' });
  
      ytdl(videoUrl, { format: audioFormat })
        .pipe(fs.createWriteStream('audio.mp3'))
        .on('finish', () => {
          message.reply(new MessageMedia('audio/mp3', 'audio.mp3'));
          console.log('cheguei aqui')
        });
    }
  });

The purpose of this code was, when calling the /yt command together with the youtube link, download the video, convert it to mp3 and send it to the chat you requested, but I’m having difficulty.
I’m using whatsapp-web.js together with ytdl-core

I’m trying to write a script that setValue from another sheet to a new row every time it runs

I want to pull data from another sheet and paste it in the same column in a new row. So basically every time the trigger runs the script, it adds another row making a list of values based on how often the script runs.

function chelsearepairlog2(){
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("IN-HOUSE CHELSEA WORKSHOP");
  var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet8");
  var currentrepairs = sheet1.getRange("S1").getValue();
  var lastRow = sheet2.getRange(1,1).getLastRow();
sheet2.getRange(lastRow+1,1).setValue(currentrepairs);
}

Accessing a JSON file in JavaScript [duplicate]

I am trying to convert a JSON file into a variable to use for a website (quote generator). I got the JSON file from Kaggle and it is in the same folder as index.html, index.js, style.css.

My JavaScript code looks like this:

fetch("./wisdom.json")
  .then((response) => {

    return response.json();
  })
  .then((data) => console.log(data));

var element = getElementById("test");
element.innerHTML = data[9].quote;

My HTML looks like this:

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

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Read JSON file with JS</title>
    <script type="module" src="index.js"></script>
</head>

<body>
    <div>
        <p id="test">Nuray</p>
    </div>
</body>

</html>

I can see the JSON object printed to the console, but when I try to access some information from it to change the paragraph text, it doesn’t work. My purpose is to be able to filter some columns based on user’s preferences in the future, so I first wanted to see if I can get individual pieces of information from the JSON file. I am new to JavaScript, so I would be glad if you can explain it to me in the simplest way possible.

Thanks!

How can I properly reference constants from a constants.js file from any other file in my Chrome extension?

I’ve got a constants.js file that contains export statements like:
const domains = ['target.com', 'amazon.com', '88rising.com'];

When I import from another file, which looks like this:

const domains = ['target.com', 'amazon.com', '88rising.com'];

document.addEventListener('DOMContentLoaded', () => {
    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
      
      const currentUrl = tabs[0].url;
      const truncatedUrlElement = document.getElementById('truncated-url');
      const siteIndexElement = document.getElementById('index-number');

      truncatedUrl = new URL(currentUrl).hostname.replace(/^www./, '');
      truncatedUrlElement.textContent = truncatedUrl;
      console.log(truncatedUrl)
      
      siteIndex = domains.indexOf(truncatedUrl) + 1;
      siteIndexElement.textContent = siteIndex.toString();
    });
  });

domains actually does properly log to the console, but is not properly logging from inside the document.addEventListener block. I’m having a really tough time understanding why this would be the case, and how to properly reference and import constants from my constants.js file across my entire Chrome extension project.

Tried to import a variable from another file, constants.js and expected the reference to be correctly handled.

It’s strangely working at the beginning of the file, but not in the middle where it needs to?

How to convert javascript to php

I got this code in javascript

 for (String i in transaction["signatur"]) {
     howManyBandwidthNeed += i.length;
 }

how to convert it to PHP code?
if the “transaction[“signatur”]” is

[signature] => Array
            (
                [0] => 05971371baf66d9f5a4edbabc1dd26b0bf763f200bb31df7282e4fe32fb77d262fc5297bc97efc0255b83dc9b44807300539512db4832261823c314bf2e562e900
            )

Thanks

Iterating over an array [title, releaseYear] to log title and release year of each story; then logging specific items in the array? [closed]

…I have a super basic question that’s one I know that I know lol. Brains just kind of overloaded right now but I’ve been spending way too much time and energy on this tiny thing.

I can’t remember how to assign a value to the property contents (title: ‘string’, releaseYear: ‘string’) within the “cases” function array, then to follow by logging each string within said array properties so it logs all of its contents.

Lesson Instructions .jpg link
Lesson .jpg link

I tried to call cases.forEach() on the properties “title” and “releaseYear”, and also tried to grab them from local storage within the .forEach statement, but no matter what I’ve inputted this far the properties of “title/releaseYear” along with function of “cases” results with no value – and no return logged.

Help a rookie out with 3 weeks coding experience and an overloaded brain? Lol I’d appreciate any guidance to jog my memory. I must just be not utilizing a simple step correctly it someone could give me an example as a refresher!

Thank you in advance 🙂

Sanity and react project starting with sign in google, I have a problem using createIfNotExists which i beleieve is realted to sanity

hello this is my code backend side of my schemaTypes file

import { defineType, defineField } from "sanity";
export const schemaTypes=
[
    defineType({
        name:'comment',
        title:'Comment',
        type:'document',
        fields:[
            defineField(
            {
                name:"postedBy",
                title:"PostedBy",
                type:"postedBy"
    
            }),
            defineField({
                name:"comment",
                title:"Comment",
                type:"string"
    
            })
        ]
    }),




    defineType(
    {
    name:'user',
    title:"User",
    type:"document",
    fields:[
        defineField(
        {
            name:'userName',
            title:"UserName",
            type:"string"
        }),

        defineField({
            name:'image',
            title:"Image",
            type:"string"
        }),
        
    ]    
}),
defineType({
    name:"postedBy",
    title:"PostedBy",
    type:"reference",
    to:[
        {
            type:"user"

    
        }
    ]

}),
defineType({
    name:"pin",
    title:"Pin",
    type:"document",
    fields:[defineField(
        {
            name:"title",
            title:"Title",
            type:"string"

        }),
        defineField({
            name:"about",
            title:"About",
            type:"string"

        }),
        defineField({
            name:"destination",
            title:"Destination",
            type:"url"

        }),
        defineField({
            name:"category",
            title:"Category",
            type:"string"

        }),
        defineField({
            name:"image",
            title:"Image",
            type:"image",
            options:{
                hotspot:true
            }

        }),
        defineField({
            name:"userId",
            title:"UserId",
            type:"string"

        }),
        defineField({
            name:"postedBy",
            title:"PostedBy",
            type:"postedBy"

        }),
        defineField({
            name:"save",
            title:"Save",
            type:"array",
            of:[{type:'save'}]

        }),
        defineField({
            name:"comments",
            title:"Comments",
            type:"array",
            of:[{type:'comment'}]

        })
    ]
}),
defineType({
    name:'save',
    title:'Save',
    type:'document',
    fields:[
        defineField({
            name:"postedBy",
            title:"PostedBy",
            type:"postedBy"

        }),
        defineField({
            name:"userId",
            title:"UserId",
            type:"string"

        })
    ]
}),



]

and this is my client.js file code

import {createClient} from "@sanity/client"
import imageUrlBuilder from "@sanity/image-url"


export default function test(){

}


export const client=()=>createClient({
    projectId:process.env.REACT_APP_SANITY_PROJECT_ID,
    dataset: 'production',
    apiVersion: '2023-03-17',
    useCdn:true,
    token:process.env.REACT_APP_SANITY_TOKEN,



})

const builder = imageUrlBuilder(client)

export const urlFor=(source)=>builder.image(source)

and this is my client side code: login page first

import React from 'react'
import { useEffect, useState } from 'react'
import {useNavigate} from "react-router-dom"
import {FcGoogle} from "react-icons/fc"
import shareVideo from "../assets/share.mp4"
import logo from "../assets/logowhite.png"
import jwt_decode from "jwt-decode"
import {client} from "../client"
import {urlFor} from "../client"


console.log(urlFor)
console.log(client)

const Login = () => {
  const navigate = useNavigate()
//const [user,setUser]=useState({})
  function handleCallbackResponse(response){

var userObject=jwt_decode(response.credential)
console.log(userObject)
//setUser(userObject)
localStorage.setItem('user',JSON.stringify(userObject))
const {name,nbf,picture}=userObject
 const doc={
  _id:nbf,
  _type:'user',
  userName:name,
  image:picture





 }

client.createIfNotExists(doc)
 .then(()=>{
   navigate('/',{replace:true})


 }).catch(err=>console.log("error creating")); 





}
  useEffect(()=>{

    window.google.accounts.id.initialize({
      client_id:process.env.REACT_APP_GOOGLE_API_TOKEN,
      callback:handleCallbackResponse
    })
    window.google.accounts.id.renderButton(document.getElementById('signInDiv'),
    {theme: "outline", size:"large"}  
    )

  })







  const responseGoogle=(response)=>{
    

  }



  return (

    <div className="flex justify-start items-center flex-col h-screen">Login
      <div className ="relative w-full h-full">
        <video
          src={shareVideo}
          type="video/mp4"
          loop
          controls={false}
          muted
          autoPlay
          className="w-full h-full object-cover"
        


        />
        
        <div className="absolute flex flex-col justify-center items-center top-0 right-0 left-0 bottom-0 bg-blackOverlay">
          <div className='p-5'>
            <img src={logo} width="130px" alt="logo"/>

          </div>
          <div className='shadow-2xl'>
            
              <button 
              id="signInDiv"
                type="button"
                className='bg-mainColor flex justify-center items-center p-3 rounded-lg cursor-pointer outline-none'
                
                >
                  <FcGoogle className='mr-4'
                  />Sign in with google


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

  )
}

export default Login


and then my home page wich should be redirected to from login page

I am getting this error when I choose the google mail I want to log in with

client__WEBPACK_IMPORTED_MODULE_4_.client.createIfNotExists is not a function
So from the first look I think I have a problem in my client file can someone help me

I think the problem is in client.js file on the part of createClient() function

Retrieve the ID of the getUser using JWT

When I make a request on Postman to retrieve the user’s ID, I get a response of -1.

I am able to register new data into the database.
I can also connect with a created account and login.

However, I am unable to make modifications due to an error, and I am unable to retrieve the ID.

Thank you in advance for any help and responses.

// jwt.utilse.js

module.exports = {
  generateTokenForUser: function (userData) {
    return jwt.sign(
      {
        userId: userData.id,
        isAdmin: userData.isAdmin,
      },
      JWT_SING_SECRET,
      {
        expiresIn: "1h",
      }
    );
  },
  parseAuthorization: function (authorization) {
    return authorization != null ? authorization.replace("Bearer ", "") : null;
  },
  getUserId: function (authorization) {
    let userId = -1;
    let token = module.exports.parseAuthorization(authorization);
    if (token != null) {
      try {
        let jwtToken = jwt.verify(token, JWT_SING_SECRET);
        if (jwtToken != null) userId = jwtToken.userId;
      } catch (err) {}
    }
    return userId;
  },
};

// usersCrtl.js

 getUserProfile: function (req, res) {
        let headerAuth = req.headers["authorization"];
        let userId = jwtUtils.getUserId(headerAuth);

        if (userId < 0) return res.status(400).json({
            error: "wrong token"
        });

        models.User.findOne({
                attributes: ["id", "email", "username", "bio"],
                where: {
                    id: userId
                },
            })
            .then(function (user) {
                if (user) {
                    res.status(201).json(user);
                } else {
                    res.status(404).json({
                        error: "user not found"
                    });
                }
            })
            .catch(function (err) {
                res.status(500).json({
                    error: "cannot fetch user"
                });
            });
    },
    updateUserProfile: function (req, res) {
        let headerAuth = req.headers["authorization"];
        let userId = jwtUtils.getUserId(headerAuth);

        let bio = req.body.bio;
        if (userId < 0) return res.status(400).json({
            error: userId
        });

        asyncLib.waterfall(
            [
                function (done) {
                    models.User.findOne({
                            attributes: ["id", "bio"],
                            where: {
                                id: userId
                            },
                        })
                        .then(function (userFound) {
                            done(null, userFound);
                        })
                        .catch(function (err) {
                            res.status(500).json({
                                error: "unable to verify user"
                            });
                        });
                },
                function (userFound, done) {
                    if (userFound) {
                        userFound
                            .update({
                                bio: bio ? bio : userFound.bio,
                            })
                            .then(function (userFound, done) {
                                done(userFound);
                            })
                            .catch(function (err) {
                                res.status(500).json({
                                    error: "cannot update user"
                                });
                            });
                    } else {
                        res.status(404).json({
                            error: "user not found"
                        });
                    }
                },
            ],
            function (userFound) {
                if (userFound) {
                    return res.status(201).json(userFound);
                } else {
                    return res.status(500).json({
                        error: "cannot update user profile"
                    });
                }
            }
        );
    },

Sort table based on the # of img tags in a given element

<body>

    <table id="myTable">
        <caption>
          SF6 LeaderBoard
        </caption>
        <thead>
          <tr>
            <th scope="col">Character Icon</th>
            <th scope="col">Username</th>
            <th scope="col">Badges</th>
            <th scope="col">Faction</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row"></th>
            <td>fighter2</td>
            <td><img style="display: block;-webkit-user-select: none;" src ="https://i.ibb.co/NSwLYkR/MARISSA-EMBLEM.png" height="50" ></td>
            <td>Blitz</td>
          </tr>
          <tr>
            <th scope="row"><img src="https://www.fightersgeneration.com/nx9/char/ultra-sf4-chibi/chunli-ultra-sf4-chibi.png" height="100" width="100"></th>
            <td>fighter1</td>
            <td><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"> <img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"></td>
            <td>Galaxy</td>
          </tr> <tr>
            <th scope="row"><img src="https://www.fightersgeneration.com/nx9/char/ultra-sf4-chibi/chunli-ultra-sf4-chibi.png" height="100" width="100"></th>
            <td>KaiRosFGC</td>
            <td><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"><img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"> <img src="https://www.pikpng.com/pngl/m/31-313648_boulder-badge-rock-gym-badge-pokemon-clipart.png" height="40" width="40"></td>
            <td>Galaxy</td>
          </tr>
   
      
         
        </tbody>
        
      </table>
   

<script>
    function sortTable() {
   var table, rows, switching, i, x, y, shouldSwitch;
   table = document.getElementById("myTable");
   switching = true;
   while (switching) {
     switching = false;
     rows = table.getElementsByTagName("tr");
     for (i = 1; i < (rows.length - 1); i++) {
       shouldSwitch = false;
       x = rows[i].getElementsByTagName("td")[2].getElementsByTagName("img").length;
       console.log(x);
       y = rows[i + 1].getElementsByTagName("td")[2].getElementsByTagName("img").length;
       if (x < y) {
         shouldSwitch = true;
         break;
       }
     }
     if (shouldSwitch) {
       rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
       switching = true;
     }
   }
 }
 console.log('hello');
       </script>

Hi im trying to create a sorting method that takes the number of img tags in a tr element and changes the order if the element has less img tags than the next. but when i run this code nothing happens at all. I have tried to move the script tags because maybe the location was the issue but i still run into the same problem of nothing being reordered.

axios-cache-interceptor “setupCache() should be called only once” error with next.js

I’m trying to use axios-cache-interceptor to cache requests. However, when I try to set it up I get this error: Error: setupCache() should be called only once

   7 | import { setupCache } from "axios-cache-interceptor";
   8 | 
>  9 | const axios = setupCache(Axios)
     |                       ^
  10 | 
  11 | export default function DashboardPage() {
  12 | const { data: session } = useSession();

I tried putting the axios object in a seperate file, setting up the cache there and then export the set up cache axios object so that it’d only run once, but it did nothing different.

Trying to delay the start of a stopwatch

I can’t seem to delay my stopwatch, and I don’t know what’s wrong with my code.

document.getElementById('start-test').onclick=function() {
    int=setInterval(timerUpdate,9);
    
}

function timerUpdate() {
    ms+=9
        if(ms>990) {
            ms=0
            s++
        }
        if (ms<10) {
            const milliseconds="00"+ms
            document.getElementById('ms').innerHTML=milliseconds
        }
        else if (ms<100) {
            const milliseconds="0"+ms
            document.getElementById('ms').innerHTML=milliseconds
        }
        else {
            const milliseconds=ms
            document.getElementById('ms').innerHTML=milliseconds
            
        }
        document.getElementById('s').innerHTML=s
}
setTimeout(timerUpdate,4000);

This is the code I used, which begins repeating every 0.009 seconds after I click the start button, but I want it to be delayed by 4 seconds. I added the setTimeout feature at the bottom to try to achieve this, however this isn’t working. Pls help.

Last.FM API in JavaScript – Error Code 5 appearing for some tracks?

I am trying to implement Last.FM API ysing a JavaScript wrapper made by ‘leemm’, and it seems to function properly, with it returning information through testing. But when I try to use the ‘track.getInfo()’ method, it starts to throw

error: {
    code: '5',
    message: "Invalid format - This service doesn't exist in that format"
  },
  text: undefined
}

For songs such as ‘Survival of The Fittest’ by ‘Mobb Deep’. But it returns information properly for other songs such as ‘HUMBLE.’ by ‘Kendrick Lamar’.

This is my function:

async function lastFMTest(){
  const data = await lastfm.track.getInfo({
    artist: 'Kendrick Lamar',
    track: 'HUMBLE.',
    username: 'NAG_Z',
    autocorrect: '1'
  });
  console.log(data.track.name, data.track.userplaycount, data.track.toptags.tag[0].name);
}

I noticed that getInfo() method returns information for a good amount of tracks before crashing on one particular track. I checked the unofficial documentation and it says:

Last.fm Error Code 5: Invalid Response Format

A format parameter is necessary in addition to the documented parameters, this may either have a value of XML or JSON (case insensitive). Requesting data in another format will emit this error. Some methods do support more than these 2 formats, the methods that do have their formats listed in this documentation.

So I tried inserting a format parameter specifying 'json' which results in the same issue, 'XML' breaks the method though I do wish my data returned in JSON format so I don’t really think XML is the way to go.

This is most likely due to my lack of understanding of the API or possibly JavaScript as I am still a novice, if anyone could help me I would greatly appreciate it!

Is there a way to fix safari from creating grid lines when scaling or transforming an iframe?

In safari, when I transform/scale an iframe, I get some weird grid lines that appear and disappear. How can I remove them?

Here is a codepen, make sure you shrink or increase your viewport to see them.
https://codepen.io/davidsalazar/full/yLxxNQX

<iframe class="position-absolute" style="transform: scale(.7);" scrolling="no" src="https://flysumo.com/davidksalazar">
</iframe>

Here is a screenshot of what I’m referring to.
enter image description here