JavaScript: The image attachment is added directly from the clipboard with the key combination ctrl + v

I have a task I don’t know how to start. Please tell me, if there’s too much code attached or if I can get any clues from old questions. Am I missing code ony in one of the files below or both?

In the client page there’s only possible to drag and drop the attachment, or click square or link and then choose any files from the computer.

Task description is this:

“Purpose and need: The image attachment is added directly from the clipboard with ctrl + v.

The server has an interface at xxxxx.com. Attachments are sent on PUT request and the query portion of the address is, for example, like ?attachment_id[/request_id/urlkey], where attachment_id is something unique and invented, request_id is the request ID number, and urlkey is the “password” associated the request. The last two are therefore either defined or not at all. The content of the transmission itself must be a multipart/form-data model.

The server then returns a JSON response and if it was a success then the okMessage field can be found in it immediately at the root. Otherwise, an error message such as errorMessages (str arr) or errors (obj → srt) will return.

There are two places on this page to send an attachment:

  1. Make a New Job Request. See if this is visible. Here’s how to check it: document.getElementById('v1r').checked. If the file was successfully uploaded to the server, it will add a tag as an extension to this table: document.getElementById ('rootNew')._fields.appendixTags.i.a_newTags.

  2. Previously sent request. See if this is visible. Here’s how: document.getElementById('v2r').checked && document.getElementById ('justRequest') parentElement.style.display != 'nothing'
    (v1r and v2r are mutually exclusive, meaning only one can be visible at a time) Then, when the file has been successfully uploaded, even if you call this function, it will already be the text you want to see: l_help_addFileList(lt, name, size, mime, days) however, only name information is currently used. But where lt comes from in 1, is document.getElementById('justNew')._fields.appendixTags.i.e_sentFiles, and the conditions in section 2 are: document.getElementById('requestAttachment').e_sentFiles.

Job Request Response (Email) Not yet

In step 2, the credentials can be angled from the tag_id and tag_key data stored in the document.getElementById ('comment') element.”

I have no idea where to start. I have two javascript files: index and sendAttachment. First of all, must I modify both files or only sendAttachment one?

Secondly, what I’m missing from the code so that in addition to dragging and droping , attachments can also be attached with ctrl + v?

I appreciate your help. Thank you!

Here’s the current codes from client side:

index.js

//SOME CODE FIRST

        //Send button
    {
        let send = document.createElement('div');
        send.id = 'send';
        send.className = 'tr';

        let button = document.createElement('input');
        button.type = 'button';
        button.onclick = new_sendForm;
        button.value = 'Submit';
        send.appendChild(button);

        root.appendChild(send);
        root._send = button;
    }

    //Shows that notification is received
    {
        let note = document.createElement('div');
        note.id = 'new_note';
        note.style.display = 'none';
        let div = document.createElement('div');

        let text = document.createElement('h2');
        text.textContent = 'Sended successfully';
        div.appendChild(text);

        let button = document.createElement('input');
        button.type = 'button';
        button.onclick = function reset(){
            note.style.display = 'none';
            new_resetForm();
            if (root._fields.attachmentTags)
                l_addBufferedAttachmentInformation(root._fields.attachmentTags.i, []);
        };
        button.value = 'Empty form';
        div.appendChild(button);

        div.appendChild(document.createElement('br'));
        div.appendChild(document.createElement('br'));

        let p = document.createElement('i');
        p.textContent = 'You can find this and previous requests from the tab named Previous'
            + ' if you gave your email address.'
        ;
        div.appendChild(p);

        p = document.createElement('p');
        p.style.fontFamily = "'Lucida Console', monospace";
        p.innerHTML = 'Here's the link<br>';
        let a = document.createElement('a');
        a.href = '#';
        a.textContent = 'The link isn't created yet';
        p.appendChild(a);
        div.appendChild(p);

        note.appendChild(div);
        root.appendChild(note);
        root._note = note;
        root._note_a = a;
    }

    {
        let email = root._fields['email'];
        let o = s_get();
        if (email && email.i && !email.i.value && o.email)
            email.i.value = o.email;
    }
}

// ----------------------------------------------------------------------------


