How to find total views in a YouTube PlayList

I am trying to find the total number of views of all videos in a playlist I own in YouTube. I can see that a “total views” number is posted under the playlist name. However this appears to be the number of views generated by entering the playlist first. When I add up the number of views of individual videos I get a substantially larger number because, I assume, most of videos are watched by following a link other than the playlist.

In searching for an answer I see two suggestions

  1. using the following JS in the YT console
ytInitialData.header.playlistHeaderRenderer.viewCountText.simpleText

But this just gives the same number that is available under the playlist name.

  1. using the following
var totalViews = 0;
var videos = document.querySelectorAll('ytd-playlist-video-renderer');
for (var i= 0; i < videos.length; i++)  {
    var viewsElement = videos[i].querySelector('#metadata > span:nth- child(1)');
    if (viewsElement !== null) {
        var views = viewsElement.textContent.trim().replace(/D/g,'');
        totalViews += parseInt(views);
    }
}
console.log('Total views of all videos in the playlist: ' + totalViews);

But this gives a total count of 0.

Oblique responsive line between 2 divs

I would like to draw two oblique lines that would join two corners of two different divs. I need these lines to be responsive. My project currently uses angular but my problem, I think, can be solved with css. I also can’t use external libraries. enter image description here

I tried svg and I don’t know if I used it wrong but it was not responsive.

 <svg width="220" height="240" class="roadLink"><line x1="50" y1="60" x2="530" y2="220" stroke="black"/></svg>
        <div class="mb-2 d-flex">
            <div class=" d-flex justify-content-between roadSize topAnrpBlock">
            </div>
        </div>
        <svg width="140" height="100" class="roadLink"><line x1="50" y1="50" x2="500" y2="200" stroke="black"/></svg>

in BootstrapVue table, can only drag and drop table header, the table items are not changing

I want to implement a drag and drop feature on my BootstrapVue table. By using the code below, I can only drag and drop the table header but table items are not changing. I console logged updatedHeaders which is undefined.

<template>
  <div class="container mt-5">
    <div class="row">
      <h3>Managing Existing Accounts</h3>
    </div>
    <div class="row mt-3">
      This section shows all accounts you currently manage.<br>
      Click on a row to open up details about that account.<br>
      Accounts that have expired will have all their personally identifiable information scrubbed in 90 days.
    </div>

    <!--toggle for column customization-->
    <div>
      <b-button v-b-toggle.column-collapse variant="primary">Column</b-button>
      <b-collapse id="column-collapse" class="mt-2">
        <b-card>
          <p class="card-text">Choose the column</p>
          <b-form-checkbox-group v-model="selectedColumns">
            <b-form-checkbox value="Renew Date">Renew Date</b-form-checkbox>
            <b-form-checkbox value="Account Name">Account Name</b-form-checkbox>
            <b-form-checkbox value="Location">Location</b-form-checkbox>
            <b-form-checkbox value="Type">Type</b-form-checkbox>
            <b-form-checkbox value="Account Type">Account Type</b-form-checkbox>
          </b-form-checkbox-group>
        </b-card>
      </b-collapse>

      <div>
        <table class="table table-striped">
          <thead class="thead-dark">
          <draggable v-model="updatedHeaders" tag="tr" @end="dragged">
            <th v-for="header in headers" :key="header" scope="col">
              {{ header }}
            </th>
          </draggable>
          </thead>
          <tbody>
          <tr v-model="updatedHeaders" v-for="item in items" :key="item.gymID">
            <td v-for="header in headers" :key="header">{{ item[header] }}</td>
          </tr>
          </tbody>
        </table>

      </div>
      <rawDisplayer class="col-2" :value="items" title="Items"/>

      <rawDisplayer class="col-2" :value="updatedHeaders" title="Headers"/>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable';

