Encrypt data with RSA in Javascript synchronously

I need to encrypt user-entered data (username, email and password) using Javascript to not transfer it over the network in the plain text. (I do using HTTPS, but RSA is here just for test purposes, I want to replace it with McEliece once in the future…) I have written the following code:

        function str2ab(str)
        {
            const buf = new ArrayBuffer(str.length);
            const bufView = new Uint8Array(buf);
            for (let i = 0, strLen = str.length; i < strLen; i++)
                bufView[i] = str.charCodeAt(i);
            return buf;
        }
        function importKey(pem)
        {
            const pemHeader = "-----BEGIN PUBLIC KEY-----";
            const pemFooter = "-----END PUBLIC KEY-----";
            const pemContents = pem.substring(
                pemHeader.length,
                pem.length - pemFooter.length - 1,
            );
            const binaryDerString = window.atob(pemContents);
            const binaryDer = str2ab(binaryDerString);
            return window.crypto.subtle.importKey(
                "spki",
                binaryDer,
                {
                    name: "RSA-OAEP",
                    hash: "SHA-512",
                },
                true,
                ["encrypt"],
            );
        }
        var pubkey = importKey(`
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
`);
        alert(pubkey); //Shows "[object Promise]"
        var encrypted = window.crypto.subtle.encrypt(
            {
                name: "RSA-OAEP",
            },
            pubkey,
            JSON.stringify(...),
        ); //TypeError: SubtleCrypto.encrypt: Argument 2 does not implement interface CryptoKey.
        ...

If I replace the importKey() function with the following:

        function importKey(pem)
        {
            const pemHeader = "-----BEGIN PUBLIC KEY-----";
            const pemFooter = "-----END PUBLIC KEY-----";
            const pemContents = pem.substring(
                pemHeader.length,
                pem.length - pemFooter.length - 1,
            );
            const binaryDerString = window.atob(pemContents);
            const binaryDer = str2ab(binaryDerString);
            let result;
            window.crypto.subtle.importKey(
                "spki",
                binaryDer,
                {
                    name: "RSA-OAEP",
                    hash: "SHA-512",
                },
                true,
                ["encrypt"],
            ).then(key => result = key);
            return result;
        }
  • alert shows “undefined”. Unfortunately, I could not use async calls since the function where I try to encrypt is synchronous and this cannot be changed. How to call encryption method synchronously? I do want to freeze a page, since I hope it won’t be a long time. I know there is .Result property in C# (my main language), maybe there is something similar in Javascript?
    I don’t use packs like Node.js etc., so the methods described here don’t work.

long webpage with height more than screen height [closed]

Picture [1] is what I want to achieve.

Picture [2] is what I currently have.

Picture [3] is a real-world example of a long webpage.

Picture 1

what I want to achieve

Picture 2

my webpage

Picture 3

real-world example

I googled and read several posts that seemed related, but still couldn’t find a solution.

I tried things below as some posts suggested

// index.css

html, body{
  height: 100%;
}
// index.css

html{
  height: 100%;
}

body{
  min-height: 100%;
// height: fit-content; doesn't seem to work either
}

I also tried

// index.css

body{
  display: flex;
  flex-direction: column;
}

I know I can simply do

// index.css

body{
   height: 200%;
   // or height: 9999px;
   // or height: 200vh;
}

But I don’t think it’s a good solution for me because it needs to be rewritten every time I append new things.

Angular 18 Chart libraries [closed]

I am planning on migrating my angular project from version 17 to 18.

Currently I am using Plotly.js-dist-min library for graphs.

When building the project (ng build) the plotly.js library does not optimise because it uses commonjs module instead of ESM.

Due to this issue the build size also increases.

I want suggestions on better chart library which is compatible with angular 18 and is light weight

I have tried resolving the optimization issue over the plotly library.

But it has led me to more errors and complicate the set-up

Uncaught (in promise) Error: Could not find identifiable element

I am using reactjs with antd, I have a form and inside it a bunch of form.items

using a component called Radio.Group with Radio as the options,

I want to add an option for ‘other’ and when that is clicked – an input will be viewable and that will be a form.item as well.

my problem is that the rule for ‘required’ for that input form.item isn’t working and I’m getting an error –

‘Uncaught (in promise) Error: Could not find identifiable element’

anyone knows why? how do i tackle this?

Changing mantine TextInput error border color

Is there a way to use a selector to change the border color for Mantine V6 TextInput when the error is set?

I can do this by setting the borderColor within the sx object as follows:

<TextInput sx={{ borderColor: error ? 'red' : 'green' }} />

but then I have to set the standard borderColor as well.

Using devtools, I can see that they have a data-invalid class, but can’t seem to find a way to use a selector to target that:

.mantine-188bo4n[data-invalid] {
    color: #fa5252;
    border-color: #fa5252;
}

