Are these export syntax the same

I see a lot of people start a component like:

export default function Example(){XYZ}

Is that the same as writing the function and then exporting at the bottom of the page like so?

function Example(){XYZ};

export default Example

I got this error when i make pnpm build how can i solve it [duplicate]

next build

▲ Next.js 14.2.25

  • Environments: .env

Creating an optimized production build …
✓ Compiled successfully
Linting and checking validity of types ..Failed to compile.

./components/HomeCard.tsx:43:12
Type error: ‘Icon’ cannot be used as a JSX component.
Its return type ‘ReactNode’ is not a valid JSX element.

41 | />
42 | ) : Icon && (

43 |
| ^
44 | )}
45 |
46 |
Next.js build worker exited with code: 1 and signal: null
Linting and checking validity of types . ELIFECYCLE  Command failed with exit code 1.

Autoupgrade prestashop 1.7.8.8 to 8.1.7 – how to solve error with “upgradeDB” step?

I try to upgrade Prestashop from 1.7.8.8 to 8.1.7. I decided to use autoupgrade via cli option. I got an error (I have many more but finally resolved them but stuck here):

INFO - 506 files left to upgrade.
INFO - === Step upgradeFiles
INFO - 106 files left to upgrade.
INFO - === Step upgradeFiles
INFO - All files upgraded. Now upgrading database...
INFO - Restart requested. Please run the following command to continue your upgrade:
INFO - $ modules/autoupgrade/cli-upgrade.php --dir=admin9254z9q7u --action=upgradeDb --data=eyJlcnJvciI6bnVsbCwic3RlcERvbmUiOmZhbHNlLCJuZXh0IjoidXBncmFkZUZpbGVzIiwic3RhdHVzIjoib2siLCJuZXh0X2Rlc2MiOiJJTkZPIC0gUmVzdGFydCByZXF1ZXN0ZWQuIFBsZWFzZSBydW4gdGhlIGZvbGxvd2luZyBjb21tYW5kIHRvIGNvbnRpbnVlIHlvdXIgdXBncmFkZTpcbiIsIm5leHRRdWlja0luZm8iOltdLCJuZXh0RXJyb3JzIjpbXSwibmV4dFBhcmFtcyI6eyJvcmlnaW5WZXJzaW9uIjoiMS43LjguOCIsIml [..]
INFO - === Step upgradeDb
INFO - Cleaning file cache
INFO - Running opcache_reset
PrestaShopException in /var/www/presta_us_klon/classes/db/Db.php line 303
#0 /var/www/presta_us_klon/classes/db/Db.php(236): DbCore::getClass()
#1 /var/www/presta_us_klon/config/alias.php(47): DbCore::getInstance()
#2 /var/www/presta_us_klon/classes/shop/Shop.php(1351): pSQL()
#3 /var/www/presta_us_klon/classes/shop/Shop.php(351): ShopCore::findShopByHost()
#4 /var/www/presta_us_klon/config/config.inc.php(117): ShopCore::initialize()
#5 /var/www/presta_us_klon/modules/autoupgrade/classes/UpgradeContainer.php(665): require_once('...')
#6 /var/www/presta_us_klon/modules/autoupgrade/classes/Task/AbstractTask.php(165): PrestaShopModuleAutoUpgradeUpgradeContainer->initPrestaShopCore()
#7 /var/www/presta_us_klon/modules/autoupgrade/classes/Task/Upgrade/UpgradeDb.php(90): PrestaShopModuleAutoUpgradeTaskAbstractTask->init()
#8 /var/www/presta_us_klon/modules/autoupgrade/classes/Task/Runner/ChainedTasks.php(59): PrestaShopModuleAutoUpgradeTaskUpgradeUpgradeDb->init()
#9 /var/www/presta_us_klon/modules/autoupgrade/cli-upgrade.php(50): PrestaShopModuleAutoUpgradeTaskRunnerChainedTasks->run()
#10 {main}

