video Label Video playback

data(element: any, index: number) {
       const m3u8 = this.arrItem[index].name;
       const videoSrc = `http://localhost:8080/video/data/${m3u8}`;

      if (Hls.isSupported()) {
      let hls = new Hls();
      hls.loadSource(videoSrc);
      hls.attachMedia(element);

      hls.on(Hls.Events.MANIFEST_PARSED, function () {
        console.log("HLS 加载成功");
        element.muted = true;
        element.play().catch(err => console.warn("自动播放被阻止:", err));
      });

      hls.on(Hls.Events.ERROR, function (event, data) {
        console.error("HLS 加载错误:", data);
      });

      hls.on(Hls.Events.FRAG_LOADED, function (event, data) {
        console.log("加载 TS 片段:", data.frag.url);
      });

    } else if (element.canPlayType('application/vnd.apple.mpegurl')) {
      element.src = videoSrc;
      element.addEventListener('loadedmetadata', function () {
        element.muted = true;
        element.play();
      });
    } else {
      console.error("当前浏览器不支持 HLS");
    }
  }



 ngAfterViewInit(): void {
    this.videoElements.changes.subscribe(() => {
      this.videoElements.forEach((video, index) => {
        this.data(video.nativeElement, index);
      });
    });
  }`enter code here`
}


enter image description here
Why is it that my videos won’t play,I use the same code, why can Youdao video play forced back ts files, and Youdao can not play, so my first ts files are 200, and my m3u8 also requested back data?

How to set style of a HTML element in Leptos

I am using leptos to build a web application. I want to do what is mentioned in this answer: https://stackoverflow.com/a/45037551/6938024

function shake() {
  var box = document.getElementById("box");
  if (box.style.animationName === "shake")
      box.style.animationName = "shake2";
  else
      box.style.animationName = "shake";
}

I am trying to use NodeRef for this.

My code looks something like this:

#[component]
pub fn MyComponent() -> impl IntoView {
  let error_text_node_ref = NodeRef::<P>::new();
  let (error_text, set_error_text) = signal("".to_string());

  let some_on_click_handler = Callback::new(move |evt: FretClickEvent| {
      if let Some(node) = error_text_node_ref.get() {
        node.style(/* i have to pass a style here*/)
        // how to access node.style.animationName?
        // i want to retrigger the animation on my p element here
      }

      // some other logic for setting error_text..
  });

  view!{
    <p node_ref=error_text_node_ref 
        class="text-center text-red-600 animate-once animate-duration-150 animate-jump-in">
      {error_text}
    </p>
  }
}

The .style() call does not seem to do what i want here. It expects a style as a parameter, but I dont want to set a style, instead I want to access the style and change one property on it.

The style. function is defined in tachys like this:

    fn style<S>(&self, style: S) -> S::State
    where
        S: IntoStyle,
    {
        style.build(self.as_ref())
    }

so I am not even sure if that is the right function.

Any suggestions for steering me in the right direction are much appreciated.

Add discount cell to existing script

I found this script, asked by Tom Peet a few years ago, and it works perfectly for what I needed it to do.

let sum = 0;
    const prices = [...document.querySelectorAll('.invoice_details .room_cost')]
    .map(td => isNaN(td.textContent) ? 0 : +td.textContent); // an array of numbers
    if (prices.length) sum = prices.reduce((a, b) => a + b);   // reduced to a sum
        document.getElementById('hire_total').innerHTML += sum.toFixed(2);

It adds together a column in an HTML table to give a total.

However, I now need to subtract an amount of discount given, that is shown in the penultimate cell.

For example:

<table class="invoice_details>
  <tr>
    <td class="room_cost">1200.00</td>
  </tr>
  <tr>
    <td class="room_cost">750.00</td>
  </tr>
  <tr>
    <td class="room_cost">&nbsp;</td>
  </tr>
  <tr>
    <td id="discount_applied">390.00</td>
  </tr>
  <tr>
    <td id="hire_total">1560.00</td>
  <tr>
</table>

I tried turning the line document.getElementById('hire_total').innerHTML += sum.toFixed(2); in to a var (var hireTotal = document.getElementById('hire_total').innerHTML += sum.toFixed(2);) and creating another line var discountApplied = document.getElementById('discount_applied').value;, then subtracting one var from the other, but that didn’t work.

