Angular directive this and closure issue

I have such directive:

@Directive({
  selector: '[imgTest]',
})
export class ImgTest implements AfterViewInit, OnDestroy {

  private originalImage: HTMLImageElement;
  private secondImage: HTMLDivElement;

  constructor(private elementRef: ElementRef, public sanitizer: DomSanitizer) {}

  @HostListener('load')
  public onLoad(): void {
    this.process();
  }

  public ngAfterViewInit(): void {
    this.originalImage = this.elementRef.nativeElement;
  }

  public ngOnDestroy(): void {
    this.removeEventListeners();
  }

  private addEventListeners(): void {
    this.originalImage.addEventListener('mousemove', this.moveImage);
    this.secondImage.addEventListener('mousemove', this.moveImage);
  }

  private removeEventListeners(): void {
    this.originalImage.removeEventListener('mousemove', this.moveImage);
    this.secondImage.removeEventListener('mousemove', this.moveImage);
  }

  private process(): void {
    if (!this.originalImage) {
      return;
    }

    /* some magic */

    this.addEventListeners();
  }

  private moveImage(e: MouseEvent): void {
    let pos: { x: number; y: number }, x: number, y: number;
    e.preventDefault();
    /* some magic that is using also this.getPos(e) */
  }

  private getPos(e: MouseEvent): { x: number; y: number } {
    /* some magic */

    return { x: x, y: y };
  }
}

and the issue is that inside moveImage this is wrong and it’s just not working at all.
what I’ve done wrong?

How to make table editable in django on the clientside

I am building this Django webapp, where I have data stored in the SQLite. And being fetched into a table in the client side.
But I have this idea of patching the data from the table itself, just like Edit in grid view, of sharepoint list.
Where If I click the toggle button ‘editable mode’, the all cells become editable and after making necessary changes, if click the toggle button again, the changes should be saved in the database as well.

Below are the snippets of the project.

views.py


class EmployeeUpdateView(View):
    def patch(self, request, employee_id):
            data = json.loads(request.body)
            try:
                employee = Employee.objects.get(id=employee_id)
                for change in data:
                    field_name = change['field_name']
                    field_value = change['field_value']
                    setattr(employee, field_name, field_value)
                employee.save()
                return JsonResponse({'success': True})
            except Employee.DoesNotExist:
                return JsonResponse({'success': False, 'error': 'Employee not found'})
            except Exception:
                return JsonResponse({'success': False, 'error': 'Error saving changes'})

this is url path

path('update/<int:employee_id>/', EmployeeUpdateView.as_view(), name='update_employee'),

this is the table template

<tbody class="thead-light">
            {% for employee in page_obj %}
            <tr style="font-size: 12px;">
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.name }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.phone }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.dob }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.doj }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.address }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.city }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.state }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.team }}</td>
                <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.salary }}</td>
            </tr>
            {% endfor %}
        </tbody>

this is button

<button id="edit-toggle" class="btn btn-white" style="margin-right: 2%; background-color: #5584AC;" onclick="toggleEditMode()">Toggle Edit Mode</button>

this is the script


var changes = []; // Global array to store changes

  function toggleEditMode() {
      var tableRows = document.getElementsByTagName('tr');
      var editToggle = document.getElementById('edit-toggle');
      if (editToggle.innerHTML === 'Toggle Edit Mode') {
          editToggle.innerHTML = 'Toggle View Mode';
          for (var i = 0; i < tableRows.length; i++) {
              var cells = tableRows[i].getElementsByTagName('td');
              for (var j = 0; j < cells.length; j++) {
                  cells[j].setAttribute('contenteditable', 'true');
              }
          }
      } else {
          editToggle.innerHTML = 'Toggle Edit Mode';
          for (var i = 0; i < tableRows.length; i++) {
              var cells = tableRows[i].getElementsByTagName('td');
              for (var j = 0; j < cells.length; j++) {
                  cells[j].setAttribute('contenteditable', 'false');
              }
          }
          saveChanges();
      }
  }

  function saveChanges() {
      if (changes.length > 0) {
          var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
          var xhr = new XMLHttpRequest();
          xhr.open('PATCH', '/update/' + employeeId + '/', true);
          xhr.setRequestHeader('Content-Type', 'application/json');
          xhr.setRequestHeader('X-CSRFToken', csrftoken);
          xhr.onload = function () {
              if (xhr.status === 200) {
                  console.log('Changes saved successfully.');
                  changes = []; // Clear the changes array
              } else {
                  console.error('Error saving changes.');
              }
          };
          xhr.send(JSON.stringify(changes));
      }
  }

  document.addEventListener('input', function (event) {
      var element = event.target;
      if (element.getAttribute('contenteditable') === 'true') {
          var row = element.closest('tr');
          var employeeId = row.dataset.employeeId;
          var fieldName = element.dataset.fieldName;
          var fieldValue = element.innerText.trim();

          // Find if the change already exists in the array
          var existingChangeIndex = changes.findIndex(function (change) {
              return change.employee_id === employeeId && change.field_name === fieldName;
          });

          if (existingChangeIndex > -1) {
              // Update the existing change
              changes[existingChangeIndex].field_value = fieldValue;
          } else {
              // Add a new change to the array
              changes.push({
                  employee_id: employeeId,
                  field_name: fieldName,
                  field_value: fieldValue
              });
          }
      }
  });

