问:
how to call a Function from another Dart file
i have this funtion which handles my Date and Time picker widget ...Code bellow...

```<code>Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }
</code>```

initially it was inside my add new task class/dart file "Stateful Widget", and everything was working fine but now i want to also use that function on the Home screen when a button is pressed.

Then i checked a StackOverflow question on how to call a function from another dart file which the solution required that i keep the Function on a different dart file then call it from there like this Example

```<code>void launchWebView () {
  print("1234");
}
</code>```

when i did i was getting an error which i lookedup and it was because of the "setState" in my function so i needed to put it inside a Stateful widget,

```<code>import 'package:flutter/material.dart';

class SelectDateAndTime extends StatefulWidget {
  @override
  _SelectDateAndTimeState createState() => _SelectDateAndTimeState();
}

class _SelectDateAndTimeState extends State<SelectDateAndTime> {

  DateTime? _selectedDate;
// DateTime _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}
</code>```

And that was the only difference from my code with the example i followed and i was still getting an error when i tried calling the funtion, and i have checked all the quetions related to clling functions from another dart file / class and none of them had SetState so their solution didn't work for me

This is the error i got when i called just the Function Name

Bellow s the error i got when i tried to call

```<code>onPressed: () => selectedDateAndTime!.selectDayAndTimeL(),
</code>```

what should i do from here?

答:
I'm guessing that you originally had a Statefull widget, that probably looked something like this:

class OriginalWidget extends StatefulWidget {
  @override
  _OriginalWidgetState createState() => _OriginalWidgetState();
}

class _OriginalWidgetState extends State<OriginalWidget> {

  DateTime? _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
          onPressed: () => selectDayAndTimeL(context));
  }
}
```
<p>Now, what you want to do is to reuse the logic of your <code>selectDayAndTimeL</code> function.</p>
<p>The problem is that both the <code>selectedDateAndTime</code> variable and the <code>setState</code> method are specific to the Statefull widget <code>_OriginalWidgetState</code>.</p>
<p>What you need to do is to modify your <code>selectDayAndTimeL</code> function so that it can take those widget-specific stuff as parameters.</p>
<p>So, in essence what you would do is:</p>
<p>1st create the function as a standalone function, for instance in a new dart file. Make sure to remove the widget-specific stuff from the body and leave them as parameters:</p>
<pre class="lang-dart prettyprint-override"><code>  Future selectDayAndTimeL(BuildContext context, void Function(DateTime) onDateAndTimeSelected) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }

      onDateAndTimeSelected(DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      ));
    // print('...');
  }
</code>```

2nd, on your new Statefull widgets, you may now call this function, make sure that you send the new onDateAndTimeSelected parameter:

class SecondWidget extends StatefulWidget {
  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}

class _SecondWidgetState extends State<SecondWidget> {
  DateTime? selectedDateAndTime;

  @override
  Widget build(BuildContext context) {
    return FlatButton(
          onPressed: () => selectDayAndTimeL(context,
        setState((DateTime selectedValue) {
             selectedDateAndTime = selectedValue;
         } )
    ));
  }
}
```

And then you could just follow the same logic for any other Statefull widget that needs to call your function.

Body:
i have this funtion which handles my Date and Time picker widget ...Code bellow...

Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

initially it was inside my add new task class/dart file "Stateful Widget", and everything was working fine but now i want to also use that function on the Home screen when a button is pressed.

Then i checked a StackOverflow question on how to call a function from another dart file which the solution required that i keep the Function on a different dart file then call it from there like this Example

void launchWebView () {
  print("1234");
}

when i did i was getting an error which i lookedup and it was because of the "setState" in my function so i needed to put it inside a Stateful widget,

import 'package:flutter/material.dart';

class SelectDateAndTime extends StatefulWidget {
  @override
  _SelectDateAndTimeState createState() => _SelectDateAndTimeState();
}

class _SelectDateAndTimeState extends State<SelectDateAndTime> {

  DateTime? _selectedDate;
// DateTime _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

And that was the only difference from my code with the example i followed and i was still getting an error when i tried calling the funtion, and i have checked all the quetions related to clling functions from another dart file / class and none of them had SetState so their solution didn't work for me

This is the error i got when i called just the Function Name

Bellow s the error i got when i tried to call

onPressed: () => selectedDateAndTime!.selectDayAndTimeL(),

what should i do from here?

Body:
I'm guessing that you originally had a Statefull widget, that probably looked something like this:

class OriginalWidget extends StatefulWidget {
  @override
  _OriginalWidgetState createState() => _OriginalWidgetState();
}

class _OriginalWidgetState extends State<OriginalWidget> {

  DateTime? _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
          onPressed: () => selectDayAndTimeL(context));
  }
}

Now, what you want to do is to reuse the logic of your selectDayAndTimeL function.

The problem is that both the selectedDateAndTime variable and the setState method are specific to the Statefull widget _OriginalWidgetState.

What you need to do is to modify your selectDayAndTimeL function so that it can take those widget-specific stuff as parameters.

So, in essence what you would do is:

1st create the function as a standalone function, for instance in a new dart file. Make sure to remove the widget-specific stuff from the body and leave them as parameters:

  Future selectDayAndTimeL(BuildContext context, void Function(DateTime) onDateAndTimeSelected) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }

      onDateAndTimeSelected(DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      ));
    // print('...');
  }

2nd, on your new Statefull widgets, you may now call this function, make sure that you send the new onDateAndTimeSelected parameter:

class SecondWidget extends StatefulWidget {
  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}

class _SecondWidgetState extends State<SecondWidget> {
  DateTime? selectedDateAndTime;

  @override
  Widget build(BuildContext context) {
    return FlatButton(
          onPressed: () => selectDayAndTimeL(context,
        setState((DateTime selectedValue) {
             selectedDateAndTime = selectedValue;
         } )
    ));
  }
}

And then you could just follow the same logic for any other Statefull widget that needs to call your function.


来源: stackexchange

问:
Chopping a string into a vector of fixed width character elements
I have an object containing a text string:

```<code>x <- "xxyyxyxy"
</code>```

and I want to split that into a vector with each element containing two letters:

```<code>[1] "xx" "yy" "xy" "xy"
</code>```

It seems like the strsplit should be my ticket, but since I have no regular expression foo, I can't figure out how to make this function chop the string up into chunks the way I want it. How should I do this?

答:
I set out looking for a vectorised solution to this, in order to avoid
lapply()ing one of the single string solutions across long vectors. Failing
to find an existing solution, I somehow fell down a rabbit hole of
painstakingly writing one in C. It ended up hilariously complicated compared
to the many one-line R solutions shown here (no thanks to me deciding to also
want to handle Unicode strings to match the R versions), but I thought I’d
share the result, in case it somehow someday helps somebody. Here’s what
eventually became of that:

#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>

// Find the width (in bytes) of a UTF-8 character, given its first byte
size_t utf8charw(char b) {
  if (b == 0x00) return 0;
  if ((b & 0x80) == 0x00) return 1;
  if ((b & 0xe0) == 0xc0) return 2;
  if ((b & 0xf0) == 0xe0) return 3;
  if ((b & 0xf8) == 0xf0) return 4;
  return 1; // Really an invalid character, but move on
}

// Find the number of UTF-8 characters in a string
size_t utf8nchar(const char* str) {
  size_t nchar = 0;
  while (*str != '\0') {
    str += utf8charw(*str); nchar++;
  }
  return nchar;
}

SEXP C_str_chunk(SEXP x, SEXP size_) {
  // Allocate a list to store the result
  R_xlen_t n = Rf_xlength(x);
  SEXP result = PROTECT(Rf_allocVector(VECSXP, n));

  int size = Rf_asInteger(size_);

  for (R_xlen_t i = 0; i < n; i++) {
    const char* str = Rf_translateCharUTF8(STRING_ELT(x, i));

    // Figure out number of chunks
    size_t nchar = utf8nchar(str);
    size_t nchnk = nchar / size + (nchar % size != 0);
    SEXP chunks = PROTECT(Rf_allocVector(STRSXP, nchnk));

    for (size_t j = 0, nbytes = 0; j < nchnk; j++, str += nbytes) {
      // Find size of next chunk in bytes
      nbytes = 0;
      for (int cp = 0; cp < size; cp++) {
        nbytes += utf8charw(str[nbytes]);
      }

      // Assign to chunks vector as an R string
      SET_STRING_ELT(chunks, j, Rf_mkCharLenCE(str, nbytes, CE_UTF8));
    }

    SET_VECTOR_ELT(result, i, chunks);
  }

  // Clean up
  UNPROTECT(n);
  UNPROTECT(1);

  return result;
}
```
<p>I then put this monstrosity into a file called <code>str_chunk.c</code>, and compiled with <code>R CMD SHLIB str_chunk.c</code>.
To try it out, we need some set-up on the R side:</p>
<pre class="lang-r prettyprint-override"><code>str_chunk <- function(x, n) {
  .Call("C_str_chunk", x, as.integer(n))
}

# The (currently) accepted answer
str_chunk_one <- function(x, n) {
  substring(x, seq(1, nchar(x), n), seq(n, nchar(x), n))
}