which is related with this class

    public static function getClass()
    {
        $class = '';
        if (PHP_VERSION_ID >= 50200 && extension_loaded('pdo_mysql')) {
            $class = 'DbPDO';
        } elseif (extension_loaded('mysqli')) {
            $class = 'DbMySQLi';
        }

        if (empty($class)) {
            throw new PrestaShopException('Cannot select any valid SQL engine.');
        }

        return $class;
    }

but as you can see I have both php7.4 extensions:

root@joffrey:/var/www# php7.4 -m | grep pdo_mysql
pdo_mysql
root@joffrey:/var/www# php7.4 -m | grep mysqli
mysqli
root@joffrey:/var/www/presta_us_klon# cat testy.php
<?php
print_r(get_loaded_extensions());
?>
root@joffrey:/var/www/presta_us_klon# php7.4 testy.php | grep -i 'mysqli|pdo_mysql'
    [33] => mysqli
    [34] => pdo_mysql

Page name ‘Login’ is not working on WordPress

I have created a new page called Login (mysite.com/login) on my wordpress website but when I tried to access the page, it throws an error

This is all I see in the source

<html>
<head>
<meta name="color-scheme" content="light dark">
<meta charset="utf-8">
</head>
<body>
<pre>{"error":"not found"}</pre>
<div class="json-formatter-container"></div>
</body>
</html>

I tried disabling and enabling the plugins and nothing worked.

Any help would be appreciated.

Is t possible to listen to multiple connections with ReactPHP truly async?

I need to start tcp server that accepts connections and for every connection creates websocket connection to another server, receives data from tcp, processes the data and sends it to WS

Data sent to tcp is being send continuously, so without truly async handling both tcp and ws, I have lost packets

I tried using reactphp/child-process, still child process needs to liste to stdin and WS, so the problem is the same

Im not proficient in reactPHP, am I doing something wrong or is it just impossible with this environment ?

Problem using define() to enable debug mode

On Prestashop, I have a production and staging server. I want to activate debug mode on staging environment.

I can use $_SERVER['SERVER_NAME'] to identify my environment, so I can define my constant like this :

if (! defined('_PS_MODE_DEV_')) {
    define('_PS_MODE_DEV_', $_SERVER['SERVER_NAME'] === 'staging.domain.name');
}

But it’s not working, the debug mode is not enabled.

When I’m testing my values :

var_dump(! defined('_PS_MODE_DEV_')); // true
if (! defined('_PS_MODE_DEV_')) {
    var_dump($_SERVER['SERVER_NAME'] === 'staging.domain.name'); // true
    define('_PS_MODE_DEV_', $_SERVER['SERVER_NAME'] === 'staging.domain.name');
}
var_dump(_PS_MODE_DEV_); // true

Everything looks good, I don’t understand why the debug mode stills disabled.

I thought it was a problem with the mode itself, but if I set like this :

if (! defined('_PS_MODE_DEV_')) {
    define('_PS_MODE_DEV_', true);
}

It works, the debug mode is enabled…

Maybe there is some limitation with define() ? (I cannot find an example using an expression).

So, I tried like this :

if (! defined('_PS_MODE_DEV_')) {
    if ($_SERVER['SERVER_NAME'] === 'staging.domain.name') {
        define('_PS_MODE_DEV_', true);
    }
    else {
        define('_PS_MODE_DEV_', false);
    }
}

That works too, the debug mode is enabled on staging. HOWEVER, the debug mode is enabled on production too !

I am completely lost, because if I set even like this :

if (! defined('_PS_MODE_DEV_')) {
    if (false) {
        define('_PS_MODE_DEV_', true);
    }
    else {
        define('_PS_MODE_DEV_', false);
    }
}

The debug mode stills enabled… I have no idea what is going on here. For me, it looks like PHP ignores my condition, and takes always the first define().

Could someone give me some ideas to understand what happens here ?

