Create combinations of arrays with values from two arrays

I have two arrays with ids that have linked lengths. By linked lengths I mean that if ArrayA has length = 4 then ArrayB will have the length equal with (ArrayA.length * (ArrayA.length - 1)) / 2 (which means if ArrayA has length = 4 then ArrayB length = 6, if ArrayA has length = 5 then ArrayB length = 10 and so on).

So let’s say these are my arrays: ArrayA = [1, 2, 3, 4] and ArrayB = [a, b, c, d, e, f].

I have to create a new array of arrays based on the next logic:

enter image description here

In the end the new array should look as it follows, where the second parameter is a value from the first array and the third parameter is a value from the second array:

[
  [uuidv4(), 1, a],
  [uuidv4(), 2, a],
  [uuidv4(), 1, b],
  [uuidv4(), 3, b],
  [uuidv4(), 1, c],
  [uuidv4(), 4, c],
  [uuidv4(), 2, d],
  [uuidv4(), 3, d],
  [uuidv4(), 2, e],
  [uuidv4(), 4, e],
  [uuidv4(), 3, f],
  [uuidv4(), 4, f]
]

In the end, I should return this kind of array no matter the size of the arrays, but the arrays have some kind of linked length.

I can’t do this with a simple mapping because I don’t know how to achieve this kind of logic.

Thank you for your time! If something is unclear, I’ll try to explain better.

How can I upload image to API Vue.js

I create API project with add and edit product, I am trying to send a data from form vue cli to my api to save it in my api database and get the image to display it in my vue cli project.

I’m new to Vue.js and this is my input code

                <input
                  type="file"
                  name="image"
                  ref="file"
                  @change="getFile"
                  class="form-control"
                  placeholder="اختر صورة المنتج"
                />
export default {
  name: "addPro",
  data: function () {
    return {
      name: null,
      price: null,
      details: null,
      subject: null,
      file: null,
    };
  },
  methods: {
    getFile: function (event) {
      this.file = event.target.files[0].name;
      console.log(this.file)
    },
    addPro: function () {
      /* const formData = new FormData();
      formData.append("file", this.file); */
      axios
        .post("http://localhost:8000/api/add-product", {
          name: this.name,
          price: this.price,
          details: this.details,
          subject: this.subject,
          image: this.file,
        })
        .then((data) => console.log(data))
        .catch((err) => console.log(err));
    },
  },
  components: { Header, Footer },
};
</script>

This is how the data is stored, but the image is stored with its name and I don’t know if this is true, I want to store them so I can display them on another page

React Cookie doesn’t work with async response

Hello I am working on a React application (an e-commerce). I noticed that when I try loading all the product on a first render, it takes about 9 seconds (Load time is similar to what I got on Postman as well). However, I am trying to improve the load time by caching the data in a cookie so I decided to try out React-Cookie library. However, I noticed that when I tried to save the response data from my API call (asynchronous), My cookie doesn’t get set with the data but it works well with hard-coded synchronous value. I have looked through the React-cookies documentation and I couldn’t find any solution to this problem. Any suggestion or pointer to how this issue can be solved would be greatly appreciated. Thank you.This is for the async data This is for the hard-coded synchronous dataThis is the component where the two functions are called This is what is available in my browser cookie

JavaScript form Validation – textarea field to display an alert if no text has been entered

I can’t seem to target the textarea field in this function.

I’m essentially using HTML “required” validation for the first three input fields, but for the textarea, I simply want to display an alert if the textarea field is empty when the user submits the form.

Or possibly, I’d like to display text within the textarea field, stating “please enter more information”, if the user attempts to submit the form without filling that area in.

      <form action="" class="contactForm" method="POST" id="contactForm">
                        <label for="name">Name:</label>
                        <input type="text" id="name" name="name" required><br>
                        <label for="number">Number:</label>
                        <input type="number" id="number" name="number" required><br>
                        <label for="email">Email:</label>
                        <input type="email" id="email" name="email" required><br>
                        <textarea id= "textArea" rows ="3" cols ="23" name="finalMessage " form="contactForm" placeholder="Enter your fitness goals..."></textarea><br>
                        <button id="buttonID">Submit</button>
                    </form>

JavaScript