dyn.load("str_chunk.dll")
</code>```

So what we’ve achieved with the C version is to take a vector inputs and return a list:

str_chunk(rep("0123456789AB", 2), 2)
#> [[1]]
#> [1] "01" "23" "45" "67" "89" "AB"
#>
#> [[2]]
#> [1] "01" "23" "45" "67" "89" "AB"
```
<p>Now off we go with benchmarking.</p>
<p>We start off strong with a 200x improvement for a long(ish) vector of
short strings:</p>
<pre class="lang-r prettyprint-override"><code>x <- rep("0123456789AB", 1000)
microbenchmark::microbenchmark(
  accepted = lapply(x, str_chunk_one, 2),
  str_chunk(x, 2)
) |> print(unit = "relative")
#> Unit: relative
#>             expr      min       lq     mean  median       uq      max neval
#>         accepted 229.5826 216.8246 182.5449 203.785 182.3662 25.88823   100
#>  str_chunk(x, 2)   1.0000   1.0000   1.0000   1.000   1.0000  1.00000   100
</code>```

… which then shrinks to a distinctly less impressive 3x improvement for
large strings.

x <- rep(strrep("0123456789AB", 1000), 10)
microbenchmark::microbenchmark(
  accepted = lapply(x, str_chunk_one, 2),
  str_chunk(x, 2)
) |> print(unit = "relative")
#> Unit: relative
#>             expr     min       lq     mean   median       uq      max neval
#>         accepted 2.77981 2.802641 3.304573 2.787173 2.846268 13.62319   100
#>  str_chunk(x, 2) 1.00000 1.000000 1.000000 1.000000 1.000000  1.00000   100

dyn.unload("str_chunk.dll")
```

So, was it worth it? Well, absolutely not considering how long it took to
actually get working properly – But if this was in a package, it would have
saved quite a lot of time in my use-case (short strings, long vectors).

ContentLicense: CC BY-SA 4.0

Body:
I have an object containing a text string:

x <- "xxyyxyxy"

and I want to split that into a vector with each element containing two letters:

[1] "xx" "yy" "xy" "xy"

It seems like the strsplit should be my ticket, but since I have no regular expression foo, I can't figure out how to make this function chop the string up into chunks the way I want it. How should I do this?

Body:
I set out looking for a vectorised solution to this, in order to avoid
lapply()ing one of the single string solutions across long vectors. Failing
to find an existing solution, I somehow fell down a rabbit hole of
painstakingly writing one in C. It ended up hilariously complicated compared
to the many one-line R solutions shown here (no thanks to me deciding to also
want to handle Unicode strings to match the R versions), but I thought I’d
share the result, in case it somehow someday helps somebody. Here’s what
eventually became of that:

#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>

// Find the width (in bytes) of a UTF-8 character, given its first byte
size_t utf8charw(char b) {
  if (b == 0x00) return 0;
  if ((b & 0x80) == 0x00) return 1;
  if ((b & 0xe0) == 0xc0) return 2;
  if ((b & 0xf0) == 0xe0) return 3;
  if ((b & 0xf8) == 0xf0) return 4;
  return 1; // Really an invalid character, but move on
}

// Find the number of UTF-8 characters in a string
size_t utf8nchar(const char* str) {
  size_t nchar = 0;
  while (*str != '\0') {
    str += utf8charw(*str); nchar++;
  }
  return nchar;
}

SEXP C_str_chunk(SEXP x, SEXP size_) {
  // Allocate a list to store the result
  R_xlen_t n = Rf_xlength(x);
  SEXP result = PROTECT(Rf_allocVector(VECSXP, n));

  int size = Rf_asInteger(size_);

  for (R_xlen_t i = 0; i < n; i++) {
    const char* str = Rf_translateCharUTF8(STRING_ELT(x, i));

    // Figure out number of chunks
    size_t nchar = utf8nchar(str);
    size_t nchnk = nchar / size + (nchar % size != 0);
    SEXP chunks = PROTECT(Rf_allocVector(STRSXP, nchnk));

    for (size_t j = 0, nbytes = 0; j < nchnk; j++, str += nbytes) {
      // Find size of next chunk in bytes
      nbytes = 0;
      for (int cp = 0; cp < size; cp++) {
        nbytes += utf8charw(str[nbytes]);
      }

      // Assign to chunks vector as an R string
      SET_STRING_ELT(chunks, j, Rf_mkCharLenCE(str, nbytes, CE_UTF8));
    }

    SET_VECTOR_ELT(result, i, chunks);
  }

  // Clean up
  UNPROTECT(n);
  UNPROTECT(1);

  return result;
}

I then put this monstrosity into a file called str_chunk.c, and compiled with R CMD SHLIB str_chunk.c.
To try it out, we need some set-up on the R side:

str_chunk <- function(x, n) {
  .Call("C_str_chunk", x, as.integer(n))
}

# The (currently) accepted answer
str_chunk_one <- function(x, n) {
  substring(x, seq(1, nchar(x), n), seq(n, nchar(x), n))
}

dyn.load("str_chunk.dll")

So what we’ve achieved with the C version is to take a vector inputs and return a list:

str_chunk(rep("0123456789AB", 2), 2)
#> [[1]]
#> [1] "01" "23" "45" "67" "89" "AB"
#>
#> [[2]]
#> [1] "01" "23" "45" "67" "89" "AB"

Now off we go with benchmarking.

We start off strong with a 200x improvement for a long(ish) vector of
short strings:

x <- rep("0123456789AB", 1000)
microbenchmark::microbenchmark(
  accepted = lapply(x, str_chunk_one, 2),
  str_chunk(x, 2)
) |> print(unit = "relative")
#> Unit: relative
#>             expr      min       lq     mean  median       uq      max neval
#>         accepted 229.5826 216.8246 182.5449 203.785 182.3662 25.88823   100
#>  str_chunk(x, 2)   1.0000   1.0000   1.0000   1.000   1.0000  1.00000   100

… which then shrinks to a distinctly less impressive 3x improvement for
large strings.

x <- rep(strrep("0123456789AB", 1000), 10)
microbenchmark::microbenchmark(
  accepted = lapply(x, str_chunk_one, 2),
  str_chunk(x, 2)
) |> print(unit = "relative")
#> Unit: relative
#>             expr     min       lq     mean   median       uq      max neval
#>         accepted 2.77981 2.802641 3.304573 2.787173 2.846268 13.62319   100
#>  str_chunk(x, 2) 1.00000 1.000000 1.000000 1.000000 1.000000  1.00000   100

dyn.unload("str_chunk.dll")

So, was it worth it? Well, absolutely not considering how long it took to
actually get working properly – But if this was in a package, it would have
saved quite a lot of time in my use-case (short strings, long vectors).


问:
Calculating year end balance and year end interest with compound interest
I am trying to create a function that calculates year end balance and year end interest based on the monthly deposits and monthly interests that accumulate in the year. For some reason, it is not outputting the correct numbers. Whenever I input 1 for investment, 50 for monthly deposit, %5 for annual interest, and 5 for years. It should output:

Year   Year End Balance   Year End Earned Interest

1       $617.55               $16.55

2       $1265.65               $48.10

3       $1946.90               $81.25

4       $2663.01               $116.11

5       $3415.76               $152.75

Instead, it is outputting:

Year   Year End Balance   Year End Earned Interest

1       $600.76               $0.16

2       $1205.65               $0.63

3       $1817.61               $1.39

4       $2440.90               $2.45

5       $3078.92               $3.82

Can someone help with function reportWithMonthlyPay()?

Here is the code I have currently:

```<code>// BankingApp.cpp : This file contains the 'main' function. Program execution begins and
ends there.
//

#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;

class Bank {
public:
    void dataInput();
    void displayInput();
    void reportWithoutMonthlyPay();
    void reportWithMonthlyPay();

private:
    double investment;
    double deposit;
    int years;
    double interest;
    double monthly_interest;
    double monthly_balance;
    double year_end_balance;
    double year_end_interest;
    vector<int> month_numbers;
    vector<int> year_numbers;
};

void Bank::dataInput() {
    cout << "Initial Investment Amount: " << endl;
    cin >> investment;
    cout << "Monthly Deposit: " << endl;
    cin >> deposit;
    cout << "Annual Interest: " << endl;
    cin >> interest;
    cout << "Number of years: " << endl;
    cin >> years;
    system("pause");       // Windows-specific command that tells
platform to pause
program
    cout << endl;
    if (cin.get()) {        // If any key is entered, displayInput
 function is called
        displayInput();
    }

}

void Bank::displayInput() {
    cout << "Initial Investment Amount: " << "$" << investment <<
 endl;
    cout << "Monthly Deposit: " << "$" << deposit << endl;
    cout << "Annual Interest: " << interest << "%" << endl;
    cout << "Number of years: " << years << endl;
    system("pause");
    cout << endl;
    reportWithoutMonthlyPay();
   }

  void Bank::reportWithoutMonthlyPay() {
    year_numbers.resize(years);
    interest = interest / 100;
    year_end_balance = investment + (investment * interest);
    year_end_interest = investment * interest;
     cout << "   Balance and Interest Without Additional Monthly
 Deposit   " << endl;
    cout << "=============================================================" <<
  endl;
    cout << "Year    Year End Balance    Year End Earned Interest"
  << endl;
    cout << "-------------------------------------------------------------" << endl;
    for (int i = 0; i < year_numbers.size(); i++) {
        year_numbers[i] = i + 1;
        cout << year_numbers[i] << "        $" << fixed <<
  setprecision(2) <<
    year_end_balance << "               $" << year_end_interest <<
  endl;
        year_numbers[i]++;
        year_end_balance += year_end_interest;
        year_end_interest = year_end_balance * interest;
    }
    cout << endl;
    system("pause");
    reportWithMonthlyPay();
}

 void Bank::reportWithMonthlyPay() {
 year_numbers.resize(years);
 month_numbers.resize(12);
 year_end_interest = 0;
 year_end_balance = investment;
  cout << "   Balance and Interest With Additional Monthly Deposit
  " << endl;
   cout <<
  "==========================================================" <<
 endl;
   cout << "Year     Year End Balance   Year End Earned Interest"
  << endl;
   cout << "-------------------------------------------------------
---" << endl;
   for (int i = 0; i < year_numbers.size(); i++) {
       year_numbers[i] = i + 1;
       for (int j = 0; j < month_numbers.size(); j++) {
        year_end_balance += deposit;
        monthly_interest = year_end_balance * (interest /
(double)12);
        year_end_balance += monthly_interest;
        year_end_interest += monthly_interest;
        month_numbers[j]++;
    }
    cout << year_numbers[i] << "        $" << fixed <<
   setprecision(2) << year_end_balance << "               $" <<
   year_end_interest << endl;
    year_numbers[i]++;
   }

int main()
{
    Bank userInput;

    userInput.dataInput();
}
</code>```

