Why can’t I recreate this CryptoJS hashing loop (for AES key derivation) in C?

I am trying to recreate this loop written in JS. From the CryptoJS library, it takes a passphrase and a salt, hashes them 10,000 times (to later derive an AES Key and IV). I believe it is just MD5(passphrase + salt) 10,000 times.

     while (derivedKeyWords.length < keySize) {
                    if (block) {
                        hasher.update(block);
                    }
                    block = hasher.update(password).finalize(salt);
                    hasher.reset();

                    // Iterations
                    for (var i = 1; i < 10000; i++) {
                        block = hasher.finalize(block);
                        hasher.reset();
                    }

                    derivedKey.concat(block);
                }

Simple enough, but when I try to recreate this in C (using OpenSSL’s MD5 function), it gives a different derived key result.

while (sizeof(derivedkey) < keysize) {
    MD5_Init(&ctx5);
    
    if (sizeof(dgest) > 0) {
        MD5_Update(&ctx5, dgest, sizeof(dgest));
    }
    
    MD5_Update(&ctx5, password, sizeof(password));
    MD5_Update(&ctx5, salt, sizeof(salt));
    MD5_Final(dgest, &ctx5);
    
    for (int j = 1; j < 10000; j++) {
            MD5_Init(&ctx5);
            MD5_Update(&ctx5, dgest, sizeof(dgest));
            MD5_Final(dgest, &ctx5);
    }
    strcat(derivedkey, dgest);
    //I've also tried memcpy(derivedkey, dgest, sizeof(dgest));
}

Thanks!

React keeps refreshing my page after a fetch

So i am following an tutorial on an react webapp https://youtu.be/LDB4uaJ87e0?si=8-b0n60EMVbllXxD&t=10012

I am using React 19 and Tailwind 4.0 since i only installed this server on 08-03-2025
until now i got everything working with only some struggles with tailwind 4.0

Made the addJob & deleteJob and now i when i also added the toastify plugin i noticed this will not work when i deleteJob and the problem seems to be in the try to fetch data.

when i commend out this specific code it will work as expected. Normal page navigation will work as expected with or without code commented. No loading favicon then.

Commented code from App.jsx deleteJob

const res = await fetch(`/api/jobs/${id}`, {
      method: "DELETE",
    });

Same goes for addJob:

const res = await fetch("/api/jobs", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(newJob),
    });

when i do not commend this out my whole page will refresh and my console will look like this Console image I stated that it will refresh also by the favicon loading.

This is my App.jsx:

import React from "react";
import {
  Route,
  createBrowserRouter,
  createRoutesFromElements,
  Router,
  RouterProvider,
} from "react-router-dom";
import HomePage from "./pages/HomePage";
import MainLayout from "./layouts/MainLayout";
import JobsPage from "./pages/JobsPage";
import NotFoundPage from "./pages/NotFoundPage";
import JobPage, { jobLoader } from "./pages/JobPage";
import AddJobPage from "./pages/AddJobPage";

const App = () => {
  // Add new Job
  const addJob = async (newJob) => {
    const res = await fetch("/api/jobs", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(newJob),
    });
    return;
  };

  // Delete Job
  const deleteJob = async (id) => {
    const res = await fetch(`/api/jobs/${id}`, {
      method: "DELETE",
    });
    return;
  };

  const router = createBrowserRouter(
    createRoutesFromElements(
      <Route path="/" element={<MainLayout />}>
        <Route index element={<HomePage />} />
        <Route path="/jobs" element={<JobsPage />} />
        <Route path="/add-job" element={<AddJobPage addJobSubmit={addJob} />} />
        <Route
          path="/jobs/:id"
          element={<JobPage deleteJob={ deleteJob } />}
          loader={jobLoader}
        />
        <Route path="*" element={<NotFoundPage />} />
      </Route>
    )
  );
  return <RouterProvider router={router} />;
};

export default App;

JobPage:

import React from "react";
import { useParams, useLoaderData, useNavigate } from "react-router-dom";
import { FaArrowLeft, FaMapMarker } from "react-icons/fa";
import { Link } from "react-router-dom";
import { toast } from "react-toastify";

const JobPage = ({ deleteJob }) => {
  const navigate = useNavigate();
  const { id } = useParams();
  const job = useLoaderData();

  const onDeleteClick = (jobId) => {
    const confirm = window.confirm("Are you sure want to delete this job?");
    if (!confirm) return;

    deleteJob(jobId);
    toast.success("Job deleted!");
    navigate("/jobs");
  };

  return (
    <>
      <section>
        <div className="container m-auto py-6 px-6">
          <Link
            to="/jobs"
            className="text-indigo-500 hover:text-indigo-600 flex items-center"
          >
            <FaArrowLeft className="mr-2" /> Back to Job Listings
          </Link>
        </div>
      </section>

      <section className="bg-indigo-50">
        <div className="container m-auto py-10 px-6">
          <div className="grid grid-cols-1 md:grid-cols-[70%_30%] w-full gap-6">
            <main>
              <div className="bg-white p-6 rounded-lg shadow-md text-center md:text-left">
                <div className="text-gray-500 mb-4">{job.type}</div>
                <h1 className="text-3xl font-bold mb-4">{job.title}</h1>
                <div className="text-gray-500 mb-4 flex align-middle justify-center md:justify-start">
                  <FaMapMarker className="mr-1 text-orange-700" />
                  <p className="text-orange-700">{job.location}</p>
                </div>
              </div>

              <div className="bg-white p-6 rounded-lg shadow-md mt-6">
                <h3 className="text-indigo-800 text-lg font-bold mb-6">
                  Job Description
                </h3>

                <p className="mb-4">{job.description}</p>

                <h3 className="text-indigo-800 text-lg font-bold mb-2">
                  Salary
                </h3>

                <p className="mb-4">{job.salary} / Year</p>
              </div>
            </main>

            {/* <!-- Sidebar --> */}
            <aside>
              {/* <!-- Company Info --> */}
              <div className="bg-white p-6 rounded-lg shadow-md">
                <h3 className="text-xl font-bold mb-6">Company Info</h3>

                <h2 className="text-2xl">{job.company.name}</h2>

                <p className="my-2">{job.company.description}</p>

                <hr className="my-4" />

                <h3 className="text-xl">Contact Email:</h3>

                <p className="my-2 bg-indigo-100 p-2 font-bold">
                  {job.company.contactEmail}
                </p>

                <h3 className="text-xl">Contact Phone:</h3>

                <p className="my-2 bg-indigo-100 p-2 font-bold">
                  {job.company.contactPhone}
                </p>
              </div>

              {/* <!-- Manage --> */}
              <div className="bg-white p-6 rounded-lg shadow-md mt-6">
                <h3 className="text-xl font-bold mb-6">Manage Job</h3>
                <Link
                  to={`/jobs/edit/${id}`}
                  className="bg-indigo-500 hover:bg-indigo-600 text-white text-center font-bold py-2 px-4 rounded-full w-full focus:outline-none focus:shadow-outline mt-4 block"
                >
                  Edit Job
                </Link>
                <button
                  onClick={() => onDeleteClick(job.id)}
                  className="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded-full w-full focus:outline-none focus:shadow-outline mt-4 block"
                >
                  Delete Job
                </button>
              </div>
            </aside>
          </div>
        </div>
      </section>
    </>
  );
};

