问:
Clicking on a button ends up making multiple instances of the Activity it navigates to
So I'm making an app in android studio, its like a fintech app. In one activity/page(SendMoney.java), you put in a number amount and tap the "Send Money" button, from here it goes to the page where you choose who you're sending this money to(SendReceiver.java). You select your desired recepient and tap on a second "Send Money" button, this then takes you to a success page that lists the amount sent and the username of the recepient(SendReceiverSuccessPage).

On the SendMoney page I need to get the amount inputted and pass that data to the SendReceiverSuccessPage, I've done this by using Intent and I've added this code to when the Send Money button is clicked, but in doing this what happens is that it for some reason creates multiple instances of the SendReceiver page it navigates to.
So on the SendReceiver page when I'm done and I hit the second "Send Money" button it just opens a new instance of SendReceiver whiles the SendReceiverSuccessPage is stuck in the background for some reason.

I need it to be one single smooth navigation flow where it goes from SendMoney to SendReceiver to SendReceiverSuccessPage without SendReceiver popping up multiple times and stacking ontop of the success page, all whiles being able to actively pass and retrieve the "AmountSent" data.

SendMoney.java

```<code>

public class SendMoney extends AppCompatActivity {

    FirebaseUser firebaseUser;
    FirebaseAuth firebaseAuth;
    FirebaseDatabase database;

    Context context;
    Double userAmountDouble;
    MaterialButton sendMoneyButton;
    ImageView backspace, back;
    TextView amount, currentBalanceText, currency, one, two, three, four, five, six, seven, eight, nine, zero, dot;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_money);

        this.context = getApplicationContext();

        // Instance of FirebaseAuth and Database
        firebaseAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        // Hooks
        back = findViewById(R.id.back);
        amount = findViewById(R.id.amount);
        currency = findViewById(R.id.currency);
        currentBalanceText = findViewById(R.id.current_balance);

        one = findViewById(R.id.one);
        two = findViewById(R.id.two);
        three = findViewById(R.id.three);
        four = findViewById(R.id.four);
        five = findViewById(R.id.five);
        six = findViewById(R.id.six);
        seven = findViewById(R.id.seven);
        eight = findViewById(R.id.eight);
        nine = findViewById(R.id.nine);
        zero = findViewById(R.id.zero);
        dot = findViewById(R.id.dot);

        backspace = findViewById(R.id.backspace);
        sendMoneyButton = findViewById(R.id.send_money_button);
        sendMoneyButton.setText("Send GH₵0");

        // Display send amount on button, in realtime
        amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //sendMoneyButton.setText("Send GH₵0");
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // This method is called whenever the text in the EditText changes
                String userInputAmount = amount.getText().toString();
                sendMoneyButton.setText("Send GH₵" + userInputAmount);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                //

            }
        });

        // Connect to the database
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
        assert firebaseUser != null;
        // Get and show available balance
        databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String currentBalance = snapshot.getValue(String.class);
                assert currentBalance != null;
                currentBalanceText.setText("GH₵"+ currentBalance + " AVAILABLE");
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // Print an error message
                System.out.println("Error retrieving user main balance: " + error.getMessage());
            }
        });

        // Send Money Button
        sendMoneyButton.setOnClickListener(v -> {
            String userInputAmount = amount.getText().toString();

            if (userInputAmount.equals("") || userInputAmount.equals("0")) {
                Toast.makeText(getApplicationContext(),"Please enter an amount",Toast.LENGTH_SHORT).show();
            } else {
                userAmountDouble = Double.parseDouble(userInputAmount);

                databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        String currentBalance = snapshot.getValue(String.class);
                        assert currentBalance != null;
                        double currentBalanceDouble = Double.parseDouble(currentBalance);

                        if (userAmountDouble > currentBalanceDouble) {
                            Toast.makeText(getApplicationContext(),"Insufficient Balance",Toast.LENGTH_SHORT).show();
                        } else {
                            // Create an Intent and include the value of userInputAmount
                            Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
                            sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
                            sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                            // Start the SendReceiver activity
                            finish();
                            startActivity(sendReceiverIntent);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        // Print an error message
                        System.out.println("Error retrieving user main balance: " + error.getMessage());
                    }
                });
            }
        });

        // Click Listeners
        back.setOnClickListener(v -> finish());
        zero.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("0");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "0");
            }
        });
        one.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("1");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "1");
            }
        });
        two.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("2");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "2");
            }
        });
        three.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("3");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "3");
            }
        });
        four.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("4");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "4");
            }
        });
        five.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("5");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "5");
            }
        });
        six.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("6");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "6");
            }
        });
        seven.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("7");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "7");
            }
        });
        eight.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("8");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "8");
            }
        });
        nine.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("9");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "9");
            }
        });
        dot.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText(".");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + ".");
            }
        });
        backspace.setOnClickListener(v -> {
            if (amount.getText().toString().equals("") | amount.getText().toString().equals("0")) {
                amount.setText("0");
            } else {
                amount.setText(amount.getText().toString().substring(0, amount.getText().length() - 1));
            }
        });
    }
}
</code>```

SendReceiver.java