function show_comment(){
    let comment = document.getElementById('comment');
    let selection = null;{
        let inputs = comment.getElementsByTagName('input');
        for (let i=0, ii=inputs.length; i<ii; i++){
            let input = inputs.item(i);
            if (input.checked){
                selection = input.value;
                break;
            }
        }
    }
    let n_comment = document.getElementById('n_comment');
    let n_comment_error = document.getElementById('n_comment_error');
    let n_comment_button = document.getElementById('n_comment_button');
    if (!selection)
        n_comment_error.textContent = 'Not done';
    else if (!n_comment.value.trim())
        n_comment_error.textContent = 'Comment missing';
    else {
        n_comment_error.textContent = '';
        n_comment_button.disabled = true;
        let post = {
            feature: "addComment",
            getRequest: {
                id: comment.key_id,
                urlkey: comment.key_key,
                status: selection,
                description: n_comment.value
            }
        }
        xhr(
            function ok(json){
                n_comment_button.disabled = false;
                if (json.errorMessages)
                    n_comment_error.innerHTML = json.errorMessages.join('<br>');
                else
                    n_comment.value = '';
                if (json.requests && json.requests[0]){
                    let request = json.requests[0];
                    let label = document.getElementById('rootRequest').getElementsByTagName('h3').item(0);
                    if (label && request.jira_fields && request.jira_fields.description){
                        label.nextElementSibling.innerHTML = '';
                        doc2html(request.jira_fields.description, bella.nextElementSibling);
                    }
                }
            },
            '/api',
            JSON.stringify(post),
            function err(json){
                n_comment_button.disabled = false;
                n_comment_error.textContent = 'Sending failed';
            }
        );
    }
}

//OTHER CODES BEFORE NEXT ONES:

        //Attachments part

        let requestAttachment = document.getElementById('requestAttachment');
        if (request.jira_fields && request.jira_fields.attachment)
            l_addJiraAttachmentInfo(requestAttachment, request.jira_fields.attachment);
        else if (pyynto.attachmentTags)
            l_addBufferedAttachmentInfo(requestAttachment, request.attachmentTags);
        else
            l_addBufferedAttachmentInfo(requestAttachment, []);
    } else {
        root.innerHTML = 'Didn't find the request';
    }
    root.parentElement.style.display = 'inline-block';
}

function show_get(id, urlkey){
    xhr(
        function ok(json){
            show_show(json);
        },
        '/api',
        JSON.stringify({
            feature: 'get',
            getRequest: {
                id: id,
                urlkey: urlkey
            }
        }),
        function err(json){
            let root = document.getElementById('rootRequest');
            root.innerHTML = '<b>Download failed</b>';
        }
    );
}

function show_initLomake(){
    let get = getParameters();
    let root = document.getElementById('rootRequest');
    if (get['id'] && get['idKey']){
        root.innerHTML = '<i>Searching...</i>';
        show_get(get['id'], get['idKey']);
        //Switching page
        document.getElementById('v2r').checked = true;
    } else {
        root.parentElement.style.display = 'none';
    }
    let requestAttachment = document.getElementById('requestAttachment');
    let comment = document.getElementById('comment');
    if (typeof l_createForm === 'function' && requestAttachment && comment)
        l_createForm(requestAttachment, comment);
    else if (comment)
        requestAttachment.parentElement.style.display = 'none';
}

    function list_sendLink(email){
    if (email){
        xhr(
            function ok(json){
                let root = document.getElementById('rootList');
                if (json.okMessage)
                    root.textContent = json.okMessage;
                else if (json.errors && json.errors['sendMssage']){
                    let div = document.createElement('div');
                    div.textContent = json.errors['sendMessage'];
                    div.className = 'error';
                    root.appendChild(div);
                } else if (json.errorMessages && json.errorMessages[0]){
                    let div = document.createElement('div');
                    div.textContent = json.errorMessages[0];
                    div.className = 'error';
                    root.appendChild(div);
                } else
                    root.innerHTML = "Something went wrong. Don't know what or where.";
            },
            '/api',
            JSON.stringify({
                feature: 'sendListTag',
                newForm: {
                    email: email
                }
            }),
            function err(json){
                let root = document.getElementById('rootList');
                let div = document.createElement('div');
                div.textContent = 'Sending the request to server failed???';
                div.className = 'error';
                root.appendChild(div);
            }
        );
    }
}

function list_initShowPrevious(){
    let get = getParameters();
    let store = s_get();
    let root = document.getElementById('rootList');
    let mm_list = document.getElementById('mm_list');

    let email = get['email'];
    let listTag = get['list'];

    if (store.email && store.listTag){
        s_forgetButton(true);
        if (!email || !listag || store.email == email && store.listTag == listTag){
            email = store.email;
            listTag = store.listTag;
            mm_list.innerHTML = 'Email and list tags.';
        } else {
            mm_list.innerHTML = 'Email and list tag, but they differ!<br><i>If you want to update, you must forget old infos first.</i>';
        }
    } else if (email && listTag){
        s_post(email, listTag);
        mm_list.innerHTML = 'Email and list tags (saved now).';
        s_forgetButton(true);
    } else {
        mm_list.innerHTML = 'Nothing';
    }

    if (email && listTag){
        root.innerHTML = '<i>Searching...</i>';
        list_get(email, listTag);

        if (!get['form'])
            document.getElementById('v2r').checked = true;
    }
}

// ----------------------------------------------------------------------------

