How do I update a d3 projection to match zoom tranform?

This is my zoom handler for my map:

const zoom = d3.zoom()
    .scaleExtent([1,25])
    .translateExtent([[width * -0.5, height * -0.5], [width * 1.5,height*1.5]])
    .on('zoom', (ev) => {
       svg.selectAll('path').attr('transform', ev.transform);  
    })

It updates the paths in the svg using the transform params from the event. This works great, but if I use projection(point) or similar methods to return the x,y coordinates of a point, then they will be incorrect.

I realise I need to update my projection to update the zoom/pan behaviour.

If I record the original map translation before any zooming, const origTrans = projection.translate(); and then apply the x,y transforms then I am able to correctly sync the projection for the top zoom level (ie k=1).

.on("end", (ev)=> {
  projection.translate([origTrans[0] + ev.transform.x * ev.transform.k, origTrans[1] + ev.transform.y * ev.transform.k]);
  const c =  projection([-3.3632, 55]);
  svg.append("circle")
    .attr("cx", c[0])
    .attr("cy", c[1])
    .attr("r", 9)
    .attr("fill", "red");
  }); 

I’m unclear as how zoom level relates to the projection scale. I can’t achieve the same thing

I’ve tried a few things e.g. – projection.scale(ev.transform.k), or projection.scale(projection.scale() * ev.transform.k) – I’m assuming there’s a lot more to it? If it helps I am using geoMercator for the projection.

QR Code:- Adding canvas(qr code surroundings color with white) and some content on image qr code along with it and download it

After downloading qr code expected results not happening

=>the below following code for gr code

var qrcode = new QRCode(document.getElementById("qrcode"), { text: qrcode_text, width: 212, height: 212, colorDark: "#000000", colorLight: "#ffffff", correctLevel: QRCode.CorrectLevel.H });

=> the below following code for canvas

`var downloadButton = document.getElementById('QRCode_download_btn');
downloadButton.addEventListener('click', function () {

    var canvas = document.getElementById('qrcode').querySelector('canvas');
    var anchor = document.createElement('a');
    anchor.href = canvas.toDataURL('image/jpeg');
    anchor.download = fileName +'.jpeg';
    anchor.click();
});`

=>example
qr code height :- 212
qr code width:- 212

canvas height :- 500
canvas width:- 500

=> after user click on download button create canvas(background color = white) and draw qr code with respective values and some content on image

Cordov JS file local resourse not loaded in Android

I want to render data from android cache memory JS file stored in my cordova project so I wrote html code as below

<script src="file:///data/data/com.stifirestop.systems2/files/system_menu_data.js"></script>

JS file code for download

var fileTransfer = new FileTransfer();
    var url = "https://systems.stifirestop.com/api/data/system_menu_data.js";
    var targetPath = cordova.file.dataDirectory + "system_menu_data.js";
    console.log("targetPath menu", targetPath);
    fileTransfer.download(
        url,
        targetPath,
        function (entry) {
            console.log("Download complete: menu " + entry.toURL());
        },
        function (error) {
            console.error("Download error:menu " + error.source + ", " + error.target + ", " + error.code);
        },
        true, // Optional, set to true if you want to overwrite existing files
         
    );

    // Second JS file
    var url2 = "https://files.stifirestop.com/automate/systems_mongo_dump/mongo_dump.js";
    var targetPath2 = cordova.file.dataDirectory + "mongo_dump.js";
    console.log("targetPath2 mongo", targetPath2);
    fileTransfer.download(
        url2,
        targetPath2,
        function (entry) {
            console.log("Download complete: mongo " + entry.toURL());
        },
        function (error) {
            console.error("Download error:menu " + error.source + ", " + error.target + ", " + error.code);
        },
        true, // Optional, set to true if you want to overwrite existing files
    );

File is successfully stored in my android files folder as below

enter image description here

When I run project in android device it give me error like

“Not allowed to load local resource: file:///data/data/com.stifirestop.systems2/files/system_menu_data.js”, source: https://localhost/index.html (0)

“Not allowed to load local resource: file:///data/data/com.stifirestop.systems2/files/mongo_dump.js”, source: https://localhost/index.html (0)

Any idea how I can solve this ?

How to correctly download pdf and docx file in React JS?

I am trying to download docx or pdf file in React JS(depending on server response) when I get the response from the server. Backend is implemented in Python/Flask.

When I try to download the file, it downloads but damaged and corrupted.