Why a login page using password_verify doesn’t work? [duplicate]

The admin page should be accessed by entering the ‘admin’ NIC and password. The patient sites for other NICs should be accessible with their password.

Here is the patient(user) table:

id NIC Password Name Phone Address
1 admin 1234 Ben 0118675456 Colombo
2 00236584V abcd1 Ann 0114253963 Dehiwela

I used NIC as primary key in the table
here is my PHP code .

<?php
session_start();
$NIC="";
$password = "";
$error = "";
if($_SERVER['REQUEST_METHOD']=='POST')
{
    $NIC = $_POST['nic'];
    $password = $_POST['password'];
    if(empty($NIC)||empty($password))
    {
        $error = "Email and Password are required !";
    }
    else
    {
        include "database.php";
        $dbConnection = getDatabaseConnection();
        
        $statement = $dbConnection->prepare("SELECT id, NIC, Password, Name, Phone, Address FROM user WHERE NIC = ?");
        
        $statement->bind_param('s',$NIC);
        $statement->execute();
        $statement->bind_result($id, $nic, $stored_password, $Name, $Phone, $Address);
        if($statement->fetch())
        {
            if(password_verify($password,$stored_password))
            {
                if(strtolower($NIC)==="admin")
                {
                    $_SESSION["admin_id"] = $id;
                    $_SESSION["admin_username"] = $nic;                 
                    header("location: admin-dashboard.php");
                    exit;
                }
                else
                {
                    $_SESSION["id"]=$id;
                    $_SESSION["nic"]=$nic;
                    $_SESSION["Name"]=$Name;
                    $_SESSION["Password"]=$password;
                    $_SESSION["Phone"]=$Phone;
                    $_SESSION["Address"]=$Address; 
                    
                    header("location: patient-profile.php");
                    exit;
                }
            }
            else
            {
                $error="Email or Password invalid";
            }
        }
        else
        {
            $error="Email or Password invalid";
        }
        $statement->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login / Signup - Wintan Hospital</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <img src="IMG/Logo.jpg" width="100px" height="100px" alt=""/><br>
        <h1>Wintan Hospital </h1>
    </header>

    <main>
        <section class="auth-section">
            <div class="login-form">
                <h2>Login</h2>
                <form action="patient-login.php" method="post">
                    <strong><?= htmlspecialchars($error) ?></strong>
                    <label for="username">Username/NIC:</label>
                    <input type="text" id="nic" name="nic" value="<?= htmlspecialchars($NIC) ?>">
                    <label for="password">Password:</label>
                    <input type="password" id="password" name="password">
                    <button type="submit">Login</button>
                    <a href="forgot-password.html">Forgot Password?</a>
                </form>
            </div>
        </section>
    </main>

    <footer>
        <p>&copy; 2024 Wintan Hospital. All rights reserved.</p>
    </footer>
</body>
</html>

TypeScript error when using amqplib that can’t

I’m working on a Node.js project using TypeScript and the amqplib package (currently at version 0.10.5). When I try to create a connection and channel in my RabbitMQ configuration file, TypeScript throws the following errors:

  1. Property ‘close’ does not exist on type ‘Connection’
  2. Property ‘createChannel’ does not exist on type ‘Connection’
  3. Type ‘ChannelModel’ is missing the following properties from type ‘Connection’: serverProperties, expectSocketClose, sentSinceLastCheck, recvSinceLastCheck, sendMessage
import * as amqp from 'amqplib';
import { Connection, Channel } from 'amqplib';

export class RabbitMQConfig {
  private static connection: Connection | null = null;
  private static channel: Channel | null = null;

  public static async connect(): Promise<void> {
    if (!this.connection) {
      this.connection = await amqp.connect('amqp://localhost');
      this.channel = await this.connection.createChannel();

      this.connection.on('close', () => {
        console.error('RabbitMQ connection closed.');
      });

      this.connection.on('error', (err) => {
        console.error('RabbitMQ connection error:', err);
      });

      console.log('RabbitMQ connected and channel created successfully.');
    }
  }

  public static getChannel(): Channel {
    if (!this.channel) {
      throw new Error('RabbitMQ channel is not initialized. Call connect() first.');
    }
    return this.channel;
  }

  public static async closeConnection(): Promise<void> {
    if (this.channel) {
      await this.channel.close();
      this.channel = null;
    }
    if (this.connection) {
      await this.connection.close();
      this.connection = null;
    }
    console.log('RabbitMQ connection closed.');
  }
}

I don’t know what seems to be the issue since I did try importing the correct module but
TypeScript still complains that the methods close() and createChannel() do not exist on the Connection type.

Any suggestions on how to resolve this type of issue would be greatly appreciated.

How can I change the size of material UI StaticTimePicker

import { StaticTimePicker } from '@mui/x-date-pickers/StaticTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DemoContainer } from '@mui/x-date-pickers/internals/demo';
      
  <LocalizationProvider dateAdapter={AdapterDayjs}>
          <DemoContainer components={['StaticTimePicker']}>
            <StaticTimePicker
              value={values.time}
              onChange={(newValue) =>
                handleChange({ target: { name: 'time', value: newValue } })
              }
              orientation="landscape"
              defaultValue={dayjs(formattedDateTime)}
            />
          </DemoContainer>
        </LocalizationProvider>

How to change the size of the StaticTimePicker?

I tried by adding sx prop and slotProps as well but it is not working.

Use global classes in vue component

Im trying to use classes defined in a scss file in a vue component but doesn’t work

Here are the files:

_zero-state.scss

@use '../../variables' as *;

.zero-state {
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  padding: 80px;

  &__image {
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    width: 208px;
    height: 208px;

  }
  
  &__header {
    margin-top: 20px;
    // text-align: center;
  }

  &__content {
    margin-top: 12px;

  }

  &--empty {
    .zero-state__image{
      background-image: url('#{$illustrations-path}empty.svg')
    }
  }

  &--search {
    .zero-state__image{
      background-image: url('#{$illustrations-path}search.svg')
    }
  }

  &--loading {
    .zero-state__image{
      background-image: url('#{$illustrations-path}empty.svg')
    }
  }

  &--report {
    .zero-state__image{
      background-image: url('#{$illustrations-path}report.svg')
    }
  }

  &--no-connection {
    .zero-state__image{
      background-image: url('#{$illustrations-path}no-connection.svg')
    }
  }

  &--not-found-day {
    .zero-state__image{
      background-image: url('#{$illustrations-path}not-found-day.svg')
    }
  }

  &--not-found-night {
    .zero-state__image{
      background-image: url('#{$illustrations-path}not-found-night.svg')
    }
  }

  &--danger {
    .zero-state__image{
      background-image: url('#{$illustrations-path}danger.svg')
    }
  }

  &--ice-pop {
    .zero-state__image{
      background-image: url('#{$illustrations-path}ice-pop.svg')
    }
  }

  &--lost {
    .zero-state__image{
      background-image: url('#{$illustrations-path}lost.svg')
    }
  }

  &--fingerprint {
    .zero-state__image{
      background-image: url('#{$illustrations-path}fingerprint.svg')
    }
  }
}

main.scss

@forward './variables';
@forward './mixins';

@forward './modules/zero-state/zero-state';

@forward './basics/colors/colors';
@forward './basics/flex/flex';
@forward './basics/typography/typography';
@forward './basics/grid/grid';
@forward './basics/icons/icons';
@forward './basics/logos/logos';
@forward './basics/text/text';

base-zero-state.vue

<script setup>
import { computed } from 'vue'

const props = defineProps({
  header: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  color: {
    type: String,
    default: 'black'
  },
  empty: {
    type: Boolean,
    default: false
  },
  report: {
    type: Boolean,
    default: false
  },
  noConnection: {
    type: Boolean,
    default: false
  },
  notFound: {
    type: Boolean,
    default: false
  },
  danger: {
    type: Boolean,
    default: false
  },
  icePop: {
    type: Boolean,
    default: false
  },
  lost: {
    type: Boolean,
    default: false
  },
  fingerprint: {
    type: Boolean,
    default: false
  },
  search: {
    type: Boolean,
    default: false
  }
})

const fontColor = computed(() => {
  return 'color: ' + props.color
})

const objectClass = computed(() => {
  const notFoundClass =
    new Date().getHours() > 18 ? 'zero-state--not-found-night' : 'zero-state--not-found-day'
  return {
    'zero-state': true,
    'zero-state--empty': props.empty,
    'zero-state--search': props.search,
    'zero-state--report': props.report,
    'zero-state--danger': props.danger,
    'zero-state--ice-pop': props.icePop,
    'zero-state--lost': props.lost,
    'zero-state--fingerprint': props.fingerprint,
    'zero-state--no-connection': props.noConnection,
    [notFoundClass]: props.notFound
  }
})
</script>

<template>
  <div :class="objectClass">
    <div class="zero-state__image"></div>
    <div class="zero-state__header">
      <div :style="fontColor" class="h6-header content-title">{{ header }}</div>
    </div>
    <div :style="fontColor" class="zero-state__content content-title body-copy-bold grey500">
      {{ content }}
    </div>
    <div class="zero-state__actions"></div>
  </div>
</template>

vite.config.js

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        // api: 'modern-compiler', // or "modern"
        additionalData: `
          @use "@/assets/scss/main.scss" as *;
          `
      }
    }
  },
})

