‘parsererror’ error In MYSQL Axaj Django upload in chunks

I want to upload a file in chunks, and it works on SQLite but i wont work with MYSQL, and it uploads the file only till 10mb/11mb. Debug false/true gives me the same error

JS:

    $.ajax({
        xhr: function () {
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    if (self.file.size < self.max_length) {
                        var percent = Math.round((e.loaded / e.total) * 100);
                    } else {
                        var percent = Math.round((uploadedChunk / self.file.size) * 100);
                    }
                    $('.progress-bar').css('width', percent + '%')
                    $('.progress-bar').text(percent + '%')
                }
            });
            return xhr;
        },

        url: '/create-post',
        type: 'POST',
        dataType: 'json',
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        error: function (xhr) {
            alert(xhr.statusText);
        },
        success: function (res) {
            if (nextChunk < self.file.size) {
                // upload file in chunks
                existingPath = res.existingPath
                self.upload_file(nextChunk, existingPath);
            } else {
                // upload complete
                $('.textbox').text(res.data);
                alert(res.data)
            }
        }
    });
}};

Views:

https://imgur.com/a/FThSXAO

All of this gives me

parsererror

Nothing else…

How toInvisible Undefined last element in JS array

I have a Javascript array, full_range:

const range1 = _.range(1, 10, 0.5);
const range2 = _.range(10, 100, 5);
const range3 = _.range(100, 1000, 50);
const range4 = _.range(1000, 10000, 500);
const range5 = _.range(10000, 105000, 5000);
const full_range = range1.concat(range2).concat(range3).concat(range4).concat(range5);

I then loop over this array and populate another array.

var transY= [];
var transX= [];
for(let i = 0; i < full_range.length; i++){
    let y = getTrans(full_range[i], dampingFactor, natFreq); //returns a float
    transY.push(y);
    transX.push(parseFloat(full_range[i]));
    }

The result is then returned to another function where:

console.log(transX); //Correct: Prints Array of 91 length (although the numbers with //decimals are at the end for some reason
console.log(transY); //Correct: Prints Array of 91 length
console.log("first");
console.log(transX[0]); //Correct: Prints 1
console.log("Last"); 
console.log(transX[-1]); //Incorrect: Prints "undefined instead of the last item

let xd = transX.pop();
console.log("xd:" + xd); //Works and correctly prints the last item in transX

The goal is to graph this dataset on a BokehJS graph, which does weird things when the last value is undefined.

Why is “undefined” being treated as an array element using slicing, but not when using pop()?

How would I be able to get the array without the undefined element?

How to concatinate string to array item name, inside function

I have a function that is taking in multiple parameters. Using spread operator. But I am stuck in trying to figure out how to concinate the name of each item with a ‘val’ to the end of it. Here is is what I have so far….

//what I am calling
_setReadOrgVals($mfirstname, $mlastname, $mchapname, $mchapnameass, $mnumber, $memail, $mgender, $memailparent, $memailadv, $mffaid);

//the function
function _setReadOrgVals(...$fields) {
  for (i = 0; i < $fields.length; i++) {
    $fields[i].attr('readonly', true).addClass('bg-black25').val($fields[i] + 'val');
    //I want it to feel like I am doing this...
    //$mfirstname.attr('readonly', true).addClass('bg-black25').val($mfirstnameval);
    //But I don't know how...my example above does not work...
  }
}

as a result, my input element outputs…

[object Object]val

Here is an example of first name I am using to go with my code above…

var $mtarget = window.jQuery('.custom-location');
var $mfirstname = $mtarget.find('#pro_fname');
var $mfirstnameval = $mfirstname.val();

So I basically want $mfirstnameval to be inside of the .val() in my example above. But feel stuck at this point…

two dtos for one controller in NestJS

I’m trying to get different types of dtos from body. If firstDto is incoming get it and transform, if secondDto is incoming transform it to secondDto. But it’s not working and I have no idea. Here is my code;

@Controller('log')
export class LogsController {
  constructor(private logsService: LogsService) {}

  @Post()
  async createStatusLog(@Body() body: CreateMessageDto | CreateStatusDto) {
    console.log(body.constructor.name);
    return body;
  }
}

app.module.ts

providers: [
    AppService,
    {
      provide: APP_PIPE,
      useValue: new ValidationPipe({
        whitelist: true,
        transform: true,
      }),
    },
  ],

how do i check if i got the right console.log output?

I am making a binary to text generator, and I need to see if I can use a console.log output in an if else statement; this is the code that I made and tried to use for this.

if (console.log(a,b,c,d,e,f,g,h) = 0 1 1 0 0 1 0 0) {console.log(‘d’)}

