问:
C# - pass on variable amount of parameters to other method within a method
I know the title is a little bit tricky to understand, but the following example should clarify what I mean:

Imagine you have a method with 2 overloads:

```<code>void Method(int i)
{
    Console.WriteLine("Method(int) called");
}

void Method(int i, string s)
{
    Console.WriteLine("Method(int, string) called");
}
</code>```

Then you have another method that takes a variable amount of parameters:

```<code>void MethodOverload(params dynamic[] parameters)
{
    Method(parameters); // Call one of the overloading methods depending on the parameter amount and their type
}
</code>```

The method above accepts any amount of parameters with any type. I want to call one of the overloading methods depending on the amount of passed parameters and their type.

For example:

```<code>void Run()
{
    TestFuncOverload(5);                 // Output: "testFunc(int) called"
    TestFuncOverload(5, "some text");    // Output: "testFunc(int, string) called"

    TestFuncOverload(5, 5);              //Error
}
</code>```

How does one achieve this in C#?

答:
I could do that with below code. It costs tons of reflection, you can consider another approach to avoid performance problems.</p>

```<code>public class Test
{
    private void Method(int i)
    {
        Console.WriteLine("Method(int) called");
    }
    private void Method(int i, string s)
    {
        Console.WriteLine("Method(int, string) called");
    }
    public void Method(params object[] parameters)
    {
        var m = typeof(Test).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
                                .Where(x => x.Name == "Method" &&
                                           !x.GetParameters()
                                             .Any(p => p.IsDefined(typeof(ParamArrayAttribute), false)))
                                .Where(x => x.GetParameters().Count() == parameters.Count())
                                .Where(x => x.GetParameters()
                                             .Select(y => Type.GetType("System." + y.ParameterType.Name))
                                             .Zip(parameters.Select(z => z.GetType()), Equals)
                                             .All(q => q))
                                .FirstOrDefault();

        if(m == null) throw new Exception ("method not found");

        //null result because of void method.
        var result = m.Invoke(this, parameters);
    }
}

static void Main(string[] args)
{
      Test t = new Test();
      //"Method(int) called"
      t.Method(0);
      //"Method(int, string) called"
      t.Method(0, "");
      //throws ex
      t.Method("", "");
}
</code>```

Body:
I know the title is a little bit tricky to understand, but the following example should clarify what I mean:

Imagine you have a method with 2 overloads:

void Method(int i)
{
    Console.WriteLine("Method(int) called");
}

void Method(int i, string s)
{
    Console.WriteLine("Method(int, string) called");
}

Then you have another method that takes a variable amount of parameters:

void MethodOverload(params dynamic[] parameters)
{
    Method(parameters); // Call one of the overloading methods depending on the parameter amount and their type
}

The method above accepts any amount of parameters with any type. I want to call one of the overloading methods depending on the amount of passed parameters and their type.

For example:

void Run()
{
    TestFuncOverload(5);                 // Output: "testFunc(int) called"
    TestFuncOverload(5, "some text");    // Output: "testFunc(int, string) called"

    TestFuncOverload(5, 5);              //Error
}

How does one achieve this in C#?

Body:
I could do that with below code. It costs tons of reflection, you can consider another approach to avoid performance problems.

public class Test
{
    private void Method(int i)
    {
        Console.WriteLine("Method(int) called");
    }
    private void Method(int i, string s)
    {
        Console.WriteLine("Method(int, string) called");
    }
    public void Method(params object[] parameters)
    {
        var m = typeof(Test).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
                                .Where(x => x.Name == "Method" &&
                                           !x.GetParameters()
                                             .Any(p => p.IsDefined(typeof(ParamArrayAttribute), false)))
                                .Where(x => x.GetParameters().Count() == parameters.Count())
                                .Where(x => x.GetParameters()
                                             .Select(y => Type.GetType("System." + y.ParameterType.Name))
                                             .Zip(parameters.Select(z => z.GetType()), Equals)
                                             .All(q => q))
                                .FirstOrDefault();

        if(m == null) throw new Exception ("method not found");

        //null result because of void method.
        var result = m.Invoke(this, parameters);
    }
}

static void Main(string[] args)
{
      Test t = new Test();
      //"Method(int) called"
      t.Method(0);
      //"Method(int, string) called"
      t.Method(0, "");
      //throws ex
      t.Method("", "");
}


来源: stackexchange

问:
Multi values parameter
Can anyone explain to me how to pass multiple values into a parameter or variable in objective-c as below and how to handle it inside method:</p>

```<code>view.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin
                      | UIViewAutoresizingFlexibleTopMargin;
</code>```

答:
What you're seeing is a simple disjunction between integers, the UIView autoresizing mask parameters are just typedef'ed enum values. You can create these on your own:

```<code>typedef enum {
    IceCreamChocolateSyrup = 1 << 1,
    IceCreamCaramelSyrup = 1 << 2,
    IceCreamMapleSyrup = 1 << 3,
    // etc. up to 31 flavors
} IceCreamSyrups;
</code>```

Then you define a method that accepts them as parameter:

```<code>- (void)addIceCreamSyrups:(IceCreamSyrups)syrups {
    if (syrups & IceCreamChocolateSyrup)
        [self addChocolateSyrup];

    if (syrups & IceCreamCaramelSyrup)
        [self addCaramelSyrup];

    if (syrups & IceCreamMapleSyrup)
        [self addMapleSyrup];
}
</code>```

And call this method as follows:

```<code>[self addIceCreamSyrups:(IceCreamChocolateSyrup | IceCreamMapleSyrup)];
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multi values parameter

Body:
Can anyone explain to me how to pass multiple values into a parameter or variable in objective-c as below and how to handle it inside method:

view.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin
                      | UIViewAutoresizingFlexibleTopMargin;

Body:
What you're seeing is a simple disjunction between integers, the UIView autoresizing mask parameters are just typedef'ed enum values. You can create these on your own:

typedef enum {
    IceCreamChocolateSyrup = 1 << 1,
    IceCreamCaramelSyrup = 1 << 2,
    IceCreamMapleSyrup = 1 << 3,
    // etc. up to 31 flavors
} IceCreamSyrups;

Then you define a method that accepts them as parameter:

- (void)addIceCreamSyrups:(IceCreamSyrups)syrups {
    if (syrups & IceCreamChocolateSyrup)
        [self addChocolateSyrup];

    if (syrups & IceCreamCaramelSyrup)
        [self addCaramelSyrup];

    if (syrups & IceCreamMapleSyrup)
        [self addMapleSyrup];
}

And call this method as follows:

[self addIceCreamSyrups:(IceCreamChocolateSyrup | IceCreamMapleSyrup)];


问:
Not able to run Jupyter notebook on Google Cloud
I am trying to run a Jupyter Notebook on Google Compute Engine(Linux VM).

After all the setting up of the VM instance, I tried to access the Jupyter Notebook on the browser with my url which is of the form:

http://INSTANCE-EXTERNAL-IP-ADDRESS:PORT-NUMBER

The browser loads for a while and then I get a connection timed out. I attempted to connect to the url with chrome and firefox.

Why do I get a connection timed out?

How do I get my notebook running?

答:
Add the firewall rule for the port where you want to run the jupyter (eg. 8888)

jupyter notebook --generate-config
It ensures you to generate the jupyter_notebook_config.py file at location /.jupyter/jupyter_notebook_config.py

sudo vi  /home/spandit/.jupyter/jupyter_notebook_config.py

c.NotebookApp.ip = '*'

c.NotebookApp.open_browser = False

c.NotebookApp.port = 8888

Add above three lines in the config file.

Now run the command

jupyter-notebook --no-browser --port=8888

http://<External Static IP Address>:<Port Number>

e.g.

http://35.238.226.244:8888/

ContentLicense: CC BY-SA 4.0


问:
How to convert two different date formats from a pandas dataframe column into same format?
I have two different date formats in a pandas column such as - DD-MM-YYYY and MM/DD/YYYY and I want to convert them into the same format.

I tried using the code -

```<code>data['SALE DATE'] = pd.to_datetime(data['SALE DATE']).dt.strftime('%m/%d/%Y')
</code>```

but this converts the dates into
DD/MM/YYYY and MM/DD/YYYY into the output - data['SALE DATE']

I want a python solution to overcome this problem. Any leads will be very helpful.

答:
The most intuitive solution is to write a custom conversion function,
someting like:

```<code>def myDateConv(tt):
    sep = tt[2]
    if sep == '-':
        return pd.to_datetime(tt, format='%d-%m-%Y')
    elif sep == '/':
        return pd.to_datetime(tt, format='%m/%d/%Y')
    else:
        return tt