React JS

function downloadDocument(downloadLink, downloadType) {
 const documentBlob = new Blob([downloadLink], { type: downloadType });
 const url = window.URL.createObjectURL(documentBlob);
 const anchor = document.createElement('a');
 anchor.href = url;
 anchor.download = document_title;
 document.body.appendChild(anchor);
 anchor.click();
 document.body.removeChild(anchor);
 window.URL.revokeObjectURL(url) ;
}

Backend Python/Flask

@app.route('/download_document_docx/<request_document_id>', methods=['GET'])
@token_required
def download_document_docx(current_user, request_document_id):
    '''
    Docx document preparation code
    '''
    return send_file(docx_file_path, as_attachment=True, mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document")

Ionic react datetime showing hours 2 hours in the past

I am new to Ionic React. I am trying to make a calendar app in which I can add/edit/delete Tasks. I can do all of that, but heres the issue.

When I edit the startDate or endDate the time seems to be 2 hours in the past. So when I create a startDate: 7-4-2024 13:00 and endDate 9-4-2024 23:59 and click edit, the values for startDate 7-4-2024 11:00 and for endDate 9-4-2024 21:59

Anyone have any idea on how to fix this? If anyone knows a better approach to doing this, ANY help is welcome :)!

EventComponentList.tsx:

interface TaskComponentProps {
    task: Task;
    index: number; // Index van de taak
    onDelete: () => void;
}

