How to add the values ​in an array of objects depending on the date value of each object

I have this array:

[{start_date: "2022-12-05T04:00:00Z" ,distance: 1000, time: 3600} 
,{start_date: "2022-02-07T04:00:00Z" ,distance: 1500, time: 6400},
{start_date: "2022-12-08T04:00:00Z" ,distance: 1000, time: 1300}]

I want to add the distance and time values ​​grouping them by the month indicated by the start_date value. For example, if two start_dates have the same month 2022-12-01 and 2022-12-08, how can I add the distance and time values ​​of those two months?

so i get a new array like this:

 [{month: 12 ,total distance: 2000, total time: 4900}, 
  {month: 02 , total distance: 1500, total time: 6400} ]

Wait sometime before loading a widget onto a page

I’m new to programming and the following code I got through an open source project.

I’m loading a widget on a website. So instead of immediately loading the widget, I want it to take 10 secs before showing the widget.

I was wondering what is the right way to achieve it?

Entire code below…………

switch (methodName) {
            case 'init':

                const loadedObject = Object.assign(defaultConfig, item[1]);
           
                // the actual rendering of the widget
    
                const wrappingElement =
                    loadedObject.element ?? win.document.body;
                targetElement = wrappingElement.appendChild(
                    win.document.createElement('div')
                );
                targetElement.setAttribute('id', `widget-${instanceName}`);
                render(targetElement, loadedObject);

                // store indication that widget instance was initialized
                win[`loaded-${instanceName}`] = true;
                break;
    
            default:
                console.warn(`Unsupported method [${methodName}]`, item[1]);
        }

    }

Close Modal with JavaScript

I’m trying to close my modal when add to cart button is clicked.

here is the code for the button to close:

<button class="btn btn-info btn-block addItemBtn" id="closemodal" >&nbsp;Add to cart</button>

here is the javascript code:

          $(document).ready(function() {

            // Send product details in the server
            $(".addItemBtn").click(function(e) {
              e.preventDefault();
              var $form = $(this).closest(".form-submit");
              var pid = $form.find(".pid").val();
              var pname = $form.find(".pname").val();
              var pdesc = $form.find(".pdesc").val();
              var pprice = $form.find(".pprice").val();
              var pcode = $form.find(".pcode").val();
              var pqty = $form.find(".pqty").val();

              $.ajax({
                url: 'action.php',
                method: 'post',
                data: {
                  pid: pid,
                  pname: pname,
                  pdesc: pdesc,
                  pprice: pprice,
                  pqty: pqty,
                  pcode: pcode
                },
                success: function(response) {
                  $("#message").html(response);
                  window.scrollTo(0, 0);
                  load_cart_item_number();
                }
              });
              $('#closemodal').click(function() {
                $('#modalwindow').modal('hide');
              });
            });
         });

When I clicked the add to cart button that I want is added to cart but the modal is still open. I want it to automatically closes when the button is clicked.

Issue with state variables of a class and dictionaries inside a constructor

I have to instantiate the class obj1, which returns a dict, and pass this object into another instantiation of a class like this:

const obj1 = new Class1() 
const obj2 = new Class2({ obj1, id: 8 })

This works fine, but the problem comes when i wrap this process into a class.

Class X () {
    constructor(newId) {
    this.obj1 = new Class1()
    this.obj2 = new Class2({this.obj1, id: newId})
    }
}

This time it throws Referenceerror: obj1 is not defined when i instantiate the class.

I think it’s because node tries to read this.obj1 as this:obj1 since we are in the context of a dict.

This might seem stupid but I’m stuck.
Any help ?

Get a value from an object inside an object

How do I get the id 43 from country ?