I know they have the errors property within the styles object but that seems to just target the error text under the input.

Any help would be much appreciated.

Note: I’m using inline styles and the sx prop. I do not want to be using external css files.

Why is mix-blend-mode: difference; not working on my SVG logo?

I’m trying to apply mix-blend-mode: difference; to an SVG logo when it overlaps a specific section of my webpage, but it’s not working. The blend mode doesn’t seem to have any effect.

Here’s what I have:

An SVG logo wrapped in <div class="logo">.
A section with data-bg="effect" where I want the blend mode effect to apply.
JavaScript that adds the effect class to the logo when it overlaps the section.

HTML:

<div class="logo">
  <svg width="100%" viewBox="0 0 565 141" xmlns="http://www.w3.org/2000/svg">
    <!-- SVG content with paths using fill="currentColor" -->
  </svg>
</div>

<div class="mask-bg" data-bg="effect">
  <!-- Section content -->
</div>

CSS:

.logo {
  color: black;
  isolation: isolate;
}

.logo.effect {
  mix-blend-mode: difference;
}

JavaScript:

const logo = document.querySelector('.logo');
const sections = document.querySelectorAll('.mask-bg');

function updateLogoClasses() {
  sections.forEach((section) => {
    const sectionRect = section.getBoundingClientRect();
    // Check if the logo overlaps the section
    if (/* overlap condition */) {
      const bg = section.dataset.bg;
      logo.classList.remove('effect');
      if (bg === 'effect') {
        logo.classList.add('effect');
      }
    }
  });
}

window.addEventListener('scroll', updateLogoClasses);
window.addEventListener('resize', updateLogoClasses);
updateLogoClasses();

Problem:

When the logo has the effect class, the mix-blend-mode: difference; doesn’t work on the SVG logo. The blending doesn’t happen.

What I’ve tried:
Confirmed that the effect class is applied to the logo.
Ensured SVG paths use fill="currentColor".
Added isolation: isolate; to the .logo class.
Tried different colors and blend modes.
Wrapped the SVG in a <div>.

Question:
Why is mix-blend-mode: difference; not affecting my SVG logo, and how can I make it work?

How to use the disabledMinutes option of TUI timepicker?

I have implemented the Toast UI timepicker from here on my website. I’m trying to use the disabledMinutes option to disable a specific time such as “03:15” but it is not working. I could still select 03:15 on my timepicker. What could be the issue?

Here is what I have so far

var tui = new tui.TimePicker('#test', {
        initialHour: 12, 
        initialMinute: 0,   
        inputType: 'spinbox',
        format: 'hh:mm', 
        disabledMinutes: {
            3 : [true, true, true, true, true, true, true, true, true, true, 
                 true, true, true, true, false, true, true, true, true, true, 
                 true, true, true, true, true, true, true, true, true, true, 
                 true, true, true, true, true, true, true, true, true, true, 
                 true, true, true, true, true, true, true, true, true, true, 
                 true, true, true, true, true, true, true, true, true, true]
        }
    });

Update.php Hey Guys, I would like to ask what could possibly be the problem with this code?

there might a problem on how it fetched the data. the data is not showing on the input field. what seems to be the problem? I tried to change the approach so many times but it is still the same. what am I missing out here?

query($year_query); //
Initialize default variables $data = []; $selected_year = ”;
$months = get_months(); // Get an array of months // Fetch months
dynamically function get_months() { return [
“1” => “January”, “2” => “February”, “3” => “March”, “4” => “April”,
“5” => “May”, “6” => “June”, “7” => “July”, “8” => “August”,
“9” => “September”, “10” => “October”, “11” => “November”, “12” => “December” ]; } // Handle form submission if ($_SERVER[“REQUEST_METHOD”] == “POST”) { // Update form logic if
(isset($_POST[‘data’]) && isset($_POST[‘year’])) {
$selected_year = $_POST[‘year’];

foreach ($_POST[‘data’] as $month => $values) {
$total_nr = $values[‘total_nr’] ?? 0;
$re_enlisted_personnel = $values[‘re_enlisted_personnel’] ?? 0;
$reprimand = $values[‘reprimand’] ?? 0;
$not_yet_re_enlisted = $values[‘not_yet_re_enlisted’] ?? 0;

$update_query = ”
UPDATE reenlistment_data
SET
total_nr = ‘$total_nr’,
re_enlisted_personnel = ‘$re_enlisted_personnel’,
reprimand = ‘$reprimand’,
not_yet_re_enlisted = ‘$not_yet_re_enlisted’
WHERE
year = ‘$selected_year’
AND month = ‘$month’
“;
$conn->query($update_query);
}

echo “Data updated successfully for $selected_year!”; }