</code>```

and then pass it as a converter for the column in question:

```<code>df = pd.read_csv('Input.csv', converters={'Date': myDateConv})
</code>```

I prepared a CSV file, which read with read_csv without any
custom converter gave the original content and both columns of
object type:

```<code>         Date Input format
0  03-05-2020   DD-MM-YYYY
1  05/07/2020   MM/DD/YYYY
</code>```

But reading the same file with the above converter gave:

```<code>        Date Input format
0 2020-05-03   DD-MM-YYYY
1 2020-05-07   MM/DD/YYYY
</code>```

with Date column of datetime64[ns] type and both dates from
May, just as intended.

Or if you have this DataFrame from other source and you want to
convert this column, run:

```<code>df.Date = df.Date.apply(myDateConv)
</code>```

Body:
I have two different date formats in a pandas column such as - DD-MM-YYYY and MM/DD/YYYY and I want to convert them into the same format.

I tried using the code -

data['SALE DATE'] = pd.to_datetime(data['SALE DATE']).dt.strftime('%m/%d/%Y')

but this converts the dates into
DD/MM/YYYY and MM/DD/YYYY into the output - data['SALE DATE']

I want a python solution to overcome this problem. Any leads will be very helpful.

Body:
The most intuitive solution is to write a custom conversion function,
someting like:

def myDateConv(tt):
    sep = tt[2]
    if sep == '-':
        return pd.to_datetime(tt, format='%d-%m-%Y')
    elif sep == '/':
        return pd.to_datetime(tt, format='%m/%d/%Y')
    else:
        return tt

and then pass it as a converter for the column in question:

df = pd.read_csv('Input.csv', converters={'Date': myDateConv})

I prepared a CSV file, which read with read_csv without any
custom converter gave the original content and both columns of
object type:

         Date Input format
0  03-05-2020   DD-MM-YYYY
1  05/07/2020   MM/DD/YYYY

But reading the same file with the above converter gave:

        Date Input format
0 2020-05-03   DD-MM-YYYY
1 2020-05-07   MM/DD/YYYY

with Date column of datetime64[ns] type and both dates from
May, just as intended.

Or if you have this DataFrame from other source and you want to
convert this column, run:

df.Date = df.Date.apply(myDateConv)


问:
i have a problem with saving data to database using LARAVEL
this is all my codes after cliking on button doesn't save to database i try to change method of saving but not work

```<code>    use App\makereservations;
use Illuminate\Http\Request;

class reservationController extends Controller
{
    public function hreservation()
    {
        return view('hreservation');
    }
    public function reserve (Request $request)
    {
        $this->validate($request ,[
            'name' => 'required',
            'email' => 'required',
            'phone' => 'required|email',
            'date' => 'required',
            'time' => 'required',

        ]);
        $reservation  = new makereservations();
        $reservation  =  $request->input('name');
        $reservation  =  $request->input('email');
        $reservation  =  $request->input('phone');
        $reservation  =  $request->input('date');
        $reservation  =  $request->input('time');
        $reservation  =  $request->input('personne');
        $reservation -> statu =  false;
        $reservation -> save();
        return redirect()->back();
    }
}
</code>```

this is the roote
route::post('reserve',  'reservationController@reserve' )->name('reserv.sent');

答:
If in the MakeReservations model you have massively assignable fields

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class makereservations extends Model
{
    protected $table = "your_table_name"
    ...
    protected $fillable = [
        'name', 'email', 'phone', 'date', 'time', 'personne', 'status'
    ];
    ...
}
</code>```

Your reserve method in reservationController it may be so:

```<code><?php

namespace App\Http\Controllers;

use App\makereservations;
use Illuminate\Http\Request;

class reservationController extends Controller
{
    ...
    public function reserve (Request $request)
    {
        $this->validate($request ,[
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required',
            'date' => 'required',
            'time' => 'required',

        ]);
        $inputs = $request->all();
        $inputs['status'] = false;
        $reservation = makereservations::create($inputs);
        return redirect()->back();
    }
}
</code>```

I have detected that in your validation method you are trying to validate that the phone is an email

Body:
this is all my codes after cliking on button doesn't save to database i try to change method of saving but not work

    use App\makereservations;
use Illuminate\Http\Request;

class reservationController extends Controller
{
    public function hreservation()
    {
        return view('hreservation');
    }
    public function reserve (Request $request)
    {
        $this->validate($request ,[
            'name' => 'required',
            'email' => 'required',
            'phone' => 'required|email',
            'date' => 'required',
            'time' => 'required',

        ]);
        $reservation  = new makereservations();
        $reservation  =  $request->input('name');
        $reservation  =  $request->input('email');
        $reservation  =  $request->input('phone');
        $reservation  =  $request->input('date');
        $reservation  =  $request->input('time');
        $reservation  =  $request->input('personne');
        $reservation -> statu =  false;
        $reservation -> save();
        return redirect()->back();
    }
}

this is the roote
route::post('reserve',  'reservationController@reserve' )->name('reserv.sent');

Body:
If in the MakeReservations model you have massively assignable fields

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class makereservations extends Model
{
    protected $table = "your_table_name"
    ...
    protected $fillable = [
        'name', 'email', 'phone', 'date', 'time', 'personne', 'status'
    ];
    ...
}

Your reserve method in reservationController it may be so:

<?php

namespace App\Http\Controllers;

use App\makereservations;
use Illuminate\Http\Request;

class reservationController extends Controller
{
    ...
    public function reserve (Request $request)
    {
        $this->validate($request ,[
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required',
            'date' => 'required',
            'time' => 'required',

        ]);
        $inputs = $request->all();
        $inputs['status'] = false;
        $reservation = makereservations::create($inputs);
        return redirect()->back();
    }
}

I have detected that in your validation method you are trying to validate that the phone is an email


问:
How to stop mongo DB in one command
I need to be able to start/stop MongoDB on the cli. It is quite simple to start:

./mongod

But to stop mongo DB, I need to run open mongo shell first and then type two commands:

$ ./mongo

use admin

db.shutdownServer()

So I don't know how to stop mongo DB in one line. Any help?

答:
Using homebrew (recommended way):

To start:

brew services start mongodb-community

To stop:

brew services stop mongodb-community

Title: How to stop mongo DB in one command


问:
PyCharm focus Python Console for input upon run
In PyCharm 2018.2.5 (Community Edition), I have bound a keyboard shortcut to "Run File in Console". This launches opens the console and runs the file, but does not focus the console for input and anything I type goes into my code. (Sometimes when I use the switcher to focus the Python console it will try to search console variables when I type.)

Is there a way to automatically focus the Python console for input when it is launched?

答:
i have just posted something related to this. It is needed to distinguish between "Python console" and "python or debug console" within the keymap options. The first one focus at the console but without automatically move caret to it, the later does it.

See more detailes in this answer.


问:
Plotting a set of data with time in hh:mm format in x axis in matlab
I have a code which goes like this:

```<code>clc;clear;close all
%%
Time=linspace(16.8,17.8,230400)';
Field=linspace(50,145,230400)';
figure('units','normalized','outerposition',[0 0 1 1])
plot(Time,Field)
%%
figure('units','normalized','outerposition',[0 0 1 1])
hammng_wndw_size=4096;
window=hamming(hammng_wndw_size); %window size
noverlap=512; % the noverlaps its the no. of points for repeating the window
nfft=4096; %size of fft
fs=32; %sampling freq
[Sp,F,T,P]=spectrogram(Field,window,noverlap,nfft,fs,'yaxis');
T_forspectrogrm=T./3600+Time(1);
surf(T_forspectrogrm,F,10*log10(P),'edgecolor','none','FaceColor','interp');
axis tight;ylim([0 4]);view(0,90);
colormap(jet);colorbar;
</code>```

The result of this plot is these two figures:

The xaxis is time and y axis is some other quantity, lets say field. Now, when I plotting, the x axis starts from 16.8 to 17.8 for first figure and 16.8 and 18.8 for second figure. This actually corresponds to 16:48:00 to 17:48:00 and similarly for the second one. How do I have to modify the program to convert the x-axis into hh:mm format do this job?

I tried in this fashion
TimeInReqFrmat=datestr(Time(:,1),'HH:MM:SS'), but this gives me a string of characters.

I am using Matlab 2016a.

Thanks in advance

答:
You approach was almost right. You need to use datetimes. It's just a bit tricky to convert decimal numbers to date times

```<code>x = [16.8;17.8]

H = floor(x); % hour
m = floor((x-H)*60); % minute
S = (x-H)*60-m; % second
% create date vector
DateVec = datetime(0,0,0,H,m,S);

plot(DateVec,rand(size(DateVec)))
% set the tick format
xtickformat('HH:mm')
</code>```

There are many options to set the xtickformat.

If you have unix-time, you can convert it right away

```<code>datetime(x,'ConvertFrom','datenum')
</code>```

If you have just time, you will need to come up with a date for a proper datetime. Otherwiese you can also think of using duration.

Body:
I have a code which goes like this:

clc;clear;close all
%%
Time=linspace(16.8,17.8,230400)';
Field=linspace(50,145,230400)';
figure('units','normalized','outerposition',[0 0 1 1])
plot(Time,Field)
%%
figure('units','normalized','outerposition',[0 0 1 1])
hammng_wndw_size=4096;
window=hamming(hammng_wndw_size); %window size
noverlap=512; % the noverlaps its the no. of points for repeating the window
nfft=4096; %size of fft
fs=32; %sampling freq
[Sp,F,T,P]=spectrogram(Field,window,noverlap,nfft,fs,'yaxis');
T_forspectrogrm=T./3600+Time(1);
surf(T_forspectrogrm,F,10*log10(P),'edgecolor','none','FaceColor','interp');
axis tight;ylim([0 4]);view(0,90);
colormap(jet);colorbar;

The result of this plot is these two figures:

The xaxis is time and y axis is some other quantity, lets say field. Now, when I plotting, the x axis starts from 16.8 to 17.8 for first figure and 16.8 and 18.8 for second figure. This actually corresponds to 16:48:00 to 17:48:00 and similarly for the second one. How do I have to modify the program to convert the x-axis into hh:mm format do this job?

I tried in this fashion
TimeInReqFrmat=datestr(Time(:,1),'HH:MM:SS'), but this gives me a string of characters.

I am using Matlab 2016a.

Thanks in advance

Body:
You approach was almost right. You need to use datetimes. It's just a bit tricky to convert decimal numbers to date times

x = [16.8;17.8]

H = floor(x); % hour
m = floor((x-H)*60); % minute
S = (x-H)*60-m; % second
% create date vector
DateVec = datetime(0,0,0,H,m,S);

plot(DateVec,rand(size(DateVec)))
% set the tick format
xtickformat('HH:mm')

