How to build a static website with NextJs

I’m having an issue while trying to build a static website created with Next.js. The out folder is not being generated.

I think the problem is related to the SSR part of Next.js. Although it’s a small website, I am using dynamic routes, which are SSR-based. To resolve this, I tried creating a server-side component and passing the params to the actual client-side component that I wanted to render.

Here’s the current structure:

In the [id] folder, I have a file called page.tsx with the following code:

import { projects } from '@/data/projects';
import ProjectPage from './ProjectPage';

export const generateStaticParams = async () =>
  projects.map((project) => ({
    id: project.id,
  }));

const fetchProjectData = async (id: string) => {
  const project = projects.find((p) => p.id === id);
  return project ?? null;
};

const Project = async ({ params }: { params: { id: string } }) => {
  const project = await fetchProjectData(params.id);

  if (!project) {
    return (
      <div className='w-full h-[100vh] flex justify-center items-center text-5xl font-bold'>
        Project{' '}
        <span style={{ color: 'var(--primary)', margin: '0 10px' }}>not</span>{' '}
        found
      </div>
    );
  }

  return <ProjectPage project={project} />;
};

export default Project;

In the same folder, I also have another file called ProjectPage.tsx, which is a client-side component:

'use client';

const ProjectPage = ({ project }: ProjectPageProps) => {
    ...
};

I added output: ‘export’, in the next.config.ts file.

However, after running npx next build, I received the following output:

$ npx next build
  ▲ Next.js 14.2.26

   Creating an optimized production build ...
 ✓ Compiled successfully
 ✓ Linting and checking validity of types    
 ✓ Collecting page data    
 ✓ Generating static pages (11/11)
 ✓ Collecting build traces    
 ✓ Finalizing page optimization

Route (app)                              Size     First Load JS
┌ ○ /                                    29.3 kB         168 kB
├ ○ /_not-found                          875 B            88 kB
├ ○ /contact                             4.49 kB        99.9 kB
├ ○ /projects                            548 B          94.5 kB
└ ● /projects/[id]                       3.32 kB         143 kB
    ├ /projects/1
    ├ /projects/2
    ├ /projects/3
    └ /projects/4
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-057d17d2e788cd74.js       31.6 kB
  ├ chunks/fd9d1056-f1963c9e20a75983.js  53.7 kB
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-057d17d2e788cd74.js       31.6 kB
+ First Load JS shared by all            87.2 kB
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-057d17d2e788cd74.js       31.6 kB
  ├ chunks/fd9d1056-f1963c9e20a75983.js  53.7 kB
  └ other shared chunks (total)          1.9 kB
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-057d17d2e788cd74.js       31.6 kB
  ├ chunks/fd9d1056-f1963c9e20a75983.js  53.7 kB
+ First Load JS shared by all            87.2 kB
+ First Load JS shared by all            87.2 kB
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-057d17d2e788cd74.js       31.6 kB
+ First Load JS shared by all            87.2 kB
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-057d17d2e788cd74.js       31.6 kB
  ├ chunks/fd9d1056-f1963c9e20a75983.js  53.7 kB
  └ other shared chunks (total)          1.9 kB


○  (Static)  prerendered as static content
●  (SSG)     prerendered as static HTML (uses getStaticProps)

Has anyone encountered a similar issue with Next.js?

Generate a PDF with Table of Contents from HTML using Paged.js

I have read the documentation.

I have tried the sample code.

The command I used to generate the pdf is pagedjs-cli index.html -o index.pdf

The code is:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.18">
<title>Salah</title>
<style>
/* Page Margins */
@page {
    size: A4;
    font-size: 18px;
}

/* Verso (left) page-specific */
@page :left {
    margin-left: 0.79in;
    margin-right: 0.59in;

    @bottom-left {
        /* content: "Page " counter(page) " of " counter(pages); */
        content: counter(page);
        text-align: left;
        margin-left: .1in; /* abs(margin-left - margin-right) / 2 */
    }
}

/* Recto (right) page-specific */
@page :right {
    margin-left: 0.59in;
    margin-right: 0.79in;

    @bottom-right {
        /* content: "Page " counter(page) " of " counter(pages); */
        content: counter(page);
        text-align: right;
        margin-right: .1in; /* abs(margin-left - margin-right) / 2 */
    }
}

