VueUse OnClickOutside ignore options not working

i’m using OnClickOutside from VueUse, the vue code is:

<template>
  <button class="button" id="button1" ref="tempRef">AAA</button>
  <OnClickOutside id="clickOutside" :options="{ ignore: [tempRef] }" @trigger="console.log(tempRef)">
    <button class="button" id="button2">BBB</button>
  </OnClickOutside>
</template>

<script setup>
import { OnClickOutside } from '@vueuse/components'
import { ref } from 'vue'

const tempRef = ref()
</script>

So, my expectation is, when I click button1, the OnClickOutside won’t be triggered since tempRef is inside the ignore.
But, it turns out, the console still output tempRef when I clicked button1. I’ve tried some adjustments but nothing works.
Do I misunderstand how to use ignore in OnClickOutside? How to fix this? Thx for the help

Here is the documentation for easy access: https://vueuse.org/core/onClickOutside/

How to get Bootstrap 5.3.x DropDown functioning correctly

In a Blazor website, I’ve tried the bootstrap 5.3.x dropdown sample code, and it doesn’t function in my site at all. I have the bootstrap css and js in my _Host.cshtml (one in the head, the other just before the body close), and I’ve copy/pasted their sample code directly. It doesn’t work at all. In order to make the dropdown open, I had to include ids on both the drop down toggle button and on the container it would open, a data-bs-target on the button that pointed to the container, and change the data-bs-toggle="dropdown" to data-bs-toggle="collapse".

The following failed to function (clicking the button did nothing at all):

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
    Dropdown button
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
  </ul>
</div>

but changing it to this actually worked:

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="collapse" aria-expanded="false" id="thing1" data-bs-target="thing2">
    Dropdown button
  </button>
  <ul class="dropdown-menu" id="thing2" aria-labelledby="thing1">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
  </ul>
</div>

So, great – it opens and closes, but this also means that their sample for auto-close doesn’t function for me either. I tried all 4 samples for auto-close, and none of them did a thing.

I’m hoping someone out there has run into, and sorted out, this same issue.

How to create/assign a variable from text in javascript

I have a file out on the web that I read in using https. The file has the following contents:

const myValues = [
    { value: 0, text: "value 0" },
    { value: 1, text: "value 1" },
    { value: 2, text: "value 2" },
    { value: 3, text: "value 3" }]

Once I get that data to my app, I can print it out fine using console.log(res.data)
What I need to do is assign those values to a variable in my code for use later to populate a drop-down list. I can find examples on how to read a local file and do it but I can’t seem to get it to work if I just want to create a variable with the contents of the http request. Thanks in advance

I’ve tried hacking up the examples using fetch and other methods but again, they seem to rely on having a local file where I’m currently reading a file using https and I just have the text data in the result.data portion of the response.

Where can I find information and documentation on how to create “Custom scheduling” in Anki?

I don’t like the standard behavior of anki. It is annoying to change the “ease” level and its STRONG effect on the result of the response buttons. I would like to do my own “Custom scheduling”. A simple schedule where only the answer buttons affect the change of intervals, without the influence of the “ease” levels of the cards.

But I can’t find documentation and educational information on this topic in any way.

I’ve been looking for a long time. That’s all I found:

As far as I understand, the list of rpc requests. With minimal explanations.
https://github.com/ankitects/anki/blob/main/proto/anki/scheduler.proto
https://github.com/ankitects/anki/blob/main/proto/anki/ankidroid.proto

An example of the implementation of a third-party fsrs4anki schedule. For some reasons, there are much more explanations in code than in the examples above.
https://github.com/open-spaced-repetition/fsrs4anki

Most likely, I will have to look for more examples of someone else’s code for “Custom scheduling”. And to figure it out through experiments.

Remove items from a list by equal quantity in JS [closed]

let a = [1, 1, 1, 2];
let b = [{id: 1}, {id: 1}, {id: 4}, {id: 1}, {id: 2}, {id: 3}, {id: 1}];

// [true, true, false, true, true, false, false]
result = [{id: 1}, {id: 3}, {id: 4}]

In other words, if there are 3 instances of the number 1 in list ‘a’ and there are 4 instances of the number 1 in list ‘b’, then 3 instances will be excluded, and so on.

What would be a way to solve this? I’ve tried several codes and couldn’t succeed.

Jest – Cannot find module ‘@lib/components’ from ‘src/components/MyComponent.test.tsx’

I’m using a third-party component library called @lib/components, and i tried to write a test MyComponent.test.tsx like so:

import * as ComponentsLib from '@lib/components';