There are many options to set the xtickformat.

If you have unix-time, you can convert it right away

datetime(x,'ConvertFrom','datenum')

If you have just time, you will need to come up with a date for a proper datetime. Otherwiese you can also think of using duration.


问:
Advanced Apex Specialist - Please ensure that the Select One label was created
I am working on "Advanced Apex Specialist" Superbadge but I am not able to pass challenge 1 as it keeps on showing me that Select one label is not created. But I have created it as you can see in below image.

enter image description here

Tried creating another playground but still same issue.

答: It got resolved by creating another Playground. Thanks!</p>


问:
How I can fix 'Could not load file or assembly 'Spss' or one of its dependencies. An attempt was made to load a program with an incorrect format.'?

Build .aspx form app

Publish in local folder the app

Copy all artifacts on IIS website

https://i.stack.imgur.com/GzK0z.png

答:
Open IIS Manager (via run you can type inetmgr)

Choose you app pool

Advance settings

Set 'Enable 32-Bit Applications' to True


问:
How to call div content in widows.open()
Actually i have a asp:LinkButton in aspx page and i just want that whenever user clicks on asp:LinkButton open popup on dat asp:LinkButton its already done and i have given another link to it(its ur website's link only) and its working fine,
but the problem is now i want to open a popup with checkboxes with the cities name.

i have made one type of you can say block in a DIV on the same aspx page in the bottom and now i want is to call this div content in the script above in windows.open..

Please help me out ..
asap

Thank You!

答:
You can't show only piece of the current page using the window.open function - only the whole page.
Use ModulPopup from the AjaxControlToolkit or Dialog from the jQuery-UI or some similar functionality.
Or you can create new page that will contain only div with cities names checkboxes and open it via the window.open function</p>


问:
How to replace a value in a string with another in c++?
if I have a string eg

```<code>2,4,-1,3,-1,
</code>```

how do I replace all the -1's with the word "wrong"? and how do I remove the comma at the very end?
the output has come from an array

```<code>cout<<array[c]<<",";
</code>```

I need a basic solution please
thank you

答:
Hard to understand what you are trying to say, better if you edit your question. You could do something like this (stackoverflow answer),</p>

```<code>  std::string subject("2,4,-1,3,-1,");
  std::string search("-1");
  std::string replace("wrong");
  size_t pos = 0;

  while ((pos = subject.find(search, pos)) != std::string::npos)
  {
    subject.replace(pos, search.length(), replace);
    pos += replace.length();
  }

  // Delete last ,
  subject.pop_back();

  std::cout << subject;
</code>```

Body:
if I have a string eg

2,4,-1,3,-1,

how do I replace all the -1's with the word "wrong"? and how do I remove the comma at the very end?
the output has come from an array

cout<<array[c]<<",";

I need a basic solution please
thank you

Body:
Hard to understand what you are trying to say, better if you edit your question. You could do something like this (stackoverflow answer),

  std::string subject("2,4,-1,3,-1,");
  std::string search("-1");
  std::string replace("wrong");
  size_t pos = 0;

  while ((pos = subject.find(search, pos)) != std::string::npos)
  {
    subject.replace(pos, search.length(), replace);
    pos += replace.length();
  }

  // Delete last ,
  subject.pop_back();

  std::cout << subject;


问:
Change button color and icon in future gridView
I have a gridview contained in Future Builder, and I'd like to have this kind of rendering.
As you can see, when an element is selected, the color change, the icon too and obviously I add it to a Set (to have only single element)

Titles come from an API called.

So I did something like this :

```<code>FutureBuilder<List<ProjectTheme>> (
 future: themeColorList.buildTheme(),
 builder: (BuildContext context, AsyncSnapshot<List<ProjectTheme>> snapshot) {
   if(snapshot.hasData)
     return GridView.builder(
       itemCount: themes.length,
       gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
       itemBuilder: (BuildContext context, int index) {
         var theme = snapshot.data[index];
           return Stack(
              children: <Widget>[
                 Positioned(
                   child: ButtonTheme(
                   height: height * 0.15,
                   minWidth: width * 0.4,
                   child: RaisedButton(
                     shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0)),
                        color: selectedThemes.contains(theme.themeName) ? theme.themeColor = Colors.grey : theme.themeColor = theme.themeColor,
                        onPressed: () {
                          setState(() {
                            changeOneClickItemState(theme);
                          });
                        },
                     ),
                   ),
                 ),
                 Padding(
                   child: Align(
                     alignment: Alignment.center,
                     child: selectedThemes.contains(theme.themeName)? Icon(Icons.check):theme.themeIcon,
                   )
                 ),
              ],
            );
          }
        );
      }
  )
</code>```

The selectedThemes is just the list where I add my selection.

And here is the method called in the onPressed button :

```<code> void changeOneClickItemState(ProjectTheme theme) {
    pressed = !pressed;
    pressed ? selectedThemes.add(theme.themeName) : selectedThemes.remove(theme.themeName);
 }
</code>```

So it worked approximately, but I need to tap several times on every element to see the element selected. It seems like the app is not reactive, and I think it's because takes times to check if element is in the list or not.
The fact is, I can't set "pressed ?" instead of "selectedTheme.contains(theme.themeName)" in the color property of my RaisedButton, because all of my buttons turn to grey. But I need to make it more reactive, because it's not acceptable for a client to tap on the button several times to make it work...

Do you have an idea on how can I solve this?

答:
Sooooo, I finally find a way to make it.
As I said, the problem was the gridView were built inside the Future Builder.

So, I made a method where I built themes and called it in init.

```<code>List<ProjectTheme> projectThemes;

void initState() {
  super.initState();
  getThemes();
  buildThemes();
}

Future<List<ProjectTheme>> buildThemes() async {
  List<ProjectTheme> projectThemeList = await themeColorList.buildTheme();
  setState(() {
    this.projectThemes = projectThemeList;
  });

  return projectThemeList;
}
</code>```

Then I built my Grid view as below after added a property "isPressed" to my class:

```<code>GridView.builder(
  itemCount: themes != null ? themes.length : 0,
  gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (BuildContext context, int index) {
      var theme = projectThemes[index];
      theme.isPressed = false;

      return projectThemes != null ? Stack(
           children: <Widget>[
              Positioned(
                child: ButtonTheme(
                   height: height * 0.15,
                   minWidth: width * 0.4,
                   child: RaisedButton.icon(
                   shape: RoundedRectangleBorder(
                   borderRadius: BorderRadius.circular(5.0)),

                   onPressed: () {
                     setState(() {
                       selectedThemes.contains(theme.themeName) ?
                       theme.isPressed = false :
                       theme.isPressed = true;

                       changeOneClickItemState(theme);
                     });
                   },
                   color: selectedThemes.contains(theme.themeName) ? Colors.grey : theme.themeColor,
                   icon: selectedThemes.contains(theme.themeName) ? Icon(Icons.check) : theme.themeIcon,
                   label: Text(''),
                 ),
                ),
              ),
            ],
          ) : Container(child: Center(child: CircularProgressIndicator()));
         }
       )
</code>```

And changeOneClickItemState :

```<code> void changeOneClickItemState(ProjectTheme theme) {
   theme.isPressed ?
   selectedThemes.add(theme.themeName) :
   selectedThemes.remove(theme.themeName);
 }
</code>```

Maybe it would help someone one day !

Body:
I have a gridview contained in Future Builder, and I'd like to have this kind of rendering.
As you can see, when an element is selected, the color change, the icon too and obviously I add it to a Set (to have only single element)

Titles come from an API called.

So I did something like this :

FutureBuilder<List<ProjectTheme>> (
 future: themeColorList.buildTheme(),
 builder: (BuildContext context, AsyncSnapshot<List<ProjectTheme>> snapshot) {
   if(snapshot.hasData)
     return GridView.builder(
       itemCount: themes.length,
       gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
       itemBuilder: (BuildContext context, int index) {
         var theme = snapshot.data[index];
           return Stack(
              children: <Widget>[
                 Positioned(
                   child: ButtonTheme(
                   height: height * 0.15,
                   minWidth: width * 0.4,
                   child: RaisedButton(
                     shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0)),
                        color: selectedThemes.contains(theme.themeName) ? theme.themeColor = Colors.grey : theme.themeColor = theme.themeColor,
                        onPressed: () {
                          setState(() {
                            changeOneClickItemState(theme);
                          });
                        },
                     ),
                   ),
                 ),
                 Padding(
                   child: Align(
                     alignment: Alignment.center,
                     child: selectedThemes.contains(theme.themeName)? Icon(Icons.check):theme.themeIcon,
                   )
                 ),
              ],
            );
          }
        );
      }
  )

The selectedThemes is just the list where I add my selection.

And here is the method called in the onPressed button :

 void changeOneClickItemState(ProjectTheme theme) {
    pressed = !pressed;
    pressed ? selectedThemes.add(theme.themeName) : selectedThemes.remove(theme.themeName);
 }

So it worked approximately, but I need to tap several times on every element to see the element selected. It seems like the app is not reactive, and I think it's because takes times to check if element is in the list or not.
The fact is, I can't set "pressed ?" instead of "selectedTheme.contains(theme.themeName)" in the color property of my RaisedButton, because all of my buttons turn to grey. But I need to make it more reactive, because it's not acceptable for a client to tap on the button several times to make it work...

Do you have an idea on how can I solve this?

Body:
Sooooo, I finally find a way to make it.
As I said, the problem was the gridView were built inside the Future Builder.

So, I made a method where I built themes and called it in init.

List<ProjectTheme> projectThemes;

void initState() {
  super.initState();
  getThemes();
  buildThemes();
}