Set a private value in Azure Pipeline and integrate with TestCafe

enter image description here

I have done for create variable group with variable, and also in file yaml for config pipeline, i have defined with thí

variables:
- group: automation-regression
- name:  testcafe
  value: '${USER_PASSWORD}'

steps:
     - task: PowerShell@2
       inputs:
            targetType: "inline"
            script: echo ${testcafe}

but when start running pipeline regression can not echo the value of testcafe

Evaluate XPath relative to context node

I am trying to evaluate an XPath relative to a particular DOM node. That is, I would like to access /div/a using the expression /a, while specifying that the XPath should be evaluated on the <div> element.

From the docs, it seems that the contextNode argument should work here.

<html>
  <body>
    <a href="#">outer</a>
    <div>
      <a href="#">inner</a>
    </div>
  </body>
</html>

I tried to evaluate the XPath on the <div> using the contextNode argument, but passing it had no effect. I would have expected that now the inner <a> element should be found.

Instead, document.evaluate('//a', div).iterateNext().innerText gives the text “outer”.

https://jsfiddle.net/mt04y8db/

data table that javascript – ajax call for Server-side

I’m following the datatables.net manual

Target: want turn every page, then load certain amount of data

now: every time will load “all” the data (17k), and wait 4 sec to do so

If page 1 just load the 1st – 10th data, page 3 is 21th – 30th data, then could save the loading time

  • tried ajax
  
draw_table(require_json)

function draw_table(data) {
    const getToken = localStorage.getItem("token");

    console.log("GET TOKEN", getToken);


    $.ajax({
        url: "http://192.168.10.01:3000/log/list/",   
        type: 'PUT',   
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8', 
        data: JSON.stringify(data), 
        headers: {
            'Authorization': 'Bearer ' + getToken  
        },
        success: function (response) {
            console.log("SUCCESS", response);
        },
        error: function (response) {
            console.log("ERROR", response);
        }
    });
}

require_json = {
    "limit": 10,
    "offset": 1,
    "search": "",
    "id": 0,
    "start_id": 0,
    "end_id": 0,
    "event": "",
    "user": "",
    "message": "",
    "type": "",
    "start_time": "",
    "end_time": "",
    "order_by": "desc",
    "order_column": "id"
}
var storedItem = localStorage.getItem("storedItem") || [];

