Is there any way to ask the browser to ask permission like being able to prompt for file input via js?

I have a keyboard shortcut in an online game, but if the user clicks CTRL+O it should prompt for a save file. But instead it complains

<input> picker was blocked due to lack of user activation.

Is there any way I could prompt for this permission (to click without user interaction)?
If it helps, my code creates a hidden input tag and clicks it with .click() to prompt for savefile.

Where the (e) parameter in the event listener function comes from [duplicate]

In JavaScript event handling, particularly when using event listeners like addEventListener, it’s common to see a parameter named e, representing an event object. What exactly is this e parameter, and where does it come from?

When setting up event listeners in JavaScript, such as:

javascriptCopy code

element.addEventListener('click', function(e) { // Event handling code here });

what is the correct way to reference image in javascript application

I’m working a js website with file structure like so:
public

public src
image_files a.html

in my a.html
i imported an image

however, it doesn’t seem to be able to locate it.

i tried to import it as

<img src="/public/images/image01.jpg" loading="lazy" alt=""/>

it still doesn’t seem to be able to locate it and i got warning message like so

Files in the public directory are served at the root path.
Instead of /public/images/image01.jpg, use /images/image01.jpg. (x2)

And here is my vite.config.js

import { defineConfig } from "vite";
import fs from "fs";
import path from "path";
export default defineConfig({
  // The base path for your application
  // **Explicitly set base path for clarity:**
  base: "./",

  // **Adjust root path if necessary:**
  root: "./src",

  // Development server configuration
  server: {
    // Port number
    port: 3000,

    // Hostname
    host: "localhost",

    // Enable HTTPS
    https: false,
  },

  // Production build configuration
  build: {
    // Adjust the chunk size warning limit as needed
    chunkSizeWarningLimit: 1000,

    // Output directory
    outDir: "dist",

    // Ensure that assets are served relative to the current directory
    assetsDir: "./",

    // Enable/disable minification
    minify: true,

    // Enable/disable CSS code splitting
    cssCodeSplit: true,

    // Configure assets behavior
    assetsInlineLimit: 4096,

    // Configure source map generation
    sourcemap: false,

    // Modify rollup options to include all HTML files in the output directory
    rollupOptions: {
      input: {
        // Specify all HTML files here dynamically
        ...Object.fromEntries(
          fs
            .readdirSync(path.resolve(__dirname, "src"))
            .filter((file) => file.endsWith(".html"))
            .map((file) => [path.basename(file, ".html"), `src/${file}`])
        ),
        // Add script.js as an entry point
        main: "/js/main.js",
        script: "/js/script.js",
      },
      output: {
        // Ensure your JS files are included in the output directory
        // (e.g., if it's in the "src/js" directory)
        dir: "dist",
        entryFileNames: "[name].[hash].js",
      },
    },
  },
});

Can this general implementation of STDIO for JavaScript be improved?

ECMA-262 doesn’t specify STDIO. If you use more than one JavaScript engine or runtime regularly you’ll notice that no two (2) JavaScript runtimes implement STDIO the same in the respective runtime-specific API’s.

After some experimentation and testing I cobbled together this script that achieves the same result using the standalone JavaScript executables node, deno, bun.

The algorithm just happens to be for Native Messaging, where the protocol is

The same format is used to send messages in both directions; each message is serialized using JSON, UTF-8 encoded and is preceded with 32-bit message length in native byte order

Modern JavaScript runtimes, in general, have implemented WHATWG Streams to an appreciable degree.

Set aside the Uint32Array preceding the message and we can use the same code in multiple JavaScript runtimes for a common, portable STDIO implementation.

Can the following general STDIO implementation for JavaScript be improved?

/*
#!/usr/bin/env -S /home/user/bin/deno run -A /home/user/bin/nm_host.js
#!/usr/bin/env -S /home/user/bin/node --experimental-default-type=module /user/bin/nm_host.js
#!/usr/bin/env -S /home/user/bin/bun run --smol /home/user/bin/nm_host.js
*/

const runtime = navigator.userAgent;
// 1 MB formatted JSON, e.g., new Array(209715)
const buffer = new ArrayBuffer(0, { maxByteLength: 1024 ** 2 });
const view = new DataView(buffer);
const encoder = new TextEncoder();
const { dirname, filename, url } = import.meta;

let readable, writable, exit, args, cwd;

if (runtime.startsWith("Deno")) {
  ({ readable } = Deno.stdin);
  ({ writable } = Deno.stdout);
  ({ exit } = Deno);
  ({ args } = Deno);
}

if (runtime.startsWith("Node")) {
  const { Duplex } = await import("node:stream");
  ({ readable } = Duplex.toWeb(process.stdin));
  ({ writable } = Duplex.toWeb(process.stdout));
  ({ exit } = process);
  ({ argv: args } = process);
}

if (runtime.startsWith("Bun")) {
  readable = Bun.stdin.stream();
  writable = new WritableStream({
    async write(value) {
      await Bun.write(Bun.stdout, value);
    },
  }, new CountQueuingStrategy({ highWaterMark: Infinity }));
  ({ exit } = process);
  ({ argv: args } = Bun);
}

const hostdir = args.at(-2).slice(0, args.at(-2).lastIndexOf("/"));


if (runtime.startsWith("Bun") || runtime.startsWith("Node")) {
  process.chdir(hostdir);
  cwd = process.cwd();
}

if (runtime.startsWith("Deno")) {
  await Deno.chdir(hostdir);
  cwd = Deno.cwd();
}

function encodeMessage(message) {
  return encoder.encode(JSON.stringify(message));
}

async function* getMessage() {
  let messageLength = 0;
  let readOffset = 0;
  for await (let message of readable) {
    if (buffer.byteLength === 0) {
      buffer.resize(4);
      for (let i = 0; i < 4; i++) {
        view.setUint8(i, message[i]);
      }
      messageLength = view.getUint32(0, true);
      message = message.subarray(4);
      buffer.resize(0);
    }
    buffer.resize(buffer.byteLength + message.length);
    for (let i = 0; i < message.length; i++, readOffset++) {
      view.setUint8(readOffset, message[i]);
    }
    if (buffer.byteLength === messageLength) {
      yield new Uint8Array(buffer);
      messageLength = 0;
      readOffset = 0;
      buffer.resize(0);
    }
  }
}

async function sendMessage(message) {
  await new Blob([
    new Uint8Array(new Uint32Array([message.length]).buffer),
    message,
  ])
    .stream()
    .pipeTo(writable, { preventClose: true });
}

try {
  await sendMessage(encodeMessage([{ dirname, filename, url }, { cwd }, ...args]));
  for await (const message of getMessage()) {
    await sendMessage(message);
  }
} catch (e) {
  exit();
}

/*
export {
  args,
  encodeMessage,
  exit,
  getMessage,
  readable,
  sendMessage,
  writable,
};
*/

React frontend Admin panel ( Firebase Auth email/password ) & Mongodb

im buildig ReactJS Frontend Admin panel for my Nodejs project
it uses Firebase Auth and mongodb
my proble is whatever i do the Dashboard always blank after redirect succuess login
Files as following:

App.js

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { AuthContextProvider } from './AuthContext';
import PrivateRoute from './PrivateRoute';
import Login from './Login';
import Dashboard from './Dashboard'; // Import Dashboard.js here
import './App.css';

function App() {
  return (
    <BrowserRouter>
      <AuthContextProvider>
        <Routes>
          <Route path="/" element={<Login />} /> {/* Public route */}
          <Route
            path="/dashboard"
            element={
              <PrivateRoute>
                <Dashboard /> {/* Dashboard component here */}
              </PrivateRoute>
            }
          />
        </Routes>
      </AuthContextProvider>
    </BrowserRouter>
  );
}

export default App;

and AuthContext.js

import React, { createContext, useContext, useState } from 'react';

const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);

  const login = (user) => {
    setCurrentUser(user);
  };

  const logout = () => {
    setCurrentUser(null);
  };

  return (
    <AuthContext.Provider value={{ currentUser, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthContextProvider');
  }
  return context;
};

and PrivateRoute.js

import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from './AuthContext'; // Import useAuth hook

const PrivateRoute = () => {
  const { currentUser } = useAuth(); // Use the useAuth hook to access currentUser

  return currentUser ? <Outlet /> : <Navigate to="/" replace />;
};

export default PrivateRoute;

and index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

and Login.js

import React, { useState } from "react";
import { auth } from "./firebase-config"; // Import your Firebase app
import { signInWithEmailAndPassword } from "firebase/auth"; // Import from Firebase
import { useNavigate } from "react-router-dom"; // Import for navigation
import { useAuth } from "./AuthContext"; // Import AuthContext using useAuth

const Login = () => {
  const [error, setError] = useState(null);
  const navigate = useNavigate();
  const { login } = useAuth(); // Use the useAuth hook to access setCurrentUser

  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      const userCredential = await signInWithEmailAndPassword(
        auth,
        e.target.email.value,
        e.target.password.value
      );

      // Set a success message
      setError("Login Successful!");

      // Update currentUser in AuthContext (assuming your AuthContext manages user state)
      login(userCredential.user);

      // Redirect to Dashboard after successful login
      navigate("/dashboard");
    } catch (error) {
      setError(error.message); // Set the error message in the state
    }
  };

  return (
    <div className="login-container">
      <div id="root" className="min-h-100vh flex grow bg-slate-50 dark:bg-navy-900" x-cloak="true">
        <main className="grid w-full grow grid-cols-1 place-items-center">
          <div className="w-full max-w-[26rem] p-4 sm:px-5">
            <div className="text-center">
              <img className="mx-auto w-32" src="assets/images/logo.png" alt="logo"/>
              <div className="mt-4">
                <h2 className="text-2xl font-semibold text-slate-600 dark:text-navy-100">
                  Welcome Back
                </h2>
                <p className="text-slate-400 dark:text-navy-300">
                  Please sign in to continue
                </p>
              </div>
            </div>
            <form onSubmit={handleLogin} className="card mt-5 rounded-lg p-5 lg:p-7">
              <label className="block">
                <span>Username:</span>
                <span className="relative mt-1.5 flex">
                  <input className="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-9 placeholder:text-slate-400/70 hover:z-10 hover:border-slate-400 focus:z-10 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" placeholder="Enter Username" type="email" id="email" required/>
                  <span className="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 transition-colors duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                    </svg>
                  </span>
                </span>
              </label>
              <label className="mt-4 block">
                <span>Password:</span>
                <span className="relative mt-1.5 flex">
                  <input className="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-9 placeholder:text-slate-400/70 hover:z-10 hover:border-slate-400 focus:z-10 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" placeholder="Enter Password" type="password" id="password" required/>
                  <span className="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 transition-colors duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                    </svg>
                  </span>
                </span>
              </label>
              
    {error && (<div class="alert flex space-x-2 rounded-lg border border-error px-4 py-4 text-error">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
    </svg>
    <p>{error === 'Login Successful!' ? 'Success!' : error}</p>
    </div>)}

      <p className="error-message"></p>
                <button type="submit" className="btn mt-5 w-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">Login</button>
            </form>
          </div>
        </main>
      </div>

      <div id="x-teleport-target"></div>
    </div>
  );
};