function init(){
    //New form?
    xhr(
        function settingsGot(json){
            new_initForm(json);
            window._settings = json;
            list_initShowPrevious();
            show_initForm();
        },
        'form.new.json',
        null,
        null
    );
}

sentAttachment.js

'use strict';

function l_createForm(root, settingSource){
    if (!root || !ss || !ss.SimpleUpload){
        console.error("Formatting of downloading attachment file failed.");
    } else {
        root.a_settingSource = settingSource;
        root.a_newTags = [];
        {
            let sendedFiles = document.createElement('fieldset');
            root.e_SendedFiles = sendedFiles;
            sendedFiles.className = 'sendedFiles';
            let legend = document.createElement('legend');
            legend.innerHTML = 'Sended files';
            sendedFiles.appendChild(legend);
            root.appendChild(sendedFiles);
        }

        {
            let progressBox = document.createElement('div');
            root.e_progressBox = progressBox;
            progressBox.className = 'progressBox';
            root.appendChild(progressBox);
        }

        {
            let key = document.createElement('p');
            root.e_key = key;
            key.className = 'key';
            key.innerHTML = '<span>Drag and drop the files you want to send to the square above</span> ' +
                'or <a>click here</a>';
            root.e_clicking = key.lastElementChild;
            root.appendChild(key);
        }

        root.e_fileUpload = new ss.SimpleUpload({
            button: [root.e_sendedFiles, root.e_clicking],
            url: function before(xhr, settings){
                let extra = '';
                if (settingSource && settingSource.tag_id && settingSource.tag_key)
                    extra = '/' + settingSource.tag_id + '/' + settingSource.tag_key;
                return location.protocol +
                    '//' + location.host +
                    '/api?' + 
                    (Date.now()) +
                    extra
                ;
            },
            name: "file",
            method: "PUT",
            dropzone: root,
            dragClass: 'fileOn',
            encodeHeaders: true,
            cors: false,
            multiple: true,
            multipleSelect: true,
            noParams: true,
            multipart: true,
            autoSubmit: true,
            responseType: "json",
            debug: false,
            onDone: function sendingPassed(
                fileName,//String
                statusCode,//the response status code, if any
                statusText,//the response status code, if any
                json,//false
                button,//Button which started sending
                fileSize//number or null
            ){
                let sendedFiles = root.e_sendedFiles;
                if (sendedFiles){
                    l_help_addFileToList(
                        sendedFiles,
                        fileName,
                        fileSize,
                        null,
                        null
                    );
                    if (json && json.attachmentTag)
                        root.a_newTags.push(json.attachmentTag);
                } else {
                    alert('File "' + fileName + '" sended successfully.');
                }
            },
            onError: function sendingError(
                fileName,//String
                errorType,//"error" or "parseerror"
                statusCode,//the response status code, if any
                statusText,//the response status code, if any
                answer,//false
                button,//Button which started sending
                fileSize//number or null
            ){
                alert('"' + fileName + '": ' + statusText);
            },
            onSubmit: function(filename, extension) {
                // Create the elements of our progress bar
                var progress = document.createElement('div'), // container for progress bar
                bar = document.createElement('div'), // actual progress bar
                fileSize = document.createElement('div'), // container for upload file size
                wrapper = document.createElement('div'), // container for this progress bar
                //declare somewhere: <div id="progressBox"></div> where you want to show the progress-bar(s)
                progressBox = root.e_progressBox; //on page container for progress bars

                // Assign each element its corresponding class
                progress.className = 'progress progress-striped';
                bar.className = 'progress-bar progress-bar-success';
                fileSize.className = 'size';
                wrapper.className = 'wrapper';

                // Assemble the progress bar and add it to the page
                progress.appendChild(bar); 
                wrapper.innerHTML = '<div class="name">Sending <b>'+filename+'</b></div>'; // filename is passed to onSubmit()
                wrapper.appendChild(fileSize);
                wrapper.appendChild(progress);                                       
                progressBox.appendChild(wrapper); // just an element on the page to hold the progress bars    

                // Assign roles to the elements of the progress bar
                this.setProgressBar(bar); // will serve as the actual progress bar
                this.setFileSizeBox(fileSize); // display file size beside progress bar
                this.setProgressContainer(wrapper); // designate the containing div to be removed after upload
            }
        });
    }
}

function l_help_addFileToList(root, name, size, mime, date){
    let square = document.createElement('div');
    square.className = 'square';

    let text = document.createElement('span');
    text.className = 'name';
    text.innerHTML = name;
    square.appendChild(text);

/*
    let size = document.createElement('i');
    size.className = 'size';
    size.innerHTML = size;
    square.appendChild(size);
*/

    root.appendChild(square);
}

