Is there any way to convert javascript into php?

I was working on a project using laravel as my framework, Last week I was on vacation and came back to the project having a bunch (hundreds of lines) of javascript written into it by another student. It in theory works with the javascript but id want to convert it to php. Is there any way to do this? Or do I have to just write it all manually and find new ways to replicate the functions written in javascript using php?

The javascript looks like this and this is just a small part of it, this is a view of mine, not a controller and thats a big issue too and I dont think this is a very secure solution either compared to using laravel as supposed to?
`function readApts(aptBlocks, logsheetID){
const fnl = { logsheet: logsheetID, currentaptblock: 0, currentapt: 0, currentsocket: 1, apts: [] };

    aptBlocks.split(',').forEach((apt, index) => { //Splits the given blocks into a list on every , and does a foreach on all of them // NN
        const out = { block: apt, apt: [] };
        const aptsInput = document.querySelector(`#apartmentBlock${index}`).value.replace(/s+/g, ''); //Reads the specific apartment input and removes all spaces in it // NN

        if(aptsInput){ //If the input actually has any data in it // NN
            const res = [];

            aptsInput.split(',').forEach((apt) => { //Splits each apartment number input into a list on every , and does a foreach on each number // NN
                if(apt.includes('-')){
                    const [start, end] = apt.split('-'); //Splits the element into 2 if it has a - // NN
                    for(let i = Number(start); i <= Number(end); i++){
                        res.push(i.toString()); //Takes every single number in between the 2 given numbers and puts them into the list // NN
                    }
                }else{
                    res.push(apt.toString()); //Just pushes the number into the list if it doesnt contain a - // NN
                }
            });

            out.apt = res;

            $.ajax({ //Sends an AJAX POST request to the set route to create the apartments into the database // NN
                type: "POST",
                url: "{{ url('log_sheets/createapartments') }}",
                async: false,
                data: {
                    block: apt,
                    apts: res,
                    logsheet: logsheetID,
                },
                success: function(response){
                    console.log(response);
                    out.id = response; //Returning the ID of each apartment // NN
                },
            });

            fnl.apts.push(out); //Saves all the info of each apartment into a bigger list // NN
        }
    });

    $.ajax({ //Sends an AJAX POST request to the set route to save all the apartment info to the specified logsheet // NN
        type: "POST",
        url: "{{ url('log_sheets/updatelog') }}",
        data: {
            logsheet: logsheetID,
            apts: fnl.apts,
        },
    });

    $.ajax({ //Sends an AJAX POST request to the set route to save all info to the session for later use // NN
        type: "POST",
        url: "{{ url('log_sheets/savesession') }}",
        data: {
            data: fnl,
        },
        success:function(res){
            console.log(res, fnl);
            document.querySelector("#measureButton").style = "";
        },
    });
}`

Tried finding a solution but have not found one, thought id give this place a shot since it usually has helped people resolve their problems

Manifest v3 sandboxed origin in iframe doesn’t have media devices permissions

our sandboxed application is wrapped by a top level html, which servers as a proxy between our app and service workers.

I need access to microphone in the application, navigator.mediaDevices.getUserMedia({ audio: {deviceId: {exact: 'default'}} }), but it seems like we cannot do that in a sandboxed origin? [Violation] Permissions policy violation: microphone is not allowed in this document.

I haven’t seen any mention of the navigator.mediaDevices being blocked in a sandboxed origin. But if that’s the case, is my only workaround to handle audio in the wrapper?

Here’s what I’ve been trying to do

Top level wrapper:

let iframe = document.createElement('iframe'),
    appUrl = chrome.runtime.getURL('index.html');

iframe.setAttribute('src', appUrl);
iframe.setAttribute('allow', 'microphone ' + appUrl);
document.body.appendChild(iframe);

Permissions in manifest.json:

"permissions": [
    "notifications",
    "storage",
    "notifications",
    "scripting",
    "contentSettings"
],

Downloading a PDF in next js

I am facing an issue while trying to download a pdf file in a next js app.
basically I want to download the pdf file that is placed inside the public folder of the next js app but it is giving error “file was not available on site”. here is the code.

code of button and utility function used to download pdf file

Code for Button:

"use client";

// utility functions
import downloadPDF from "@/utils/downloadPDF";

// components
import Button from "@/components/common/Button";

// import resume from "../../public/resume.pdf";

const ResumeButton = () => {
  const resumeClick = (e) => {
    e.preventDefault();
    // window.open("../../public/resume.pdf", "_blank");

    downloadPDF("../../public/resume.pdf", "HaroonAhmed.pdf");
  };
  return (
    <Button
      bgColor="bg-lime-600"
      textColor="text-white"
      className="my-4"
      handleClick={resumeClick}
    >
      Download Resume
    </Button>
  );
};

export default ResumeButton;

utility function to download file

const downloadPDF = (url, filename) => {
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

export default downloadPDF;

I tried to open pdf in new tab using window.open(“../../public/resume.pdf”, “_blank”); as well as pdf download function but both of these ways face same error. file not found. I will be happy if one of the ways work.

Is there any software which could display webpages using custom URLs and it could be work on top of other applications? [closed]

I’m currently working on a project related to Formula 1, where I display updates from a webpage, for my virtual F1 league and FIA decisions on a webpage. I also integrate this content into Twitch streams using OBS’s web feature and send custom messages to Discord. Now, I’m looking for a Windows application that can notify the league’s racing drivers about events like penalties or race red flags. If anyone knows of existing solutions or has suggestions, I’d appreciate the input.

Greetings everyone, I’m currently grappling with a challenge outlined in the title and would appreciate your recommendations.

To provide some context, I’ve developed a hobby project related to Formula 1, which serves as a system for displaying webpage content. Specifically, it showcases updates from my virtual F1 league and FIA decisions on-screen, akin to real-life broadcasts. I manage the content backend, ensuring webpage refreshes upon sending new information. Additionally, I integrate this content into Twitch streams via OBS’s web display feature, with supplementary custom messages sent to Discord, albeit their relevance is secondary.

My next endeavor involves finding or developing a Windows application for the league’s racing drivers to use on their personal screens. This application would provide notifications for events like 5-second penalties or race red flags. I’m open to coding solutions if necessary, as challenges like this don’t scare me. However, if there are existing solutions available, I’d greatly appreciate any insights or recommendations.

Dragging a Node with Its Children in React Flow

I am working with React Flow and I am trying to achieve a behavior where dragging a node also moves all the nodes connected to it as children. Does anyone know of a solution that would allow for this?

I’ve attempted a solution as shown below, but it doesn’t fully work as expected. The connected nodes do move with the dragged node, however, the movement does not account for the zoom level.

Here’s the code snippet I tried:

function onNodesDrag(event: React.MouseEvent, node: Node) {
       const { movementX, movementY } = event;

       const nodes = getNodes();
       const edges = getEdges();

       const dx = movementX;
       const dy = movementY;

       const connectedEdges = edges.filter((edge) => edge.source === node.id);

       const connectedNodeIds = new Set(
         connectedEdges.map((edge) =>
           edge.source === node.id ? edge.target : edge.source
         )
       );

       const updatedNodes = nodes.map((n) => {
         if (n.id === node.id || connectedNodeIds.has(n.id)) {
           return {
             ...n,
             position: {
               x: n.position.x + dx,
               y: n.position.y + dy,
             },
           };
         }
         return n;
       });

       setNodes(updatedNodes);
     }

I also tried a version where I fetched the zoom value from React Flow, but the calculations I performed were incorrect. Can someone guide me on how to properly account for the zoom level when moving nodes and their connected children?

HorizontalNavigation – NuxtUI – Passing data from a Pinia store

I’m having an issue regarding the UHorizontalNavigation from NuxtUI.

When passing the “links” array to the “UHorizontalNavigation” component, it works.

However, I would like to deport the “links” array to a dedicated Pinia store.

When I do so, “UHorizontalNavigation” component is unable to display the icons anymore. Any clue ?

// This works : 

<template>
  <UHorizontalNavigation :links="links"></UHorizontalNavigation>
</template>

<script setup lang="ts">
interface ILayoutState {
  icon: string;
  label: string;
  to: string;
}

const links = [
  [
    {
      icon: 'i-heroicons-home-solid',
      label: 'Home',
      to: '/',
    },
    {
      icon: 'i-heroicons-book-open-solid',
      label: 'Product',
      to: '/product',
    },
  ],
  [
    {
      icon: 'i-heroicons-user-circle-solid',
      label: 'Login',
      to: '/login',
    },
  ],
] as ILayoutState[][];
</script>

// This doesn't work (icons are not displayed) :

<template>
  <UHorizontalNavigation :links="links"></UHorizontalNavigation>
</template>

<script setup lang="ts">
const layoutStore = useLayoutStore();
const links = computed(() => layoutStore.links);
</script>

// Below, is the store :

import { defineStore } from 'pinia';

interface ILayoutState {
  icon: string;
  label: string;
  to: string;
}

export const useLayoutStore = defineStore({
  id: 'layoutStore',
  state: () => ({
    links: [
      [
        {
          icon: 'i-heroicons-home-solid',
          label: 'Home',
          to: '/',
        },
        {
          icon: 'i-heroicons-book-open-solid',
          label: 'Product',
          to: '/product',
        },
      ],
      [
        {
          icon: 'i-heroicons-user-circle-solid',
          label: 'Login',
          to: '/login',
        },
      ],
    ] as ILayoutState[][],
  }),
  getters: {},
  actions: {},
});

Is there a way to detect the position of a button that was clicked?

I’m trying to build a little tool for myself that essentially takes a screenshot of the current tab whenever an action is taken (ex. button clicked, a text field is completed) and draws some sort of square around the part of the current tab where the action was taken.

A basic example would be that if I was on Wikipedia reading an article about bears and I clicked on a hyperlink to a page about mammals, a screenshot would be generated of the page about bears with a red box around the hyperlink.

I’ve tried looking around and so far people only can add listeners to find the button actions. However, I also want the “coordinates” of the element manipulated. Any help would be appreciated 🙂

Videos download [closed]

I have website where we study for final exam from and they won’t allow us to take the videos you need to pay more extension can you download the videos from this website
“Its only open on microsoft edge”

Someone to tell me is it possible or not

Swiper is not working after merge the code from main branch

This is the code i am using in html file

  <swiper-container [pagination]="true">
    @for (user of userList; track $index;) {
    <swiper-slide class="d-flex align-items-center justify-content-center">
      <ion-card class="mt0 ml0 mr0">
        <div class="gradient-overlay"></div>
        <img
          class="object-fit-cover"
          width="420"
          height="220"
          [src]="user?.img"
          alt=""
        />

        <div
          class="d-flex justify-content-between w-100 position-absolute pdb16 px-3 bottom-0"
        >
          <div class="pdl-h3 pdl-clr-white pdb6">
            {{ user.padelCourtName }}
          </div>
          <div class="pdl-h3 d-flex text-end bold pdl-clr-white">
            ${{ user.price }}/h
          </div>
        </div>
      </ion-card>
    </swiper-slide>
    }
  </swiper-container>

and the ts code is

userList: any[] = [
{
id: 1,
padelCourtName: ‘Padel Court Name 1′,
price: ’50’,
img: ‘../../assets/court-img.jpg’,
},
{
id: 2,
padelCourtName: ‘Padel Court Name 1′,
price: ’50’,
img: ‘../../assets/court-img.jpg’,
},
{
id: 3,
padelCourtName: ‘Padel Court Name 1′,
price: ’50’,
img: ‘../../assets/court-img.jpg’,
},
];

I also import the CUSTOM_ELEMENTS_SCHEMA and schemas for this when i am using this before the merge code it is work properly and now i merge the the code to my branch from the main branch and there is no error in console .
what should i do ?

I also ask the Chatgpt and it is told me to check the data but it is also not working

Update component JS for chart when component refreshre-render

I am using ApexChart and added that in the Livewire component,

   <select class="form-select form-select-solid" aria-label="Select example" wire:model.change="expiry">
                <option>Select Expiry</option>
                <option value="2024-03-28">2024-03-28</option>
                <option value="2024-04-25">2024-04-25</option>
    </select>

    <div class="card-body" id="chart">
            --This is chart
    </div>

@push('scripts')
         ......
        var chart = new ApexCharts(document.querySelector("#chart"), options);
        chart.render();
@endpush

When the page loads, the component loads and I can see a chart with correct data. So far all good.

Now, I have select option in the component and based on the selected value, data are being queried in DB and I get the correct data,

I can see the component getting refreshed, but I don’t see any updates in chart data, and even console.log() doesn’t print anything, so it looks like the script inside the component doesn’t reactivate.

So how to refresh scripts which are inside livewire component itself?

Expression similar to Regex_Replace in Tableau in PowerQuery editor of Power BI

I want to implement something similar to regex_replace of Tableau in PowerBI

From the internet, I got this video:
https://youtu.be/ggrGg6zsaHc?feature=shared

I modified my script to use str.replace method in JS

`