export default Login;

the package.json

{
  "name": "admin-panel",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.11.4",
    "@emotion/styled": "^11.11.0",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^10.8.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.22.3",
    "react-scripts": "^3.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8000",
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Finally the Dashboard.js component

import React, { useState, useEffect } from 'react';
import { useAuth } from './AuthContext'; // Import useAuth hook

const Dashboard = () => {
  const { currentUser } = useAuth(); // Access currentUser from AuthContext
  const [error, setError] = useState(null); // State for error message

  // Fetch error data from your backend or state management solution (if applicable)
  useEffect(() => {
    const fetchErrorData = async () => {
      try {
        // Replace with your actual error data fetching logic (e.g., API call)
        const response = await fetch('/api/dashboard/errors'); // Example API call
        const errorData = await response.json();
        setError(errorData?.message); // Update error state with fetched message
      } catch (error) {
        console.error('Error fetching error data:', error);
      }
    };

    fetchErrorData();
  }, []);

  return (
    <div className="dashboard-container">
      <h1 className="dashboard-heading">Welcome, {currentUser.displayName || currentUser.email}!</h1>
      {error && (
        <div className="error-log alert alert-error">
          <svg className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.7-7.29a4 4 0 00-2.82-2.82L13.7 6.9l-1.41-1.41a4 4 0 00-2.82 2.82l-1.41 1.41L6.9 13.7a4 4 0 002.82 2.82L10 16.1l1.41 1.41a4 4 0 002.82-2.82l1.41-1.41z" clipRule="evenodd" />
          </svg>
          <p>{error}</p>
        </div>
      )}
      <p className="dashboard-message">You are now logged in to your dashboard.</p>

      {/* Additional dashboard content and features go here */}
    </div>
  );
};

export default Dashboard;

i almost tried everything without any success
also i browser consoel i got the following error :
Uncaught SyntaxError: Identifier ‘observeDomChanges’ has already been declared (at ruleApplier.js:1:1)

but there is no ruleApplier.js in the project at all
and the docx for react and firebase have nothing about it 🙁
anyone faced such issue ?!!
any suggestion will be helpful at this point 😀

Cors error occur while fetch request in chrome extension’s content-script except https://api.openai.com

i’ve tried fetch request such as https://slack.com/XXX or https://gateway.ai.cloudflare.com/XXX in content-script.js but they all got blocked CORS Error, except https://api.openai.com, even if i change my computer or network, can someone tell me why and what’s the solution , thx ~

enter image description here
enter image description here
enter image description here

how can i fetch the urls except “https://api.openai.com” in content-script.js and won’t blocked by CORS Error

Customizing Step Indicator in React Native

I create this step indicator using react-native-step-indicator

enter image description here

I want to customize the labels inside the indicator to show symbols instead of numbers, similar to this image:

enter image description here

I have tried various approaches but couldn’t find a way to achieve this.

Below is my current code:

  <StepIndicator
            stepCount={getStepsData?.getSteps?.length}
            customStyles={styles.customStyles}
            currentPosition={activePosition}
            direction="vertical"
            labels={getStepsData?.getSteps?.map((step) => step.name)}
            onPress={(position) => setActivePosition(position)}
            renderLabel={({ position, stepStatus, label, currentPosition }) => {
              return (
                <View key={position}>
                  <Text style={position === activePosition ? styles.pressedTitle : styles.title}>{getStepsData?.getSteps[position].name}</Text>
                  {position === activePosition &&
                    <Text style={styles.stepDescription}>{getStepsData?.getSteps[position].description}</Text>
                  }
                </View>
              );
            }}
          />    

Custom Styles:

customStyles: {
        stepIndicatorSize: 30,
        labelAlign: 'flex-start',
        currentStepIndicatorSize: 40,
        separatorStrokeWidth: 3,
        currentStepStrokeWidth: 5,
        stepStrokeCurrentColor: Colors.DeepGreen,
        separatorFinishedColor: Colors.DeepGreen,
        separatorUnFinishedColor: Colors.DeepGreen,
        stepIndicatorFinishedColor: Colors.DeepGreen,
        stepIndicatorUnFinishedColor: Colors.DeepGreen,
        stepIndicatorCurrentColor: Colors.white,
        stepIndicatorLabelFontSize: 15,
        currentStepIndicatorLabelFontSize: 15,
        stepIndicatorLabelCurrentColor: '#000000',
        stepIndicatorLabelFinishedColor: Colors.white,
        stepIndicatorLabelUnFinishedColor: Colors.white,
        labelColor: Colors.DarkSlate,
        labelSize: 15,
        currentStepLabelColor: Colors.DeepGreen,
    },

‘Cannot find module ‘framework7-vue/bundle’ or its corresponding type declarations’ on brand new project. What needs to be changed?

I am trying to learn a stack to use Vue to make mobile apps. I ended up finding that people use Capacitor + Framework7, so I created a new project and followed the installation guides for both Capacitor and Framework7. The problem is I’m getting an error when trying to include registerComponents in that it can’t find framework7-vue/bundle. I can see it being exported in the package, so I’m curious if anyone has a solution to this? I had to change the Framework7 import to something that wasn’t referenced in the docs so I’m wondering if that is the case for the framework7-vue/bundle import as well?

This is my main.ts, very bare bones as I am just beginning with this project.

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

import Framework7 from "framework7/lite/bundle";
import Framework7Vue, { registerComponents } from "framework7-vue/bundle";

Framework7.use(Framework7Vue);

const app = createApp(App);
registerComponents(app);

app.use(router).mount("#app");

I’ve tried importing from some of the different classes exposed in the framework7-vue package, to no avail. There was a user in the framework7 forum that had experienced the same issue, but there was no solution there

javascript stored procedure in snowflake logic

I have a snowflake table like this.
enter image description here

i want to have a SCD type 2 table based on the table shown above. The logic is, when

1.) ID’s are the same

