What do the different physics modes in Phaser JS do?

I just started making games with Phaser JS and want to know what other options are there for the default in the physics part of the config and what they do.

physics: {
    default: 'arcade',
    arcade: {
      gravity: { x: 50 },
      enableBody: true,
    }

I searched on the Phaser website but I couldn’t find much information.

Hello guys i have a question about running through a predefined input and merging every second letter into a new word [closed]

this is the question
Given is a word word. Run through the word and merge every second letter into a new word.

this is the code ive compiled so far,

  function strangeWord(word) {
      let len = word.length;
      let i = 0;
      let newWord = word;
      if (i <= len) {
        word % 2 == 0;
        return newWord;
      }
    }

the biggest challenge i face right now is to output the desired letters merged into a new word but i am struggling on figuring out what steps to take next.

ive tried assigning some range but its giving me errors. im not sure if i should be using an range or index, im very new to javascript so sorry if my responses to my issues are a bit confusing, thank you for taking the time to read this and providing insight.

Cannot save api response to prisma

I am trying to save the response from the replicateAI api, but it doesn’t work it makes a prediction, but it doesn’t save it I have tried a lot of stuff including making a separate api endpoint for saving

Here is my code for the api endpoint:

import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import Replicate from "replicate";
import prismadb from "@/lib/prisma";

const replicate = new Replicate({
  auth: process.env.REPLICATE_API_TOKEN!,
});

export const maxDuration = 300;

export async function POST(req: Request) {
  try {
    const { userId } = auth();
    const body = await req.json();
    const { prompt } = body;

    if (!userId) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    if (!prompt) {
      return new NextResponse("Prompt is required", { status: 400 });
    }

    const response = await replicate.run(
      "pnickolas1/sdxl-coloringbook:d2b110483fdce03119b21786d823f10bb3f5a7c49a7429da784c5017df096d33",
      {
        input: {
          prompt: `${prompt}, black and white coloring page, simple`,
          width: 800,
          height: 1600,
          negative_prompt: "complicated, a lot of details, colors",
          scheduler: "K_EULER",
        },
      }
    ) ;

    // Assuming response has imgUrl property
    const imgUrl = response.data.imgUrl[0]

    try {
      await prismadb.coloringSheet.create({
        data: {
          imgUrl: imgUrl,
          prompt: prompt,
          userId: userId,
        },
      });
      console.log("Image URL saved successfully!");
    } catch (error) {
      console.error("Error saving image URL:", error);
      // Handle the error here, potentially retry or log details
    }

    await prismadb.user.update({
      where: {
        userId: userId,
      },
      data: {
        credits: {
          decrement: 1,
        },
      },
    });

    return NextResponse.json({ imgUrl });
  } catch (error) {
    console.error("[VIDEO ERROR]", error);
    return new NextResponse("Internal error", { status: 500 });
  }
}

and the page where I call it:

"use client";
import React from "react";
import { formSchema } from "@/components/sidebar/constants";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form, FormControl, FormField, FormItem } from "@/components/ui/form";
import { Input } from "../ui/input";
import { Button } from "../ui/button";
import { useRouter } from "next/navigation";
import axios from "axios";
import { Comic_Neue } from "next/font/google";
const kavoon = Comic_Neue({ weight: "700", subsets: ["latin"] });
const DashboardForm = () => {
  const router = useRouter();
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      prompt: "",
    },
  });

  const isLoading = form.formState.isSubmitting;

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
      await axios.post("/api/create", {
        prompt: values.prompt,
      });

      form.reset();
    } catch (error) {
      console.log(error);
    } finally {
      router.refresh();
    }
  };

  return (
    <div className=" flex flex-col h-screen bg-white text-black ">
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="  w-full p-4 px-3 md:px-6  h-full flex flex-col gap-4 border-r-black border-t-0 border-solid border-2"
        >
          {" "}
          <h1 className={`text-xl font-semibold ${kavoon.className}`}>
            Create a new coloring sheet
          </h1>
          <FormField
            name="prompt"
            render={({ field }) => (
              <FormItem className="col-span-12 lg:col-span-10">
                <FormControl className="m-0 p-0">
                  <Input
                    className="w-full pl-3"
                    placeholder="A lion driving an F1 car"
                    disabled={isLoading}
                    {...field}
                  />
                </FormControl>
              </FormItem>
            )}
          />
          <p className="w-full break-normal text-gray-500 text-sm ">
            Enter text describing the coloring sheet you want. Example prompts:
            'An astronaut riding a horse', 'A lion driving an F1 car'.
          </p>
          <Button
            className="col-span-12 lg:col-span-2 w-full bg-gradient-to-r from-purple-500  via-blue-600 to-pink-500  bg-300% animate-gradient"
            disabled={isLoading}
          >
            Generate
          </Button>
        </form>
      </Form>
    </div>
  );
};