const jobLoader = async ({ params }) => {
  const res = await fetch(`/api/jobs/${params.id}`);
  const data = await res.json();
  return data;
};

export { JobPage as default, jobLoader };

I pressed delete button on JobPage.jsx and was expected to go to /jobs with an toast.succes notify in right top of my screen. I have searched over 3 hours now without succes. ChatGPT also dont know and keeps telling me my errors come from the form…

Trying to build azure speech program that can transcribe and diarize audio real-time, how do I do this on javascript/html? Can’t find working examples

I specifically am trying to build an application that can run an html-javascript file that can recognize the speech input from a microphone, transcribe it, and assign it to a speaker, continuously until I hit stop.

I have a working code that can transcribe from microphone input well enough, but when I tweaked it so the config would diarize, I only saw it transcribe the text without identifying the speaker, even though I had set the config to diarize, as well.

After I tweaked it to diarize, I wrote this:

<!DOCTYPE html>
<html>

<head>
    <title>Speech Sample</title>
    <meta charset="utf-8" />
    <script type="text/javascript" src="./difflib-browser.js"></script>
</head>

<body style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:13px;">
    <div id="warning">
        <h1 style="font-weight:500;">Speech Recognition Speech SDK not found
            (microsoft.cognitiveservices.speech.sdk.bundle.js missing).</h1>
    </div>
    <div id="content" style="display:none">
        <table>
            <tr>
                <td></td>
                <td>
                    <h2 style="font-weight:500;">Microsoft Cognitive Services Speech SDK</h2>
                    <h3 style="font-weight:500;">Javascript Browser Sample</h3>
                </td>
            </tr>
            <tr>
                <td align="right"><a href="https://www.microsoft.com/cognitive-services/sign-up"
                        target="_blank">Subscription</a>:</td>
                <td><input id="key" type="text" size="60" placeholder="required: speech subscription key"></td>
            </tr>
            <tr>
                <td align="right">Region:</td>
                <td align="left">
                    <select id="regionOptions">
                        <option value="westus" selected="selected">West US</option>
                        <option value="westus2">West US 2</option>
                        <option value="eastus">East US</option>
                        <option value="eastus2">East US 2</option>
                        <option value="eastasia">East Asia</option>
                        <option value="southeastasia">South East Asia</option>
                        <option value="centralindia">Central India</option>
                        <option value="northeurope">North Europe</option>
                        <option value="westeurope">West Europe</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td align="right">Recognition language:</td>
                <td align="left">
                    <select id="languageOptions">
                        <option value="en-US" selected="selected">English - US</option>
                        <!-- Add other languages as desired -->
                    </select>
                </td>
            </tr>
            <tr>
                <td align="right"><b></b></td>
                <td>
                    <button id="scenarioStartButton">Start</button>
                    <button id="scenarioStopButton" disabled="disabled">Stop</button>
                </td>
            </tr>
            <tr>
                <td align="right">Results:</td>
                <td align="left">
                    <textarea id="phraseDiv" style="display: inline-block;width:500px;height:200px"></textarea>
                </td>
            </tr>
            <tr>
                <td align="right">Events:</td>
                <td align="left">
                    <textarea id="statusDiv"
                        style="display: inline-block;width:500px;height:200px;overflow: scroll;white-space: nowrap;">
                    </textarea>
                </td>
            </tr>
        </table>
    </div>

    <!-- Speech SDK REFERENCE -->
    <script src="https://aka.ms/csspeech/jsbrowserpackageraw"></script>

    <!-- Speech SDK presence check -->
    <script>
        function Initialize(onComplete) {
            if (!!window.SpeechSDK) {
                document.getElementById('content').style.display = 'block';
                document.getElementById('warning').style.display = 'none';
                onComplete(window.SpeechSDK);
            }
        }
    </script>

    <script>
        var SpeechSDK;
        var phraseDiv, statusDiv;
        var key, authorizationToken;
        var regionOptions;
        var recognizer;
        
        document.addEventListener("DOMContentLoaded", function () {
            scenarioStartButton = document.getElementById('scenarioStartButton');
            scenarioStopButton = document.getElementById('scenarioStopButton');
            phraseDiv = document.getElementById("phraseDiv");
            statusDiv = document.getElementById("statusDiv");
            key = document.getElementById("key");
            regionOptions = document.getElementById("regionOptions");

            scenarioStartButton.addEventListener("click", function () {
                doContinuousRecognition();
            });

            scenarioStopButton.addEventListener("click", function() {
                if (recognizer) {
                    recognizer.stopContinuousRecognitionAsync();
                }
            });
        });

        function getAudioConfig() {
            return SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
        }

        function getSpeechConfig() {
            var speechConfig = SpeechSDK.SpeechConfig.fromSubscription(key.value, regionOptions.value);
            speechConfig.setProperty(SpeechSDK.PropertyId.SpeechServiceConnection_EnableSpeakerDiarization, "true"); // Enable speaker diarization
            console.log("Speaker diarization enabled."); // Log confirmation
            return speechConfig;
        }

        function onRecognized(sender, recognitionEventArgs) {
            var result = recognitionEventArgs.result;
            console.log(result); // Log the entire result for debugging
            phraseDiv.scrollTop = phraseDiv.scrollHeight;
        
            var speakerId = result.speakerId ? ` [Speaker ID: ${result.speakerId}]` : '';
        
            statusDiv.innerHTML += `(recognized) Reason: ${SpeechSDK.ResultReason[result.reason]}`;
            phraseDiv.innerHTML += `${result.text}${speakerId}rn`;
        }

        function doContinuousRecognition() {
            var audioConfig = getAudioConfig();
            var speechConfig = getSpeechConfig();
            if (!audioConfig || !speechConfig) return;

            recognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);
            recognizer.recognized = onRecognized;

            recognizer.startContinuousRecognitionAsync();
        }

        Initialize(async function (speechSdk) {
            SpeechSDK = speechSdk;
        });
    </script>
