Zoom into a rectangular part of an image, using translate and scale

I’m trying to highlight a rectangule that is clipped from a background image, and after that I want to highlight that rectangule and keep it in the view port(the clipped part).

I have tried many ways,
I tried clip-path with transform-origin: center, and used some translate and scale to manipulate where the image is,but I can’t seem to figure out how to sdo the zooming in part to show the highlighted rectangule, I would like for it to work as I want

Understanding Arrow Function Behavior with Conditional Operations in JavaScript

I’m learning arrow functions in JavaScript and attempting to conditionally set the value of show to false based on a certain value. While using the ‘&&’ operator for this purpose, I encountered a syntax issue with the following code:

const obCallback = (something) =>
    something.value === 1
    && show = false;

I know it works when I do this:

const obCallback = (something) => {
    if (something.value === 1) {
        show = false;
    }
};

or this:

const obCallback = (something) => something.value === 1 ? show = false : undefined;

Can anyone of you please explain why the first code snippet doesn’t work and the other do? Can we only do function calls but not assignments after “&&” in an arrow function, because the below seems to be working?

const obCallback = (something) =>
    something.value === 1
    && Dance(); //This works

I know this seems like a basic question but I’m seeking a thorough explanation to improve my understanding of using arrow functions in the future.

How to add percentage symbol at end of input value in input filed with yup validation

enter image description here
How to add percentage symbol at end of input value in input filed with yup validation. Here I am using javascript inbuilt method to covert percentage

<FormField
                  control={form.control}
                  name='additionalTax'
                  render={({ field }) => (
                    <FormItem>
                      <FormControl className='relative'>
                        <Input
                          {...field}
                          value={percentageFormat.format(
                            Number(field?.value?.replace('%', '')) / 100,
                          )}
                          className=' py-5 text-start text-lg'
                          disabled={!form.getValues('isIndirectTax')}
                          onChange={(e) => {
                            const val = e.target.value;
                            console.log(val);
                            field.onChange(val);
                          }}
                          onFocus={(e) => {
                            const input = e.target;
                            const value = input.value;
                            const percentIndex = value.indexOf('%');

                            if (percentIndex !== -1) {
                              console.log(percentIndex);

                              // Move the cursor before the '%' symbol
                              input.setSelectionRange(value.length-1, value.length-1);
                            }
                          }}
                        />
                      </FormControl>
                      <FormMessage className='text-sx text-brand inline-flex' />
                    </FormItem>
                  )}
                />

I want to dynamically add the percentage symbol at end of input value while onchange

aspdotnet core with identity logout call from ajax does not log user out

I am trying to use ajax to post from a link to log a user out using the identity pages.

The page model function I’m calling from ajax is in Logout.cshtml.cs (scaffolded and unmodified):

public async Task<IActionResult> OnPost(string returnUrl = null)
{
    await _signInManager.SignOutAsync();
    _logger.LogInformation("User logged out."); //I see this output
    if (returnUrl != null)
    {
        return LocalRedirect(returnUrl); //this line gets executed
    }
    else
    {
        // This needs to be a redirect so that the browser performs a new
        // request and the identity for the user gets updated.
        return RedirectToPage();
    }
}

I post to this with ajax like so:

$('#submitLogout').on("click", function (e) {
        alert("jquery: Clicked Logout!");
        PostLogout();
        alert("out of Ajax and back to link click function.")
        window.location.href = '@Url.Action("Home","Index")'
});

function PostLogout() {
    alert("Ajax POST executing . . . ");
    $.ajax({
        type: "POST",
        url: "/Identity/Account/Logout",
        data: { returnUrl: '@Url.ActionLink("Index", "Home")'},
        headers: {
            RequestVerificationToken: $(
                'input:hidden[name="__RequestVerificationToken"]'
            ).val()
        },
        success: function () {
            alert("success in Ajax");
            return false;
        }
    });
}

I have verified that the page OnPost handler is being called (with a breakpoint and from the logger information in the console), but my user stays logged in. If I return false from the jquery function I end up with the standard logout page and can click here to logout successfully (right outcome but have to click two logout links). My ajax success function never gets called.

my link code looks like this:

<a class="nav-item" id="submitLogout" href="/Identity/Account/Logout">Logout</a>
@Html.AntiForgeryToken()