when i ran it, and the output was the desired outcome, and the if else was true, it would output the letter d into the console.

Date field from SQL returning date minus 1 with Node/JS

I have a very simple SQL string that brings a Date field from sql:

SELECT dbo.table.effDate from table where.....

I need to convert that date to a date variable at Node so I can perform a calculation. This date is always the first of a month, so my results at SQL are

2023-01-01
2022-05-01
2022-08-01

etc.

So, when I try to convert the field to a node date type, in these different ways, I always get the previous date of the one at the field (for the example above)

2022-12-31
2022-04-30
2022-07-31

Im using:

let effDate = moment(response[i].effDate, 'YYYY-MM-DD').format('YYYY-MM-DD')

Then

let effDate = new Date(response[i].effDate)

even this is bringing me a previous date

let effDate = response[I].effDate.toString()

and this:

let effDate = new Date(response[I].effDate).toLocaleDateString('en-US')

I could fix this by adding one day to whatever SQL brings me back, but its not the point, I want to do it right.

I also tried using getTimezoneOffset

effDate = new Date(response[i].effdate.getTime() - response[i].effdate.getTimezoneOffset() * 60000)

But I always get the previous date.

What confuses me is that javascript UTC zones should have nothing to do when it comes to the value returned by SQL:

enter image description here

Again, I could just add a day but that wont be right, and I would like to know why this is happening (even using toString()).

Thanks.

Checking the strength of a password (JavaScript)

I am trying to check the strength of a password and I am having trouble validating that if the function has an empty argument, it should return “invalid” but I am getting “weak” instead.

function passwordStrength(password) {
  let strengthCounter = 0;
  for (const prop in regexObj) {
    if (!regexObj[prop].regex.test(password) && (!Object.values(regexObj)[0].regex.test(password) || !Object.values(regexObj)[1].regex.test(password))) {
      strengthCounter;
    } else if (regexObj[prop].regex.test(password) && Object.values(regexObj)[1].regex.test(password)) {
      strengthCounter++;
    }
  }

  if (strengthCounter >= 6) return strengthStatusObj.strong;
  if (strengthCounter >= 4) return strengthStatusObj.medium;
  if (strengthCounter == 3) return strengthStatusObj.weak;
  if (strengthCounter < 3) return strengthStatusObj.invalid;
}

Create Custom Social Share Buttons in angular

I will appreciate any ideas and support for this issue

I have an angular project and I try to create icons share buttons for social media.
I have a component named landing.component. in the HTML file I implemented a Modal popup to allow showing a new windows where I have the icons. Please, follow screenshots below

Here I click the share button

Below, is the new windows

new windows opened with share icons

the HTML code is here

<div class="card-wrapper" fxLayout="row wrap" fxLayoutAlign="start start">
  <div
    class="card active-card"
    fxFlex="25"
    *ngFor="let category of categories"
    (click)="categoryClick(category)"
  >
    <picture>
      <img [src]="category.imageLocation" />
    </picture>
    <div class="card-overlay" fxLayout="row wrap" fxLayoutAlign="center end">
      <span class="card-title" fxFlex="100">{{ category.title }}</span>
      <div class="card-buttons" fxFlex="100" fxLayout="row">

        <ul class="list-inline text-center member-icons ">
          <li class="list-inline-item">
            <button mat-icon-button disableRipple class="btn btn-primary" routerLink="/mtl"  (click)="open(content)"><i class="fa-solid fa-share"></i></button>
          </li>
          <span fxFlex></span>
        </ul>

        <!-- <button mat-icon-button disableRipple>
          <heart-icon></heart-icon>
        </button> -->
        <!-- <span fxFlex></span> -->
        <!-- <button mat-icon-button disableRipple> -->
          <!-- <download-icon></download-icon> -->
       <!--  </button> -->
      <!--   <button mat-icon-button disableRipple>
          <share-icon></share-icon>
        </button> -->
      </div>
    </div>
  </div>
</div>

<section
  class="cragcity-container p-t-5"
  fxLayout="row"
  fxLayoutAlign="space-between start"
>
  <div style="margin: auto">
    <img class="socmed-icon m-r-15" src="./assets/icons/facebook.webp" />
    <img class="socmed-icon m-r-15" src="./assets/icons/skype.webp" />
    <img class="socmed-icon" src="./assets/icons/instagram.webp" />
  </div>
</section>