</body>

</html>

Client side request for monero-wallet-rpc with credentials

I wonder how to create a axios request from client side for monero-wallet-rpc with –rpc-login credentials because all of my tries are failing with response status code 401. Below is my sample command to run my wallet rpc.

monero-wallet-rpc ^
--testnet ^
--wallet-file C:/monero/testnet_wallet ^
--password "Password" ^
--rpc-bind-port 28083 ^
--daemon-address http://localhost:28081 ^
--rpc-login testuser:testpassword ^
--rpc-access-control-origins "*" ^
--tx-notify "C:/Windows/System32/curl.exe -X POST -H "Content-Type: application/json" -d "{\"txid\":\"%s\"}" http://localhost:3000/api/webhook"

Here is my code within my axios.
Method 1 axios: failed with 401

try {
  const response = await axios.post('http://localhost:28083/json_rpc', {
    jsonrpc: '2.0',
    id: '0',
    method: 'make_integrated_address',
  },
  {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    },
    auth: {
      username: 'testuser',
      password: 'testpassword'
    }
  });
  const { integrated_address, payment_id } = response.data.result;
  consolelog(integrated_address, payment_id)
} catch (error) {
  console.log('error:', error);
}

Method 2 axios: failed with 401

try {
  const response = await axios.post('http://localhost:28083/json_rpc', {
    jsonrpc: '2.0',
    id: '0',
    method: 'make_integrated_address',
  },
  {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Authorization': 'Basic ' + Buffer.from('testuser:testpassword').toString('base64')
    }
  });
  const { integrated_address, payment_id } = response.data.result;
  consolelog(integrated_address, payment_id)
} catch (error) {
  console.log('error:', error);
}

Method 3 curl: failed 401

curl -v -u testuser:testpassword 
http://127.0.0.1:28083/json_rpc 
-H "Content-Type: application/json" 
-d '{"jsonrpc":"2.0","id":"0","method":"make_integrated_address","params":{}}'