function l_addJiraAttachmentInfo(root, attachment_arr){
    if (root.e_sendedFiles && attachment_arr instanceof Array){
        root.e_sendedFiles.innerHTML = '';
        root.a_newTags = [];
        for (let i=0, ii=attachment_arr.length; i<ii; i++){
            let a = attachment_arr[i];
            l_help_addFileToList(
                root.e_sendedFiles,
                a.filename,
                a.size,
                a.mimeType,
                a.created
            );
        }
    }
}

function l_addBufferedAttachmentInfo(root, attachmentTags){
    if (root.e_sendedFiles && attachmentTags instanceof Array){
        root.e_sendedFiles.innerHTML = '';
        root.a_newTags = [];
        for (let i=0, ii=attachmentTags.length; i<ii; i++){
            let a = attachmentTags[i];
            l_help_addFileToList(
                root.e_sendedFiles,
                'Sending_' + a,
                -1,
                null,
                null
            );
        }
    }
}

function l_getSendedTags(root){
    if (root.a_newTags)
        return root.a_newTags;
    else
        return null;
}

Angular 10: repeat the same http request after obtaining the refresh token

I am trying to achieve the following in my HTTP calls

  1. If an API request returns 401 then call the refresh token endpoint to get the token.
  2. Retry the same HTTP call with the updated token

Here is the relevant code

// this method invoke when the HTTP interceptor returns 401 status code

handle401(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.refreshTokenInProgress) {
      this.refreshTokenInProgress = true;
      this.refreshTokenSubject.next(null);
      return this.getToken((data: any) => {
        this.refreshTokenInProgress = false;
        this.refreshTokenSubject.next(data);
        request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${data}`) });
        return next.handle(request);
      })
    } else {
      return this.refreshTokenSubject.pipe(
        filter(token => token != null),
        take(1),
        switchMap((accessToken) => {
          request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`) });
          return next.handle(request);
        })
      );
    }
  }

Obtain the refresh token

getToken(cb: any) {
    let poolData = {
      UserPoolId: environment.cognitoUserPoolId, // Your user pool id here
      ClientId: environment.cognitoAppClientId // Your client id here
    };
    let userPool = new CognitoUserPool(poolData);
    let cognitoUser = userPool.getCurrentUser();
    cognitoUser?.getSession((err: any, session: any) => {
      const refresh_token = session.getRefreshToken();
      cognitoUser?.refreshSession(refresh_token, (refErr, refSession) => {
        
        const userToken = localStorage.getItem('token');
        cb(userToken);
      });
    })
  }

While executing I am getting the new token from the getToken method, but the retry of the same HTTP call is not happening.

The execution of HTTP request stops after obtaining the refresh token from the getToken method.

Can somebody please help on this issue

How can I make my carousel add 1 image per next or back?

I was trying to make a carousel that add only 1 image every click of next or back button
same as this on the link, I wanted to copy this but I found out that the developer using booststrap 4 only and using old version of jquery, js and css links. I can’t find any good tutorial about this.

.banner-name,
.banner-price {
    text-align: center;
    font-family: marcellus-sc, Arial, Helvetica, sans-serif;
}

.wrapper-banner
.wrapper-banner1,
.carousel {
    margin-top: 30px;
}

.wrapper .section .content-banner {
    justify-content: center;
    display: flex;
}
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<div id="carousel-2" class="carousel slide" data-bs-ride="carousel" data-bs-interval="false">
    <div class="carousel-inner">
        <div class="carousel-item active">
            <div class="row">
                <div class="col">
                    <img class="banner-carousel" src="https://picsum.photos/200" />
                    <div class="banner-name">
                        Curabitur sitamet
                    </div>
                    <div class="banner-price">
                        <span class="economy">₱ </span><span class="price">300</span>
                    </div>
                </div>
                <div class="col">
                    <img class="banner-carousel" src="https://picsum.photos/200" />
                    <div class="banner-name">
                        Curabitur sitamet
                    </div>
                    <div class="banner-price">
                        <span class="economy">₱ </span><span class="price">300</span>
                    </div>
                </div>
                <div class="col">
                    <img class="banner-carousel" src="https://picsum.photos/200" />
                    <div class="banner-name">
                        Curabitur sitamet
                    </div>
                    <div class="banner-price">
                        <span class="economy">₱ </span><span class="price">300</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="carousel-item">
            <div class="row">
                <div class="col">
                    <img class="banner-carousel" src="https://picsum.photos/200" />
                    <div class="banner-name">
                        Curabitur sitamet
                    </div>
                    <div class="banner-price">
                        <span class="economy">₱ </span><span class="price">300</span>
                    </div>
                </div>
                <div class="col">
                    <img class="banner-carousel" src="https://picsum.photos/200" />
                    <div class="banner-name">
                        Curabitur sitamet
                    </div>
                    <div class="banner-price">
                        <span class="economy">₱ </span><span class="price">300</span>
                    </div>
                </div>
                <div class="col">
                    <img class="banner-carousel" src="https://picsum.photos/200" />
                    <div class="banner-name">
                        Curabitur sitamet
                    </div>
                    <div class="banner-price">
                        <span class="economy">₱ </span><span class="price">300</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <button class="carousel-control-prev" type="button" data-bs-target="#carousel-2" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
    </button>
    <button class="carousel-control-next" type="button" data-bs-target="#carousel-2" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
    </button>
