Filtering MongoDB collection by a partial match on a single object in an array

In MongoDB I have a collection of documents like this:

{
    name: "john",
    animals: [...arrayOfAnimals],
    cars: [...arrayOfCars],
    
}

where an example of an animal would be:


{
    animal: "horse",
    age: 15,
    name: "bob",
}

and where an example of a car would be:

{
    manufacturer: "nissan",
    year: 2015,
    convertible: false,
}

How would you filter the collection to get a list of documents that matches all the partial input objects?

e.g.
if I have two objects A and B that are partial animals, and two objects C and D that are partial cars, then this object would be returned as there is a match on all the inputs:

{
    name: "mike",
    animals: [
        {A, missing properties},
        {B, missing properties},
        ...other animals
    ],
    cars: [
        {C, missing properties},
        {D, missing properties},
        ...other cars
    ],
    
}

but this object would not be returned because it does not have a match on B:

{
    name: "jenny",
    animals: [
        {A, missing properties},
        ...other animals
    ],
    cars: [
        {C, missing properties},
        {D, missing properties},
        ...other cars
    ],
    
}

I can already filter for matches of full child objects with $elemMatch but can’t get it to work for matches of partial objects.

How can I remove the .html from the URL?

I am creating a page using only JavaScript and the page that I am being redirected from the main html file has a .html extension.(http://127.0.0.1:5501/products.html) . I want my URL file to be http://127.0.0.1:5501/products. I also need to mention that I am not using a server at the moment and I am fetching the products from a JSON local file using async and await. How to remove the .html in the URL?

The link redirection in my index.html file :

 <li><a href="./products.html">Продукти</a></li>

and my JavaScript file

document.addEventListener('DOMContentLoaded', () => {
spinner.style.display = 'block';
const fetchHoney = async () => {
    try {
        const response = await fetch('/products.json');
        const data = await response.json();
        if (!response.ok) {
            throw new Error(`HTTP error! status:${response.status}`)
        } else {
            return data;
        }
    } catch (error) {
        content.innerHTML = "There was a problem! Please refresh the page and try again.";
        content.classList.add('errorMsg');
    }

}

fetchHoney().then(data => {
    let arrayPrice = '';
content.style.display = 'none';



    const displayHoney = () =>{
        const filteredHoney = data.filter(data => data.listing === 'honey');
        const productsHoney = filteredHoney.map((product) => {
            const {id,name,image,price} = product;

            if (Array.isArray(price)) {
                arrayPrice = price.join(' денари - ');;
            } else {
                arrayPrice = price;
            }

            return `    
            <div class="b-products__wrap">
            <div class="bla">
            <img class="b-products__img b-products__img${id}" src="${image}" alt="">
            
            </div>
            <div class="b-products__name b-products__name${id}">${name}</div>
            <div class="b-products__price">${arrayPrice} денари</div>       
            </div>`;
        }).join('');

    honeyProducts.innerHTML = productsHoney;

    }


  const displayBees = () =>{
      const filteredBees = data.filter(data => data.listing === 'bee');
        const productsBees = filteredBees.map((product) => {

            const {id,name,image,price} = product;


            if (Array.isArray(price)) {
                arrayPrice = price.join(' денари - ');
                console.log(arrayPrice);
            } else {
                arrayPrice = price;
            }

            return `
            <div class="b-products__wrap">
            <div class="bla">
            <img class="b-products__img b-products__img${id}" src="${image}" alt="">
            
            </div>
            <div class="b-products__name b-products__name${id}">${name}</div>
            <div class="b-products__price">${arrayPrice} денари</div>
            </div>`;
        }).join('');
        
        beeProducts.innerHTML = productsBees;

  }  
  displayHoney();
  displayBees();

  setTimeout(() => {
spinner.style.display = 'none';      
content.style.display = 'flex';

 }, 1000);

  });

})

How to import data to excel without error?

Hi my problem is that when importing a file into excel. ExportToXls method builds a complete CSV content in the form of an HTML table. Once I download the xls file then when opening it in Excel I get an error stating “The file you are trying to open .xls has a different format than specified by the file extension. The file may be corrupt or from an untrusted source. Do you want to open the file?”. The file opens fine formatted with correct data but I want it to not open with the error message. I think the problem is with wrong datatype. Any suggestions?

var ExportCsv = ExportCsv || {}

ExportCsv.exportToXls = function (columnMetadata, fileName){
//headers generation...
//rows generation...
// rows and headers are in html data which are in htmldata variable

var data_type = 'data:application/vnd.ms-excel;charset=utf-8,%EF%BB%BF';
var fileName = (fileName === undefined || fileName === null || fileName === "" ? "export" : fileName) + ".xls"
ExportCsv.exportDataToXls(fileName, htmldata, data_type)
return null;
}

ExportCsv.exportDataToXls = function (filename, htmldata, data_type) {
var blob = new Blob(["ufeff" + htmldata], { type: data_type });
if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveBlob(blob, filename);
}
else {
    var elem = window.document.createElement('a');
    elem.href = window.URL.createObjectURL(blob);
    elem.download = filename;
    document.body.appendChild(elem);
    elem.click();
    document.body.removeChild(elem);
}
}