Future<List<ProjectTheme>> buildThemes() async {
  List<ProjectTheme> projectThemeList = await themeColorList.buildTheme();
  setState(() {
    this.projectThemes = projectThemeList;
  });

  return projectThemeList;
}

Then I built my Grid view as below after added a property "isPressed" to my class:

GridView.builder(
  itemCount: themes != null ? themes.length : 0,
  gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (BuildContext context, int index) {
      var theme = projectThemes[index];
      theme.isPressed = false;

      return projectThemes != null ? Stack(
           children: <Widget>[
              Positioned(
                child: ButtonTheme(
                   height: height * 0.15,
                   minWidth: width * 0.4,
                   child: RaisedButton.icon(
                   shape: RoundedRectangleBorder(
                   borderRadius: BorderRadius.circular(5.0)),

                   onPressed: () {
                     setState(() {
                       selectedThemes.contains(theme.themeName) ?
                       theme.isPressed = false :
                       theme.isPressed = true;

                       changeOneClickItemState(theme);
                     });
                   },
                   color: selectedThemes.contains(theme.themeName) ? Colors.grey : theme.themeColor,
                   icon: selectedThemes.contains(theme.themeName) ? Icon(Icons.check) : theme.themeIcon,
                   label: Text(''),
                 ),
                ),
              ),
            ],
          ) : Container(child: Center(child: CircularProgressIndicator()));
         }
       )

And changeOneClickItemState :

 void changeOneClickItemState(ProjectTheme theme) {
   theme.isPressed ?
   selectedThemes.add(theme.themeName) :
   selectedThemes.remove(theme.themeName);
 }

Maybe it would help someone one day !


问:
Read React Context value without subscription like Redux's store.getState()
```<code>const UsersStateContext = React.createContext( [{user:1},{user:2},{user:3}] );

function getState(){
  return UsersStateContext._currentValue;
}
</code>```

After hours of searching I was able to find this method that is not supported officially. Is there a solution for React hooks to just read current state without subscription like Redux's store.getState()?

Or is this method it safe to use in production?

答:
Short answer: It's not safe in production, instead you can maintain a global variable.

This "hack" is exactly like reading from a global variable. Your component can't be notified when the global variable updates.

See the explanation on global variables here: Why need useRef to contain mutable variable but not define a variable outside the component function?

```<code>let counter = 0;

const Component = () => {
 /*
    On changing the counter value, the component won't get re-rendered with its new value.
 */
  console.log(counter);
  return <></>
}
</code>```

Is there a solution for React hooks to just read current state without subscription like Redux's store.getState()?

store.getState() returns the last value returned by the store's reducer. It's exactly the behavior like you intended with UsersStateContext._currentValue, if you want to feel safer, you can maintain a global variable as mentioned.

The official way is to subscribe to context by consuming it, for example with useContext:

```<code>const value = useContext(MyContext);
</code>```

Body:
const UsersStateContext = React.createContext( [{user:1},{user:2},{user:3}] );

function getState(){
  return UsersStateContext._currentValue;
}

After hours of searching I was able to find this method that is not supported officially. Is there a solution for React hooks to just read current state without subscription like Redux's store.getState()?

Or is this method it safe to use in production?

Body:
Short answer: It's not safe in production, instead you can maintain a global variable.

This "hack" is exactly like reading from a global variable. Your component can't be notified when the global variable updates.

See the explanation on global variables here: Why need useRef to contain mutable variable but not define a variable outside the component function?

let counter = 0;

const Component = () => {
 /*
    On changing the counter value, the component won't get re-rendered with its new value.
 */
  console.log(counter);
  return <></>
}

Is there a solution for React hooks to just read current state without subscription like Redux's store.getState()?

store.getState() returns the last value returned by the store's reducer. It's exactly the behavior like you intended with UsersStateContext._currentValue, if you want to feel safer, you can maintain a global variable as mentioned.

The official way is to subscribe to context by consuming it, for example with useContext:

const value = useContext(MyContext);


问:
tensorflow2.1 InvalidArgumentError: assertion failed: [0] [Op:Assert] name: EagerVariableNameReuse
I trained my custom model and used tensorflow 2.1. When I run the code I'm getting the following error:

InvalidArgumentError: assertion failed: [0] [Op:Assert] name:
  EagerVariableNameReuse

Here is the line which showing the error:

```<code>self.train_accuracy = tf.keras.metrics.CategoricalAccuracy('train_accuracy')
</code>```

What does this error mean, thanks in advance.

答:
Providing the solution here even though it is present in Github, for the benefit of the Stackoverflow Community.

Whenever we are trying to run two python programs that use Tensorflow at the same time triggers this error. Please close other python session using Tensorflow will resolve this issue.

For more information please refer here.

Body:
I trained my custom model and used tensorflow 2.1. When I run the code I'm getting the following error:

InvalidArgumentError: assertion failed: [0] [Op:Assert] name:
  EagerVariableNameReuse

Here is the line which showing the error:

self.train_accuracy = tf.keras.metrics.CategoricalAccuracy('train_accuracy')

What does this error mean, thanks in advance.


问:
How to use nested components defined as constant with arrow functions in React?
If I comment out {children} from Layout this works as expected.
Otherwise, error

index.js Invariant Violation: Objects are not valid as a React child (found: object with keys {children})

Why?

layout.js

```<code>const Layout = (children) => (<div>
  <Header />
  {children}
</div>)

export default Layout
</code>```

index.js (root component)

```<code>const IndexPage = () => (
  <Layout>
    <h1>Hi people</h1>
  </Layout>
)

export default IndexPage
</code>```

答:
```<code>(children) =>
</code>```

Despite what you've called it, this is the entire props object, not just the children. Either use destructuring to pick the children prop:

```<code>({ children }) =>
</code>```

Or access props.children explicitly:

```<code>(props) => (
  <div>
    <Header />
    {props.children}
  </div>
)
</code>```

Body:
If I comment out {children} from Layout this works as expected.
Otherwise, error

index.js Invariant Violation: Objects are not valid as a React child (found: object with keys {children})

Why?

layout.js

const Layout = (children) => (

  {children}

)

export default Layout

index.js (root component)

const IndexPage = () => (
  <Layout>

Hi people

  </Layout>
)

export default IndexPage

Body:
(children) =>

Despite what you've called it, this is the entire props object, not just the children. Either use destructuring to pick the children prop:

({ children }) =>

Or access props.children explicitly:

(props) => (
  <div>
    <Header />
    {props.children}
  </div>
)


问:
Disable autocomplete on chrome (React)
I'm  trying to disable autocomplete on some inputs (or all of them inside some form), but I cannot do that! I looked for lot of examples, trying lot of answers there on stackoverflow, but still doesnt work.

This doesnt work:

```<code><input type="text" name="asdf" autoComplete="off/nope/new-password/somethingtotallydifferent"/>
</code>```

Also when I put autocomplete="off" inside <form/> element. Same result.

Can someone show me how to do that on latest versions of Chrome (and all modern browsers) without issues?

答:
Did you try  this. With Capital 'C'</p>

```<code>autoComplete="off"
</code>```

Title: Disable autocomplete on chrome (React)

Body:
I'm  trying to disable autocomplete on some inputs (or all of them inside some form), but I cannot do that! I looked for lot of examples, trying lot of answers there on stackoverflow, but still doesnt work.

This doesnt work:

<input type="text" name="asdf" autoComplete="off/nope/new-password/somethingtotallydifferent"/>

Also when I put autocomplete="off" inside <form/> element. Same result.

Can someone show me how to do that on latest versions of Chrome (and all modern browsers) without issues?

Body:
Did you try  this. With Capital 'C'

autoComplete="off"


问:
How does redis persist Nodejs sessions?
I recently started using Redis on my Nodejs project. I use it to store my sessions.

```<code>const session = require("express-session")
const redis = require('redis')
let RedisStore = require('connect-redis')(session)

let redisClient
if(process.env.REDISTOGO_URL){
    // let redisURL = url.parse(process.env.REDISTOGO_URL);
    redisClient = redis.createClient(process.env.REDISTOGO_URL)
} else {
    redisClient = redis.createClient()
}

app.use(
        session({
            store: new RedisStore({
                client: redisClient
            }),
            secret: keys.session.secret,
            resave: false,
            saveUninitialized: false
        })
    )
</code>```

I am also using passport.js to handle user sessions:

```<code>passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        pool.query( `Select users.* where users.id = ${id} `, function(err, rows) {
            if(err){
                console.log(err)
            }
            else{
                done(err,rows[0]);
            }
        });
    });
</code>```

I was reading about how redis works and came upon this:

When using a memory cache, your cookie only contains a session ID.
  This removes the risk of private user information being exposed in the
  cookie.

This means that at any given time the Nodejs server still has to store the session ID. When the browser sends the cookie back with user infromation and the encrypted secret Nodejs will have to find the session ID in the redis store and make sure that the information is correct.

Why is it that refreshing the Nodejs server not clear all the session ID from the database? Why do I not have to re-login everytime I refresh the server?

答:
redis by default doesnt persist data to disk every time you write (normally just aof and no rdf). So if you restart redis, your data can be gone and your sessionId within your cookie doesn't exist anymore

you will need to enable persistence within redis or configure that in your redistogo instance.

if you want to flush all session information you can FLUSHALL on your redis instance. Best would be to set the ttl (time to live) so your sessions eventually get flushed by redis automatically after 30days or so

Title: How does redis persist Nodejs sessions?

Body:
I recently started using Redis on my Nodejs project. I use it to store my sessions.

const session = require("express-session")
const redis = require('redis')
let RedisStore = require('connect-redis')(session)