.sect1 {
    page-break-after: always;
}

/* Use it using [.pagebreak] */

.pagebreak {
    page-break-before: always;
}

@page clean {
    @bottom-right {
        content: none;
    }

    @bottom-left {
        content: none;
    }
}

/* Use it using pass:pass:[<div class="counter-reset"></div>] */
.counter-reset {
    counter-reset: page 1;
    /* counter-increment: page 1; */
}

/* Use it using pass:[<div class="blank-page"></div>] */
.blank-page {
    page-break-before: always;
    page: clean;
    display: none;
}

/* Add this to your counter-reset class */
.counter-reset {
    counter-reset: page 1;
}
</style>
</head>
<body class="book">
<div id="header">
<h1>Salah</h1>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div id="my-toc-content"></div>
</div>
</div>
<div class="sect1">
<h2 id="_what_to_say_after_the_takbir">What to say after the Takbir</h2>
<div class="sectionbody">

</div>
</div>
<div class="sect1">
<h2 id="_invocation_in_bowing_and_prostrations">Invocation in Bowing and Prostrations</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_this_is_the_third">This is the third</h3>
<script>
function createToc(config) {
  const content = config.content;
  const tocElement = config.tocElement;
  const titleElements = config.titleElements;

  let tocElementDiv = content.querySelector(tocElement);
  let tocUl = document.createElement("ul");
  tocUl.id = "list-toc-generated";
  tocElementDiv.appendChild(tocUl);

  // add class to all title elements
  let tocElementNbr = 0;
  for (var i = 0; i < titleElements.length; i++) {
    let titleHierarchy = i + 1;
    let titleElement = content.querySelectorAll(titleElements[i]);

    titleElement.forEach(function (element) {
      // add classes to the element
      element.classList.add("title-element");
      element.setAttribute("data-title-level", titleHierarchy);

      // add id if doesn't exist
      tocElementNbr++;
      idElement = element.id;
      if (idElement == "") {
        element.id = "title-element-" + tocElementNbr;
      }
      let newIdElement = element.id;
    });
  }

  // create toc list
  let tocElements = content.querySelectorAll(".title-element");

  for (var i = 0; i < tocElements.length; i++) {
    let tocElement = tocElements[i];

    let tocNewLi = document.createElement("li");

    // Add class for the hierarcy of toc
    tocNewLi.classList.add("toc-element");
    tocNewLi.classList.add(
      "toc-element-level-" + tocElement.dataset.titleLevel
    );

    // Keep class of title elements
    let classTocElement = tocElement.classList;
    for (var n = 0; n < classTocElement.length; n++) {
      if (classTocElement[n] != "title-element") {
        tocNewLi.classList.add(classTocElement[n]);
      }
    }

    // Create the element
    tocNewLi.innerHTML =
      '<a href="#' + tocElement.id + '">' + tocElement.innerHTML + "</a>";
    tocUl.appendChild(tocNewLi);
  }
}

class handlers extends Paged.Handler {
    constructor(chunker, polisher, caller) {
      super(chunker, polisher, caller);
    }

    beforeParsed(content) {
      createToc({
        content: content,
        tocElement: "#my-toc-content",
        titleElements: ["h2", "h3"],
      });
    }
  }
  Paged.registerHandlers(handlers);

</script>
</div>
</div>
</div>
</div>
</body>
</html>

It gives me the page numbers but does not give me the table of content. How can I create the table of content.

receiving [object object] instead of mongodb object id (react, typeScript)

I am trying to disply doucuments to the user, everything is working propertly exept the objectId of the mongodb doucument.
enter image description here
as you can see I can see it as [object object] instead of the actual id string.
I found out that I should use JSON.stringfy but that didnt work (it just put “” around the [object object]).
this is the components where I disply the doucuments:

function Show() 
{
    let groups = useLoaderData()
    let updated_groups = groups?.map((cardData: any, index: Key | null | undefined) => (
      <div key={index} className="card">
        <p>Id: {JSON.stringify(String(cardData._doc._id))}</p>
        <p>name: {JSON.stringify(cardData._doc.name)}</p>
        <p>groups: {JSON.stringify(cardData._doc.groups_part)}</p>
        <p>peoples: {JSON.stringify(cardData._doc.peoples_part)}</p>
        <p>parent: {JSON.stringify(cardData._doc.group_parent)}</p>
      </div>
    ))
  return (
    <div>
      {updated_groups}
    </div>
  );
}