```<code>

public class SendReceiver extends AppCompatActivity{
    FirebaseUser firebaseUser;
    FirebaseAuth firebaseAuth;
    FirebaseDatabase database;

    Context context;

    ArrayList<SearchedUsersModel> searchedUsersModel;
    RecyclerView searchedUsersRecycler;
    SearchView svSearch;
    MaterialButton finalSendBtn;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sendreceiver);

        // Retrieve the value of userInputAmount from the Intent
        Intent intent = getIntent();
        String userInputAmount = intent.getStringExtra("USER_INPUT_AMOUNT");

        this.context = getApplicationContext();

        // Instance of FirebaseAuth and Database
        firebaseAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        // Hooks
        searchedUsersRecycler = findViewById(R.id.recyclerUsers);
        svSearch = findViewById(R.id.svSearch);
        finalSendBtn = findViewById(R.id.final_send_button);

        // Set the hint for the search bar
        svSearch.setQueryHint("Enter name or email of user");

        // On click listener for when you hit the Send button
        finalSendBtn.setOnClickListener(v -> {
            DatabaseReference databaseReference = database.getReference("Users");
            assert firebaseUser != null;
            databaseReference.child(firebaseUser.getUid()).child("transactions").child("sendTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(userInputAmount);

            // Get a reference to the "transactions" collection
            DatabaseReference transactionsRef = database.getReference("Transactions");

            // Get a reference to the "sendTransactions" sub-collection
            DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");

            // Generate a unique ID for the new transaction
            String transactionUID = sendTransactionsRef.push().getKey();

            // Add the new transaction to the "sendTransactions" sub-collection
            assert transactionUID != null;
            sendTransactionsRef.child(transactionUID).child("amount").setValue(userInputAmount);

            // This deducts the same amount from the current users main balance
            databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    String currentBalance = snapshot.getValue(String.class);
                    DecimalFormat df = new DecimalFormat("0.00");
                    assert currentBalance != null;

                    // The current balance minus the amount withdrawn
                    double amountToSubtract = Double.parseDouble(currentBalance) - Double.parseDouble(userInputAmount);
                    String newBalance = Double.toString(Double.parseDouble(df.format(amountToSubtract)));

                    // Write the new balance to the database
                    databaseReference.child(firebaseUser.getUid()).child("userMainBalance").setValue(newBalance).addOnCompleteListener(task -> {
                        if (task.isSuccessful()) {
                            System.out.println("Error updating user main balance: " + task.getException());
                        } else {
                            // Print an error message
                            System.out.println("Error updating user main balance: " + task.getException());
                        }
                    });
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    // Print an error message
                    System.out.println("Error retrieving user main balance: " + error.getMessage());
                }
            });

            finish();
            startActivity(new Intent(getApplicationContext(), SendReceiverSuccessPage.class));
        });

        // Connect to the database
        if (svSearch != null) {
            svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String s) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String s) {

                    svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                        @Override
                        public boolean onQueryTextSubmit(String query) {
                            return false;
                        }

                        @Override
                        public boolean onQueryTextChange(String newText) {
                            if (!newText.isEmpty()) {
                                // Connect to the database
                                String currentUserId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getEmail();

                                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
                                assert firebaseUser != null;
                                databaseReference.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                                        if(snapshot.exists()){
                                            searchedUsersModel = new ArrayList<>();
                                            for (DataSnapshot ds : snapshot.getChildren()) {

                                                // Removes current user from list
                                                SearchedUsersModel user = ds.getValue(SearchedUsersModel.class);
                                                assert user != null;
                                                if (!user.getMail().equals(currentUserId)) {  // check if user's ID does not match current user's ID
                                                    searchedUsersModel.add(user);  // add this user to the list of searched users
                                                }
                                            }

                                            //Filter through the users based on Name or Email
                                            ArrayList<SearchedUsersModel> myList = new ArrayList<>();
                                            for(SearchedUsersModel object : searchedUsersModel) {
                                                if(object.getMail().toLowerCase().contains(newText.toLowerCase())) {
                                                    myList.add(object);
                                                }
                                                else if(object.getName().toLowerCase().contains(newText.toLowerCase())) {
                                                    myList.add(object);
                                                }
                                            }
                                            SearchedUsersAdapter searchedUsersAdapter = new SearchedUsersAdapter(myList, finalSendBtn, svSearch);
                                            searchedUsersRecycler.setAdapter(searchedUsersAdapter);
                                        }
                                    }

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError error) {

                                    }
                                });
                            } else {
                                // Clear the data from the RecyclerView
                                searchedUsersModel = new ArrayList<>();
                                SearchedUsersAdapter searchedUsersAdapterClass = new SearchedUsersAdapter(searchedUsersModel, finalSendBtn, svSearch);
                                searchedUsersRecycler.setAdapter(searchedUsersAdapterClass);

                                //Set button to disabled
                                finalSendBtn.setEnabled(false);
                            }
                            return false;
                        }
                    });

                    return true;
                }
            });
        }
    }
}
</code>```

SendReceiverSuccessPage

```<code>

public class SendReceiverSuccessPage extends AppCompatActivity {
    MaterialButton greatNextButton;
    TextView sendSuccessText;

    public static String usersName;

    FirebaseUser firebaseUser;
    FirebaseAuth firebaseAuth;
    FirebaseDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sendreceiver_success_page);

        // Instance of FirebaseAuth and Database
        firebaseAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        greatNextButton = findViewById(R.id.great_next_button);
        sendSuccessText = findViewById(R.id.send_success);

        //Get sent amount from database
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
        assert firebaseUser != null;
        DatabaseReference transactionsRef = databaseReference.child(firebaseUser.getUid()).child("transactions");
        DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");

        //
        sendTransactionsRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot transactionSnapshot : dataSnapshot.getChildren()) {
                    String lastTransactionKey = transactionSnapshot.getKey();

                    assert lastTransactionKey != null;
                    sendTransactionsRef.child(lastTransactionKey).child("amount").addValueEventListener(new ValueEventListener() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            String sentAmount = snapshot.getValue(String.class);
                            sendSuccessText.setText("GH₵" + sentAmount + " has been sent to " + usersName);

                            //TODO This can also be where receiveTransactions document is created in the users database

                            // This sends the money to the chosen user by their name
                            databaseReference.orderByChild("name").equalTo(usersName).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                    for (DataSnapshot userSnapshot : snapshot.getChildren()) {
                                        // Get the main balance of the chosen user
                                        String mainBalance = userSnapshot.child("userMainBalance").getValue(String.class);
                                        DecimalFormat df = new DecimalFormat("0.00");

                                        // Convert the main balance and amount sent to doubles
                                        assert mainBalance != null;
                                        double mainBalanceDouble = Double.parseDouble(mainBalance);
                                        assert sentAmount != null;
                                        double amountSentDouble = Double.parseDouble(sentAmount);

                                        // Add the amount sent to the main balance
                                        double updatedMainBalance = mainBalanceDouble + amountSentDouble;

                                        // Convert the updated main balance back to a string
                                        String updatedMainBalanceString = Double.toString(Double.parseDouble(df.format(updatedMainBalance)));

                                        // Update the main balance in the database for the chosen user
                                        userSnapshot.getRef().child("userMainBalance").setValue(updatedMainBalanceString);

                                        userSnapshot.getRef().child("transactions").child("receivedTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(sentAmount);

                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {

                                }
                            });
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {
                            // Print an error message
                            System.out.println("Error retrieving user main balance: " + error.getMessage());
                        }
                    });
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // Handle error
            }
        });

        greatNextButton.setOnClickListener(v -> {
            startActivity(new Intent(getApplicationContext(), MainDashboard.class));
        });
    }
}

</code>```

There are also some Adapter classes I can add if needed.

I've been trying to figure it out with ChatGPT and have literally tried out everything.

Through testing I found out that anytime I take the

```<code>                            Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
                            sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
                            sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
</code>```

lines out of the sendMoney button it ended up not creating multiple instances and working exactly like how I need it to. The only problem is that the amount sent that I need to pass to the success page isn't recoreded or passed. So ideally, if I could find a way or alternative to getting this data to the desired page without putting it into the button OnClick or having it create multiple instances of the activity.

Body:
So I'm making an app in android studio, its like a fintech app. In one activity/page(SendMoney.java), you put in a number amount and tap the "Send Money" button, from here it goes to the page where you choose who you're sending this money to(SendReceiver.java). You select your desired recepient and tap on a second "Send Money" button, this then takes you to a success page that lists the amount sent and the username of the recepient(SendReceiverSuccessPage).

On the SendMoney page I need to get the amount inputted and pass that data to the SendReceiverSuccessPage, I've done this by using Intent and I've added this code to when the Send Money button is clicked, but in doing this what happens is that it for some reason creates multiple instances of the SendReceiver page it navigates to.
So on the SendReceiver page when I'm done and I hit the second "Send Money" button it just opens a new instance of SendReceiver whiles the SendReceiverSuccessPage is stuck in the background for some reason.

I need it to be one single smooth navigation flow where it goes from SendMoney to SendReceiver to SendReceiverSuccessPage without SendReceiver popping up multiple times and stacking ontop of the success page, all whiles being able to actively pass and retrieve the "AmountSent" data.

SendMoney.java

public class SendMoney extends AppCompatActivity {

    FirebaseUser firebaseUser;
    FirebaseAuth firebaseAuth;
    FirebaseDatabase database;