I can use a form submit button and get the behavior I want, but the button never looks the same as just a link (font size is always a little bit different) thus my current attempt to post from a link. This is the form submit button that works:

<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout"
    asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
    <button type="submit" class="nav-item btn-pgdBanner" style="color: var(--color5)">Logout</button>
</form>

I’m not sure if I can get this to work the way I want, so will end up using the standard post from an inline form to logout, but wonder if there is something fairly simple that I’m just missing?

parsing error unexpected token. Reach – Udemy Course

Pretty simple component with an error that makes no sense to me. I match the supplied code in the video completely not to mention its super basic. I am using visual studio code if that matters.

import React from 'react'

const App = () => {
    return (
        <div>
            Hello world
        </div>
    )
}
export default App;
[eslint] 
src/App.js
  Line 8:2:  Parsing error: Unexpected token (8:2)
ERROR in [eslint] 
src/App.js
  Line 8:2:  Parsing error: Unexpected token (8:2)

webpack compiled with 1 error

How to detect an active child menu from a parent menu?

Creating a single level menu can easily be achieved with a single state holding the active menu:

import React from 'react';

import { Menu } from './Menu';

export const App = () => {
  const [active, setActive] = React.useState<React.ReactNode>(null);
  return (
    <>
      <Menu label="A" active={active} setActive={setActive}>
        <Menu label="A.A" active={active} setActive={setActive} />
        <Menu label="A.B" active={active} setActive={setActive} />
      </Menu>
      <Menu label="B" active={active} setActive={setActive}>
        <Menu label="B.A" active={active} setActive={setActive} />
        <Menu label="B.B" active={active} setActive={setActive} />
      </Menu>
    </>
  );
};
import React from 'react';

type Props = {
  label: string;
  active?: HTMLElement;
  setActive?: (active: HTMLElement) => void;
  children?: React.ReactNode;
};

export const Menu = ({ label, active, setActive, children }: Props) => {
  const ref = React.useRef<HTMLDivElement>(null);
  const onClick = () => setActive?.(children && ref.current);
  return (
    <div ref={ref}>
      <button type="button" onClick={onClick}>
        {label}
      </button>
      {active && active === ref.current && children}
    </div>
  );
};

But creating a multiple level menu is difficult because when a child menu is active its parents also need to be active and I don’t know how to implement that:

import React from 'react';

import { Menu } from './Menu';

export const App = () => {
  const [active, setActive] = React.useState<React.ReactNode>(null);
  return (
    <>
      <Menu label="A" active={active} setActive={setActive}>
        <Menu label="A.A" active={active} setActive={setActive}>
          <Menu label="A.A.A" active={active} setActive={setActive} />
          <Menu label="A.A.B" active={active} setActive={setActive} />
        </Menu>
        <Menu label="A.B" active={active} setActive={setActive}>
          <Menu label="A.B.A" active={active} setActive={setActive} />
          <Menu label="A.B.B" active={active} setActive={setActive} />
        </Menu>
      </Menu>
      <Menu label="B" active={active} setActive={setActive}>
        <Menu label="B.A" active={active} setActive={setActive}>
          <Menu label="B.A.A" active={active} setActive={setActive} />
          <Menu label="B.A.B" active={active} setActive={setActive} />
        </Menu>
        <Menu label="B.B" active={active} setActive={setActive}>
          <Menu label="B.B.A" active={active} setActive={setActive} />
          <Menu label="B.B.B" active={active} setActive={setActive} />
        </Menu>
      </Menu>
    </>
  );
};
import React from 'react';

type Props = {
  label: string;
  active?: HTMLElement;
  setActive?: (active: HTMLElement) => void;
  children?: React.ReactNode;
};

export const Menu = ({ label, active, setActive, children }: Props) => {
  const ref = React.useRef<HTMLDivElement>(null);
  const onClick = () => setActive?.(children && ref.current);
  return (
    <div ref={ref}>
      <button type="button" onClick={onClick}>
        {label}
      </button>
      {active && Array.isArray(children) && children.includes(active) && children}  // DOES NOT WORK!
    </div>
  );
};

children.includes(active) is always false because children is a React.ReactNode whereas active is an HTMLElement. How to cast the types to make the comparison work?

FFMPEG Watermark multiple lines only first vible

I am adding 2 lines of watermarks but only first is visible