export default ExportCsv

.NET 7.0 MVC Sending View to Controller Custom List Object

I send the list information I took from the Web API to the Web Page as a list via the Controller. Here I show the elements I need. I want to bulk delete the items I selected as checkboxes from these displayed elements. The relevant function falls on the Controller, but the parameter is empty.

This is where I send my list from controls to view.

try
{
    List<Material> MaterialInfo = new List<Material>();

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Baseurl);
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage Res = await client.GetAsync("api/Materials");
        if (Res.IsSuccessStatusCode)
        {
            var MaterialsResponse = Res.Content.ReadAsStringAsync().Result;
            MaterialInfo = JsonConvert.DeserializeObject<List<Material>>(MaterialsResponse);
            CurrentMaterials.Add(MaterialInfo);
        }
        return View(MaterialInfo);
    }
}
catch (Exception)
{
    return View();
}

This part is the parameters that I show on the screen in View.

<tbody>
    @using (Html.BeginForm("StartProcedure", "LastedStatus", FormMethod.Post))
    {
        @foreach (var material in Model)
        {
            @if(material.CabinStatus == CabinStatus.outCabin)
            {
                <tr>
                    <td>
                        @Html.CheckBoxFor(r => material.isSelected, new { @class = "checkbox" })
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.Code)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.Description)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.BatchNumber)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.RfId)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.Weight)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.MaterialDrawerNo)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.MaterialLocation_X)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.MaterialLocation_Y)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.RemainingTime)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.PickUpTime)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.OutsideTime)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.CabinStatus)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.TimeAlarm)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.LifeEnding)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => material.TimeProcess)
                    </td>
                </tr>
            }
        }

        <input type="button" id="deleteItems" value="Delete Selected Items" name="Verify Order Information" class="btn btn-primary btn-large" />
    }
    
    
</tbody>

The action performed when the Delete button is pressed in this section.

@section scripts{
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">

        $("body").on("click", "#deleteItems", function () {
            //Loop through the Table rows and build a JSON array.
            var materials = new Array();
            $("#table BODY TR").each(function () {
                var row = $(this);
                var material = {};
                material.isSelected = row.find("td:eq(0)").html();
                material.Id = row.find("td:eq(1)").html();
                material.Code = row.find("td:eq(2)").html();
                material.Name = row.find("td:eq(3)").html();
                material.Description = row.find("td:eq(4)").html();
                material.BatchNumber = row.find("td:eq(5)").html();
                material.RfId = row.find("td:eq(6)").html();
                material.Weight = row.find("td:eq(7)").html();
                material.MaterialDrawerNo = row.find("td:eq(8)").html();
                material.MaterialLocation_X = row.find("td:eq(9)").html();
                material.MaterialLocation_Y = row.find("td:eq(10)").html();
                material.RemainingTime = row.find("td:eq(0)").html();
                material.PickUpTime = row.find("td:eq(11)").html();
                material.OutsideTime = row.find("td:eq(12)").html();
                material.CabinStatus = row.find("td:eq(13)").html();
                material.TimeAlarm = row.find("td:eq(14)").html();
                material.LifeEnding = row.find("td:eq(15)").html();
                material.TimeProcess = row.find("td:eq(16)").html();

                materials.push(material);
            });

            //Send the JSON array to Controller using AJAX.
            $.ajax({
                type: "POST",
                url: "/LastedStatus/StartProcedure",
                data: JSON.stringify(materials),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r + " Success.");
                }
            });
        });
    </script>
}