export default DashboardForm;

It says that response doesn’t have data

Picking offset for pagination that grabs from two sources

I have a page to view notifications. My company created a new system for managing these notifications so now when fetching the notifications from the api we have to pull from two sources.

If the limit is set to 25, it grabs 25 from both sources, sorts them by created_at updates two variables called source_1_offset and source_2_offset with the number of each source that is in the first 25 items of the sorted list. For example if 10 items from source I and 15 items from source 2 are in the first 25 sorted items, source_1_offset = 10 source_2_offset = 15.

This works perfectly when stepping ahead one page at a time. The issue is when the user wants to jump pages i.e. from page 4 to page 8. If the notifications were coming from one source I would just do limit * page_num for the offset. But because it is coming from two sources I have no idea how many will have come from source 1 and how many from source two.

The way I am currently handling this is just by making a guess on the offsets by setting them both to limit (25) * page_num (8). This ensures that no row is shown twice and if they step back or forward they can still see all the elements. The issue here is if they are on page 3 and the date for the last notification on the page is 4/19/24 and they want to jump to 03/19/24 if they jump ahead 2 or more pages i.e. page 5, the offset will again be treated as a guess and be set to 5 * 25. This leads to some situations where you are the dates from the two sources are wildly separated. source 1 might be correctly grabbing notifications from around 03/19/24 but source 2 might be grabbing from 05/01/23, in which case only notifications from source 1 will be displayed even if in reality there are notifications from source 2 in March 2024.

Any suggestions on how to handle guessing the offset? I have considered making more specific predictions based on how many notifications from each source we have seen up until the page jump.

Below is the function that sets the offset on a page forward

 newNotificationsArray.sort((a, b) => {
                let aItem = a[sort.column]
                let bItem = b[sort.column]

                if (a.fields) {
                    aItem = a.fields[sort.column]

                    if (sort.column === 'created_at') {
                        aItem = new Date(aItem * 1000).toISOString()
                    }
                }

                if (b.fields) {
                    bItem = b.fields[sort.column]

                    if (sort.column === 'created_at') {
                        bItem = new Date(bItem * 1000).toISOString()
                    }
                }

                if (aItem < bItem) return sort.order === 'desc' ? 1 : -1
                if (aItem > bItem) return sort.order === 'desc' ? -1 : 1
                return 0
            })

            let notificationsCount = 0
            let eventNotificationsCount = 0

            for (var i = 0; i < self.limit; i++) {
                // only source one has property source
                if (newNotificationsArray[i].hasOwnProperty('source')) {
                    notificationsCount += 1
                }
                else {
                    eventNotificationsCount += 1
                }
            }

            self.notificationsOffset += notificationsCount
            self.eventNotificationsOffset += eventNotificationsCount

            return newNotificationsArray.slice(0, self.limit)

This is offset for page jumps

if (self.pageJump) {
               self.notificationsOffset = page * self.limit
               self.eventNotificationsOffset = page * self.limit
            }

Using express-rate-limit without reloading the entire page

I’m using express-rate-limit to limit the number of connection attempts.

homeController.js

const express = require('express');
const router = express.Router();

//limiter à 5 tentatives de log sur 5 minutes
const limitter = require("express-rate-limit");
const signInlimitter = limitter({ 
    windowMs: 5*60*1000, 
    limit: 1, 
    handler: (req, res, next) => {
        const date = new Date(req.rateLimit.resetTime);
        req.rateLimit.resetTime = date.toLocaleTimeString();
        res.status(429).send(`Trops de tentatives ! Vous pourez réessayer à ${req.rateLimit.resetTime}.`);
    }
});