</div>                           

So far I tried to change my code into

$('#carousel-2').on('slide.bs.carousel', function () {
    var $e = $(e.relatedTarget);
    var idx = $e.index();
    var itemPerSlide = 3;
    var totalItems = $('.carousel-item').length;

    if (idx = totalItems - (itemsPerSlide)) {
        var it = itemPerSlide - (totalItems - idx);
        for (var i = 0; i < it; i++) {
            if (e.directed == 'left') {
                $('.carousel-item').eq(i).appendTo('.carousel-inner');
            } else {
                $('.carousel-teim').eq(0).appendTo('.carousel-inner');
            }
        }
    }
})
.banner-name,
.banner-price {
    text-align: center;
    font-family: marcellus-sc, Arial, Helvetica, sans-serif;
}

.wrapper-banner
.wrapper-banner1,
.carousel {
    margin-top: 30px;
}

.content-banner {
    justify-content: center;
    display: flex;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="carousel-2" class="carousel slide" data-bs-ride="carousel" data-bs-interval="false">
    <div class="carousel-inner row">
        <div class="carousel-item col active">
            <img class="banner-carousel" src="https://picsum.photos/200" />
            <div class="banner-name">
                Curabitur sitamet
            </div>
            <div class="banner-price">
                <span class="economy">₱ </span><span class="price">300</span>
            </div>
        </div>
        <div class="carousel-item col active">
            <img class="banner-carousel" src="https://picsum.photos/200" />
            <div class="banner-name">
                Curabitur sitamet
            </div>
            <div class="banner-price">
                <span class="economy">₱ </span><span class="price">300</span>
            </div>
        </div>
        <div class="carousel-item col active">
            <img class="banner-carousel" src="https://picsum.photos/200" />
            <div class="banner-name">
                Curabitur sitamet
            </div>
            <div class="banner-price">
                <span class="economy">₱ </span><span class="price">300</span>
            </div>
        </div>
        <div class="carousel-item col active">
            <img class="banner-carousel" src="https://picsum.photos/200" />
            <div class="banner-name">
                Curabitur sitamet
            </div>
            <div class="banner-price">
                <span class="economy">₱ </span><span class="price">300</span>
            </div>
        </div>
    </div>
    <button class="carousel-control-prev" type="button" data-bs-target="#carousel-2" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
    </button>
    <button class="carousel-control-next" type="button" data-bs-target="#carousel-2" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
    </button>
</div>

But no luck about doing this that i wanted to be

How do I invoke a function when using inquirer?

I’m building a node CLI ‘battleship’ game. Initially, a user enters coordinates which are stored in the variables xCoordinate and xCoordinate . This is handled using inquirer :

index.js

import inquirer from 'inquirer'

//write a function that takes in user coordinates
const question1 = [
  {
    type: "input",
    name: "x-coordinate",
    message: "Please enter the first of two coordinates",
  },
  {
    type: "input",
    name: "y-coordinate",
    message: "Please enter the last coordinate",
  },
];

  let xCoordinate;
  let yCoordinate;

  inquirer.prompt(question1).then((answers) => {
    let xCoordinate = answers["x-coordinate"];
    let yCoordinate = answers["y-coordinate"];
    console.log(
      `You have entered [${xCoordinate}, ${yCoordinate}] as your coordinates`
    );
  });

I have a function screenForShips thats screens the inputed coordinates against a matrix containing the “ships”, and tells the user whether they have a hit or not.

So my question is this – in inquirer, how do you invoke the function screenForShips after receiving input from a user?

I am trying to create custom checkbox inside dropdown list using pure JavaScript

//When we click outside the panel, or when you click on another panel, or the panel itself, the dropdown panel should disappear. When I click outside panel or any other panel it is working fine but when I click inside panel it is not working.it is working after second click. it seems toggle is not working properly



function reply_click(clicked_id) {
    var element = document.getElementById(clicked_id);
    window.addEventListener('click', (e) => {
        if (element.contains(e.target)) {
            element.classList.toggle("is-active")

        } else {
            element.classList.remove("is-active")
        }

    })

}
html,
body {
    height: 100%;
}

.checkbox-dropdown {
    width: 200px;
    border: 1px solid #aaa;
    padding: 10px;
    position: relative;
    margin: 0 auto;
    user-select: none;
}


/* Display CSS arrow to the right of the dropdown text */

.checkbox-dropdown:after {
    content: '';
    height: 0;
    position: absolute;
    width: 0;
    border: 6px solid transparent;
    border-top-color: #000;
    top: 50%;
    right: 10px;
    margin-top: -3px;
}


/* Reverse the CSS arrow when the dropdown is active */

.checkbox-dropdown.is-active:after {
    border-bottom-color: #000;
    border-top-color: #fff;
    margin-top: -9px;
}

.checkbox-dropdown-list {
    list-style: none;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 100%;
    /* align the dropdown right below the dropdown text */
    border: inherit;
    border-top: none;
    left: -1px;
    /* align the dropdown to the left */
    right: -1px;
    /* align the dropdown to the right */
    opacity: 0;
    /* hide the dropdown */
    transition: opacity 0.4s ease-in-out;
    overflow-x: hidden;
    pointer-events: none;
    /* avoid mouse click events inside the dropdown */
}

.is-active .checkbox-dropdown-list {
    opacity: 1;
    /* display the dropdown */
    pointer-events: auto;
    /* make sure that the user still can select checkboxes */
    z-index: 1;
    background: #fff;
}

.checkbox-dropdown-list li label {
    display: block;
    border-bottom: 1px solid silver;
    padding: 10px;
    transition: all 0.2s ease-out;
}

.checkbox-dropdown-list li label:hover {
    background-color: #555;
    color: white;
}
It should execute the div id dynamically. I tried various ways but it not working. please tell me what i am doing wrong here. I have searched for hours now without any luck.



<div id="myDIV1" onClick="reply_click(this.id)" class="checkbox-dropdown">
   Choose city
   <ul class="checkbox-dropdown-list">
      <li>
         <label>
         <input type="checkbox" value="Vejle" name="city" />Milwaukee
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Horsens" name="city" />Denver
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Kolding" name="city" />Boston
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Kolding" name="city" />LA
         </label>
      </li>
   </ul>
</div>
<div style="height:50px"></div>
<div id="myDIV2" onClick="reply_click(this.id)" class="checkbox-dropdown">
   Choose city
   <ul class="checkbox-dropdown-list">
      <li>
         <label>
         <input type="checkbox" value="Vejle" name="city" />Milwaukee
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Horsens" name="city" />Denver
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Kolding" name="city" />Boston
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Kolding" name="city" />LA
         </label>
      </li>
   </ul>
</div>
<div style="height:50px"></div>
<div id="myDIV3" onClick="reply_click(this.id)" class="checkbox-dropdown">
   Choose city
   <ul class="checkbox-dropdown-list">
      <li>
         <label>
         <input type="checkbox" value="Vejle" name="city" />Milwaukee
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Horsens" name="city" />Denver
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Kolding" name="city" />Boston
         </label>
      </li>
      <li>
         <label>
         <input type="checkbox" value="Kolding" name="city" />LA
         </label>
      </li>
   </ul>
</div>
/*When we click outside the panel, or when you click on another panel, or the panel itself, the dropdown panel should disappear. When I click outside panel or any other panel it is working fine but when I click inside panel it is not working.
it is working after second click. it seems toggle is not working properly */
<div id="myDIV1" onClick="reply_click(this.id)" class="checkbox-dropdown">
        Choose city
        <ul class="checkbox-dropdown-list">
            <li>
                <label>
                    <input type="checkbox" value="Vejle" name="city" />Milwaukee
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Horsens" name="city" />Denver
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Kolding" name="city" />Boston
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Kolding" name="city" />LA
                </label>
            </li>

        </ul>
    </div>
    <div style="height:50px"></div>
    <div id="myDIV2" onClick="reply_click(this.id)" class="checkbox-dropdown">
        Choose city
        <ul class="checkbox-dropdown-list">
            <li>
                <label>
                    <input type="checkbox" value="Vejle" name="city" />Milwaukee
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Horsens" name="city" />Denver
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Kolding" name="city" />Boston
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Kolding" name="city" />LA
                </label>
            </li>

        </ul>
    </div>
    <div style="height:50px"></div>
    <div id="myDIV3" onClick="reply_click(this.id)" class="checkbox-dropdown">
        Choose city
        <ul class="checkbox-dropdown-list">
            <li>
                <label>
                    <input type="checkbox" value="Vejle" name="city" />Milwaukee
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Horsens" name="city" />Denver
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Kolding" name="city" />Boston
                </label>
            </li>
            <li>
                <label>
                    <input type="checkbox" value="Kolding" name="city" />LA
                </label>
            </li>

        </ul>
    </div>

Why isn’t the popup box closing while testing with React Testing Library?

I’m currently using a module from material-ui-dropzone. Which basically opens a popup dialog box when a button is clicked, and then to close it we just have to click outside the popup or click the cancel button.

screenshot

When I test and try this in the UI, it works PERFECTLY.

however in my test suite I’m struggling a bit. This is my react component:

import React, { useState } from 'react';
import { DropzoneDialog } from 'material-ui-dropzone';

export const UploadBox = () => {
    const [open, setOpen] = useState(false);

    const handleClickOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    const handleSubmit = async file => {
        // unrelated logic
    };

    return (
        <div>
            <button onClick={handleClickOpen}>
                Set Picture
            </button>
            <DropzoneDialog
                open={open}
                onSave={handleSubmit}
                acceptedFiles={['image/*']}
                showPreviews={true}
                maxFileSize={5000000}
                onClose={handleClose}
            />
        </div>
    );
};

And this is my testing file:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UploadBox } from './UploadBox';
import React from 'react';
import '@testing-library/jest-dom';

