Why does can’t read the js and php codes in my registration.php? [closed]

I have a sidebar here and it has sections like registration.php. The registration php contains a form with JavaScript and Php codes. When I tried to run the registration.php alone(localhost/registration.php) in my browser, it is working but when i tried to combine it with my system like this in the sidebar, it is not working. How can i fix it?

I tried to use the include function in php and it worked so i think the problem is that href can’t handle JavaScript and Php codes?

Gmail delete messages straight from inbox

Aware that there’s been a few questions about this over the years, but Google’s documentation has changed, and methods etc. have changed. Aware that also, the recommendation is that trash is used. The Gscript that I’ve got to move all messages with a certain filter move to trash fine but I want that same script to dump them from trash too and I’d prefer, in this case, to bypass it entirely.

Have added the Gmail API service into the project, and also enabled the GmailAPI in my account.

So initially, I thought I’d trash it, and then remove from trash, thus:

function DeleteMail() { 
  var threads = GmailApp.search('subject:test');
  for (var i = 0; i < threads.length; i++) {
    threads[i].moveToTrash();
  }

  var threads2= GmailApp.search('in:trash subject:test')
  for (var p = 0; p < threads2.length; p++) {
    var thisid=threads2[p].getId();
      Gmail.Users.messages.delete('me', threads2[p].thisid);
  }
}

I get the error: TypeError: Cannot read properties of undefined (reading ‘delete’)

So I altered the script so that it would bypass the trashing bit and just straight up remove it