In this section, the part of the operation that is performed when the Delete button is pressed is the part that I tried before.

@section scripts{
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">

        $("body").on("click", "#deleteItems", function () {
            //Loop through the Table rows and build a JSON array.
            var materials = new Array();
            $("#table BODY TR").each(function () {
                var row = $(this).closest("tr");
                var material = {};
                material.isSelected = row.find("TD").eq(0).html();
                material.Id = row.find("TD").eq(1).html();
                material.Code = row.find("TD").eq(2).html();
                material.Name = row.find("TD").eq(3).html();
                material.Description = row.find("TD").eq(4).html();
                material.BatchNumber = row.find("TD").eq(5).html();
                material.RfId = row.find("TD").eq(6).html();
                material.Weight = row.find("TD").eq(7).html();
                material.MaterialDrawerNo = row.find("TD").eq(8).html();
                material.MaterialLocation_X = row.find("TD").eq(9).html();
                material.MaterialLocation_Y = row.find("TD").eq(10).html();
                material.RemainingTime = row.find("TD").eq(11).html();
                material.PickUpTime = row.find("TD").eq(12).html();
                material.OutsideTime = row.find("TD").eq(13).html();
                material.CabinStatus = row.find("TD").eq(14).html();
                material.TimeAlarm = row.find("TD").eq(15).html();
                material.LifeEnding = row.find("TD").eq(16).html();
                material.TimeProcess = row.find("TD").eq(17).html();

                materials.push(material);
            });

            //Send the JSON array to Controller using AJAX.
            $.ajax({
                type: "POST",
                url: "/LastedStatus/StartProcedure2",
                data: JSON.stringify(materials),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r + " Success.");
                }
            });
        });
    </script>
}

How to convert a Dart Future to a Javascript Promise for flutter webview“

I have used webview_flutter to load my site url, and used a JavaScriptChannel for two way communication between javascript and dart, as i want some native result from Android/IOS platform to javascript.

In Flutter

controller = WebViewController()
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..addJavaScriptChannel('FlutterChannel',
      onMessageReceived: (JavaScriptMessage message) async {
    
        //Here i am doing some operation and returning a result as
        controller.runJavaScriptReturningResult('window.function($result)');
    
  })
  ..loadRequest(
    Uri.parse(
        'https://demo.com/')
  );

In JavaScript to interact with flutter channel-

var params = {'key':'alternate_preference','value': ''}; 
var data = { plugin: 'SharedPref', method: 'fetch', params: [params] };
FlutterChannel.postMessage(JSON.stringify(data))

To capture result in javascript-

function flutterResponseFunc(flutterResult) {
   console.log(flutterResult);
}
window.function= flutterResponseFunc;

How can i capture the result in callback of FlutterChannel.postMessage itself instead of creating a different function for result in javascript. Like Promise.then function in javascript.

enter image description here

I have gone through this answer

But it seems like a platform specific(i.e. for web platform only), as i can not use dart:js_interop & dart:html libs for Android/IOS platform. Any help will be appreciated. Thanks !!

How to get specific nested child component from parent component slot in render function?

I am conditionally rendering a child component using render function. Here is an example of the parent component with the child component:

<Parent :index="1">
  <Child> ... </Child>
  <Child> ... </Child>
  <Child> ... </Child>
</Parent>

in the render function of Parent component, I have the following code to conditionally render the child component like this:

return () => {
  const content = slots.default?.();
  const children = content?.filter(child => child.type === Child);
  const childToRender = children?.[props.index] ?? h('div')
  return h('div', {}, () => [childToRender]);
}

the code is working as expected.

However, I would like to wrap one of the child component with another component. For example like this:

<Parent :index="1">
  <Child> ... </Child>
  <ChildWrapper> ... </ChildWrapper>
  <Child > ... </Child>
</Parent>

where ChildWrapper.vue looks like this:

<template>
  <Child> <slot/> </Child>