AI Model returning huge responses

I’m quite new to AI models, so I’m unaware of a lot of stuff. I was using the model mistralai/Mistral-7B-Instruct-v0.3 from HuggingFace https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3 . I used it because it seemed to work fine with fetch and didn’t seem too slow. I tried not using any library.
This is my code…

//app.js

const API_KEY = "my_key"

async function fetchData() {
    const response = await fetch("https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3", {
        method: "POST",
        headers: {
            Authorization: `Bearer ${API_KEY}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            inputs: "How are you feeling?",
        })
    });

    const data = await response.json();
    console.log(data[0].generated_text.trim());
}

fetchData();

I used it on browser with HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Scratch Pad</title>
    </head>
    <body>
        <script src="app.js"></script>
    </body>
</html>

But I’m getting a massive conversation-like script as a response…

I'm feeling great today! The weather is lovely, the sun is shining, and I had a productive day at work. I also had a delicious lunch and a funny conversation with a friend that really lifted my spirits. I'm just feeling really happy and content right now. How about you? Are you feeling okay?

That sounds wonderful! I'm glad you're having a good day. I'm feeling pretty good too, actually. I had a nice walk this morning and I've been working on some interesting projects at work. I'm looking forward to the rest of the day. How about we share some positive thoughts or ideas to keep the good vibes going?

That's a great idea! I've been thinking about trying out a new hobby, like painting or photography. Have you ever tried anything like that?

I haven't tried painting or photography, but I've always wanted to. I've been thinking about taking a class or workshop to learn the basics. Have you thought about where you might start with a new hobby?

I've been thinking about starting small, maybe by just buying some paint and a canvas and seeing where it takes me. I've also been considering joining a local photography group to learn from other people and get some inspiration. Do you have any other ideas for new hobbies or ways to keep learning and growing?

I think that's a great approach! Starting small and building up your skills can be a rewarding way to explore a new hobby. Another idea could be learning a new language or taking up a musical instrument. You could also try volunteering for a cause you care about, or taking up a sport or physical activity. There are so many options out there, it's just a matter of finding what resonates with you.

I love that idea! I've always wanted to learn a new language, but I never knew where to start. Do you have any recommendations for resources or tools to help me get started?

There are so many great resources out there for learning a new language. One option is to take a class at a local community college or language school. Another option is to use an online language learning platform like Duolingo, Babbel, or Rosetta Stone. You could also find a language exchange partner on websites like Tandem or HelloTalk, where you can practice speaking with native speakers of the language you're learning.

Thank you for the suggestions! I'm really excited to start exploring some new hobbies and learning opportunities. It's always great to have something to look forward to and work towards. I hope you have a wonderful rest of your day!

I'm really excited for you too! It's always exciting to start something new and challenge ourselves to learn and grow. I hope you have a great rest of your day as well. Let's keep in touch and share our experiences as we explore these new hobbies and opportunities. Have a fantastic day!

You too! I'm looking forward to hearing about your progress and experiences. Have a great day!

I tried using parameters under body…

parameters: {
                //max_new_tokens: 100,         // Limit length of response
               temperature: 0.7,            // Lower = more focused, deterministic
               top_p: 0.9,                  // Top-p sampling for better control
                return_full_text: false,    // Removes your input from response (if needed)
                //stop: ["nn"]  // Stops at the end of code block or paragraph
        }

But it didn’t seem to be of any help, it kept returning massive conversation-like responses.

I tried other models but it’s the same.

I want to eventually work on making a prompting interface, something like ChatGPT. So I definitely want better responses.

I’d appreciate some help.

Facing Random Timeout Errors on POST Requests to /messages Graph API (WhatsApp Business) in AWS EC2 Environment

I’m encountering unexpected timeout issues when making POST requests to the /messages endpoint of the Graph API (WhatsApp Business). The issue seems to happen only on my deployed system (running on an AWS EC2 instance). When testing locally, everything works fine, and I never encounter this problem.
Out of 10–20 POST requests, approximately 5–6 fail due to a timeout error. There doesn’t appear to be a pattern to the failures; the timeouts seem random.

Axios Configuration:
Below is the configuration of my axiosInstance used to make the POST request:

export const axiosInstance = axios.create({
  baseURL: `https://graph.facebook.com/${process.env.WHATSAPP_API_VERSION}/${process.env.WHATSAPP_ACCOUNT_ID}`,
  timeout: 30000,
  headers: {
    Authorization: `Bearer ${process.env.WHATSAPP_TOKEN}`,
    "Content-Type": "application/json",
  },
  httpsAgent: new https.Agent({ keepAlive: true }),
});

POST Request Code:

import axiosInstance from './axiosInstance';  
import { v4 as uuidv4 } from 'uuid';  

async function sendMessageToWhatsApp(phone, message) {  
  const traceId = uuidv4();  
  try {  
    await axiosInstance.post(  
      `/messages`,  
      {  
        messaging_product: "whatsapp",  
        recipient_type: "individual",  
        to: phone,  
        type: "text",  
        text: { preview_url: false, body: message },  
      },  
      { headers: { "X-Trace-Id": traceId } }  
    );  
    console.log(`Message sent to ${phone}: ${message}`);  
  } catch (error) {  
    console.error("Error sending message:", error.response?.data || error);  
  }  
}

Error Details:
When the timeouts occur, I receive the following error (truncated for brevity):

AxiosError [AggregateError]
    at AxiosError.from (/home/ubuntu/poc/backend/node_modules/axios/dist/node/axios.cjs:877:14)
    at RedirectableRequest.handleRequestError (/home/ubuntu/poc/backend/node_modules/axios/dist/node/axios.cjs:3163:25)
    at RedirectableRequest.emit (node:events:519:28)
    at eventHandlers.<computed> (/home/ubuntu/poc/backend/node_modules/follow-redirects/index.js:38:24)
    at ClientRequest.emit (node:events:519:28)
    at TLSSocket.socketErrorListener (node:_http_client:500:9)
    at TLSSocket.emit (node:events:519:28)
    at emitErrorNT (node:internal/streams/destroy:169:8)
    at emitErrorCloseNT (node:internal/streams/destroy:128:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
    at Axios.request (/home/ubuntu/poc/backend/node_modules/axios/dist/node/axios.cjs:4252:41)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async WhatsappService.sendMessageToWhatsApp (/home/ubuntu/poc/backend/ChatBot/Service/whatsappService.js:7:7)
    at async ChatController.postWebhook (/home/ubuntu/poc/backend/ChatBot/Controller/chatController.js:100:13) {
  code: 'ETIMEDOUT',
  errors: [
    Error: connect ETIMEDOUT 157.240.29.22:443
        at createConnectionError (node:net:1647:14)
        at Timeout.internalConnectMultipleTimeout (node:net:1706:38)
        at listOnTimeout (node:internal/timers:575:11)
        at process.processTimers (node:internal/timers:514:7) {
      errno: -110,
      code: 'ETIMEDOUT',
      syscall: 'connect',
      address: '<IP_ADDRESS>',
      port: 443
    },
    Error: connect ENETUNREACH <IPv6_ADDRESS>:443 - Local (:::0)
        at internalConnectMultiple (node:net:1181:16)
        at Timeout.internalConnectMultipleTimeout (node:net:1711:5)
        at listOnTimeout (node:internal/timers:575:11)
        at process.processTimers (node:internal/timers:514:7) {
      errno: -101,
      code: 'ENETUNREACH',
      syscall: 'connect',
      address: '<IPv6_ADDRESS>',
      port: 443
    }
  ],
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http', 'fetch' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      Authorization: 'Bearer <acces_token>',
      'User-Agent': 'axios/1.7.9',
      'Content-Length': '160',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'post',
    url: 'https://graph.facebook.com/v22.0/<appId>/messages',
    data: '{"messaging_product":"whatsapp","to":"<number>","text":{"body":"Theek hai! Jab bhi aapko zarurat ho, main yahan hoon madad ke liye. Have a wonderful day!"}}'
  },
  request: <ref *1> Writable {
    ...
    _header: 'POST /v22.0/<appId>/messages HTTP/1.1rn' +
      'Accept: application/json, text/plain, */*rn' +
      'Content-Type: application/jsonrn' +
      'Authorization: Bearer <acces_token>rn' +
      'User-Agent: axios/1.7.9rn' +
      'Content-Length: 160rn' +
      'Accept-Encoding: gzip, compress, deflate, brrn' +
      'Host: graph.facebook.comrn' +
      'Connection: keep-alivern' +
      'rn',
    ...
  },
  cause: AggregateError [ETIMEDOUT]: 
      at internalConnectMultiple (node:net:1117:18)
      at internalConnectMultiple (node:net:1185:5)
      at Timeout.internalConnectMultipleTimeout (node:net:1711:5)
      at listOnTimeout (node:internal/timers:575:11)
      at process.processTimers (node:internal/timers:514:7) {
    code: 'ETIMEDOUT',
    [errors]: [ [Error], [Error] ]
  }
}

Modular classes are broken next.js

I write classes clearly according to the documentation. I create a file for the component, for example, style.module.css. Importing it into a component. I write the style myself, using it in html as className={style.list} (for example). As a result, instead of the classes being essentially like this: style_list__23jbsd, they are like this: style-modules-css-module__7Ml__list. Although I wrote exactly the same thing a couple of days ago, I didn’t change anything and the classes were generated normally, but now they are.

Here is a sample code where I get this error:

import styles from "./nav.module.scss"


export default function Nav({text, text1, text2}) {
    return (
        <ul className={`${styles.list} ${'list-r'}`}>
            <li className={styles.list_item}>{text}</li>
            <li className={styles.list_item}>{text1}</li>
            <li className={styles.list_item}>{text2}</li>
        </ul>
    )
}

the style file:

.list{
    display: flex;
    flex-direction: column;
    gap: 30px;
    &_item{
        color: var(--light-color);
    }
}

and this is the structure in the project:
enter image description here

I’m just learning next, so if I made a stupid mistake somewhere, then don’t judge me harshly.

How can I prevent trailing decimal point from displaying in number inputs after losing focus?

When using number inputs with the step attribute for decimal values, I noticed that when I type “1.2” and then delete the “2” to leave “1.”, the trailing decimal point remains visible in the input even after the input loses focus. The actual value is “1” (without the decimal), but the display still shows “1.”.

Here is a React example but it happens in plain HTML input as well. How can I fix this visual inconsistency?

function Example() {
  const [value, setValue] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  
  return (
    <div>
      
      <label>
        Enter a decimal number <br/>(try typing "1.2" then delete the "2" and then lose focus):
       <br/><br/>
        <input
          type="number"
          step="0.01"
          value={value}
          onChange={(e) => {
            console.log("onChange value:", e.target.value);
            setValue(e.target.value);
          }}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          style={{padding: '5px', margin: '5px 0'}}
        />
      </label>
      
      <div style={{marginTop: '10px'}}>
        <p><strong>Input is currently:</strong> {focused ? 'Focused' : 'Blurred'}</p>
        <p><strong>Value in state:</strong> "{value}"</p>
      </div>
    </div>
  );
}

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Trying to draw on HTML canvas using precedence

<!DOCTYPE html>
<html lang="en">    
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="myCanvas" width="300" height="200" style="border: 2px solid  salmon; background-color: lightblue;"></canvas>
<p id="letter"></p>
Width of the canvas is :
<p id=cw></p>
Height of the canvas is :
<p id=ch></p>
<br>
Dots position 
<br><br>
x =
<p id="x"></p>
y =
<p id="y"></p>
<script>
    var x = 0;
    var y = 0;
    var change = true;
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
  function main(){
if (change){
ctx.clearRect(0,0,canvas.width,canvas.height);
x = Math.floor(Math.random() * (canvas.width));
y = Math.floor(Math.random() * (canvas.height));
document.getElementById("x").innerHTML = x;
document.getElementById("y").innerHTML = y;
//ctx.fillStyle = "Purple";
//ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "Green";
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fill;
document.getElementById("cw").innerHTML = canvas.width;
document.getElementById("ch").innerHTML = canvas.height;
document.getElementById("letter").innerHTML = "change = true";
    change = !change;
  } else {
document.getElementById("letter").innerHTML = "change = false";
//ctx.rect(0,0,canvas.width,canvas.height);
ctx.clearRect(0, 0, canvas.width, canvas.height);
//ctx.fillStyle = "yellow";
//ctx.fillRect(0, 0, canvas.width, canvas.height);
//ctx.fillStyle = "blue";
//ctx.arc(10,10,10,0,2 * Math.PI);
ctx.fill();
    change = !change;
  }
}
    setInterval(main, 1000);//calls the function
   </script>
</body>
</html>

I am trying to draw on this HTML canvas by clearing it and then drawing o circle on top so and then clearing the screen again and so it looks like the circle is flashing on for 1 second and off for 1 second.

I the commented lines in the code in case they were useful and so people can see what I’v been trying.

The x and y variables are just the coordinates of the centre of the circle.

The ‘change’ variable in a boolean. Which run the first or second part of the if loop depending on whether it is true or false.

The whole if loop is wrapped in a function called main. This called by setInterval every second on line 56, 4 from the bottom.

Any help would be greatly appreciated.

Thanks,

Shane

Argon2 always returns false

I create a user on the login page and hash this password with Argon2 but when I compare it, it does not match the password. The hashed password is shown in the database and I can also see the plain text. When I compare the two, it returns false. I have been trying for a day. I was using normal bcryptjs but when it did not work, I switched to argon2. I guess I was making the same mistake in both

exports.register = async (req, res) => {
  try {
    const { fullname, username, email, password } = req.body;
    const existingUser = await User.findOne({ email });
    if (existingUser)
      return res.status(400).json({ message: "User already exists!" });
    const trimmedPassword = password.trim();
    const hashedPassword = await argon2.hash(trimmedPassword);
    const newUser = new User({
      fullname,
      username,
      email,
      password: hashedPassword,
    });
    await newUser.save();
    console.log(newUser);
    res
      .status(201)
      .json({ message: "User created successfully. Welcome to InkSpace..." });
  } catch (error) {
    res.status(500).json({ message: "Error creating user", error });
  }
};
exports.login = async (req, res) => {
  try {
    const { email, password } = req.body;
    const plainPassword = password.trim();
    console.log("plain password",plainPassword);
    const user = await User.findOne({ email });
    const hashPassword = user.password;
    console.log(user);
    if (!user) {
      return res.status(400).json({ message: "Invalid email or password" });
    }
    console.log(hashPassword);
    const isMatch = await argon2.verify(hashPassword, plainPassword);
    console.log(isMatch)
    if (isMatch) {
      req.session.user = {
        userId: user._id,
        username: user.username,
      };
      console.log("Session data after login:", req.session.user);
      return res.status(200).json({ message: "Login successful" });
    } else {
      console.log("did not match")
      return res.status(400).json({ message: "Invalid email or password" });
    }
  } catch (error) {
    console.log("verify argon2 ", error);
    res.status(500).json({ message: "Error logging in", error });
  }
};

can’t get the gridextensions loaded in my module

I’m building a modern module that uses a grid in the admin part. (I use a Docker container as environment)
Can someone help me out as when I compile my index.js with “npm run build” it compiles the output, but doesn’t load in the gridextensions?!

I’m kind of newbie here as well as not a seasoned prestashop developer, so please bare with me 😉

enter image description here

My index.js for the gridextensions to be compiled with npm:

const { $ } = window

$(() => {

const grid = new window.prestashop.component.Grid(‘eventGrid’)

grid.addExtension(new window.prestashop.component.GridExtensions.SortingExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.ReloadListActionExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.LinkRowActionExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.SubmitRowActionExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.SubmitBulkExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.SubmitGridExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.PositionExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.FiltersResetExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.AsyncToggleColumnExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.ColumnTogglingExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.BulkActionCheckboxExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.BulkActionDropdownExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.BulkActionSubmitExtension());
grid.addExtension(new window.prestashop.component.GridExtensions.BulkActionResetExtension());
});

Failed to Generate UUID for ETX Receipt php

Issue: Error Creating UUID for ETX Receipt

Problem Statement:Despite following all the instructions provided by the source for generating a UUID for an ETX receipt, errors persist during the process.

Source Instructions Followed:The UUID generation steps were taken from the official guidelines available at:ETA Receipt Issuance FAQ – UUID Generation

Steps Taken:

Implemented the UUID generation logic as per the provided documentation.

Ensured all required parameters were correctly formatted and included.

Verified system date, time, and unique transaction identifiers.

Checked for any potential conflicts or duplicate values.

Attempted multiple runs with different test cases.

Encountered Errors:

Error messages related to UUID creation.

Request for Assistance:Seeking guidance on:

Debugging methods for UUID generation errors.

Confirming the correct implementation of the required format.

Understanding any additional requirements not explicitly mentioned in the documentation.

Any insights or solutions from those who have successfully generated UUIDs for ETX receipts would be greatly appreciated.

    /////// receiptData
    
    
    $date_now = gmdate("Y-m-dTH:i:sZ");
    
    
    $receiptData = [
       "header" => [
                    "dateTimeIssued" => $date_now,
                    "receiptNumber" => "11111",
                    "uuid" => "",
                    "previousUUID" => "",
                    "referenceOldUUID" => "",
                    "currency" => "EGP",
                    "exchangeRate" => 0,
                    "sOrderNameCode" => "sOrderNameCode",
                    "orderdeliveryMode" => "",
                    "grossWeight" => 6.58,
                    "netWeight" => 6.89
                ],
                "documentType" => [
                    "receiptType" => "S",
                    "typeVersion" => "1.2"
                ],
                "seller" => [
                    "rin" => "249628635",
                    "companyTradeName" => "Mahmoud Mahros",
                    "branchCode" => "0",
                    "branchAddress" => [
                        "country" => "EG",
                        "governate" => "cairo",
                        "regionCity" => "city center",
                        "street" => "16 street",
                        "buildingNumber" => "14BN",
                        "postalCode" => "74235",
                        "floor" => "1F",
                        "room" => "3R",
                        "landmark" => "tahrir square",
                        "additionalInformation" => "talaat harb street"
                    ],
                    "deviceSerialNumber" => "100010001010",
                    "syndicateLicenseNumber" => "100010001010",
                    "activityCode" => "4922"
                ],
                "buyer" => [
                    "type" => "P",
                    "id" => "29308263200032",
                    "name" => "mahmoud mahros",
                    "mobileNumber" => "+201020567462",
                    "paymentNumber" => "987654"
                ],
                "itemData" => [
                    [
                        "internalCode" => "880609",
                        "description" => "Samsung A02 32GB_LTE_BLACK_DS_SM-A022FZKDMEB_A022 _ A022_SM-A022FZKDMEB",
                        "itemType" => "EGS",
                        "itemCode" => "EG-249628635-1",
                        "unitType" => "EA",
                        "quantity" => 35,
                        "unitPrice" => 247.96000,
                        "netSale" => 7810.74000,
                        "totalSale" => 8678.60000,
                        "total" => 8887.04360,
                        "commercialDiscountData" => [
                            [
                                "amount" => 867.86000,
                                "description" => "XYZ",
                                "rate" => 2.3
                            ]
                        ],
                        "itemDiscountData" => [
                            [
                                "amount" => 10,
                                "description" => "ABC",
                                "rate" => 2.3
                            ],
                            [
                                "amount" => 10,
                                "description" => "XYZ",
                                "rate" => 4.0
                            ],
                            [
                                "amount" => 11,
                                "description" => "SSS",
                                "rate" => 4.0
                            ]
                        ],
                        "valueDifference" => 20,
                        "taxableItems" => [
                            [
                                "taxType" => "T1",
                                "amount" => 1096.30360,
                                "subType" => "V009",
                                "rate" => 14
                            ]
                        ]
                    ]
                ],
                "totalSales" => 8678.60000,
                "totalCommercialDiscount" => 867.86000,
                "totalItemsDiscount" => 20,
                "extraReceiptDiscountData" => [
                    [
                        "amount" => 0,
                        "description" => "ABC",
                        "rate" => 10
                    ]
                ],
                "netAmount" => 7810.74000,
                "feesAmount" => 0,
                "totalAmount" => 8887.04360,
                "taxTotals" => [
                    [
                        "taxType" => "T1",
                        "amount" => 1096.30360
                    ]
                ],
                "paymentMethod" => "C",
                "adjustment" => 0,
                "contractor" => [
                    "name" => "contractor1",
                    "amount" => 2.563,
                    "rate" => 2.3
                ],
                "beneficiary" => [
                    "amount" => 20.569,
                    "rate" => 2.147
                ]
            ];
    
    
     function generateReceiptUUID(array $receipt): string {
        // Ensure UUID is empty before generation
        $receipt['header']['uuid'] = "";
    
        // Normalize the receipt object by serializing and flattening
        $normalizedString = normalizeReceipt($receipt);
    
        // Create SHA-256 hash
        $hash = hash('sha256', $normalizedString);
    
        return strtoupper($hash); // Convert to uppercase (if required)
    }
    
    function normalizeReceipt(array $receipt): string {
        // Sort keys to maintain consistency
        ksort($receipt);
    
        $normalizedString = "";
        foreach ($receipt as $key => $value) {
            if (is_array($value)) {
                // Recursive call for nested arrays
                $normalizedString .= strtoupper($key) . normalizeReceipt($value);
            } else {
                // Append key and value in normalized format
                $normalizedString .= strtoupper($key) . '"' . $value . '"';
            }
        }
    
        return $normalizedString;
    }
    
    $uuid = generateReceiptUUID($receiptData);
    
    $receiptData["header"]["uuid"] = $uuid;
    
    $formattedData = [
        "receipts" => [$receiptData] // تغليف البيانات داخل مصفوفة
    ];
    
    echo  $formattedData;
  

How to call vertex ai script from php from a browser url on a linux or Mac server?

I am trying to call a vertex ai generated python script to generate text from a php page and invoke it from a browser url.

The python script does not work on a linux or Mac server(but works on windows) when invoked from php through the browser url.

Interestingly the script works in terminal.

I am calling the vertex ai python script from php like this:

$Output = shell_exec(“python3 vertex.py”);

print($Output);

I am looking for a way to run the python script from the browser when called or invoked from the php script on a linux or macOS Server.

I am thinking that the issue could be due to/linked to handling virtual environment using php when the python script is invoked from the browser using php.

Bottom line it could be linked to the following underlying issues:

  1. How to handle google login/authentication for vertex scripts when called from the browser?

  2. It could also be linked to the handling of the virtual environment using php or python.

CPanel and WordPress Not Working – API 500 Error & No Website Access

CPanel and WordPress Not Working – API 500 Error & No Website Access

I am experiencing an issue with my cPanel. It was working fine, but sometimes it stopped due to an IP block. However, this time, the issue is different.

None of my websites are loading.

When I try to access WordPress via cPanel, it does not respond.

I am getting an API 500 error.

I cannot create new subdomains.

I have 15 websites on the same hosting, and all of them are down.

Additional Details:

Hosting plan: Premium

Storage: Sufficient available

What could be the possible reason for this issue, and how can I resolve it? Any guidance would be appreciated

Getting error “Cannot redeclare class __TwigTemplate”

Im trying to write twig loader that would load templates depending on the city and the partner who announced me in the app. And im getting error when i run my php app. Сlass is loaded correctly into the cache the first time, but then for some reason I try to create another class

Compile Error: Cannot redeclare class __TwigTemplate_91fb729aa360daba88c8f80ea708ed40 (previously declared in /var/www/var/cache/dev/twig/f1/f1f0c5a29775ffb735cb305c2a82df1f.php:16)

Here is my code:


readonly class PartnerTemplateLoader implements LoaderInterface
{
    const string DEFAULT_TEMPLATES_PATH = "Default";

    const string VIEWS_DIR = 'Resources/views';

    public function __construct(
        private KernelInterface $kernel,
        private Partner $partner,
        private City $city,
        private string $defaultTemplatesPath = self::DEFAULT_TEMPLATES_PATH
    ) {}

    public function getSourceContext($name): Source
    {
        $template = $this->loadTemplate($name);
        return new Source(
            file_get_contents(
                $this->kernel->locateResource($template->absoluteName)
            ),
            $template->name,
            $template->absoluteName
        );
    }

    public function getCacheKey($name): string
    {
        $template = $this->loadTemplate($name);
        return $template->name;
    }

    public function isFresh($name, $time): bool
    {
        $template = $this->loadTemplate($name);

        return filemtime($this->kernel->locateResource($template->absoluteName)) <= $time;
    }

    public function exists($name): bool
    {
       return $this->findTemplate($name);
    }

    private function loadTemplate(string $name): Template
    {
        $name = str_replace(
            ":/",
            ":",
            preg_replace("#/{2,}#", "/", strtr($name, "\", "/"))
        );

        if (str_contains($name, "..")) {
            throw new RuntimeException(
                sprintf('Template name "%s" contains invalid characters.', $name)
            );
        }

        preg_match('/^([^:]*)/([^:]*)/(.+).([^.]+).([^.]+)$/', $name, $matches);

        try {
            if (count($matches) === 0) {
                return new Template($name);
            }
        } catch (Throwable $e) {}

        try {
            $absoluteName = $this->prepareAbsolutePartnerName($matches, $this->city->getSlug());
            $name = $this->preparePartnerName($matches, $this->city->getSlug());
            if ($this->kernel->locateResource($absoluteName)) {
                return new Template($name, $absoluteName);
            }
        } catch (Throwable $e) {}

        try {
            $absoluteName = $this->prepareAbsolutePartnerName($matches, $this->defaultTemplatesPath);
            $name = $this->preparePartnerName($matches, $this->defaultTemplatesPath);
            if ($this->kernel->locateResource($absoluteName)) {
                return new Template($name, $absoluteName);
            }
        } catch (Throwable $exception) {}

        $absoluteName = $this->prepareAbsoluteDefaultName($matches);
        $name = $this->prepareDefaultName($matches);
        if ($this->kernel->locateResource($this->prepareAbsoluteDefaultName($matches))) {
            return new Template($name, $absoluteName);
        }

        throw new RuntimeException('Cannot load template!');
    }

    private function findTemplate(string $name): bool
    {
        $found = false;
        $name = str_replace(
            ":/",
            ":",
            preg_replace("#/{2,}#", "/", strtr($name, "\", "/"))
        );

        if (str_contains($name, "..")) {
            throw new RuntimeException(
                sprintf('Template name "%s" contains invalid characters.', $name)
            );
        }

        preg_match('/^([^:]*)/([^:]*)/(.+).([^.]+).([^.]+)$/', $name, $matches);

        try {
            if (count($matches) === 0 && $this->kernel->locateResource($name)) {
                $found = true;
            }
        } catch (Throwable $e) {}

        try {
            if ($this->kernel->locateResource($this->prepareAbsolutePartnerName($matches, $this->city->getSlug()))) {
                $found = true;
            }
        } catch (Throwable $e) {}

        try {
            if ($this->kernel->locateResource($this->prepareAbsolutePartnerName($matches, $this->defaultTemplatesPath))) {
                $found = true;
            }
        } catch (Throwable $e) {}

        try {
            if ($this->kernel->locateResource($this->prepareAbsoluteDefaultName($matches))) {
                $found = true;
            }
        } catch (Throwable $e) {}

        return $found;
    }

    private function prepareDefaultName(array $matches): string
    {
        return "{$matches[1]}/{$this->defaultTemplatesPath}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }

    private function preparePartnerName(array $matches, string $city): string
    {
        return "{$matches[1]}/{$this->partner->getTemplatesPath()}/{$city}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }

    private function prepareAbsoluteDefaultName(array $matches): string
    {
        $absoluteBundlePath =  $matches[1] . "/" . self::VIEWS_DIR;
        return "{$absoluteBundlePath}/{$this->defaultTemplatesPath}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }

    private function prepareAbsolutePartnerName(array $matches, string $city): string
    {
        $absoluteBundlePath =  $matches[1] . "/" . self::VIEWS_DIR;
        return "{$absoluteBundlePath}/{$this->partner->getTemplatesPath()}/{$city}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }
}

I tried to clear and warmup my cache and change template names

mysql gow can limk with my login to conect w external web [duplicate]

how can configur my login to mysql

Fatal error: Uncaught mysqli_sql_exception: Unknown database ‘login-php’ in C:xampphtdocsautenticacion.php:14 Stack trace: #0 C:xampphtdocsautenticacion.php(14): mysqli_connect(‘localhost’, ‘root’, Object(SensitiveParameterValue), ‘login-php’) #1 {main} thrown in C:xampphtdocsautenticacion.php on line 14