"hq_locations":[{"id":1886112,"address":"10 Rue Laurencin, 69002 Lyon, France","street":"Rue Laurencin","street_number":"10","zip":"69002","lat":45.7527311,"lon":4.8321804,"country":{"id":43,"name":"France","lat":46.227638,"lon":2.213749,"trade_register_office":"Info Greffe"}

How to add elements to the particular key in javascript?

“pfm_csp_56525_1_ck” :
{FLD_universityobject_Entry_Web_universityobject_DUMMY$$universityname_input : “none”}

“pfm_csp_56525_1_ck” :
{FLD_universityobject_Entry_Web_universityobject_DUMMY$$universityemail_input : “none”}

“pfm_csp_56525_1_ck” :
{FLD_universityobject_Entry_Web_universityobject_DUMMY$$address_input : “none”}

“pfm_csp_56525_2_ck” :
{FLD_universityobject_Entry_Web_universityobject_DUMMY$$location_input : “none”}

“pfm_csp_56525_2_ck” :
{FLD_universityobject_Entry_Web_universityobject_DUMMY$$status_input : “none”}

i need this elements to the particular group like (example) = >

public compositeSet = {
“pfm_csp_56525_1_ck” : {‘FLD_institute_d_w_entry_institute_dummy$$secretcode_input’:”none”, ‘FLD_institute_d_w_entry_institute_dummy$$addressline1_input’: “none” },
“pfm_csp_56525_2_ck”: {‘FLD_institute_d_w_entry_institute_dummy$$email_input’: “none”, ‘FLD_institute_d_w_entry_institute_dummy$$institutename_input’: “none” },
}

I get an empty error when submitting multiple forms with file uploads with ajax in laravel

my problem is while posting multiple forms with ajax in laravel, I am sending the form data without any problem, but I cannot send the file.
File is empty error. I’ve been dealing with this for 2 days, there is no method I haven’t tried, please help me.
Apart from that, I added multipart to the form, but it still didn’t work, I’m sharing my codes with you.

Sorry for my bad english.

I want it to upload 2 photos in the normal 4th form until the createProduct3 form, I tried to get them by doing the normal new formData() and I tried otherwise and I couldn’t succeed.
It sends it to Laravel server side as [Object File].
My Form

<form class="form" id="createProduct4" method="POST" action="">
<input type="file" class="upload-box-title" id="urun-fotografi" name="urun_fotografi" value="Fotoğraf Seç">
<input type="file" class="upload-box-title" id="urun-dosyasi" name="urun_dosyasi" value="Dosya Seç">
</form>

My blade ajax:

function createProducts()
{
    var dataString = $("#createProduct1, #createProduct2, #createProduct3, #createProduct4").serialize();
    let photo = document.getElementById("urun-dosyasi").files[0];
    let photo2 = document.getElementById("urun-fotografi").files[0];
    console.log(photo,photo2);

    $.ajax({
        url: "{{ route('user.product.create') }}",
        type: "POST",
        data: dataString+"&urun_dosyasi="+photo+"&urun_fotografi="+photo2,
        success: function( data ) {
            $('#submit').html('Submit');
            $("#submit"). attr("disabled", false);
            Swal.fire({
                title: "Bilgi mesajı!",
                html: data,
                showConfirmButton: true
            })
        },
        error: function(xhr)
        {
            console.log(xhr);
            var err = JSON.parse(xhr.responseText);
            Swal.fire({
                title: "Hata!",
                html: err.message,
                icon: 'error',
                showConfirmButton: true
            })
        }
    });
}

Server Function

 public function createProduct(Request $request)
{
    $file = $request->file('urun_dosyasi');
    $file2 = $request->file('urun_fotografi');
    $filename = $file->getClientOriginalName();
    $extension = $file->getClientOriginalExtension();
    $filename2 = $file2->getClientOriginalName();
    $extension2 = $file2->getClientOriginalExtension();

    echo $filename,$extension."2. doc: ".$filename2.$extension;
}

Javascript error:

Screenshot a error image

Filter arrays inside array on the basis of status

I have a array which contains multiple arrays. Sample data is as follows:

[
[
  {
    "id":1,
    "status":1
  },
   {
    "id":2,
    "status":2
  },
   {
    "id":3,
    "status":3
  },
   {
    "id":4,
    "status":4
  }
],
[
   {
    "id":5,
    "status":1
  },
   {
    "id":6,
    "status":2
  },
   {
    "id":7,
    "status":3
  },
   {
    "id":8,
    "status":4
  }
],
[
  {
    "id":8,
    "status":1
  },
   {
    "id":9,
    "status":1
  }
]
]

I am using PrimeNg checkbox. My code for it as follows:

<h5>Multiple</h5>
<div class="p-field-checkbox">
  <p-checkbox
    name="group1"
    value="New York"
    [(ngModel)]="selectedCities"
    inputId="ny"
  ></p-checkbox>
  <label for="ny">New York</label>
</div>
<div class="p-field-checkbox">
  <p-checkbox
    name="group1"
    value="San Francisco"
    [(ngModel)]="selectedCities"
    inputId="sf"
  ></p-checkbox>
  <label for="sf">San Francisco</label>
</div>
<div class="p-field-checkbox">
  <p-checkbox
    name="group1"
    value="Los Angeles"
    [(ngModel)]="selectedCities"
    inputId="la"
  ></p-checkbox>
  <label for="la">Los Angeles</label>
</div>
<div class="p-field-checkbox">
  <p-checkbox
    name="group1"
    value="Chicago"
    [(ngModel)]="selectedCities"
    inputId="ch"
  ></p-checkbox>
  <label for="ch">Chicago</label>
</div>

Stackblitz is as follows:

https://stackblitz.com/edit/primeng-checkbox-demo-d9kasz?file=src%2Fapp%2Fapp.component.html

I want to filter array such that if “New York” is selected then each internal array should have only elements with status 1.If “San Francisco” is selected then each internal array should have only elements with status 2. if “Los Angeles” is selected then each internal array should have only elements with status 3. If “Chicago” is selected then each internal array should have only elements with status 4. For example if “New York” is selected than final output should be as follows:

output : [
[
  {
    "id":1,
    "status":1
  }
],
[
   {
    "id":5,
    "status":1
  }
],
[
  {
    "id":8,
    "status":1
  },
   {
    "id":9,
    "status":1
  }
]
]

and so on for other elements. How can I do this?

Lerna / Nx / Turborepo or other monorepo systems for non-js apps (php)

I have repository with /frontend (JS/Vue) and /backend (PHP) and docker-compose.yml for development. But now I need to add another JS frontend that will be sharing some components, libs etc. I do not want to repeat code, so I found that I can use many tools for this like lerna, nx, turborepo and more for managing monorepo with shared packages.

Problem is that all tutorials and example repos I found are based on 100% JS repos, like React on front + Nest on back etc.

So question – using for ex. nx makes sense on repos with multiple languages, just to leverage it on JS packages? If yes, how directory structure should look like? Or maybe there are better monorepo tools that are designed for multiple languages, not just JS?

Calculate the No. of possible ways two chess pieces can be placed [closed]

This was one of the questions asked in a mock test. If any one has seen this problem somewhere else or know the solution, please help me out.

A famous chess grandmaster was analyzing one of his games in his head and… he suddenly forgot the positions of two important pieces.

However, he is sure about some facts:

  • the location of the first piece on the board is (x1; y1) and xl1 <=
    x1 <= xr1, yl1 <= y1 <= yr1.
  • the location of the second piece on the board is (x2; y2) and xl2
    <= x2 <= xr2, yl2 <= y2 <= yr2.
  • the chessboard cells corresponding to the pieces are of the same
    color.

In other words, he doesn’t remember the exact positions of the pieces, however, for every piece, he is sure about the part of the board where it can be. Part of the board here is just a rectangular submatrix described by 4 coordinates.

Note: obviously, two pieces can’t be in the same location.

Now the grandmaster is wondering, how many placements of this two pieces are possible if he remembers everything correctly?

Input Format:

  • The first line contains an integer, x1, denoting the minimum possible
    row of the first piece.
  • The next line contains an integer xr1, denoting the maximum possible
    row of the first piece
  • The next line contains an integer, yl1, denoting the minimum possible
    column of first piece
  • The next line contains an integer yr1, denoting the maximum possible
    column of the first piece.
  • The next line contains an integer, xl2, denoting the minimum possible
    row of the second piece.
  • The next line contains an integer, xr2, denoting the maximum possible
    row of the second piece.
  • The next line contains an integer, y12, denoting the minimum or
    possible the second piece.
  • The next line contains an integer, yr2, denoting the maximum possible
    column of the second piece.

Sample Input:
Image with sample input and output

Thanks

I have been trying in the past few days to solve this problem and i can’t

Whenever I add an addEventListener, or a toggle in javascript, I get ”can’t read **** of null” or ”can’t read of undefined”. I tried many different ways to solve it, deleting the javascript file and recreating it, putting everything inside an “addEventListener(‘DOMContentLoaded, …’), moving the javascript code in html file. Nothing works, I don’t know why. I tried all the ways that they say on the internet that work.

enter image description here

(In what manner should I) feed Excel file into MySQL?

Disclaimer, this not looking for HOW (yet), but asking which method is safer and/or more efficient. This is possibly subjective.

I can see 2 processes when reading an excel file and feeding it into a MySQL database. Either:

  1. Convert whole file into one Insert statement
  2. Insert one row at a time

I thought about #1, and can see it working, but I also have a step after this: I need to normalize (separate into multiple connected tables) the content.

If I insert one row at a time, I can weave the normalization within the insertion as a stored procedure.

If I insert as a giant sql file, I just need to clean up afterwards cells of the same values and columns.

While my tables aren’t millions of rows, I still am just one person, so any way to make it easier for me would be appreciated.

So, which sounds better? Clean up a giant file? or Loop the file’s rows one at a time?

Is it fine to use the same mkcert certificate for both your frontend and backend?

I’m developing a webapp that uses vite on the frontend for my local testing environment and also a separate API backend.

I used mkcert to generate a local dev certificate and am using that one for the backend.

My question is, for my frontend dev environment I also can use a certificate, as shown here in the vite config:

server: {
  https: {
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem'),
  },
  proxy: {
    '/v1': {
      target: 'https://127.0.0.1:8080'
    }
  }
}

My question is: can I use this same generated certificate (key.pem and cert.pem) for my backend and frontend servers? It seems to work okay, but I’m not sure of the implications for this.

I generated my mkcert certificate using the following command:

mkcert localhost 127.0.0.1 ::1 192.168.1.96

Toggle image source with vanilla javascript function

I am trying to swap an SVG logo image on click using Javascript. My script looks like this:

document.querySelector('.logo').addEventListener('click', function() {
    document.querySelector('#logo-switch').src='logo-B.svg';
    document.querySelector('#logo-switch').src='logo-A.svg';
    })

The function works on the first click (when the third line of code is removed):
document.querySelector('#logo-switch').src='logo-A.svg';

However, I would like for it to switch back to the original src each time the logo is clicked — this should function as a toggle.

Is this done with an if statement? Or how is this achieved?

Many thanks