MCDatepicker throws error on app start, how to fix this error?

I am getting the below error while importing MCDatepicker, and the app could not start.

[1] Module parse failed: Unexpected token (141:23)
[1] File was processed with these loaders:
[1]  * ./node_modules/babel-loader/lib/index.js
[1] You may need an additional loader to handle the result of these loaders.
[1] |     instance.pickedDate = date;
[1] |     updateLinkedInputValue(instance);
[1] >     if (activeInstance?._id !== instance._id) return;
[1] |     var _activeInstance4 = activeInstance,
[1] |         store = _activeInstance4.store;

Please help out.

How to pass active class in carousel using Vue.js?

for some months now, i have decided to learn Vue.js, for that I have decided to choose a projet on whcich i will learn so that my learning experience will be more pratical, I am actually working on a carousel which worked perfectly the way I want with JQUERY but I would like to do it now with Vue.js.

PROBLEM: the problem i am facing now is with the “slider-item”, I have just noticed from the chrome devtool that only one “slider-item” displays and I dont know also how to pass the “active” class to it whenever I click to next img or previous img. To summarize I want the “active” class to be passed to each “slider-item” when the previous button or next button is pressed. I have attached a picture to illustrate what i am trying to achieve, please I need help to solve this cause it will help me understand in solving problem related to carousel in Vue.js
enter image description here

// carousel items
const carousels = [
    {
        img: 'https://www.static-src.com/siva/asset//02_2022/GI-JAN-2022-2000x500-desktop-16feb.jpg?w=960',
        href: "#"
    },
    {
        img: 'https://www.static-src.com/siva/asset//02_2022/bliresto-feb22-blm-carousel-desktop-2000x500_desktop_16feb.jpg?w=960',
        href: "#"
    },
    {
        img: 'Home-Desk-Hometronics-Valentine-12-13-Feb-22.jpg',
        href: "#"
    },
    {
        img: 'https://www.static-src.com/siva/asset//02_2022/rabcan-homepage2000x500-desktop-16feb.jpg?w=960',
        href: "#"
    }
];

// vue
new Vue({
  el: '#app',
  data: {
        carouselName: 'carousel-next',
        carousels: carousels,
        len: 0,
    show: 0,
        xDown: null, // for swiper
        yDown: null, // for swiper
        autoplay: false, 
        timer: null, // auto play
        timerDelay: 3000, 
        toggleTimer: true, // pause auto play
        minHeight: 0 
  },
    methods: {
        toNext() {
            this.carouselName = 'carousel-next';
            this.show + 1 >= this.len ? this.show = 0 : this.show = this.show + 1;
        },
        toPrev() {
            this.carouselName = 'carousel-prev';
            this.show - 1 < 0 ? this.show = this.len - 1 : this.show = this.show - 1;
        },
        // swiper event(for mobile)
        touchStart(e) {
            this.xDown = e.touches[0].clientX;
            this.yDown = e.touches[0].clientY;
        },
        touchMove(e) {
            const _this = this;
            if(!this.xDown || !this.yDown) { return; }

            let xUp = e.touches[0].clientX;
            let yUp = e.touches[0].clientY;

            let xDiff = this.xDown - xUp;
            let yDiff = this.yDown - yUp;

            if(Math.abs(xDiff) > Math.abs(yDiff)) {
                xDiff > 0 ? _this.toNext() : _this.toPrev();
            }
            this.xDown = null;
            this.yDown = null;
        },
        //
        autoPlay() {
            setInterval(() => {
                if(this.toggleTimer) this.toNext();
            }, this.timerDelay);
        }
    },
    mounted() {
        this.len = this.carousels.length;
        this.autoplay = this.$refs.carousel.dataset.auto == 'true';
        this.timerDelay = Number(this.$refs.carousel.dataset.delay) || 3000;
        if(this.autoplay) this.autoPlay();
        window.addEventListener('load', () => {
            this.minHeight = this.$refs.carousel.offsetHeight + 'px';
        });
    },
});
*, *::before, *::after {
  box-sizing: border-box;
}