function DeleteMail() { 
  var threads = GmailApp.search('subject:test');
  for (var i = 0; i < threads.length; i++) {
    var thisId = threads[i].getId();
      Gmail.users.messages.delete('me', threads[i].thisId);
  }

and get the error: TypeError: Cannot read properties of undefined (reading ‘messages’)

Can anyone point me where I’m going wrong here please?

Cordova connect with Node.js Sockect.io Server

“I’m trying to make my Cordova app talk to my Socket.io Server built with Node.js, but it’s not working! I made a mobile app using Cordova and set up a real-time communication server using Node.js and Socket.io. However, when I try to connect them, it’s not happening.

I need some help figuring out what’s going wrong. If you have any advice on how to connect a Cordova app to a Socket.io server or if there are common mistakes I might be making, I’d really appreciate your help.

Thanks a bunch!

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
  attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
    <meta
      name="viewport"
      content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"
    />
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <meta name="msapplication-tap-highlight" content="no" />
    <title>Hello World</title>
  </head>
  <body>
    <div class="app">
      <h1>Apache Cordova</h1>
      <div id="deviceready" class="blink">
        <p class="event listening">Connecting to Device</p>
        <p class="event received">Device is Ready</p>
      </div>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script
      type="text/javascript"
      src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"
    ></script>
    <script type="text/javascript" src="js/index.js"></script>
  </body>
</html>

Javascript/Cordova

document.addEventListener("deviceready", function () {
  try {
    const socket = io("https://chat-ten-umber.vercel.app");
    socket.on("connect", function () {
      alert("Yeeeeeeeee");
      socket.on("text", function (text) {
        alert(text);
      });
    });
  } catch (err) {
    alert(err);
  }
});

Server:

const express = require("express");
const app = express();
const http = require("http").Server(app);
const cors = require("cors");
const io = require("socket.io")(http);

app.use(cors());

io.on("connection", (socket) => {
  console.log("A user is connected");

  socket.on("disconnect", () => {
    console.log("The user disconnect");
  });

  socket.on("message", (data) => {
    console.log("Received message:", data);
    socket.broadcast.emit("message", { message: data.message, to: data.to });
  });
});

// start server
http.listen(8000, () => {
  console.log("Server running on port 8000");
});

app.get("/", (req, res, next) => {
  res.send("Hello");
});

Why I am getting these error during fetching an api?

I’m using the offical API of Swiggy to show the restaurant near me in cards but sometime the api works correctly and sometime not. I didn’t understand how to solve that error . Can someone help me with this. enter image description here

I’m getting this error and also i’m providing the api which i’m using:

API: https://corsproxy.io/?https://www.swiggy.com/dapi/restaurants/list/v5?lat=21.1702401&lng=72.83106070000001&page_type=DESKTOP_WEB_LISTING

I’m trying to fetch an api and show the data in a card but got errors during fetching.

Mock `Number.toLocaleString()` so it returns same results in tests independent of user locale

Introduction

We have code in our class that basically formats a number by transforming for example 1000000 to 1 M and 1500000 to 1.5 M respectively.

To achieve this we are using the following code

export const shortNumberString = (number: number) => {
  if (!number) {
    return number === 0 ? '0' : '';
  }

  const i = Math.floor(Math.log(number) / Math.log(1000));

  return (
    Number((number / Math.pow(1000, i)).toFixed(1)).toLocaleString() +
    ' ' +
    ['', 'K', 'M', 'B'][i]
  ).trim();
};

The code works as expected and does what we want them to do, but we have developers from all over the world so based on the locale of the user this test fails.

Normally we just ignore these failed tests, but they are super annoying because you always see these tests failing but have to activiely check to ignore them.

The tests basically fail because for some users it gets formatted to 1.5 M and for others to 1,5 M.

Attempted Solutions

Add NODE_ICU

Some users have recommended to use NODE_ICU package, which I added using

yarn add -D NODE_ICU

Afterwards I have added this to our test script

"test": "NODE_ICU_DATA=node_modules/full-icu craco test",

However, running yarn test does still result in errors. I have also tried to run this via command line but the same error appears


Mock Number().toLocaleString()

I have tried to mock Number.toLocaleString but without success. I have tried the following methods

Ignore the return values as I just wanted it to fail with the given input so I’m sure it works with mocking

  (global as any).Number.toLocaleString = jest.fn(() => ({
    ...(global as any).Number,
    toLocaleString: jest.fn(() => '12.3.2019 13.47.47'),
  }));

However, this does not work. It is not mockin anything

Same applies for this code

(global as any).Number.toLocaleString = jest.fn(() => new Date('2019-04-07T10:20:30Z'));
  (global as any).Number = jest.fn(() => ({
    toLocaleString: jest.fn(() => '12.3.2019 13.47.47'),
  }));

This also fails, because of the following error

Cannot read properties of undefined (reading ‘toLocaleString’)
TypeError: Cannot read properties of undefined (reading ‘toLocaleString’)

  jest.mock('Number', () => ({
    ...jest.requireActual('Number'),
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    toLocaleString: () => {
      return Promise.resolve('yolo');
    },
  }));

This does not work as there is no module named Number jest can mock. I have not found a way to mock

jest
    .spyOn(global.Number, 'toLocaleString')
    .mockImplementation((number: string) => 10);

This also does not work as it tells me I cannot call the method spyOn like .spyOn(global.Number, 'toLocaleString')

Set env.LL etc

I have also tried to set the locales of env manually

  const env: any = process.env;
  env.LANG = 'en-GB';
  env.LANGUAGE = 'en-GB';
  env.LC_ALL = 'en-GB';
  env.LC_MESSAGES = 'en-GB';
  const language = env.LANG || env.LANGUAGE || env.LC_ALL || env.LC_MESSAGES;
  console.log(language);

in the console.log it returns en-GB but the tests are still failing even though en-GB should return the correct format


I am out of ideas but cannot believe that it is impossible to mock this. However, everything I find on Google is mostly for Date mocking but not for Number mocking and I cannot apply these suggestions to Number formatting to get them working.

Any help would be appreciated

input mask for ip like 225.222.324.222/32

I’m using React.js
I need to create an input mask for IPs with networg range, Ips that looks likw that: 22.23.23.14/32
or 111.111.111.111./20 for example.
how do I create the input field so it will have a mask like this:.../___

thanks!
looked for libraries

Angular Gridster 2, nested Grids

I am facing an issue with angular gridster 2, I want to have nested gridster,
Here is the configs I am using

zItemsNesteing: IGridsterConfig = {
    gridsterConfig: this.gridsterOptions,
    gridsterItems: [
      {
        x: 0,
        y: 0,
        rows: 2,
        cols: 2,
        zItems: {
          gridsterConfig: this.gridsterOptions,
          gridsterItems: [
            { x: 0, y: 0, rows: 2, cols: 2},
            { x: 2, y: 1, rows: 1, cols: 1 },
          ],
        },
      },
      { x: 0, y: 0, rows: 2, cols: 2 },
    ],
  };`enter code here`

Here is my component

<div class="gridster-container">
    <app-grid
      [options]="zItemsNesteing.gridsterConfig"
      [dashboard]="zItemsNesteing.gridsterItems"
    ></app-grid>
  </div>

and here I am trying nesting

<gridster [options]="options">
  <gridster-item [item]="item" *ngFor="let item of dashboard">
    Hello
    <div class="gridster-container" *ngIf="item.zItems">
      <app-grid
        [options]="item.zItems.gridsterConfig"
        [dashboard]="item.zItems.gridsterItems"
      ></app-grid>
    </div>
  </gridster-item>
</gridster>

This is my output, nested gridster seems not working.

enter image description here

If you see in nested gridster we have two items but it is comming one after another instead of on the same row and the specified colummn.

Net Core RedirectAction not working after using javascript on form onsubmit

Im using javascript to on my form onsubmit.
It passes the data just fine on backend, but the redirect action on my controller doesnt seem to work afterwards

async function submitForm(event) {
    event.preventDefault();
    var form = document.getElementById('createAccountForm');
    var password = document.getElementById('user_password_input').value;
    if (!password) {
        var pworderrmsg = document.getElementById('pworderrormsg');
        pworderrmsg.textContent = "Please Enter a Valid Password!";
        pworderrmsg.style.display = 'block';
        return; // Form will not be submitted
    }
    //get the anti-forgery token
    // Retrieve the anti-forgery token value from the hidden input field
    var antiForgeryToken = document.querySelector('input[name="__RequestVerificationToken"]').value;

    // Make a POST request to your .NET Core API
    var options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'RequestVerificationToken': antiForgeryToken // Include the anti-forgery token in the headers
        },
        body: JSON.stringify({
            username_or_email: document.getElementById('user_email_input').value,
            Password: password
        })
    };
    await fetch('/auth/createaccount',options )
        .then(response => {
            if (!response.ok) {
                console.log(response);
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.text();
        })
        .then(data => {
            alert(data.message);
            // Optionally, redirect or perform other actions upon successful account creation
        })
        .catch(error => {
            console.error('Error:', error.message);
            // Display a user-friendly error message or handle the error scenario appropriately
        });
}