let redisClient
if(process.env.REDISTOGO_URL){
    // let redisURL = url.parse(process.env.REDISTOGO_URL);
    redisClient = redis.createClient(process.env.REDISTOGO_URL)
} else {
    redisClient = redis.createClient()
}

app.use(
        session({
            store: new RedisStore({
                client: redisClient
            }),
            secret: keys.session.secret,
            resave: false,
            saveUninitialized: false
        })
    )

I am also using passport.js to handle user sessions:

passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        pool.query( `Select users.* where users.id = ${id} `, function(err, rows) {
            if(err){
                console.log(err)
            }
            else{
                done(err,rows[0]);
            }
        });
    });

I was reading about how redis works and came upon this:

When using a memory cache, your cookie only contains a session ID.
  This removes the risk of private user information being exposed in the
  cookie.

This means that at any given time the Nodejs server still has to store the session ID. When the browser sends the cookie back with user infromation and the encrypted secret Nodejs will have to find the session ID in the redis store and make sure that the information is correct.

Why is it that refreshing the Nodejs server not clear all the session ID from the database? Why do I not have to re-login everytime I refresh the server?


问:
clearInterval in if doesn't work
I have something like this:

```<code>function myFunction()
{
    var testVar;
    if(txt == "Maybe")
    {
        txt == "No";
        testVar = setInterval(function(){ zrobTo() }, 1000);
    }
    else if(txt == "No")
   {
        txt == "Maybe";
        clearInterval(testVar);
    }
}
</code>```

When clearInterval isn't in if then code is working, but I wanna have this in if. Is it possible?

答: The reason is that the setInterval is never leaving the function. Since the variable is local, it is deleted when the function ends. There is no way around this that I have found. D=</p>

Title: clearInterval in if doesn't work

Body:
I have something like this:

function myFunction()
{
    var testVar;
    if(txt == "Maybe")
    {
        txt == "No";
        testVar = setInterval(function(){ zrobTo() }, 1000);
    }
    else if(txt == "No")
   {
        txt == "Maybe";
        clearInterval(testVar);
    }
}

When clearInterval isn't in if then code is working, but I wanna have this in if. Is it possible?


问:
How do I download a file in Alamofire 4 and save to the Documents directory?
I'm trying to use Alamofire4 for Swift3. I need to download .mp3 files and save them to the Documents directory. Current code is like so:

```<code>func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {

        let fileManager = FileManager.default
        let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let audioFullURL = String.ensureFullURLPath(url)

        alamoManager.download(audioFullURL)
            .validate { request, response, temporaryURL, destinationURL in

                var pathComponent = response.suggestedFilename!
                if pathComponent == "m4a.mp4" {
                    // Due to the old Android audio files without a filename
                    // Assign a unique name so audio files don't overwrite each other
                    pathComponent = "\(NSUUID().uuidString).mp4"
                }
                let localURL = directoryURL.appendingPathComponent(pathComponent)

                if response.statusCode == 200 {
                    completion?(.success, localURL)
                } else {
                    completion?(.failure, nil)
                }
                return .success
            }

            .responseJSON { response in
                debugPrint(response)
                print(response.temporaryURL)
                print(response.destinationURL)
        }
    }
</code>```

However I can't actually access the files from the localURL after saving. I have also noticed that the localURL will be exactly the same for different files I try to download (maybe they are overwriting?). E.g: file:///Users/testuser/Library/Developer/CoreSimulator/Devices/D4254AEA-76DD-4F01-80AF-F1AF3BE8A204/data/Containers/Data/Application/29755154-DD21-4D4C-B340-6628607DC053/Documents/file1.mp3

Any ideas what I am doing wrong here?

Edited my code to look like this:

```<code>func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {

        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

            documentsURL.appendPathComponent("Audiofile.mp3")
            return (documentsURL, [.removePreviousFile])
        }

        Alamofire.download(url, to: destination).response { response in

            if let localURL = response.destinationURL {

                completion?(.success, localURL)

            } else {

                completion?(.failure, nil)
            }

        }
}
</code>```

How would I check for m4a.mp4 though?

答:
Swift 5 - Alamofire 5.1.
This is the approach.</p>

```<code>let destination: DownloadRequest.Destination = { _, _ in
        let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("image.png")

            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }

    AF.download("https://httpbin.org/image/png", to: destination).response { response in
        debugPrint(response)

        if response.error == nil, let imagePath = response.fileURL?.path {
            let image = UIImage(contentsOfFile: imagePath)
        }
    }
</code>```

Body:
I'm trying to use Alamofire4 for Swift3. I need to download .mp3 files and save them to the Documents directory. Current code is like so:

func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {

        let fileManager = FileManager.default
        let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let audioFullURL = String.ensureFullURLPath(url)

        alamoManager.download(audioFullURL)
            .validate { request, response, temporaryURL, destinationURL in

                var pathComponent = response.suggestedFilename!
                if pathComponent == "m4a.mp4" {
                    // Due to the old Android audio files without a filename
                    // Assign a unique name so audio files don't overwrite each other
                    pathComponent = "\(NSUUID().uuidString).mp4"
                }
                let localURL = directoryURL.appendingPathComponent(pathComponent)

                if response.statusCode == 200 {
                    completion?(.success, localURL)
                } else {
                    completion?(.failure, nil)
                }
                return .success
            }

            .responseJSON { response in
                debugPrint(response)
                print(response.temporaryURL)
                print(response.destinationURL)
        }
    }

However I can't actually access the files from the localURL after saving. I have also noticed that the localURL will be exactly the same for different files I try to download (maybe they are overwriting?). E.g: file:///Users/testuser/Library/Developer/CoreSimulator/Devices/D4254AEA-76DD-4F01-80AF-F1AF3BE8A204/data/Containers/Data/Application/29755154-DD21-4D4C-B340-6628607DC053/Documents/file1.mp3

Any ideas what I am doing wrong here?

Edited my code to look like this:

func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {

        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

            documentsURL.appendPathComponent("Audiofile.mp3")
            return (documentsURL, [.removePreviousFile])
        }

        Alamofire.download(url, to: destination).response { response in

            if let localURL = response.destinationURL {

                completion?(.success, localURL)

            } else {

                completion?(.failure, nil)
            }

        }
}

How would I check for m4a.mp4 though?

Body:
Swift 5 - Alamofire 5.1.
This is the approach.

let destination: DownloadRequest.Destination = { _, _ in
        let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("image.png")

            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }

    AF.download("https://httpbin.org/image/png", to: destination).response { response in
        debugPrint(response)

        if response.error == nil, let imagePath = response.fileURL?.path {
            let image = UIImage(contentsOfFile: imagePath)
        }
    }


问:
C++ - How to bind a callback to a class method without being static?
I have my class:

```<code>class Foo
{
public:
  (...)
private:
    void mycallback(void* buff, wifi_promiscuous_pkt_type_t type);
    void registerMyCallback();
};
</code>```

The mycallback is the callback.

I want to use a method esp_wifi_set_promiscuous_rx_cb to register the mycallback so that when a WiFi packet is detected, this callback method will be executed.

The esp_wifi_set_promiscuous_rx_cb signature is:

```<code>esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb);
</code>```

Where the wifi_promiscuous_cb_t definition is:

```<code>typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type);
</code>```

I want to use the mycallback method inside my class, therefore I simply can't use like this:

```<code>  void Foo::registerMyCallback()
  {
    esp_wifi_set_promiscuous_rx_cb(&mycallback);
  }
</code>```

I know that I could use something similar if I would just make my method as static.
Is there anyway that I bind mycallback to esp_wifi_set_promiscuous_rx_cb without making the callback static?

I have tried the following:

```<code>esp_wifi_set_promiscuous_rx_cb(std::bind(&Foo::mycallback, this, std::placeholders::_1, std::placeholders::_2));
</code>```

But I am still having the following error:

```<code>cannot convert 'std::_Bind_helper<false, void (Foo::Foo::*)(void*, wifi_promiscuous_pkt_type_t),
Foo::Foo*, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type
to
'wifi_promiscuous_cb_t {aka void (*)(void*, wifi_promiscuous_pkt_type_t)}' for argument '1'
</code>```

答:
After some research, I hope I found the solution. The trick is to bind member function first and then obtain the function pointer from the std::function. Notice the usage of my_wifi_promiscuous_cb_t and std::function::target<>().

```<code>#include <iostream>
#include <functional>
using namespace std::placeholders;

// using fake definitions
extern "C"
{
  enum wifi_promiscuous_pkt_type_t {};
  typedef int32_t esp_err_t;
  typedef void (*wifi_promiscuous_cb_t)(void* buf, wifi_promiscuous_pkt_type_t type);
  typedef void my_wifi_promiscuous_cb_t(void* buf, wifi_promiscuous_pkt_type_t type);
  esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb)
  {
    return 0;
  }
}

class Class
{
public:
  void mycallback(void* buff, wifi_promiscuous_pkt_type_t type) {}

  void registerMyCallback() {
    std::function<void(void*, wifi_promiscuous_pkt_type_t)> fun2 = std::bind(&Class::mycallback, this, _1, _2);
    esp_wifi_set_promiscuous_rx_cb(fun2.target<my_wifi_promiscuous_cb_t>());
  }
};

int main()
{
  Class c;
  c.registerMyCallback();
}
</code>```

Body:
I have my class:

class Foo
{
public:
  (...)
private:
    void mycallback(void* buff, wifi_promiscuous_pkt_type_t type);
    void registerMyCallback();
};

The mycallback is the callback.

I want to use a method esp_wifi_set_promiscuous_rx_cb to register the mycallback so that when a WiFi packet is detected, this callback method will be executed.

The esp_wifi_set_promiscuous_rx_cb signature is:

esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb);

Where the wifi_promiscuous_cb_t definition is:

typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type);