package.json

 "devDependencies": {
    "@mdi/font": "^7.4.47",
    "@rushstack/eslint-patch": "^1.2.0",
    "@vitejs/plugin-vue": "^5.2.1",
    "@vitest/coverage-c8": "^0.31.1",
    "@vue/eslint-config-prettier": "^7.1.0",
    "@vue/test-utils": "^2.3.2",
    "eslint": "^8.39.0",
    "eslint-plugin-vue": "^9.11.0",
    "jsdom": "^22.0.0",
    "prettier": "^2.8.8",
    "sass": "^1.85.1",
    "vite": "^6.2.1",
    "vite-plugin-ejs": "^1.6.4",
    "vitest": "^0.31.0"
  }

I’ve missing something? I can use the colors defined in @forward ‘./basics/colors/colors’; in the proyect but no the classes defined @forward ‘./modules/zero-state/zero-state’;

How can I create an alias for a function?

I would like to remove classes of an element not with the function document.querySelector("#id").classList.remove("class") but with the function document.querySelector("#id").classes.del("class")

I was able to create an alias for the remove function and now I can use the function document.querySelector("#id").classList.del("class")

Option 1:

DOMTokenList.prototype.del = function () {
    return DOMTokenList.prototype.remove.apply(this, Array.prototype.slice.call(arguments));
}

