How to load application.js build by webpack using sprockets

I’m moving an elderly application from rails 5.x to 7.2. Most things are working except loading application.js.

After following the migration guide and moved to jsbundling-rails, I have two application.js files

app/assets/javascripts/application js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the     bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require_tree .

app/javascript/application.js

// Entry point for the build script in your package.json
import jQuery from "jquery";
import "bootstrap";

The application.js is used by yarn properly but the results are not included in the served html.

How can I tell sprockets to use the js output generated by webpack / jsbundling-rails?

Unable to upload image from my React-Native app to Appwrite

I have create a React-Native code to upload images to my appwrite storage but i am not able to and getting error. Can anyone please review the code and give me a concrete answer

My appwrite logic –

const client = new Client();

client
  .setEndpoint(appwriteConfig.endpoint) // Your Appwrite Endpoint
  .setProject(appwriteConfig.projectId) // Your project ID
  .setPlatform(appwriteConfig.platform); // Your application ID or bundle ID.

const account = new Account(client);
const avatar = new Avatars(client);
const databases = new Databases(client);
const storage = new Storage(client);

export const uploadImageToAppwrite = async (urin) => {
  try {
    const result = await storage.createFile(
      appwriteConfig.storageId,
      ID.unique(),
      {
        name: "photo.jpg",
        type: "image/jpg",
        uri: urin,
      },
      [
        Permission.read(Role.any()),
        Permission.update(Role.users()),
        Permission.delete(Role.users()),
      ]
    );

    console.log("File uploaded successfully:", result);
  } catch (error) {
    console.error("File upload failed:", error);
  }
};`

Here urin is the file path “file:///data/user/0/com.anonymous.ecommerce/cache/rn_image_picker_lib_temp_84dae6a9-44fb-4146-a7d6-ad80081a09f3.jpg”

I have used blob also but it also is not working. Currently in the above code i get this output in the log =

LOG  File uploaded successfully: undefined

Any help is much appreciated

I tried the above code i gave and file should be uploaded in DB but I am getting output as undefined

TypeError: builder.resolve is not a function

here’s my code

import { TelegramClient } from "telegram";
import input from "input";
import fs from "fs";
import { NewMessage } from "telegram/events/event.js";

const apiId = 123456;

const apiHash = "1234567890";

const phone = '+123456789';

const sessionFilePath = './session.txt';

let savedSessionString = "";

if (fs.existsSync(sessionFilePath)) {
  savedSessionString = fs.readFileSync(sessionFilePath, 'utf-8');
}

const stringSession = new StringSession(savedSessionString);

(async () => {
  const client = new TelegramClient(stringSession, apiId, apiHash, {
    connectionRetries: 5,
  });

  async function eventPrint(event) {
    const messageText = event.message.message;
   
    if (messageText.startsWith('.try') && event.message.fromId && event.message.fromId.userId === (await client.getMe()).id) {
      await client.sendMessage("me", { message: "Hello!" });
    }
  }

  try {
    await client.start({
      phoneNumber: async () => phone,
      password: async () => await input.text("Enter password:"),
      phoneCode: async () => await input.text("Enter code:"),
      onError: (err) => console.error(err),
    });

    console.log("Connection successful!");

    const sessionString = client.session.save();
    fs.writeFileSync(sessionFilePath, sessionString, 'utf-8');

    client.addEventHandler(eventPrint, new NewMessage({}));

  } catch (error) {
    console.error("Error during login:", error.message);
  }
})();

This code summarizes a tool for authorization in telegram and after using userbot to expand the capabilities telegram, but i was only able to write that i can send myself messages in “Save messages”.

Here is a snippet of the code

await client.sendMessage("me", { message: "Hello!" }); })();

my idea was to start by writing “.try” so that to send me a message in “Save message”, or i had an idea to change it to the word i want, but i got an error every time.

` await builder.resolve(client);
^