2.) data in the table on a given day is always the date for that day and that day – 1 (today and yesterday). At any given time, there is only data for 2 days in the table.

if a owner has been added between today and yesterday, then i need to populate the table in snowflake below like this.

enter image description here

How do I do this using a javascript stored procedure in snowflake? It would be very helpful if you can provide a solution for this.

How to connect Button in activity main…java, android studio

I created Live Streaming application by using ZegoCloud. Everything is working but now I want to replace buttons, in video example was Name,id, and then you click go live and Live stream starting. How can I make…click on button and go live directly without typing my name? Because registration page I created now separate….and if host wants to go live them can make it by just clicking on button and start live, no need entre name or id many times, same for customers…sorry I’m new in it. I hope for your help.))))
If you have any source code for streaming application would be happy, like Liveme, bigo….just to understand how to connect Button

I tried to change it in activity main but was error

Button startLiveButton = findViewById(R.id.start_live_button);

    startLiveButton.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

And sorry no clue what to do next
Java

Why won’t my binary search work for numbers that are double digits? [duplicate]

My binary search only works for single digits. I am trying to run a very simple React program to visualize a binary search but for now, the basic search will not work. Here are all the important parts for that code.

function binarySearch(arr, val) {
    let start = 0;
    let end = arr.length - 1;
  
    while (start <= end) {
      let mid = Math.floor((start + end) / 2);
  
      if (arr[mid] === val) {
        return mid;
      }
  
      if (val < arr[mid]) {
        end = mid - 1;
      } else {
        start = mid + 1;
      }
    }
    return -1;
  }
 