const setup = () => {
  const view = render(<MyComponent />);

  return { view };
};

jest
  .spyOn(ComponentsLib, 'Comp1')
  .mockImplementation(() => (
    <div data-testid='test'>{'test'}</div>
  ));

it('renders', () => {
  setup();
  expect(screen.queryByTestId('test')).toBeTruthy();
});

However, i’m getting the following error:
Cannot find module '@lib/components' from 'src/components/MyComponent.test.tsx'

How could then i mock the implementation of Comp1 from that component library?

AppwriteException: Invalid query:

Here I am trying to run this query and it is giving me error. I don’t understand why it is a bad request. I am trying to get the specific user from the database using accountId. Please help

This is the function to call the get current user

export async function getCurrentUser() {
  try {
    const currentAccount = await account.get();

    if (!currentAccount) throw Error;
    const currentUser = await databases.listDocuments(
      appwriteConfig.databaseId,
      appwriteConfig.userCollectionId,
      [Query.equal("accountId", [currentAccount.$id])]
    );
    console.log(currentUser);

    if (!currentUser) throw Error;
    return currentUser.documents[0];
  } catch (error) {
    console.log("from getCurrentUser");
    console.log(error);
  }
}

**this specific line is not executing **

[Query.equal("accountId", [currentAccount.$id])]

**this is the error **
Error message

this is the response
request response with the query

note that without [Query.equal(“accountId”, [currentAccount.$id])] this line the request is working fine. giving me response of

without the query

please help!

Need help to identify Gamepad

I am developing a game in JS and I am trying to identify what type of gamepad is connected to the computer (XBox or PS or Switch) to display the correct icons. With the Gamepad API in JS it seems that the id property of a gamepad object would allow this to be done. But the syntax is nowhere to be explained. And what you could test if you have a gamepad, tell me what yours is with your browser and the type of gamepad you have.
navigator.getGamepads();
allows you to get the Gampads connected
THANKS

ref not available in HTMLAttributes

I have a reusable wrapper component which like this:

import { FC, HTMLAttributes } from "react";

const Wrapper: FC<HTMLAttributes<HTMLDivElement>> = ({
  children,
  className,
  ...props
}) => (
  <div className={`h-[90vh] ${className ? className : ""}`} {...props}>
    {children}
  </div>
);

export default Wrapper;

But I can’t add the ref prop to the component.

<Wrapper ref={ref} ...

Property 'ref' does not exist on type 'IntrinsicAttributes & HTMLAttributes<HTMLInputElement>'.

What typescript type should I use for the Wrapper component and add the ref prop without an error?

Cannot implement JWT authorization in `hapi.js`

I am interested in incorporating the JWT strategy into the backend of my Hapi.js application to enhance security measures and improve authentication processes. here is my server code :

const Hapi = require('@hapi/hapi');
const Joi = require('joi');
const Inert = require('inert');
const Vision = require('vision');
const HapiSwaggered = require('hapi-swaggered');
const HapiSwaggeredUI = require('hapi-swaggered-ui');
const knexConfig = require('./knexfile.js')
const knex = require('knex')(knexConfig.development)
const Jwt = require('@hapi/jwt')