this is my loader:

export async function loader()
{
    return groups_controller.controller_group_everyone()
}

controller_group_everyone() just does the mongodb find method and returns the doucuments as an array

I want to disply the mongo objectId as a string in the browser.

every google link I found about this issue says to use json,stringfy.
am I using it wrong or is there any other problem??

(I dont know if this helps but I am recieving this issue as well that is maybe related: “Uncaught Error: Hydration failed because the server rendered HTML didn’t match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:

  • A server/client branch if (typeof window !== 'undefined').
  • Variable input such as Date.now() or Math.random() which changes each time it’s called.
  • Date formatting in a user’s locale which doesn’t match the server.
  • External changing data without sending a snapshot of it along with the HTML.
  • Invalid HTML tag nesting.

It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.”)

Id: {JSON.stringify((cardData._doc._id).toString())}

returns: “[object Object]”

Id: {JSON.stringify((cardData._doc._id))}

return buffer ({“buffer”:{“0″:103,”1″:227,”2″:185,”3″:253,”4″:70,”5″:96,”6″:29,”7″:90,”8″:8,”9″:38,”10″:181,”11”:247}})

Id: {(cardData._doc._id).toString()}

returns: [object Object]

PushState() removes previous entries or creates doubles

Here’s my code:

$.ajax({
    url: link,
    type: 'get',
    data: { },
    success: function (res) {
        document.title = res.title;
        document.description = res.description;

        $('body').html(res.html);
        addToHistoryUrl(res, link);
    }
});

function addToHistoryUrl(res, url){
window.history.pushState({'title' : res.title, 'description' : res.description},"", url);}

Most of the time it works fine but sometimes pushstate() creates a double entries or removes some of them or even edit some entries.

I dont use onpopstate() handler, all navigation (back, forward) works by browser’s solutions.

Modal does not open when clicking the button – Javascript issue

I’m working on a website where I need to display a modal popup when a user clicks a button. However, the modal doesn’t open when the button is clicked. I’m using basic HTML, CSS, and JavaScript to implement the modal. I followed some tutorials online, but it still doesn’t seem to work.

The modal doesn’t open when I click the button (Erfahren Sie mehr über mich).

I’ve followed tutorials and checked the code, but the modal remains hidden.

I’m using basic JavaScript to manipulate the modal’s visibility.

The btn.onclick function should trigger the modal to appear, but it doesn’t seem to work.

What I’ve tried:
I’ve checked the console for errors, but there are none.

I made sure the IDs and classes match between HTML, CSS, and JavaScript.

I’ve also tried modifying the display property in different ways (using block, flex, etc.), but it still doesn’t work.

Any help would be greatly appreciated! I’ve been stuck on this for a while.

Additional Information:
Browser: Chrome (latest version)

I’m not using any frameworks or libraries, just pure HTML, CSS, and JavaScript.

### JavaScript-Code:
// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
### CSS-Code:
.modal {
  display: none; 
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}


<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>In der Not für Sie da - Seniorenhilfe</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <header>
        <div class="container">
            <h1>In der Not für Sie da</h1>
            <nav>
                <ul>
                    <li><a href="#services">Leistungen</a></li>
                    <li><a href="#contact">Kontakt</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <section class="hero">
        <div class="container">
            <div class="hero-content">
                <div class="hero-text">
                    <h2>Arbenita </h2>
                    <p>Liebevolle Seniorenbetreuung mit Herz und Erfahrung</p>
                    <button id="myBtn">Erfahren Sie mehr über mich</button>
              
                    <div id="myModal" class="modal">
                        <div class="modal-content">
                            <span class="close">&times;</span>
                            <p>Mein Name ist Arbenita , ich bin 39 Jahre alt, Mutter von vier wunderbaren Kindern und seit über 15 Jahren als Pflege- und Haushaltshilfe tätig.</p>
                            <p>Es ist mir eine Herzensangelegenheit, älteren Menschen zu helfen und ihren Alltag durch liebevolle Unterstützung und Fürsorge zu erleichtern. Mit meiner langjährigen Erfahrung in der Branche setze ich mich mit viel Engagement und Empathie dafür ein, den Menschen ein würdevolles und angenehmes Leben zu ermöglichen.</p>
                            <img src="deine-mama.jpg" alt="Foto von Arbenita ">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <footer>
        <p>&copy; 2025 Seniorenhilfe | Alle Rechte vorbehalten</p>
    </footer>

    <script>
        // Get the modal
        var modal = document.getElementById("myModal");

        // Get the button that opens the modal
        var btn = document.getElementById("myBtn");

        // Get the <span> element that closes the modal
        var span = document.getElementsByClassName("close")[0];

        // When the user clicks on the button, open the modal
        btn.onclick = function() {
            modal.style.display = "block";
        }

        // When the user clicks on <span> (x), close the modal
        span.onclick = function() {
            modal.style.display = "none";
        }

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
    </script>