I want to use the mycallback method inside my class, therefore I simply can't use like this:

  void Foo::registerMyCallback()
  {
    esp_wifi_set_promiscuous_rx_cb(&mycallback);
  }

I know that I could use something similar if I would just make my method as static.
Is there anyway that I bind mycallback to esp_wifi_set_promiscuous_rx_cb without making the callback static?

I have tried the following:

esp_wifi_set_promiscuous_rx_cb(std::bind(&Foo::mycallback, this, std::placeholders::_1, std::placeholders::_2));

But I am still having the following error:

cannot convert 'std::_Bind_helper<false, void (Foo::Foo::*)(void*, wifi_promiscuous_pkt_type_t),
Foo::Foo*, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type
to
'wifi_promiscuous_cb_t {aka void (*)(void*, wifi_promiscuous_pkt_type_t)}' for argument '1'

Body:
After some research, I hope I found the solution. The trick is to bind member function first and then obtain the function pointer from the std::function. Notice the usage of my_wifi_promiscuous_cb_t and std::function::target<>().

#include <iostream>
#include <functional>
using namespace std::placeholders;

// using fake definitions
extern "C"
{
  enum wifi_promiscuous_pkt_type_t {};
  typedef int32_t esp_err_t;
  typedef void (*wifi_promiscuous_cb_t)(void* buf, wifi_promiscuous_pkt_type_t type);
  typedef void my_wifi_promiscuous_cb_t(void* buf, wifi_promiscuous_pkt_type_t type);
  esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb)
  {
    return 0;
  }
}

class Class
{
public:
  void mycallback(void* buff, wifi_promiscuous_pkt_type_t type) {}

  void registerMyCallback() {
    std::function<void(void*, wifi_promiscuous_pkt_type_t)> fun2 = std::bind(&Class::mycallback, this, _1, _2);
    esp_wifi_set_promiscuous_rx_cb(fun2.target<my_wifi_promiscuous_cb_t>());
  }
};

int main()
{
  Class c;
  c.registerMyCallback();
}


问:
Tensorflow RNN text generation example tutorial
Looking at this tutorial here, they use a starting sequence of “Romeo: “.

```<code>int(generate_text(model, start_string=u"ROMEO: "))
</code>```

However, looking at the actual generation step, is it fair to say it’s only using the last character “ “? So it’s the same whether we use “ROMEO: “ or just “ “? It’s hard to test as it samples from the output distribution ...

Relatedly, it’s  unclear how it would predict from such a short string as the original training sequence is much longer. I understand if we trained on a history of 100 chars we predict the 101st and then use 2-101 to predict 102... but how does it start with just 7 characters?

EDIT

As a specific example, I reworked my model to be of the following form:

```<code>    model = tf.keras.Sequential()
model.add(tf.keras.layers.SimpleRNN(units=512, input_shape = (seq_len, 1), activation="tanh"))
    model.add(tf.keras.layers.Dense(len(vocab)))
    model.compile(loss=loss, optimizer='adam')
    model.summary()
</code>```

Notice, I use a simpleRNN instead of a GRU and drop the embedding step. Both of those changes are to simplify the model but that shouldn't matter.

My training and output data is as follows:

```<code>>>> input_array_reshaped
array([[46., 47., 53., ..., 39., 58.,  1.],
       [ 8.,  0., 20., ..., 33., 31., 10.],
       [63.,  1., 44., ..., 58., 46., 43.],
       ...,
       [47., 41., 47., ...,  0., 21., 57.],
       [59., 58.,  1., ...,  1., 61., 43.],
       [52., 57., 43., ...,  1., 63., 53.]])
>>> input_array_reshaped.shape
(5000, 100)

>>> output_array_reshaped.shape
(5000, 1, 1)

>>> output_array_reshaped
array([[[40.]],

       [[ 0.]],

       [[56.]],

       ...,

       [[ 1.]],

       [[56.]],

       [[59.]]])
</code>```

However, if I try to predict on a string less than 100 characters I get:

```<code>ValueError: Error when checking input: expected simple_rnn_1_input to have shape (100, 1) but got array with shape (50, 1)
</code>```

Below is my prediction function if needed. If I change the required_training_length to anything but 100 it crashes. It requires "specifically" time_steps of length 100.

Can someone tell me how to adjust the model to make it more flexible as in the example? What subtlety am I missing?

```<code>def generateText(starting_corpus, num_char_to_generate = 1000, required_training_length = 100):
    random_starting_int = random.sample(range(len(text)),1)[0]
    ending_position = random_starting_int+required_training_length

    starting_string = text[random_starting_int:ending_position]
    print("Starting string is: " + starting_string)
    numeric_starting_string = [char2idx[x] for x in starting_string]
    reshaped_numeric_string = np.reshape(numeric_starting_string, (1, len(numeric_starting_string), 1)).astype('float32')

    output_numeric_vector = []
    for i in range(num_char_to_generate):
        if i%50 == 0:
            print("Processing character index: "+str(i))
        predicted_values = model.predict(reshaped_numeric_string)
        selected_predicted_value = tf.random.categorical(predicted_values, num_samples = 1)[0][0].numpy().astype('float32') #sample from the predicted values
        #temp = reshaped_numeric_string.copy()
        output_numeric_vector.append(selected_predicted_value)
        reshaped_numeric_string = np.append(reshaped_numeric_string[:,1:,:], np.reshape(selected_predicted_value, (1,1,1)), axis = 1)

    predicted_chars = [idx2char[x] for x in output_numeric_vector]
    final_text = ''.join(predicted_chars)
    return(final_text)
</code>```

答:
However, looking at the actual generation step, is it fair to say
  it’s only using the last character “ “? So it’s the same whether we
  use “ROMEO: “ or just “ “? It’s hard to test as it samples from the
  output distribution ...

No, it is taking all characters into consideration. You can easily
verify that by using a fixed random seed:

```<code>from numpy.random import seed
from tensorflow.random import set_seed
seed(1)
set_seed(1)
print('======')
print(generate_text(m, 'ROMEO: '))
seed(1)
set_seed(1)
print('======')
print(generate_text(m, ' '))
</code>```

Relatedly, it’s unclear how it would predict from such a short
  string as the original training sequence is much longer. I
  understand if we trained on a history of 100 chars we predict the
  101st and then use 2-101 to predict 102... but how does it start
  with just 7 characters?

Internally it runs the sequence in a loop. It takes the first
character and predicts the second. Then the second to predict the
third and so on. While doing so it updates its hidden state so that
its predictions becomes better and better. Eventually it plateaus
because it cannot remember arbitrary long sequences.

Body:
Looking at this tutorial here, they use a starting sequence of “Romeo: “.

int(generate_text(model, start_string=u"ROMEO: "))

However, looking at the actual generation step, is it fair to say it’s only using the last character “ “? So it’s the same whether we use “ROMEO: “ or just “ “? It’s hard to test as it samples from the output distribution ...

Relatedly, it’s  unclear how it would predict from such a short string as the original training sequence is much longer. I understand if we trained on a history of 100 chars we predict the 101st and then use 2-101 to predict 102... but how does it start with just 7 characters?

EDIT

As a specific example, I reworked my model to be of the following form:

    model = tf.keras.Sequential()
model.add(tf.keras.layers.SimpleRNN(units=512, input_shape = (seq_len, 1), activation="tanh"))
    model.add(tf.keras.layers.Dense(len(vocab)))
    model.compile(loss=loss, optimizer='adam')
    model.summary()

Notice, I use a simpleRNN instead of a GRU and drop the embedding step. Both of those changes are to simplify the model but that shouldn't matter.

My training and output data is as follows:

>>> input_array_reshaped
array([[46., 47., 53., ..., 39., 58.,  1.],
       [ 8.,  0., 20., ..., 33., 31., 10.],
       [63.,  1., 44., ..., 58., 46., 43.],
       ...,
       [47., 41., 47., ...,  0., 21., 57.],
       [59., 58.,  1., ...,  1., 61., 43.],
       [52., 57., 43., ...,  1., 63., 53.]])
>>> input_array_reshaped.shape
(5000, 100)

>>> output_array_reshaped.shape
(5000, 1, 1)

>>> output_array_reshaped
array([[[40.]],

       [[ 0.]],

       [[56.]],

       ...,

       [[ 1.]],

       [[56.]],

       [[59.]]])

However, if I try to predict on a string less than 100 characters I get:

ValueError: Error when checking input: expected simple_rnn_1_input to have shape (100, 1) but got array with shape (50, 1)

Below is my prediction function if needed. If I change the required_training_length to anything but 100 it crashes. It requires "specifically" time_steps of length 100.

Can someone tell me how to adjust the model to make it more flexible as in the example? What subtlety am I missing?

def generateText(starting_corpus, num_char_to_generate = 1000, required_training_length = 100):
    random_starting_int = random.sample(range(len(text)),1)[0]
    ending_position = random_starting_int+required_training_length

    starting_string = text[random_starting_int:ending_position]
    print("Starting string is: " + starting_string)
    numeric_starting_string = [char2idx[x] for x in starting_string]
    reshaped_numeric_string = np.reshape(numeric_starting_string, (1, len(numeric_starting_string), 1)).astype('float32')

    output_numeric_vector = []
    for i in range(num_char_to_generate):
        if i%50 == 0:
            print("Processing character index: "+str(i))
        predicted_values = model.predict(reshaped_numeric_string)
        selected_predicted_value = tf.random.categorical(predicted_values, num_samples = 1)[0][0].numpy().astype('float32') #sample from the predicted values
        #temp = reshaped_numeric_string.copy()
        output_numeric_vector.append(selected_predicted_value)
        reshaped_numeric_string = np.append(reshaped_numeric_string[:,1:,:], np.reshape(selected_predicted_value, (1,1,1)), axis = 1)

    predicted_chars = [idx2char[x] for x in output_numeric_vector]
    final_text = ''.join(predicted_chars)
    return(final_text)