const init = async () => {
    const server = Hapi.Server({
        port: 4545,
        host: 'localhost',
        "routes": {
          "cors": {
              "origin": ["*"],
              "headers": ["Accept", "Content-Type"],
              "additionalHeaders": ["X-Requested-With"]
          }
      }
    });



    server.ext('onPreResponse', (request, h) => {
      const response = request.response;
      if (response.isBoom) {
          // Error response, add CORS headers
          response.output.headers['Access-Control-Allow-Origin'] = 'https://hapi.dev';
          response.output.headers['Access-Control-Allow-Header'] = '*';

        } else {
          // Non-error response, add CORS headers
          response.headers['Access-Control-Allow-Origin'] = 'https://hapi.dev';
          response.headers['Access-Control-Allow-Headers'] = '*';

      }
      return h.continue;
    });

    await server.register(Jwt)



    server.auth.strategy('my_jwt_strategy', 'jwt', {
      keys: 'some_shared_secret',
      verify: {
          aud: 'urn:audience:test',
          iss: 'urn:issuer:test',
          sub: false,
          nbf: true,
          exp: true,
          maxAgeSec: 14400, // 4 hours
          timeSkewSec: 15
      },
      validate: (artifacts, request, h) => {
        console.log('Validation: Start');
        console.log('Decoded JWT:', artifacts.decoded);

        // Your validation logic here...

        console.log('Validation: End');

        return { isValid: true }; // Replace with your actual validation result
      }
    
    });




    server.auth.default('my_jwt_strategy');

    server.route({
        method: 'POST',
        path: '/login',
        handler: async (request, h) => {
            // Replace this logic with actual user authentication
            const { username, password } = request.payload;
            if (username === 'exampleUser' && password === 'examplePassword') {
                // Generate JWT token upon successful authentication
                const token = Jwt.token.generate({ user: username }, 'some_shared_secret');
                return { token };
            } else {
                return h.response({ message: 'Invalid credentials' }).code(401);
            }
        },
        options: {
          auth: false
        }
    });

    server.route({
        method: 'POST',
        path: '/register',
        handler: async (request, h) => {
            console.log('requested !')
            // Replace this logic with actual user registration
            const { username, password } = request.payload;
            // Implement user registration logic here, such as saving user to database
            
            // Generate JWT token upon successful registration
            const token = Jwt.token.generate({ user: username }, 'some_shared_secret');
            console.log(token)
            return { token };
        },
        options: {
          auth: false,
          cors: {
            origin: ['*'],
            headers: ['*'],
            credentials: true
          }
        }
    });

    server.route({
      method: 'GET',
      path: '/',
      handler: (request, h) => {
          const headers = request.headers;
          console.log('Request Headers:', headers);
          return 'Hello, World!';
      }
    });



    await server.register([require('./posts/posts_list'), 
                          require('./posts/posts_insert')]);
    await server.register([
        Inert,
        Vision,
        {
          plugin: HapiSwaggered,
          options: {
            info: {
              title: 'Test API Documentation',
              version: '1.0.0',
            },
          },
        },
        {
          plugin: HapiSwaggeredUI,
          options: {
            title: 'Swagger UI',
            path: '/docs', 
          },
        },
      ]);
       

    await server.start();
    console.log('Server started on port 4545 !');
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

First I make a register request and get a token like this:

await fetch('http://localhost:4545/register', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({username: 'balbalsbd', password: 'asdasdada'})
})
.then(response => {
    if (response.ok) {
        return response.json();
    } else {
        return Promise.reject({ status: response.status, message: response.statusText });
    }
})
.then(data => {
    console.log('Registration successful:', data);
})
.catch(error => {
    console.error('Registration failed:', error);
});

After that, with this token in hand, I proceeded to send a request via the console to the route / in order to examine the functionality of JWT, however, I was met with a 401 error code.

await fetch('http://localhost:4545/', {
    method: 'GET',
    headers: {
        'Authorization': `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYXNkc2QiLCJpYXQiOjE3MTExMTM5OTR9.5xND-Cp6G8w89R9Qpc6lWpVzf9CQ9lNM3mCk9EURYhw`
    }
})
.then(response => {
    if (response.ok) {
        return response.json();
    } else {
        return Promise.reject({ status: response.status, message: response.statusText });
    }
})
.then(data => {
    console.log('Response:', data);
})
.catch(error => {
    console.error('Error:', error);
});

convert ref from class based component to functional component

I have a codepen i am working on https://codepen.io/a166617/pen/MWRmvLO?editors=1111
the only problem with this implementation is that it is class based component in the codepen and i need to use it as a functional component.

i have converted most of the part but i am stuck at the part where ref is used.
for e.g. Inside the bodyClick function, it give an error Property 'contains' does not exist on type 'MutableRefObject<null>'

There are 2 other errors in the html syntax
for e.g. on this line ref={(el) => { buttonRef = el; }}, it throws an error Cannot assign to 'buttonRef' because it is a constant. Similar error shows on <div ref={(el) => { tipContentRef = el; }} className="controlled-example">

Can someone help me on this whether i am doing anything wrong in assigning those refrences.

Here is the class based component

class SaveDefaultTab extends React.Component {
  constructor(props) {
    super(props);

    this.state = { tipOpen: false };

    this.toggleTip = this.toggleTip.bind(this);
    this.bodyClick = this.bodyClick.bind(this);
    this.saveDefault = this.saveDefault.bind(this);
  }
  

  componentDidMount() {
    document.addEventListener('mousedown', this.bodyClick);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.bodyClick);
  }

  tipContentRef;

  buttonRef;

  toggleTip() {
    this.setState(prevState => ({ tipOpen: !prevState.tipOpen }));
  }