then on my controller ,I tried redirecting to a random page, just to test things

return RedirectToAction("Index", "Home");

And Nothing happens.

here is my form

<form id="createAccountForm" onsubmit="return submitForm(event)">
                                    @Html.AntiForgeryToken()
                //other stuffs

location.href method isn’t redirecting to the index page after pull on GitHub Pages

I have a question regarding my website. Can anyone help me troubleshoot this issue? I have tried several solutions, but I cannot seem to get the location.href method to redirect to the main page. The website works perfectly fine on my local machine, but not on GitHub Pages. Despite specifying the file path and ensuring everything is set up correctly, the modal, buttons, and switcher do not redirect to the main page as intended. I set path /, ../, index.html,…/, I even left it blank, wrote a slash and a grid, but locally everything works as it should, the browser cache is clean! What is wrong, who has encountered this?

https://codepen.io/kyrylomatkash/pen/PoVJymz

How to remove Grand total for each bar from only Grand Summary series in Highchart

I wanted to remove the Grand Total For Each Bars bar from Grand Summary series. I have tried to remove it but it removes from all series April,May,Jun. I need to keep in other series group but not in Grand Summary. Here is my data and script. You can check if categories has Grand Summary then the Grand Total For Each Bars bar would not show in series.
Here is my script:

var seriesData = [
    {
        "data": [
            690,
            230,
            230,
            230
        ],
        "name": "Grand Total For Each Bars"
    },
    {
        "data": [
            230,
            100,
            100,
            100
        ],
        "name": "April"
    },
    {
        "data": [
            230,
            50,
            50,
            50
        ],
        "name": "May"
    },
    {
        "data": [
            230,
            80,
            80,
            80
        ],
        "name": "Jun"
    }
];

var categoriesData = ['Grand Summary', 'April', 'May', 'Jun'];

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Remove Grand total for each bars in Grand total sumary series group',
        align: 'left'
    },
    xAxis: {
        categories: categoriesData,
        type: 'datetime',
        title: {
            text: null
        },
       
    },
    yAxis: {
       
        title: {
            text: '',
            align: 'high'
        },
        labels: {
            overflow: 'justify'
        },
        gridLineWidth: 0
    },
    
    series: seriesData
});
.highcharts-figure,
.highcharts-data-table table {
    min-width: 310px;
    max-width: 800px;
    margin: 1em auto;
}