export const BinarySearch = () => {
    const [outputArea, setOutputArea] = useState('');


    const runSearch = (arr, x) => {
        const searched = binarySearch(arr, x);
        setOutputArea(searched + 1);
    }
    


    return (

        <div>
            Enter List: <input type="text"
                        id="listEntry" />
            Enter Number: <input type="text"
                        id="numberEntry" />

            <button type="button"
            onClick={(e) => runSearch(document.getElementById("listEntry").value.split(","), document.getElementById("numberEntry").value)}
            ></button>

            <textarea name="output"  cols="30" rows="10" value={outputArea}></textarea>



        </div>

    );

I tried looking at different versions of the search but no options available have worked. The length of the array does not matter as long as the target number is a single digit.

function binarySearch(arr, val) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    let mid = Math.floor((start + end) / 2);

    if (arr[mid] === val) {
      return mid;
    }

    if (val < arr[mid]) {
      end = mid - 1;
    } else {
      start = mid + 1;
    }
  }
  return -1;
}

const runSearch = (arr, x) => {
  return binarySearch(arr, x);
  setOutputArea(searched + 1);
}
<div>
  Enter List: <input type="text" id="listEntry" /> Enter Number: <input type="text" id="numberEntry" />

  <button type="button" onclick="document.getElementById('output').value = runSearch( document.getElementById('listEntry').value.split(','), document.getElementById('numberEntry').value)">Search</button>

  <textarea id="output" name="output" cols="30" rows="10"></textarea>