$(document).ready(() => {
    const getToken = localStorage.getItem("token");
    const API_URL = "http://192.168.10.01:3000/api/log/all";  // this one is correct that can load and print data as table     
                                                       //  (but need to load for few second cause data is about 17k)
    var rowData;

    console.log("GET TOKEN", getToken);

    var accountType = localStorage.getItem("acc_type");
    var buttons = [
        {
            extend: "csv",
            text: "CSV",
            className: "btn btn-outline-warning btn-lg",
        },
        {
            extend: "excel",
            text: "Excel",
            className: "btn btn-outline-success btn-lg",
        },
    ];


    var buttonRow = $('<div class="row"></div>');
    
    buttons.forEach(function (button) {
        var buttonCol = $('<div class="col"></div>').append(button);
        buttonRow.append(buttonCol);
    });
    

    if (accountType === "OP") {
        buttons = buttons.slice(2);
    }

    var table = $("#example").DataTable({
        ajax: {
            url: API_URL,
            headers: {
                Authorization: "Bearer " + getToken,
            },
            dataSrc: function (response) {
                console.log("DATA", response);
                return response.logs;
            },
        },
        lengthChange: false,
        pageLength: 10,
        serverSide: true,
        scrollY: true,
        

        columns: [
            { data: "id", title: "id" },
            { data: "message", title: "message" },
            { data: "type", title: "type" },
            { data: "user", title: "created_by" },
            { data: "created_at", title: "created_at" },
        ],
        dom: '<"row"<"col"B><"col text-right"l><"col"f>>rtip',
        buttons: buttons,
    });

    table.draw();

    $("#example tbody").on("click", "button", function (event) {
        var data = table.row($(this).parents("tr")).data();
        rowData = data;
        console.log("GET edit DATA", data);
    });

    $("#exampleModal").on("show.bs.modal", function (event) {
        var button = $(event.relatedTarget);
        var recipient = button.data("whatever");
        var modal = $(this);
        var data = rowData;
        modal.find(".modal-title").text("Update data " + recipient);
        var inputFields = modal.find(".modal-body input");

        if (button.attr("id") == "AddedNew_Data") {
            inputFields.val("");
        } else {
            var keys = Object.keys(data);
            for (var i = 0; i < inputFields.length; i++) {
                $(inputFields[i]).val(rowData[keys[i]]);
            }
        }
    });

    $("#exampleModal").on("show.bs.modal", (e) => {
        $(".modalTextInput").val("");
        let btn = $(e.relatedTarget);
        let id = btn.data("id");
        $(".saveEdit").data("id", id);
    });

    $(".saveEdit").on("click", function () {
        let id = $(this).data("id");
        saveNote(id);
        $("#exampleModal").modal("toggle");
    });
});

Next.js Deployment Error – TypeError: Can’t access property “user”, “m” is undefined when using OAuth/Next.js signIn during deployment

Image of the error
I’m encountering a peculiar issue while deploying my Next.js application. During the deployment process, I face an error message stating: “Application error: a client-side exception has occurred (see the browser console for more information)”. However, when I run the application locally, the OAuth sign-in functionality works perfectly fine without any errors.

The specific error displayed in the browser console is: “TypeError: can’t access property ‘user’, ‘m’ is undefined”. It seems to be related to accessing the ‘user’ property during the sign-in process.

I’m using Next.js version 10 for my application. I have implemented OAuth sign-in functionality, which is working as expected in my local environment. However, it fails to work properly during deployment.

I would greatly appreciate any insights, suggestions, or potential solutions to resolve this issue and successfully deploy my Next.js application with OAuth sign-in. Are there any additional configuration or deployment steps that need to be considered in order to avoid this error?

Thank you for your assistance!

fs module in node js fs.existsSync not recognising with Latin filename

I have some file names in “LATIN” but the fs.existsSync function is not able to recognise it

1689017335025-Naan En Nesarudaiyavan â mix.json

I tired with buffer too but still not able to get the proper response.

I am providing the proper path of the file too but still its not detecting that file.

I am using the fs module in electron js.

Other files other than Latin are been properly detected by fs.existsSync

How Handle a Full screen while Automating through Cypress

I am working on Payment functionlity in one of the Insurer and I am using Cypress Automation Tool to Automate that functionlity and Running Test cases through Test runner .while clicking on makepayment2 button Another Page is open and its open in Full screen mode so i cant Automate that Page How to Handle that Full screen Page and How to Automate and url of that Page is https://uat.billdesk.com/pgidsk/pgijsp/banksimulator.jsp

My Code