const TaskComponent: React.FC<TaskComponentProps> = ({task, index, onDelete}) => {
    const [newTask, setNewTask] = useState<Task>({...task}); // State for the new task
    const [editing, setEditing] = useState(false); // New state for editing mode
    const [expandedText, setExpandedText] = useState<string | null>(null); // State for expanded text

    const {
        handleInputChange,
        handleDateChange,
        handleToggleChange,
        handleEditTask,
    } = useTaskForm();

    // useEffect hook to reset newTask when editing mode is turned off
    useEffect(() => {
        if (!editing) {
            setNewTask({...task}); // Reset newTask when editing mode is turned off
        }
    }, [editing, task]);

    const handleEditClick = () => {
        setEditing(true); // Turn on editing mode
    };

    const handleSaveClick = () => {
        handleEditTask(index, newTask); // Save the edited task
        setEditing(false); // Turn off editing mode
    };

    const handleCancelClick = () => {
        setEditing(false); // Turn off editing mode
    };

    const toggleExpand = (textType: string) => {
        setExpandedText(expandedText === textType ? null : textType); // Toggle expanded text
    };

     return (
        <IonCard>
            
                <IonList className={'edit-task-form'}>
                    <IonItem>
                      <IonTextarea
                            label={"Name"}
                            labelPlacement={"floating"}
                            autoGrow={true}
                            name="name"
                            value={newTask.title}
                            onIonChange={(e) => setNewTask({...newTask, title: e.detail.value!})}
                        />
                    </IonItem>

                    {/* rest of the inputs */}

                    <IonItem>
                        <IonLabel>Start Date</IonLabel>
                        <IonDatetimeButton datetime="startDate"></IonDatetimeButton>
                        <IonModal keepContentsMounted={true}>
                            <IonDatetime
                                id="startDate"
                                onIonChange={handleDateChange('startDate')}
                                value={newTask.startDate.toISOString()}
                            >
                            </IonDatetime>
                        </IonModal>
                    </IonItem>
                    <IonItem>
                        <IonLabel>End Date</IonLabel>
                        <IonDatetimeButton datetime={"endDate"}></IonDatetimeButton>
                        <IonModal keepContentsMounted={true}>
                            <IonDatetime
                                id="endDate"
                                onIonChange={handleDateChange('endDate')}
                                value={newTask.endDate.toISOString()}
                            >
                            </IonDatetime>
                        </IonModal>
                    </IonItem>

TaskHelper.tsx:

export function useTaskForm() {

    const handleDateChange = (name: string) => (e: CustomEvent<any>) => {
        const value = new Date(e.detail.value);
        setNewTask(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

Task.tsx:

interface Task {
  title: string;
  description: string;
  startDate: Date;
  endDate: Date;
  openTimeSlot: boolean;
  remindMe: boolean;
  priority: number;
  category: number;
  url: string;
  note: string;
}

export default Task;

things I’ve tried:
1.
value={newTask.startDate ? newTask.startDate.toISOString() : undefined}
display-timezone=”UTC”
2.
value={newTask.startDate ? newTask.startDate.toISOString() : undefined} // Convert Date to string
onIonChange={(e) => setNewTask({…newTask, startDate: new Date(e.detail.value!)})}
3.
value={newTask.startDate.getTime() + 2 * 60 * 60 * 1000).toISOString()}

none of the above seem to work when editing a Task :`(

how to get current URl from Iframe

I have a requirement where i call api to extend the session , it’s a redirect Api which goes to IDP and IDP calls the rest api via iframe and then it calls the component where the iframe resides. If there is any error then we are passing queryParam “hasError” while calling component from backend. With in the component I am not able to look for queryParam . Can somebody please provide the guidance here :

this is my html : 
<iframe id='myIframe' hidden="hidden" (load)="onLoadIframe(iframe)" title="iframe-authn"></iframe>

this is my component : 

@Component({
    selector: "sso-authn",
    templateUrl: "./sso-authn.component.html"
})
export class SSOAuthNComponent implements AfterViewInit {
@Input()
public loadIframe: boolean;

constructor( @Inject('Window') private window: Window, private webhookServerConfigManager: WebhookServerConfigManager,private router: Router, private acRoute: ActivatedRoute) { }

    ngAfterViewInit() {
        if (this.loadIframe) {
            this.iframe = document.getElementById('myIframe');
            this.iframe.src= "http://localhost.com:4200/extend?goto=http://localhost.ukg.com:4200/sso-authn&realm=ok&compReq=ok;
        }
    }

    onLoadIframe(iframe: any) {
        **//tried to get url with this approach but it is returning parent window location href.**
        const iframeUrl = window.location.href;
  
        let queryParam = this.acRoute.snapshot.queryParams || {};
        if (iframeUrl && iframeUrl.indexOf("hasError") >= 0) {
            // Display session timeout page
            window.parent?.window?.postMessage({ "extendSession": false },     this.ServerConfigManager.ssoOrigin);
            // terminate session and redirect to error page
            console.log('error from auth',queryParam);
            window.parent?.window?.postMessage({ "extendSession": false, "error": queryParam }, this.ServerConfigManager.ssoOrigin);
             this.loadIframe = false;
        } else if (iframeUrl && iframeUrl.indexOf("hasSSO") >= 0) {
            console.log('success response');
            window.parent?.window?.postMessage({ "extendSession": true }, this.ServerConfigManager.ssoOrigin);
            this.loadIframe = false;
        }
    }
path to my component is :  {
    path:'sso-authn',
    component:SSOAuthNComponent
  }

# I want to access queryParam hasError from below url :
http://localhost.com:4200/sso-authn?hasSSO=true&realm=ok&hasError=QVVUSENPREVfSU5WQUxJRA%3D%3D


Webpack 5 Error after Successful build! ( Uncaught Runtime Error Inpage.js )

I’m using webpack version 5 with:

The console leading me to inpage.js file that I don’t have it in my source I assume it’s webpack thing (I’m newbie) and the code that cause’s error is:

setConnectionUrl() {
                return Nc(this, null, function*() {
                    const {nodes: C} = yield this.bm.emit(Mu.GET_NODE, Ve.solana);
                    this.provider.connection = D1(C[0].url)
                })
            }

The part that giving error cannot read properties of undefined (reading '0') is D1(C[0].url

Console Error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0')
    at U1.<anonymous> (inpage.js:28930:39845)
    at Generator.next (<anonymous>)
    at ce (inpage.js:28930:37705)

I tried Updating all of the subpackages like loaders, babels, etc. But it was not helpful.
I put my github rep link down here so you can take a look at the source and config file yourself.

Clone: https://github.com/mhmdmsvi24/Front-End-Projects.git

It’s my first project and it’s in early stages and each time I reload this bug appears I can click on the X and the projects works just fine but It’s on my nerve.

I do not have enough reputation to post images please clone the project and check it out!

Split PDF File Using PDF.JS

I’m working on a project where I’m trying to process PDF files using OCR (Optical Character Recognition). I’ve managed to split the PDF into individual pages using PDF.js on the client side, but now I’m stuck on how to upload each page to the backend for OCR processing.

Here’s what I’ve done so far:

Successfully integrated PDF.js into my project to split the PDF into separate pages.
I can access each page as a canvas element and perform some basic processing.
However, I’m struggling with the next steps:

How do I upload each page of the PDF to the backend one by one after splitting it using PDF.js?

Is it possible to use react sigma to visualize graph data from neo4j?

I’m trying to build a web application that loads data from neo4j graph database and visualize it with the ability to control node placement and send query to sort the graph in different ways. I’ve heard of neosigma library that connects neo4j database to sigma js for visualization, but i don’t know if it’s possible to use it with react-sigma, especially since i’m still learning react and javascript along with it.

The farthest i’ve gone is trying react-sigma basic and neosigma library. the former is successful but since it use the example dataset made from randomly generated names, i’m not sure on how it works with a database and the limitations, and the latter i’m not even sure where to start.

MedusaJS does not trigger subscribers. Why?

I wrote a subscriber to send messages when placing an order, but it is not triggered. I removed all the code from my email client and left only the logs, but it still doesn’t work.
event-bus-redis works, new events are created in my redis.

import {
    Logger,
    OrderService,
    SubscriberArgs,
    SubscriberConfig,
} from "@medusajs/medusa";

type OrderPlacedEvent = {
    id: string;
    no_notification: boolean;
};

export default async function orderPlacedHandler({data, eventName, container}: SubscriberArgs<OrderPlacedEvent>) {

    const logger = container.resolve<Logger>("logger")

    console.log("Order placed event received")
    console.log(data)
    console.log(eventName)

    logger.log("Order placed event received")


    const orderService: OrderService = container.resolve('orderService');

    const order = await orderService.retrieve(data.id, {
        relations: ["items", "items.variant", "items.variant.product"],
    });

    // Do something with the order
}

export const config: SubscriberConfig = {
    event: OrderService.Events.PLACED,
    context: {
        subscriberId: "order-place-handler",
    },

};

Call to a member function links() on array error with custom pagination in laravel 10

I’m trying to create a custom pagination in laravel 10, but I’m getting the error code

Call to a member function links() on array

this is my code:

CulinaryController.php

    public function index(Request $request)
    {
        $client = new Client();

        $qs = http_build_query($request->query());
        $qs = $qs ? '?'.$qs : '';
        $url = initURLPath("culinary" . $qs);
        $response = $client->get($url);
        // dd($response->getBody()->getContents());

        $json = json_decode((string)$response->getBody()->getContents(), true);
        
        if ($request->query('dd')) {
            // dd($response->getBody());
            dd($json);
        }

        $view_data = [
            'title' => 'Browse Culinary',
            'data' => $json,
        ];
        return view('culinary.index', $view_data);
    }

Api/V1/CulinaryController.php

    public function index(Request $request)
    {
        $perPage = $request->query('per_page', 8);
        $currentPage = $request->query('page', 1);
        $pageOffset = ($currentPage - 1) * $perPage;

        $result = Culinary::get();

        $data = $result->toArray();

        $resultWithPagination = new LengthAwarePaginator(
            array_slice($data, $pageOffset, $perPage),
            count($data),
            $perPage,
            LengthAwarePaginator::resolveCurrentPage(),
            [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'query' => $request->query(),
            ]
        );

        return $resultWithPagination;
    }

and this is the code that causes the error in the blade view:

{{ $data->links() }}

any help is appreciated.

Why Django does not be deployed easily?

I have been learning Django for a long time, and I always find difficulties in deploying my projects,

I often deploy my projects on AWS, and it takes a lot of money,

also, the other platforms take a lot of fees to make your Django project deployed on their platforms,

After that I decided to move to PHP

here I found a difference,

and the difference is in the amount of time, that you need to deploy your project (which is a lot shorter than Django),

and the amount of fees that you need to pay to the platform to deploy your project on (it is 100%100 cheaper than Django),

and there are a lot of platforms for PHP, while Django there are few platforms to deploy your project on,

and PHP is much easier to deploy, there are platforms that just you take your project and drag it then drop it to them, and this is everything.

my questions are :

1- Why sometimes you have to take a cloud computer service then you have to install python , and everything in python , then you upload the Django project, it is like you are using it on your computer,

2- does Django need a whole computer system, to be deployed on because it does not work on a server directly ?

3- and why PHP is easier ? , is it because it works on a server directly and does not need anything like whole computer system to be deployed on , just it needs a server and that is is ?

4- and what is difference between hosting platforms, and services like cloud computer ?

Too few arguments to function AppJobsOrangeJob::__construct(), 0 passed in

when i run the laravel schedule comman, “php artisan schedule:work “i get this error. am running;
laravel 11
php 8.3


   ArgumentCountError 

  Too few arguments to function AppJobsOrangeJob::__construct(), 0 passed in D:projectspulseroutesconsole.php on line 8 and exactly 1 expected

  at appJobsOrangeJob.php:20
     16▕ {
     17▕     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
     18▕     public $tries = 3;
     19▕     public  $orange;
  ➜  20▕     public function __construct( $orange )
     21▕     {
     22▕         $this->orange=$orange;
     23▕     }
     24▕

  1   routesconsole.php:8
      AppJobsOrangeJob::__construct()
  2   vendorlaravelframeworksrcIlluminateFoundationConsoleKernel.php:499

don’t know why i get that error.

here is my controller from where am dispatching the job

    public function index()
    {
        $oranges = DB::connection('connectpay')
            ->table('oranges')
            ->whereYear('created_at', '=', date('Y'))
            ->where('created_at', '<', Carbon::now()->subMinutes(1)->toDateTimeString())
            ->where('status', '=', 'pending')->get();

        foreach ($oranges as $orange) {
            OrangeJob::dispatch($orange);
        }
    }

my laravel’s job class

<?php

namespace AppJobs;

use AppModelsTest;
use CarbonCarbon;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;
use IlluminateSupportFacadesDB;
use function LaravelPromptstable;

class OrangeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 3;
    public  $orange;
    public function __construct( $orange )
    {
        $this->orange=$orange;
    }

    public function handle():void
    {
    
       $orange= $this->orange;
        //        we check our transactions status
        $this->checkOrangeTransactions($orange);
    }

here is my routes/console file where i want to chedule the job

<?php

use AppJobsOrangeJob;



Schedule::job(new OrangeJob())->everySecond();

thank in advance

MongoError when uploading excel on Laravel platform

I have been having this error on Laravel 11 when I try to upload an Excel document where my database is a MongoDB instance:

Transaction numbers are only allowed on a replica set member or mongos

Steps to reproduce

  1. I installed Laravel 11
composer create-project laravel/laravel
  1. I added Laravel Mongodb composer package
composer require mongodb/laravel-mongodb
  1. I added the Laravel Excel composer package
composer require maatwebsite/excel:^3.1
  1. Added some User Interface to facilitate the upload of the document. I am trying to upload assets into the web platform.

  2. Created an AssetsImport document

php artisan make:import AssetsImport

The part that’s producing the error is on this file,

class AssetsImport implements ToCollection 
{
  public function collection(Collection $collection) 
  {
     foreach ($collection as $key => $row) {
        $asset = Asset::where('asset_no', $row[2])->first();
        if($asset) {
            continue;
        }
        // add the upload code
        ....
     }
  }
}

The above script is meant to check if there’s an existing Asset. If it’s there, then don’t add it (Continue with the foreach loop).

After checking this similar question, I still could not find a solution for this. Is this the correct way of implementing, and if so, how do I go about solving this error. I don’t have control over the database (there’s a Server Admin) so I cannot just add a replica set. Kindly assist.

Redmine – author_id Params Not Working When Creating New Issue Through REST API

I have migrated the Redmine version from 3.4.6 to 5.0.5 and I used to create a Redmine issue via the rest API, After migration author_id param is not working

I used the below code to create an issue

Before migration: It created an issue with dynamic author_id
After migration: It created an issue with the user’s ID that authenticates with the API. (author_id params not working)

<?php

// Redmine API endpoint for issues
$redmineUrl = 'https://live-url/issues.json';

$apiKey = 'XXXXXXXXXXXX';

// Issue data
$issueData = array(
    'issue' => array(
        'project_id' => 'xyz',
        'subject' => 'Issue subject',
        'description' => 'Issue description',
        'tracker_id' => 'bug', // Tracker ID for the type of issue (e.g., bug, feature, task)
        'status_id' => 'New', // Status ID for the initial status of the issue
        'author_id' => '12',
        'watcher_user_ids' => [70,16],   
    )
);

// Set up cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $redmineUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($issueData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'X-Redmine-API-Key: ' . $apiKey
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request
$response = curl_exec($ch);

echo "<pre>";
print_r($response);

// Check for errors
if ($response === false) {
    echo 'Error: ' . curl_error($ch);
} else {
    echo 'Issue created successfully!';
}

// Close cURL
curl_close($ch);