</body>
</html>


EventCalander – Stop overlapping event on load

I’m using this script https://github.com/vkurko/calendar to create an event calendar.
It seems to be working well, but I’m trying to work out how to stop an event being added if will overlap another event.

I’ve created a simple codepen, https://codepen.io/Tom_T/pen/emYjbJm

When you go to Week view there is one existing event. If you click load at the bottom of the page it adds a new event which overlaps the existing one. I want to stop this happening, if there is already an event then don’t add the new one.

The code I’m using to check if there is an existing event is:

newevent = data[i]

    var start = new Date(newevent.start);
    var end = new Date(newevent.end);
    console.log ( 'TEST: ' + start + ' --- ' + end );
    console.log ( ec.getEvents().filter(e => e.start < newevent.end && newevent.start < e.end ) )

If the result of the filter is > 0 then don’t add the event. At the moment it is only returning 0 so the event is added.

Does anyone know how I can filter the existing events to see if there are any clashing/overlapping entries ?

Thanks

Direct download link for Google Drive files on android without opening google drive

On my webpage, I am downloading google drive files via the following approach:

https://drive.google.com/uc?export=download&id=${fileId}

However, this only works on computers. On phones (such as an android), it opens up google drive instead of downloading the file.

On the other hand, if I paste the link on my phone’s browser, it downloads as expected instead of opening google drive.

One solution that seems to work even on phones is by using google drive api:

https://www.googleapis.com/drive/v3/files/FILE_ID?alt=media&key=YOUR_API_KEY

However, the name of the downloaded file is set to the file ID instead of the file name.

I’ve seen an answer which says to use Content-Disposition headers to set the file name, however, I do not have any server-side support, and apparently I will need expressjs to set content headers (Please tell me if I’m wrong) . My webpage has to be client-side only.

So how do I obtain a google drive download link that:

  1. Works everywhere without opening google drive (iPhone/iPads are an exception as they don’t allow downloads)
  2. Lets me keep or set the file name instead of setting the file id as the downloaded file name.

PHP problem getting JSON POST after decrypting initial POST data

I have an Android app that POSTS data to a PHP server via Retrofit. The app uses encryption to send data to server. The encryption and decryption on the server works well.

I am now implementing a multipart POST in Retrofit for images. My tests are giving me an issue getting the JSON data after the decryption of the POST data happens.

Sample of what the message looks like before decrpytion:

{"message":"IPJqXxv3eI1HURLVEup+PXIoZ94vhsxCkvPEx8bhOXTV1iGmf89O...."}

Working example below without multipart data POST on PHP server:

    $data = json_decode(file_get_contents('php://input'));       

    $message = $data->{'message'};

    $json = $myUtils->decryptPost($message);

This is the relevent part of the decryption function:

    function decryptPost($message){

         ....

    $str = mb_convert_encoding($str, "UTF-8");

    $json = json_decode($str, true);

    return $json;
}

When I do the same with the multipart form data, $json is NULL.

What I have tried so far inside the end of the decryptPost function:

        $str = mb_convert_encoding($str, "UTF-8");

        echo $str;

This prints out the right data but I just can’t access it via JSON. The JSON name indicated in the app is labeled as “items”, which it is named properly.