ffmpeg()
  .input(tempLocalPath)
  .complexFilter([
    `[0:v]drawtext=text='${watermarkTextLine1}':x=(w-tw)/2:y=(h-460):fontsize=24:[email protected]:fontfile=/Windows/Fonts/arial.ttf`,
    `[0:v]drawtext=text='${watermarkTextLine2}':x=(w-tw)/2:y=(h-200):fontsize=32:fontcolor=red:fontfile=/Windows/Fonts/arial.ttf`,
  ])
  .output(
    path.join(tempLocalDir, video_cid.replace(".mp4", "-") + "watermarked.mp4"),
  )
  .on("end", function () {
    // Send the watermarked video as a response
    res.download(
      path.join(
        tempLocalDir,
        video_cid.replace(".mp4", "-") + "watermarked.mp4",
      ),
      "video.mp4",
      function (downloadError) {
        if (downloadError) {
          console.error("Error during download:", downloadError);
        }

        // Clean up: Delete the temporary local file
        fs.unlink(tempLocalPath, (unlinkError) => {
          if (unlinkError) {
            console.error(
              "Error deleting the temporary video file:",
              unlinkError,
            );
          }
        });
      },
    );
  })
  .inputFormat("mp4")
  .run();

why my Web blazor wasm component/page returns this info: Unhandled exception rendering component: ‘<' is an invalid start of a value

My Web Assembly wasm was running fine without any errors and was deployed successful. i then made a few changes to the code and tried to run it locally, now i am getting this errors, when i run it on my local machine browser(still under development).

System.Net.Http.HttpClient.IGenericService<AccountM>.ClientHandler[101]
      Received HTTP response headers after 699.0999ms - 200
blazor.webassembly.js:1 info: System.Net.Http.HttpClient.IGenericService<AccountM>.LogicalHandler[101]
      End processing HTTP request after 829.7ms - 200