</div>

Issue with Postback and ScriptManager.RegisterStartupScript not working

I am using ASP.net with VB.net code behind.

The page is successfully using ScriptManager.RegisterStartupScript to execute a Javascript function from multiple asp:DropdownList OnSelectedIndexChanged events. Each dropdown has the property AutoPostBack=”True”. In these cases, the code behind and the ScriptManager both execute flawlessly.

I needed to add (3) asp:RadioButtons. Each using OnCheckedChanged and with AutoPostBack=”True” like the Dropdowns. Unlike the DropDowns, all the code in the code behind executes as expected except the ScriptManager. It appears to be the only thing that consistently fails and it always fails on the combination of RadioButton and OnCheckChanged.

I tried changing the position of the ScriptManager from last element of code to the first. Tried removing all the code but the ScriptManager and it still fails.

I tied my javascript function to a button so after the page rendered, I could confirm my function works. It does.

I tried adding an onclick event. Let it call the function directly with return. It works running the javascript but doesn’t run the OnCheckedChange code behind. Looking like this:
<asp:RadioButton runat="server" ID="radApptN" value="A" GroupName="radAppt" text=" Add New" AutoPostBack="true" checked="true" onclick="return gotoCalView();" OnCheckedChanged="radAppt_OnChanged" />

If I put the script call into the Body Onload it works but, I don’t want it to fire all the time.