TypeError: builder.resolve is not a function`

replaced client.on('newMessage', eventPrint) with client.addEventHandler(eventPrint,newMessage'),

tried other methods

How to print a text file from a web page on a button click

I’m building an html/css/js application, no additional libraries.

The application collects some data from the user and, when he clicks the ‘COMPILE’ button, the data is processed in a certain way and displayed in a div.

I would like that when the user clicks the button the application creates a log file, i.e. a text file saved in a certain directory, containing in textual form the state of the application at the time of the click.

How can I create a text file from a web page?

Problems of removing and redrawing the overlays after applying for leaflet.greatCircle.js

the layers remained

  1. I am running a small web project using Open Street Map using leaflet.
  2. Since OSM doesn’t take earth’s curvature into account. It drew a simple straight polyline.
  3. I found leaflet.greatCircle.js on the internet and applied to my twilight overlays and measurement functions
  4. However the layers are not removed properly causing them to keep stacking up each other
  5. I asked gpt to find out what the problem is, and I am replied to modify removing and redrawing layers. I followed its suggestions however the issue persists.

changed the handling of removing and redrawing functions after chatgpt solutions

remove: function () {
    if (this._polygon) this._polygon.remove();
    if (this._circle) this._circle.remove();
    if (typeof this._circles !== "undefined") {
        if (this._circles.length > 0) {
            for (var i in this._circles) {
                this._circles[i].remove();
            }
        }
        this._circles = undefined;
    }
    this._addedToMap = false;
},

Solana transaction confirmation error after successful transaction

   async function makePayment() {
        try {
            setProcessing(true);
            
            let success = false;
            while (!success) {
                const transaction = new Transaction().add(
                    SystemProgram.transfer({
                        fromPubkey: publicKey!,
                        toPubkey: new PublicKey("BEwvWR2TjmkgPJ8kCBFkqHNRGDuVWH4AyvnFCiFaEcAs"),
                        lamports: 22348000, // 0.022348 sol // 3.10 usd  // 260 inr
                    })
                );
    
                const { context: { slot: minContextSlot }, value: { blockhash, lastValidBlockHeight } } = await connection.getLatestBlockhashAndContext();
    
                const signature = await sendTransaction(transaction, connection, { minContextSlot });
                
                try {
                    await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight });
                    success = true;
                    console.log("Payment succeeded with signature:", signature);
                    setTxSignature(signature);
                    alert("Payment success. Now add task!");
                } catch (confirmationError) {
                    console.warn("Confirmation failed, retrying with a new blockhash...", confirmationError);
                }
            }
        } catch (err) {
            setProcessing(false);
            console.error("Payment failed:", err);
            alert("Payment failed. Please try again.");
        } finally {
            setProcessing(false);
        }
    }

After initiating the transaction of the mentioned lamports, it is getting success but confirmation is giving following error:

upload.tsx:63 Confirmation failed, retrying with a new blockhash… TransactionExpiredBlockheightExceededError: Signature 64UmRfE4D5y1T9gGi2aV4m2Y13gqn3WgUHhfRmRrcyCT4b7xYfnanvZrnDntjuz4eqjQMEchQHcwFnWfNnCP3Gf2 has expired: block height exceeded.
at Connection.confirmTransactionUsingBlockHeightExceedanceStrategy (connection.ts:4059:15)
at async Connection.confirmTransaction (connection.ts:3870:14)
at async makePayment (upload.tsx:57:21)

I tried changing the factor of verifying transaction to only signature and it is showing the strategy is deprecated

Integrating search train API

I’m currently working on a travel companion project, and so I need to fetch data for both direct and indirect trains between stations in India. During my research, I couln’t find any apis or ways that meets my requirements with its direct train search and via station indirect train search features.

I’m reaching out to see if anyone knows of any APIs or methods to fulfill my needs.

Any advice or recommendations would be greatly appreciated!

Thanks in advance!

Twitch API send message not working using websockets

so I am creating a EventSub via websockets once the websocket is open then it waits for a notification (“message”) and it will send a message to the chat of the broadcaster that works well but then if you try to do that a second time it doesnt do it. it console logs it but it doesnt appear on the chat on twitch. when i console log the data of the sent message the message id is the exact same one for all the messages

    let websocketSessionID;
    
    // Function to start the WebSocket client
    function startWebSocketClient() {
      const websocketClient = new WebSocket(EVENTSUB_WEBSOCKET_URL);
    
      websocketClient.onopen = () => {
        console.log('WebSocket connection opened to ' + EVENTSUB_WEBSOCKET_URL);
      };
    
      websocketClient.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
    
      websocketClient.onmessage = (event) => {
        try {
          const dataInfo = JSON.parse(event.data);
          console.log('Received WebSocket message:', dataInfo);
    
          if (dataInfo.metadata.message_type === 'session_welcome') {
            websocketSessionID = dataInfo.payload.session.id;
            console.log('WebSocket Session ID:', websocketSessionID);

        // Call the function to subscribe to the event once the session ID is received
        subscribeToChatMessage();
      }

      if (dataInfo.metadata.message_type === 'notification') {
        console.log('Notification received:', dataInfo.payload.event);
        console.log('Message Text:', dataInfo.payload.event.message.text);

        // Call the function to send a chat message
        sendChatMessage('Hello, world! I am testing this thing out');
      } } catch (error) {
      console.error('Error processing WebSocket message:', error);
    }
  };
}

// Function to subscribe to the channel.chat.message event
function subscribeToChatMessage() {
  const url = 'https://api.twitch.tv/helix/eventsub/subscriptions';
  const accessToken = OAUTH_TOKEN;
  const clientId = CLIENT_ID;

  const requestBody = {
    type: 'channel.chat.message',
    version: '1',
    condition: {
      user_id: BOT_USER_ID,
      broadcaster_user_id: CHAT_CHANNEL_USER_ID
    },
    transport: {
      method: 'websocket',
      session_id: websocketSessionID,
    },
  };

  const options = {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${accessToken}`,
      'Client-Id': clientId,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestBody),
  };

  fetch(url, options)
    .then((response) => {
      if (!response.ok) {
        return response.json().then((errorData) => {
          throw new Error(`Request failed: ${errorData.message}`);
        });
      }
      return response.json();
    })
    .then((data) => {
      console.log('Subscription created successfully:', data);
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}

function sendChatMessage(message) {
  const url = 'https://api.twitch.tv/helix/chat/messages';
  const accessToken = OAUTH_TOKEN;
  const clientId = CLIENT_ID;

  const requestBody = {
    broadcaster_id: CHAT_CHANNEL_USER_ID,
    sender_id: BOT_USER_ID,
    message: message
  };

  const options = {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${accessToken}`,
      'Client-Id': clientId,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestBody),
  };

  fetch(url, options)
    .then((response) => {
      if (!response.ok) {
        return response.json().then((errorData) => {
          throw new Error(`Request failed: ${errorData.message}`);
        });
      }
      return response.json();
    })
    .then((data) => {
      console.log('Chat message sent successfully:', data);
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}

// Start the WebSocket client
startWebSocketClient();

Make Enable/Disable of ComboBox2 based on value from another ComboBox1 and set the value of ComboBox2

I have a question.I am working on a Classic ASP website.
So this question is related to VBSCRIPT and JavaScript and sql server.

I have a database table [test_table].On the website there are 2 comboboxes : ComboBox 1 and ComboBox 2.

When the page is shown ,
I will populate my ComboBox 1 with data from [test_table] Setting the ComboBox 1 value with t00_test_cd and text with (t00_test_cd : t00_test_name ) format. If there is No data or records in 「test_table」ComboBox 1 ‘s value is “” and text is blankspace.

ComboBox 2 is populated with the following value and text (value:0 is selected)

「value : 0 , text : text0」
「value : 1 , text : text1」
「value : 2 , text : text2」

When I change the ComboBox 1 value which is t00_test_cd , ComboBox 2 is Disabled or Enabled Base on t00_combo2_display.

(t00_combo2_display → 0:comboBox 2 disabled and comboBox 2 value should be set with t00_combo2_val)
(t00_combo2_display → 1:comboBox 2 enable and comboBox 2 is selected with value 0 and text text0 and user can choose the comboBox 2 value)

「test_table」

t00_timestamp t00_test_cd t00_test_name t00_combo2_display t00_combo2_val
2024-08-31 11:57:41.773 01 test_01 0 0
2024-08-31 11:57:41.773 02 test_02 1 2

Explanation of 「test_table」values

t00_test_cd → populate the Combo Box 1’s value (and text)

t00_test_name → populate the Combo Box 1’s text (t00_test_cd : t00_test_name) for example, (01 : test_01)

t00_combo2_display → 0 is Combo Box 2 disabled and Combo Box 2 value will be t00_combo2_val.
→ 1 is Combo Box 2 enable and user can choose Combo Box 2 value of「value : 0 , text : text0」 「value : 1 , text : text1」 「value : 2 , text : text2」

t00_combo2_val → when t00_combo2_display is 0 , Combo Box 2 value is set with t00_combo2_val.t00_combo2_val can be 「0」「1」「2」.

I have tried to query Combo Box 1 value from test_table and populate the Combo Box 2 value with default「0,1,2」.After that, i don’t know what to do Next.

Code Below


<% @LANGUAGE="VBSCRIPT" %>
<%Option Explicit%><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=Shift_JIS">

<HTML>
</HTML>
<!--#INCLUDE VIRTUAL="/scripts/db/database.asp"-->

<%

Dim DBC,DBC1
Dim RS,RS1
Dim cmd
Dim t00_test_cd
Dim t00_test_name
Dim t00_combo2_display
Dim t00_combo2_val

Call Set_Value



%>

<html>

<body>

<h1>This Is Test Page</h1>

<br>

<h6>
I Want to query from「test_table」and populate the Combo Box 1 with t00_test_cd value(Defalut value is "" and text is blankspace) and Combo Box 2 with (value:0, text0) , (value:1, text1),(value:2, text2)
when the t00_combo2_display is 「0」Combo Box 2 is disabled and value and text will be (value:t00_combo2_val, text0) and user cannot change the Combo Box 2.
when the t00_combo2_display is 「1」Combo Box 2 is enabled and value and text will be (value:0, text0) and user can change the Combo Box 2 value with (value:0, text0) , (value:1, text1),(value:2, text2) .

</h6>


<br>

<TABLE BORDER="0" BGCOLOR="#33d4ff" WIDTH="50%" CELLSPACING="1" CELLPADDING="1">
    <TR VALIGN="MIDDLE">
        <TH NOWRAP ALIGN="left" COLSPAN="8" class="auto-style1">&nbsp;&nbsp;&nbsp;&nbsp;<FONT COLOR="Red">COMBO BOX 1 :</FONT>  </TH>
        <TD NOWRAP ALIGN="center" class="auto-style1"></TD>
    </TR>

    <TR VALIGN="MIDDLE">
        <TD NOWRAP ALIGN="RIGHT" WIDTH="5%">
                                 
        </TD>
        <TD NOWRAP ALIGN="LEFT" COLSPAN="7">
                        
            <SELECT NAME="m49_provider_cd" onchange="ComboChange(providerClsDic)">
            <OPTION VALUE=""></OPTION>
            <%Set DBC1 = ConnectDB("","","","")
            Set RS1 = Server.CreateObject("ADODB.RecordSet")
            RS1.CursorLocation = conCursorLocation
            RS1.Open "SELECT * FROM test_table with(nolock) order by t00_test_cd",DBC1,conCursorType,conLockType,conCommandType
            Set RS1.ActiveConnection = Nothing
            If RS1.EOF<>True Then
            Do While true%>
            <OPTION VALUE="<%=RS1.Fields("t00_test_cd")%>"<%If trim(RS1.Fields("t00_test_cd"))=trim(t00_test_cd) Then Response.Write " SELECTED" End If%>><%="(" & RS1.Fields("t00_test_cd") & ")" & RS1.Fields("t00_test_cd")%></OPTION>
            <%RS1.MoveNext
            If RS1.EOF Then Exit Do
            Loop
            End If
            RS1.Close
            Set RS1 = Nothing
            Call DisConnectDB(DBC1)%>
            </SELECT>
        </TD>
        <TD NOWRAP ALIGN="center">&nbsp;</TD>
    </TR>

    <TR>
        <TD NOWRAP ALIGN="center">&nbsp;</TD>
    </TR>

    <TR VALIGN="middle">
        <TD NOWRAP ALIGN="right" WIDTH="1%">
            <FONT COLOR="Red"> COMBO BOX 2 :</FONT>
        </TD>
        <TD NOWRAP ALIGN="left" COLSPAN="7">
            <SELECT NAME="t00_combo2_val">
                <OPTION VALUE=""
                    <% If trim(t00_combo2_val) = "0" Then   Response.Write " SELECTED" End If   %> >text0</OPTION>
                <OPTION VALUE="1"
                    <% If trim(t00_combo2_val) = "1" Then   Response.Write " SELECTED" End If   %> >text1</OPTION>
                <OPTION VALUE="2"
                    <% If trim(t00_combo2_val) = "2" Then   Response.Write " SELECTED" End If   %> >text2</OPTION>
            </SELECT>
        </TD>
        <TD NOWRAP ALIGN="center">&nbsp;</TD>
    </TR>
</Table>




</body>
</html>

<%
    Sub Set_Value()
        t00_test_cd = ""
        t00_test_name = ""
        t00_combo2_display = ""
        t00_combo2_val = ""

    End Sub
%>

Page is Shown

ComboBox 1 value (01) is selected and ComboBox 2 value is 0 and disalbed

ComboBox 1 value (02) is selected and ComboBox 2 is enabled and user can choose value of (0,1,2)

How to reset the password using Firebase in Reactjs when user logged out?

I use the Firebase 10.13.0 version in my React 18.3.1 and Vite app. I am implementing a reset password. Below is my Reset Password modal which comes after the verification code because I am implementing code base verification and mail using mailjs which is working fine when I am very code for my rest password it comes to the ResetPassword component which is the modal. Everything is working fine, but the problem is that I am logged out and my updatePassword function is not working with bot auth.currentuser(come when login) and user from the snapshot of Firebase Firestore my password is not updating. Please look in the handleResetPassword function I am updating to a way by auth.currentUser which is null because I am logged out and the second is a snapshot from user collection from the Firebase Firestore user is coming but when I pass the user to updatePassword I get TypeError: user.getIdToken is not a Function this error because I am not logged in. How to reset passwords and how to solve this problem. Please help me to resolve this query.

import { IoIosArrowRoundBack } from "react-icons/io";
import Button from "../Button";
import Input from "../Input";
import useAuthModalStore from "../../stores/authModalStore";
import toast from "react-hot-toast";
import * as Yup from "yup";
import { Formik } from "formik";
import { updatePassword } from "firebase/auth";
import { auth, db } from "../../firebase";
import { doc, getDoc } from "firebase/firestore";

const validationSchema = Yup.object().shape({
  password: Yup.string()
    .min(8, "Password must be at least 8 characters long")
    .required("Password is required")
    .matches(
      /(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}/,
      "Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character"
    ),
  confirmPassword: Yup.string()
    .required("Please confirm your password")
    .oneOf([Yup.ref("password")], "Passwords must match"),
});

const initialValues = {
  password: "",
  confirmPassword: "",
};

const ResetPassword = () => {
  const { resetModalType, closeModal, data } = useAuthModalStore();
  const userRef = doc(db, "users", data.id);
  const handleResetPassword = async (values) => {
    // const user = auth.currentUser
    const snapshot = await getDoc(userRef);
    const user = snapshot.data()
    if(user.authProvider !== "email") {
      toast.error("Reset password is only available for email-based authentication");
      return;
    }

    
    try {
      updatePassword(user, values.password);
      closeModal();
      resetModalType();
      toast.success("Password reset successfully");
      // eslint-disable-next-line no-unused-vars
    } catch (error) {
      toast.error("An error occurred while resetting your password");
    }
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={handleResetPassword}
    >
      {({ handleSubmit, values, errors, handleChange, isSubmitting }) => (
        <form onSubmit={handleSubmit} className="space-y-4">
          <Input
            type="password"
            label="Password"
            id="password"
            name="password"
            value={values.password}
            onChange={handleChange}
            error={errors.password}
          />
          <Input
            type="password"
            label="Confirm Password"
            id="confirmPassword"
            name="confirmPassword"
            value={values.confirmPassword}
            onChange={handleChange}
            error={errors.confirmPassword}
          />
          <Button
            width="100%"
            type="submit"
            label="Reset password"
            onClick={() => {}}
            disabled={isSubmitting}
            loading={isSubmitting}
          />
          <p
            onClick={resetModalType}
            className="text-center text-sm font-medium flex items-center justify-center gap-1 cursor-pointer"
          >
            <IoIosArrowRoundBack size={22} />
            Back to Login
          </p>
        </form>
      )}
    </Formik>
  );
};

export default ResetPassword;

I want to prevent numbers and special characters in an input, to force a character in the first position

I have already been successful in doing these other things:

  • prevented first character from being a space using javascript
  • prevented consecutive spaces using javascript
  • forced each word in the input to be capitalized using html
    Now I want to force the first character to be forced a letter, to prevent a number and special character only in the first character.
    I know it can be done but I can not find this helpful code. I have done so much and this is the last thing I need for my form! 😀

This is how I did all of the mentioned above:

function SpaceBlock() {
    var space = document.getElementById("real_name");
        if(space.selectionStart === 0 && window.event.code === "Space"){
            window.event.preventDefault(); } }

function SpaceBlock2() {
    var space = document.getElementById("display_name");
        if(space.selectionStart === 0 && window.event.code === "Space"){
            window.event.preventDefault();} }
            
var lastkey;
var ignoreChars = ' rn'+String.fromCharCode(0);
function ignoreSpaces(e) {
    e = e || window.event;
    var char = String.fromCharCode(e.charCode);
    if(ignoreChars.indexOf(char) >= 0 && ignoreChars.indexOf(lastkey) >= 0) {
        lastkey = char;
        return false; }
    else {
        lastkey = char;
        return true; } }

var lastkey2;
var ignoreChars2 = ' rn'+String.fromCharCode(0);
function ignoreSpaces2(e) {
    e = e || window.event;
    var char2 = String.fromCharCode(e.charCode);
    if(ignoreChars2.indexOf(char2) >= 0 && ignoreChars2.indexOf(lastkey2) >= 0) {
        lastkey2 = char2;
        return false; }
    else {
        lastkey2 = char2;
        return true; } }
<input type="text" name="real_name" placeholder="Real Name" id="real_name" required minlength="6" maxlength="24" tabindex="1" onkeydown="SpaceBlock()" onkeypress="return ignoreSpaces(event);" style="text-transform: capitalize;" >

<input type="text" name="display_name" placeholder="Display Name" id="display_name" required minlength="6" maxlength="24" tabindex="1" onkeydown="SpaceBlock()" onkeypress="return ignoreSpaces(event);" style="text-transform: capitalize;" >

This is the last thing I need for my form, just hoping someone will help. Thanks!

How to Create a Bubble Chart Design Using HTML, CSS, and JavaScript or ReactJS?

I’m trying to create a bubble chart similar to a design I found on Figma, where multiple bubbles containing text are arranged around a central bubble. The design includes glowing effects and hovering animations. You can view the original reference design here: Figma Link.

Here’s what I want to achieve:

A central bubble with text, surrounded by random sized bubbles.
Each bubble should have a glowing effect and a hover animation.bubblechart-design

I Attempted to adjust sizes manually, but this approach is not scalable or dynamic.

What I need help with:

How to dynamically vary the size of each bubble based on the design, possibly using CSS, JavaScript, or ReactJS.
Any existing libraries or approaches in ReactJS that might simplify this design.

Thanks in advance! Any advice or code examples would be very helpful.