Method 4 browser: success
So i tried to access it via direct url into browser (http://127.0.0.1:28083/json_rpc), the browser asked me for credentials, after entering the credentials,I got a response. this means i got access but it shows an error because im accessing it without the method and parameters

{
  "error": {
    "code": -32600,
    "message": "Invalid Request"
  },
  "id": 0,
  "jsonrpc": "2.0"
}

Method 4 Run monero RPC without credentials: success
If i run the command disabling the rpc-login, my axios request are working fine.

monero-wallet-rpc ^
--testnet ^
--wallet-file C:/monero/testnet_wallet ^
--password "Password" ^
--rpc-bind-port 28083 ^
--daemon-address http://localhost:28081 ^
--disable-rpc-login ^
--tx-notify "C:/Windows/System32/curl.exe -X POST -H "Content-Type: application/json" -d "{\"txid\":\"%s\"}" http://localhost:3000/api/webhook"

Anyone know why all my method on axios are failing into 401 status code?

useFormContext()’s watch not triggering a re-render

In a const component, I have this watch configured:

const { watch, setValue, control } = useFormContext<QuoteCalculatorValues>();
const fuelCostWatch = watch('fees')?.[fuel_costs]?.[0];
const watchPath = `fees.[fuel_costs][0].`;

‘fees’ is a key/value array, with the following:

export type FormPayableAccessoryFeeDto = {
    quantity: number;
    rate: number;
};

export interface FormPayableAccessoryFeeIndexDto {
    [key: string]: FormPayableAccessoryFeeDto[] | undefined;
}

export type QuoteCalculatorValues = {
    fees: FormPayableAccessoryFeeIndexDto;
};

Here’s an input I configured to be monitored by the watch

<Controller
    name={`fees.[fuel_costs][0].quantity`}
    control={control}
    render={({ field }) => (
        <Input
          field={field}
          defaultValue={0}
          onChange={value => {
            setValue(`fees.[fuel_costs][0].quantity`, value as never);
          }}
        />
      )}
/>

I’m expecting that because I’m watch‘ing values in fee, when I change the value in the input, the component should re-render.

One thing I noticed, is that in onChange, I have to cast value as never, which might indicate a problem I guess ?

I tested this with a more basic structure (ex: if I watch('info') and create an input on info.firstName) and this works.

Is there a problem with the way my form data’s structured ?

Can’t find button using playwright (or puppeteer) for web scraping

There are many similar questions (like this: Scraping Websites With Playwright), yet I did not find and solution to this:

I have this url:
https://www.derstandard.at/search?n=&fd=2025-02-17&td=2025-03-06&s=score&query=apple

Which leads to a page that looks like this.
enter image description here

I’m interested in the number 71 (that is circled in red). I think much of the content is server-rendered or somehow fetched. I first tried Rselenium as I’m more familiar with R. Yet, on my arm mac, I could not connect to the server on localhost…

I now am using playwright with node to somehow get this number. Yet I am still failing. My script looks like this:

const { firefox } = require("playwright");

(async () => {
  // Launch Firefox in headless mode
  const browser = await firefox.launch({ headless: false });
  const page = await browser.newPage();

  // Navigate to the website
  const url =
    "https://www.derstandard.at/search?n=&fd=2025-02-17&td=2025-03-06&s=score&query=ukraine";
  await page.goto(url, { waitUntil: "domcontentloaded" });

  // Check if the button exists before trying to click
  const buttonSelector = ".message-component";
  if (await page.$(buttonSelector)) {
    console.log("Clicking the button...");
    await page.click(buttonSelector);
    await page.waitForTimeout(2000); // Wait a bit for content to update
  } else {
    console.log("Button not found, continuing...");
  }

  // Extract all <h1> elements
  const h1s = await page.evaluate(() =>
    Array.from(document.querySelectorAll("h1")).map((el) => el.innerText.trim())
  );

  console.log("Extracted <h1> elements:", h1s);

  // Close the browser
  await browser.close();
})();

As I am prompted with this site first:
enter image description here

As I have to click the left button first to get to this site…
However, I can’t access this button either:/

If anyone has any idea on how I programatically can get this number, that would be very very much appreciated!:)

selecting a city doesn’t populate the area dropdown in my subarea form in Laravel 11

I have created City, Area, Subarea Crud in Laravel 11.
where city and area are simple are working correctly but the subarea blade in add form
when city is selected then why respected areas to that city is not show in dropdown of area. I check and use ChatGPT solution in my blade ajax script and try almost every solution but the problem not solved. if you need any code part to understand problem then I can provide that but I want a exact solution of my problem.

the laravel blade :


`@extends('layouts.app')
@section('content')
    <div class="main-content app-content">
        <div class="container-fluid">
            <!-- Page Header -->
            <div class="d-md-flex d-block align-items-center justify-content-between my-4 page-header-breadcrumb">
                <h1 class="page-title fw-semibold fs-18 mb-0">{{ isset($subarea) ? 'Edit Sub Area' : 'Add Sub Area' }}</h1>
                <div class="ms-md-1 ms-0">
                    <nav>
                        <ol class="breadcrumb mb-0">
                            <li class="breadcrumb-item">Route Management</li>
                            <li class="breadcrumb-item active" aria-current="page">Subarea</li>
                        </ol>
                    </nav>
                </div>
            </div>
            <!-- Form and List -->
            <div class="container">
                <div class="row">
                    <!-- Add/Edit Form -->
                    <div class="col-xl-6">
                        <div class="card custom-card">
                            <div class="card-body">
                                <form
                                    action="{{ isset($subarea) ? route('subareas.update', $subarea->id) : route('subareas.store') }}"
                                    method="POST">
                                    @csrf
                                    @if (isset($subarea))
                                        @method('PUT')
                                    @endif

                                    <div class="mb-3">
                                        <label for="city-dropdown" class="form-label fs-14 text-dark">City</label>
                                        <select id="city-dropdown" name="city_id"
                                            class="form-control js-example-basic-single">
                                            <option value="">Select a City</option>
                                            @foreach ($cities as $city)
                                                <option value="{{ $city->id }}"
                                                    {{ isset($subarea) && $subarea->city_id == $city->id ? 'selected' : '' }}>
                                                    {{ $city->city_name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="area-dropdown" class="form-label fs-14 text-dark">Area</label>
                                        <select id="area-dropdown" name="area_id" class="form-control js-example-basic-single">
                                            <option value="">Select an Area</option>
                                            @if(isset($subarea))
                                                @foreach($subarea->city->areas as $area)
                                                    <option value="{{ $area->id }}" 
                                                        {{ $subarea->area_id == $area->id ? 'selected' : '' }}>
                                                        {{ $area->area_name }}
                                                    </option>
                                                @endforeach
                                            @endif
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="form-text" class="form-label fs-14 text-dark">Sub Area Name</label>
                                        <input type="text" class="form-control" id="form-text" name="sub_area_name"
                                            value="{{ old('sub_area_name', isset($subarea) ? $subarea->sub_area_name : '') }}"
                                            placeholder="Sub Area Name">
                                    </div>

                                    <button class="btn btn-primary"
                                        type="submit">{{ isset($subarea) ? 'Update' : 'Add' }}</button>
                                </form>
                            </div>
                            <div class="card-footer d-none border-top-0"></div>
                        </div>
                    </div>

                    <!-- Right Side List of Saved Sub Areas -->
                    <div class="col-xl-6">
                        <div class="card custom-card">
                            <div class="card-body">
                                <h5 class="card-title">Saved Sub Areas</h5>
                                <div class="table-responsive">
                                    <table class="table text-nowrap">
                                        <thead>
                                            <tr>
                                                <th scope="col">City</th>
                                                <th scope="col">Area</th>
                                                <th scope="col">Sub Area</th>
                                                <th scope="col">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($subareas as $subarea)
                                                <tr>
                                                    <td>{{ $subarea->city->city_name }}</td>
                                                    <td>{{ $subarea->area->area_name }}</td>
                                                    <td>{{ $subarea->sub_area_name }}</td>
                                                    <td>
                                                        <div class="hstack gap-2 fs-15">
                                                            <a href="{{ route('subareas.edit', $subarea->id) }}"
                                                                class="btn btn-icon btn-sm btn-info-light m-1">
                                                                <i class="ri-edit-line"></i>
                                                            </a>
                                                            <form method="POST"
                                                                action="{{ route('subareas.destroy', $subarea->id) }}">
                                                                @csrf
                                                                @method('DELETE')
                                                                <button type="submit"
                                                                    class="btn btn-icon btn-sm btn-danger-light m-1">
                                                                    <i class="ri-delete-bin-line"></i>
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection



`This is My script to populate areas dropdown after city is selected`
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="../assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        $('.js-example-basic-single').select2();

        // Handle city change
        $('#city-dropdown').on('change', function() {
            var cityId = $(this).val();
            var areaDropdown = $('#area-dropdown');
            
            areaDropdown.empty().append('<option value="">Loading...</option>');
            
            if (cityId) {
                $.ajax({
                    url: "{{ route('get-areas', '') }}/" + cityId,
                    type: 'GET',
                    success: function(data) {
                        areaDropdown.empty()
                            .append('<option value="">Select an Area</option>');
                        $.each(data, function(index, area) {
                            areaDropdown.append(new Option(area.area_name, area.id));
                        });
                        areaDropdown.trigger('change');
                    },
                    error: function(xhr) {
                        console.error('Error:', xhr.responseText);
                        areaDropdown.empty().append('<option value="">Error loading areas</option>');
                    }
                });
            }
        });

        // Trigger initial load if editing
        @if(isset($subarea))
            $('#city-dropdown').trigger('change');
        @endif
    });
</script>

Any help is much appreciated!




I tried ChatGPT But it waste my many time I can't find exact solution ChatGPT says me that check select2 and jquery load before script of ajax. I do this but not solved my problem. Then I try to change ajax query :

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="../assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        $('.js-example-basic-single').select2();

        // Handle city change
        $('#city-dropdown').on('change', function() {
            var cityId = $(this).val();
            var areaDropdown = $('#area-dropdown');
            
            areaDropdown.empty().append('<option value="">Loading...</option>');
            
            if (cityId) {
                $.ajax({
                    url: "{{ route('get-areas', '') }}/" + cityId,
                    type: 'GET',
                    success: function(data) {
                        areaDropdown.empty()
                            .append('<option value="">Select an Area</option>');
                        $.each(data, function(index, area) {
                            areaDropdown.append(new Option(area.area_name, area.id));
                        });
                        areaDropdown.trigger('change');
                    },
                    error: function(xhr) {
                        console.error('Error:', xhr.responseText);
                        areaDropdown.empty().append('<option value="">Error loading areas</option>');
                    }
                });
            }
        });

        // Trigger initial load if editing
        @if(isset($subarea))
            $('#city-dropdown').trigger('change');
        @endif
    });
</script>`

but this not solve my problem.

How do make this script work with firebase and github?

I’m working on a project that involves connecting my script code for a community form to Firebase and GitHub, but I’m running into some issues and could use some guidance. I was told that Firebase was the best free option for global storage, but I couldn’t make it work properly. I have the SDK setup properly but the rest of script I’m not sure.

const usernames = [
    "HappyTiger", "BraveElephant", "GentlePanda", "CuriousDolphin", "KindRabbit"
];

async function assignUsername() {
    let deviceId = localStorage.getItem("deviceId");
    if (!deviceId) {
        deviceId = "device_" + Math.random().toString(36).substr(2, 9);
        localStorage.setItem("deviceId", deviceId);
    }

    const userRef = db.collection("users").doc(deviceId);
    const doc = await userRef.get();

    if (doc.exists) {
        localStorage.setItem("username", doc.data().username);
    } else {
        const newUsername = usernames[Math.floor(Math.random() * usernames.length)];
        await userRef.set({ username: newUsername });
        localStorage.setItem("username", newUsername);
    }
}

async function submitPost() {
    const title = document.getElementById("post-title").value.trim();
    const content = document.getElementById("post-content").value.trim();
    const imageInput = document.getElementById("post-image");
    const username = localStorage.getItem("username") || "AnonymousUser";

    if (!title || !content) return;

    const reader = new FileReader();
    reader.onload = async function(event) {
        await db.collection("posts").add({
            title,
            content,
            image: imageInput.files.length ? event.target.result : "",
            likes: 0,
            username,
            timestamp: firebase.firestore.FieldValue.serverTimestamp()
        });
        loadPosts();
    };

    if (imageInput.files.length) {
        reader.readAsDataURL(imageInput.files[0]);
    } else {
        reader.onload();
    }
}

async function loadPosts() {
    const postsContainer = document.getElementById("posts");
    postsContainer.innerHTML = "";

    const querySnapshot = await db.collection("posts").orderBy("timestamp", "desc").get();
    querySnapshot.forEach((doc) => {
        const post = doc.data();
        const postId = doc.id;
        const currentUsername = localStorage.getItem("username") || "AnonymousUser";
        const isOwner = post.username === currentUsername;
        const isLiked = localStorage.getItem(`liked_${postId}`) === "true";

        const postElement = document.createElement("div");
        postElement.classList.add("forum-post");
        postElement.innerHTML = `
            <h3>${post.title}</h3>
            <p>${post.content}</p>
            <p><strong>Posted by:</strong> ${post.username}</p>
            ${post.image ? `<img src="${post.image}" class="forum-image">` : ''}
            <button onclick="likePost('${postId}')" ${isLiked ? "disabled" : ""}>${post.likes} Likes</button>
            ${isOwner ? `<button onclick="deletePost('${postId}')">Delete</button>` : ""}
        `;

        postsContainer.appendChild(postElement);
    });
}

async function likePost(postId) {
    const postRef = db.collection("posts").doc(postId);

    const doc = await postRef.get();
    if (doc.exists && !localStorage.getItem(`liked_${postId}`)) {
        const currentLikes = doc.data().likes || 0;
        await postRef.update({ likes: currentLikes + 1 });
        localStorage.setItem(`liked_${postId}`, "true");
        loadPosts();
    }
}

async function deletePost(postId) {
    const postRef = db.collection("posts").doc(postId);
    const doc = await postRef.get();
    if (doc.exists && doc.data().username === localStorage.getItem("username")) {
        await postRef.delete();
        loadPosts();
    }
}

document.addEventListener("DOMContentLoaded", async function() {
    await assignUsername();
    loadPosts();
});

Having trouble with a text formatting function

Probably some easy rep points here.

I have this method:

function formatText(input) {
    return input
        .replaceAll(
            /[#[0-9a-fA-F]{3,6}]/g,
            (match) => `<span style="color:${match.slice(1, -1)}">`
        )
        .replaceAll(/[b]/g, '<b>')
        .replaceAll(/[i]/g, '<i>')
        .replaceAll(/[u]/g, '<u>')
        .replaceAll(/[!b]/g, '</b>')
        .replaceAll(/[!i]/g, '</i>')
        .replaceAll(/[!u]/g, '</u>')
        .replaceAll(/[!c]/g, '</span>');
}

It’s intended to be a simple formatting language. However, when I put any text through it (even without formatting) it doesn’t print and raises an error.

Here’s my full code:

<!doctype html>
<html lang="en">

<head>
    <title>ECMAtermOS</title>
    <link rel="stylesheet" href="style.css">
    <script src="jquery.js" defer></script>
    <script src="ecmaterm.js" defer></script>
    <meta charset="utf-8">
</head>

<body>
    <script defer>
        addEventListener("DOMContentLoaded", _ => {
            const term = new ECMAterm();
            term.newTerm('body');
            term.print(['[#0f0]test[!c]']);
            term.print(['test 2']);
    });
    </script>
</body>

</html>
class ECMAterm {
    constructor() {
        this.terminal = /*html*/ `
            <pre><code id="terminal">ECMAtermOS v1.0.0-alpha.1</code></pre>
        `;
    }

    newTerm(containerSel) {
        this.instance = $(containerSel).append(this.terminal);
        this.output = $('#terminal');
    }

    print(args, type = 'text') {
        function formatText(input) {
            return input
                .replaceAll(
                    /[#[0-9a-fA-F]{3,6}]/g,
                    (match) => `<span style="color:${match.slice(1, -1)}">`
                )
                .replaceAll(/[b]/g, '<b>')
                .replaceAll(/[i]/g, '<i>')
                .replaceAll(/[u]/g, '<u>')
                .replaceAll(/[!b]/g, '</b>')
                .replaceAll(/[!i]/g, '</i>')
                .replaceAll(/[!u]/g, '</u>')
                .replaceAll(/[!c]/g, '</span>');
        }

        for (const arg of args) {
            arg = formatText(arg);

            this.output.append(/*html*/ `<div class=${type}>${arg}</div>`);
        }
    }
}

LLMs can’t seem to fix it, which leads me to think it’s a stupid mistake I made somewhere, but I can’t find it.

Here’s how I’m using it:

addEventListener("DOMContentLoaded", _ => {
    const term = new ECMAterm();
    term.newTerm('body');
    term.print(['[#0f0]test[!c]']); // Should return <span style="color:#0f0">test</span>
    term.print(['test 2']); // Should return itself
});

Neither of the strings print.

EDIT:
Note – if I don’t run arg through formatText() it prints as normal

Playing MP3 Stream in Javascript

I have a POST endpoint that returns an MP3 stream, and I want to play it in JavaScript using the native browser fetch API. The goal is to implement a cross-browser solution, but so far, nothing works in Firefox. Since I need to use a POST endpoint, using new Audio(url) isn’t an option. To make this easier to reproduce, I will use a GET endpoint for a random radio station that streams MP3, but the issue remains the same.

What I’ve tried:

  1. Using MediaSource
const playMP3Stream = async () => {
  const audio = new Audio();
  const mediaSource = new MediaSource();
  audio.src = URL.createObjectURL(mediaSource);

  mediaSource.onsourceopen = async () => {
    const sourceBuffer = mediaSource.addSourceBuffer("audio/mpeg");

    const response = await fetch("http://sc6.radiocaroline.net:8040/mp3");

    if (!response.ok) {
      return;
    }

    const reader = response.body?.getReader();

    if (!reader) return;

    while (mediaSource.readyState === "open") {
      const { value, done } = await reader.read();

      if (done) {
        mediaSource.endOfStream();
        break;
      }
      sourceBuffer.appendBuffer(value);
    }
  };

  await audio.play();
};
  1. Using AudioContext
const playMP3Stream = async () => {
  const audioContext = new (window.AudioContext || window.webkitAudioContext)();

  const response = await fetch('http://sc6.radiocaroline.net:8040/mp3');
  const reader = response.body.getReader();

  let streamBuffer = new Uint8Array();
  let startTime = audioContext.currentTime;

  async function processChunk() {
    const { done, value } = await reader.read();

    if (done) {
      return;
    }

    try {
      const newBuffer = new Uint8Array(streamBuffer.length + value.length);
      newBuffer.set(streamBuffer);
      newBuffer.set(value, streamBuffer.length);
      streamBuffer = newBuffer;

      if (streamBuffer.length > 10000) {
        const audioBuffer = await audioContext.decodeAudioData(
          streamBuffer.buffer,
        );
        const source = audioContext.createBufferSource();
        source.buffer = audioBuffer;
        source.connect(audioContext.destination);
        source.start(startTime);
        startTime += audioBuffer.duration;

        streamBuffer = new Uint8Array();
      }
    } catch (error) {
      console.error('Error decoding audio chunk:', error);
    }

    processChunk();
  }

  processChunk();
}

MediaSource works well in Chromium browsers, but unfortunately, the "audio/mpeg" MIME type is not supported in Firefox. The AudioContext approach works to some extent, but there are gaps between chunks, and it still only functions in Chromium browsers. I’m not sure if this is particularly difficult, or if I’m just struggling with the implementation, but I can’t figure out how to play an MP3 audio stream in Firefox.

I would greatly appreciate any help, whether it’s a working example of gapless MP3 streaming in Firefox or anything else that could help me make this work.

Thanks in advance!

Custom vue component library fails to resolve vuetify components when installed

I’m making a component library for vue.js components that I’ve created that I’d like to reuse. It’s my first time making a library. I’ve run the library locally and “installed” it locally in another project using ‘npm link’ successfully. But when I actually download the published package it can’t seem to resolve the vuetify components that I’ve used to create my first component. I get the following error:

[Vue warn]: Failed to resolve component: v-autocomplete
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. 
  at <EmployeeAutocomplete> 
  at <Tester> 
  at <About onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <VMain> 
  at <VLayout> 
  at <Default onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <VApp> 
  at <App>

The component library can be found here
I’m using a default vuetify project to test it. That’s here

I will try to publish the package itself to my npm this evening, I think I’m blocked at work.

How to Embed a Sketchfab 3D Model in a React JSX Hero Section with Proper Sizing?

I’m trying to embed a Sketchfab 3D model in my React JSX hero section, but every time I do, the model appears extremely small—like a single pixel.
However, the model remains tiny. How can I properly size and scale the 3D model inside my hero section so it fits well and is fully visible?
https://sketchfab.com/3d-models/traveler-f86f5f2a779d496c95c9aca8ba13246f#comments
im trying to use that exact model directed by the link. Other models appear fine but not this.

Any help is appreciated!

import React, { Suspense, useRef, useEffect, useState } from "react";
import { Canvas, useFrame, useLoader, useThree } from "@react-three/fiber";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls, Environment, Html, useGLTF } from "@react-three/drei";
import { Box3, Vector3 } from "three";
import * as THREE from 'three';

// Model component that loads and animates the 3D model
function Model() {
  const gltf = useLoader(GLTFLoader, "/traveler.glb");
  const modelRef = useRef();
  const mixer = useRef();
  const { camera } = useThree();

  useEffect(() => {
    if (!gltf || !modelRef.current) return;

    // Setup animation mixer
    if (gltf.animations.length) {
      mixer.current = new THREE.AnimationMixer(gltf.scene);
      gltf.animations.forEach((clip) => {
        mixer.current.clipAction(clip).play();
      });
    }

    // Auto-scale and center model
    const box = new THREE.Box3().setFromObject(modelRef.current);
    const center = box.getCenter(new THREE.Vector3());
    const size = box.getSize(new THREE.Vector3());

    const maxDim = Math.max(size.x, size.y, size.z);
    const fov = camera.fov * (Math.PI / 180);
    const distance = Math.abs(maxDim / Math.sin(fov / 2));

    camera.position.set(center.x, center.y, distance * 1.5);
    camera.lookAt(center);

    const scaleFactor = 2 / maxDim;
    modelRef.current.scale.setScalar(scaleFactor);
    modelRef.current.position.set(-center.x, -center.y, -center.z);
  }, [gltf]);

  useFrame((_, delta) => {
    if (mixer.current) mixer.current.update(delta);
  });

  return <primitive ref={modelRef} object={gltf.scene} />;
}

// Loader component for displaying during model loading
function Loader() {
  return (
    <Html center>
      <div style={{ color: "white", display: "flex", flexDirection: "column", alignItems: "center" }}>
        <div className="loader"></div>
        <p>Loading 3D model...</p>
      </div>
    </Html>
  );
}

// Main component
const HeroModel3D = () => {
  return (
    <div className="hero-model-3d">
      <Canvas
        camera={{ position: [0, 0, 10], fov: 50 }}
        style={{ background: "transparent" }}
      >
        <ambientLight intensity={0.8} />
        <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} intensity={1} castShadow />
        <Suspense fallback={<Loader />}>
          <Model />
          <Environment preset="city" />
          <OrbitControls 
            enableZoom={true}
            enablePan={true}
            rotateSpeed={0.5}
            autoRotate={false}
          />
        </Suspense>
      </Canvas>
    </div>
  );
};

export default HeroModel3D;

this is my inspo
This is my inspo

Intersection observer aggressively batching entries in safari IOS

In the following (pretty basic) implementation of intersection observer, I’m noticing that IOS safari is batching the entries very aggressively in a single callback: if I scroll through the six items my observer is watching very quickly, the callback only fires once with six entries, whereas on desktop the callback fires six times, once for each target.

Is this just a safari problem, or is there something I’m doing wrong in my code which could be contributing to this?

Minimum reproducible example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        window.addEventListener('load',function(){
            let steps=[...document.querySelectorAll('.step')];

            const observerOptions = {
                threshold: [0,1],
                rootMargin: `0px 0px 0px 0px`,
                root: document
            };

            let observer = new IntersectionObserver((entries) => {
                console.log('callback-------------------------')
                console.log('batched entries:',entries.length)
                let active=null;
                for (let entry of entries) {
                    if(entry.intersectionRatio==1){
                        active=entry.target;
                    }
                }
                console.log('detected fully in view:',active);
                if(active){
                    for(let step of steps){
                        step.classList.toggle('active',active==step);
                    }
                }

            }, observerOptions);

            for(let step of steps) observer.observe(step);
        })
    </script>
    <style>
        .step-outer{
            height:60svh;
            width:100%;
            position:relative;
        }

        .step{
            position:absolute;
            top:0;
            left:0;
            height:100%;
            width:100%;
            box-sizing:border-box;
            border-bottom:1px solid red;
            transition:background-color 0.3s;
        }

        .step.active{
            background-color: coral;
        }

        .outer{
            margin-top:100px;
            margin-bottom:100px;
        }
    </style>
  </head>
  <body>
    <div class="outer">
        <div class="step-outer"><div class="step"></div></div>
        <div class="step-outer"><div class="step"></div></div>
        <div class="step-outer"><div class="step"></div></div>
        <div class="step-outer"><div class="step"></div></div>
        <div class="step-outer"><div class="step"></div></div>
        <div class="step-outer"><div class="step"></div></div>
    </div>
    
  </body>
</html>

How to implement a Dropzone for folders in a React/Electron app and process the folder contents?

Is there a way in electron based apps to let a user drop a folder onto a React-component and handle the drop event so that the main process can fully access it and recursively scan the folder’s contents?

My setup so far:

  • the Renderer has a <DropZone> component with onDrop and onDragOver.
  • the drop event fires and i can see event.dataTransfer.files, but the path (webkitRelativePath) for dropped folders is empty also for files.
const folderDropped = async (event: React.DragEvent) => {
  event.preventDefault();

  // If a folder or file has been dragged
  if (event.dataTransfer.files.length > 0) {
    const filePath = event.dataTransfer.files[0].path;
    console.log("Drop event:", event.dataTransfer.files);
    console.log("Dropped file path:", filePath);

    // Call the IPC handler: readDroppedFile
    const result = await window.api.readDroppedFile(filePath, browserWindowId);
    console.log("readDroppedFile result:", result);

     /* Further Process:
       After the api call, the object is checked if its a folder and that it contains files
       of a specific type (for example, only PNG files). Once confirmed, the main process will scan through all the
       files within the folder recursively.
    */
  }
};

Visual Studio Code, which is also built with Electron, can accept dropped files and folders from the Explorer, so it should be possible for my app as well.

Additional details (optional):

  • Electron version: 35
  • React version: 19
  • Windows 11

How to properly simulate electric field lines

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<canvas id="canvas" width="700" height="500"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

function vec3_add(a, b) {
   return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
}

function vec3_sub(a, b) {
   return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
}

function vec3_scale(v, s) {
   return [v[0] * s, v[1] * s, v[2] * s];
}

function vec3_magnitude(v) {
   return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
}

function vec3_normalize(v) {
   const mag = vec3_magnitude(v);
   if (mag === 0) return [0, 0, 0];
   return [v[0] / mag, v[1] / mag, v[2] / mag];
}
const charges = [{
       pos: [250, 250, 0],
       id: "negative"
   },
   {
       pos: [450, 250, 0],
       id: "positive"
   }
];
const lines = 16;
const step_size = 4;
const max_steps = 1000;

function calculate_field_at_point(point, charges) {
   let field = [0, 0, 0];
   for (let charge of charges) {
       let dir = vec3_sub(charge.pos, point);
       let dist = vec3_magnitude(dir);
       if (dist < 5) continue;
       let strength = charge.id.includes("negative") ? 1 : -1;
       strength /= (dist * dist);
       field = vec3_add(field, vec3_scale(dir, strength));
   }
   return vec3_normalize(field);
}

function rk4_step(point, charges) {
   let k1 = calculate_field_at_point(point, charges);
   let temp = vec3_add(point, vec3_scale(k1, step_size * 0.5));
   let k2 = calculate_field_at_point(temp, charges);
   temp = vec3_add(point, vec3_scale(k2, step_size * 0.5));
   let k3 = calculate_field_at_point(temp, charges);
   temp = vec3_add(point, vec3_scale(k3, step_size));
   let k4 = calculate_field_at_point(temp, charges);
   return vec3_scale(
       vec3_add(
           vec3_add(
               vec3_scale(k1, 1 / 6),
               vec3_scale(k2, 1 / 3)
           ),
           vec3_add(
               vec3_scale(k3, 1 / 3),
               vec3_scale(k4, 1 / 6)
           )
       ),
       step_size
   );
}

function generate_circle_points(center, radius, num_points) {
   let points = [];
   for (let i = 0; i < num_points; i++) {
       let angle = (i / num_points) * Math.PI * 2.0;
       let x = center[0] + radius * Math.cos(angle);
       let y = center[1] + radius * Math.sin(angle);
       points.push([x, y, 0]);
   }
   return points;
}

function integrate_field_line(start_point, charges) {
   let points = [start_point];
   let current_point = [...start_point];
   for (let i = 0; i < max_steps; i++) {
       let step = rk4_step(current_point, charges);
       if (vec3_magnitude(step) < 0.1) break;
       current_point = vec3_add(current_point, step);
       points.push([...current_point]);
       let too_close = charges.some(charge => vec3_magnitude(vec3_sub(current_point, charge.pos)) < 15);
       if (too_close) break;
       if (current_point[0] < 0 || current_point[0] > canvas.width ||
           current_point[1] < 0 || current_point[1] > canvas.height) break;
   }
   return points;
}
const positive_charges = charges.filter(c => c.id.includes("positive"));
for (let charge of positive_charges) {
   let start_points = generate_circle_points(charge.pos, 35, lines);
   for (let start_point of start_points) {
       let points = integrate_field_line(start_point, charges);
       if (points.length > 5) {
           ctx.beginPath();
           ctx.moveTo(points[0][0], points[0][1]);
           for (let i = 1; i < points.length; i++) {
               ctx.lineTo(points[i][0], points[i][1]);
           }
           ctx.strokeStyle = "rgba(0, 0, 0, 0.5)";
           ctx.lineWidth = 2;
           ctx.stroke();
       }
   }
}
ctx.beginPath();
ctx.arc(charges[0].pos[0], charges[0].pos[1], 30, 0, Math.PI * 2);
ctx.fillStyle = "blue";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = "black";
ctx.stroke();
ctx.beginPath();
ctx.moveTo(charges[0].pos[0] - 15, charges[0].pos[1]);
ctx.lineTo(charges[0].pos[0] + 15, charges[0].pos[1]);
ctx.lineWidth = 5;
ctx.strokeStyle = "black";
ctx.stroke();
ctx.beginPath();
ctx.arc(charges[1].pos[0], charges[1].pos[1], 30, 0, Math.PI * 2);
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = "black";
ctx.stroke();
ctx.beginPath();
ctx.moveTo(charges[1].pos[0] - 15, charges[1].pos[1]);
ctx.lineTo(charges[1].pos[0] + 15, charges[1].pos[1]);
ctx.moveTo(charges[1].pos[0], charges[1].pos[1] - 15);
ctx.lineTo(charges[1].pos[0], charges[1].pos[1] + 15);
ctx.lineWidth = 5;
ctx.strokeStyle = "black";
ctx.stroke();
</script>
</body>
</html>

I am trying to simulate an electric field between two charged particles.
To do I sample points around the positive charge, take a series of small steps and approximate the direction of the electric field each time using Runge–Kutta.

However in my snippet the field lines cannot reach behind the negative charge on the left.

I tried generating lines from negative to positive charges but lines start colliding and it looks ugly.

Basically this is what I have:
enter image description here

And what I want:
enter image description here