</template>

which evidently the filter function (content?.filter(child => child.type === Child)) will not pick up the Child component in the ChildWrapper component.

If I inspect the ChildWrapper VNode’s children property, it shows an object (with the default slot function) instead of an array with Child component which I expected. So my question is how do I get hold of the nested Child component?

Why function within useEffect runs twice [duplicate]

export const Redirect = () => {
    const navigate = useNavigate();
    const url = new URL(window.location.href);
    const authorizationCode = url.searchParams.get('code');
    const { provider } = useParams();
    const updateUserState = useSetRecoilState(userState);

    useEffect(() => {
        const socialLogin = async () => {
            const idtoken = await requestIdtoken(authorizationCode, provider);
            const isUser = await requestLogin(provider, idtoken);

            if (isUser) {
                const response = await requestUserInfo();
                *updateUserState({ ...response.data, isLogin: true });*
                navigate('/');
            } else {
                navigate(`/signup/${provider}`);
            }
        };
 
        socialLogin();
    }, []);

    return <div></div>;

Here is my code.

when I run this code. socialLogin function run twice.
but if I annotate <React.StrictMode>, it goes well.

I thought changing the state within useEffect was the cause, but it’s also resolved in the above way, so I wonder what’s the real cause

using useRef I ensure that the function runs only once.

export const Redirect = () => {
    const navigate = useNavigate();
    const url = new URL(window.location.href);
    const authorizationCode = url.searchParams.get('code');
    const { provider } = useParams();
    const updateUserState = useSetRecoilState(userState);
    *const isEffectRun = useRef(false);*

    useEffect(() => {
        *if (isEffectRun.current) {  
            return;
        }*
        const socialLogin = async () => {
            const idtoken = await requestIdtoken(authorizationCode, provider);
            const isUser = await requestLogin(provider, idtoken);

            if (isUser) {
                const response = await requestUserInfo();
                updateUserState({ ...response.data, isLogin: true });
                navigate('/');
            } else {
                navigate(`/signup/${provider}`);
            }
        };
 
        socialLogin();
        *isEffectRun.current = true;*
    }, []);

    return <div></div>;

StrictMode vs. Change state in useEffect( updateUserState() )

which one is the real cause? or both? (There is no parent Component and props)

And also let me know if you have any better ideas

Using Firebase Realtime Database `update` to perform multiple updates on the same node

I’m working with Firebase Realtime Database and I want to update multiple properties under the same node using the update() method. I’ve seen examples of using update() to perform multiple updates on different nodes, but I want to clarify if it’s valid to use update() on the same node. Here’s an example of what I have in mind:

const rootRef = ref.child('');
rootRef.update({
  'users/gracehop/city': 'New York',
  'users/gracehop/nickname': 'Amazing Grace',
  'users/anotherUser/nickname': 'John Doe',
  'customers/someId/role/admin': true,
  'customers/IdForUserThatShouldBeDeleted': null,
});

In this example, I’m updating properties under the “users” node, specifically under the “gracehop” user. Is this a valid use of the update method, and will it work as intended?

Documentation: https://firebase.google.com/docs/database/admin/save-data#section-update

reactjs state updating in a for each loop and displaying the corresponding value for each increment in a dialog box

I have a for each loop in which the properties are loaded dynamically and also shows a button to show dialog box with corresponding values of the each property but in react after rendering the entire page every dialog box is showing the last loaded property values rather than the corresponding values.

<div>
  <span id={property + '1'} className="ServiceImpactingIconForText">
      {showDialogBox(
        property,
        defaultValue[property],
        jschema[property].readOnly
       )}
     </span>
</div>

I added this div after the property div in for each loop. property, defaultValue[property] and jschema[property].readonly are the values passed to showdialogbox component which renders the button to show the dialog box

const showDialogBox = (title, value, readOnly) => { return (
<div>
  <ArrowLineExpandIcon size="10px" color="gray" backgroundColor="red" style={{ cursor: 'pointer', }} onClick={this.openDialog} />
  <Dialog title={title} value={value} readOnly={readOnly} />
</div>
}

openDialog is a funtion which will return true to show the dialog box.

Browser freezes while webcam live streaming in ReactJs

I am building a simple face recognition application.In the application the frames are captured live in webcam streaming and processed to detect face. but after a while browser freezes without any error. The source codes are given below. what might be the reason behind this

import './App.css';

import React, { useEffect, useRef,useState } from 'react';
import * as faceapi from 'face-api.js';
import axios from 'axios';

function App() {
  
  const videoRef = useRef();
  let isDetectionInProgress = false;

  const loadModels = async () =>{
    try{
      await faceapi.nets.tinyFaceDetector.loadFromUri('/model')
    }catch(error){
      console.log(error)
    }
  }
  useEffect(() => {
    
    loadModels();

    const init = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        videoRef.current.srcObject = stream;
      } catch (error) {
        console.error('Error accessing webcam:', error);
      }
    };
  
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      init();
    } else {
      console.error('Error accessing webcam:');
    }
    
    const intervalId = setInterval(() => {
      if (!isDetectionInProgress) {
        emitFrame();
      }
    }, 500);

    const hardRefreshIntervalId = setInterval(() => {
      // This code will be executed every hour (3600000 milliseconds)
      window.location.reload(true);
    }, 3600000);
  

    return () => {

      if (videoRef.current.srcObject) {
        const tracks = videoRef.current.srcObject.getTracks();
        tracks.forEach((track) => track.stop());
        videoRef.current.srcObject = null;
      }

      clearInterval(intervalId);
      clearInterval(hardRefreshIntervalId)
      console.log("App unmounted")
    };
  }, []);

  const emitFrame = async () => {
    isDetectionInProgress = true
    if (videoRef.current?.srcObject?.getVideoTracks()[0]) {
      
      let imageCapture = new ImageCapture(videoRef.current.srcObject.getVideoTracks()[0]);
      
      if (faceapi.nets.tinyFaceDetector.isLoaded) {
        let blob = null;
        try {
          
          blob = await imageCapture.takePhoto();
    
          if ("size" in blob) {
            
            
            let imageUrl = null;
            let image = null;
            try{
              imageUrl = URL.createObjectURL(blob);
              image = new Image();
              image.src = imageUrl;
              const faces =  await faceapi.detectAllFaces(image, new faceapi.TinyFaceDetectorOptions({}));
              if(faces && faces.length>0 && image){
              
                const formData = new FormData();
                formData.append('blob', blob, 'frame.png'); 
                
                const now = new Date();
                const isoFormattedTime = now.toISOString(); 
                formData.append('isoFormattedTime', isoFormattedTime);
        
                axios
                .post('http://127.0.0.1:5000/backend/detect_face', formData,{
                  headers: {
                    'Content-Type': 'multipart/form-data', 
                  },
                })
                .then((response) => {
                  if (response.status === 200) {
     
                    const speechUtterance = new SpeechSynthesisUtterance(response.data?.message);
                    window.speechSynthesis.speak(speechUtterance);
                    console.log(response.data?.message);
                    console.log(response.data?.request_time,response.data?.response_time);
                  } else {
                    console.log('No face Detected', response.data?.message);
                  }
                })
                .catch((error) => {
                  console.error('Error during api response :', error);
                });
                
              }
            }catch(error){
              console.log(error)
            }
            finally{
              URL.revokeObjectURL(imageUrl);
              image = null
            }
            
          }
        } catch (error) {
          console.log("imageCapture",imageCapture)
          console.error('Error during face detection:', error);
        } finally{
          blob = null
        }
      }
      imageCapture = null
    }
    isDetectionInProgress = false
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
    <h1 style={{ color: 'red', fontSize: '24px' }}>Ixora Solution Limited AI Front Desk Assistance</h1>
    <video ref={videoRef} autoPlay></video>
  </div>
  );
}