blazor.webassembly.js:1  crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
 ---> System.Text.Json.JsonReaderException: '<' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
   at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.Serialization.JsonConverter`1[[BankClient.Models.AccountM[], BankClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
   at System.Text.Json.Serialization.JsonConverter`1[[BankClient.Models.AccountM[], BankClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[AccountM[]](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[AccountM[]](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& state, JsonConverter converterBase)
   at System.Text.Json.JsonSerializer.ContinueDeserialize[AccountM[]](ReadBufferState& bufferState, JsonReaderState& jsonReaderState, ReadStack& readStack, JsonConverter converter, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.<ReadAllAsync>d__65`1[[BankClient.Models.AccountM[], BankClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__4`1[[BankClient.Models.AccountM[], BankClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[BankClient.Models.AccountM[], BankClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at BankClient.Service.GenericService`1.<GetEntities>d__18[[BankClient.Models.AccountM, BankClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() in C:UsersmolebOneDriveDocumentsGitHubTshepoBankAppBankClientServiceGenericService.cs:line 85
   at BankClient.GenericClasses.GenericListBase`1.<OnInitializedAsync>d__18[[BankClient.Models.AccountM, BankClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() in C:UsersmolebOneDriveDocumentsGitHubTshepoBankAppBankClientGenericClassesGenericListBase.cs:line 47
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
window.Module.s.printErr @ blazor.webassembly.js:1
Fe._internal.dotNetCriticalError @ blazor.webassembly.js:1
St @ blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a4c1
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed_BINDINGS_SetTaskSourceResult @ managed_BINDINGS_SetTaskSourceResult:17
(anonymous) @ dotnet.6.0.22.tarpzix3in.js:1
Promise.then (async)
_wrap_js_thenable_as_task @ dotnet.6.0.22.tarpzix3in.js:1
_js_to_mono_obj @ dotnet.6.0.22.tarpzix3in.js:1
_mono_wasm_invoke_js_with_args @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a47a
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed_BINDINGS_SetTaskSourceResult @ managed_BINDINGS_SetTaskSourceResult:17
(anonymous) @ dotnet.6.0.22.tarpzix3in.js:1
Promise.then (async)
_wrap_js_thenable_as_task @ dotnet.6.0.22.tarpzix3in.js:1
_js_to_mono_obj @ dotnet.6.0.22.tarpzix3in.js:1
_mono_wasm_invoke_js_with_args @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a47a
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS @ managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS:16
endInvokeJSFromDotNet @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
Promise.then (async)
beginInvokeJSFromDotNet @ blazor.webassembly.js:1
St @ blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a4c1
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS @ managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS:16
endInvokeJSFromDotNet @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
Promise.then (async)
beginInvokeJSFromDotNet @ blazor.webassembly.js:1
St @ blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a4c1
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS @ managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS:16
endInvokeJSFromDotNet @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
Promise.then (async)
beginInvokeJSFromDotNet @ blazor.webassembly.js:1
St @ blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a4c1
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed_BINDINGS_SetTaskSourceResult @ managed_BINDINGS_SetTaskSourceResult:17
(anonymous) @ dotnet.6.0.22.tarpzix3in.js:1
Promise.then (async)
_wrap_js_thenable_as_task @ dotnet.6.0.22.tarpzix3in.js:1
_js_to_mono_obj @ dotnet.6.0.22.tarpzix3in.js:1
js_to_mono_obj @ dotnet.6.0.22.tarpzix3in.js:1
receiveHotReload @ blazor-hotreload.js:2
St @ blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a4c1
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS @ managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS:16
endInvokeJSFromDotNet @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
Promise.then (async)
beginInvokeJSFromDotNet @ blazor.webassembly.js:1
St @ blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a4c1
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
managed_BINDINGS_SetTaskSourceResult @ managed_BINDINGS_SetTaskSourceResult:17
(anonymous) @ dotnet.6.0.22.tarpzix3in.js:1
Promise.then (async)
_wrap_js_thenable_as_task @ dotnet.6.0.22.tarpzix3in.js:1
_js_to_mono_obj @ dotnet.6.0.22.tarpzix3in.js:1
js_to_mono_obj @ dotnet.6.0.22.tarpzix3in.js:1
Fe._internal.getSatelliteAssemblies @ blazor.webassembly.js:1
St @ blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor @ dotnet.6.0.22.tarpzix3in.js:1
$func219 @ dotnet.wasm:0x1a4c1
$func167 @ dotnet.wasm:0xce8f
$func166 @ dotnet.wasm:0xbd73
$func2815 @ dotnet.wasm:0xabf2c
$func1619 @ dotnet.wasm:0x6fcb4
$func1623 @ dotnet.wasm:0x70321
$mono_wasm_invoke_method @ dotnet.wasm:0x969f
Module._mono_wasm_invoke_method @ dotnet.6.0.22.tarpzix3in.js:1
_call_method_with_converted_args @ dotnet.6.0.22.tarpzix3in.js:1
call_method @ dotnet.6.0.22.tarpzix3in.js:1
(anonymous) @ dotnet.6.0.22.tarpzix3in.js:1
call_assembly_entry_point @ dotnet.6.0.22.tarpzix3in.js:1
callEntryPoint @ blazor.webassembly.js:1
At @ blazor.webassembly.js:1
await in At (async)
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1

THIS IS MY CODE THAT REQUESTS THE API

 protected override async Task OnInitializedAsync()
        {

            
            role = await sessionStorage.GetItemAsync<string>("role");


            if(entities == null)
                entities = await genericService.GetEntities();
            else
                str = "already initialized";
        }        

AND MY CONTROLLER OR SERVICES

public async Task<IEnumerable<T>> GetEntities()
        {
            await GetToken();
            if (myType.Name == "AppUser")
            {
                var  response = await httpClient.GetFromJsonAsync<T[]>("api/AuthManagement/users");

                return response;
            }
            else
            {
                var response = await httpClient.GetFromJsonAsync<T[]>($"api/{myType.Name}");
                Console.Write(response);
                return response;
               
            }
        }
        

I TRIED A FEW SUGGESTIONS FROM OTHER POSTS/QUESTIONS IN THE FORUM BUT TO NO LUCK.
OTHERS SUGGESTED I CLEAR MY BROWSER DATA, CHANGE ENDPOINTS AND SO ON.

HERE ARE A FEW OF THEM : clear browesr

and this one
endpoints

How to make client video stream be accessible on an api

What I am trying to do is get a client’s video stream (from their webcam) to be accessible on an api endpoint that I will then access using opencv (cap = cv2.VideoCapture(url_api_endpoint))

So far, all I’ve read about is implementing webRTC. I would love if someone could help me with a minimal code that can do the mentioned task.

Vanilla Javascript accessing a private method variables from within a different constructor function

I am trying to build a drawing app for my University task and I am forced to use encapsulation for this and object oriented programming. Using P5.js, I have 2 constructor functions, first constructor (as you can see below) has a few methods out of which has one private method that “gets” the color that the user clicks. The second constructor is just a tool to draw circles.

By default, the first constructor has a fill option. From within the second constructor I am drawing circles and I’ve made a button that once clicked, removes the fill or adds it back.

My problem is here, once I click to remove the fill, it works, but when I want to apply the fill back to any future circle drawing, I can’t access the first constructor’s private method to get the current color that the user picked.

I have tried, within my main sketch.js file, to create a new colourPalette (first constructor function) assinging it to a variable and then when creating the main CircleTool (second constructor function) I passed as an argument this variable thinking that I will be able to access the colourPalette from within the second constructor, see the below code:

Main sketch.js file:

var toolbox = null;
var colourP = null;
var helpers = null;

function setup() {

    //create a canvas to fill the content div from index.html
    canvasContainer = select('#content');
    var c = createCanvas(canvasContainer.size().width, canvasContainer.size().height);
    c.parent("content");

    //create helper functions and the colour palette
    helpers = new HelperFunctions();
    colourP = new ColourPalette();

    //create a toolbox for storing the tools
    toolbox = new Toolbox();

    //add the tools to the toolbox.
    toolbox.addTool(new FreehandTool());
    toolbox.addTool(new LineToTool());
    toolbox.addTool(new SprayCanTool());
    toolbox.addTool(new mirrorDrawTool());
    toolbox.addTool(new CircleTool(colourP));
    background(255);

}

function draw() {
    //call the draw function from the selected tool.
    //hasOwnProperty is a javascript function that tests
    //if an object contains a particular method or property
    //if there isn't a draw method the app will alert the user
    if (toolbox.selectedTool.hasOwnProperty("draw")) {
        toolbox.selectedTool.draw();
    } else {
        alert("it doesn't look like your tool has a draw method!");
    }
}

colourPalette constructor:

function ColourPalette() {
    //a list of web colour strings
    this.colours = ["black", "silver", "gray", "white", "maroon", "red", "purple",
        "orange", "pink", "fuchsia", "green", "lime", "olive", "yellow", "navy",
        "blue", "teal", "aqua"
    ];
    //make the start colour be black
    this.selectedColour = "black";
    
    var self = this;

    var colourClick = function() {
        //remove the old border
        var current = select("#" + self.selectedColour + "Swatch");
        current.style("border", "0");

        //get the new colour from the id of the clicked element
        c = this.id().split("Swatch")[0];

        //set the selected colour and fill and stroke
        self.selectedColour = c;
        fill(c);
        stroke(c);

        //add a new border to the selected colour
        this.style("border", "2px solid blue");
        return c;
    }

    //load in the colours
    this.loadColours = function() {
        //set the fill and stroke properties to be black at the start of the programme
        //running
        fill(this.colours[0]);
        stroke(this.colours[0]);

        //for each colour create a new div in the html for the colourSwatches
        for (var i = 0; i < this.colours.length; i++) {
            var colourID = this.colours[i] + "Swatch";

            //using p5.dom add the swatch to the palette and set its background colour
            //to be the colour value.
            var colourSwatch = createDiv()
            colourSwatch.class('colourSwatches');
            colourSwatch.id(colourID);

            select(".colourPalette").child(colourSwatch);
            select("#" + colourID).style("background-color", this.colours[i]);
            colourSwatch.mouseClicked(colourClick)
        }

        select(".colourSwatches").style("border", "2px solid blue");
    };
    //call the loadColours function now it is declared
    this.loadColours();
    this.selectedColor = function() {
        var color = colourClick();
        fill(color);
    }
}

CircleTool Constructor:

function CircleTool(palette) {
    this.name = "circleTool";
    this.icon = "/assets/circle.jpg";
    this.colorPalette = palette;

    var startMouseX = -1;
    var startMouseY = -1;
    var drawing = false;
    this.draw = function() {
        //Function to draw the circle
        if(mouseIsPressed) {
            if(startMouseX == -1) {
                drawing = true;
                startMouseX = mouseX;
                startMouseY = mouseY;
                loadPixels();
            }    
            else {
                updatePixels();
                ellipse(startMouseX,startMouseY,dist(startMouseX,startMouseY,mouseX,mouseY));
            }        
        }
        else if(drawing) {
            drawing = false;
            startMouseX = -1;
            startMouseY = -1;
        }
    }
    //adds a button and click handler to the options area. When clicked
    //toggle the fill of the circle
    this.populateOptions = function() {
        select(".options").html(
            "<button id='directionButton'>Fill circle</button>");
        //  //click handler
        select("#directionButton").mouseClicked(function() {
            var button = select("#" + this.elt.id);
            if (self.axis == "fill") {
                self.axis = "notFill";
                console.log(colorPalette);
                button.html('Circle not Filled');
            } else {
                self.axis = "fill";
                self.lineOfSymmetry = width / 2;
                noFill();
                button.html('Circle Filled');
            }
        });
    };
}

Now, inside the CircleTool constructor I am taking that argument and assign it to a variable. What I need to access is the private method from within colourPalette called “colourClick()”, specifically the variable “c” that holds the current color that the user clicked (I tried to return the variable “c” when the function is called so that I can get the value but it doesn’t work, I’m missing something. Is there a way to take advantge of that and get the value of that variable “c” and use it in the CircleTool constructor in the “populateOptions” method? I am only allowed to use vanilla Javascript and p5.js methods to create this.

Need help accessing array outside of arrow function [duplicate]

I am totally new to javascript I’m usually using C#. I need to read in a text file in order to populate an array. I have all this working however I can’t access the array properly outside of the arrow function. I sent the array data to an existing array outside of that function but it looks different when debugging and is causing later code to not work. I can post the entire

// default names
const names = [];


// Load names from names.txt
fetch("names.txt")
  .then((res) => res.text())
  .then((text) => {
    const fileNames = text.split("n");
    console.log('fileNames', fileNames);
    fileNames.forEach((name, idx) => {
      if (name) names[idx] = name;
    });
    setupWheel();
   })
  .catch((e) => console.error(e));

console.log('names', names);

const colors = [
  "hsl(197 30% 43%)",
  "hsl(173 58% 39%)",
  "hsl(43 74% 66%)",
  "hsl(27 87% 67%)",
  "hsl(12 76% 61%)",
];

const reactions = ['resting', 'dancing', 'laughing', 'shocked'];
const prizes = () => names.map((name, idx) => {
  return {
    text: name,
    color: colors[idx],
    reaction: reactions[Math.floor(Math.random()*reactions.length)]
  }
});

array differences

See the attached image to see how the arrays are showing up differently. I believe it is missing the elements but like I said I am completely new to javascript. I appreciate any help!

I’ve tried getting sending the array to an existing array and I’ve tried to get the array out of the function but don’t understand how to do it.

New instance is not defined

index.js

import { Player } from "./Players.js"
const player1 = new Player;
player1.getCharacter()

Here I import class Player, into my main javaScript file, defined as export class Player {} from Players.js

Then I initialize a player1 object and assign to it an instance of the Player class.

Then I call a method from player1 which exist within the Player class.

MY PROBLEM is … Within the browser, the console tells me player1 is not defined. Whereas the method works as I can player1.getCharacter(). However the function is being called from Players.js.

HOW TO make the browser aware of the new instance ?!

I’ve tried to instantiate a new object but it doesn’t seem to work as chrome’s browser tells me it is undefined when I try to call it.

console.log(player1)
// player1 is undefined

Vite server failing to reload Vue.js page

So, I work on a SPA with Vue.js, which me and my team used vue-cli to create it. A few weeks back we decided to change it to Vite, since there’s so many benefits developing with Vite rather than with Webpack, and all the problems that we crossed until now were pretty much easy to solve.

But yesterday I crossed with the problem of not being able to reload (specifically) nested routes, as I get the error
GET http://localhost:5173/admin/src/main.js net::ERR_ABORTED 404 (Not Found), which is totally new, so I assume is a Vite-related problem.

Redirecting happens fine, e.g. if I type localhost:5173/admin I am redirected to localhost:5173/admin/home, but as soon as I reload the page, the error above is thrown, as if the server is looking for a admin directory on the root. This happens with every other page that is nested, and the error is not given for parent routes.

For example,
localhost:5173/dashboard will reload fine, but
localhost:5173/dashboard/profile will throw an error on reload (GET http://localhost:5173/dashboard/src/main.js net::ERR_ABORTED 404 (Not Found)).

I already tried some things, since reloading problems are not new with SPA, but nothing worked for me. I tried some different Server Configurations, but adding connect-history-api-fallback dependency to my node.js back-end didn’t solve it, since my back-end is mostly for APIs, and there’s no server-side rendering. I also tried a .htaccess file, not successful as well.

Here’s my .htaccess file:

<IfModule mod_negotiation.c>
  Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

That’s it, I’m going to leave some sample code so it might help someone see what I couldn’t.

vite.config.js

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd());

  return {
    plugins: [
      vue(),
    ],
    server: {
      proxy: {
          '^/api': {
              changeOrigin: true,
              target: `http://${env.VITE_IP_API}:${env.VITE_PORTA_API}`,
          }
      }
    }
  }
});

src/router/admin.js

// this code is imported on src/router/index.js and spread on the root array
export default [
    {
        path: '/admin', // works and redirects correctly
        name: 'admin',
        redirect: {
            name: 'homeAdmin'
        },
        children: [
            {
                path: 'home', // doesn't work on reload
                name: 'homeAdmin',
                component: () => import('../views/admin/AdminHome.vue'),
            },
        ],
        beforeEnter: async (to) => {
            // some api call
        }
    },
    {
        path: '/admin/login', // doesn't work on reload
        name: 'loginAdmin',
        component: () => import('../views/admin/AdminLogin.vue')
    }
]

src/main.js

import './assets/styles/styles.scss';

import { createApp } from 'vue';

import App from './App.vue';
import router from './router';
import store from './store';

import axiosInstance from './lib/axios/axiosInstance.js';
import axios from 'axios';

axiosInstance.axios = axios.create({
    baseURL: (import.meta.env.VITE_NODE_ENV === 'production')
        ? `https://${import.meta.env.VITE_IP_API}:${import.meta.env.VITE_PORTA_API}/api`
        : `/api`,
    withCredentials: true,
    timeout: 50000,
});

const app = createApp(App);

app.use(router);
app.use(store);

app.config.globalProperties.$axios = axiosInstance.axios;

app.mount('#app');

Again, I think is worth repeating that I hadn’t had this problem with Webpack. Pages reloaded correctly on refresh.

i want to change the sanity link

enter image description here

export async function getStaticProps() {
  const res = await fetch(
    "**https://2w7owe8f.api.sanity.io/v1/data/query/production?query=*%5B_type+%3D%3D+%22post%22%5D%7Btitle%2C+_createdAt%2C+slug%7Bcurrent%7D%2C+image%7Balt%2C+caption%2C+image%7Basset%7B_ref%7D%7D%7D%2C+body%7D**"
  );
  // *[_type == "blog"]{title, _createdAt, slug{current}, image{alt, caption, image{asset{_ref}}}, body}
  const rawData = await res.json();

  const data = rawData.result.map((v) => {
    return {
      title: v.title,
      date: v._createdAt,
      image: {
        alt: v.image.alt ? v.image.alt : "alt...",
        url:
          "**https://cdn.sanity.io/images/2w7owe8f/production**/" +
          v.image.image.asset._ref
            .replace(/image-/g, "")
            .replace(/-(?!.*-)/g, "."),
      },
      body: v.body,

i used this text

btw im a newbie trying new stuff

i already have sanity but when i change the link i have this error enter image description here

i tried to change link but i dont understand why i got this error

How to target ALL elements in shadow-root?

I am trying to add a class to an element inside of the shadow root for 3 slides within a carousel. Here is my code:

let modalFlexDisplay = document.querySelector("#ipm-ad-modal-div").querySelector("#rs-two-col").shadowRoot.querySelector(".wrapper");

modalFlexDisplay.classList.add("hidden");
<div id="ipm-ad-modal-div">
<div id="rs-two-col">
  <template shadowrootmode="open">
<div class="wrapper">
<p>hello and happy halloween</p>
</div>
</template>
</div>
<div id="rs-two-col">
  <template shadowrootmode="open">
<div class="wrapper">
<p>hello and happy halloween</p>
</div>
</template>
</div>
</div>

If you inspect the code snippet here, you can see that the class was successfully added to just the first div.wrapper tag. However I want to add them on all, and not just the first one.

When I try to add “querySelectorAll” to any or all of the elements, it returns an error saying it cannot read the properties of querySelector. How do i add the class “hidden” to all elements within each shadow root?