答:
ok, well i run your code and its all over the place. inputting 1,50,5,5 as entered in the question is doesnt do any monthly payment processing  because it only calls reportWithoutMonthlyPay

If I change the code to call reportWithMonthlyPay the output is nothing like you show. So then I fixed one line and the output is close

```<code>            monthly_interest = year_end_balance * (interest /  (double)1200);
</code>```

in reportWithMonthy. Ie scale down interest by 100.

output is

```<code>Year     Year End Balance   Year End Earned Interest
-------------------------------------------------------  -- -
1        $617.55               $16.55
2        $1265.65               $64.65
3        $1946.90               $145.90
4        $2663.01               $262.01
5        $3415.76               $414.76
</code>```

still not like what you gave as expected output but closer. I leave it to you to find out why

OK cracked that too. You need to reset year_end_interes to 0 for each year loop in reportWithMonthlyPay. When I do that

```<code>==========================================================
Year     Year End Balance   Year End Earned Interest
-------------------------------------------------------  -- -
1        $617.55               $16.55
2        $1265.65               $48.10
3        $1946.90               $81.25
4        $2663.01               $116.11
5        $3415.76               $152.75
</code>```

so A for me on the assignment

Body:
I am trying to create a function that calculates year end balance and year end interest based on the monthly deposits and monthly interests that accumulate in the year. For some reason, it is not outputting the correct numbers. Whenever I input 1 for investment, 50 for monthly deposit, %5 for annual interest, and 5 for years. It should output:

Year   Year End Balance   Year End Earned Interest

1       $617.55               $16.55

2       $1265.65               $48.10

3       $1946.90               $81.25

4       $2663.01               $116.11

5       $3415.76               $152.75

Instead, it is outputting:

Year   Year End Balance   Year End Earned Interest

1       $600.76               $0.16

2       $1205.65               $0.63

3       $1817.61               $1.39

4       $2440.90               $2.45

5       $3078.92               $3.82

Can someone help with function reportWithMonthlyPay()?

Here is the code I have currently:

// BankingApp.cpp : This file contains the 'main' function. Program execution begins and
ends there.
//

#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;

class Bank {
public:
    void dataInput();
    void displayInput();
    void reportWithoutMonthlyPay();
    void reportWithMonthlyPay();

private:
    double investment;
    double deposit;
    int years;
    double interest;
    double monthly_interest;
    double monthly_balance;
    double year_end_balance;
    double year_end_interest;
    vector<int> month_numbers;
    vector<int> year_numbers;
};

void Bank::dataInput() {
    cout << "Initial Investment Amount: " << endl;
    cin >> investment;
    cout << "Monthly Deposit: " << endl;
    cin >> deposit;
    cout << "Annual Interest: " << endl;
    cin >> interest;
    cout << "Number of years: " << endl;
    cin >> years;
    system("pause");       // Windows-specific command that tells
platform to pause
program
    cout << endl;
    if (cin.get()) {        // If any key is entered, displayInput
 function is called
        displayInput();
    }

}