const homeRegex = /^/(home)?$/;

const homeView = (req, res) => { res.render("home.ejs", { message: "" }); };

router.route(homeRegex).get(homeView).post(signInlimitter, homeView);

module.exports = router;

index.js

...
app.use('/', require('./controllers/homeController')); 
...

So far, not too complicated.
However, when the limit is exceeded, it refreshes the entire page, and only displays the message.

enter image description here
enter image description here

This doesn’t suit me because I would like to display the message in a textbox or an alert() without recalling everything, in the same idea as with a fetch (or ajax).

Thanks !

I have the ejs packages if that helps.

Displaying hidden element in a div moves the whole horizontal grid row down, how to make it only move the element BELOW the opening element move down?

I am practicing HTML, CSS and JavaScript and I encountered a problem while trying to create a container for company services. Every single service div has a button to show more text which “opens” the div down. I noticed that the whole row in a grid moves down.

There should be 3 service divs in a row and then there should be rows as much as there is service divs remaining and the first element in a horizontal row should be on the left side. I tried to make that when the hidden element is displayed, it would ONLY move down the service div below the opened element and not the whole row.
when hidden element is opened

when hidden element is not displayed

Multilevel dropdown in react-bootstrap , nested dropdown in react-bootstrap library

i want to achieve multilevel dropdown in with react-bootstrap or nested dropdown with react-bootstrap. can anyone know how can we achieve multilevel dropdown with react-bootstrap or is there any props which we can use?

i have tried this way but not working

const dropDownMenu = () => {
    <Dropdown>
        <Dropdown.Toggle as="div" role="button">
            <i className="bi bi-three-dots-vertical"></i>
        </Dropdown.Toggle>

        <Dropdown.Menu>
              <Dropdown.Item as="button" onClick={() => {}}>
                   Item 1
              </Dropdown.Item>

              <Dropdown.Item>
                   <Dropdown>
                         <Dropdown.Toggle as="div" role="button">
                              Item 2
                         </Dropdown.Toggle>

                         <Dropdown.Menu>
                               <Dropdown.Item href="#/action-1">Action</Dropdown.Item>
                               <Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
                               <Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
                        </Dropdown.Menu>
                </Dropdown>
           </Dropdown.Item>
      </Dropdown.Menu>
  </Dropdown>
}

i want to open children dropdown when we click on parent dropdown ** Item 2 **

How to stop button onclick event using javascript?

Is there anyone that can assist?

 <div class="select-button">
     <button type="button" class="button-1 select-billing-address-button" onclick="selectBillingAddress@(item.Id)()">@T("Checkout.BillToThisAddress")</button>
     
     <script asp-location="Footer">
         function selectBillingAddress@(item.Id)() {
             if ($('#@Html.IdFor(model => model.ShipToSameAddress)')
                 .is(':checked')) {
                 setLocation(
                     '@Html.Raw(Url.RouteUrl("CheckoutSelectBillingAddress", new {addressId = item.Id, shipToSameAddress = "true"}))');
             } else {
                 setLocation(
                     '@Url.RouteUrl("CheckoutSelectBillingAddress", new {addressId = item.Id})');
             }
         }
     </script>
 </div>

I would like to check a few conditions before making a call, but I am unable to modify the function or button at this time. Could you please provide a solution? I would like to use load new js.
Many thanks in advance.

I’m trying to add some code under the function and override the old one, but nothing is working. I want to use load new js to accomplish this, and I can only do that.

display:none not hiding the empty option in dropdown

I have running Angular 11 application. In the page I have 2 radio buttons and one dropdown. The behavior is that whenever I change the radio button selection, I want to reset dropdown value and show empty value in the dropdown.

Below code is working fine in Chrome. But in IE I can still see empty option in the dropdown. I don’t want to show empty option in the dropdown list.

test.component.html

<form [formGroup]="myForm">
    <select [id]="control.Id" [formControlName]="control.Id" [value]="control.Value">
      <ng-container *ngFor="let item of control.Items">                        
         <option [value]="item.Value">{{item.Key}}</option>
       </ng-container>
       <option hidden disabled value="" style="display:none;"></option>
     </select>