saveDefault() {
   console.log('save default')
  this.setState(prevState => ({ tipOpen: !prevState.tipOpen }));
  }

  bodyClick(e) {
    if ((this.tipContentRef && this.tipContentRef.contains(e.target)) || this.buttonRef.contains(e.target)) {
      return;
    }

    this.setState({ tipOpen: false });
  }
  
  render() {
    const { tipOpen } = this.state;
    return (
      <div className="wrapper">
        <section style={{ marginTop: '5%'}}>

          <button className="hide-button"
            ref={(el) => { this.buttonRef = el; }}
            onClick={this.toggleTip}
          >
            <div class="test"></div>
          </button>
          <Tooltip
            content={(
              <div ref={(el) => { this.tipContentRef = el; }} className="controlled-example">
                <div 
                  onClick={this.saveDefault}
                  className="controlled-example_header">
                  Save as Default
                </div>
              </div>
            )}
            isOpen={tipOpen}
            tagName="span"
            direction="right"
            forceDirection
          >
          </Tooltip>
        </section>
     </div>
    );
  }
}



Here is the functional component i have worked on

import { useState, useEffect, useRef } from "react";
import Tooltip from "react-tooltip-lite";

const SelectDefualtTab = (props: any) => {
  const [tipOpen, setTipOpen] = useState(false)
  const tipContentRef = useRef(null);
  const buttonRef = useRef(null);
  const toggleTip = () => {
    setTipOpen(!tipOpen)
  }

  const saveDefault = () => {
    console.log('save default')
   setTipOpen(!tipOpen)
   }
    
   const bodyClick = (e) => {
    if ((tipContentRef && tipContentRef.contains(e.target)) || buttonRef.contains(e.target)) {
      return;
    }
    setTipOpen(false)
  }
   useEffect(() => {
    document.addEventListener('mousedown', bodyClick);
    return () => {
        document.removeEventListener('mousedown', bodyClick);
    };
  }, []);

  return (
    
    <div className="wrapper">
        <section style={{ marginTop: '5%'}}>

          <button className="hide-button"
            ref={(el) => { buttonRef = el; }}
            onClick={toggleTip}
          >
            <span className="select-default-tab"></span>
          </button>
          <Tooltip
            content={(
              <div ref={(el) => { tipContentRef = el; }} className="controlled-example">
                <div 
                  onClick={saveDefault}
                  className="controlled-example_header">
                  Save as Default
                </div>
              </div>
            )}
            isOpen={tipOpen}
            tagName="span"
            direction="right"
            forceDirection
          >
          </Tooltip>
        </section>
     </div>
  );
};

Trying to consume API data from Django backend to React

I am trying to consume the Bing web search api. I have my view setup in Django backend. I was able to retrieve the search result data in terminal. But I am getting an error when fetching the data in React. If you could please help with a detailed response it would be much appreciated! Thanks in advance.

Django runserver terminal when refreshing React page:

  
                         'name': 'iPhone 13 review | Tom&#39;s Guide',
                         'noCache': False,
                         'primaryImageOfPage': {'height': 80,
                                                'imageId': 'OIP.63KzaXCF-d8nPkQdmM6bWgHaDL',
                                                'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1',
                                                'width': 80},
                         'snippet': 'The<b> iPhone 13</b> is a great '
                                    'budget-friendly flagship phone with a '
                                    'brighter display, longer battery life and '
                                    'powerful cameras. Read our in-depth '
                                    'review to find out its strengths and '
                                    'weaknesses, and how it compares to the '
                                    'iPhone 14 and other models.',
                         'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1',
                         'url': 'https://www.tomsguide.com/reviews/iphone-13'}],
              'webSearchUrl': 'https://www.bing.com/search?q=iphone+13'}}
Internal Server Error: /home/
Traceback (most recent call last):
  File "C:UsersstormAppDataLocalProgramsPythonPython310libsite-packagesdjangocorehandlersexception.py", line 55, in inner
    response = get_response(request)
  File "C:UsersstormAppDataLocalProgramsPythonPython310libsite-packagesdjangoutilsdeprecation.py", line 136, in __call__
    response = self.process_response(request, response)
  File "C:UsersstormAppDataLocalProgramsPythonPython310libsite-packagesdjangomiddlewareclickjacking.py", line 27, in process_response
    if response.get("X-Frame-Options") is not None:
AttributeError: 'list' object has no attribute 'get'
[22/Mar/2024 14:15:37] "GET /home/ HTTP/1.1" 500 72597