<ng-template #content let-modal>
    <div class="modal-header">
        <h4 class="modal-title" id="modal-basic-title">Share Social Media</h4>
        <button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
    </div>
    <div class="modal-body">


    <form>
            <div class="mb-3">
                <label for="Social Media"></label>

        <div class="share-btn-container">
          <a #facebook href="#" class="facebook-btn">
            <i class="fab fa-facebook"></i>
          </a>
          <a href="#" class="twitter-btn">
            <i class="fab fa-twitter"></i>
          </a>

          <a href="#" class="pinterest-btn">
            <i class="fab fa-pinterest"></i>
          </a>

          <a href="#" class="linkedin-btn">
            <i class="fab fa-linkedin"></i>
          </a>

          <a href="#" class="whatsapp-btn">
            <i class="fab fa-whatsapp"></i>
          </a>
        </div>
                <!-- <div class="input-group">
                    <input

                        name="dp"
                        ngbDatepicker
                        #dp="ngbDatepicker"
                    />
                    <button class="btn btn-outline-secondary bi bi-calendar3" (click)="dp.toggle()" type="button"></button>
                </div> -->
            </div>
        </form>


    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Close</button>
    </div>
</ng-template>

<app-cragcity-footer></app-cragcity-footer>

In the facebook option, I created a variable #facebook that will allow me to use viewchildren in the ts file to do an elementref and find the element in the DOM.
In the viewchildren option, I created a variable link1.

then, in the ngAfterViewInit I created two variables url and title. the url variable will take the link of my page to be share and the title is just message.
Finally, I used this command:

this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)

(this is what I believe is the same in js document.location.href) but used in ts

The code is not working, basically when I click the facebook icon only close the windows and that’s it and the web shows me this error here bbelwo:

no sure if that is relevant

the landing. component.ts code is here below:

import { Component, OnInit, Input, ViewChild, ElementRef, AfterViewInit, ViewChildren } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DataService } from 'src/app/core/services/data.service';
import { category } from '../models/category';

import { ModalDismissReasons, NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.scss']
})
export class LandingComponent implements OnInit, AfterViewInit {

  public categories = new Array<category>();
  @Input() name;

  url:string;
  title:string;

  closeResult: string | undefined;


  constructor(private _dataService: DataService, private router: Router, private modalService: NgbModal, private route: ActivatedRoute) {

  }


  ngOnInit(): void {
    this.retrieveCategories();
  }

  @ViewChildren("facebook")link1: ElementRef;


  ngAfterViewInit() {

    this.url = this.router.url;
    /* this.link1.nativeElement = this.url; */

    this.title = encodeURI("Facebook");


    this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)
    /* console.log(this.link1);
    console.log(this.url);
 */
    /* this.link1.nativeElement.setAttribute('xlink:href') */
  }


  retrieveCategories() {
    const actionUrl = 'v1/category';
    const params = {};
    this._dataService.get<any>(actionUrl, params)
      .subscribe(data => {
        if (data !== null) {
          if (!data.isError) { this.categories = data.result; }
        }
      });
  }

  categoryClick(data: category) {
    if (data.subCategory.length > 0)
      this.router.navigate(['mtl', data.id]);
  }

  open(content) {
        this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then(
            (result) => {
                this.closeResult = `Closed with: ${result}`;
            },
            (reason) => {
                this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
            },
        );
    }

  private getDismissReason(reason: any): string {
        if (reason === ModalDismissReasons.ESC) {
            return 'by pressing ESC';
        } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
            return 'by clicking on a backdrop';
        } else {
            return `with: ${reason}`;
        }
    }

}

I really appreciate any help

Regards

Dynamically add a referenced field to another document using Sanity

I have a sanity v3 document. In which There is a Pin section which contains

  • Title -> String
  • about -> String
  • destination -> String
  • image -> Url
  • savedBy [ ] -> Array
  • commentedBy [ ] -> Array of referenced Value

QUESTION: So, the commentedBy section is an array of referenced object field, where it is pointing to the Comment document.

Now, If I want to add a comment to a Pin, first i have to manually create that comment (which is expected), after that I manually set/reference the comment to that pin.

Problem: Is that whenever i/someone creates a new comment that comment should automatically be added/referenced to the pin document! Which it does not do. For now Manually I have to do it!

Attempts:

  • I have tried adding referencing the comment section to the Pin document.
  • Tried creating a whole comment section inside of the Pin document. At the end it messes up with the code!

Work-around: Well there is a cheap solution to solve this problem. For example, whenever comment is made manually set the reference to the pin Section, simultaneously creating the comment. This might work around for small group of users but for large group of users this will put a lot of pressure to the backend.

Search: For these different approaches I looked into these websites! Sanity Doc v3,
Sanity Cross-Reference

