cy.session() issues with cypress 10

I am using cy.session(baseurl) in cypress10 for session storage in before(), in their actual documentation, it says once you store the session, you can call page paths by cy.visit(/page1′) in each it() block you want. However, in my case, it says 404 not found unless I use cy.visit(baseurl + ‘/page1’). Can someone help me with this why the correct implementation i.e. (‘/page1’) is not working in it() block.
code snipped:

    before("Open Website and Login", () => {
        cy.session([host, username, password], () => {
            cy.visit(host)
            lgn.fillSignUpEmail(username);
            lgn.fillSignUpPassword(password);
            lgn.clickSubmitButton();
            cy.wait(5000);


        })
    })

    // ******* Dashboard Page ***********

    it("Check Dashboard Page", () => {
        cy.visit(host + '/admin');
        cy.wait(5000);
        cy.title().should('eq', 'Dashboard | Menu Admin');
        dbrd.clickDashboard();
    })

env file – semicolon is automatically added at the end

enter image description here

As you can see the screen, in my .envfile, semicolon is automatically added at the end.

And front and behind the = there comes space between = also automatically.

Problem is when I get data from env file, like process.env.ACCOUNT_SID, if I console.log this variable, then it shows data with ;. So it doesn’t work as a key.

VAb57c6dd85cee7e3c8975857c2bd54a1c;

So I need to remove semicolon by my self like process.env.ACCOUNT_SID.replace(";", "").

Then it works.

VAb57c6dd85cee7e3c8975857c2bd54a1c

I don’t know which setting makes this happen. I use prettier.

how can I change this format not to put semicolon at the end?

Handling PayloadTooLargeError using bodyParser and express

I am using the following in the express app and I am trying to write some error handling for when PayloadTooLargeError arrives. I am not increasing the limit here, just error handling.

import express from 'express';
import bodyParser from 'body-parser';
import { errorHandlingMiddleware } from './middleware';

const app = express();