void Bank::displayInput() {
    cout << "Initial Investment Amount: " << "$" << investment <<
 endl;
    cout << "Monthly Deposit: " << "$" << deposit << endl;
    cout << "Annual Interest: " << interest << "%" << endl;
    cout << "Number of years: " << years << endl;
    system("pause");
    cout << endl;
    reportWithoutMonthlyPay();
   }

  void Bank::reportWithoutMonthlyPay() {
    year_numbers.resize(years);
    interest = interest / 100;
    year_end_balance = investment + (investment * interest);
    year_end_interest = investment * interest;
     cout << "   Balance and Interest Without Additional Monthly
 Deposit   " << endl;
    cout << "=============================================================" <<
  endl;
    cout << "Year    Year End Balance    Year End Earned Interest"
  << endl;
    cout << "-------------------------------------------------------------" << endl;
    for (int i = 0; i < year_numbers.size(); i++) {
        year_numbers[i] = i + 1;
        cout << year_numbers[i] << "        $" << fixed <<
  setprecision(2) <<
    year_end_balance << "               $" << year_end_interest <<
  endl;
        year_numbers[i]++;
        year_end_balance += year_end_interest;
        year_end_interest = year_end_balance * interest;
    }
    cout << endl;
    system("pause");
    reportWithMonthlyPay();
}

 void Bank::reportWithMonthlyPay() {
 year_numbers.resize(years);
 month_numbers.resize(12);
 year_end_interest = 0;
 year_end_balance = investment;
  cout << "   Balance and Interest With Additional Monthly Deposit
  " << endl;
   cout <<
  "==========================================================" <<
 endl;
   cout << "Year     Year End Balance   Year End Earned Interest"
  << endl;
   cout << "-------------------------------------------------------
---" << endl;
   for (int i = 0; i < year_numbers.size(); i++) {
       year_numbers[i] = i + 1;
       for (int j = 0; j < month_numbers.size(); j++) {
        year_end_balance += deposit;
        monthly_interest = year_end_balance * (interest /
(double)12);
        year_end_balance += monthly_interest;
        year_end_interest += monthly_interest;
        month_numbers[j]++;
    }
    cout << year_numbers[i] << "        $" << fixed <<
   setprecision(2) << year_end_balance << "               $" <<
   year_end_interest << endl;
    year_numbers[i]++;
   }

int main()
{
    Bank userInput;

    userInput.dataInput();
}

Body:
ok, well i run your code and its all over the place. inputting 1,50,5,5 as entered in the question is doesnt do any monthly payment processing  because it only calls reportWithoutMonthlyPay

If I change the code to call reportWithMonthlyPay the output is nothing like you show. So then I fixed one line and the output is close

            monthly_interest = year_end_balance * (interest /  (double)1200);

in reportWithMonthy. Ie scale down interest by 100.

output is

Year     Year End Balance   Year End Earned Interest
-------------------------------------------------------  -- -
1        $617.55               $16.55
2        $1265.65               $64.65
3        $1946.90               $145.90
4        $2663.01               $262.01
5        $3415.76               $414.76

still not like what you gave as expected output but closer. I leave it to you to find out why

OK cracked that too. You need to reset year_end_interes to 0 for each year loop in reportWithMonthlyPay. When I do that

==========================================================
Year     Year End Balance   Year End Earned Interest
-------------------------------------------------------  -- -
1        $617.55               $16.55
2        $1265.65               $48.10
3        $1946.90               $81.25
4        $2663.01               $116.11
5        $3415.76               $152.75

so A for me on the assignment


问:
PHP - Filter error messages
I have found a PHP system that have a interesting feature.

If there is a error on the code, the default error message is not showed, the programmer have created a way to filter those messages and create a log to show those error messages as simple alerts on the administrator view.

How do I do that?

Thanks in advance

MORE DETAILS

Server: Apache

The system is from a company in Brazil and do not have access to it, it was just presented to me

答:
Use set_error_handler

http://php.net/manual/en/function.set-error-handler.php

ContentLicense: CC BY-SA 3.0

Title: PHP - Filter error messages


问:
Read data from own api url and use a interface
I try to get the json-data from a api-server. I can't add this to the variable.
I got the error

Type is missing the following properties from Type "Observable" missing the properties from type "GAMELIST[]": "length, pop, push, concat" und 27 weitere.ts(2740)

Where I is my mistake?

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import gamelistjson from '../../assets/data/gamelist.json';

interface GAMELIST {
    id: number,
    title: string,
    releasedate: number,
    shortdescription: string,
    adddate: string,
    changedate: string,
    tags: any
}

@Component({
  selector: 'app-gamelist',
  templateUrl: './gamelist.component.html',
  styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {

  private data:any = [];
  games: GAMELIST[] = this.getJSON();
  idspiel: number = 0;

  constructor(private router: Router, private http: HttpClient) {
      this.getJSON().subscribe(data => {
          console.log(data);
      });
  }

  ngOnInit(): void {
  }

  public getJSON(): Observable<any> {
    return this.http.get("https://example.org/api/gamelist");
  }

  onSelect(game: any){
    this.router.navigate(['/spiel', game.id, game.title]);
  }
}
</code>```

答:
I think this is the problematic line.

```<code>games: GAMELIST[] = this.getJSON();
</code>```

this.getJson() returns an observable and you're trying to assign observable to GAMELIST[] type. You should assign it inside the subscription

Here is the changed code;

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import gamelistjson from '../../assets/data/gamelist.json';

interface GAMELIST {
    id: number,
    title: string,
    releasedate: number,
    shortdescription: string,
    adddate: string,
    changedate: string,
    tags: any
}

@Component({
  selector: 'app-gamelist',
  templateUrl: './gamelist.component.html',
  styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {

  private data:any = [];
  games: GAMELIST[];
  idspiel: number = 0;

  constructor(private router: Router, private http: HttpClient) {

  }

  ngOnInit(): void {
  this.getJSON().subscribe(data => {
          this.games = data;
      });
  }

  getJSON(): Observable<GAMELIST[]> {
    return this.http.get("https://example.org/api/gamelist");
  }

  onSelect(game: any){
    this.router.navigate(['/spiel', game.id, game.title]);
  }
}

</code>```

Body:
I try to get the json-data from a api-server. I can't add this to the variable.
I got the error

Type is missing the following properties from Type "Observable" missing the properties from type "GAMELIST[]": "length, pop, push, concat" und 27 weitere.ts(2740)

Where I is my mistake?

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import gamelistjson from '../../assets/data/gamelist.json';

interface GAMELIST {
    id: number,
    title: string,
    releasedate: number,
    shortdescription: string,
    adddate: string,
    changedate: string,
    tags: any
}

@Component({
  selector: 'app-gamelist',
  templateUrl: './gamelist.component.html',
  styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {

  private data:any = [];
  games: GAMELIST[] = this.getJSON();
  idspiel: number = 0;

  constructor(private router: Router, private http: HttpClient) {
      this.getJSON().subscribe(data => {
          console.log(data);
      });
  }

  ngOnInit(): void {
  }

  public getJSON(): Observable<any> {
    return this.http.get("https://example.org/api/gamelist");
  }

  onSelect(game: any){
    this.router.navigate(['/spiel', game.id, game.title]);
  }
}

Body:
I think this is the problematic line.

games: GAMELIST[] = this.getJSON();

this.getJson() returns an observable and you're trying to assign observable to GAMELIST[] type. You should assign it inside the subscription

Here is the changed code;

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import gamelistjson from '../../assets/data/gamelist.json';

interface GAMELIST {
    id: number,
    title: string,
    releasedate: number,
    shortdescription: string,
    adddate: string,
    changedate: string,
    tags: any
}

@Component({
  selector: 'app-gamelist',
  templateUrl: './gamelist.component.html',
  styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {

  private data:any = [];
  games: GAMELIST[];
  idspiel: number = 0;

  constructor(private router: Router, private http: HttpClient) {

  }

  ngOnInit(): void {
  this.getJSON().subscribe(data => {
          this.games = data;
      });
  }

  getJSON(): Observable<GAMELIST[]> {
    return this.http.get("https://example.org/api/gamelist");
  }

  onSelect(game: any){
    this.router.navigate(['/spiel', game.id, game.title]);
  }
}


问:
Find the index number of where a variable fits between in pandas column
I have the following dataframe:

```<code>import pandas as pd
#Create DF
d = {
     'Category': ['A','B','C','D','E','F','G'],
    'Value':[10,20,30,40,50,60,70],
    }

df = pd.DataFrame(data=d)
df
</code>```

I then have a defined variable of a number that may change:
e.g val = 45

How do i search the dataframe column Value and return the index number of the row where val  would fit.

Expected value would be:

for val = 45 the index i would like returned is 4

for val = 22 the index i would like returned is 2

for val = 60 the index i would like returned is 6 (would go after if it has a match)

Any help would be greatly appreciated!

答:
You can just use argmax

```<code>(df['Value'] > 45).argmax() # 4
(df['Value'] > 22).argmax() # 2
(df['Value'] > 60).argmax() # 6
</code>```

This assumes 'Value' is sorted, but it works because the result of the comparison is a boolean array, so it is returning the index of the first True value.

Edit

To be more rigorous, we can support numbers that are greater than any value in the array:

```<code>tmp = (df['Value'] > 100)
index = tmp.argmax() if tmp.any() else len(df)
</code>```

In this case, we correctly get 7 whereas using argmax alone returns 0.

If you hate the extra one line, it looks like you can use the walrus operator in Python 3.8+:

```<code> tmp.argmax() if (tmp := (df['Value'] > 100)).any() else len(df)
</code>```

Correction

Thanks to @Bill, I can see that argmax is in fact deprecated, and idxmax is the correct way to go:

```<code>(df['Value'] > 45).idxmax() # 4
(df['Value'] > 22).idxmax() # 2
(df['Value'] > 60).idxmax() # 6

tmp.idxmax() if (tmp := (df['Value'] > 100)).any() else len(df) # 7
tmp.idxmax() if (tmp := (df['Value'] > 22)).any() else len(df) # 2
</code>```

Body:
I have the following dataframe:

import pandas as pd
#Create DF
d = {
     'Category': ['A','B','C','D','E','F','G'],
    'Value':[10,20,30,40,50,60,70],
    }

df = pd.DataFrame(data=d)
df

I then have a defined variable of a number that may change:
e.g val = 45

How do i search the dataframe column Value and return the index number of the row where val  would fit.

Expected value would be:

for val = 45 the index i would like returned is 4

for val = 22 the index i would like returned is 2

for val = 60 the index i would like returned is 6 (would go after if it has a match)

Any help would be greatly appreciated!

Body:
You can just use argmax

(df['Value'] > 45).argmax() # 4
(df['Value'] > 22).argmax() # 2
(df['Value'] > 60).argmax() # 6

This assumes 'Value' is sorted, but it works because the result of the comparison is a boolean array, so it is returning the index of the first True value.

Edit

To be more rigorous, we can support numbers that are greater than any value in the array:

tmp = (df['Value'] > 100)
index = tmp.argmax() if tmp.any() else len(df)

In this case, we correctly get 7 whereas using argmax alone returns 0.

If you hate the extra one line, it looks like you can use the walrus operator in Python 3.8+:

 tmp.argmax() if (tmp := (df['Value'] > 100)).any() else len(df)

Correction

Thanks to @Bill, I can see that argmax is in fact deprecated, and idxmax is the correct way to go:

(df['Value'] > 45).idxmax() # 4
(df['Value'] > 22).idxmax() # 2
(df['Value'] > 60).idxmax() # 6

tmp.idxmax() if (tmp := (df['Value'] > 100)).any() else len(df) # 7
tmp.idxmax() if (tmp := (df['Value'] > 22)).any() else len(df) # 2


问:
How to fix these Typescript errors on the window object of my Vue app?
In a component of my Vue 3 app I need to work with some custom properties on the Window, like this:

```<code>window.ZohoHCAsapSettings = { //<-- ERROR HERE
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};
</code>```

But I get a TypeScript error on ZohoHCAsapSettings:

```<code>Property 'ZohoHCAsapSettings' does not exist on type 'Window & typeof globalThis'. ts(2339)
</code>```

So I tried extending the window like so:

```<code>interface customWindow extends Window {
  ZohoHCAsapSettings?: unknown;
}
declare const window: customWindow; //<-- ERROR HERE
window.ZohoHCAsapSettings = {
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};
</code>```

This removes the error on ZohoHCAsapSettings but generates another error on declare that says:

```<code>Modifiers cannot appear here. ts(1184)
</code>```

I'm new to TypeScript so not sure what's going on here.

I am using Visual Studio Code as my IDE if that matters.

Any ideas?

答:
How about doing like this:

interface Window { ZohoHCAsapSettings?: unknown; }
```

Works here: TS Playground

Body:
In a component of my Vue 3 app I need to work with some custom properties on the Window, like this:

window.ZohoHCAsapSettings = { //<-- ERROR HERE
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};

But I get a TypeScript error on ZohoHCAsapSettings:

Property 'ZohoHCAsapSettings' does not exist on type 'Window & typeof globalThis'. ts(2339)

So I tried extending the window like so:

interface customWindow extends Window {
  ZohoHCAsapSettings?: unknown;
}
declare const window: customWindow; //<-- ERROR HERE
window.ZohoHCAsapSettings = {
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};

This removes the error on ZohoHCAsapSettings but generates another error on declare that says:

Modifiers cannot appear here. ts(1184)

I'm new to TypeScript so not sure what's going on here.

I am using Visual Studio Code as my IDE if that matters.

Any ideas?

Body:
How about doing like this:

interface Window { ZohoHCAsapSettings?: unknown; }

Works here: TS Playground


问:
Is an incomplete array type compatible with a complete array type?
Question: are int (*)[] and int (*)[1] compatible?

Demo 1:

```<code>typedef int T0;
typedef T0  T1[];
typedef T1* T2[];

T1 x1 = { 13 };
T2 x2 = { &x1 };
</code>```

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

```<code><source>(21): warning C4048: different array subscripts: 'T1 (*)' and 'T0 (*)[1]'
</code>```

Note: the T1 (*) is int (*)[], the T0 (*)[1] is int (*)[1].

Demo 2:

```<code>int c[][1] = {0};
int (*r)[] = c;
</code>```

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

```<code><source>(30): warning C4048: different array subscripts: 'int (*)[0]' and 'int (*)[1]'
</code>```

Extra: C2x, 6.7.6.2 Array declarators, 6:

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values.

答:
Are int (*)[] and int (*)[1] compatible?

It seems that yes.

C2x, 6.2.7 Compatible type and composite type, 5:

EXAMPLE Given the following two file scope declarations:

```<code>int f(int (*)(), double (*)[3]);
int f(int (*)(char *), double (*)[]);
</code>```

The resulting composite type for the function is:

```<code>int f(int (*)(char *), double (*)[3]);
</code>```

and:

A composite type can be constructed from two types that are compatible; ...

Here we see that double (*)[3] is the composite type constructed from types double (*)[3] and double (*)[].

Hence, the types double (*)[3] and double (*)[] are compatible.

Hence, the types int (*)[] and int (*)[1] are compatible.

Body:
Question: are int (*)[] and int (*)[1] compatible?

Demo 1:

typedef int T0;
typedef T0  T1[];
typedef T1* T2[];

T1 x1 = { 13 };
T2 x2 = { &x1 };

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

<source>(21): warning C4048: different array subscripts: 'T1 (*)' and 'T0 (*)[1]'

Note: the T1 (*) is int (*)[], the T0 (*)[1] is int (*)[1].

Demo 2:

int c[][1] = {0};
int (*r)[] = c;

GCC, Clang, ICC generate no diagnostics.

MSVC generates:

<source>(30): warning C4048: different array subscripts: 'int (*)[0]' and 'int (*)[1]'

Extra: C2x, 6.7.6.2 Array declarators, 6:

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values.

Body:
Are int (*)[] and int (*)[1] compatible?

It seems that yes.

C2x, 6.2.7 Compatible type and composite type, 5:

EXAMPLE Given the following two file scope declarations:

int f(int (*)(), double (*)[3]);
int f(int (*)(char *), double (*)[]);

The resulting composite type for the function is:

int f(int (*)(char *), double (*)[3]);

and:

A composite type can be constructed from two types that are compatible; ...

Here we see that double (*)[3] is the composite type constructed from types double (*)[3] and double (*)[].

Hence, the types double (*)[3] and double (*)[] are compatible.

Hence, the types int (*)[] and int (*)[1] are compatible.


答:
There's a ton of ways to do this, but this also works exactly as you would like and is identical to using argmax.</p>
```<code>val = 45

min(df.loc[(df['Value'] > val)].index)
</code>```

Title: Find the index number of where a variable fits between in pandas column

Body:
There's a ton of ways to do this, but this also works exactly as you would like and is identical to using argmax.

val = 45

min(df.loc[(df['Value'] > val)].index)


问:
The code works. But besides that, there is an error. Why and how to fix it?
The code works. But besides that, there is an error. Why and how to fix it?</p>
```<code>def make_casserole
    puts "Preheat oven to 375 degrees"
    ingredients = yield
    puts "Place #{ingredients} in dish"
    puts "Bake for 20 minutes"
end

make_casserole do
  "noodles, celery, and tuna"
end

make_casserole do
  "rice, broccoli, and chicken"
end

make_casserole

blocc.rb:31:in `make_casserole': no block given (yield) (LocalJumpError)from blocc.rb:45:in `<main>'
</code>```

答: You must change the line ingredients = yield to ingredients = yield if block_given?. This is because you invoke the method without passing a block. The method cannot yield if no block given.

Body:
The code works. But besides that, there is an error. Why and how to fix it?

def make_casserole
    puts "Preheat oven to 375 degrees"
    ingredients = yield
    puts "Place #{ingredients} in dish"
    puts "Bake for 20 minutes"
end

make_casserole do
  "noodles, celery, and tuna"
end

make_casserole do
  "rice, broccoli, and chicken"
end

make_casserole

blocc.rb:31:in `make_casserole': no block given (yield) (LocalJumpError)from blocc.rb:45:in `'


问:
Perl: How to encode and decode characters in uppercase alpha letters only
im dealing with that quite some time now. I have characters from lets say the Latin alphabet and want them to be encoded in uppercase alpha strings only. Is there any module that could do this? Or any BaseX encoding that i can modify to just use uc alpha characters?

i currently have implemented parts of it using regex substitutions, but it only covers a few characters and is definetly not efficient :)

anyway if there is no way to deal with that via a module or function,
is there any way to do this efficient via a regex?

i thought about a tr/[\+,\-,...]/[PLUS,MINUS,...]/cds;

but it seems like tr only substitutes char by char and not char by sequence of chars :(

any ideas?

achim

答:
For a bit of fun, here's my Enigma simulator. There isn't an easy way to achieve what you want to do as the wheels don't have any escape chars, and any sequences you invent to represent an escape sequence will significantly reduce the strength of the cipher.

However, 8 bit latin input could be mapped from 0-255 to [A-P][A-P] using 65+($Char&15).65+($Char>>4), and reversed on output, but R-Z would be wasted and there would be a lot of holes in the input, though this could be solved running through gzip first.

The Germans usually used X to represent spaces, and spelled out punctuation if really necessary, trying to avoid spelling the same thing twice the same.
I know it is annoying, but that is the way it is. If we increase the number of letters on the wheels, then it ceases to be an Enigma machine!

```<code>#!/usr/bin/perl
#Tinigma 2010 Usage:tinigma.pl 123 rng ini "GHWVYYDVPQGEWQWVT"
($n,$o,$p)=map(ord()-65,split//,uc$ARGV[1]);($z,$y,$x)=map(ord
()-65,split//,uc$ARGV[2]);($l,$m,$r)=map$_-1,split//,$ARGV[0];
$t=uc$ARGV[3];$t=~s/[^A-Z]//g;$b=26;$j=0;@N=qw(7 25 11 6 1);@R
=('EKMFLGDQVZNTOWYHXUSPAIBRCJ'x3,'AJDKSIRUXBLHWTMCQGZNPYFVOE'x
3,'BDFHJLCPRTXVZNYEIWGAKMUSQO'x3,'ESOVPZJAYQUIRHXLNFTGKDCMWB'x
3,'VZBRGITYUPSDNHLXAWMJQOFECK'x3,'YRUHQSLDPXNGOKMIEBFZCWVJAT'x
3);@t=split//,$t;for$v(@R){$i=0;for(split//,$v){$c=ord($_)-65;
$F[$j][$i]=$c;$R[$j][$c+$b*(int($i/$b))]=$i;$i++}$j++}@S=@{$F[
5]};$f=$y==$F[$m][$N[$m]]?1:0;$i=0;for(@t){if($f){$y++;$y%=$b;
$z++;$z%=$b;$f=0}if($x==$F[$r][$N[$r]]){$y++;$y%=$b;if($y==$F[
$m][$N[$m]]){$f=1}}$x++;$x%=$b;$e.=chr(($R[$r][$R[$m][$R[$l][$
S[$F[$l][$F[$m][$F[$r][ord($_)-39+$x-$n]-$x+$n+$y-$o]-$y+$o+$z
-$p]-$z+$p]+$z-$p]-$z+$p+$y-$o]-$y+$o+$x-$n]-$x+$n)%$b+65)}
print"$e\n"
</code>```

Body:
For a bit of fun, here's my Enigma simulator. There isn't an easy way to achieve what you want to do as the wheels don't have any escape chars, and any sequences you invent to represent an escape sequence will significantly reduce the strength of the cipher.

However, 8 bit latin input could be mapped from 0-255 to [A-P][A-P] using 65+($Char&15).65+($Char>>4), and reversed on output, but R-Z would be wasted and there would be a lot of holes in the input, though this could be solved running through gzip first.

The Germans usually used X to represent spaces, and spelled out punctuation if really necessary, trying to avoid spelling the same thing twice the same.
I know it is annoying, but that is the way it is. If we increase the number of letters on the wheels, then it ceases to be an Enigma machine!

#!/usr/bin/perl
#Tinigma 2010 Usage:tinigma.pl 123 rng ini "GHWVYYDVPQGEWQWVT"
($n,$o,$p)=map(ord()-65,split//,uc$ARGV[1]);($z,$y,$x)=map(ord
()-65,split//,uc$ARGV[2]);($l,$m,$r)=map$_-1,split//,$ARGV[0];
$t=uc$ARGV[3];$t=~s/[^A-Z]//g;$b=26;$j=0;@N=qw(7 25 11 6 1);@R
=('EKMFLGDQVZNTOWYHXUSPAIBRCJ'x3,'AJDKSIRUXBLHWTMCQGZNPYFVOE'x
3,'BDFHJLCPRTXVZNYEIWGAKMUSQO'x3,'ESOVPZJAYQUIRHXLNFTGKDCMWB'x
3,'VZBRGITYUPSDNHLXAWMJQOFECK'x3,'YRUHQSLDPXNGOKMIEBFZCWVJAT'x
3);@t=split//,$t;for$v(@R){$i=0;for(split//,$v){$c=ord($_)-65;
$F[$j][$i]=$c;$R[$j][$c+$b*(int($i/$b))]=$i;$i++}$j++}@S=@{$F[
5]};$f=$y==$F[$m][$N[$m]]?1:0;$i=0;for(@t){if($f){$y++;$y%=$b;
$z++;$z%=$b;$f=0}if($x==$F[$r][$N[$r]]){$y++;$y%=$b;if($y==$F[
$m][$N[$m]]){$f=1}}$x++;$x%=$b;$e.=chr(($R[$r][$R[$m][$R[$l][$
S[$F[$l][$F[$m][$F[$r][ord($_)-39+$x-$n]-$x+$n+$y-$o]-$y+$o+$z
-$p]-$z+$p]+$z-$p]-$z+$p+$y-$o]-$y+$o+$x-$n]-$x+$n)%$b+65)}
print"$e\n"


问:
What happened to my matrix col, it shows NA
I am learning R now and I want to make a matrix to store scores. I don't know why the named_matrix can't show the Student_6. The picture as below shows the Student_NA.

```<code>scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)

scores_matrix <- matrix(scores, nrow = 2,ncol = length(scores)/2, byrow = TRUE)
scores_matrix

named_matrix <- scores_matrix
suffix <- seq(1:n)
rownames(named_matrix) <- paste("Quiz_",suffix[1:nrow(named_matrix)],seq=" ")
colnames(named_matrix)<- paste("Student_",suffix[1:ncol(named_matrix)],seq=" ")
named_matrix
</code>```

答:
Solution

Here I just used your code up to this point:

```<code>scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)

scores_matrix <- matrix(scores,
                        nrow = 2,
                        ncol = length(scores)/2,
                        byrow = TRUE)
scores_matrix
</code>```

Then just entered the names like so:

```<code>colnames(scores_matrix) <- paste("Student", 1:6)
rownames(scores_matrix) <- c("Quiz 1", "Quiz 2")
scores_matrix
</code>```

Which gives you this:

```<code>       Student 1   Student 2   Student 3   Student 4   Student 5   Student 6
Quiz 1          58          46          50          90          42          52
Quiz 2          62          44          96          92          54          82
</code>```

Alternative transpose format

Also if you prefer a column format, since it is in a matrix, you can simply make a transpose of the matrix like so:

```<code>t(scores_matrix)
</code>```

Which creates this:

```<code>            Quiz 1 Quiz 2
Student 1       58     62
Student 2       46     44
Student 3       50     96
Student 4       90     92
Student 5       42     54
Student 6       52     82
</code>```

Body:
I am learning R now and I want to make a matrix to store scores. I don't know why the named_matrix can't show the Student_6. The picture as below shows the Student_NA.

scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)

scores_matrix <- matrix(scores, nrow = 2,ncol = length(scores)/2, byrow = TRUE)
scores_matrix

named_matrix <- scores_matrix
suffix <- seq(1:n)
rownames(named_matrix) <- paste("Quiz_",suffix[1:nrow(named_matrix)],seq=" ")
colnames(named_matrix)<- paste("Student_",suffix[1:ncol(named_matrix)],seq=" ")
named_matrix

Body:
Solution

Here I just used your code up to this point:

scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)

scores_matrix <- matrix(scores,
                        nrow = 2,
                        ncol = length(scores)/2,
                        byrow = TRUE)
scores_matrix

Then just entered the names like so:

colnames(scores_matrix) <- paste("Student", 1:6)
rownames(scores_matrix) <- c("Quiz 1", "Quiz 2")
scores_matrix

Which gives you this:

       Student 1   Student 2   Student 3   Student 4   Student 5   Student 6
Quiz 1          58          46          50          90          42          52
Quiz 2          62          44          96          92          54          82

Alternative transpose format

Also if you prefer a column format, since it is in a matrix, you can simply make a transpose of the matrix like so:

t(scores_matrix)

Which creates this:

            Quiz 1 Quiz 2
Student 1       58     62
Student 2       46     44
Student 3       50     96
Student 4       90     92
Student 5       42     54
Student 6       52     82


问:
How do I detect the current background color of the terminal in which my python script was invoked?
I am using a xfce4 terminal and I want to be able to detect if the background color is set to either black or white (or presumably some other color)

My code looks like this:

```<code>def print_color(string, style, textColor, background):
     string = "\033[{};{};{}m{}\033[m ".format(style,textColor,background,string)
     print(string)
</code>```

I would like to detect the current background color and use it instead of passing it in.

I've tried not setting it, like this:

```<code>def print_color(string, style, textColor):
     string = "\033[{};{};m{}\033[m ".format(style,textColor,string)
     print(string)
</code>```

but that did not work as I expected.

答:
XFCE4 terminal uses VTE, which lacks the ability to respond to queries of the colors.  That would be the SGR flavor of DECRQSS, which is mostly unimplemented in VTE.

(The example shown wouldn't work anyway).  This is unrelated to the GTK+ toolkit.

Body:
I am using a xfce4 terminal and I want to be able to detect if the background color is set to either black or white (or presumably some other color)

My code looks like this:

def print_color(string, style, textColor, background):
     string = "\033[{};{};{}m{}\033[m ".format(style,textColor,background,string)
     print(string)

I would like to detect the current background color and use it instead of passing it in.

I've tried not setting it, like this:

def print_color(string, style, textColor):
     string = "\033[{};{};m{}\033[m ".format(style,textColor,string)
     print(string)

but that did not work as I expected.


问:
Find consecutively increasing numbers in subarray C++
I am currently working on finding at least 4 and 5 consecutive numbers (such as {3, 4, 5, 6} and {2, 3, 4, 5, 6}) in one row of a 2D array.

For example, if you were given a 2D array like this:

```<code>int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};
</code>```

How would you go about testing if only the subarray {6, 3, 4, 5, 1} has at least 4 consecutive numbers?

Here is what I considered at first (please note that I am new to C++):

```<code>int lowerStraight(int arr[][5]) {

    //lower straight code
    int lowerStraightSum = 0;
    int minNum, nextNum, threeNum, fourNum;
    minNum = findMin(arr);
    nextNum = minNum + 1;
    threeNum = nextNum + 1;
    fourNum = threeNum + 1;
    for (int i = 0; i < 5; i++) {
        if (arr[1][i] == nextNum) {
            if (arr[1][i] == threeNum) {
                if (arr[1][i] == fourNum) {
                    lowerStraightSum = 30;
            }
        }
    }
}
cout << lowerStraightSum;
return lowerStraightSum; }
</code>```

The code above prints 0 even if the array has 4 or more consecutive numbers. Plus, it assumes that the minimum number is where the consecutive numbers start, which may not be the case. Any advice on both of these things is appreciated.

答:
The code below:

walks an input matrix of ints;

for each subarray, calls a longest_sequence method to find the longest sequence of consecutive numbers, and

print that subarray if the sequence is equals to or bigger than 4.

It uses:

a range-based for loop to get each subarray from the matrix,

std::ranges::sort to sort the array,

std::max to compare the current longest sequence to the, until now, longest sequence.

You should not need the templated code if you are always going to work with subarrays of length 5.

It doesn't claim to be the fastest method, since it does a sort and then a walk, but it's simple enough.

Demo

#include <algorithm>  // max, sort
#include <iostream>  // cout
#include <ostream>

template <size_t N>
std::ostream& operator<<(std::ostream& os, int (&arr)[N])
{
    os << "{ ";
    bool first{true};
    for (int i : arr)
    {
        os << (first ? "" : ", ") << i;
        first = false;
    }
    return os << " }";
}

template <size_t N>
size_t longest_sequence(int (&arr)[N])
{
    if (N == 0) { return 0; }
    std::ranges::sort(arr);
    size_t max_sequence_length{1};
    size_t current_sequence_length{1};
    for (size_t i{1}; i < N; ++i)
    {
        if (arr[i] == arr[i-1] + 1)
        {
            current_sequence_length++;
        }
        else
        {
            max_sequence_length = std::max(max_sequence_length, current_sequence_length);
            current_sequence_length = 1;
        }
    }
    max_sequence_length = std::max(max_sequence_length, current_sequence_length);
    return max_sequence_length;
}

int main()
{
    int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};
    for (auto& subarr : arr)
    {
        if (longest_sequence(subarr) >= 4)
        {
            std::cout << subarr << "\n";
        }
    }
}

// Outputs:
//
//    { 1, 3, 4, 5, 6 }
```

Body:
I am currently working on finding at least 4 and 5 consecutive numbers (such as {3, 4, 5, 6} and {2, 3, 4, 5, 6}) in one row of a 2D array.

For example, if you were given a 2D array like this:

int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};

How would you go about testing if only the subarray {6, 3, 4, 5, 1} has at least 4 consecutive numbers?

Here is what I considered at first (please note that I am new to C++):

int lowerStraight(int arr[][5]) {

    //lower straight code
    int lowerStraightSum = 0;
    int minNum, nextNum, threeNum, fourNum;
    minNum = findMin(arr);
    nextNum = minNum + 1;
    threeNum = nextNum + 1;
    fourNum = threeNum + 1;
    for (int i = 0; i < 5; i++) {
        if (arr[1][i] == nextNum) {
            if (arr[1][i] == threeNum) {
                if (arr[1][i] == fourNum) {
                    lowerStraightSum = 30;
            }
        }
    }
}
cout << lowerStraightSum;
return lowerStraightSum; }

The code above prints 0 even if the array has 4 or more consecutive numbers. Plus, it assumes that the minimum number is where the consecutive numbers start, which may not be the case. Any advice on both of these things is appreciated.


问:
How to get HttpClient to pass credentials along with the request?
I have a web application (hosted in IIS) that talks to a Windows service. The Windows service is using the ASP.Net MVC Web API (self-hosted), and so can be communicated with over http using JSON. The web application is configured to do impersonation, the idea being that the user who makes the request to the web application should be the user that the web application uses to make the request to the service. The structure looks like this:

(The user highlighted in red is the user being referred to in the examples below.)

The web application makes requests to the Windows service using an HttpClient:

```<code>var httpClient = new HttpClient(new HttpClientHandler()
                      {
                          UseDefaultCredentials = true
                      });
httpClient.GetStringAsync("http://localhost/some/endpoint/");
</code>```

This makes the request to the Windows service, but does not pass the credentials over correctly (the service reports the user as IIS APPPOOL\ASP.NET 4.0). This is not what I want to happen.

If I change the above code to use a WebClient instead, the credentials of the user are passed correctly:

```<code>WebClient c = new WebClient
                   {
                       UseDefaultCredentials = true
                   };
c.DownloadStringAsync(new Uri("http://localhost/some/endpoint/"));
</code>```

With the above code, the service reports the user as the user who made the request to the web application.

What am I doing wrong with the HttpClient implementation that is causing it to not pass the credentials correctly (or is it a bug with the HttpClient)?

The reason I want to use the HttpClient is that it has an async API that works well with Tasks, whereas the WebClient's asyc API needs to be handled with events.

答:
Set identity's impersonation to true and validateIntegratedModeConfiguration to false in web.config

<configuration>
  <system.web>
    <authentication mode="Windows" />
    <authorization>
      <deny users="?" />
    </authorization>
    <identity impersonate="true"/>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" ></validation>
  </system.webServer>
</configuration>
```

Body:
I have a web application (hosted in IIS) that talks to a Windows service. The Windows service is using the ASP.Net MVC Web API (self-hosted), and so can be communicated with over http using JSON. The web application is configured to do impersonation, the idea being that the user who makes the request to the web application should be the user that the web application uses to make the request to the service. The structure looks like this:

(The user highlighted in red is the user being referred to in the examples below.)

The web application makes requests to the Windows service using an HttpClient:

var httpClient = new HttpClient(new HttpClientHandler()
                      {
                          UseDefaultCredentials = true
                      });
httpClient.GetStringAsync("http://localhost/some/endpoint/");

This makes the request to the Windows service, but does not pass the credentials over correctly (the service reports the user as IIS APPPOOL\ASP.NET 4.0). This is not what I want to happen.

If I change the above code to use a WebClient instead, the credentials of the user are passed correctly:

WebClient c = new WebClient
                   {
                       UseDefaultCredentials = true
                   };
c.DownloadStringAsync(new Uri("http://localhost/some/endpoint/"));

With the above code, the service reports the user as the user who made the request to the web application.

What am I doing wrong with the HttpClient implementation that is causing it to not pass the credentials correctly (or is it a bug with the HttpClient)?

The reason I want to use the HttpClient is that it has an async API that works well with Tasks, whereas the WebClient's asyc API needs to be handled with events.


问:
Unknown Pipe in Angular
In the indice page, I would like to format the number to two decimal  in the cours column.

Example: 11345.654589 to 11345.65.

I created a format-num.pipe folder in shared/pipes.

pipes.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule, DecimalPipe } from '@angular/common';
import { FormatNumPipe } from './format-num.pipe';

@NgModule({
  declarations: [
    FormatNumPipe
  ],
  imports: [
    CommonModule
  ],

  providers: [
    DecimalPipe,
  ]

})
export class PipesModule { }
</code>```

format-num.pipe.ts

```<code>import { DecimalPipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'formatNum'
})
export class FormatNumPipe implements PipeTransform {

  constructor(private decimalPipe: DecimalPipe) {
  }

  transform(input: number | string | null | undefined, digitsInfo?: string): string | null {
    return this.decimalPipe.transform(input, digitsInfo);
  }

}
</code>```

indice.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { IndiceComponent } from './indice.component';
import { PipesModule } from 'src/app/shared/pipes/pipes.module';

@NgModule({
  declarations: [
    IndiceComponent
  ],
  imports: [
    CommonModule,
    PipesModule,
  ]
})
export class IndiceModule { }
</code>```

indice.component.html

```<code><td class="text-end"> {{ indiceData.valeur | formatNum:'1.2-2' }} </td>
</code>```

The error message is:

```<code>src/app/views/dashboard/views/market/views/indice/indice.component.html:18:66 - error NG8004: No pipe found with name 'formatNum'.

18  <td class="text-end"> {{ indiceData.valeur | formatNum:'1.2-2' }} </td>
</code>```

My code is available on Stackblitz.

On this page here... They say that it's a problem with the module declaration? But I made a declaration.

答:
I guess that you miss to export your pipe.

In pipes.module.ts:

```<code>exports: [
    FormatNumPipe
  ],
</code>```

NOTE: you have an error (an extra '}') at the final of the format-num.pipe file.

Title: Unknown Pipe in Angular

Body:
In the indice page, I would like to format the number to two decimal  in the cours column.

Example: 11345.654589 to 11345.65.

I created a format-num.pipe folder in shared/pipes.

pipes.module.ts

import { NgModule } from '@angular/core';
import { CommonModule, DecimalPipe } from '@angular/common';
import { FormatNumPipe } from './format-num.pipe';

@NgModule({
  declarations: [
    FormatNumPipe
  ],
  imports: [
    CommonModule
  ],

  providers: [
    DecimalPipe,
  ]

})
export class PipesModule { }

format-num.pipe.ts

import { DecimalPipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'formatNum'
})
export class FormatNumPipe implements PipeTransform {

  constructor(private decimalPipe: DecimalPipe) {
  }

  transform(input: number | string | null | undefined, digitsInfo?: string): string | null {
    return this.decimalPipe.transform(input, digitsInfo);
  }

}

indice.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { IndiceComponent } from './indice.component';
import { PipesModule } from 'src/app/shared/pipes/pipes.module';

@NgModule({
  declarations: [
    IndiceComponent
  ],
  imports: [
    CommonModule,
    PipesModule,
  ]
})
export class IndiceModule { }

indice.component.html

 {{ indiceData.valeur | formatNum:'1.2-2' }}

The error message is:

src/app/views/dashboard/views/market/views/indice/indice.component.html:18:66 - error NG8004: No pipe found with name 'formatNum'.

18   {{ indiceData.valeur | formatNum:'1.2-2' }}

My code is available on Stackblitz.

On this page here... They say that it's a problem with the module declaration? But I made a declaration.

Body:
I guess that you miss to export your pipe.

In pipes.module.ts:

exports: [
    FormatNumPipe
  ],

NOTE: you have an error (an extra '}') at the final of the format-num.pipe file.


问:
Vimeo Embed Video 'Because of its privacy settings, this video cannot be played here'
I am trying to embed my client videos in our website. The videos are set to domain level privacy. I am using the generated code from Vimeo

```<code><div style="padding:28% 0 0 0;position:relative;">
      <iframe src="https://player.vimeo.com/video/{{video_id}}" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen ></iframe>
    </div>
</code>```

where ```{{video_id}}`` is the id of the video. I have followed all the documentation and made sure that the listed domain is spelled correctly.

I am getting:

Sorry

Because of its privacy settings, this video cannot be played here.

Why? What am I doing wrong?

答:
Looks like you got it. Apparently there was a change w/ Django 3.1 that causes this.

https://docs.djangoproject.com/en/4.0/releases/3.1/#security

You can fix it with a Django setting. This is one option, but any of the valid referrer policies that share the origin with Vimeo will work.

```<code>SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
</code>```

Body:
I am trying to embed my client videos in our website. The videos are set to domain level privacy. I am using the generated code from Vimeo

where ```{{video_id}}`` is the id of the video. I have followed all the documentation and made sure that the listed domain is spelled correctly.

I am getting:

Sorry

Because of its privacy settings, this video cannot be played here.

Why? What am I doing wrong?

Body:
Looks like you got it. Apparently there was a change w/ Django 3.1 that causes this.

https://docs.djangoproject.com/en/4.0/releases/3.1/#security

You can fix it with a Django setting. This is one option, but any of the valid referrer policies that share the origin with Vimeo will work.

SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"


问:
Stack with an error when trying to replace missing data
Please I need your help in my mini-project,  I need to create a prediction model using a dataset from Kaggle, I am stuck with an error when I try to replace the missing data from a 'value' column.
It seems that the value are considered like a string, because they have points between numbers.
It's not possible to edit the column manually, it has more than 49000 rows.
How can resolve this problem?

Here's the code and the error:

```<code>x['value'].replace(' ',np.NaN).astype(np.float)
</code>```

ValueError: could not convert string to float: '154.619.063'

The dataset: Multinationals by industrial sector
the dataset from Kaggle
Thank you so much for your help

答:
```<code>import numpy as np
import pandas as pd
from pandas import read_csv
from pandas.plotting import scatter_matrix
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import r2_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
%pylab inline
import seaborn as sns
import pandas_profiling as pp
import plotly.graph_objs as go
from plotly.offline import iplot
import plotly.express as px
import tensorflow as tf
df = pd.read_csv("C:\\Users\\Souf win\\Downloads\\multinationals.csv", delimiter = ';')
def preprocessing(df):
df = df.copy()
df = df.drop(['partner country','ind', 'var','declaring country','unit code','part', 'cou', 'year','year.1', 'unit', 'power_code code', 'power_code' , 'reference period code', 'reference period' ], axis=1)
missing_target_rows=df[df['value'].isna()].index
df= df.drop(missing_target_rows, axis=0).reset_index(drop=True)
df['value']=df['value'].str.replace('.', '').replace(' ',np.NaN).astype(np.float)

for column in ['economic variable' ,'industry' ]:
    dummies=pd.get_dummies(df[column], prefix=column)
    df = pd.concat([df, dummies], axis=1)
    df = df.drop(column, axis=1)
#split df to x and y
y = df['value']
x = df.drop('value', axis=1)
#Train_test split
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7,         shuffle=True, random_state=1 )
#scale x
scaler = StandardScaler()
scaler.fit(x_train)
#x_train = scaler.transform(x_train)
x_train = pd.DataFrame(scaler.transform(x_train), index=x_train.index, columns=x_train.columns)
x_test = pd.DataFrame(scaler.transform(x_test), index=x_test.index, columns=x_test.columns)

return x_train, x_test, y_train, y_test

x_train, x_test, y_train, y_test = preprocessing(df)
x_train
y_train
x_train.shape
inputs = tf.keras.Input(shape=(86,))
x = tf.keras.layers.Dense(128, activation='relu')(inputs)
x = tf.keras.layers.Dense(128, activation='relu')(x)
outputs=tf.keras.layers.Dense(1, activation='linear')(x)

model = tf.keras.Model(inputs=inputs, outputs=outputs)

model.compile(
optimizer='adam',
loss = 'mse'
)

history=model.fit(
    x_train,
    y_train,
    validation_split=0.2,
    batch_size=32,
    epochs=100,
    callbacks= [
        tf.keras.callbacks.EarlyStopping(
        monitor='val_loss',
        patience=3,
        restore_best_weights=True
        )
    ]
)
</code>```

Body:
Please I need your help in my mini-project,  I need to create a prediction model using a dataset from Kaggle, I am stuck with an error when I try to replace the missing data from a 'value' column.
It seems that the value are considered like a string, because they have points between numbers.
It's not possible to edit the column manually, it has more than 49000 rows.
How can resolve this problem?

Here's the code and the error:

x['value'].replace(' ',np.NaN).astype(np.float)

ValueError: could not convert string to float: '154.619.063'

The dataset: Multinationals by industrial sector
the dataset from Kaggle
Thank you so much for your help


问:
Cannot read properties of undefined (reading 'title')
I am trying to add a query param to my link button in pug it should render a pre populated form of the product i want to edit but i keep getting an error in my console which says "Cannot read properties of undefined (reading 'title')" it says this for my imageUrl, price etc, But they have been defined.

admin.js

```<code>const Product = require('../models/product');

exports.getAddProduct = (req, res, next) => {
    //res.render(path.join(rootDir, 'views', '/add-product.pug'))
      res.render('admin/edit-product',
      {pageTitle: 'Add Product',
      path: '/admin/add-product',
      editing: false
     });
   }

exports.postAddProduct=  (req, res, next) => {
    const title = req.body.title;
    const imageUrl = req.body.imageUrl;
    const price = req.body.price;
    const description = req.body.description;
    const product = new Product(title, imageUrl, description, price);
    product.save();
    res.redirect('/');
};

exports.getEditProduct = (req, res, next) => {
      const editMode = req.query.edit;
      if (!editMode) {
          return res.redirect('/');
      }
      const prodId = req.params.productId;
      Product.findById(prodId, product => {
          if (!product) {
              res.redirect('/')
          }
        res.render('admin/edit-product',
        {pageTitle: 'Edit Product',
        path: '/admin/edit-product',
        editing: editMode,
        product: product
       });
      });
   };

exports.getProducts = (req, res, next) => {
    Product.fetchAll((products) => {
        res.render('admin/products', {
        prods: products,
        pageTitle: 'Admin Products',
        path: '/admin/products'
        });
    });
}
</code>```

edit-product.pug

```<code>extends ../layouts/main-layout.pug

block styles
    link(rel="stylesheet", href="/css/product.css")
    link(rel="stylesheet", href="/css/forms.css")

block content
    main
        .main-form
            if editing
                form(action="/admin/edit-product", method="POST")
                    .main-input
                        label(for="title") Title
                        input(type="text", name="title", placeholder="Search Product", value=product.title)
                    .main-input
                        label(for="imageUrl") Image URL
                        input(type="url", name="imageUrl", id="imageUrl", value=product.imageUrl)
                    .main-input
                        label(for="price") Price
                        input(type="number", name="price", id="price", step="0.01", value=product.price)
                    .main-input
                        label(for="description", value=product.description) Description
                        textarea(name="description", id="description", rows="5")
                    .main-button
                        if editing
                            button.btn(type="submit") Update Product
                        else
                            button.btn(type="submit") Add Product
            else
                form(action="/admin/add-product", method="POST")
                    .main-input
                        label(for="title") Title
                        input(type="text", name="title", placeholder="Search Product")
                    .main-input
                        label(for="imageUrl") Image URL
                        input(type="url", name="imageUrl", id="imageUrl")
                    .main-input
                        label(for="price") Price
                        input(type="number", name="price", id="price", step="0.01")
                    .main-input
                        label(for="description") Description
                        textarea(name="description", id="description", rows="5")
                    .main-button
                        if editing
                            button.btn(type="submit") Update Product
                        else
                            button.btn(type="submit") Add Product
</code>```

products.pug

```<code>extends ../layouts/main-layout.pug

block styles
    link(rel="stylesheet", href="/css/main.css")
    link(rel="stylesheet", href="/css/card.css")

block content
    main
        if prods.length > 0
            .grid
                each product in prods
                    article.product-item
                        header.card__header
                            h1.product__title #{product.title}
                        .card__image
                            img(src=`${product.imageUrl}`
                            alt="#{product.title}")
                        .card__content
                            h2.product__price #{product.price}
                            p.product__description #{product.description}
                        .card__actions
                            a(href="/admin/edit-product/:product.id:?edit=true") Edit
                            form(action="/admin/delete-product" method="POST")
                                .btn
                                    button(class="btn", type="submit")  Remove
        else
            h1 No Product
</code>```

答:
now when i do make these changes you have stated, i get an error saying

Cannot read properties of undefined (reading 'length') in my
'products.pug' file
this wasnt happening before until these changes were made.

my 'products.pug' file

```<code>extends ../layouts/main-layout.pug

block styles
    link(rel="stylesheet", href="/css/main.css")
    link(rel="stylesheet", href="/css/card.css")

block content
    main
        if prods.length > 0
            .grid
                each product in prods
                    article.product-item
                        header.card__header
                            h1.product__title #{product.title}
                        .card__image
                            img(src=`${product.imageUrl}`
                            alt="#{product.title}")
                        .card__content
                            h2.product__price #{product.price}
                            p.product__description #{product.description}
                        .card__actions
                            a(href="/admin/edit-product/:product.id:?edit=true") Edit
                            form(action="/admin/delete-product" method="POST")
                                .btn
                                    button(class="btn", type="submit")  Remove
        else
            h1 No Product
</code>```

Body:
I am trying to add a query param to my link button in pug it should render a pre populated form of the product i want to edit but i keep getting an error in my console which says "Cannot read properties of undefined (reading 'title')" it says this for my imageUrl, price etc, But they have been defined.

admin.js

const Product = require('../models/product');

exports.getAddProduct = (req, res, next) => {
    //res.render(path.join(rootDir, 'views', '/add-product.pug'))
      res.render('admin/edit-product',
      {pageTitle: 'Add Product',
      path: '/admin/add-product',
      editing: false
     });
   }

exports.postAddProduct=  (req, res, next) => {
    const title = req.body.title;
    const imageUrl = req.body.imageUrl;
    const price = req.body.price;
    const description = req.body.description;
    const product = new Product(title, imageUrl, description, price);
    product.save();
    res.redirect('/');
};

exports.getEditProduct = (req, res, next) => {
      const editMode = req.query.edit;
      if (!editMode) {
          return res.redirect('/');
      }
      const prodId = req.params.productId;
      Product.findById(prodId, product => {
          if (!product) {
              res.redirect('/')
          }
        res.render('admin/edit-product',
        {pageTitle: 'Edit Product',
        path: '/admin/edit-product',
        editing: editMode,
        product: product
       });
      });
   };

exports.getProducts = (req, res, next) => {
    Product.fetchAll((products) => {
        res.render('admin/products', {
        prods: products,
        pageTitle: 'Admin Products',
        path: '/admin/products'
        });
    });
}

edit-product.pug

extends ../layouts/main-layout.pug

block styles
    link(rel="stylesheet", href="/css/product.css")
    link(rel="stylesheet", href="/css/forms.css")

block content
    main
        .main-form
            if editing
                form(action="/admin/edit-product", method="POST")
                    .main-input
                        label(for="title") Title
                        input(type="text", name="title", placeholder="Search Product", value=product.title)
                    .main-input
                        label(for="imageUrl") Image URL
                        input(type="url", name="imageUrl", id="imageUrl", value=product.imageUrl)
                    .main-input
                        label(for="price") Price
                        input(type="number", name="price", id="price", step="0.01", value=product.price)
                    .main-input
                        label(for="description", value=product.description) Description
                        textarea(name="description", id="description", rows="5")
                    .main-button
                        if editing
                            button.btn(type="submit") Update Product
                        else
                            button.btn(type="submit") Add Product
            else
                form(action="/admin/add-product", method="POST")
                    .main-input
                        label(for="title") Title
                        input(type="text", name="title", placeholder="Search Product")
                    .main-input
                        label(for="imageUrl") Image URL
                        input(type="url", name="imageUrl", id="imageUrl")
                    .main-input
                        label(for="price") Price
                        input(type="number", name="price", id="price", step="0.01")
                    .main-input
                        label(for="description") Description
                        textarea(name="description", id="description", rows="5")
                    .main-button
                        if editing
                            button.btn(type="submit") Update Product
                        else
                            button.btn(type="submit") Add Product

products.pug

extends ../layouts/main-layout.pug

block styles
    link(rel="stylesheet", href="/css/main.css")
    link(rel="stylesheet", href="/css/card.css")

block content
    main
        if prods.length > 0
            .grid
                each product in prods
                    article.product-item
                        header.card__header
                            h1.product__title #{product.title}
                        .card__image
                            img(src=`${product.imageUrl}`
                            alt="#{product.title}")
                        .card__content
                            h2.product__price #{product.price}
                            p.product__description #{product.description}
                        .card__actions
                            a(href="/admin/edit-product/:product.id:?edit=true") Edit
                            form(action="/admin/delete-product" method="POST")
                                .btn
                                    button(class="btn", type="submit")  Remove
        else
            h1 No Product

Body:
now when i do make these changes you have stated, i get an error saying

Cannot read properties of undefined (reading 'length') in my
'products.pug' file
this wasnt happening before until these changes were made.

my 'products.pug' file

extends ../layouts/main-layout.pug

block styles
    link(rel="stylesheet", href="/css/main.css")
    link(rel="stylesheet", href="/css/card.css")

block content
    main
        if prods.length > 0
            .grid
                each product in prods
                    article.product-item
                        header.card__header
                            h1.product__title #{product.title}
                        .card__image
                            img(src=`${product.imageUrl}`
                            alt="#{product.title}")
                        .card__content
                            h2.product__price #{product.price}
                            p.product__description #{product.description}
                        .card__actions
                            a(href="/admin/edit-product/:product.id:?edit=true") Edit
                            form(action="/admin/delete-product" method="POST")
                                .btn
                                    button(class="btn", type="submit")  Remove
        else
            h1 No Product


问:
Android Studio Bumblebee Navigation can't access FragmentDirections for action
I create such action before Android Studio bumblebee update and it was working fine.

```<code>fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}
</code>```

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

```<code>buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My build.gradle App

```<code>plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}
</code>```

答:
Have you tried cleaning and re-building your project?

This may be a similar case to: Safeargs library doesnt generate direction class

If not, given that you are having trouble accessing the FragmentDirections class, it may be due to the default addition of the non-transitive R class property in the Bumblebee update.

In the gradle.properties[app] file you will find:

# Enables namespacing of each library's R class so that its R class includes only the

# resources declared in the library itself and none from the library's dependencies,

# thereby reducing the size of the R class for that library

android.nonTransitiveRClass=true

A good summation of the change and solutions to migrating R classes can be found here:

https://blog.blundellapps.co.uk/speed-up-your-build-non-transitive-r-files/

Best of luck!

Body:
I create such action before Android Studio bumblebee update and it was working fine.

fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My build.gradle App

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}