export default {
  components: {
    draggable,
  },
  data() {
    return {
      dataLoaded: false,
      accountList: [],
      items: [],
      selectedColumns: ['Renew Date', 'Account Name', 'Location', 'Type', 'Account Type'],
      _xsrf: "",
    };
  },
  created() {
    // Load the saved column order from local storage
    const headers = localStorage.getItem('tableHeaders');

    if (headers !== "undefined") {
      const selectedFields = JSON.parse(headers);
      this.selectedColumns = selectedFields.map(field => field.label);
    }

    fetch('/distributor/api/managing-existing-accounts')
        .then(response => response.json())
        .then(data => {
          this.accountList = data.accountList;
          this.items = data.accountList;
          this.dataLoaded = true;
          this._xsrf = data._xsrf;
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
  },
  computed: {
    filteredFields() {
      if (this.dataLoaded) {
        return Object.keys(this.items[0] ? this.items[0] : {})
            .filter(field => this.selectedColumns.includes(field))
            .map(field => ({
              key: field,
              label: field
            }));
      }
    },
    headers() {
      console.log(this.updatedHeaders);
      return this.updatedHeaders ? this.updatedHeaders : this.filteredFields?.map(field => field.key);
    },
  },

  methods: {
    dragged() {
      // Map the new order of headers to their corresponding labels
      const updatedLabels = this.updatedHeaders?.map(header => this.filteredFields.find(field => field.key === header).label);
      // Save the new order of headers to local storage
      localStorage.setItem('tableHeaders', JSON.stringify(this.headers));
    }
  }
}
</script>

<style>
/* Add your styles here */
</style>

I want to have checkboxes to select the column I want to show and I can drag and drop the table columns.

regex for string with. fixed PREFIX/SUFFIX words at rear ends

I am trying to make a regex for JS. following are inputs

PREFIX hello SUFFIX
PREFIX PREFIX SUFFIX
PREFIX SUFFIX SUFFIX
PREFIX var+2 SUFFIX

Note: PREFIX and SUFFIX are kind of fixed. in between these words, we can have any number. of words.

I came up with this regex

(PREFIX(?=(?<spaces>[sS]+SUFFIX))k<spaces>)

but this one was reported as polynomial

https://regex101.com/r/YCbU0f/1 has attack string which causes more backtracking.. Can we make it safe from tool above meeting above requirements.

Redirect(to specific page) Background notifications in react js web

in web react js we catch the background notification event in ‘firebase-messaging-sw’ this file but for redirection and some data pass there is no option so please tell me how we can pass data or catch event in the application other than this file

we add redirection in ‘firebase-messaging-sw’ but packages are not imported there so i want to catch event in root files like index.js

How to update modal information without reopening the modal in react native?

I have a modal which opens when a product is clicked and details of that product are displayed in modal there is also a you might also like section of products which have the same view as product now I want that when a you might like product is clicked the modal should update the information without opening a modal above existing modal. How can I do that?

const cartProducts = useSelector(state => state.cart.cartProducts);
const dispatch = useDispatch();
const [MyProducts,setProducts] = useState([]);
const prodCode = product.ItemCode;
const {user} = useSelector(state=>state.auth);

async function fetchProducts(){
 //console.log(prodCode);
 await axios({
               method:'GET',
               url:`${BASE_URL}/items/${prodCode}`,
               headers:{
                   'Authorization': AUTH_KEY,
               }
           })
           .then((response)=>{  
             setIsLoading(false);
             const status = response.data[0]['status'];
             //console.log(status);
             if(status=='success'){
               const items = response.data[0]['body']['related'];
               if(items){
                 //console.log(items);
                 setProducts(items);
               }
               //console.log(Products);
               }
               if(status=='error'){
                 MyToast(status);
               }
           }).catch((error)=>{
             setIsLoading(false);
               MyToast('Error: '+error.message);
               //console.log('Error is: ',error.message);
           });
}

useEffect(()=>{
 if(MyProducts.length === 0 && visible){
 fetchProducts();
 }
},[MyProducts]);

return (
 <Modal
   animationType="slide"
   transparent={true}
   visible={visible}>
   <View style={styles.centeredView}>
     <View style={styles.modalView}>
       <View style={styles.modalClose}>
         <TouchableOpacity style={styles.button} onPress={() => { handlePinClick()}}>
           <IconPin name={isPin ? 'pushpin' : 'pushpino'} size={responsiveWidth(6)} color={Colors.primary} />
         </TouchableOpacity>
         <TouchableOpacity style={styles.button} onPress={() => { handleFavoriteClick() }}>
           <IconFavorite style={{ padding: responsiveWidth(1.5) }} name={'ios-heart'} size={responsiveWidth(8)} color={isFavorite ? 'red' : Colors.grey} />
         </TouchableOpacity>
         <IconClose style={[styles.button, { padding: responsiveWidth(1.5) }]} name='cross' size={responsiveWidth(8.5)} color={Colors.black} onPress={() => onClose()} />
       </View>
       <ScrollView style={{ paddingBottom: responsiveHeight(7) }}>
         <Image style={styles.modalImage} source={{ uri: isFromAll ? product.feature_image : product['item_details'].feature_image }} />
         <Text style={styles.modalProdName}>{isFromAll ? product.ItemName : product['item_details'].ItemName}</Text>
         <ExpandableComponent product={product} isFromAll={isFromAll}/>
           {MyProducts.length !== 0 && 
           <View style={{ paddingVertical: responsiveHeight(1) }}>
           <Text style={styles.youMightText}>You might also Like</Text>
           {isLoading ?
             <View style={{height:responsiveHeight(28),flexWrap:'wrap' }}>
                 {widthList.map((item, index) => <ShimmerItem key={index} item={item} />)}
             </View> :
             <FlatList
               horizontal
               data={MyProducts}
               renderItem={({ item }) => <Product key={item.key} product={item} isFromAll={true}/>}
               ListEmptyComponent={()=><EmptyComponent height={30} text={'No Product!'}/>}
             />
             }
             </View>
             }
       </ScrollView>
       <View style={styles.bottomView}>
         {cartProducts && <BottomSheetScreen itemsCount={cartProducts.length} />}
       </View>
     </View>
   </View>
 </Modal>
)
}


How to decode base64 text to binary file?

I am converting binary file’s buffer to base64 text before storing to mongodb. I am using multer to get image alongside with with other field. I am sending those data in FormData and the back end is

app.post('/image', multer().single('image'), (req, res) => {
    const image = Buffer.from(req.file.buffer).toString('base64')
    database.collection('images').insertOne({image})
}

Now, how do I decode this base64 text to binary image?

I tried this in the front end after getting the json from the back end

URL.createObjectURL(new Blob([window.atob(data.image)]))

But I think the binary file is corrupted.

Is it possible to make a pixelated bitmap font in node-canvas?

I’ve been recently working on a Node.js project that uses node-canvas module.

Although I have a problem. I want to completely disable the font smoothing (like you can do in Paint.net, Photoshop, Adobe Animate, etc), so that the font is pixelated and crisp.

Here’s the picture of the text with the same font and size. The top one is rendered by node-canvas, while the bottom one is how I want it to look like (i.e. unsmoothed, crispy).

hi there

Does anyone know if it’s possible or not?

watch method of fs module in node.js logs the output twice

fs.watch is unstable and not consistent and sometimes reports events twice. I tried other packages out there but still the same thing. I tried the ‘chokidar’ package not to get the double logs, but it doesn’t report all the events if they happen extremely fast, for example doing a thousand writes to a file.

Can someone explain what is happening behind the scenes with C++ APIs and OS while calling the watch method in node.js?

import { log } from "console";
import { watch } from "fs/promises";
(async () => {
  const watcher = watch("./somefile.txt");
  for await (const event of watcher) {
      log(event);
  }
})();

NestJS TypeORM createQueryBuilder SELECT query

I am trying ‘SELECT USER_CODE FROM USERS’ query by TypeORM in nestJS.
My databse is MySQL and this database has ‘users’ table.
the columns are ‘USER_CODE’, ‘USER_EMAIL’, ‘USER_PASSWORD’, ‘USER_PHONE’.
I’ve seen TypeORM official documents several times, but I don’t understand them well.

//service.ts
import { InjectRepository } from '@nestjs/typeorm';
import { Injectable } from '@nestjs/common';
import { Users } from './entity/users.entity';
import { Repository } from 'typeorm';
import { UsersSignupDto } from './dto/users.signup.dto';
import { generateCode } from 'src/common/utils/code.generator';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(Users) private userRepository: Repository<Users>,
  ) {}

  async signup(body: UsersSignupDto) {
    const user = await this.userRepository
      .createQueryBuilder()
      .select('users.user_code')
      .from(users,'users')
      .where('users.user_code = :id', { id: '74EQQK' })
      .getOne();
    console.log(user);
   
}

the code returns ‘null’ but I checked that table’s rows are not empty.

but when i tried

const user = await this.userRepository
      .createQueryBuilder()
      .where('users.user_code = :id', { id: '74EQQK' })
      .getOne();
      console.log(user);

It works.. but this qurey gets all informations from table.
I just want to get ‘user_code’ column. How to make it works? or Can someone link me the references information?

Can not start server file of Git Cloned MERN-Stack Backend folder [duplicate]

I cloned the MERN-STACK backend folder from Github. It is our group project. So That backend is working well when it starts by person who created that. But When I tried to run it showed the following error.

node index.js
(node:81836) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/masterlwa/Desktop/new/ITP_Project__GYMLY/backend/src/index.js:1
import "dotenv/config";
^^^^^^
SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1195:20)
    at Module._compile (node:internal/modules/cjs/loader:1239:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Module._load (node:internal/modules/cjs/loader:972:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

I installed node modules to that file and tried to run it using node index.js command (index is a server file). But I show the following error. How to fix it?

Sharing vCard using Web-Share API: Permission Denied

I have the following code to share vCard on my android device.

        <Button
          variant={buttonColorHandler()}
          onClick={handleAddToContact}
        >
          Add to Contact
        </Button>

And handler

const handleAddToContact = async () => {
    console.log('Add to contact');
    console.log(navigator.canShare);
    const res = await fetch('/vcard.vcf');
    const data = await res.blob();
    const file = new File([data], 'vcard.vcf', { type: 'text/vcard' });
    const shareData = {
      files: [file],
      title: 'vCard',
    };

    console.log(shareData);
    console.log(navigator.canShare(shareData)); // getting true here


    navigator
      .share(shareData)
      .then(() => {
        console.log('Data was shared successfully');
      })
      .catch(err => {
        console.log(err);
      });
  };

When I’m running the following code and after clicking on Button I’m getting following exception

DOMException: Permission denied

JavaScript in Qualtrics: Referencing the displayed order of choices

For a question, I have 4 choices (alpha, beta, gamma, delta) displayed in random order through choice randomization. I want the displayed order of these choices to be captured in embedded data fields, to be used later in the survey.
For example, if the choices were displayed

beta
gamma
alpha
delta

I want embedded data fields pos_beta = 1, pos_gamma = 2, pos_alpha=3 and pos_delta=4.

If they were displayed

gamma
alpha
beta
delta

I want embedded data fields pos_gamma = 1, pos_alpha = 2, etc

Easiest way to implement this? (Also, could the answer be generic enough to capture if the choices had random text around the keywords – “blah blah gamma blah blah” etc?)

Thanks in advance!

(I looked at other questions on this site but could not find anything that addresses this).