export default App;

is the problem related to webcam streaming or any other issues?

Show list of key value pairs in Gijgo subgrid on expand

I have the following data in a Gijgo grid,

The main grid shows the Fields Id, ItemBC, ParItemBC etc.. fine
But I want to show the ParamDetails in the subgrid in detailTemplate, but not able to show this. Tried many things with the detailTemplate but not able to show the details in the subgrid.

Data:

{
"records":  
    [
        {
            "Id":33321,         
            "ItemBC":"000463712",
            "ParItemBC":"000118974",            
            "Status":"1",
            "CreatedBy":"u228",
            "CreationDate":"/Date(1695848400000)/",
            "OId":1,
            "ParamDetails":
            [
                {
                    "PName":"Param1",
                    "PValue":"33.5"
                },
                {
                    "PName":"Param2",
                    "PValue":"493.4"
                },
                {
                    "PName":"Param3",
                    "PValue":"88"
                },
                {
                    "PName":"Param8",
                    "PValue":"Testing Param8"
                }
            ]
        }
    ]
}

JavaScript:

$(document).ready(function () {
            grid = $('#grid').grid({
                async: true,
                dataSource: '/Search/ListPages',
                uiLibrary: "bootstrap4",
                columnReorder: true,
                fontSize: '13px',               
                iconsLibrary: 'fontawesome',
                columns: [                    
                    { field: 'Id', sortable: true, width: 60 },                    
                    { field: 'ItemBC', title: 'ItemBC', sortable: true, width: 80 },
                    { field: 'ParItemBC', title: 'ParentItemBC', sortable: true, width: 80},
                    { field: 'Status', title: 'Status', width: 100 },
                    { field: 'CreatedBy', title: 'CreatedBy', width: 70, cssClass: 'label-primary' },        
                    { field: 'CreationDate', title: 'CreationDate', width: 80 }               
                ],

                detailTemplate: '<div></div>',
                icons: {
                    expandRow: '<i class="fa fa-plus-circle"></i>',
                    collapseRow: '<i class="fa fa-minus-circle"></i>'
                },

                pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] }
            });

            grid.on('detailExpand', function (e, $detailWrapper, record) {
                var subggrid = $detailWrapper.append('<table id="subgrid"/>').find('table').grid({
                    dataSource: record,
                    columns: [
                        { title: 'PName',  renderer: function (value, record) { return record.ParamDetails.PName; }},
                        { title: 'PValue', renderer: function (value, record) { return record.ParamDetails.PValue; }}
                    ],
                });               
            });
            grid.on('detailCollapse', function (e, $detailWrapper, record) {
                $detailWrapper.empty();
            });

            $("#btnSearch").on("click", Search);
            $("#search").keyup(function (event) {
                if (event.keyCode === 13) {
                    $("#btnSearch").click();
                }
            });
        });