Code:

  // comment.js document

  export default defineType({
  name: 'comments',
  title: 'Comments',
  type: 'document',
  fields: [
    defineField({
      name: 'pinId',
      title: 'PinId',
      type: 'reference',
      to: [{type: 'pins'}],
    }),
    defineField({
      name: 'postedBy',
      title: 'PostedBy',
      type: 'reference',
      to: [{type: 'user'}],
    }),
    defineField({
      name: 'comment',
      title: 'Comment',
      type: 'string',
    }),
  ],
  })

// pin.js document
export default defineType({
  name: 'pins',
  title: 'Pins',
  type: 'document',
  fields: [
    defineField({
      name: 'title',
      title: 'Title',
      type: 'string',
    }),
    defineField({
      name: 'about',
      title: 'About',
      type: 'string',
    }),
    defineField({
      name: 'destination',
      title: 'Destination',
      type: 'url',
    }),
    defineField({
      name: 'category',
      title: 'Category',
      type: 'string',
    }),
    defineField({
      name: 'userId',
      title: 'userId',
      type: 'string',
    }),
    defineField({
      name: 'image',
      title: 'image',
      type: 'image',
      options: {
        hotspot: true,
      },
    }),
    defineField({
      name: 'postedBy',
      title: 'Posted By',
      type: 'reference',
      to: [{type: 'user'}],
    }),
    defineField({
      name: 'save',
      title: 'Save',
      type: 'array',
      of: [{type: 'save'}],
    }),
    defineField({
      name: 'comments',
      title: 'Comments',
      type: 'array',
      of: [
        {
          type: 'reference',
          to: [{type: 'comments'}],
        },
      ],
    }),
  ],
})

How to make an asymmetric gallery?

how can i make the same asymmetric gallery as in the view below, with all 4 images of different sizes in each header in a different place, while it is only in two columns, regardless of the size of the monitor?

1

I didn’t even find an example of this anywhere.

Is it worth to use MUI/ChakraUI with NextJS?

I am quite new to NextJS and I were developing apps using React and Django before. So please correct me if I am miss understanding some points. I have some questions about NextJS, however I searched a lot but couldn’t find my clear answers and they confused me.

1- Is NextJS really suitable for backend? I searched about this; there are two answers (yes it is full-stack/No, better to use other backend specific frameworks)

2- Doesn’t using MUI/ChakraUI breaks the NextJS concept? because when the site is based on MUI every component is a client component right? So, what ever I am going to show the user is a client component that it becomes something like pure react.

Linkedin sign in not working, errors sgugest that the library is not fully loaded

So I have this javascript code:

$(document).ready(function () {
    $("#login_with_linkedin").on("click", requestAuthLinkedIn);
    googleInit();
    LinkedInInit();
});

function LinkedInInit() {
    $.getScript("https://platform.linkedin.com/in.js", function () {
        IN.init({
            api_key: MY_API_KEY,
            authorize: true,
            onLoad: function () {
                IN.Event.on(IN, "auth", function () {
                    onLinkedInAuth();
                });
            },
            scope: "r_basicprofile r_emailaddress openid email profile"
        });
    });
}

function onLinkedInAuth() {
    IN.API.Profile("me").result(function (data) {
        var profile = data.values[0];
        console.log(profile);
    });
}

function requestAuthLinkedIn() {
    IN.User.authorize();
}

This would be the frontend part:

<div id="loginLinkedIn" runat="server" visible="false">
    <div id="login_with_linkedin">
        <img src="<%= ComunControls.Global.URL_Resources %>i/login/LinkedIn_SignIn.png" alt="" />
    </div>
</div>

The problem is that when I click on the linkedin “button”(image), I keep gettint this error in the javascript console

Uncaught TypeError: Cannot read properties of
undefined (reading ‘then’)
at Object.authorize (in.js?_=1676306000491:25:68028)
at HTMLDivElement.requestAuthLinkedIn (:38:13)
at HTMLDivElement.dispatch (com_5jq.min.js?v=382:2:68763)
at a.handle (com_5jq.min.js?v=382:2:66808)

If I’m not mistaken, the linkedin JS is fully loaded when I try to trigger the event, so I don’t really know what I’m doing wrong

Yup validation with ISO Format in REACT

I am trying to validate date using Yup validation. The requirement is that the ToDate should be greater or equal to the fromDate.

fromDate : ‘2022-02-13T16:31:13.983Z’

toDate : ‘2023-02-01T00:00:00.000Z’

REQUIREMENT

  • toDate >= fromDate
        fromDate: Yup.string().required('required.'),
        toDate: Yup.string().required('required')
        .test(
            "fromDate",
            "To Date should be greater or equal to From Date",
            (date) => moment().isAfter(moment(date), 'hours')
          ),

But it seems the logic is quite wrong. . I’d appreciate your help. Thanks.