// Fetch data for the selected year if (isset($_POST[‘year’])) {
$selected_year = $_POST[‘year’];
$data_query = “SELECT * FROM reenlistment_data WHERE year = ‘$selected_year’ ORDER BY month ASC”;
$data_result = $conn->query($data_query);

// Prepare data for form rendering
if ($data_result) {
while ($row = $data_result->fetch_assoc()) {
$data[$row[‘month’]] = $row;
}
} } } ?> content=”width=device-width, initial-scale=1.0″> Update
Re-enlistment Data
Update Re-enlistment Data

Select Year:

Select Year
fetch_assoc()): ?>

” >

Load Data

“>

Month
Total NR
Re-enlisted Personnel
Reprimand
Not Yet Re-enlisted

$month_name):
$row = $data[$month_num] ?? [‘total_nr’ => ”, ‘re_enlisted_personnel’ => ”, ‘reprimand’ => ”,
‘not_yet_re_enlisted’ => ”];
?>

][total_nr]”
value=””>
][re_enlisted_personnel]” value=””>
][reprimand]”
value=””>
][not_yet_re_enlisted]” value=””>

Update Data

No data available for the selected year.

Form.io hide Component tabs like API, Conditional, Logic and Layout tabs

I am working on the form.io from builder integration part. I am not able to hide API, Conditional, Logic and Layout Tabs.
I am using angular JS version 1. Here i have added default configuration for that.

I am not able to hide that. How can i do that?

I also want to hide the help section.

enter image description here

Code Snippet:-

     var builderOptions = {
  builder: {
    allComponents: {
      title: 'Components',
      weight: 0,
      default: true,
      components: {
        textfield: true,
        textarea: true,
        number: true,
        mycomponent: true, // Example custom component
      },
    },
    // Disable other groups
    basic: false,
    advanced: false,
    layout: false,
    data: false,
    premium: false,
  },

};

Formio.builder(document.getElementById('builder'), {}, builderOptions)
  .then(function(builder) {
  console.log(formioComponents);
  console.log(builder);
  builder.on('change', function(schema) {
    console.log('Form Schema Changed:', schema);
    $scope.formSchema = schema;
    $scope.$apply();
  });
});

enter image description here

How do we inject JavaScript using cookies in an in-app browser in react-native Expo app? [closed]

I am new to react-native, Expo. I want my users to directly be logged in into a website using cookies the link will open up in an in-app browser.

For this I’m using package expo-web-browser. But this library only allows my users to open links in in-app browser.

Also, I can’t use Webview component because it doesn’t have in-app browser based controls. (Custom crome tabs and safari controller)

I’m unable if there’s a way to even integrate custom Crome tabs in webview, then I can use it.

Please suggest.

Select multiple month in MonthCalendar from MUI mui/x-date-pickers

So in mui i want to select the multiple months like i can select from jan to july and there should be border display on selected months like in mui days selection.

<MonthCalendar 
        views={['month']} 
        disableFuture={disableFuture} 
        value={isArrowValue ? moment(arrowValue) : moment(value)} 
        minDate={moment(minDate)}  
        maxDate={moment(maxDate)}  
        onChange={handleDateChange}  
        disabled={disabled}
        slots={{
                  monthButton: CustomMonthButton,
                }}

                slotProps={{
                  monthButton: {
                    // value: startDate,
                    // startDate: moment(months.startDate),
                    maxDate: moment(maxDate),
                    startDate: startDate,
                    endDate: endDate,
                    // handleMouseOut: handleMouseOut,
                    // handleMouseOver: handleMouseOver,
                    hoverEndDate: hoverEndDate,
                    variant: variant,
                    dayPickerClasses: dayPickerClasses,
                  },
                }}
                sx={
                  isArrowValue &&
                  moment(value).format('Y') !== moment(arrowValue).format('Y')
                    ? classes.navMonthPicker
                    : classes.monthPicker
                }
              />

this is code till now and CustomMonthButton is the component that render each months
So till now i pass this
monthButton: CustomMonthButton
and in this add button for each months but i want something in range.
am using mui/x-date-pickers ^7.22.2 and mui 5.16.7
i want same as mui date picker where i can select in range.

Synchronize react state with react router url search params

I’m building an e-commerce page using React that includes various options stored in state, such as sortBy, itemsPerPage, and several interdependent categories. I want these state values to also be reflected in the URL as search parameters.

I’m using React Router’s useSearchParams hook to keep the state and URL in sync. However, I’m encountering issues with useEffect dependencies and potential logical flaws due to intentionally omitting certain values from the dependency array to avoid circular dependencies.

I created a custom hook called useURLSync so that different state can sync and share the same searchParams object returned by the useSearchParams hook and to hide all the synchronization logic.

import { useState, useEffect } from "react";