My Code](https://i.stack.imgur.com/8LnQr.png)

I am Exepecting that i want to Automate that FUll screen mode Page

Undefined javascript array to html [closed]

I started learning javascript and created a simple to-do web app to practice. However, an error that is breaking me apart is appearing, for example, i have an array with all the tasks which will store the tasks, then i will get the task content from the creation of the task and push it into the array and finally create the task element for the html part. But i dont know why, when the html part is created, the first element created always comes with two tasks, one saying what the content was and another saying undefined. The other tasks show up normal.

enter image description here

As you can see, when i created task1 the undefined one showed up, and i dont know why this is hapening…

And in the console, the array is working fine:

enter image description here

Here is the relevant code:

let add = document.querySelector("#add")
let tasksArray = []

let taskContent = document.querySelector("#task-content")

add.addEventListener("click", () => {
  let task = ""
  tasksArray.push(taskContent.value);
  for (let index = 0; index <= tasksArray.length; index++) {
    task +=
      `
        <div class="task">
            <input type="checkbox">
            <span id="task-name">${tasksArray[index]}</span>
            <span class="material-symbols-outlined" id="mark-as-important">grade</span>
        </div>
        `
  }
  document.querySelector(".tasks-list").innerHTML = task;


  console.log(tasksArray);
})
<div class="add-task">
  <span id="task-title">Add new task</span>
  <input type="text" id="task-content">
  <button type="submit" id="add">Add</button>
</div>

<div class="tasks-list">

</div>

By my understanding of the code, the tasksArray[index] is returning undefined but still, why is it showing up two times, one correct and another undefined??

I have tried changing the position of the code various times or even trying to eliminate the task that said “undefined” but it didn’t work. I dont really know how to fix this. I was expecting that the undefined task would disappear but it just would not.

Javascript downloading PDF from personal GoogleDrive

I try to load PDF from GoogleDrive like the following:

    function getConfigFile() {
        const fileAddress = 'https://drive.google.com/uc?id=15USHSjPl2kOjUL7WReHgFiwFVEUXJtqo';
        const requestInit = {
            'headers' : {
                'Access-Control-Allow-Origin' : '*'
            },
            'mode' : 'cors',
            'method' : 'GET'
        };

        fetch(fileAddress, requestInit).then(res => console.log(res)).catch(er => console.log(er));
    }

Unfortunately I receive error message:

Access to fetch at ‘https://drive.google.com/uc?id=15USHSjPl2kOjUL7WReHgFiwFVEUXJtqo’ from origin ‘http://localhost:63342’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Problem occurs no matter if I try to fetch data from localhost or GitHub Pages.
Here is the page itself if You want to have full access to the code:

https://testaccountforkotek.github.io/html/calendar.html

I tried to modify the request header in many ways like null or origin instead of * and I’ve read many threads associated with similar issues but still couldn’t find the right answer.

ideally I’d like to receive the file and be able to operate on it further in JS file.

Thank You in advance!

copy link address of .csv file , the URL is not pasted but the word JavaScript:, is only visible, not the actual URL. URL of file is to be pasted

when I select(by left click of mouse) “copy link address” of a .csv file and then paste the same in a google or excel sheet, the URL is not pasted but the word JavaScript:, is only visible, not the actual URL. So I am unable to download the file on spreadsheet. Kindly share your views.

Tried by copying(ctrl+c) and pasting (cntr+v) manually the complete URL without using COPY LINK ADDRESS, but still I am unable to download the .csv file

window.print() suddenly prints one table row per page [closed]

I am not sure where it comes from as I tried looking in the code and it seem unchanged and worked for a long time.

But now when I use window.print() on a table, it prints every row in a single page. So if I have 10 rows, it prints them 1 row per page ending up printing 10 pages.

But why? Where should I start looking at? What would be suspect for this behavior? Which css styling?

<table class="visibleOnPrint">
   ...
</table>

.visible-to-print {
    display: block;
}

.do-no-print {
    display: none;
}

Group only rows that have some properties and others keep as single row

I have a rowData like this

[
    {key: income, ...},
    {key: sumIncome, ...},
    {key: cost, ...},
    {key: sumCost, ...},
    {key: total, ...},
]

Here, I need to only group that has keys as income and cost. other rows should keep as single rows in that position.

for now, I use groupRemoveSingleChildren: true, property in the grid option and it is working only below the object array.

[
    {key: income, ...},
    {key: income, ...},
    {key: sumIncome, ...},
    {key: cost, ...},
    {key: cost, ...},
    {key: sumCost, ...},
    {key: total, ...},
]

So when I have one value for income and cost like the first array object, I can’t get the behavior that I want. Any solution to get this thing done?

Getting Jest test undefined error when trying write tests for component that use other lib UI components

Getting TypeError: Cannot read properties of undefined when trying to write Jest tests for components that use custom UI components from custom lib.

import { getData, Text, Loader } from 'my-custom-lib';
import { InputField } from '../InputField';

export const Example = () => {
  const getData = useGetData(undefined, { refetchOnMount: false });

  const data = getData.data?.user;

  return (
    <>
      <Text size="10" weight="light">
        Title
      </Text>
      <Loader loading={getData.loading}>
        <InputField label="some label value={user?.label} />
      </Loader>
    </>
  );
};

for example this test fails with error TypeError: Cannot read properties of undefined (reading ’10’)

describe('Example.tsx', () => {
  it('should get data', async () => {
    render(
      <QueryClientProvider client={queryClient}>
        <Example />
      </QueryClientProvider>
    );

    const getDataResponse = await api.data.getDataResponse;

    expect(getDataResponse.user?.label).toBe('text');
  });

What should be done for this test and component ?