describe('UploadBox', () => {
    test('opens upload popup box on button click', () => {
        render(<UploadBox />);

        userEvent.click(screen.getByRole('button'), { name: 'Set Picture' });

        expect(screen.getByText('Upload file')).toBeInTheDocument();
    });

    test('closes upload popup box on cancel button click', () => { // FAILING
        render(<UploadBox />);

        userEvent.click(screen.getByRole('button'), { name: 'Set Picture' });
        userEvent.click(screen.getByText('Cancel'));

        expect(screen.getByText('Upload file')).not.toBeInTheDocument();
    });
});

My last test named closes upload popup box on cancel button click is failing which should not be the case. The message I get is expected document not to contain element, found <h2 class="MuiTypography-root MuiTypography-h6">Upload file</h2> instead, which means that it is still in the document. Any ideas as to why?

Warning: Array to string conversion in C:xampphtdocswp-webdoggowp-contentthemesdoggofunctions.php on line 192

I am developing a wordpress theme and i addedd inline_style css into my function.php. all was going fine but when i added @media for set min-max width, at that time it showing me a warning error. plz help me, how can i added @media css into inline_style. I already mentioned the “line 192”. Thank you advanced.

<?php
function doggo_inline_styles_method() {
    wp_enqueue_style(
        'custom-style',
        get_template_directory_uri() . 'assets/css/custom_script.css'
    );
        global $doggo_redux;
        $top_h_l_hight = $doggo_redux['top_header_height'];
        $top_h_bg_color = $doggo_redux['top_h_bg_color'];
        $top_h_icon_color = $doggo_redux['top_h_icon_color']['regular'];
        $top_h_icon_size = $doggo_redux['top_header_icon_size'];
        $menu_height = $doggo_redux['menu_height'];
        $menu_bg_color = $doggo_redux['menu_bg_color'];
        $footer_bg = $doggo_redux['footer_bg_color'];
        $footer_heading_color = $doggo_redux['footer_heading_color'];
        
        $custom_css = "
                .container-fluid.top-bar{
                       line-height: {$top_h_l_hight}px;
                       background: {$top_h_bg_color};
                }

                .top-bar .contact-details i {
                    color:{$top_h_icon_color};
                }

                ul.contact-details.float-left li i, ul.social-list.float-right.list-inline li i {
                    font-size: {$top_h_icon_size}px;
                }

                .navbar.container-fluid {
                    height: {$menu_height}px;
                }

                footer.footer {
                    background: {$footer_bg}!important;
                }

                footer.footer h5 {
                    color: {$footer_heading_color}!important;
                }

                @media (max-width: 1200px){
                    .container {
                        background: {$menu_bg_color}; *** this is line num 192 ***
                        z-index: 100;
                    }
                }


                
                ";
        wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'doggo_inline_styles_method' );