Thought it might have something to do with the PostBack not processing the same as OnSelectedIndexChanged. I tried the following. Didn’t work.

Page.ClientScript.RegisterStartupScript(me, me.GetType(),"CallView","window.onload = function(){ gotoCalView(); }",true)

Should this not work like putting into the Body Onload call?

After reading sample posts there were a lot of questions about using an Update Panel. I am not in this page.

Any suggestions to try that maybe I missed? Feel like i hit a brick wall.

Solidity Smart Contract & Hedera Hashgraph Javascript Integration

I am dealing with an issue with a codebase that was previously working fine, but now it’s not working as expected.

Context
The Smart Contract JobPost provides a decentralized platform for job postings, allowing users to create, update, and retrieve job listings. It introduces two events, JobPostCreated and JobPostUpdated, to emit notifications upon job creation and updates, enhancing the contract’s transparency and providing hooks for off-chain applications to react to these changes.

The Hashgraph Javascript script:
The JavaScript code interacts with the Hedera network to deploy and interact with the JobPost contract.

The Issue
My issue is that when I try to post a new job, it says that the job was successfully created, but whenever I try to fetch the javascript code, it returns an empty element, meaning that it seems like the job was not successfully posted to the blockchain with its parameters.

Snippets of the source code

Smart contract:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

pragma experimental ABIEncoderV2;

contract JobPost {
    struct Job {
        uint256 jobId;
        string jobTitle;
        string paymentMethod;
        string accountId;
        address account;
    }

    enum paymentMethods {
        CASH,
        DEBIT,
        CREDIT,
        CRYPTO
    }

    event JobPostCreated(
        uint256 jobId,
        string jobTitle,
        string paymentMethod,
        string accountId,
        address account
    );

    event JobPostUpdated(
        uint256 _jobId,
        string _jobTitle,
        string _paymentMethod,
        address _account,
        string _accountId
    );

    // mapping(uint => Job) JobsByIndex;
    mapping(address => Job[]) JobsByAccount;
    uint256 public jobCounter = 0;

    constructor() {}

    function newJobPostByAccount(
        string memory _jobTitle,
        string memory _paymentMethod,
        string memory _accountId
    ) public {
        jobCounter++;
        JobsByAccount[msg.sender].push(
            Job({
                jobId: jobCounter,
                jobTitle: _jobTitle,
                paymentMethod: _paymentMethod,
                accountId: _accountId,
                account: msg.sender
            })
        );

        emit JobPostCreated(
            jobCounter,
            _jobTitle,
            _paymentMethod,
            _accountId,
            msg.sender
        );
    }

    function getOneJobPostByAccount2(
        address _account,
        uint256 _jobId
    )
        public
        view
        returns (
            address account,
            string memory accountId,
            uint256 jobId,
            string memory jobTitle,
            string memory paymentMethod
        )
    {
        // require(_account <= jobCounter);
        Job[] storage jobs = JobsByAccount[_account];
        for (uint256 index = 0; index < jobs.length; index++) {
            if (jobs[index].jobId == _jobId) {
                return (
                    jobs[index].account,
                    jobs[index].accountId,
                    jobs[index].jobId,
                    jobs[index].jobTitle,
                    jobs[index].paymentMethod
                );
            }
        }
    }

    function getOneJobPostByAccount(
        address _account,
        uint256 _jobId
    ) public view returns (Job memory job) {
        // require(_account <= jobCounter);
        Job[] storage jobs = JobsByAccount[_account];
        for (uint256 index = 0; index < jobs.length; index++) {
            if (jobs[index].jobId == _jobId) {
                return (jobs[index]);
            }
        }
        // return (0,"","",0x0);
    }

    function updateJobPostByAccount(
        uint256 _jobId,
        string memory _jobTitle,
        string memory _paymentMethod,
        address _account,
        string memory _accountId
    ) public {
        Job[] storage jobs = JobsByAccount[_account];
        require(_jobId <= jobCounter);
        // require(jobs, "This user does not exist");
        require(jobs.length > 0, "No Job post exists for this user");
        for (uint256 i = 0; i < jobs.length; i++) {
            if (jobs[i].jobId == _jobId) {
                jobs[i].jobTitle = _jobTitle;
                jobs[i].paymentMethod = _paymentMethod;
                jobs[i].account = _account;
                jobs[i].accountId = _accountId;
            }
        }
        emit JobPostUpdated(
            _jobId,
            _jobTitle,
            _paymentMethod,
            _account,
            _accountId
        );
    }

    function getAllJobsByAccount(
        address _account
    ) public view returns (Job[] memory) {
        Job[] storage jobs = JobsByAccount[_account];
        // require(jobs.length > 0, "No Job post exists for this user");
        if (jobs.length > 0) {
            return jobs;
        } else {
            Job[] memory emptyJobs;
            return emptyJobs;
        }
    }
}