function formValidation(e) {
    e.preventDefault();
    const form = document.getElementById("contactForm");
    const textArea = document.getElementById("textArea").value;

    if(textArea.value === ""){
        alert("please enter more information");
    }

    document.getElementById("buttonID").addEventListener("click", function () {
        form.submit();
    });

} formValidation();

Creating a circular time left component

this is more of a general question, because it’s pretty hard to do and I don’t expect anyone to full code this for me, I’m just wondering if somebody have a starting point or an online tutorial(I couldn’t find any). Here is what I want to do:

enter image description here

I know how to do the logic of the no time left, but I can’t think of a proper way to animate those circles based on your time left. Can anybody can give me some direction?

unable to connect to the server

I am unable to connect to the server. when I try it will show this error

WebSocket connection to ‘wss://10.180.192.20:5905/’ failed:

createWebsocket @ worker.js:24
open

@ worker.js:52
(anonymous)

@ worker.js:80

I am trying to open this on a web page with url.

https://localhost:9999

I have self signed certificate for this to run.

I am trying to get amplifier data for a prgram from server to display on the above mentioned url through the iframe but it is not giving any display. Please help.

how to fetch items if any search keyword matched?

I have this document in my elastic DB.I am using this package
https://www.npmjs.com/package/@elastic/elasticsearch

I am searching on title.

I am doing like this.