?>

I tried to add @media
into function.php but I didn’t. How can I added these codes without error show. Thanks.

How to make Javascript (raining matrix code) as a background of the website

The problem I encounter is that I dont know how to overlay a text, image, and video on a javascript. I tried to find it on youtube and google but I find no answer. Can somebody help me? Thanks!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css">
    <title></title>
</head>
<body style="background-color: black">
  

    <canvas id="Matrix" style="width: 100%; height: 100%;"></canvas>
    <script src="./index.js"></script>

  


</body>
</html>
html {
    background: black;
    height: 100%;
    overflow: hidden;
}

body {
    margin: 0;
    padding: 0;
    height: 100%;
}
const canvas = document.getElementById('Matrix');
const context = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const katakana = 'アァカサタナハマヤャラワガザダバパイィキシチニヒミリヰギジヂビピウゥクスツヌフムユュルグズブヅプエェケセテネヘメレヱゲゼデベペオォコソトノホモヨョロヲゴゾドボポヴッン';
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';

const alphabet = katakana + latin + nums;

const fontSize = 16;
const columns = canvas.width/fontSize;

const rainDrops = [];

for( let x = 0; x < columns; x++ ) {
    rainDrops[x] = 1;
}

const draw = () => {
    context.fillStyle = 'rgba(0, 0, 0, 0.05)';
    context.fillRect(0, 0, canvas.width, canvas.height);
    
    context.fillStyle = '#0F0';
    context.font = fontSize + 'px monospace';

    for(let i = 0; i < rainDrops.length; i++)
    {
        const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length));
        context.fillText(text, i*fontSize, rainDrops[i]*fontSize);
        
        if(rainDrops[i]*fontSize > canvas.height && Math.random() > 0.975){
            rainDrops[i] = 0;
        }
        rainDrops[i]++;
    }
};