Javascript Code

console.clear();
require("dotenv").config({ path: "../.env" });

const {
  Client,
  AccountId,
  PrivateKey,
  Hbar,
  FileCreateTransaction,
  FileAppendTransaction,
  ContractCallQuery,
  ContractCreateTransaction,
  ContractFunctionParameters,
  ContractExecuteTransaction,
} = require("@hashgraph/sdk");
const fs = require("fs");

const Web3 = require("web3");
const web3 = new Web3();

// console.log(process.env.HEDERA_ACCOUNT_ID);
const operatorId = process.env.HEDERA_ACCOUNT_ID;
const operatorKey = PrivateKey.fromStringECDSA(process.env.HEDERA_PRIVATE_KEY);

const bytecode = require("../build/contracts/JobPost.json", "utf8").bytecode;
const abi = require("../build/contracts/JobPost.json", "utf8").abi;
let bytecodeFileId;

const client = Client.forTestnet().setOperator(operatorId, operatorKey);

// Deploy the smart Contract to Hedera (createContractBytecodeFileId + uploadByteCode + instantiateContract)
await deploySmartContract(client, operatorKey, bytecode, 3000000, 10);

// Create a New Job Post
  await newJobPostByAccount(
    client,
    contractId,
    operatorId,
    "Job Post #1",
    "CASH"
  );

// Get One Job Post By Account
  await getOneJobPostByAccount2(
    client,
    "getOneJobPostByAccount2",
    contractId,
    operatorId,
    2
  );

async function newJobPostByAccount(
  _client,
  _contractId,
  _accountId,
  _title,
  _paymentMethod,
  _gas = 3000000
) {
  const contractExecTx = await new ContractExecuteTransaction()
    .setContractId(_contractId)
    .setGas(_gas)
    .setFunction(
      "newJobPostByAccount",
      new ContractFunctionParameters()
        .addString(_title)
        .addString(_paymentMethod)
        .addString(_accountId)
    );
  const contractExecSubmit = await contractExecTx.execute(_client);
  const contractExecRx = await contractExecSubmit.getReceipt(_client);
  console.log(contractExecRx);
  console.log(`nCREATING A NEW JOB POST ======= n`);
  console.log(`- New Job Post Created: ${contractExecRx.status.toString()}`);
  console.log(`nRETRIEVE A JOB POST BY ACCOUNT ======= n`);
}


async function getOneJobPostByAccount2(
  _client,
  _functionName,
  _contractId,
  _accountId,
  _jobId,
  _gas = 100000,
  _queryPaymentInHBars = 2
) {
  const contractQuery = await new ContractCallQuery()
    //Set the gas for the query
    .setGas(_gas)
    //Set the contract ID to return the request for
    .setContractId(_contractId)
    //Set the contract function to call
    .setFunction(
      _functionName,
      new ContractFunctionParameters()
        .addAddress(AccountId.fromString(_accountId).toSolidityAddress())
        .addUint256(_jobId)
    )
    //Set the query payment for the node returning the request
    //This value must cover the cost of the request otherwise will fail
    .setQueryPayment(new Hbar(_queryPaymentInHBars));

  //Submit to a Hedera network
  const contractExec = await contractQuery.execute(_client);
  // console.log(contractExec);
  console.log(`nRETRIEVE A JOB POST BY ACCOUNT ======= n`);
  console.log(
    `- New Job Post Account Owner: ${await contractExec.getString(0)}`
  );
  // console.log(`- New Job Post Created2: ${await contractExec.getString(1)}`)
  console.log(`- New Job Post Title: ${await contractExec.getString(2)}`);
  console.log(
    `- New Job Post Payment Method: ${await contractExec.getString(3)}`
  );
  const res = await decodeFunctionResult(_functionName, contractExec.bytes);
  console.log(res[0]);
  return res[0];
}