(regex as text, str as text, replacement as text) =>

let

html = "<script>var regex = " & regex & "; var str = """ & str & """; var res = str.replace(regex, '" & replacement & "'); document.write(res)</script>",

replacedText = Web.Page(html)[Data]{0}[Children]{0}[Children]{1}[Text]{0}

in

replacedText`

Now I want to implement something similar to loops of regex_replace in Tableau.
I want to pass a list of regex, a string , and then a list of replacement text corresponding to the regex.
I tried but the query gave error upon running.

I tried following
`

(regex as list, str as text, replacements as list) =>

let

regexList = List.Transform(regex, each Text.From(_)),

replacementsList = List.Transform(replacements, each Text.From(_)),



// Ensure both lists have the same number of elements

minLength = List.Min({List.Count(regexList), List.Count(replacementsList)}),

regexString = "[" & Text.Combine(List.FirstN(regexList, minLength), ",") & "]",

replacementsString = "[" & Text.Combine(List.FirstN(replacementsList, minLength), ",") & "]",



html = "<script>

let modifiedString = '" & str & "';

let regex = " & regexString & ";

let replacements = " & replacementsString & ";

if (regex.length === replacements.length) {

    regex.forEach((reg, index) => {

        modifiedString = modifiedString.replace(new RegExp(reg, 'g'), (match, ...capturedGroups) => {

            const replacement = replacements[index];

            const replacedString = replacement.replace(/\$(\d+)/g, (match, groupIndex) => {

                const capturedGroupIndex = parseInt(groupIndex, 10) - 1;

                return capturedGroups[capturedGroupIndex] || '';

            });

            return replacedString;

        });

    });

    document.write(modifiedString);

} else {

    document.write('Error: Number of regex patterns does not match the number of replacement strings.');

}

</script>"

in

html`

This gave following error

Expression.Error: There weren’t enough elements in the enumeration to complete the operation.

Details:

[List]

How to place a submit button near Upload Component from Ant-D

I want to place a Submit button near the Upload Component. I am new to web development, please someone guide me how can I make it possible. here I am attaching my code and current look of the component.
click to view image here

As per the Image the Submit button is really far from the Upload button. I want to make it place it on the right side of the Upload button, exactly just 3px away from right side.

Here, is my code:

<>
  <div style={{ display: "flex", justifyContent: "center", gap: "3px" }}>
    <Upload {...this.uploadProps} accept="image/png, image/jpeg" maxCount={1}>
      <Button icon={<UploadOutlined />}>Upload</Button>
    </Upload>
    {this.state.uploadEmployeeDocument.length > 0 ? (
      <Button
        onClick={() => {
          window.alert("hello world");
        }}
        size="small"
        type="primary"
      >
        Submit
      </Button>
    ) : (
      ""
    )}
  </div>
  <CardContainerSettings></CardContainerSettings>
</>;

I have tried with my code. but alignment not working properly as expected

How to force custom js/css files in Sphinx to always load changes without caching?

In conf.py I have:

html_css_files = ['css/custom.css']
html_js_files = ['js/custom.js']

However if I make any change in custom.js or custom.css then this change does not reflect to in the user’s browser unless http://www.example.com/_static/js/custom.js is forcefully reloaded on the client (similarly for CSS).

How can I force the custom CSS + JS to never cache on the user’s browser?

JSON Parse Error: unexpected identifier ‘undefined’ – but I believe I have valid JSON

I’m working on a react native app and am calling an API to get an array of JSON objects. As it says in the title, I’m getting an error: JSON Parse Error: unexpected identifier 'undefined'. I am able to JSON.stringify() my response (although it is already coming back as a string). I also tried validating the response in an online JSON validator. Here is what the original API response looks like (type is object):

["[{"model": "users.label", "pk": 1, "fields": {"english_title": "test1", "french_title": "test1", "grade": "0"}}, {"model": "users.label", "pk": 2, "fields": {"english_title": "test2", "french_title": "test2", "grade": "2"}}]", "[{"model": "users.label", "pk": 1, "fields": {"english_title": "test1", "french_title": "test1", "grade": "9"}}]"]

I think there is something wonky with the API, as it looks like one of the fields (test1) is repeated. Ultimately, I want to be able to identify an “english title” given a particular pk value on my end. But I haven’t even gotten that far. I get the undefined error when I try this:

JSON.parse(JSON.stringify(myResponse[0])) or JSON.parse(myResponse[0])

I am getting the error above. One weird thing I notice is I am actually able to log the value if the page is already loaded, but every time I refresh it is there again. Here is how I get the response value:

  useEffect(() => {
    getData().then((value) => {
      fetch(`${MY_URL}/list-view/${value?.username}`, {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      })
        .catch((e) => console.log(e))
        .then(async (res) => {
          const response = await res.json()
          const myResponse = JSON.parse(response).stuff
          setMyResponse(JSON.parse(myResponse))
        })
    })
  }, [navigation])

myResponse is the response in question. Let me know if I need to clarify anything and any help is appreciated. Thanks!

WooCommerce checkout input value being lost on click or submit

I need to set #billing-postcode to a certain value, via a JS script.

If I go on the checkout page and write

jQuery('#billing-postcode').val('2222')

I see the input with the value 2222 and the Postcode label on top of it. If I click the postcode input, the value gets cleared.

I’ve tried adding to the parent the is-active class, which solved the issue of showing the label on top of the value in the field, but the second I click on the input it gets cleared.

When I check the DOM, there is no value set so I’ve added the attribute value with 2222 and this time it stays there.

The issue is not gone, as if I submit the form, the postcode gets emptied and the value lost.

I also tried to POST to /wp-json/wc/store/v1/batch?_locale=user, path /wc/store/v1/cart/update-customer which indeed keeps the value on refresh, but then again, if I change the value from the console, once again, not it flickers between the old value and the new value.

[UPDATE] I just turned off all the event listeners on all input fields and that solves my issue, BUT it creates another few… no more live validation, countries dropdown not working etc.

Is there anyone who had this issue and found a fix?

**With a fresh WP installation, fresh Woocommerce, no other plugins and the default theme, the field value doesn’t get filled.
**

  • adding is-active class to the parent
  • post value to /wp-json/wc/store/v1/batch?_locale=user
  • remove all event listeners
  • set the value via attribute