    Context context;
    Double userAmountDouble;
    MaterialButton sendMoneyButton;
    ImageView backspace, back;
    TextView amount, currentBalanceText, currency, one, two, three, four, five, six, seven, eight, nine, zero, dot;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_money);

        this.context = getApplicationContext();

        // Instance of FirebaseAuth and Database
        firebaseAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        // Hooks
        back = findViewById(R.id.back);
        amount = findViewById(R.id.amount);
        currency = findViewById(R.id.currency);
        currentBalanceText = findViewById(R.id.current_balance);

        one = findViewById(R.id.one);
        two = findViewById(R.id.two);
        three = findViewById(R.id.three);
        four = findViewById(R.id.four);
        five = findViewById(R.id.five);
        six = findViewById(R.id.six);
        seven = findViewById(R.id.seven);
        eight = findViewById(R.id.eight);
        nine = findViewById(R.id.nine);
        zero = findViewById(R.id.zero);
        dot = findViewById(R.id.dot);

        backspace = findViewById(R.id.backspace);
        sendMoneyButton = findViewById(R.id.send_money_button);
        sendMoneyButton.setText("Send GH₵0");

        // Display send amount on button, in realtime
        amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //sendMoneyButton.setText("Send GH₵0");
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // This method is called whenever the text in the EditText changes
                String userInputAmount = amount.getText().toString();
                sendMoneyButton.setText("Send GH₵" + userInputAmount);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                //

            }
        });

        // Connect to the database
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
        assert firebaseUser != null;
        // Get and show available balance
        databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String currentBalance = snapshot.getValue(String.class);
                assert currentBalance != null;
                currentBalanceText.setText("GH₵"+ currentBalance + " AVAILABLE");
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // Print an error message
                System.out.println("Error retrieving user main balance: " + error.getMessage());
            }
        });

        // Send Money Button
        sendMoneyButton.setOnClickListener(v -> {
            String userInputAmount = amount.getText().toString();

            if (userInputAmount.equals("") || userInputAmount.equals("0")) {
                Toast.makeText(getApplicationContext(),"Please enter an amount",Toast.LENGTH_SHORT).show();
            } else {
                userAmountDouble = Double.parseDouble(userInputAmount);

                databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        String currentBalance = snapshot.getValue(String.class);
                        assert currentBalance != null;
                        double currentBalanceDouble = Double.parseDouble(currentBalance);

                        if (userAmountDouble > currentBalanceDouble) {
                            Toast.makeText(getApplicationContext(),"Insufficient Balance",Toast.LENGTH_SHORT).show();
                        } else {
                            // Create an Intent and include the value of userInputAmount
                            Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
                            sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
                            sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                            // Start the SendReceiver activity
                            finish();
                            startActivity(sendReceiverIntent);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        // Print an error message
                        System.out.println("Error retrieving user main balance: " + error.getMessage());
                    }
                });
            }
        });

        // Click Listeners
        back.setOnClickListener(v -> finish());
        zero.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("0");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "0");
            }
        });
        one.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("1");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "1");
            }
        });
        two.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("2");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "2");
            }
        });
        three.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("3");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "3");
            }
        });
        four.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("4");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "4");
            }
        });
        five.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("5");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "5");
            }
        });
        six.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("6");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "6");
            }
        });
        seven.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("7");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "7");
            }
        });
        eight.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("8");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "8");
            }
        });
        nine.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText("9");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + "9");
            }
        });
        dot.setOnClickListener(v -> {
            if (amount.getText().toString().equals("0")) {
                amount.setText(".");
            } else if (amount.getText().toString().length() == 7) {
                amount.setText(amount.getText().toString());
            } else {
                amount.setText(amount.getText().toString() + ".");
            }
        });
        backspace.setOnClickListener(v -> {
            if (amount.getText().toString().equals("") | amount.getText().toString().equals("0")) {
                amount.setText("0");
            } else {
                amount.setText(amount.getText().toString().substring(0, amount.getText().length() - 1));
            }
        });
    }
}

SendReceiver.java

public class SendReceiver extends AppCompatActivity{
    FirebaseUser firebaseUser;
    FirebaseAuth firebaseAuth;
    FirebaseDatabase database;

    Context context;

    ArrayList<SearchedUsersModel> searchedUsersModel;
    RecyclerView searchedUsersRecycler;
    SearchView svSearch;
    MaterialButton finalSendBtn;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sendreceiver);

        // Retrieve the value of userInputAmount from the Intent
        Intent intent = getIntent();
        String userInputAmount = intent.getStringExtra("USER_INPUT_AMOUNT");

        this.context = getApplicationContext();

        // Instance of FirebaseAuth and Database
        firebaseAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        // Hooks
        searchedUsersRecycler = findViewById(R.id.recyclerUsers);
        svSearch = findViewById(R.id.svSearch);
        finalSendBtn = findViewById(R.id.final_send_button);

        // Set the hint for the search bar
        svSearch.setQueryHint("Enter name or email of user");

        // On click listener for when you hit the Send button
        finalSendBtn.setOnClickListener(v -> {
            DatabaseReference databaseReference = database.getReference("Users");
            assert firebaseUser != null;
            databaseReference.child(firebaseUser.getUid()).child("transactions").child("sendTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(userInputAmount);

            // Get a reference to the "transactions" collection
            DatabaseReference transactionsRef = database.getReference("Transactions");

            // Get a reference to the "sendTransactions" sub-collection
            DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");

            // Generate a unique ID for the new transaction
            String transactionUID = sendTransactionsRef.push().getKey();

            // Add the new transaction to the "sendTransactions" sub-collection
            assert transactionUID != null;
            sendTransactionsRef.child(transactionUID).child("amount").setValue(userInputAmount);

            // This deducts the same amount from the current users main balance
            databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    String currentBalance = snapshot.getValue(String.class);
                    DecimalFormat df = new DecimalFormat("0.00");
                    assert currentBalance != null;

                    // The current balance minus the amount withdrawn
                    double amountToSubtract = Double.parseDouble(currentBalance) - Double.parseDouble(userInputAmount);
                    String newBalance = Double.toString(Double.parseDouble(df.format(amountToSubtract)));

                    // Write the new balance to the database
                    databaseReference.child(firebaseUser.getUid()).child("userMainBalance").setValue(newBalance).addOnCompleteListener(task -> {
                        if (task.isSuccessful()) {
                            System.out.println("Error updating user main balance: " + task.getException());
                        } else {
                            // Print an error message
                            System.out.println("Error updating user main balance: " + task.getException());
                        }
                    });
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    // Print an error message
                    System.out.println("Error retrieving user main balance: " + error.getMessage());
                }
            });

            finish();
            startActivity(new Intent(getApplicationContext(), SendReceiverSuccessPage.class));
        });

        // Connect to the database
        if (svSearch != null) {
            svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String s) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String s) {

                    svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                        @Override
                        public boolean onQueryTextSubmit(String query) {
                            return false;
                        }

                        @Override
                        public boolean onQueryTextChange(String newText) {
                            if (!newText.isEmpty()) {
                                // Connect to the database
                                String currentUserId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getEmail();

                                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
                                assert firebaseUser != null;
                                databaseReference.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                                        if(snapshot.exists()){
                                            searchedUsersModel = new ArrayList<>();
                                            for (DataSnapshot ds : snapshot.getChildren()) {

                                                // Removes current user from list
                                                SearchedUsersModel user = ds.getValue(SearchedUsersModel.class);
                                                assert user != null;
                                                if (!user.getMail().equals(currentUserId)) {  // check if user's ID does not match current user's ID
                                                    searchedUsersModel.add(user);  // add this user to the list of searched users
                                                }
                                            }

                                            //Filter through the users based on Name or Email
                                            ArrayList<SearchedUsersModel> myList = new ArrayList<>();
                                            for(SearchedUsersModel object : searchedUsersModel) {
                                                if(object.getMail().toLowerCase().contains(newText.toLowerCase())) {
                                                    myList.add(object);
                                                }
                                                else if(object.getName().toLowerCase().contains(newText.toLowerCase())) {
                                                    myList.add(object);
                                                }
                                            }
                                            SearchedUsersAdapter searchedUsersAdapter = new SearchedUsersAdapter(myList, finalSendBtn, svSearch);
                                            searchedUsersRecycler.setAdapter(searchedUsersAdapter);
                                        }
                                    }

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError error) {

                                    }
                                });
                            } else {
                                // Clear the data from the RecyclerView
                                searchedUsersModel = new ArrayList<>();
                                SearchedUsersAdapter searchedUsersAdapterClass = new SearchedUsersAdapter(searchedUsersModel, finalSendBtn, svSearch);
                                searchedUsersRecycler.setAdapter(searchedUsersAdapterClass);

                                //Set button to disabled
                                finalSendBtn.setEnabled(false);
                            }
                            return false;
                        }
                    });

                    return true;
                }
            });
        }
    }
}