Body:
However, looking at the actual generation step, is it fair to say
  it’s only using the last character “ “? So it’s the same whether we
  use “ROMEO: “ or just “ “? It’s hard to test as it samples from the
  output distribution ...

No, it is taking all characters into consideration. You can easily
verify that by using a fixed random seed:

from numpy.random import seed
from tensorflow.random import set_seed
seed(1)
set_seed(1)
print('======')
print(generate_text(m, 'ROMEO: '))
seed(1)
set_seed(1)
print('======')
print(generate_text(m, ' '))

Relatedly, it’s unclear how it would predict from such a short
  string as the original training sequence is much longer. I
  understand if we trained on a history of 100 chars we predict the
  101st and then use 2-101 to predict 102... but how does it start
  with just 7 characters?

Internally it runs the sequence in a loop. It takes the first
character and predicts the second. Then the second to predict the
third and so on. While doing so it updates its hidden state so that
its predictions becomes better and better. Eventually it plateaus
because it cannot remember arbitrary long sequences.


问:
Reading a json webpage using python
I am trying to read a json webpage and insert it into a dataframe.

import urllib3
import json
import pandas as pd

url = 'https://covid.ourworldindata.org/data/owid-covid-data.json'
http = urllib3.PoolManager()
r = http.request('GET', url, headers={'Accept': 'application/json'})

data = json.loads(r.data.decode('utf-8'))
data_copy = data

df = pd.DataFrame.from_dict(data_copy, orient='index')
df.transpose()
```

I need to use the same code I previewed but the output has to be in the following format:

答:
Here's a solution for this specific data:

```<code>req = requests.get("https://covid.ourworldindata.org/data/owid-covid-data.json")
d = json.loads(req.content)
records = [{**{"iso_code": key}, **item} for key, val in d.items() for item in val]

pd.DataFrame.from_records(records)
</code>```

The result is:

Title: Reading a json webpage using python

Body:
I am trying to read a json webpage and insert it into a dataframe.

import urllib3
import json
import pandas as pd

url = 'https://covid.ourworldindata.org/data/owid-covid-data.json'
http = urllib3.PoolManager()
r = http.request('GET', url, headers={'Accept': 'application/json'})

data = json.loads(r.data.decode('utf-8'))
data_copy = data

df = pd.DataFrame.from_dict(data_copy, orient='index')
df.transpose()

I need to use the same code I previewed but the output has to be in the following format:

Body:
Here's a solution for this specific data:

req = requests.get("https://covid.ourworldindata.org/data/owid-covid-data.json")
d = json.loads(req.content)
records = [{**{"iso_code": key}, **item} for key, val in d.items() for item in val]

pd.DataFrame.from_records(records)

The result is:


问:
System.Data.DbType Vs System.Data.SqlType
Am using enterprise library data access application block...
is there any performance impact of using System.Data.DbType Vs System.Data.SqlType?

And also, would like to know performance impact for the statement:

```<code>DatabaseFactory.CreateDatabase("MyDB")
</code>```

Vs

```<code>new SqlDatabase(myConnectionString);
</code>```

答: Any performance difference will be neglible (especially compared with database accesses).</p>

OwnerDisplayName: Jeremy Thomson

Body:
Am using enterprise library data access application block...
is there any performance impact of using System.Data.DbType Vs System.Data.SqlType?

And also, would like to know performance impact for the statement:

DatabaseFactory.CreateDatabase("MyDB")

Vs

new SqlDatabase(myConnectionString);

OwnerDisplayName: Mitch Wheat

ContentLicense: CC BY-SA 2.5


问:
How to delete authenticated user from firebase in angular
when clicking on a button i called a function,

```<code>onDelete(id:string){ this.db.collection('Students').doc(id).delete(); }
</code>```

Here, id is a name of document that i want to delete, db is a property of type AngularFireStore, 'Students' is a name of collection.

Structure of document:
enter image description here
 In the above image, collection name is Students, under which multiple documents exist, since document name must be unique so i given that name a number of type string which acts as id. In every document, there is email field, i want to delete that email from authentication when i delete the same document.

code to sign up users:

```<code>this.afAuth.auth.createUserWithEmailAndPassword(email:string,password:string).then(res=>{})
</code>```

答:
If you want to delete a user existing in Firebase authentication you have two possibilities:

1/ Using the JavaScript SDK (since your app is made with angular)

You call the delete() method, as follows:

```<code>const user = firebase.auth().currentUser;
user.delete()
.then(() => {
   //....
})
.catch(err => {
  if (err.code === "auth/requires-recent-login") {
     //Re-authenticate the user
  } else {
     //....
  }
})
</code>```

Note however, that this method "requires the user to have recently signed in. If this requirement isn't met, ask the user to authenticate again and then call firebase.User.reauthenticateWithCredential". An error with the auth/requires-recent-login code is "thrown if the user's last sign-in time does not meet the security threshold".

So, only the logged-in user can call this method from a front-end, in order to delete his/her own account.

2/ Using the Admin SDK

You can use the Admin SDK's deleteUser() method, for example within a Cloud Function.

In this case, there is no need to have the user logged-in since this is executed in the back-end and it is therefore possible to delete any user.

For example, you could have a Callable Cloud Function triggered by an admin user.

Another possibility, is to trigger a Cloud Function upon the Firestore user's document deletion.

Update based on your Question update:

I understand that you want to delete the user record in the Auth service upon deletion. For that you can write a Cloud Function as follows:

```<code>exports.deleteUser = functions.firestore
    .document('Students/{studentID}')
    .onDelete((snap, context) => {

        const deletedValue = snap.data();
        const userEmail = deletedValue.Email;

        return admin.auth().getUserByEmail(userEmail)
            .then(userRecord => {
                const userID = userRecord.uid;
                return admin.auth().deleteUser(userID)
            })
            .catch(error => {
                console.log(error.message);
                return null;
            })

    });
</code>```

Body:
when clicking on a button i called a function,

onDelete(id:string){ this.db.collection('Students').doc(id).delete(); }

Here, id is a name of document that i want to delete, db is a property of type AngularFireStore, 'Students' is a name of collection.

Structure of document:
enter image description here
 In the above image, collection name is Students, under which multiple documents exist, since document name must be unique so i given that name a number of type string which acts as id. In every document, there is email field, i want to delete that email from authentication when i delete the same document.

code to sign up users:

this.afAuth.auth.createUserWithEmailAndPassword(email:string,password:string).then(res=>{})

Body:
If you want to delete a user existing in Firebase authentication you have two possibilities:

1/ Using the JavaScript SDK (since your app is made with angular)

You call the delete() method, as follows:

const user = firebase.auth().currentUser;
user.delete()
.then(() => {
   //....
})
.catch(err => {
  if (err.code === "auth/requires-recent-login") {
     //Re-authenticate the user
  } else {
     //....
  }
})

Note however, that this method "requires the user to have recently signed in. If this requirement isn't met, ask the user to authenticate again and then call firebase.User.reauthenticateWithCredential". An error with the auth/requires-recent-login code is "thrown if the user's last sign-in time does not meet the security threshold".

So, only the logged-in user can call this method from a front-end, in order to delete his/her own account.

2/ Using the Admin SDK

You can use the Admin SDK's deleteUser() method, for example within a Cloud Function.

In this case, there is no need to have the user logged-in since this is executed in the back-end and it is therefore possible to delete any user.

For example, you could have a Callable Cloud Function triggered by an admin user.

Another possibility, is to trigger a Cloud Function upon the Firestore user's document deletion.

Update based on your Question update:

I understand that you want to delete the user record in the Auth service upon deletion. For that you can write a Cloud Function as follows:

exports.deleteUser = functions.firestore
    .document('Students/{studentID}')
    .onDelete((snap, context) => {

        const deletedValue = snap.data();
        const userEmail = deletedValue.Email;

        return admin.auth().getUserByEmail(userEmail)
            .then(userRecord => {
                const userID = userRecord.uid;
                return admin.auth().deleteUser(userID)
            })
            .catch(error => {
                console.log(error.message);
                return null;
            })

    });


问:
Are there dynamic typings on python?
I have a specific use-case for typings which I find hard to implement.

I have the concept of "Service" classes on my python codebase, which are classes with a handful of functions I want to "expose" so only they will be available when using an API. The implementation of the Service is like this:

```<code>class MyService(BaseService):
    def normal_function(self):
        pass

    @exposed
    def exposed_function(self):
        pass
</code>```

What's happening behind the @exposed thing is that it adds a unique property to the wrapped method which allows someone who uses it to know which functions are "exposed" or not.

I wish to make a type smart enough to understand that only the "exposed" functions are available.

Any ideas?

答:
You could use name mangling:

```<code>class MyService():
    def __normal_function(self):
        pass

    def exposed_function(self):
        pass