#container {
    height: 400px;
}

.highcharts-data-table table {
    font-family: Verdana, sans-serif;
    border-collapse: collapse;
    border: 1px solid #ebebeb;
    margin: 10px auto;
    text-align: center;
    width: 100%;
    max-width: 500px;
}

.highcharts-data-table caption {
    padding: 1em 0;
    font-size: 1.2em;
    color: #555;
}

.highcharts-data-table th {
    font-weight: 600;
    padding: 0.5em;
}

.highcharts-data-table td,
.highcharts-data-table th,
.highcharts-data-table caption {
    padding: 0.5em;
}

.highcharts-data-table thead tr,
.highcharts-data-table tr:nth-child(even) {
    background: #f8f8f8;
}

.highcharts-data-table tr:hover {
    background: #f1f7ff;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
    <div id="container"></div>
    <p class="highcharts-description">
      
    </p>
</figure>

enter image description here
Thanks

JSON API not working as it should for new user registration in node and express

i am writing a program and got a problem with my API testing

***RegisterController.js

const data = {
    users: require('../model/users.json'),
    setUsers: function (data){
        this.users = data
    }
};
const fspromises = require('fs').promises;
const bcrypt = require('bcrypt');
const path = require('path');


const handleNewUser = async (req,res) =>{

    const {user,pwd} = req.body;

    if(!user || !pwd) return res.json({'message': 'username and password are required'})
    
    try{

        const saltround = await bcrypt.genSalt(10);
        const hashpwd = await bcrypt.hash(pwd,saltround);

        const newUser = {
            "username": user,
            "password": hashpwd
        }

        data.setUsers([...data.users,newUser]);

        await fspromises.writeFile(path.join(__dirname, '..','model', 'users.json'), data.users);
        console.log(data.users);
        res.json({'Success':`User ${user} successfully created`})
    }catch(error){
        console.log(error);
    }

}

module.exports = { handleNewUser };

in my register controller file i have an async function that handle the registration of new users,
NB: I haven’t established any database connection, i’m writing or registering the information of a new user into a json file (users.json). And the backend is not connected to any frontend

i have a register file in my routes folder which handles the resquest from the user

***register.js

const express = require('express');
const router = express.Router();
const registerController = require('../controller/registerController');

router.post('/', registerController.handleNewUser);

module.exports = router;

i have the register file imported in my js server file

app.use('/register', require('./routes/register'));
{
  "user": "Brayn",
  "pwd": "Leeaa"
}

After making this POST request in thunder client, i got this message

{
  "message": "username and password are required"
}

I gone through the code and i can’t see what may have gone wrong

HTML form input validation using Bootstrap 5 does not prevent submit

I’m trying to implement client side validation of HTML form input using Bootstrap 5 as decsribed here Bootstrap 5 Docs, and here How to Validate Forms with Bootstrap 5. Unfortunately, the form is not validated upon clicking the Submit button. I.e. the form is submitted even when required input is missing.

I know HTML and CSS pretty good, but not so Javascript. I think the anonymous function which is supposed to add the submit event listener is not executed at all. I might be missing something basic.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="de">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form Testing</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    </head>
    <body>
        <header>
            <div class="col">
                <h1>Bootstrap Form Validation Testing</h1>
            </div>
        </header>
        <main>
            <form class="row g-3 mb-4 needs-validation" novalidate action="go-on.php" method="post">
                <div class="col-md-12">
                    <label for="customerName" class="form-label">Ihre Angaben</label>
                    <input type="text" class="form-control" id="customerName" name="customerName" value="" placeholder="Vorname & Name" required>
                    <div class="invalid-feedback">
                        Bitte geben Sie ihren Vornamen & Namen ein.
                    </div>
                </div>
                <div class="col-md-12">
                    <input type="text" class="form-control" id="customerAddr2" name="customerAddr2" placeholder="Adresszusatz" value="">
                    <div class="valid-feedback">
                        Fakultativ.
                    </div>
                </div>
                <div class="col-12">
                    <button class="btn btn-primary" type="submit">Submit</button>
                </div>
            </form>     
        </main>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
        <script>
            (() => {
                'use strict'

                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                const forms = document.querySelectorAll('.needs-validation')

                // Loop over them and prevent submission
                Array.from(forms).forEach(form => {
                    form.addEventListener('submit', event => {
                        if (!form.checkValidity()) {
                            event.preventDefault()
                            event.stopPropagation()
                        }

                        form.classList.add('was-validated')
                    }, false)
                })
            })()
        </script>
    </body>
</html>

Vue Draggable – How to get position of element being dragged

I am building a calendar day view, and I have cards that are draggable for events.

I am trying to workout how I can detect where the card is being moved to, I can detect the mouse position, but I need the position of the top of the element I am dragging.

<script setup> 
    import {ref} from "vue";
    import draggable from "vuedraggable";
    const appointments = ref([ // appointment data ]);

    function test(event) {
        console.log(event)
        console.log('ClientY = ' + event.clientY);
        console.log('PageY = ' + event.pageY);
        console.log('ScreenY = ' + event.screenY);
        console.log('LayerY = ' + event.layerY);
        console.log('OffsetY = ' + event.offsetY);
    }
</script>

<template>
    <draggable
        v-model="appointments"
        tag="ol"
        @drag="test"
    >
        <li>Appointment...</li>
    </draggable>
</template>

Axios sending cookies for subdomain as well

I have created an application and hosted on dev & production. This how the urls looks like app.hello.com, app.dev.hello.com. My server sending cookies and set cookie domain to hello.com, and dev.hello.com. All cookies set to HTTPOnly and Secure: true, Samesite:Lax.

I am using axios, and set withCredentials:true to read the cookies and send it in request headers.

  • When I open app.hello.com only cookies with hello.com is sent to server.
  • When I open app.dev.hello.com then all the cookies has either hello.com, or dev.hello.com sent to server. I need to restrict this to only dev.hello.com.

How can I do that?

Selenium: DragAndDrop in selenium not working in chrome (C#)

I want to simulate a DragAndDrop during selenium automation tests in chrome.

AFAIK, the DragAndDrop methods provided by selenium are not working anymore because of different reasons (HTML5, Chrome not supporting it anymore?!)

So im now looking for a work around by using a Java Script.

I already went through all the DragAndDrop topics in here, but most of the solutions are from years ago and do not really give me a answer.

There is this one answer which has a Java Script in one of the older questions:
Drag_and_drop does nothing

I tried the java script directly in “google chrome – inspect – console” and modified it a bit but im still getting too many errors (see code below). I assume the errors appear because of the many chrome updates in the past.

I appreciate any help!

Source element id: ATest_DragDropElement

Destination element id: ATest_DropZone

function simulateDragDrop(sourceNode, destinationNode) {
                  var EVENT_TYPES = {DRAG_END: 'dragend',DRAG_START: 'dragstart',DROP: 'drop'};
                  function createCustomEvent(type) {
                      var event = new CustomEvent('CustomEvent');
                      event.initCustomEvent(type, true, true, null);
                      event.dataTransfer = 
                      {
                          data: {},
                          setData: function(type, val) {this.data[type] = val;},
                          getData: function(type) {return this.data[type];},
                          files: {},
                          items: {}
                      };
                      return event;
                  };
                  function dispatchEvent(node, type, event) {
                      if (node.dispatchEvent) {
                          return node.dispatchEvent(event);
                      }
                      if (node.fireEvent) {
                          return node.fireEvent('on' + type, event);
                      }
                  };
                  var event = createCustomEvent(EVENT_TYPES.DRAG_START);
                  dispatchEvent(sourceNode, EVENT_TYPES.DRAG_START, event);
                  var dropEvent = createCustomEvent(EVENT_TYPES.DROP);
                  dropEvent.dataTransfer = event.dataTransfer;
                  dispatchEvent(destinationNode, EVENT_TYPES.DROP, dropEvent);
                  var dragEndEvent = createCustomEvent(EVENT_TYPES.DRAG_END);
                  dragEndEvent.dataTransfer = event.dataTransfer;
                  dispatchEvent(sourceNode, EVENT_TYPES.DRAG_END, dragEndEvent);
               };

var sourceNode = document.getElementById("ATest_DragDropElement");
var destinationNode = document.getElementById("ATest_DropZone");

simulateDragDrop(sourceNode, destinationNode);