> 2025-03-26 05:26:49.566 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I 
> --1dbcd23c-55d7-46aa-8801-422d2814fd62 2025-03-26 05:26:49.569 22294-22647 okhttp.OkHttpClient     com.itgeek25.syncourlists         
> I  Content-Disposition: form-data; name="items" 2025-03-26
> 05:26:49.570 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I  Content-Transfer-Encoding:
> binary 2025-03-26 05:26:49.571 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I  Content-Type:
> application/json; charset=UTF-8 2025-03-26 05:26:49.571 22294-22647
> okhttp.OkHttpClient     com.itgeek25.syncourlists            I 
> Content-Length: 182 2025-03-26 05:26:49.573 22294-22647
> okhttp.OkHttpClient     com.itgeek25.syncourlists            I  
> 2025-03-26 05:26:49.574 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I 
> {"category":"Books","deleted":[],"items":[{"id":71,"is_marked":1,"item":"Mistake"},{"id":72,"is_marked":1,"item":"Subardf"}],"list_id":147,"sol_id":-10,"title":"Something
> important"} 2025-03-26 05:26:49.574 22294-22647 okhttp.OkHttpClient   
> com.itgeek25.syncourlists            I 
> --1dbcd23c-55d7-46aa-8801-422d2814fd62--

Each approach returns either null or can’t access object in array:

$json = json_encode($str);
$json = json_decode($json, true);
echo $json['items'];
echo $json->{'items'};

How to update and delete records in a table based on a new request?

I need to update records for Guide Steps (Every recipe has steps/instruction and my table was created for storing this data)

I was able to create those records in the db with quite easy syntax:

GuideStep::insert($groupedSteps); // $groupedSteps is an array

But now I need to update those records (and remove unnecessary ones), for this moment I came up with logic that can only update records or create if there is no such records:

foreach ($groupedSteps as $step){
  GuideStep::updateOrInsert(
    ['recipe_id' => $recipeId, 'step_number' => $step['step_number']],
    ['step_text' => $step['step_text'], 'step_image' => $step['step_image']]
  );
}

migration:

Schema::create('guide_steps', function (Blueprint $table) {
            $table->id();
            $table->foreignId('recipe_id')->constrained()->cascadeOnDelete();
            $table->integer('step_number');
            $table->text('step_text');
            $table->string('step_image')->default('recipes-images/default/default_photo.png');
            $table->timestamps();
        });

I thought that I’ll be able to use upsert() but this method requires unique columns (I don’t have those)

Be grateful for some advices

Run Gobgp commnad By Web Interface ( ubuntu server) [closed]

Hi i need php or other web languagues that have box ( ip address ) and two bottom ban or unban

if select ban fetch ip address from box and run shell script

script is gobgp global rib add -a ipv4 $ip/32 community 65000:666

If select unban fetch ip address from box and run this shell script

gobgp global rib del -a ipv4 $ip/32 community 65000:666

Problems with complexity in dependency conditional injection with PHP-DI

I’m working on a PHP project where I’m using PHP-DI for dependency injection, but I’m struggling to configure a hierarchical structure of classes cleanly and scalably. I have interfaces like ParentLoader and ChildLoader, with concrete implementations for different types: XML (e.g., XmlParentLoader, XmlChildLoader) that depend on a DOMDocument, and SQL (e.g., SqlParentLoader, SqlChildLoader) that depend on a PDO. These loaders are hierarchical (ParentLoader depends on ChildLoader), and I need to inject them conditionally based on a configuration (e.g., "type" => "xml" or "type" => "sql" from a settings file) into a service that uses two ParentLoader instances.

Here’s a simplified example of my classes:

interface ParentLoader
{
    public function load(): array; // Just an example
}

interface ChildLoader
{
    public function load(): array; // Just an example
}

class XmlParentLoader implements ParentLoader
{
    public function __construct(private XmlChildLoader $childs, private DOMDocument $source)
    {
    }

    public function load(): array
    {
        // Logic using $source and $childs
        return [];
    }
}

class XmlChildLoader implements ChildLoader
{
    public function __construct(private DOMDocument $source)
    {
    }

    public function load(): array
    {
        // Logic using $source
        return [];
    }
}

class SqlParentLoader implements ParentLoader
{
    public function __construct(private SqlChildLoader $childs, private PDO $source)
    {
    }

    public function load(): array
    {
        // Logic using $source and $childs
        return [];
    }
}

class SqlChildLoader implements ChildLoader
{
    public function __construct(private PDO $source)
    {
    }

    public function load(): array
    {
        // Logic using $source
        return [];
    }
}

class MyService
{
    public function __construct(
        private ParentLoader $model, // Based on "model" from settings
        private ParentLoader $target  // Based on "target" from settings
    ) {
    }

    public function execute(): array
    {
        $dataModel = $this->model->load();
        $dataTarget = $this->target->load();
        // Combine or process data
        return array_merge($dataModel, $dataTarget);
    }
}

I’m using PHP-DI to conditionally inject these dependencies based on a configuration. For example, if the config specifies "model" => ["type" => "xml"], $model should use XmlParentLoader and XmlChildLoader with a DOMDocument; if "target" => ["type" => "sql"], $target should use SqlParentLoader and SqlChildLoader with a PDO. Here’s what I tried in my ContainerBuilder:

use DIContainerBuilder;
use PsrContainerContainerInterface;

$builder = new ContainerBuilder();
$builder->addDefinitions([
    'xml.source' => function () {
        $dom = new DOMDocument();
        $dom->load('some/path.xml'); // Simplified for example
        return $dom;
    },
    'sql.source' => function () {
        return new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); // Simplified
    },
    'parent.model' => function (ContainerInterface $container) {
        $settings = $container->get('settings'); // Assume settings has "model" and "target"
        $type = $settings['model']['type'];
        if ($type === 'xml') {
            return $container->get('xml.parent.loader.model');
        } elseif ($type === 'sql') {
            return $container->get('sql.parent.loader.model');
        }
        throw new Exception('Invalid type in model configuration');
    },
    'parent.target' => function (ContainerInterface $container) {
        $settings = $container->get('settings');
        $type = $settings['target']['type'];
        if ($type === 'xml') {
            return $container->get('xml.parent.loader.target');
        } elseif ($type === 'sql') {
            return $container->get('sql.parent.loader.target');
        }
        throw new Exception('Invalid type in target configuration');
    },
    'xml.parent.loader.model' => DIcreate(XmlParentLoader::class)
        ->constructor(DIget('xml.child.loader.model'), DIget('xml.source')),
    'xml.child.loader.model' => DIcreate(XmlChildLoader::class)
        ->constructor(DIget('xml.source')),
    'sql.parent.loader.model' => DIcreate(SqlParentLoader::class)
        ->constructor(DIget('sql.child.loader.model'), DIget('sql.source')),
    'sql.child.loader.model' => DIcreate(SqlChildLoader::class)
        ->constructor(DIget('sql.source')),
    'xml.parent.loader.target' => DIcreate(XmlParentLoader::class)
        ->constructor(DIget('xml.child.loader.target'), DIget('xml.source')),
    'xml.child.loader.target' => DIcreate(XmlChildLoader::class)
        ->constructor(DIget('xml.source')),
    'sql.parent.loader.target' => DIcreate(SqlParentLoader::class)
        ->constructor(DIget('sql.child.loader.target'), DIget('sql.source')),
    'sql.child.loader.target' => DIcreate(SqlChildLoader::class)
        ->constructor(DIget('sql.source')),
    MyService::class => DIcreate()
        ->constructor(DIget('parent.model'), DIget('parent.target'));
]);