Contact Form 7 v7.5.9.3 is not working correctly

Please test form at website footer

I have a custom Contact Form 7 for email address optin.

I created a custom confirmation thank you div via javascript that replace the place of the form.

The new v7.5.9 upgrade is now refreshing the page on every submit and my custom confirmation is not working.

Here is the form:

      <div class="optWRAP">
    <div class="mailICON"></div>
   <div class="srchWRAP_ft">
       <h2>Get Email Updates on New Shirts, Events, and Sales</h2>
       <div class="fldWRP">
       <div class="emailADDR">[email* kooraw id:email placeholder "enter email address"]</div>
     [submit "Sign Me Up"]
  </div>
  <div class="disclaim">By signing up via email, you agree to receive periodical emails from KOORAW. Consent is not a condition of any purchase. View <a href="https://kooraw.com/terms">Terms</a> & <a href="https://kooraw.com/privacy">Privacy</a>.   </div>
  <div class="validTHK" style="display: none;">
     <div class="thk">Thank you!</div>
     <div class="thkTXT">We received your email, and we'll send you updates.</div>
  </div>
  </div>
  </div>

Here is the javascript:

   addEventListener('wpcf7mailsent', function(event) {
    event.preventDefault();
    document.querySelector('.fldWRP').style.display = 'none';
    document.querySelector('.disclaim').style.display = 'none';
    document.querySelector('.validTHK').style.display = 'block';
    setTimeout(function() {
    document.querySelector('.fldWRP').style.display = 'flex';
    document.querySelector('.disclaim').style.display = 'flex';
    document.querySelector('.validTHK').style.display = 'none';
    }, 10000);
    });
 

enter image description here

Pagination problem with ajax page loading

I have some links on the WordPress archive page that I want to load their content without reloading the page
I was able to do this with the code below, but the problem is that the pagination doesn’t load properly!
My theme uses an Ajax pagination that loads the next page by scrolling.
When we are on the main page of the archive and we go to the second page without clicking on the links, and then we click on a link, the Ajax pagination is not loaded on that page! But if we do not go to the second page on the main page of the archive and click on the link, the Ajax pagination will be loaded correctly in that link.
It seems that Ajax pagination is loaded and working only once in every page reload, how can I solve the pagination problem?

<script>
    jQuery(document).ready(function($) {
        $('.tag-cattab a').on('click', function(e) {
            e.preventDefault();
            $('.tag-cattab a').removeClass('active');
            $(this).addClass('active');
            var tabLink = $(this).attr('href');
            $('.row.posts').empty();
            $.ajax({
                url: tabLink,
                type: 'GET',
                success: function(response) {
                    $('.row.posts').html($(response).find('.row.posts').html());
                },
                error: function(error) {
                    console.log('Error: ', error);
                }
            });
        });

        $('.tag-cattab a').click(function(e) {
            e.preventDefault();
        });
    });
</script>
    <div class="tag-cattab">
        <a rel="nofollow" href="https://example.com/blog/tag/photoshop/?cat=1584" class="ntab"><div class="tcattab" >buttontitle1</div></a>
        <a rel="nofollow" href="https://example.com/blog/tag/photoshop/?cat=1588" class="ntab"><div class="tcattab" >buttontitle2</div></a>
    </div>

theme archive code:

<div class="row posts">
    <?php while ( have_posts() ) : the_post();
        azin_post_archive_content( get_the_ID(), $col );
    endwhile; ?>
</div>

<div class="col-12 pagination">
    <?php wp_pagination(); ?>
</div>

<?php
//Ajax Load More
if( azin_opt( 'ajax_prod' ) ) {
    ?>
    <div class="col-12 load-more">
        <div class="page-load-status">
            <p class="infinite-scroll-request"><i class="fal fa-spinner-third fa-spin" aria-hidden="true"></i></p>
        </div>
        <span id="load-more-button" class="load-more-button btn azin-btn btn-lg"><?php _e( 'Load More Posts', 'azin-file') ?></span>
    </div>
<?php } ?>

Here we load the content of the links without updating the url and reloading.
I’m not sure what this ajax will do with the cache.
But it would be better if we could update the url of the page but not reload the page (only if it’s better for the cache).

I’m beginner, thanks for the help.
Here’s the problem: B2n.ir/m68190