my_service = MyService()
my_service.exposed_function() # this works, user can use the exposed function
my_service.__normal_function() # error: MyService instance has no attribute '__normal_function'
my_service._MyService__normal_function() # normal_function can only be called using its "mangled" name
</code>```

In this case, the name of the normal function - __normal_function - will be textually replaced with _MyService__normal_function, so that the user will not be able to call the function using its "original" name.

Note that the normal function can still be called outside of the class, since private variables and methods don't exist in Python, but name mangling is probably the closest you can get to implementing private-like behavior.

Title: Are there dynamic typings on python?

Body:
I have a specific use-case for typings which I find hard to implement.

I have the concept of "Service" classes on my python codebase, which are classes with a handful of functions I want to "expose" so only they will be available when using an API. The implementation of the Service is like this:

class MyService(BaseService):
    def normal_function(self):
        pass

    @exposed
    def exposed_function(self):
        pass

What's happening behind the @exposed thing is that it adds a unique property to the wrapped method which allows someone who uses it to know which functions are "exposed" or not.

I wish to make a type smart enough to understand that only the "exposed" functions are available.

Any ideas?

Body:
You could use name mangling:

class MyService():
    def __normal_function(self):
        pass

    def exposed_function(self):
        pass

my_service = MyService()
my_service.exposed_function() # this works, user can use the exposed function
my_service.__normal_function() # error: MyService instance has no attribute '__normal_function'
my_service._MyService__normal_function() # normal_function can only be called using its "mangled" name

In this case, the name of the normal function - __normal_function - will be textually replaced with _MyService__normal_function, so that the user will not be able to call the function using its "original" name.

Note that the normal function can still be called outside of the class, since private variables and methods don't exist in Python, but name mangling is probably the closest you can get to implementing private-like behavior.


问:
No property saveAll found for type
I recently started using ReactiveCouchbaseRepository (spring-data-couchbase - 3.0.0.M2, spring-boot-starter-parent - 2.0.0.M2) in one of our projects.

I referred to unpublished doc from here and setup the project but I am getting the following error.

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dummyRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property saveAll found for type Dummy!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1717) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:305) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:233) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:303) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:250) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
</code>```

Here is the relevant information about setting up my project.

@Maven

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.M2</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

...

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-couchbase</artifactId>
        <version>3.0.0.M2</version>
    </dependency>
</code>```

@java

```<code>//Repository class
public interface DummyRepository extends ReactiveCouchbaseSortingRepository<Dummy, String> {
}

//Model class
public class Dummy {

@Id
private final String id;

@Field
private final String name;

@Field
private final String address;

...
}

//Java config class
@Configuration
@EnableReactiveCouchbaseRepositories
public class CouchbaseDatabaseConfig extends AbstractReactiveCouchbaseConfiguration {

...
}
</code>```

Now, i did go through this and this but here i have no custom method written in the DummyRepository class.

Note that when I change from ReactiveCouchbaseSortingRepository to CouchbaseRepository, the things works fine.

Thanks for the help in advance.

答: You should Add @Query on you method otherwise, the jpa will treat it as a property</p>

Title: No property saveAll found for type

Body:
I recently started using ReactiveCouchbaseRepository (spring-data-couchbase - 3.0.0.M2, spring-boot-starter-parent - 2.0.0.M2) in one of our projects.

I referred to unpublished doc from here and setup the project but I am getting the following error.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dummyRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property saveAll found for type Dummy!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1717) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:305) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:233) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:303) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:250) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]

Here is the relevant information about setting up my project.

@Maven

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.M2</version>
    <relativePath/>
</parent>

...

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-couchbase</artifactId>
        <version>3.0.0.M2</version>
    </dependency>

@java

//Repository class
public interface DummyRepository extends ReactiveCouchbaseSortingRepository<Dummy, String> {
}

//Model class
public class Dummy {

@Id
private final String id;

@Field
private final String name;

@Field
private final String address;

...
}

//Java config class
@Configuration
@EnableReactiveCouchbaseRepositories
public class CouchbaseDatabaseConfig extends AbstractReactiveCouchbaseConfiguration {

...
}

Now, i did go through this and this but here i have no custom method written in the DummyRepository class.

Note that when I change from ReactiveCouchbaseSortingRepository to CouchbaseRepository, the things works fine.

Thanks for the help in advance.


问:
Trying to have multiple input elements
But when i use handle input change function it erases the entire object and replaces it with one property

Also If someone can help me reset the form data?  because I'm setting state to the initial state value but the text fields arent erasing.

```<code>const initialState = {
  name: '',
  number: '',
  message: '',
  email: '',
  messageSent: false,
};

//State After typingState
{email: "2"}
</code>```

I was using a class-based component and it was working fine I switched over and now I am getting one property on submit instead of 4
 I would like for the handle change to change a particular property and not the entire object
stepped away from react for a while an d not sure what to google fo this fix. Tried
Handling Multiple inputs Functional Components React etc..

```<code> let handleInputChange = (event) => {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    setstate({
      [name]: value,
    });
  }
    return (
      <section
        id="contact-form"
        className={
         GrayBg === true
            ? 'contact-form-area_3'
            : 'contact-form-area_3  contact-page-version'
        }
      >
        <div className="container">
          <div className="section-title mb45 headline text-center">
            <span className="subtitle text-uppercase">Send us a message</span>
            <h2>
              Send Us A<span> Message.</span>
            </h2>
          </div>

          <div className="contact_third_form">
            <form
              className="contact_form"
              encType="multipart/form-data"
              onSubmit={ sendEmail}
            >
              <div className="row">
                <div className="col-md-4">
                  <div className="contact-info">
                    <input
                      className="name"
                      name="name"
                      type="text"
                      value={state.value}
                      onChange={handleInputChange}
                      placeholder="Your Name."
                    />
                  </div>
                </div>
                <div className="col-md-4">
                  <div className="contact-info">
                    <input
                      className="email"
                      name="email"
                      type="email"
                      value={state.value}
                      onChange={handleInputChange}
                      placeholder="Your Email"
                    />
                  </div>
                </div>
                <div className="col-md-4">
                  <div className="contact-info">
                    <input
                      className="number"
                      name="number"
                      type="number"
                      value={state.value}
                      onChange={handleInputChange}
                      placeholder="Phone Number"
                    />
                  </div>
                </div>
              </div>
              <textarea
                name="message"
                placeholder="Message."
                value={state.value}
                onChange={handleInputChange}
              ></textarea>
              <div className="nws-button text-center  gradient-bg text-uppercase">
                <button id="contact-button" type="submit">
                  {state.messageSent ? 'Sent!' : 'Send'}{' '}
                  <i
                    className={
                      state.messageSent
                        ? 'fas fa-check'
                        : 'fas fa-caret-right'
                    }
                  ></i>
                </button>
              </div>
            </form>
          </div>
        </div>
</code>```

答:
State updates are not merged with hooks unlike in class components, you need to do so yourself.

Update your state using a functional approach to setState and by spreading the rest of the values within the returned object like

```<code>setstate(prev => ({
  ...prev,
  [name]: value,
}));
</code>```

Title: Trying to have multiple input elements

Body:
But when i use handle input change function it erases the entire object and replaces it with one property

Also If someone can help me reset the form data?  because I'm setting state to the initial state value but the text fields arent erasing.

const initialState = {
  name: '',
  number: '',
  message: '',
  email: '',
  messageSent: false,
};

//State After typingState
{email: "2"}

I was using a class-based component and it was working fine I switched over and now I am getting one property on submit instead of 4
 I would like for the handle change to change a particular property and not the entire object
stepped away from react for a while an d not sure what to google fo this fix. Tried
Handling Multiple inputs Functional Components React etc..

 let handleInputChange = (event) => {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    setstate({
      [name]: value,
    });
  }
    return (

            Send us a message

              Send Us A Message.

            <form
              className="contact_form"
              encType="multipart/form-data"
              onSubmit={ sendEmail}
            >

                    <input
                      className="name"
                      name="name"
                      type="text"
                      value={state.value}
                      onChange={handleInputChange}
                      placeholder="Your Name."
                    />

                    <input
                      className="email"
                      name="email"
                      type="email"
                      value={state.value}
                      onChange={handleInputChange}
                      placeholder="Your Email"
                    />

                    <input
                      className="number"
                      name="number"
                      type="number"
                      value={state.value}
                      onChange={handleInputChange}
                      placeholder="Phone Number"
                    />

              <textarea
                name="message"
                placeholder="Message."
                value={state.value}
                onChange={handleInputChange}
              ></textarea>

                <button id="contact-button" type="submit">
                  {state.messageSent ? 'Sent!' : 'Send'}{' '}

                </button>

            </form>

Body:
State updates are not merged with hooks unlike in class components, you need to do so yourself.

Update your state using a functional approach to setState and by spreading the rest of the values within the returned object like

setstate(prev => ({
  ...prev,
  [name]: value,
}));


问:
Using JavaScript , how do I keep user input on page after it has reloaded?
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

```

With JavaScript, is there anyway to make input stay once the page reloads?

答:
You can use storage APIs (sessionStorage, localStorage) to acheive the same.
Note: Store only the data which is not sensitive. Never use it for sensitive data.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

Example using sessionStorage: https://codepen.io/kishin-karra/pen/zYvgQZZ?editors=1010

sample code:

```<code>var savedPost = sessionStorage.getItem('text');
document.getElementById("printhere").innerHTML = savedPost;
document.getElementById("userInput").value = savedPost;
function display() {
    var post = document.getElementById("userInput").value;
    document.getElementById("printhere").innerHTML = post;
    sessionStorage.setItem('text', post);
}
</code>```

Enter the text, click post and refresh

Body:
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

With JavaScript, is there anyway to make input stay once the page reloads?

Body:
You can use storage APIs (sessionStorage, localStorage) to acheive the same.
Note: Store only the data which is not sensitive. Never use it for sensitive data.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

Example using sessionStorage: https://codepen.io/kishin-karra/pen/zYvgQZZ?editors=1010

sample code:

var savedPost = sessionStorage.getItem('text');
document.getElementById("printhere").innerHTML = savedPost;
document.getElementById("userInput").value = savedPost;
function display() {
    var post = document.getElementById("userInput").value;
    document.getElementById("printhere").innerHTML = post;
    sessionStorage.setItem('text', post);
}

Enter the text, click post and refresh