SendReceiverSuccessPage

public class SendReceiverSuccessPage extends AppCompatActivity {
    MaterialButton greatNextButton;
    TextView sendSuccessText;

    public static String usersName;

    FirebaseUser firebaseUser;
    FirebaseAuth firebaseAuth;
    FirebaseDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sendreceiver_success_page);

        // Instance of FirebaseAuth and Database
        firebaseAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        greatNextButton = findViewById(R.id.great_next_button);
        sendSuccessText = findViewById(R.id.send_success);

        //Get sent amount from database
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
        assert firebaseUser != null;
        DatabaseReference transactionsRef = databaseReference.child(firebaseUser.getUid()).child("transactions");
        DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");

        //
        sendTransactionsRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot transactionSnapshot : dataSnapshot.getChildren()) {
                    String lastTransactionKey = transactionSnapshot.getKey();

                    assert lastTransactionKey != null;
                    sendTransactionsRef.child(lastTransactionKey).child("amount").addValueEventListener(new ValueEventListener() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            String sentAmount = snapshot.getValue(String.class);
                            sendSuccessText.setText("GH₵" + sentAmount + " has been sent to " + usersName);

                            //TODO This can also be where receiveTransactions document is created in the users database

                            // This sends the money to the chosen user by their name
                            databaseReference.orderByChild("name").equalTo(usersName).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                    for (DataSnapshot userSnapshot : snapshot.getChildren()) {
                                        // Get the main balance of the chosen user
                                        String mainBalance = userSnapshot.child("userMainBalance").getValue(String.class);
                                        DecimalFormat df = new DecimalFormat("0.00");

                                        // Convert the main balance and amount sent to doubles
                                        assert mainBalance != null;
                                        double mainBalanceDouble = Double.parseDouble(mainBalance);
                                        assert sentAmount != null;
                                        double amountSentDouble = Double.parseDouble(sentAmount);

                                        // Add the amount sent to the main balance
                                        double updatedMainBalance = mainBalanceDouble + amountSentDouble;

                                        // Convert the updated main balance back to a string
                                        String updatedMainBalanceString = Double.toString(Double.parseDouble(df.format(updatedMainBalance)));

                                        // Update the main balance in the database for the chosen user
                                        userSnapshot.getRef().child("userMainBalance").setValue(updatedMainBalanceString);

                                        userSnapshot.getRef().child("transactions").child("receivedTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(sentAmount);

                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {

                                }
                            });
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {
                            // Print an error message
                            System.out.println("Error retrieving user main balance: " + error.getMessage());
                        }
                    });
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // Handle error
            }
        });

        greatNextButton.setOnClickListener(v -> {
            startActivity(new Intent(getApplicationContext(), MainDashboard.class));
        });
    }
}

There are also some Adapter classes I can add if needed.

I've been trying to figure it out with ChatGPT and have literally tried out everything.

Through testing I found out that anytime I take the

                            Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
                            sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
                            sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

lines out of the sendMoney button it ended up not creating multiple instances and working exactly like how I need it to. The only problem is that the amount sent that I need to pass to the success page isn't recoreded or passed. So ideally, if I could find a way or alternative to getting this data to the desired page without putting it into the button OnClick or having it create multiple instances of the activity.


来源: stackexchange

问:
Update WebSocket Results in webpage on a loop
I am attempting to create a site which will load the latest prices of BitCoin from multiple exchanges, however the prices are only retrieved the first time the python app is called and not on a loop.

I have attached my scripts below to see if it is possible to help

Application called from here

```<code>from flask import Flask
from views import views

app = Flask(__name__)
app.register_blueprint(views, url_prefix="/views")

if __name__ == '__main__':
    app.run(debug=True, port=3004)
</code>```

Index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>
    <div><h1>Price Details</h1></div>
    <p>Binance details = {{ binanceresult }} <br>
        ByBit details = {{ bybitresult }}
    </p>
</body>
</html>
</code>```

my views

```<code>from flask import Blueprint, render_template, request, jsonify
from price import binance_price
from bybitprice import last_price

views = Blueprint(__name__, "views")

@views.route("/")
def home():
    return render_template("index.html", binanceresult=binance_price, bybitresult=last_price)

</code>```

My price calls to Bybit and Binance

```<code>import json
import websocket
import sys

class BitfinexWebSocketReader():
    endpoint = "wss://dstream.binance.com/ws/btcusd_perp@markPrice"
    def __init__(self):
        #websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp(
                BitfinexWebSocketReader.endpoint,
                on_message = self.on_message,
                on_error = self.on_error,
                on_close = self.on_close
         )
        self.ws.on_open = self.on_open
        self.store = []

        try:
            self.run()
        except KeyboardInterrupt:
            self.ws.close()

    def run(self):
        self.ws.run_forever()
        print("### run ###")
        pass

    def on_message(self, ws, message):
        if "data" in message:
            self.store.append(message)
        #print(message)

    def on_error(self, ws, error):
        print(error)
        sys.exit()

    def on_close(self, ws):
        print("### closed ###")

    def on_open(self, ws):
        #print("### open ###")
        ws.send(json.dumps({"event": "subscribe", "channel": "Trades", "symbol": "tBTCUSD"}))

if __name__=="__main__":
    message = BitfinexWebSocketReader()
    print(message)

</code>```
```<code>import json
from websocket import create_connection

ws = create_connection("wss://stream-testnet.bybit.com/realtime")
ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCUSD"]}');
bybitresult = json.loads(ws.recv())
last_price = bybitresult['data']['index_price']
timestamp = bybitresult['timestamp_e6']
#print(last_price, timestamp)
#print(ws.recv())
ws.close()