setInterval(draw, 30);

I am expecting the javascript to be the background of my entire website while only using HTML,CSS, and JS.

How to put regex expression to validate number between 1.0 to 4.5 (range between decimal values)?

I need an expression to validate numbers between 1.0 to 4.5 but it’s not working precisely for it.

Expression I’m using: /^[1-4]{0,1}(?:[.]d{1,2})?$/

Requirement is to only accept value between 1.0 to 4.5

but

buildInserForm(): void {
    this.insertLeavesForm = this.fb.group({
     **your text**
      hours: [
        { value: 4.5, disabled: true },
        [
          Validators.required,
          Validators.pattern(**/^[1-4]{0,1}(?:[.]d{1,2})?$/**),
        ],
      ],
    });
  }

Currently restricting the numbers from 1.0 to 4.0, But the issue comes in decimal points, it shows an error if entered any number between 6-9 in decimal places, like 1.7,2.8, 3.9.

acceptance criteria are 1.0 to 4.5.

Map 3D array to cells in Google Sheet – Apps Scirpt

Hey I am trying to place arrays of data into a Google Sheet. I’ve got a list of dimensions which I am mapping through a function calling an external API to get numerical values for each dimension. I then want to input these into my spreadsheet – however I am unsure how to do this. I would also like to input the specific Date into a collumn as well. So ideal output would be column A = date, column B = dimensions, column C = numerical value.

function function() {
  var dimensions = ["CN","IN","NZ","US","UK","MY","SG","JP","KR","DE"];
  var counts = dimensions.map(dim => [getValue(dim)]);
}

function getValue(dim) {
  // ive removed the detail for the API call
  var response = UrlFetchApp.fetch(fetchUrl, params);
  var json = JSON.parse(response.getContentText());
  var dataSet = json.results;

  Logger.log(dataSet);

  return dataSet;

}

Logger results

Bootstrap navbar isn’t refreshing in react

My bootstrap navbar is working fine but when I click on current page navbar link, that link is unclickable means it is not letting me click on it again. Other navbar link are clickable except current narbar link.

<Navbar collapseOnSelect sticky='top' expand='sm' variant='dark' className='background color '>
    <Container >
      <Navbar.Toggle aria-controls='responsive-navbar-nav' />
      <Navbar.Collapse className='mobile-nav' id='responsive-navbar-nav'>
      <Nav className='me-auto'>
          <Nav.Link as={NavLink} to="/" >Home</Nav.Link>
      </Nav>
      <Nav>
          <Nav.Link as={NavLink} to="/about">About</Nav.Link>
          
       </Nav>
      </Navbar.Collapse>
    </Container>
  </Navbar>

Array not returning from a router

I’m having some trouble getting some values from my database via express. On my server, I have this router call:

router.get('/list/:id', TokenController.isAValidToken, async (req, res) => {
    const { cardID } = req.query;

    try {
        if (cardID != null) {
            ...
        } else {
            const cards = await CardsController.getCardsForList(req.params.id);
            const orderItems = await OrderItemController.getOrderItemsForCardsInList(cards, req.params.id);
            console.log(orderItems); // <- This prints an array with the info I need
            res.json(orderItems);
        }
    } catch (error) {
        ...
    }
});

My getOrderItemsForCardsInList function has this:

static async getOrderItemForCardInList(cardID, listID) {
   return OrderItem.find({ card: cardID, list: listID }).exec();
}

static async getOrderItemsForCardsInList(cards, listID) {
   return Promise.all(cards.map((card) => OrderItemController.getOrderItemForCardInList(card, listID)));
}

On my client, I call the router function like this:

async function getOrderItemsForCardsInList(listID) {
    const token = await getToken();
    const response = await fetch(`${basePath}/order/list/${listID}`, {
        method: 'GET',
        headers: getTokenAuthHeaders(token)
    });

    return response.json();
}

export default function useOrderItemsForCardsInList(cards) {
    const { listID } = useParams();

    return useQuery(['order', ...cards], () => {
        if (listID != null) {
            return getOrderItemsForCardsInList(listID);
        } else {
            throw Error('No list id defined');
        }
    });
}

And I call that custom hook over here:

const { orderdata } = useOrderItemsForCardsInList(cards.map((card) => card !== null && card._id));
console.log('Data', orderdata);

The problem is that orderdata is printing undefined, meaning that the values are not getting returned as they should, my theory is that probably I’m messing something up in my useOrderItemsForCardsInList custom hook.