Option 2:

DOMTokenList.prototype.del = DOMTokenList.prototype.remove;

Please tell me which of these options is better.

But then I can’t create an alias for classList.
I tried the following options:

Element.prototype.classes = Element.prototype.classList;
Element.prototype.classes = DOMTokenList;
Element.prototype.classes = Object.create(DOMTokenList);
Element.prototype.classes = new DOMTokenList();

“Uncaught (in promise) OperationError” when decrypting response using SubtleCrypto in Vue.js

By using SubtleCrypto, I’m trying to create function for encrypting and decrypting data to make my http request and response to be encrypted to protect sensitive data from unauthorized access.

I send request via axios by doing below.

MyComponent.vue


const key = await this.generateKey();
const data = "Protected Request";
const { ciphertext, iv, tag } = await this.encryptData(key, data);

const exportedKey = await this.exportKey(key);

let dataObj = {}
dataObj.ciphertext = Buffer.from(ciphertext).toString('base64')
dataObj.iv = Buffer.from(iv).toString('base64')
dataObj.tag = Buffer.from(tag).toString('base64')
dataObj.key = Buffer.from(exportedKey).toString('base64')

const response = await axios.post('api/fetchingData', dataObj);

let result = response.data

MyController.php


public function store(Request $request){
    $ciphertext = base64_decode($request->input('ciphertext'));
    $iv = base64_decode($request->input('iv'));
    $tag = base64_decode($request->input('tag'));
    $key = base64_decode($request->input('key'));
    
    //function to decrypt data.
    
    /** Want to encrypt the return data to protect sensitive information from database */
    $returnData = "This is sample return data to be encrypted";
    $encryptedResponse = openssl_encrypt(
        $returnData,
        'aes-256-gcm',
        $key,
        OPENSSL_RAW_DATA,
        $iv,
        $tag
    );
    return response()->json([
        'encryptedResponse' => base64_encode($encryptedResponse),
        'iv' => base64_encode($iv),
        'tag' => base64_encode($tag),
    ]);

}