</code>```

I have attempted to use the asyncio function in multiple of the python scripts however cannot get this to function how I wouldn't like. Thanks

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to create a site which will load the latest prices of BitCoin from multiple exchanges, however the prices are only retrieved the first time the python app is called and not on a loop.

I have attached my scripts below to see if it is possible to help

Application called from here

from flask import Flask
from views import views

app = Flask(__name__)
app.register_blueprint(views, url_prefix="/views")

if __name__ == '__main__':
    app.run(debug=True, port=3004)

Index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>

Price Details

Binance details = {{ binanceresult }}

        ByBit details = {{ bybitresult }}

my views

from flask import Blueprint, render_template, request, jsonify
from price import binance_price
from bybitprice import last_price

views = Blueprint(__name__, "views")

@views.route("/")
def home():
    return render_template("index.html", binanceresult=binance_price, bybitresult=last_price)

My price calls to Bybit and Binance

import json
import websocket
import sys

class BitfinexWebSocketReader():
    endpoint = "wss://dstream.binance.com/ws/btcusd_perp@markPrice"
    def __init__(self):
        #websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp(
                BitfinexWebSocketReader.endpoint,
                on_message = self.on_message,
                on_error = self.on_error,
                on_close = self.on_close
         )
        self.ws.on_open = self.on_open
        self.store = []

        try:
            self.run()
        except KeyboardInterrupt:
            self.ws.close()

    def run(self):
        self.ws.run_forever()
        print("### run ###")
        pass

    def on_message(self, ws, message):
        if "data" in message:
            self.store.append(message)
        #print(message)

    def on_error(self, ws, error):
        print(error)
        sys.exit()

    def on_close(self, ws):
        print("### closed ###")

    def on_open(self, ws):
        #print("### open ###")
        ws.send(json.dumps({"event": "subscribe", "channel": "Trades", "symbol": "tBTCUSD"}))

if __name__=="__main__":
    message = BitfinexWebSocketReader()
    print(message)

import json
from websocket import create_connection

ws = create_connection("wss://stream-testnet.bybit.com/realtime")
ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCUSD"]}');
bybitresult = json.loads(ws.recv())
last_price = bybitresult['data']['index_price']
timestamp = bybitresult['timestamp_e6']
#print(last_price, timestamp)
#print(ws.recv())
ws.close()

I have attempted to use the asyncio function in multiple of the python scripts however cannot get this to function how I wouldn't like. Thanks


问:
Can´t change password in Administrate or Madmin. Rails 7 + Devise
Try installing administrate(thoughtbot) and Madmin(GoRails). But in both cases when I change the password of a user in /admin or /madmin and try to login again with the new password, I get the following error.
raise Errors::InvalidHash.new("invalid hash")

I check that user.rb has :database_authenticatable

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
end
</code>```

Is just standar rails new 7 + devise, bcrypt is commented

```<code># Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"
</code>```

The users can edit his own password but i need to close the new signups and only create new users manually in /admin

Body:
Try installing administrate(thoughtbot) and Madmin(GoRails). But in both cases when I change the password of a user in /admin or /madmin and try to login again with the new password, I get the following error.
raise Errors::InvalidHash.new("invalid hash")

I check that user.rb has :database_authenticatable

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
end

Is just standar rails new 7 + devise, bcrypt is commented

# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"

The users can edit his own password but i need to close the new signups and only create new users manually in /admin


问:
Having trouble using Vue Google Adsense pluging
I recently wanted to add google AdSense to my Vue 3 website. I tried using Vue Google Adsense but after doing everything right, I keep getting this error "Uncaught (in promise) TypeError: vue__WEBPACK_IMPORTED_MODULE_0__.normalizeClass is not a function". Has anyone successfully used this plugin in Vue 3?</p>


问:
cant install h5py on mac using pip
Cant install h5py on mac

```<code>ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py, which is required to install pyproject.toml-based projects
</code>```

have done

```<code>pip install --upgrade pip setuptools wheel

pip install versioned-hdf5

pip install h5py
</code>```

nothing working.

Ultimately I'm trying to install tensorflow but that's not working so i tried this

```<code>python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.12.0-py3-none-any.whl
</code>```

but now its giving me the cannot build wheels for h5py error.

Title: cant install h5py on mac using pip

Body:
Cant install h5py on mac

ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py, which is required to install pyproject.toml-based projects

have done

pip install --upgrade pip setuptools wheel

pip install versioned-hdf5

pip install h5py

nothing working.

Ultimately I'm trying to install tensorflow but that's not working so i tried this

python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.12.0-py3-none-any.whl

but now its giving me the cannot build wheels for h5py error.


问:
Is there a way to sort a list of ordered tuples of strings into a list of strings while maintaining the order of the strings in the tuples?
I have a list of tuples. Each tuples is ordered according to a string that appears before another. So for the first tuple in list ‘gi-‘ linearly proceeds ‘ba-‘.

list = [(‘gi-‘, ‘ba-‘), (‘be-‘, ‘ke-‘), (‘be-‘, ‘ba-‘), (‘gi-‘, ‘ke-‘), … ]

I am trying to make a function to give the ordered_list. Notice that I expect some strings to be unordered with respect to each other, such as ‘ke-‘ and ‘ba-‘.

ordered_list = [‘gi-‘, ‘be-‘, {‘ke-‘, ba-} … ]

I’m not sure what sorting method I would use to do this task. This is a nltk project that is similar to forming a Cinque style order of adverbs.


问:
How can I find the USB drives Connected to the computer in macOS
I want to write back up utility for myself. And I don't know how to find the drivers that are connected to the computer.

I googled for a bit but I can't find anything helpful.


问:
How can you set a list as a query paramter?
I got this code with a little help from chattgpt. But it is not working. It always say it needs a int:

Exception in thread "main" java.lang.IllegalArgumentException: You have attempted to set a value of type class java.util.Arrays$ArrayList for parameter list with expected type of int from query string SELECT s.studygroupid FROM SubjectStudyGroup s WHERE s.subjectid IN (:list).
at org.eclipse.persistence.internal.jpa.QueryImpl.setParameterInternal(QueryImpl.java:946)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:609)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:69)
at Testen.Testen.main(Testen.java:27)

Can you explain why it does not take the list-paramter or how he will accept the parameter.

```<code>  private static EntityManager em = null;
  private static EntityManagerFactory emf = null;

public static void main(String[] args) throws SQLException, ClassNotFoundException {
    open();
    List<Integer> subjectIds = Arrays.asList(1, 2, 3);
    Query query = em.createQuery("SELECT s.studygroupid FROM SubjectStudyGroup s WHERE s.subjectid IN (:list)");
    query.setParameter("list", subjectIds);
    List<Integer> studyGroupIds = query.getResultList();
    close();

}

private static void open()
{
    emf = Persistence.createEntityManagerFactory("PU");
    em = emf.createEntityManager();
}

private static void close()
{
    if(em != null)
    {
        em.close();
        em = null;
    }

    if(emf != null)
    {
        emf.close();
        em = null;
    }
}
</code>```

Body:
I got this code with a little help from chattgpt. But it is not working. It always say it needs a int:

Exception in thread "main" java.lang.IllegalArgumentException: You have attempted to set a value of type class java.util.Arrays$ArrayList for parameter list with expected type of int from query string SELECT s.studygroupid FROM SubjectStudyGroup s WHERE s.subjectid IN (:list).
at org.eclipse.persistence.internal.jpa.QueryImpl.setParameterInternal(QueryImpl.java:946)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:609)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:69)
at Testen.Testen.main(Testen.java:27)

Can you explain why it does not take the list-paramter or how he will accept the parameter.

  private static EntityManager em = null;
  private static EntityManagerFactory emf = null;

public static void main(String[] args) throws SQLException, ClassNotFoundException {
    open();
    List<Integer> subjectIds = Arrays.asList(1, 2, 3);
    Query query = em.createQuery("SELECT s.studygroupid FROM SubjectStudyGroup s WHERE s.subjectid IN (:list)");
    query.setParameter("list", subjectIds);
    List<Integer> studyGroupIds = query.getResultList();
    close();

}

private static void open()
{
    emf = Persistence.createEntityManagerFactory("PU");
    em = emf.createEntityManager();
}

private static void close()
{
    if(em != null)
    {
        em.close();
        em = null;
    }

    if(emf != null)
    {
        emf.close();
        em = null;
    }
}


问:
OpenCV's connectedComponentsWithStats() returns NaN position for first centroid
I am using the OpenCV C++ API (version 4.7.0). I have an application where I need to determine the centroid of a laser spot through a camera feed, and to do that I am attempting to use the connectedComponentsWithStats() function.