SearchResults.js React file:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const SearchResults = () => {
const [data, setData] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get(`http://localhost:8000/home/`);
    
                setData(response.data);
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        };
    
        fetchData();
    }, []);
    
    return (
        <div>
            <h1>My Component</h1>
            {data ? (
                <ul>
                    {data.map((item) => (
                        <li key={item.id}>{item.name}</li>
                    ))}
                </ul>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );

};

export default SearchResults;

views.py inside of bing_api (app folder):

def home(request):
  url = 'https://api.bing.microsoft.com/v7.0/search'
  search_url = "https://api.bing.microsoft.com/v7.0/search"
  search_term = 'iphone 13'

  headers = {"Ocp-Apim-Subscription-Key": API_KEY}
  params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"}
  response = requests.get(search_url, headers=headers, params=params)
  response.raise_for_status()
  search_results = response.json()
  data = response.json()
  pprint(data)

  #below is to view in React
  pages = search_results['webPages']
  results = pages['value']
  # pprint(results[0])
  return results

url.py folder:

from django.urls import path
from . import views

urlpatterns = [
path('home/', views.home, name='home'),
]

How to auto select item from Fluent UI Dropdown

i am trying to make fluent UI dropdown component i want i have one button when i click on it so my any one item automatic select from dropdown and show in the dropdown input. automatic populate option let suppose now i when click on button i have set selected item “ASIFMA Committees” need to show in dropdown input and also show in in list as selected here is my code

import * as React from "react";
import { Button, Dropdown, makeStyles, Option, shorthands, useId } from "@fluentui/react-components";

const useStyles = makeStyles({
  root: {
    display: "grid",
    gridTemplateRows: "repeat(1fr)",
    justifyItems: "start",
    ...shorthands.gap("2px"),
    maxWidth: "400px",
  },
});

const CustomDropdown = () => {
  const dropdownId = useId("dropdown-default");
  const options = [
    {
      Name: "Advisory Councils",
      CommitteeCode: null,
      DivisionCode: "LEGCOMPLL",
    },
    {
      Name: "ASIFMA Committees",
      CommitteeCode: null,
      DivisionCode: "CAPMARK",
    },
    // Add the rest of your API response here
  ];

  const styles = useStyles();
  const [selectedItems, setSelectedItems] = React.useState([]);
  const [selectedText, setSelectedText] = React.useState("ASIFMA Committees");

  const handleOptionSelect = (event, data) => {
    const selectedOption = data.optionValue;
    const selectedOptionText = options.find((option) => option.DivisionCode === selectedOption)?.Name || "";
    setSelectedText(selectedOptionText);

    if (selectedItems.includes(selectedOption)) {
      setSelectedItems(selectedItems.filter((item) => item !== selectedOption));
    } else {
      setSelectedItems([...selectedItems, selectedOption]);
    }
  };

  const setItem = () => {
    const asifmaOption = options.find((option) => option.Name === "Advisory Councils");
    if (asifmaOption) {
      setSelectedText(asifmaOption.Name); // Update the selected text
      handleOptionSelect(null, {
        optionValue: asifmaOption.DivisionCode,
        optionText: asifmaOption.Name,
        selectedOptions: [asifmaOption.DivisionCode],
      });
    }
  };

  return (
    <div className={styles.root}>
      <label id={dropdownId}>Select an option</label>
      <Dropdown
        aria-labelledby={dropdownId}
        placeholder="Select an option"
        onOptionSelect={handleOptionSelect}
        selectedOptions={selectedItems}
        defaultValue={selectedText}
        defaultSelectedOptions={[selectedText]}
        // text={selectedText} // Pass selectedText to the Dropdown component
      >
        {options.map((option, index) => (
          <Option key={index} value={option.DivisionCode}>
            {option.Name}
          </Option>
        ))}
      </Dropdown>
      <Button onClick={setItem}>Set Auto</Button>
    </div>
  );
};

export default CustomDropdown;

``` here is my code if anyone can help me


i want when i click on button automatic select item in dropdown.

How to store html5 data_atribute in php string

I have a form which includes:

<form>
    <select id = 'title'>
    <option value='Movie Name_1' data-production='USA' data-dur='120'> Movie Name_1</option>
    <option value='Movie Name_2' data-production='USA' data-dur='125'> Movie Name_2</option>
    <select>
    </form>

I need store this /data-dur=’120 or 125’/ in php string /without form posting/:
$movie_duration = ‘120’

<script>  
$("#title").on("change", function () {    
    var dur = $('option:selected', this).attr("data-dur");   
    $("#dur").val(dur);  or
    $("#dur").html(dur);
    });
</script> 

But i am not able to extract in string from div or input the value of data-dur.
I hope this is possible. I’ve looked around stackoverflow and google for an answer but could not find one for my purpose.