This works, but it’s a mess. I have to manually define every loader in the hierarchy (e.g., xml.parent.loader.model, xml.child.loader.model, etc.) and their dependencies (DOMDocument or PDO) for each source (model and target). It gets worse when the hierarchy grows (e.g., adding a GrandChildLoader). My goal is a solution where I don’t need to manually define every loader and its dependencies in the DI container for each source and type combination, making use of autowire for example, which currently I can’t because of the “conditional injection”. If wasn’t for the “source” parameter, I would be able to use autowire, but I need the source.

Is there a better way to structure this with or without PHP-DI? Maybe a factory pattern or some trick to avoid these repetitive definitions? I’d love to leverage autowiring more, but the specific sources (DOMDocument and PDO) make it tricky. Any ideas would be awesome!

Thanks!

How to save image from front camera with input file type capture camera [closed]

I want to create a web application with a feature to take pictures from the front camera with html tag such as

  • html
<form id="data" method="post" enctype="multipart/form-data">
<input type="file" capture="camera" accept="image/*" class="btn btn-primary" 
       id="takePhoto" name="takePhoto" />
<input type="submit" id="submit" name="submit" class="btn btn-primary" value="Upload!" />
</form>

  • Javascript
       <script>
    
        $(document).ready(function(){
           $("form#data").submit(function(e) {
               e.preventDefault();    
               var formData = new FormData(this);

               $.ajax({
                  url:'https://example.com/proccess.php',
                  crossDomain: true,
                  type: 'POST',
                  data: formData,
                  success: function (data) {
                     alert(data)
                  },
                  cache: false,
                  contentType: false,
                  processData: false
               });
            });
        });
     </script>

  • php