In my current setup, the image data is defined in a text file as a 2D array. This data is of a binary image, which is expected by connectedCoponentsWithStats(). The size of the image is 625X889. Here is what the binary image looks like:

This is the result of a binary thresholding operation.

Here is my C++ code for computing the centroids of the connected components:

```<code>/* Grouping and centroiding implementation using OpenCV's
 * ConnectedComponentsWithStats().
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <fstream>

#include <opencv2/opencv.hpp>

using namespace std;

int main()
{
        uint32_t ROWS=625;
        uint32_t COLS=889;
        uint8_t image_array[ROWS][COLS];
        uint8_t *image_data = new uint8_t[ROWS * COLS];
        int i;
        int j;

        //Read data from file and save into image_array[][].
        ifstream fp("./data/binary_image/binary_image1.txt");
        if (! fp)
        {
                cout << "Error opening file" << endl;
                return 1;
        }
        for (i=0; i<ROWS; i++)
        {
                for (j=0; j<COLS; j++)
                {
                        fp >> image_array[i][j];
                        if (! fp)
                        {
                                cout << "Error reading file for element " << i << "," << j << endl;
                                return 1;
                        }
                }
        }

        //Copy data into a 1D array called image_data.
        for (i=0; i<ROWS; i++)
        {
                for (j=0; j<COLS; j++)
                {
                        if (image_array[i][j] == 1)
                        {
                                image_array[i][j] = 255;
                        }
                        image_data[i * COLS + j] = image_array[i][j];
                }
        }

        //Create image object.
        cv::Mat image(ROWS, COLS, CV_8U, image_data);

        //Create output objects.
        cv::Mat labels, stats, centroids;

        //Pass image to connectedComponentsWithStats() function.
        int num_components = cv::connectedComponentsWithStats(image, labels, stats, centroids);

        //Print out the centroids
        for (i=0; i<num_components; i++)
        {
                cout << "Centroid "<< i << ": (" << centroids.at<double>(i, 0) << ", " << centroids.at<double>(i,1) << ")" << endl;
        }

        return 0;
}

</code>```

Not that is it important, but this is how I compiled the code:

```<code>g++ `pkg-config --cflags opencv4` -c opencv_grouping.cpp
g++ opencv_grouping.o `pkg-config --libs opencv4` -o opencv_test
</code>```

This is the output after running ./opencv_test:

```<code>Centroid 0: (nan, nan)
Centroid 1: (444, 312)
</code>```

I am not really sure why I am getting the nan result, but I suppose this means that the area of that connected component is 0? As for the (444, 312) result, that just corresponds (roughly) to the center of a 625X889 grid, which is the size of the inputted image. So it essentially just computed the center of that grid. I tried with several other input images of the same size that were generated using different thresholds (so the spot size varried), and it yielded exactly the same result.

Does anyone have any insight/suggestions as to what might be going on here? Does OpenCV provide other functions that can be used to compute the centroid of the spot?

--Update--

I think that I found out where the problem is coming from. Something very strange is happening when I am reading in the data from the text file. It's not reading the data correctly at all. It gets to row 440 and then the rest of the data is either 0 or some garbage value (like a really large negative number for example). I am not sure why this is happening. In addition to declaring image_array as uint8_t image_array[ROWS][COLS], I have also tried allocating memory for it with new:

```<code>uint8_t **image_array = new uint8_t*[ROWS];
for (i=0; i<ROWS; i++)
        {
                image_array[i] = new uint8_t[COLS];
        }
</code>```

Both of these run into the same problem. As a sanity check, I created a smaller (19X20) array to test with. It looks like this in a text file:

```<code>0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 255 255 255 255 255 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 0 255 255 255 0 0 0 0
0 0 255 255 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 255 255 255 255 255 0 0 0 0 255 255 255 255 0 0 0 0
0 0 0 0 255 255 255 255 255 0 0 255 255 255 0 0 0 0 0 0
0 0 0 0 0 0 255 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 255 255 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>```

I run this through the code my code (with ROWS=19 and COLS=20) and it actually gives a reasonable output for the centroids:

```<code>Centroid 0: (9.63497, 9.22086)
Centroid 1: (3.8, 3.1)
Centroid 2: (14, 2.55556)
Centroid 3: (8.71429, 10.2857)
</code>```

So the issue is that the larger array is not getting read from the text file correctly. Any suggestions?

Body:
I am using the OpenCV C++ API (version 4.7.0). I have an application where I need to determine the centroid of a laser spot through a camera feed, and to do that I am attempting to use the connectedComponentsWithStats() function.

In my current setup, the image data is defined in a text file as a 2D array. This data is of a binary image, which is expected by connectedCoponentsWithStats(). The size of the image is 625X889. Here is what the binary image looks like:

This is the result of a binary thresholding operation.

Here is my C++ code for computing the centroids of the connected components:

/* Grouping and centroiding implementation using OpenCV's
 * ConnectedComponentsWithStats().
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <fstream>

#include <opencv2/opencv.hpp>

using namespace std;

int main()
{
        uint32_t ROWS=625;
        uint32_t COLS=889;
        uint8_t image_array[ROWS][COLS];
        uint8_t *image_data = new uint8_t[ROWS * COLS];
        int i;
        int j;

        //Read data from file and save into image_array[][].
        ifstream fp("./data/binary_image/binary_image1.txt");
        if (! fp)
        {
                cout << "Error opening file" << endl;
                return 1;
        }
        for (i=0; i<ROWS; i++)
        {
                for (j=0; j<COLS; j++)
                {
                        fp >> image_array[i][j];
                        if (! fp)
                        {
                                cout << "Error reading file for element " << i << "," << j << endl;
                                return 1;
                        }
                }
        }

        //Copy data into a 1D array called image_data.
        for (i=0; i<ROWS; i++)
        {
                for (j=0; j<COLS; j++)
                {
                        if (image_array[i][j] == 1)
                        {
                                image_array[i][j] = 255;
                        }
                        image_data[i * COLS + j] = image_array[i][j];
                }
        }

        //Create image object.
        cv::Mat image(ROWS, COLS, CV_8U, image_data);

        //Create output objects.
        cv::Mat labels, stats, centroids;

        //Pass image to connectedComponentsWithStats() function.
        int num_components = cv::connectedComponentsWithStats(image, labels, stats, centroids);

        //Print out the centroids
        for (i=0; i<num_components; i++)
        {
                cout << "Centroid "<< i << ": (" << centroids.at<double>(i, 0) << ", " << centroids.at<double>(i,1) << ")" << endl;
        }

        return 0;
}

Not that is it important, but this is how I compiled the code:

g++ `pkg-config --cflags opencv4` -c opencv_grouping.cpp
g++ opencv_grouping.o `pkg-config --libs opencv4` -o opencv_test

This is the output after running ./opencv_test:

Centroid 0: (nan, nan)
Centroid 1: (444, 312)

I am not really sure why I am getting the nan result, but I suppose this means that the area of that connected component is 0? As for the (444, 312) result, that just corresponds (roughly) to the center of a 625X889 grid, which is the size of the inputted image. So it essentially just computed the center of that grid. I tried with several other input images of the same size that were generated using different thresholds (so the spot size varried), and it yielded exactly the same result.

Does anyone have any insight/suggestions as to what might be going on here? Does OpenCV provide other functions that can be used to compute the centroid of the spot?

--Update--

I think that I found out where the problem is coming from. Something very strange is happening when I am reading in the data from the text file. It's not reading the data correctly at all. It gets to row 440 and then the rest of the data is either 0 or some garbage value (like a really large negative number for example). I am not sure why this is happening. In addition to declaring image_array as uint8_t image_array[ROWS][COLS], I have also tried allocating memory for it with new:

uint8_t **image_array = new uint8_t*[ROWS];
for (i=0; i<ROWS; i++)
        {
                image_array[i] = new uint8_t[COLS];
        }

Both of these run into the same problem. As a sanity check, I created a smaller (19X20) array to test with. It looks like this in a text file:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 255 255 255 255 255 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 0 255 255 255 0 0 0 0
0 0 255 255 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 255 255 255 255 255 0 0 0 0 255 255 255 255 0 0 0 0
0 0 0 0 255 255 255 255 255 0 0 255 255 255 0 0 0 0 0 0
0 0 0 0 0 0 255 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 255 255 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

I run this through the code my code (with ROWS=19 and COLS=20) and it actually gives a reasonable output for the centroids:

Centroid 0: (9.63497, 9.22086)
Centroid 1: (3.8, 3.1)
Centroid 2: (14, 2.55556)
Centroid 3: (8.71429, 10.2857)

So the issue is that the larger array is not getting read from the text file correctly. Any suggestions?


Title: How to label dots in python PCA analysis?

Body:
I have tried PCA analysis with this script.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn
from sklearn.preprocessing import StandardScaler

raw_data_frame =
pd.read_table('/content/drive/MyDrive/BI/colab_input_output/16samples_vaf_df_forpca.csv',
sep=",", header=0, index_col=0)

data_scaler = StandardScaler()
data_scaler.fit(raw_data_frame)
scaled_data_frame = data_scaler.transform(raw_data_frame)
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
pca.fit(scaled_data_frame)

x_pca = pca.transform(scaled_data_frame)
plt.figure(figsize=(10, 7))
plt.scatter(x_pca[:,0],x_pca[:,1], c=raw_data_frame['target'], cmap='viridis')
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')

And the output is

I want to label the dots with the information in the dataframe.

The format of the dataframe is

     ('1', 187963806)   ('19', 49972822)    ('8', 14555764) ('11', 127666530)   ('18', 67693298)    target
15_R71_epi  0.310344828 0.227272727 0.217391304 0.149253731 0   1
15_R21_epi  0.1875  0.228070175 0.173913043 0.25862069  0   1
15_L133_epi     0.078947368 0.085714286 0.145454545 0.119047619 0   1
15_L58_epi  0.222222222 0.19047619  0.302325581 0.333333333 0   1
15_C5_epi   0.267326733 0.132075472 0.275362319 0.220779221 0   1
15_Lt_Nasal_derm    0.359375    0.039215686 0.274509804 0.192982456 0   2
15-H-21     0.322580645 0.255319149 0.238095238 0.380952381 0   3
15_H-55     0.446808511 0.27027027  0.387755102 0.347826087 0   3
15_H-49     0.30952381  0.236363636 0.266666667 0.235294118 0   3
15_H-3  0.12962963  0.153846154 0.085106383 0.205479452 0   3
15_H-33     0.349206349 0.263157895 0.298245614 0.328571429 0   3
15-RK-62    0.235294118 0.152173913 0.191780822 0.2 0   4
15_RK-29    0.078431373 0.094339623 0.175438596 0.121212121 0   4
15_LK-168   0.185185185 0.132075472 0.12    0.2 0   5
15_LK-114   0.173076923 0.075   0.14893617  0.237288136 0   5
15_LK-176   0.253968254 0.113207547 0.127272727 0.291666667 0.035087719 5

(This looks bad, but if you copy, it would be in a good form)

The color of the dots correspond with the numbers in the column "target"

But in the figure I can't distinguish the names of the samples.

How can I do?


问:
How to Differentiate Objects that Have Multiple Key/Value Pairs From Objects with String Values in JavaScript
I would like to recursively iterate through an object to create one array with all the keys and value pairs in the top level using javascript.

The function would take the following:

obj1 = { name: "Goggles", price: 1499, obj: {no: "hi", yes: "bye"} }

and convert it into this:

{ name: "Goggles", price: 1499, no: "hi", yes: "bye" }

I am using Object.keys(obj1).length to tell whether or not a property has a value containing  multiple properties. The problem is that when it sees a string as a value, it treats it as an Object with each character representing a value:

Object.keys(obj).length, where obj == name: "Goggles"

retruns 7

this is because Object.keys(...)length interprets it as
{0: G, 1: o, 2: g, 3: g, 4: l, 5: e, 6: s}

Is there a way to differentiate Objects that have multiple key/value pairs from those that don't? Specifically from a key with a value that happens to be a String.


问:
convert_tz is taking on GMT at the end of the date although I'm converting to East Coast Time
So here the the time in the database...

```<code>2023-01-02 21:00:00
</code>```

Here is the select that I use to get the information out of the database...

```<code>SELECT job_id,job_desc,
    CONVERT_TZ(job_date, 'GMT', 'US/Eastern') "job_date",
    cust_auto_id,
    cost,
    paid,
    mileage,
    (
    SELECT
    CONCAT(LastName, ',', FirstName)
    from
    persons
    where
    jobs.person_id = persons.person_id) "Name"
    from jobs where job_id = %s'''
        cursorone.execute(sql,(1,))
</code>```

Here is what is returned in the JSON block

```<code>{
  "Name": "Lterkdkflskd,Robert",
  "cost": "0.00",
  "cust_auto_id": 2,
  "job_date": "Mon, 02 Jan 2023 16:00:00 GMT",
  "job_desc": "Front Tires",
  "job_id": 1,
  "mileage": 123432,
  "paid": ""
}
</code>```

Body:
So here the the time in the database...

2023-01-02 21:00:00

Here is the select that I use to get the information out of the database...

SELECT job_id,job_desc,
    CONVERT_TZ(job_date, 'GMT', 'US/Eastern') "job_date",
    cust_auto_id,
    cost,
    paid,
    mileage,
    (
    SELECT
    CONCAT(LastName, ',', FirstName)
    from
    persons
    where
    jobs.person_id = persons.person_id) "Name"
    from jobs where job_id = %s'''
        cursorone.execute(sql,(1,))

Here is what is returned in the JSON block

{
  "Name": "Lterkdkflskd,Robert",
  "cost": "0.00",
  "cust_auto_id": 2,
  "job_date": "Mon, 02 Jan 2023 16:00:00 GMT",
  "job_desc": "Front Tires",
  "job_id": 1,
  "mileage": 123432,
  "paid": ""
}


问:
Select Option not working but input text is
I have an endpoint, let say https://localhost:3003/requests
And I have this React form:
First, the input text (this is no problem, I can post data correctly to backend):

```<code><div className="input-type">
<input type="text" onChange={setFormData} name="nama"
    className="border w-full px-5 py-3 focus:outline-none rounded-md"
    placeholder="Nama" />

</div>
</code>```

And then, I have this select option that can't post the data:

```<code><div className="input-type">
                <label htmlFor="pet” className="block text-sm font-medium text-gray-700">
                    Sektor
                </label>
                <select
                    id="pet”
                    name="pet”
                    autoComplete="pet-name"
                    className="border w-full px-5 py-3 focus:outline-none rounded-md"
                    onChange={setFormData}
                    >
                    <option value="Chika”>Chika</option>
                    <option value="Chiki”>Chiki</option>
                    <option value="Chikoo”>Chikoo</option>

                </select>
            </div>
</code>```

And this is setFormData get from:

```<code>import { BiPlus } from 'react-icons/bi'
import Success from "./successRequest"
import Bug from "./bugRequest"
import { useQueryClient, useMutation } from "react-query"
import { addRequest, getRequests } from "../../lib/helper"

export default function AddRequestForm({ formData, setFormData }) {

    const queryClient = useQueryClient()
    const addMutation = useMutation(addRequest, {
        onSuccess: () => {
            queryClient.prefetchQuery('requests', getRequests)
        }
    })

    const handleSubmit = (e) => {
        e.preventDefault();
        if (Object.keys(formData).length == 0) return console.log("Don't have Form Data");
        let { name, pet } = formData;

        const model = {
            name, pet
        }

        addMutation.mutate(model)
    }

    if (addMutation.isLoading) return <div>Loading!</div>
    if (addMutation.isError) return <Bug message={addMutation.error.message}></Bug>
    if (addMutation.isSuccess) return <Success message={"Added Successfully"}></Success>

return(
<div className="input-type">
<input type="text" onChange={setFormData} name="nama"
    className="border w-full px-5 py-3 focus:outline-none rounded-md"
    placeholder="Nama" />

</div>

<div className="input-type">
                <label htmlFor="pet” className="block text-sm font-medium text-gray-700">
                    My Pet
                </label>
                <select
                    id="pet”
                    name="pet”
                    autoComplete="pet-name"
                    className="border w-full px-5 py-3 focus:outline-none rounded-md"
                    onChange={setFormData}
                    >
                    <option value="Chika”>Chika</option>
                    <option value="Chiki”>Chiki</option>
                    <option value="Chikoo”>Chikoo</option>

                </select>
            </div>

)}
</code>```

How to do it correctly, so I can pass all input data to backend?

Body:
I have an endpoint, let say https://localhost:3003/requests
And I have this React form:
First, the input text (this is no problem, I can post data correctly to backend):

<input type="text" onChange={setFormData} name="nama"
    className="border w-full px-5 py-3 focus:outline-none rounded-md"
    placeholder="Nama" />

And then, I have this select option that can't post the data:

                    Sektor

                <select
                    id="pet”
                    name="pet”
                    autoComplete="pet-name"
                    className="border w-full px-5 py-3 focus:outline-none rounded-md"
                    onChange={setFormData}
                    >
                    <option value="Chika”>Chika</option>
                    <option value="Chiki”>Chiki</option>
                    <option value="Chikoo”>Chikoo</option>

                </select>

And this is setFormData get from:

import { BiPlus } from 'react-icons/bi'
import Success from "./successRequest"
import Bug from "./bugRequest"
import { useQueryClient, useMutation } from "react-query"
import { addRequest, getRequests } from "../../lib/helper"

export default function AddRequestForm({ formData, setFormData }) {

    const queryClient = useQueryClient()
    const addMutation = useMutation(addRequest, {
        onSuccess: () => {
            queryClient.prefetchQuery('requests', getRequests)
        }
    })

    const handleSubmit = (e) => {
        e.preventDefault();
        if (Object.keys(formData).length == 0) return console.log("Don't have Form Data");
        let { name, pet } = formData;

        const model = {
            name, pet
        }

        addMutation.mutate(model)
    }

    if (addMutation.isLoading) return
Loading!

    if (addMutation.isError) return <Bug message={addMutation.error.message}></Bug>
    if (addMutation.isSuccess) return <Success message={"Added Successfully"}></Success>

return(

<input type="text" onChange={setFormData} name="nama"
    className="border w-full px-5 py-3 focus:outline-none rounded-md"
    placeholder="Nama" />

                    My Pet

                <select
                    id="pet”
                    name="pet”
                    autoComplete="pet-name"
                    className="border w-full px-5 py-3 focus:outline-none rounded-md"
                    onChange={setFormData}
                    >
                    <option value="Chika”>Chika</option>
                    <option value="Chiki”>Chiki</option>
                    <option value="Chikoo”>Chikoo</option>

                </select>

)}

How to do it correctly, so I can pass all input data to backend?


问:
How to stream data from Delta Table to Kafka Topic
Internet is filled with examples of streaming data from Kafka topic to delta tables. But my requirement is to stream data from Delta Table to Kafka topic. Is that possible? If yes, can you please share code example?
Here is the code I tried.

```<code>val schemaRegistryAddr = "https://..."
val avroSchema = buildSchema(topic) //defined this method

val Df = spark.readStream.format("delta").load("path..")
.withColumn("key", col("lskey").cast(StringType))
.withColumn("topLevelRecord",struct(col("col1"),col("col2")...)
.select(
          to_avro($"key", lit("topic-key"), schemaRegistryAddr).as("key"),
          to_avro($"topLevelRecord", lit("topic-value"), schemaRegistryAddr, avroSchema).as("value"))

Df.writeStream
.format("kafka")
.option("checkpointLocation",checkpointPath)
.option("kafka.bootstrap.servers", bootstrapServers)
.option("kafka.security.protocol", "SSL")
.option("kafka.ssl.keystore.location", kafkaKeystoreLocation)
.option("kafka.ssl.keystore.password", keystorePassword)
.option("kafka.ssl.truststore.location", kafkaTruststoreLocation)
.option("topic",topic)
.option("batch.size",262144)
.option("linger.ms",5000)
.trigger(ProcessingTime("25 seconds"))
.start()
</code>```

But it fails with: org.spark_project.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException: Schema not found; error code: 40403

But when I try to write to the same topic using a Batch Producer it goes through successfully. Can anyone please let me know what am I missing in the streaming write to Kafka topic?

Later I found this old blog which says that current Structured Streaming API does not support 'kakfa' format.
https://www.databricks.com/blog/2017/04/04/real-time-end-to-end-integration-with-apache-kafka-in-apache-sparks-structured-streaming.html?_ga=2.177174565.1658715673.1672876248-681971438.1669255333

Body:
Internet is filled with examples of streaming data from Kafka topic to delta tables. But my requirement is to stream data from Delta Table to Kafka topic. Is that possible? If yes, can you please share code example?
Here is the code I tried.

val schemaRegistryAddr = "https://..."
val avroSchema = buildSchema(topic) //defined this method

val Df = spark.readStream.format("delta").load("path..")
.withColumn("key", col("lskey").cast(StringType))
.withColumn("topLevelRecord",struct(col("col1"),col("col2")...)
.select(
          to_avro($"key", lit("topic-key"), schemaRegistryAddr).as("key"),
          to_avro($"topLevelRecord", lit("topic-value"), schemaRegistryAddr, avroSchema).as("value"))

Df.writeStream
.format("kafka")
.option("checkpointLocation",checkpointPath)
.option("kafka.bootstrap.servers", bootstrapServers)
.option("kafka.security.protocol", "SSL")
.option("kafka.ssl.keystore.location", kafkaKeystoreLocation)
.option("kafka.ssl.keystore.password", keystorePassword)
.option("kafka.ssl.truststore.location", kafkaTruststoreLocation)
.option("topic",topic)
.option("batch.size",262144)
.option("linger.ms",5000)
.trigger(ProcessingTime("25 seconds"))
.start()

But it fails with: org.spark_project.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException: Schema not found; error code: 40403

But when I try to write to the same topic using a Batch Producer it goes through successfully. Can anyone please let me know what am I missing in the streaming write to Kafka topic?

Later I found this old blog which says that current Structured Streaming API does not support 'kakfa' format.
https://www.databricks.com/blog/2017/04/04/real-time-end-to-end-integration-with-apache-kafka-in-apache-sparks-structured-streaming.html?_ga=2.177174565.1658715673.1672876248-681971438.1669255333