export default function useURLSync(
  searchParams,
  setSearchParams,
  paramName,
  type = "string",
  initialValue = ""
) {
  // Type validation
  if (type === "array" && !Array.isArray(initialValue)) {
    throw new Error(
      `useURLSync: initialValue must be an array when type is "array"`
    );
  }
  if (type === "string" && typeof initialValue !== "string") {
    throw new Error(`
        useURLSync: initialValue must be a string when type is "string"`);
  }

  // Intiliaze state from URL search params according to the paramName if it exists,
  // if not, return the initial value
  const [state, setState] = useState(() => {
    if (searchParams.has(paramName)) {
      const paramValue = searchParams.get(paramName);
      if (paramValue) {
        if (type === "string") {
          return paramValue;
        } else if (type === "array") {
          return paramValue.split(",");
        }
      }
    }
    return initialValue;
  });

  // Update the URL when state changes
  useEffect(() => {
    // Create a new URL search params object from a copy of the current one
    const newSearchParams = new URLSearchParams(searchParams);
    let shouldChange = false;

    if (state.length > 0) {
      const currentParamValue = searchParams.get(paramName);

      if (type === "array") {
        const newParamValue = state.join(",");
        if (newParamValue !== currentParamValue) {
          newSearchParams.set(paramName, newParamValue);
          shouldChange = true;
        }
      } else if (type === "string") {
        const newParamValue = state;
        if (newParamValue !== currentParamValue) {
          newSearchParams.set(paramName, newParamValue);
          shouldChange = true;
        }
      }
    } else if (newSearchParams.has(paramName)) {
      newSearchParams.delete(paramName);
      shouldChange = true;
    }

    if (shouldChange) {
      setSearchParams(newSearchParams, { replace: true });
    }
  }, [state]);

  // Update state when URL seach params changes
  useEffect(() => {
    const paramValue = searchParams.get(paramName);
    let newStateValue = initialValue;
    if (paramValue) {
      if (type === "array") {
        newStateValue = paramValue.split(",");
      } else if (type === "string") {
        newStateValue = paramValue;
      }
      if (JSON.stringify(newStateValue) !== JSON.stringify(state)) {
        setState(newStateValue);
      }
    } else if (state !== initialValue) {
      setState(initialValue);
    }
  }, [searchParams]);

  return [state, setState];
}

And here is how it is used:


  // Search Params
  const [searchParams, setSearchParams] = useSearchParams();

  // Page State
  const [page, setPage] = useURLSync(
    searchParams,
    setSearchParams,
    "page",
    "string",
    "1"
  );

  // PerPage state
  const [perPage, setPerPage] = useURLSync(
    searchParams,
    setSearchParams,
    "perPage",
    "string",
    "12"
  );

  // Sort state
  const [sort, setSort] = useURLSync(
    searchParams,
    setSearchParams,
    "sort",
    "string",
    "alpha-desc"
  );

  const [selectedPlatforms, setSelectedPlatforms] = useURLSync(
    searchParams,
    setSearchParams,
    "platforms",
    "array",
    []
  );

In the first useEffect, I update the URL whenever the React state changes. I include the state in the dependency array. Within this useEffect, I also use the searchParams object returned by useSearchParams to get the current parameter value and check if a change is necessary. I intentionally omit searchParams from the dependency array to avoid a circular dependency.

In the second useEffect, I update the state whenever the URL search parameters change. Here, I include searchParams in the dependency array but omit the state, even though I use it for comparison.

Is intentionally omitting dependencies in useEffect the right way to prevent circular updates? How can I properly synchronize the state and URL search parameters without causing circular updates or omitting necessary dependencies?

Thank you!

How can I develope and write a code for this problem?

There is a game in n steps. The probability of gaining in step j is “xj/100” (1<= xj <= 100). The game begins from step 1 on day 1 as follows:

  • If you gain in step j you stop the game and begin step j+1 the next day.
  • If you fail in step j you stop the game and begin the game from step 1 the next day.

The question is: What is the expectation of number of days that it will take to complete this game?

Input include two consecutive lines: First line : n

      Second line:  n numbers showing xi

Output is just a number that is expectation of days it needs to solve this game

As an example: Input: 3

                  10 20 50

Output: 112

Is that possible to write a code for this problem?

There is a game in n steps. The probability of gaining in step j is “xj/100” (1<= xj <= 100). The game begins from step 1 on day 1 as follows:

  • If you gain in step j and you gain you stop the game and begin step j+1 the next day.
  • If you are in step j and you fail you stop the game and begin the game from step 1 the next day.

The question is: What is the expectation of number of days that it will take to complete this game?

Input include two consecutive lines: First line : n

      Second line:  n numbers showing xi

Output is just a number that is expectation of days it needs to solve this game

As an example: Input: 3

                  10 20 50

Output: 112