If i console.log(result) to check the result, it shows below
enter image description here

Which seems correct, as it really encrypted data.

Now, i want to decrypt this result so i can use it on my webpage(example: table)
I do..

const importedKey = await this.importKey(exportedKey);
const resultData = new Uint8Array(atob(result.encryptedResponse).split("").map(c => c.charCodeAt(0)));

console.log("importedKey:", importedKey);
console.log("resultData:", resultData);
console.log("iv:", iv);

and give me this console result
enter image description here

But when I try to decrypt data, it gives me error below..

“Uncaught (in promise) OperationError”

enter image description here

This is how I do it and my decryptData() function


async fetchData(){
    // Other codes(see above)..
    const decryptedData = await this.decryptData(importedKey, resultData, iv);
    console.log("Decrypted Data Result:", decryptedData);
},  
        
async decryptData(key, encryptedData, myIV) {
    try {
        const decryptedData = await window.crypto.subtle.decrypt(
            {
                name: "AES-GCM",
                iv: myIV, 
                tagLength: 128 
            },
            key,
            encryptedData // the content
        );

        return new TextDecoder().decode(decryptedData);
    } catch (error) {
        console.error("Decryption error:", error);
        throw error;
    }
},

How to do so I can decrypt the response.data or result? The value of show in console should be “This is sample return data to be encrypted.”, which is came from the encrypted data in controller.

Unable to Access API in Next.js App Router – 404 Not Found

I’m new to Next.js and I’m trying to send an email using an API route, but I’m facing an issue where I cannot access the API.

I have the following structure:

  • API Route: src/app/api/send-mail/route.ts
  • Front-end Component: src/app/UnityGame.tsx

Even when I try to access the API manually by going to "https://localhost:3000/api/send-mail", I get a 404 Not Found error.

I’ve double-checked that the API route is in the correct directory and the file is set up properly with the POST handler. I also confirmed that I’m using the App Router in Next.js, but still, the route seems inaccessible.

Has anyone encountered a similar issue, or could you guide me on what might be causing this problem?

// src/app/api/send-mail/route.ts
import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

export async function POST(req: Request) {
  const { recipient, body } = await req.json();

  if (!recipient || !body) {
    return NextResponse.json({ error: 'Recipient and body are required' }, { status: 400 });
  }

  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: parseInt(process.env.SMTP_PORT || '587'),
    secure: process.env.SMTP_PORT === '465',
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });

  const mailOptions = {
    from: process.env.SMTP_USER,
    to: recipient,
    subject: 'Test Email',
    text: body,
  };

  try {
    await transporter.sendMail(mailOptions);
    return NextResponse.json({ message: 'Email sent successfully' });
  } catch (error) {
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

When I attempt to send a request to the API from the client-side, I cannot reach the endpoint.