.slide-placeholder {
    position: relative;
}

@media screen and (min-width: 769px), print{
.slide-placeholder {
    min-height: 190px;
    margin-bottom: 16px;
}
}

.slide-placeholder:before {
    content: '';
    width: 100%;
    background: #0095da;
    position: absolute;
    top: 0;
}

.slide-placeholder__carousel-container {
    position: relative;
    margin: 0 auto;
    width: 100%;
    background-size: cover;
    background-repeat: no-repeat;
    overflow: hidden;
}

.carousel-container__background {
    width: 100%;
    height: 100%;
    background-size: 100% 100%;
    background-position: top;
    background-repeat: no-repeat;
    position: absolute;
    -webkit-filter: blur(20px);
    filter: blur(20px);
    -webkit-transition: all .3s ease-in-out;
    transition: all .3s ease-in-out;
    -webkit-transform: scale(1.2);
    transform: scale(1.2);
    opacity: 90%;
}

.custom__container {
    width: 100%;
    position: relative;
}

.slide-placeholder__carousel-container .custom__container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 10px 0;
}

.carousel-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.carousel-container .items {
    height: 100%;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    white-space: nowrap;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.carousel-container .items.placeholder-slider {
    margin: 10px auto;
}

@media screen and (min-width: 960px){
.carousel-container .items.placeholder-slider {
    width: 80%;
}
}

@media screen and (min-width: 769px), print{
.carousel-container .items.placeholder-slider {
    max-width: none;
}
}

@media screen and (min-width: 769px), print{
.carousel-container .items .slider-item {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    height: 100%;
    width: 100%;
}
}

@media screen and (min-width: 960px){
.carousel-container .items.placeholder-slider .slider-item {
    -webkit-transform: scale(0.92);
    transform: scale(0.92);
}
}


@media screen and (min-width: 960px){
.carousel-container .items.placeholder-slider .slider-item.active {
    -webkit-transform: scale(1.05);
    transform: scale(1.05);
}
}

img {
    display: table;
    max-width: 100%;
    object-fit: cover;
    margin: 0 auto;
}

.carousel-container__slide__content {
    width: 100%;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: pointer;
}

@media screen and (min-width: 769px), print{
.carousel-container__slide__content {
    border-radius: 16px;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script>
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>vue.js carousel</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="app">
  <section class="slide-placeholder">
      <div class="slide-placeholder__carousel-container">
          <div class="carousel-container__background" :style="'background-image: url(' + carousels[show].img + ')'"></div>
            <div class="custom__container">
                <div class="carousel-container" ref="carousel" data-auto="true" data-delay="1500000" @mouseenter.stop="toggleTimer = false" @mouseleave.stop="toggleTimer = true" @touchstart.stop="touchStart" @touchmove.stop="touchMove" :style="'min-height:' + minHeight ">
                  <keep-alive>
                    <transition :name="carouselName">
                      <div class="items placeholder-slider" v-for="(s, i) in carousels" v-if="show == i" :key="i">
                            <div class="slider-item active">
                                <div class="carousel-container__slide">
                                  <a :href="s.href">
                                      <img :src="s.img" class="carousel-container__slide__content">
                                  </a>
                                </div>
                            </div>
                      </div>
                    </transition>
                  </keep-alive>
                  <a class="button-prev" href="#" @click.prevent="toPrev" style="color: white; text-decoration:none; font-size:50px">
                      <
                  </a>
                  <a class="button-next" href="#" @click.prevent="toNext" style="color: white; text-decoration:none; font-size:50px">
                      >
                  </a>
                  <div class="dot-group"><a v-for="(l, i) in len" href="#" :class="{ 'active': show == i }" @click.prevent="show = i"></a></div>
                </div>
            </div>
    </div>
  </section>
</div>
</body>
</html>

How to properly install a Pinia Store?

I’m building a Vue app using the OptionsAPI along with a Pinia Store but I frequently run into an issue stating that I’m trying to access the store before createPinia() is called.

I’ve been following the documentation to use the Pinia store outside components as well, but maybe I’m not doing something the proper way.

Situation is as follows:

I have a login screen (/login) where I have a Cognito session manager, I click a link, go through Cognito’s signup process, and then get redirected to a home route (/), in this route I also have a subroute that shows a Dashboard component where I make an API call.

On the Home component I call the store using useMainStore() and then update the state with information that came on the URL once I got redirected from Cognito, and then I want to use some of the state information in the API calls inside Dashboard.

This is my Home component, which works fine by itself, due to having const store = useMainStore(); inside the mounted() hook which I imagine is always called after the Pinia instance is created.

<template>
  <div class="home">
    <router-view></router-view>
  </div>
</template>

<script>
import {useMainStore} from '../store/index'

export default {
  name: 'Home',
  components: {
  },
  mounted() {
    const store = useMainStore();

    const paramValues = {}

    const payload = {
      // I construct an object with the properties I need from paramValues
    }

    store.updateTokens(payload); // I save the values in the store
  },
}
</script>

Now this is my Dashboard component:

<script>
import axios from 'axios'
import {useMainStore} from '../store/index'

const store = useMainStore();

export default {
    name: "Dashboard",
    data() {
    return {
        user_data: null,
      }
  },
  mounted() {
    axios({
      url: 'myAPIUrl',
      headers: { 'Authorization': `${store.token_type} ${store.access_token}`}
    }).then(response => {
      this.user_data = response.data;
    }).catch(error => {
      console.log(error);
    })
  },
}
</script>

The above component will fail, and throw an error stating that I’m trying to access the store before the instance is created, I can solve this just by moving the store declaration inside the mounted() hook as before, but what if I want to use the store in other ways inside the component and not just in the mounted hook? And also, why is this failing? By this point, since the Home component already had access to the store, shouldn’t the Dashboard component, which is inside a child route inside Home have the store instance already created?

Why does my use state does not update even after using prevState? Is useEffect the only way?

I understand useState does not update instantly. Some of the tutorial videos on react shows use of callback function as a way to achieve the result for immediate update. I tried that but it doesnt seem working .attaching the sample code

import { useState } from "react";
const testComponent = () => {
    const [userInputs, setUserInputs] = useState({
        age: '',
        comments: ''
    })

    function commentInputHandler(event) {
        setUserInputs((prevState) => {
            return {
                ...prevState,
                comments: event.target.value
            }
        })
        console.log(userInputs.comments)
    }
    render(
        <textarea onChange={commentInputHandler} className="form-control" required ></textarea>
    )
}

Change WordPress Menu Based on Customer Location with Cloudflare Worker

I am attempting to change the WordPress Menu based on Viewer Location using cloudflare workers. Here is a simple method to do this in functions.php: https://gist.github.com/timersys/1eaa6ed10e2dea0e9a972733acd3ded0

My Goal is to write something similar as such:

    addEventListener('fetch', event => {
        event.passThroughOnException()
        event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest(request) {
        const country = request.cf.country
        if (country != 'US' && country !='CA') {
    
        CHANGE MENU

}

    
        // return modified response
         return new Response(html, response) 
    }

Local HTML+Local JSON security

I have an application that generates a JSON file. It is to be consumed by a local HTML/JS file. My experience and google/StackOverflow seem to indicate the following:

  • This is easy when wrapping this into a Javascript assignment and just use <script src>. This works just fine.
  • For security reasons, we can not read JSON directly from a local file (e.g. using require, or d3.json, using Chrome).

I don’t understand the difference between these two methods w.r.t. security. I would have expected both to work, or neither. Am I missing something?

How to detect left mouse slicking

I have a problem that i couldn’t find a single working way to detect if left mouse button is being pressed, I use visualstudio but i dont know is it a bug in the studio that javascript doesn’t work or are people just bad at giving answers.

Props not passing in dynamic URL – TypeError React.js

I am trying to pass props to a component, Location, using React router as a url parameter, however I am getting a type error because props.match.params.location is undefined. I am passing the location in the url Link of the Locations component and when I click on this link in the browser, it redirects to the correct url with the correct parameter:

http://localhost:3000/locations/tokyo

However this is triggering this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'params')
at Location (Location.js:10:1)

App.js:

class App extends React.Component {

render() {
    return (
        <div className="App">
            <AppNavbar />
            <Routes>
                <Route path="/" element={<Dashboard />} />
                <Route path="/stock-levels" element={<StockLevels />} />
                <Route path="/locations" element={<Locations />} />
                <Route path="/locations/:location" element={<Location />} />
            </Routes>
        </div>
    )
}

}

export default App;

Locations.js:

import {Link} from "react-router-dom";

function Locations() {

const locations = ["tokyo", "location2", "location3", "location4", "location5", "location6", "location7", "location8"]

const locationList = locations.map(location => {
    return <div className="location-container">
        <Card className="location-card">

            <CardTitle><Link to={`/locations/${location}`}>{location}</Link></CardTitle>
        </Card>
    </div>
})

return (
    <>
      <h1>Locations</h1>

        {locationList}

    </>
)

}

export default Locations

Location.js:

function Location(props) {

//Make location equal to the location passed via route
const location = props.match.params.location

return (
    <>
        <h1>Location</h1>
        <h2>{location}</h2>
    </>
)

}

export default Location

As far as I can tell, with how the routes are configured and the link url:

<Link to={`/locations/${location}`}>

This should be passed as props.

Thanks for any help!

Using a prisma query with callback seems to ignore try/catch blocks (Node)

I have this piece of code (the error handler is taken from the prisma docs):

try {
    prisma.daRevisionare.create({ data: { "idTweet": tweet.id, "testo": testotweet, url } }).then((dati) => {
      bot.sendMessage(chatId, testotweet, { "reply_markup": { "inline_keyboard": [[{ "text": "Aggiungi", "callback_data": `si,${dati.id}` }], [{ "text": "Scarta", "callback_data": `no,${dati.id}` }]] } })
    })
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError) {
      if (e.code === 'P2002') {
        console.log(
          'There is a unique constraint violation, a new user cannot be created with this email'
        )
      }
    }
  }

The try/catch block should in theory prevent the application from crashing when a unique constraint is violated, but when I try to trigger the error the application just crash:

  45 try {
→ 46   prisma.daRevisionare.create(
  Unique constraint failed on the constraint: `daRevisionare_idTweet_key`
    at cb (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:38703:17)
    at async PrismaClient._request (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:40853:18) {
  code: 'P2002',
  clientVersion: '3.9.1',
  meta: { target: 'daRevisionare_idTweet_key' }
}

it seems to completely ignore the try/catch block, how can I solve this?

Prisma.io equivalent of Mongoose isModified method

Just wondering if there is something in Prisma equivalent to the Mongoose isModified method
to be used in Prisma middleware

prisma.$use(async (params, next) => {

if (params.model == 'User' && params.action == 'create') {
   // check if password modified
    params.args.data.password = await bcrypt.hash(params.args.data.password, 10);

   }

   return next(params);
});

Thanks

Make Folium map interactible from page where it’s embedded

I’m working on an app that uses ReactJS for front end.

I’m using Folium to generate different kind of maps (choropleth / heatmap / markercluster).

My goal is to be able to control some features of the map from the other components of the app (for instance highlighting markers or area when they’re selected in a form).

I first tried to retrieve the map id in my app’s main JS code, but I realised that Folium renders maps into iframes which prevents to add any interactivity with the rest of the app.
I hoped I it was possible to render Folium map outside a Branca figure which seems to add the iframe, but it doesn’t seem to work and would be just an ugly hack anyway.

I guess I’m not the first willing to achieve something like this, but I was unable to find any solution.

How could I achieve what I’m trying to do ? Thanks.

How can I make live input update for cart on popover?

I am trying to make live input updating popover in my ecommerce site. It’s something like that I’ll give input on add cart option and popover will be able refresh and show current value. Everything is working fine except live update in popover. popover showing old value.
I am using bootstrap5.

function updateCart(cart) {
            
            for (var item in cart) {
                document.getElementById('div' + item).innerHTML = "<button id='minus" + item + "'class='btn btn-primary minus'>-</button> <span id='val" + item + "''>" + cart[item] + "</span> <button id='plus" + item + "' class='btn btn-primary plus'> + </button>";
            }
            localStorage.setItem('cart', JSON.stringify(cart));
            document.getElementById('cart').innerHTML = Object.keys(cart).length;
            console.log(cart);
            updatePopover(cart);
        }
        // if plus or minus button is clicked, change the cart as well as the diplay value

        // For plus
        $('.divpr').on("click", "button.plus", function () {
            b = this.id.slice(6,)
            cart['pr' + b] = cart['pr' + b] + 1
            document.getElementById('valpr' + b).innerHTML = cart['pr' + b]
            updateCart(cart)
        });

        // For minus
        $('.divpr').on("click", "button.minus", function () {
            a = this.id.slice(7,)
            cart['pr' + a] = cart['pr' + a] - 1
            cart['pr' + a] = Math.max(0, cart['pr' + a]);
            document.getElementById('valpr' + a).innerHTML = cart['pr' + a]
            updateCart(cart)

        });
 function updatePopover(cart) {
            console.log('we are inside udatePopover');
            var popStr = "";
            popStr = popStr + "<h5> Your selected Items </h5><div class=' mx-2 my-2'>";
            var i = 1;
            for (var item in cart) {
                popStr = popStr + "<b>" + i + "</b>. ";
                popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0,15)+"..." + " Qty: " + cart[item] + '<br>'
                i = i + 1;
            };
            popStr = popStr + "</div>"
            console.log(popStr);
            document.querySelector('[data-id="popcart"]').setAttribute('data-bs-content', popStr);
            var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-id="popcart"]'))
            var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
                return new bootstrap.Popover(popoverTriggerEl,

                    {
                        html: true
                    })
            });

        }
        updatePopover(cart);

Vuetify radio button show/hide section

I am working on radio buttons with vuetify. I have two radio buttons, I need to hide one when the other is checked and show both when I click on toggleChangeOption button. The below is an illustration of my code.

What do I need to change in my code:

<v-radio-group v-model="options">
<div v-show="isFocus" :class="{focus: isFocus, 'display-options': showAll}">
  <v-radio 
  label="radio 1" 
  value="radio 1"
  @click="showOne"
  ></v-radio>
  <v-btn v-show="isActive" :class="{active: isActive}" @click="toggleChangeOption">
    Change
  </v-btn>
</div>
<div v-show="isFocus" :class="{focus: isFocus, 'display-options': showAll}">
  <v-radio label="radio 2" value="radio 2" @click="showTwo"></v-radio>
  <v-btn v-show="isActive" :class="{active: isActive}" @click="toggleChangeOption">
    Change
  </v-btn>
</div>
</v-radio-group>

My script

<script>
export default {
 data () {
    return {
     options: null,
     isActive: false,
     isFocus: false,
     showAll: false,
     showOne: true
     showTwo: true
    }
  },
  methods: {
   showOne(){
      this.isFocus = false
      this.isActive = true
      this.showTwo = false
   },
   showTwo(){
      this.showOne = false
      this.showAll = true
    },
    toggleChangeOption(){
      this.showOne = true
      this.showTwo = true
      this.showAll = false
    }
  }
};
</script>

The css

<style>
.active {
  display: block;
}

.display-options {
  display: none;
}
</style>

How to format a number to a specific format if it is too big or too small with a built in function

I already know about the function toExponential, which convert a number to a scientific notation. But I am wondering if another built-in function exists, that formats a number if it is too big or too small (in other words, if the number of digits is too much) . For instance, this function takes 2 arguments: a number, and a length. If the number length is higher than the length, the number is formated, otherwise, it is not.

func(12,2) // Should print 12, because the length of 12 is not bigger than 2
func(12,1) // Should print 1.2e1, because the length of 12 is bigger than 1
func(0.012,2) // Should print 1.2e-2 since the length of 0.012 is bigger than 2

This function should look like this aproximately:

const formatNumber = (num:number,digits:number):number =>{
  const length = num.toString().length
  return length>digits? num.toExponential(1): num
}

But I am not able to find such a function. Does it exist? If not, then I can still continue to use the one that I created, but I was just wondering if there is a more “official” function for doing this.

ResizeObserver not being triggered when content height changes (React)

It works when I manually resize the window, but not when the content height changes which is what I need.

Am I doing something wrong?

class MainContainer extends React.Component {
  constructor(props) {
    super(props);
    this.containerRef = React.createRef();
    this.containerObserver = null;
    this.state = {
      top: false,
    };
  }

  componentDidMount() {
    this.containerObserver = new ResizeObserver((e) => this.handleResize(e));
    this.containerObserver.observe(this.containerRef.current);
  }

  componentWillUnmount() {
    if (this.containerObserver) {
      this.containerObserver.disconnect();
    }
  }

  handleResize = (e) => {
    const { target } = e[0];

    const top = target.scrollTop;
    const scrollHeight = target.scrollHeight;
    const position = scrollHeight - top;
    const clientHeight = target.clientHeight;

    console.log({ top }, { scrollHeight }, { position }, { clientHeight });

    if (top < 10) {
      if (this.state.top) {
        this.setState({ top: false });
      }
    } else {
      if (!this.state.top) {
        this.setState({ top: true });
      }
    }

    if (position >= clientHeight - 40 && position <= clientHeight) {
      if (!this.state.top) {
        this.setState({ top: true });
      }
    }
  };

  render() {
    return (
      <React.Fragment>
        <Container ref={this.containerRef} onScroll={this.handleScroll}>
          <Body />
        </Container>
        <ShadowTop show={this.state.top} />
      </React.Fragment>
    );
  }
}

export const Container = styled.div`
  @media (max-width: 760px) {
    position: absolute;
  }

  margin-top: ${({ theme }) => theme.header.height.percent}%;
  margin-top: -webkit-calc(${({ theme }) => theme.header.height.pixel}px);
  margin-top: -moz-calc(${({ theme }) => theme.header.height.pixel}px);
  margin-top: calc(${({ theme }) => theme.header.height.pixel}px);

  height: ${({ theme }) => Math.abs(100 - theme.header.height.percent)}%;
  height: -webkit-calc(100% - ${({ theme }) => theme.header.height.pixel}px);
  height: -moz-calc(100% - ${({ theme }) => theme.header.height.pixel}px);
  height: calc(100% - ${({ theme }) => theme.header.height.pixel}px);

  position: fixed;
  float: none;
  clear: both;
  top: 0;
  right: 0;

  width: ${({ theme }) => 100 - theme.sidebar.width.percent}%;
  width: -webkit-calc(100% - ${({ theme }) => theme.sidebar.width.pixel}px);
  width: -moz-calc(100% - ${({ theme }) => theme.sidebar.width.pixel}px);
  width: calc(100% - ${({ theme }) => theme.sidebar.width.pixel}px);


  z-index: 2;
  pointer-events: auto;
  overflow: auto;
`;