Any help is appreciated.

Thanks.

how to fix undefined this keyword variable when calling from function

I would like to run this code but its giving me output of undefined in second console log instead of Oracle as I’m trying to call it from var retrieve name with reference to global var and this keyword.

this.name = "Oracle";
var website = {
name: "Java",
getName: function () {
return this.name;
   },
 };

console.log(website.getName()); // Java

var retrieveName = website.getName; //
console.log(retrieveName()); // Oracle but its printing undefined

var boundGetName = retrieveName.bind(website);
console.log(boundGetName()); // Java

How can define router guard in standalone components in Angular?

I have defined my routes as follows:

import { Routes } from '@angular/router';
import { domainGuard } from './guard-routes.service';
import { NotFoundComponent } from './notFound/not-found.component';
export const routes: Routes = [
  {
    path: '',
    loadComponent: () =>
      import('./home/home.component').then((m) => m.HomeComponent),
  },
  {
    path: 'users',
    loadComponent: () =>
      import('./user/user.component').then((m) => m.UserComponent),
  },
  {
    path: 'profile',
    loadComponent: () =>
      import('./profile/profile.component').then((m) => m.ProfileComponent),
  },
  { path: '**', component: NotFoundComponent },
].map((page: any) => {
  page.canActivate = [domainGuard];
  return page;
});

and My app.config is defined as :

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes)],
};

I have used a functional guard for my routes as follows:

import { Router } from '@angular/router';
import { AuthService } from './auth.service';
import { inject } from '@angular/core';

export const domainGuard = () => {
  const router = inject(Router);
  const service = inject(AuthService);
  if (service.IsAuth()) {
    router.navigate(['/user']);
    return true;
  } else {
    router.navigate(['/profile']);
    return false;
  }
};

And my authService:

import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {
  isLoggedIn = false;

  login() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        this.isLoggedIn = true;
      }, 3000);
    });
  }

  logOut() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        this.isLoggedIn = false;
      }, 3000);
    });
  }

  IsAuth() {
    return this.isLoggedIn;
  }
}

Finally when I add my route guard to routes. the following error appears:

main.ts:5 ERROR NullInjectorError: NullInjectorError: No provider for _AuthService!.

How can solve it?

Font-family Converter output SVG line animation

I want to achieve such a web effect.
It’s like the animation effect of the text writing path after text input.

Like this.==>codepen

<svg ...>
  <path class="path" stroke="#000000" ... >
</svg>
svg {
  stroke-width:17;
  width:200px;
  height:100px;
  transition:transform .5s ease-out;
  path {
    stroke-dasharray: 1200;
    stroke-dashoffset: 1200;
    stroke-width:5;
    animation:summerbird-s .75s linear forwards .5s;
  }
}

And I learned that it is implemented using svg-path and stroke-dashoffset.

Reference documentation1
Reference documentation2

But I still need to convert the font family to svg path. It would be great if there is a better implementation process or a suitable js library to help me.

Hope I can get other thoughts and help.
Thank you very much.

Out of Memory error in Fabric.js canvas causing blank screen in Chrome in mobile Devices

Description:

I am encountering an issue while using Fabric.js canvas for rendering objects onto the canvas. During the process, the canvas becomes blank, and Chrome throws an “Out of Memory” error.

Here’s a summary of the problem:

1.Context: I’m utilizing Fabric.js to render objects onto the canvas in my web application.

2.Issue: At some point during the canvas rendering process, the canvas goes blank.

3.Error: Chrome displays an “Out of Memory” error.

4.Observations: This issue seems to occur when there are a considerable number of objects or complex shapes being rendered onto the canvas.

5.Attempts: I’ve tried optimizing the code by reducing unnecessary object duplication and using fabric.js methods efficiently, but the problem persists.

Please check below image

Please check

  const canvasConfigOptions2 = {
      hoverCursor: 'default',
      selection: false,
      selectionBorderColor: '#00c3f9',
      selectionColor: 'rgba(0, 195, 249, 0.2)',
      preserveObjectStacking: true,
      originX: 'center',
      originY: 'center',
      fireRightClick: false,
      perPixelTargetFind: false
  }

      let height2 = document.getElementById('canvas-wrapper').offsetHeight;

      let width2 = document.getElementById('canvas-wrapper').offsetWidth;

      const zoomLevelX = this.isFullScreen == true ? width2 / this.zoomWidthRef : (width2 - 40) /      this.zoomWidthRef;

       const zoomLevelY = this.isFullScreen == true ?  height2 / this.zoomHeightRef : (height2 - 60) / this.zoomHeightRef;

       const zoomLevel = Math.min(zoomLevelX, zoomLevelY); // for regenerate the issue you can take zoomlevel above 1;

       this.zoomWidthRef = 3000px;

       this.zoomHeightRef = 3000px;

       this.canvas = new fabric.Canvas('canvas', canvasConfigOptions2);

       this.canvas.setZoom(zoomLevel);

       this.canvas.setDimensions({

        width: Math.round(this.zoomWidthRef * zoomLevel),
        height: Math.round(this.zoomHeightRef * zoomLevel)

        })
      this.canvas.calcOffset();

     // render json on fabric.js canvas

     this.canvas.loadFromJSON(json, async function () {
        this.canvas.renderAll();
     })
---- Add canvas tag into html file:

//html code start

<div class="canvas-wrapper canvas-wrapper2" style="position: absolute;top: 60px;left: 0; display: flex;justify-content: center;" id="canvas-wrapper"> <canvas id="canvas" class="shadow canvas-style" style="cursor: none;"></canvas> </div>

//html code end

image:

Additional context:

Browser: Chrome [Version 120.0.6099.144] , safari All version

Fabric.js version: [1.7.22]

angular version : [6.0.0]

Approximate number of objects being rendered: [10 to 15]

Note: This issue generate mostly in mobile browser

I’d appreciate any insights or suggestions on how to tackle this “Out of Memory” error while rendering on the Fabric.js canvas in Chrome. Thank you!