app.use(bodyParser.json({ limit: '1kb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '1kb' }));

app.use(errorHandlingMiddleware());

I am trying to check against instanceof PayloadTooLargeError however I am not sure where to import it from. Already tried import bodyParser, { PayloadTooLargeError } = 'body-parser' etc.

Here’s the middleware I wrote but PayloadTooLargeError does not exist of course (IDE suggests not declared), however this is what it actually throws.

export function errorHandlingMiddleware() {
  return (
    error: Error,
    req: express.Request,
    _res: express.Response,
    next: express.NextFunction
  ) => {
    if (error instanceof PayloadTooLargeError) {
      //REACH THIS PLACE
    } else {
      next(error);
    }
  };
}

The error:

PayloadTooLargeError: request entity too large

Angular How to send value from one Sibling to another and send it back changed to the first sibling

I’d like to ask how can I send data from one sibling component to another and send it back with changed value?
I need to add bootstrap effect fadeInDown to a newly added comment in my comments section.
It works but unfortunately it affects all of the comments when I reload the page and the effect is also added when I edit a comment.
I need to send boolean value on method addComment from new-comment component to comment component but then I need that value in new-component to become false again. Now it’s false and after using addComment method it becomes true forever. How can I handle this?

I will be glad for any advice

This is my comment section:
Comment section

This is the structure of my files: Files structure

These are the components I’m working on:
Comment section HTML

<h6>Comments: ({{commentsCount}})</h6>
<app-new-comment class="d-block mt-3" [requestId]="requestId" (update)="updateComments()"> 
</app-new-comment>
<app-comment *ngFor="let comment of comments; let i = first"
         [ngClass]="{'fadeInDown': i}"
         class="d-block mt-3 animated"
         [comment]="comment"
         (update)="updateComments()"></app-comment>

Comment section TS

export class CommentSectionComponent implements OnInit, OnDestroy {

@Input() requestId: string
comments: CommentDetailsDto[]
commentsCount = 0

private subscription: Subscription

constructor(
    private commentsService: CommentsService,
    private alert: AlertService
) {
}

ngOnInit(): void {
    this.updateComments()
}

ngOnDestroy(): void {
    this.unsubscribe()
}

updateComments(): void {
    this.unsubscribe()
    this.subscription = this.commentsService.getComments(this.requestId)
        .subscribe({
            next: (comments: CommentDetailsDto[]) => {
                this.comments = comments.reverse()
                this.commentsCount = this.getCommentsCount(comments)
            },
            error: (error: HttpErrorResponse) => {
                this.alert.handleHttpError(error)
            }
        })
}

private getCommentsCount(comments: CommentDetailsDto[]): number {
    return comments.reduce(
        (cnt, comment) => cnt + 1 + (comment.replies ? this.getCommentsCount(comment.replies) : 0),
        0
    )
}

private unsubscribe(): void {
    if (this.subscription instanceof Subscription) {
        this.subscription.unsubscribe()
    }
}

}

Comment section SCSS

@keyframes fadeInDown {
from {
    opacity: 0;
    transform: translate3d(0, -100%, 0);
}
to {
    opacity: 1;
    transform: translate3d(0, 0, 0);
}
}

.fadeInDown {
    animation-name: fadeInDown;
}

New comment component HTML

<div class="d-flex">
<app-user-image class="mr-3"></app-user-image>
<textarea #textArea class="d-block" placeholder="Add comment" [(ngModel)]="newComment"> 
 </textarea>
 </div>
 <div class="text-right mt-3">
    <button class="btn btn-primary font-weight-bold px-5" type="button" 
 [disabled]="!newComment" (click)="submit()">
       Post
     </button>
 </div>

New comment TS

export class NewCommentComponent implements OnInit {

@ViewChild('textArea') textArea: ElementRef<HTMLTextAreaElement>
@Input() requestId?: string
@Input() comment?: CommentDetailsDto
@Output() update = new EventEmitter()
newComment: string

private readonly commentResponseObserver = {
    error: (error: HttpErrorResponse) => {
        this.alert.handleHttpError(error)
    },
    complete: () => {
        delete this.newComment
        this.update.emit()
        this.alert.showSuccess('Comment submitted successfully')
    }
}

constructor(
    private commentsService: CommentsService,
    private alert: AlertService,
    private route: ActivatedRoute
) {
}

ngOnInit(): void {
    if (this.comment) {
        this.textArea.nativeElement.focus()
    }
}

submit(): void {
    if (this.requestId) {
        this.addComment()
    } else if (this.comment) {
        this.addReply()
    }
}

addComment(): void {
    if (this.newComment) {
        this.commentsService.addComment(this.requestId, this.newComment)
            .subscribe(this.commentResponseObserver)
    }
}

addReply(): void {
    if (this.newComment) {
        this.commentsService.addReply(this.route.snapshot.queryParamMap.get('requestId'), this.comment, this.newComment)
            .subscribe(this.commentResponseObserver)
    }
}
}

Comment component HTML

<div class="comment">
<app-user-image></app-user-image>
<div class="position-relative d-inline-block flex-fill">
    <div class="d-flex justify-content-between align-items-center">
        <div><strong>{{comment.author.name}} / {{comment.author.id}}</strong><span
            class="date">{{comment.created | krakenDateTime}}</span></div>
        <div class="actions">
            <button *ngIf="this.hateoas.supports(comment, 'update') && !edit"
                    type="button" class="bg-transparent border-0" title="Edit"
                    (click)="toggleEdit()"><i class="icon-kraken icon-kraken-edit"></i></button>
            <button *ngIf="this.hateoas.supports(comment, 'delete')"
                    type="button" class="bg-transparent border-0" title="Delete"
                    (click)="displayDeletionConfirmation()"><i class="icon-kraken icon-kraken-trash"></i></button>
        </div>
    </div>
    <textarea *ngIf="edit; else readonlyComment"
              #textarea
              class="d-block w-100"
              style="min-height: 7rem;"
              [rows]="rows()"
              [(ngModel)]="commentContent"></textarea>
    <ng-template #readonlyComment>
        <div [innerHTML]="commentContentHtml()"></div>
    </ng-template>
    <strong *ngIf="showReplyButton"
            class="reply-button"
            (click)="toggleReplyComponent()"><a href="#temporaryLastRow">Reply</a></strong>
    </div>
 </div>
 <div *ngIf="edit" class="animated fadeIn text-right mt-3">
    <button class="btn btn-sm discard" (click)="cancelEdit()">Discard</button>
    <button class="btn btn-sm ml-2 update" (click)="updateComment()">Update</button>
 </div>
 <div class="replies">
     <app-new-comment *ngIf="showNewReplyWindow"
                 class="d-block mt-3"
                 [comment]="comment"
                 (update)="this.update.emit()"></app-new-comment>
    <app-comment *ngIf="firstReply"
             class="d-block my-3"
             [comment]="firstReply"
             (update)="update.emit()"></app-comment>
     <div *ngIf="moreReplies.length" class="replies-toggle" (click)="showMoreReplies = 
 !showMoreReplies">
    <div class="horizontal-bar"></div>
    <span class="mx-3">{{showMoreReplies ? 'Hide' : 'See'}} {{moreReplies.length}} more 
 comments</span>
    <div class="horizontal-bar"></div>
</div>
<div *ngIf="showMoreReplies">
    <app-comment *ngFor="let reply of moreReplies"
                 class="d-block my-3"
                 [comment]="reply"
                 (update)="update.emit()"></app-comment>
</div>
<span id="temporaryLastRow"></span>

Comment TS

export class CommentComponent implements OnInit {

@ViewChild('textarea', {static: true}) textarea: ElementRef<HTMLTextAreaElement>

@Input() comment: CommentDetailsDto
@Output() update = new EventEmitter()

edit = false
showReplyButton = false
showNewReplyWindow = false
showMoreReplies = false
commentContent: string
firstReply: CommentDetailsDto
moreReplies: CommentDetailsDto[]

constructor(
    private commentsService: CommentsService,
    private modalFactoryService: ModalFactoryService,
    public hateoas: HateoasService,
    private alert: AlertService
) {
}

ngOnInit(): void {
    this.commentContent = this.comment.content
    this.showReplyButton = this.hateoas.supports(this.comment, 'reply')
    this.moreReplies = this.comment.replies.reverse().slice(1)
    this.firstReply = this.comment.replies[0]
}

toggleEdit(): void {
    this.edit = !this.edit
}

updateComment(): void {
    this.commentsService.updateComment(this.comment, this.commentContent)
        .subscribe({
            error: (error: HttpErrorResponse) => {
                this.alert.handleHttpError(error)
            },
            complete: () => {
                this.alert.showSuccess('Comment updated successfully')
                this.update.emit()
            }
        })
}

cancelEdit(): void {
    this.edit = false
    this.commentContent = this.comment.content
}

displayDeletionConfirmation(): void {
    this.modalFactoryService.openConfirmationModal(
        'Delete Comment',
        {
            message: 'Are you sure you want to delete this comment?',
            yesOptionButton: 'Yes',
            noOptionButton: 'No'
        },
        () => {
            this.hateoas.execute(this.comment, 'delete')
                .subscribe({
                    error: (error: HttpErrorResponse) => {
                        this.alert.handleHttpError(error)
                    },
                    complete: () => {
                        this.alert.showSuccess('Comment deleted successfully')
                        this.update.emit()
                    }
                })
        }
    )
}

toggleReplyComponent(): void {
    this.showNewReplyWindow = !this.showNewReplyWindow
}

commentContentHtml(): string {
    return this.commentContent.replace(/n/g, '<br>')
}

rows(): number {
    const newLines = this.commentContent.match(/n/g) || []
    return newLines.length + 1
}
}

 export interface Author {
id: string
name: string
}

 export interface CommentDetailsDto extends Resource {
content: string
author: Author
replies: CommentDetailsDto[]
created: string
 }

Service worker not updating when reloading website even if cache version changed

I have a cache-first approach on my service worker so that load times are quick. When i change the cache version and reload the website, the cache does not update. I need to close the tab and open it again for it to work, or do a hard refresh.

I wanted to implement a feature that reloaded the website once there is an upadate available so that users always have the latest version, but i can’t do it if reloading doesn’t update the cache.
This is my service worker, i’m using react with react router if that might be useful
This is the website

What could be the issue?

How can I update multiple documents, without reading them from the database?

I need to update every document that has a certain field foo

const firestoreDB = getFirestore(app);
const q = query(collection(firestoreDB, 'myCollection'), where('foo', '!=', false));

But I dont need to read the documents, in order to update their values. But since batch(and document) syntax dictates that I need to have a documentSnapshotRef to update it, this seems like it leads to unnecessary reads.

(async () => {
  const docsSnapshot = await getDocs(query);
  const batch = writeBatch(firestoreDB);
  const docsSnapshot.forEach( (docRef) => {
    batch.update(docRef,{
      foo: 123,  // some number that I need to update
    }
  });
})()

So in this case, if there are a 100 documents with foo in it, then I would incur 100 reads and 100 writes, while in reality I only needed a 100 writes. Any solution to this? Some way to use query with batch?

Getting ArgumentNullException: Value cannot be null when using DateTimePicker

Before I use it DateTimePicker everything was working fine, but after adding some javascript code for datetimepicker I am getting ArgumentNullException for
@Html.DropDownListFor(x => x.LeagueId, new SelectList(ViewBag.Leagues, "Id", "LeagueType"), "", new { @class = "form-control", id="liga" }), first player is added successfully but when I want to one more, my application crashes.

Input for date

<div class="form-group">
                        <label asp-for="Player.Birth" class="control-label">@DbResHtml.T("Датум на раѓање","Resources")</label>
                        <input asp-for="Player.Birth" type="text" class="form-control datepicker" required id="birth" />
                        <span asp-validation-for="Player.Birth" class="text-danger"></span>
                    </div>

After adding this lines of code my app crashes

<script>
        $(document).ready(function() {
            $.datetimepicker.setDateFormatter('moment');
            $(".datepicker").datetimepicker({
                timepicker: false,
                format: 'DD/MM/YYYY',
            });
        })
    </script>

Other scripts for Create page

<script>
        $(document).ready(function() {
            $('#select2-3').find('option').not(':selected').remove();
            var count = 0;

            $('#liga').on('change', function() {
                var selectedText = $(this).find('option:selected').text();
                var selectedVal = $(this).val();

                var leagueAjax = $.ajax({
                    type: "POST",
                    url: "@Url.Action("GetClubsForLeague", "Player")",
                    data: {
                        id: selectedVal
                    },
                    success: function(data) {
                        if (count == 0) {
                            var s = '<option value="-1"></option>';
                        }
                        count++;
                        $('#select2-3').find('option').not(':selected').remove();


                        for (var i = 0; i < data.length; i++) {
                            s += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                        }
                        $('#select2-3').append(s);

                        var mycode = {};
                        $("select[id='select2-3'] > option").each(function() {
                            if (mycode[this.text]) {
                                $(this).remove();
                            } else {
                                mycode[this.text] = this.value;
                            }
                        });
                    },
                    error: function(req, status, error) {
                        ajaxErrorHandlingAlert("error", req.status);
                    }
                })
            })
        })
    </script>
    <script>
        $(document).ready(function() {
            $('#select2-3').change(function() {
                var cc = $('#select2-3').val();
                var ids = [];
                for (let i = 0; i < cc.length; i++) {
                    ids.push(cc[i]);
                }
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("GetClubsById","Player")",
                    data: { "ids": ids },
                    success: function(data) {
                        console.log(data);
                        $('#clubsTBody tr').remove();
                        var counter = 1;
                        for (let i = 0; i < data.length; i++) {
                            $("#clubsTBody").append("<tr><td>" + counter + "</td>"
                                + "<td>" + data[i].name + "</td>"
                                + "<td>" + data[i].league.leagueType + "</td>"
                                + "<td>" + '<button  class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"  [email protected]("Delete", "Resources")></button>' + "</td>"
                                + "</tr >");
                            counter++;
                        }
                    },
                    error: function(req, status, error) {
                        console.log(msg);
                    }
                });
            })
            $('#clubs').on('click', '.deleteBtn', function() {
                $(this).parents('tr').remove();
                var value = $(this).closest('tr').children('td:eq(1)').text();
                $(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
            });
        })
    </script>

I am debugging for 3 days, but still nothing.

How to disable two fingers zoom on mobile – Leaflet js

I’m using leaflet js with getsureHandling addon to disable interaction with map using one finger on mobile, and enable the interaction using two fingers.
Everything is fine but when I start dragging the map using two fingers it starts zooming in/out a little bit (but not to a level where it completely zooms) until I stop dragging.
A simple example in the official website of leaflet: here
I want to disable zooming using two fingers (only on mobile), and keeps the zoom controled by the zoom controls (which I already have on my map).
I tried playing with the touchZoom option of the map, here’s the map initialization I’ve tried without success (it completely removed dragging interaction from the map).
let map = L.map('map', { touchZoom: !L.Browser.mobile, dragging: true, gestureHandling: true })

How select a item and show the text of the inside the select button?

I’m getting confuse in this part. I have a list li and I would like to select one item on the list and then show the text to a Select Button.
I dunno if it’s the right way how I proceeding, if it’s right to use a props or not etc. Thank you for your help.

This is the List_Selected.js

export default function List_Selected(props) {

const [list, setList] = useState ( [
{ id: 1, name:'Names', image:'/image-logo.svg' }, 
{ id: 2, name:'Names', image:'/image-logo.svg' }, 
{ id: 3, name:'Names', image:'/image-logo.svg' }
])

function selectedItem(e) {
    console.log(e);
    
}

return (

    <>
    <Select></Select>
    
    <section className='container_blur' >

        <div className={style.container}>
            <div className={style.nav}>
                <span>Select token</span>

                <Close_Button></Close_Button>
            </div>
            <Input_search></Input_search>

            <div className={style.coin_container}>
                <ul className={style.ul}>

                    {list.map((lists) => <div className={style.li} key={lists.id}  onClick={ () => selectedItem(lists.name)} >
                        <li ><Image src={lists.image} width={27} height={35}></Image><p>{lists.name}</p></li>
                    </div>)}


                </ul>
            </div>
        </div>

    </section></>


)
}

This is the Select Button.js

 export default function Select(props) {


    function open(){
        var open = document.querySelector('.container_blur');
        
        setTimeout(function(){
          open.style.opacity = 1;
          open.style.transition = 'opacity 0.3s ease';
          }
          ,200)
  
      setTimeout(function(){
          open.style.display ='flex';
      },10)
  
    }



return (

    <div className={style.select_container}>

        <button className={style.select_btn} onClick={open} >
            <span className="text">{props.coiName}</span>
        </button>
           

    </div>


)
}

Javascript selector not getting input value

I have a very odd but very basic problem. I have a Page containing a searchbox. I want to sue the value of this search box on the onkeyup event. However, for some reason, I am unable to obtain the value of the input. See the screenshot below.

You can see the ID of the element highlighted and you can see in the rendered HTML there is a value in it. However when I try a document.getElementById() it doesn’t return me the value.

enter image description here

If I edit the DOM in Developer Tools to a different ID value, it returns the value.

enter image description here

If I then set it back to the original value, it fails to retrieve again.

enter image description here

What am I missing?

How can I distinguish a swipe from an automatic slide on mobile device

in a slider (in this case lory.js) I’m trying to figure out when a slide is swiped via touch by the user rather than sliding automatically (carousel style). I’m really struggling to come up with a solution that lets me detect it. My main problem is that if I do the action in the touch events provided by lory.js, the action is also fired when the user touches the element while scrolling the site rather than when swiping.

I thought about using the after slide event but that fires every time a slide slides both automatically and when a user swipes.

Is there maybe a way to combine the after.slide and touch events? Or does anyone have an idea/concept that could help me solve this?

Much Thanks!

Creating a reusable firebase component to import across multiple projects

Is it possible to create my own version of the firebaseui-web component that can be reused across multiple different projects/sites? I have created a component and hooked up to firebase however when importing this into other projects, how could I emit the firebase call backs/user details to the project? All projects use Pinia/Vuex, so emitting the details from the imported component are vital.

Download file that downloaded by running js script

I have script

const generate = () => {
    const element = document.querySelector('.wrap');
    html2pdf(element);
}

generate()

on client. This script generates pdf file and send to user (user downloads pdf)

How to do this in php? I want to download file that generates by script on page by php.

Why do I have by default a prefilled name in my dropdown whereas I want to display ‘Select’ by default using react?

can someone see why in my Dropdown menu, I have by default a name filled, whereas I’d like to have by default Select. What is wrong please ?

export default function Overview() {
    const [questions, setQuestions] = useState()
    const [questionDrop, setQuestionDrop] = useState()
    const [overview, setOverview] = useState()

    useEffect(() => {
        ClearApi.listQuestions()
            .then(res => {
                const i = res.data.questions
                console.log('Questions: ', i)
                setQuestions(i.map(i => ({ ...i, value: i._id, name: i.title })))
                if (i.length > 0) setQuestionDrop(i[0])
            })
            .catch(err => {
                console.log(err)
            })
    }, [])

    useEffect(() => {
        if (questionDrop !== undefined)
            myfunctionAPI.displayOverview(questionDrop._id)
                .then(res => {
                    const d = res.data.overviews
                    console.log('Overview: ', d)
                    setOverview(d)
                })
                .catch(err => {
                    console.log(err)
                })
    }, [questionDrop]);

    return (
        <div >
            <Dropdown
                label={questionDrop?.title ?? 'Select'}
                items={questions}
                onSelect={({ value }) => setQuestionDrop(questions.find(i => i._id === value))}
            />
        </div>
    )
}