….

            header("Access-Control-Allow-Origin: *");
            header('Access-Control-Allow-Methods: GET, POST, REQUEST');
     
            $folderPath = "uploads/";
        $tdate = date('d_m_Y_h_i_s');       
        $allowed_ext = array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'rar', 'zip', 'jpg', 'jpeg', 'png');
        $file_name = $_FILES["takePhoto"]["name"];
        $file_temp = $_FILES["takePhoto"]["tmp_name"];
        $sourceProperties = getimagesize($file_temp);
             
             $fileNewName = $tdate;
             $ext = pathinfo($_FILES["takePhoto"]["name"], PATHINFO_EXTENSION);
             $getname = explode(".", $file_name);
         
             $ori_file = substr(str_replace(str_split('\/:*#?"<>|&+-;.()'), '_', $getname[0]),0);
             $ori_file = str_replace(" ","_",$ori_file);
         
             $file_name_exp = explode(".", $file_name);
         $file_ext = strtolower(array_pop($file_name_exp));
                = strtolower(end(explode('.', $file_name)));
         $file_size = $_FILES["takePhoto"]['size'];
         
             $file_name_up = $ori_file.'_'.$tdate.'.'.$file_ext;
                                
         if(in_array($file_ext, $allowed_ext) === true){
        
           $local = 'uploads/'.$file_name_up;
         
                  if (move_uploaded_file($file_tmp,$local)) {
                      echo "The file ". basename( $file_name_up) . " has been uploaded.<br>";
          
                        
                      if(rename($local, "/mnt/drive/server/uploads/".basename( $file_name_up))) {
                          echo "File moving operation success<br/>"; 
                       }
                       
                  } else {
                       echo "";
                  }
                            
         }else{
         echo '<div class="error">ERROR: Extentions not available!</div>';
         }              

If using the smartphone’s rear camera, the image can be saved, but if using the front camera, the image cannot be saved perfectly, whether because of the resolution or other things.

Is it possible to edit create an permanent editable textbox in html?

So I am trying to make an announcement website, but the people who actually set the announcements complain that announcements are too tricky to make (I literally give them the html file and they need to find the announcements div, create a new one using a tutorial I give them and then edit the text to their announcement). I understand that, but I literally have no idea how to change it. I went to google and looked it up. I think it has something to do with AJAX and JQuery, but I don’t know how that works. Here is about the website code but then like a sketch (the actual code has more decorations and is too long):

<!DOCTYPE html>
<html>
    <head>
        <style>
            .announcement{
                display: inline-block;
                font-size: 48px;
            }
        </style>
    </head>
    <body>
        <div id = 'announcement'>
            <a href = '/page.html'>
                <h1>Announcement here</h1>
            </a>
            <p>Announcement description</p>
        </div>
    </body>
</html>

Anyway, now there are no announcements until it is fixed and they use discord for now. It would really help if somebody helped me. Also, note that the edit announcement feature is only available with logging in.

Nested scrollable issue on react native

I am developing a book application, which supports both portrait and landscape modes. The pages of the book are svgs which are rendered inside a horizontal @shopify/flash-list. The Page component also has a vertical ScrollView which is enabled only in landscape mode.
The problem is that when in landscape mode I scroll vertically fast the ScrollView seems to be not rendered yet and the FlashList scroll is getting triggered, i.e page swipe instead of staying on the same page and scrolling down. If I wait for 1-2 sec. everything works fine and the indented scrollable is getting triggered