const result= await client.search({
      index: 'products',
      "query": {
        "bool": {
          "should": [
            {
              "wildcard": { "title": "*" + search + "*" }
            }
          ],
          "minimum_should_match": 1
        }
      }

when I search “title” this issue . it give me one result but When I am seacrhing i have issue . it is giving zero or 0 result.why ? is it possible to fetch that data.issue keyword is present in first collection why it is not picking ?

[
  {
    "_index": "products",
    "_id": "wZRh3n8Bs9qQzO6fvTTS",
    "_score": 1.0,
    "_source": {
      "title": "laptop issues",
      "description": "laptop have issue present in according"
    }
  },
  {
    "_index": "products",
    "_id": "wpRh3n8Bs9qQzO6fvzQM",
    "_score": 1.0,
    "_source": {
      "title": "buy mobile",
      "description": "mobile is in Rs 250"
    }
  },
  {
    "_index": "products",
    "_id": "w5Rh3n8Bs9qQzO6fvzTz",
    "_score": 1.0,
    "_source": {
      "title": "laptop payment",
      "description": "laptop payment is given in any way"
    }
  }
]

how to search on keywords? any keyword match . I need to pick that whole colloection

How does transition work when rendering a component in React?

I have a div with adding a class by condition

        <div
          className={`${
            showLinks ? "links-container show-container" : "links-container"
          }`}
        >

And some styles

.links-container {
  height: 0;
  overflow: hidden;
  transition: all 0.3s linear;
}
.show-container {
  height: 10rem;
}

So when the component is render/rerender, a smooth div extension animation is triggered thanks to my transition style. How it works? Is this css or react rules?

Calling a javascript function with parameters in innerHTML

I’m trying to build my own comment system.

Here’s the code that show a comment box when clicking on the “Reply” button:

function postComment(i, parentId) {
    let content;
    if (parentId === undefined) {
        content = commentBox.value
    } else {
        content = eval("subCommentBox"+i).value
    }
    const body = JSON.stringify({
        "post_slug": location.pathname.slice(1),
        "username": "quantong",
        "parent_id": parentId,
        "content": content,
    })
    fetch("http://localhost:8080/comments", {
        method: "post",
        headers: { "Content-Type": "application/json" },
        body: body
    })
        .then(resp => {
            if (resp.status === 200) {
                return resp.json()
            } else {
                console.log("Status: " + resp.status)
            }
        })
    commentBox.value = "";
    window.location.reload();
}

let allElements = document.body.getElementsByClassName("replybtn");

let addCommentField = function () {
    for (let i = 0; i < allElements.length; i++) {
        if (allElements[i] === this) {
            if (document.getElementsByClassName("replyform")[i].innerHTML.length === 0) {
                document.getElementsByClassName("replyform")[i].innerHTML = `
                    <div class="form-group">
                        <textarea class="form-control" id="subCommentBox`+i+`" rows="3"></textarea>
                    </div>
                    <div class="d-flex flex-row-reverse">
                        <button type="button" class="btn btn-success" onclick="postComment(` + i + `, ` + allElements[i].id + `)">Comment</button>
                    </div>
                `
            }
        }
    }
};

It worked fine if I put in a .js file.

The thing is after use is logged in, I want to pass username and profile picture as a body to the backend side, so I moved it to App.svelte file:

    let commentBox;
    function postComment(i, parentId) {
        let content;
        if (parentId === undefined) {
            content = commentBox
        } else {
            content = eval("subCommentBox"+i).value
        }
        const body = JSON.stringify({
            "post_slug": location.pathname.slice(1),
            "image_url": responsePayload.picture,
            "username": responsePayload.name,
            "parent_id": parentId,
            "content": content},
        )
        fetch("http://localhost:8090/comments", {
            method: "post",
            headers: { "Content-Type": "application/json" },
            body: body
        })
            .then(resp => {
                if (resp.status === 200) {
                    return resp.json()
                } else {
                    console.log("Status: " + resp.status)
                }
            })
        commentBox = "";
        window.location.reload();
    }

If I leave the innerHTML text as it is, it caused:

Uncaught ReferenceError: postComment is not defined

If I change it from:

<button type="button" class="btn btn-success" onclick="postComment(` + i + `, ` + allElements[i].id + `)">Comment</button>

to:

<button type="button" class="btn btn-success" on:click={() => postComment(i, allElements[i].id)}>Comment</button>

it will be rendered as:

enter image description here

So, in a .svelte file, how can I call a javascript function with parameters in innerHTML?

Nested routing react-router-dom v6 not working

I am following this project. But I am stuck on converting the nested routed in version6 of react-router-dom.

In V5 it is as follows:

App.js

  return (
      <div>
        <Header />
        <Switch>
          <Route exact path='/' component={HomePage} />
          <Route path='/shop' component={ShopPage} />
          <Route exact path='/checkout' component={CheckoutPage} />
          <Route
            exact
            path='/signin'
            render={() =>
              this.props.currentUser ? (
                <Redirect to='/' />
              ) : (
                <SignInAndSignUpPage />
              )
            }
          />
        </Switch>
      </div>
    );

ShopPage

      const ShopPage = ({ match }) => (
  <div className='shop-page'>
    <Route exact path={`${match.path}`} component={CollectionsOverview} />
    <Route path={`${match.path}/:collectionId`} component={CollectionPage} />
  </div>
);

I want to convert it in V6 and I had tried as follows:

My App.js

return (
  <div >
    <Header />
    <Routes>
      <Route path='/' element={<HomePage />} />
      <Route path='/shop' element={<ShopPage />} />
        
      <Route path='/checkout' element={<CheckoutPage />} />
      <Route path='/signin' element={<>
        {this.props.currentUser ?
          <Navigate to="/" />
          :
          <SignInAndSignUpPage />

        }
      </>
      }

      />

      <Route path='/signin' element={this.props.user ? <Navigate to="/" /> : <SignInAndSignUpPage />} />
     

    </Routes>
  </div>
);

My Shopage

    const ShopPage = () => {
    let { pathname } = useLocation();

    console.log(pathname);
   
    return (
        <div className='shop-page'>
            <Routes>
                <Route path={`${pathname}`} element={<CollectionsOverview />} />
                <Route path={`${pathname}/:collectionId`} element={<CollectionItems />} />
            </Routes>
        </div>
    )
};

In pathname console log I am getting /shop but the items are not showing.
How can acheive nested routing in v6?

React : React children can’t recognize the props passed to it

I am trying to simply pass the props to my component but facing these warning, and it is not rendering properly.

Getting warning as:-

React does not recognize the `reactionsState` prop on a DOM element. If you intentionally 
want it to appear in the DOM as a custom attribute, spell it as lowercase 
`reactionsstate` instead. If you accidentally passed it from a parent component, remove
 it from the DOM element.

Same warning for setReactionsState and postId

ReactionsTab.tsx:

import axios from "axios";
import React, { Dispatch, SetStateAction, useEffect, useState } from "react";
import { Button, Tab } from "react-bootstrap";
import { useElementOnScreen } from "utils/hooks/useElementOnScreen";
import styles from "../styles/reactions.module.css";
import { ReactionListMainState, RenderTitle, UserListItemType } from "./ReactionsList";
import UserListItem from "./UserListItem";

type Props = {
  reactionsState: ReactionListMainState;
  setReactionsState: Dispatch<SetStateAction<ReactionListMainState>>;
  postId: number;
  eventKey: string | null;
};

export default function ReactionTab(props: Props) {
  const { reactionsState, setReactionsState, postId, eventKey, ...rest } = props;
  const [loading, setLoading] = useState(false);

  const [containerRef, isVisible] = useElementOnScreen({
    root: document.querySelector(`#reactionListModal${eventKey}`),
    rootMargin: "0px",
    threshold: 1.0,
  });
  useEffect(() => {
    if (isVisible) {
      console.log("isVisible");
      fetchMoreReactions(eventKey as string);
    }
  }, [isVisible]);
  const fetchMoreReactions = async (type: string) => {
    setLoading(true);
    const size = reactionsState.reactions[type].size;
    const page = reactionsState.reactions[type].number;
    if (reactionsState.reactions[type].last) return;
    const url = `${process.env.REACT_APP_BACKEND_URL}post/getPostReactions?page=${
      page + 1
    }&size=${size}`;
    const response = await axios.post(url, {
      postId,
      type,
    });
    setReactionsState({
      ...reactionsState,
      reactions: {
        ...reactionsState.reactions,
        [type as string]: {
          content: [...reactionsState.reactions[type].content, ...response.data.reactions.content],
          number: response.data.reactions.number,
          size: response.data.reactions.size,
          last: response.data.reactions.last,
        },
      },
    });
    setLoading(false);
  };

  return (
    <Tab
      eventKey={eventKey as string | number}
      className={styles.listContent}
      title={<RenderTitle type={eventKey as string} reactionsState={reactionsState} />}
    >
      <div id={`reactionListModal${eventKey}`}>
        <ul className={styles.userListItemContainer}>
          {reactionsState?.reactions[eventKey as string]?.content.map((user: UserListItemType) => (
            <UserListItem userData={user} key={user.reactedByEmployeeId} />
          ))}
        </ul>
        {!reactionsState?.reactions?.LIKE?.last && (
          <Button ref={containerRef} disabled={loading}>
            {loading ? "Loading..." : "Load more"}
          </Button>
        )}
      </div>
    </Tab>
  );
}

Trigger a custom Event when element in viewport – JavaScript

I need to link these two codes so that when the “isElementInViewport” function returns true to trigger the “inviewport” event:

let inViewportEvent = document.createEvent("Event");
inViewportEvent.initEvent("inviewport", true, true);

document.addEventListener("inviewport", (e) => {
    console.log(`${e.target} in viewport!`)
}, false);

document.dispatchEvent(inViewportEvent);

and this function to detect if a element are in viewport:

const isElementInViewport = el => {
    let rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

how to get a variable value from form to python function in django from javascript

I am trying to scan QR code using javascript as shown below. this part is working fine:

<title>Django Online Barcode Reader</title>
<meta charset="utf-8">
 
{% csrf_token %}

<script src={% static "html5-qrcode.min.js"%}></script>
<style>
.result{
background-color: green;
color:#fff;
padding:20px;
}
.row{
display:flex;
}
</style>

<!--<form action="" method="POST">-->
{% csrf_token %}
<div class="row">
<div class="col">
<div style="width:500px;" id="reader"></div>
</div>
<div class="col" style="padding:30px;">
<h4>SCAN RESULT</h4>
<!--<div id="result" name="result">Result Here</div>-->
<output type="post" id="result" name="resutl" placeholder="qrCodeMessage">
  
</div>
</div>

<script type="text/javascript">
function onScanSuccess(qrCodeMessage) {
document.getElementById('result').innerHTML = '<span class="result">'+qrCodeMessage+'</span>';}

function onScanError(errorMessage) {
//handle scan error
}

var html5QrcodeScanner = new Html5QrcodeScanner(
"reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess, onScanError);
</script>

But I need to pass the value of result variable to python function as following and print it but did not work. It does not print any!

def userspage(request):
    if request.method == 'POST':
        result = request.POST.get("result")
        context = {}
        print(result)
        return render(request, 'users.html', context)

I need your usual help to fix this. Thanks,