</form>

test.component.ts

this.myForm.controls['City'].valueChanges.subscribe(this.onCityChange.bind(this));

onCityChange()
{
   this.myForm.get['City'].patchValue('');
}

Chart.js Line Graph not displaying data for total Revenue for the past 15 days

I’ve been debugging this some time now and probably 2 hours now. I want to display the line graph of chart.js the revenue for the past 15 days.

I have a function to get the ajax result for the previous days. This is the js script I made.

// Function to fetch revenue data from PHP script
function fetchRevenueData() {
    $.ajax({
        url: '../config/tables/semi_weekly_revenue.php',
        dataType: 'json',
        success: function(data) {
            var revenueValues = labels.map(function(date) {
                return data[date] || 0; 
            });
        
            myLineChart.data.datasets[0].data = revenueValues;
            myLineChart.update();

        },
        error: function(xhr, status, error) {
            console.error('Error fetching revenue data:', error);
        }
    });
}

the line graph:

// Area Chart Example
var ctx = document.getElementById("myAreaChart");
var myLineChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: labels, 
        datasets: [{
            label: "Revenue",
            lineTension: 0.3,
            backgroundColor: "rgba(2,117,216,0.2)",
            borderColor: "rgba(2,117,216,1)",
            pointRadius: 5,
            pointBackgroundColor: "rgba(2,117,216,1)",
            pointBorderColor: "rgba(255,255,255,0.8)",
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(2,117,216,1)",
            pointHitRadius: 50,
            pointBorderWidth: 2,
            data: [],
        }],
    },
    options: {
        scales: {
            xAxes: [{
                time: {
                    unit: 'date'
                },
                gridLines: {
                    display: false
                },
                ticks: {
                    maxTicksLimit: 7
                }
            }],
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 40000,
                    maxTicksLimit: 5
                },
                gridLines: {
                    color: "rgba(0, 0, 0, .125)",
                }
            }],
        },
        legend: {
            display: false
        }
    }
});

//The fetchRevenueData function will update the Linechart upon called.
fetchRevenueData();

my php query script looks like this:

 // Query to fetch total revenue for each of the past 15 days
    $query = "SELECT 
                DATE_FORMAT(sale_date, '%Y-%m-%d') AS date,
                SUM(total_amount) AS total_revenue
              FROM sales
              WHERE sale_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 15 DAY)
              GROUP BY date
              ORDER BY date";

    $stmt = $pdo->query($query);

   // Fetch revenue data and populate the revenueData array
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $revenueData[$row['date']] = $row['total_revenue'];
    }

   // Return revenue data as JSON
   echo json_encode($revenueData);

Did I miss something? I’ve read the documentation about data passing and maybe I miss something. I’m still learning JavaScript now. Thanks!

I expect the result to show the Line Graph similar to the bar graph but it will on semi-weekly Forecast of revenue for the past 15 days.

Engine for Fingerprint matching/Auth-React.js

I am able to read fingerprint from hardware in React.js. However I need help in finding an engine for matching/auth fingerprint of user when they try to login. I have used @digitalpersona/devices to read fingerprint.

I have found an engine in Python but If anyone knows a library for react.js then It will be better.

whenever i hit run in visual studio code it opens another window

it’s been a a couple days of trying but I’m just too new to understand.
the same happens when i hit start debugging.
This is what im running just a very simple code to get started
enter image description here
enter image description here

console.log("-----------");
console.log("Hello world");
console.log("rise and shine!");
console.log("ready for a new day");
console.log("-----------");

i tried redownloading, rebooting, tutorials

Enforce naming convention of useState destructured variables [foo, setFoo]?

When using the useState hook, typically the two destructured array variables take the form: foo and setFoo.

Some examples that deviate from this template are:

const [foo, setfoo] = useState();    
const [foo, updateFoo] = useState();    
const [foo, fooSetter] = useState();    

During code review, I would recommend the above examples be changed to:

const [foo, setFoo] = useState();    

Is there a way of statically checking (ESLint) for this situation?