问:
how to send image to server in react expo
I sent the image to server by bitmap in android studio this way:

```<code>  bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), resultUri);

       ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap = Bitmap.createScaledBitmap(bitmap , 500, 500, true);
        bitmap .compress(Bitmap.CompressFormat.JPEG, 100, baos);

        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

</code>```

Now in expo I have the uri using image picker ,How can I do this in react expo?

答:
You can send a formData if backend using RestAPI like this </p>

```<code> // Upload the image using the fetch and FormData APIs
  let formData = new FormData();
  // Assume "photo" is the name of the form field the server expects
  formData.append('photo', { uri: localUri, name: filename, type });

  return await fetch(YOUR_SERVER_URL, {
    method: 'POST',
    body: formData,
    headers: {
      'content-type': 'multipart/form-data',
    },
  });
</code>```

Body:
I sent the image to server by bitmap in android studio this way:

  bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), resultUri);

       ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap = Bitmap.createScaledBitmap(bitmap , 500, 500, true);
        bitmap .compress(Bitmap.CompressFormat.JPEG, 100, baos);

        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

Now in expo I have the uri using image picker ,How can I do this in react expo?

Body:
You can send a formData if backend using RestAPI like this

 // Upload the image using the fetch and FormData APIs
  let formData = new FormData();
  // Assume "photo" is the name of the form field the server expects
  formData.append('photo', { uri: localUri, name: filename, type });

  return await fetch(YOUR_SERVER_URL, {
    method: 'POST',
    body: formData,
    headers: {
      'content-type': 'multipart/form-data',
    },
  });


来源: stackexchange

问:
incompatibility for accepts_nested_attributes_for between rails 2.3.5 and rails 2.3.8
I just discovered a change of behaviour between rails 2.3.5 and rails 2.3.8 and I can not find anything googling.

I have to models

```<code>class Book < ActiveRecord::Base
  has_many :authors
  accepts_nested_attributes_for authors
end

class Author < ActiveRecord::Base
  belongs_to :book
end
</code>```

I have a view to fill a book with authors nested views.

Into book controller I have an update action

```<code>def update
  @book = Book.find(params[:id])
  @book.attributes = params[:book]
  ....
end
</code>```

params[:book] look likes this :

```<code>{:name=>"a great book", "authors_attributes"=>{"1"=>{:id"=>"2", "_destroy"=>"", :name => "Boney M"}}}
</code>```

Latter in my proccess, I want to access to my updated collection (before saving the book object, for validation for example), with rails 2.3.5 @book.authors gave me the authors collection updated with the value into params[:book] hash. But with 2.3.8, it gives me the author collection reloaded from database.

My problem comes from function assign_nested_attributes_for_collection_association (/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/nested_attributes.rb). It returns a AssociationProxy object with @loaded = false. Thus the first time I want to access my collection with @book.authors, it reloads it from db. This was not the case with rails 2.3.5.

Did I missed something here or this new behaviour has been reported somewhere ?

Thanks in advance for your help.

答:
Not sure if this is related, but I just noticed that when I updated my app from 2.3.5 to 2.3.8 I can no longer update the associated record.  The system ignores updated information for already existing records and will only add new records.  I find that if I want to update the associated record I have to remove it from the db and then create it again.  Totally sucks.

```<code>class Product < ActiveRecord::Base
    has_many :allowed_design_types, :dependent => :destroy, :include => [:design_type], :order => 'design_types.name'
    has_many :design_types, :through => :allowed_design_types
    accepts_nested_attributes_for(
      :allowed_design_types,
      :allow_destroy => true,
      :reject_if => proc { |obj| p obj; !['1', 'true'].include?(obj.delete('allow')) }
    )
end
</code>```

This gets sent in the params but gets completely ignored:

```<code>"product"=>{"allowed_design_types_attributes"=>{"0"=>{"design_type_id"=>"5", "allow"=>"1", "product_id"=>"1", "id"=>"45", "your_price"=>"3", "_destroy"=>""}}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I just discovered a change of behaviour between rails 2.3.5 and rails 2.3.8 and I can not find anything googling.

I have to models

class Book < ActiveRecord::Base
  has_many :authors
  accepts_nested_attributes_for authors
end

class Author < ActiveRecord::Base
  belongs_to :book
end

I have a view to fill a book with authors nested views.

Into book controller I have an update action

def update
  @book = Book.find(params[:id])
  @book.attributes = params[:book]
  ....
end

params[:book] look likes this :

{:name=>"a great book", "authors_attributes"=>{"1"=>{:id"=>"2", "_destroy"=>"", :name => "Boney M"}}}

Latter in my proccess, I want to access to my updated collection (before saving the book object, for validation for example), with rails 2.3.5 @book.authors gave me the authors collection updated with the value into params[:book] hash. But with 2.3.8, it gives me the author collection reloaded from database.

My problem comes from function assign_nested_attributes_for_collection_association (/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/nested_attributes.rb). It returns a AssociationProxy object with @loaded = false. Thus the first time I want to access my collection with @book.authors, it reloads it from db. This was not the case with rails 2.3.5.

Did I missed something here or this new behaviour has been reported somewhere ?

Thanks in advance for your help.

Body:
Not sure if this is related, but I just noticed that when I updated my app from 2.3.5 to 2.3.8 I can no longer update the associated record.  The system ignores updated information for already existing records and will only add new records.  I find that if I want to update the associated record I have to remove it from the db and then create it again.  Totally sucks.

class Product < ActiveRecord::Base
    has_many :allowed_design_types, :dependent => :destroy, :include => [:design_type], :order => 'design_types.name'
    has_many :design_types, :through => :allowed_design_types
    accepts_nested_attributes_for(
      :allowed_design_types,
      :allow_destroy => true,
      :reject_if => proc { |obj| p obj; !['1', 'true'].include?(obj.delete('allow')) }
    )
end

This gets sent in the params but gets completely ignored:

"product"=>{"allowed_design_types_attributes"=>{"0"=>{"design_type_id"=>"5", "allow"=>"1", "product_id"=>"1", "id"=>"45", "your_price"=>"3", "_destroy"=>""}}

ContentLicense: CC BY-SA 3.0


问:
Conditional Formatting Question - Excel (AND,ISNUMBER,LARGE)
I can't write this correctly.  I'd like to highlight the cells in the H column that are a number (ISNUMBER) while matching them with the greatest date (LARGE) in the column A.

I tried:

```<code>=AND(ISNUMBER($H4),$A4=LARGE($A$4:$A$15,1))
</code>```

H4 contains 6.93

A4 contains 1/1/2020 - correctly formatted as date

Conditional formula: =$A4=LARGE($A$4:$A$15,1) works fine, standalone.  The value 12/1/2020 highlights.

Conditional formula: =ISNUMBER($H4) highlights the correct values, standalone.

I really need this formula to highlight H9 as it reflects the LARGE date 06/01 and the ISNUMBER cell H9 that has the value 6.01 and the largest date with a number in column H.

I don't know where I'm going wrong.  My syntax is bad.  I'm only an Admin. I'd appreciate any support I'm given. Thank you.

ExcelDatasheet:

答:
Here is the conditional formatting.

```<code>=AND(H4>0,ISNUMBER(H4),N(A4)=MAX(IF($H$4:$H$15=H4,$A$4:$A$15)))
</code>```

Here we use =And(Criteria1,Criteria2,Criteria3)

Criteria1: we use H4>0 to filter the blank cell. you can also use H4<>0

Criteria2: we use IsNumber to filter the "-" string.

Criteria3: we use MAX(If()) to find the duplicate number with the latest date.

ContentLicense: CC BY-SA 4.0

Body:
I can't write this correctly.  I'd like to highlight the cells in the H column that are a number (ISNUMBER) while matching them with the greatest date (LARGE) in the column A.

I tried:

=AND(ISNUMBER($H4),$A4=LARGE($A$4:$A$15,1))

H4 contains 6.93

A4 contains 1/1/2020 - correctly formatted as date

Conditional formula: =$A4=LARGE($A$4:$A$15,1) works fine, standalone.  The value 12/1/2020 highlights.

Conditional formula: =ISNUMBER($H4) highlights the correct values, standalone.

I really need this formula to highlight H9 as it reflects the LARGE date 06/01 and the ISNUMBER cell H9 that has the value 6.01 and the largest date with a number in column H.

I don't know where I'm going wrong.  My syntax is bad.  I'm only an Admin. I'd appreciate any support I'm given. Thank you.

ExcelDatasheet:

Body:
Here is the conditional formatting.

=AND(H4>0,ISNUMBER(H4),N(A4)=MAX(IF($H$4:$H$15=H4,$A$4:$A$15)))

Here we use =And(Criteria1,Criteria2,Criteria3)

Criteria1: we use H4>0 to filter the blank cell. you can also use H4<>0

Criteria2: we use IsNumber to filter the "-" string.

Criteria3: we use MAX(If()) to find the duplicate number with the latest date.


问:
I can't fetch documents from the downloads folder in android
I am trying to attach documents from download folder. But i am getting the error
"java.io.FileNotFoundException: /storage/emulated/0/DownloadReact-native commands.pdf (No such file or directory)".Here i show the code that i used to get path.</p>

```<code> if (isDownloadsDocument(uri)) {

                    Log.d("build_version_one", Build.VERSION.SDK_INT.toString())
                    Log.d("build_version_two", Build.VERSION_CODES.M.toString())

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        val id: String
                        var cursor: Cursor? = null
                        try {
                            cursor = context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
                            if (cursor != null && cursor.moveToFirst()) {

                                val fileName = cursor.getString(0)
                               // val path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
                                val path = Environment.getExternalStorageDirectory().toString() +"/Download" + fileName
                                val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download" + fileName

                                Log.d("orginal_path","one"+path)
                                Log.d("orginal_path","two"+ss)

                                if (!TextUtils.isEmpty(path)) {
                                    Log.d("orginal_path","working")
                                    return path
                                }
                            }
                        } finally {
                            cursor?.close()
                        }
                        id = DocumentsContract.getDocumentId(uri)
                        if (!TextUtils.isEmpty(id)) {
                            if (id.startsWith("raw:")) {
                                return id.replaceFirst("raw:".toRegex(), "")
                            }
                            val contentUriPrefixesToTry = arrayOf(
                                    "content://downloads/public_downloads",
                                    "content://downloads/my_downloads"
                            )
                            for (contentUriPrefix in contentUriPrefixesToTry) {
                                return try {
                                    val contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), java.lang.Long.valueOf(id))
                                    Log.d("orginal_content_uri", contentUri.toString())
                                    /*   final Uri contentUri = ContentUris.withAppendedId(
                                                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
                                    getDataColumn(context, contentUri, null, null)
                                } catch (e: NumberFormatException) {
                                    //In Android 8 and Android P the id is not a number
                                    uri.path.replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "")
                                }
                            }
                        }
                    }
                }
</code>```

答: getExternalStorageDirectory deprecated in API level 29 java. Use getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDir() (methods on Context).

Body:
I am trying to attach documents from download folder. But i am getting the error
"java.io.FileNotFoundException: /storage/emulated/0/DownloadReact-native commands.pdf (No such file or directory)".Here i show the code that i used to get path.

 if (isDownloadsDocument(uri)) {

                    Log.d("build_version_one", Build.VERSION.SDK_INT.toString())
                    Log.d("build_version_two", Build.VERSION_CODES.M.toString())

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        val id: String
                        var cursor: Cursor? = null
                        try {
                            cursor = context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
                            if (cursor != null && cursor.moveToFirst()) {

                                val fileName = cursor.getString(0)
                               // val path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
                                val path = Environment.getExternalStorageDirectory().toString() +"/Download" + fileName
                                val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download" + fileName

                                Log.d("orginal_path","one"+path)
                                Log.d("orginal_path","two"+ss)

                                if (!TextUtils.isEmpty(path)) {
                                    Log.d("orginal_path","working")
                                    return path
                                }
                            }
                        } finally {
                            cursor?.close()
                        }
                        id = DocumentsContract.getDocumentId(uri)
                        if (!TextUtils.isEmpty(id)) {
                            if (id.startsWith("raw:")) {
                                return id.replaceFirst("raw:".toRegex(), "")
                            }
                            val contentUriPrefixesToTry = arrayOf(
                                    "content://downloads/public_downloads",
                                    "content://downloads/my_downloads"
                            )
                            for (contentUriPrefix in contentUriPrefixesToTry) {
                                return try {
                                    val contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), java.lang.Long.valueOf(id))
                                    Log.d("orginal_content_uri", contentUri.toString())
                                    /*   final Uri contentUri = ContentUris.withAppendedId(
                                                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
                                    getDataColumn(context, contentUri, null, null)
                                } catch (e: NumberFormatException) {
                                    //In Android 8 and Android P the id is not a number
                                    uri.path.replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "")
                                }
                            }
                        }
                    }
                }


问:
Is there a more elegant cast from int to float than static_cast<float>?
I'm a .NET developer trying to do c++ (ahem) and I encountered a compiler warning in here:

```<code>const auto u = (textel.character % font_glyph_column_count) * font_glyph_size; // <- all int
const auto v = (textel.character / font_glyph_column_count) * font_glyph_size; // <- all int
const auto top_left_uv = sf::Vector2f(u, v);
</code>```

In the last line, where 'u' and 'v' are passed as args to the Vector ctor, the compiler says:

conversion from 'const int' to 'T', possible loss of data

Ok, .NET doesn't do this, but i looked it up and i understand that not all int32 can be represented by a float. (Now I wonder why .NET doesn't warn about this :) )

So, my .NET inspired solution is - apparently called - a "C cast", which my Resharper complains about: so, i change it to a  static_cast. Okido...

```<code>const auto u = static_cast<float>(textel.character % font_glyph_column_count) * font_glyph_size;
const auto v = static_cast<float>(textel.character / font_glyph_column_count) * font_glyph_size;
const auto top_left_uv = sf::Vector2f(u, v);
</code>```

But yuk! now my arithmetic code gets littered with these casts, while the juggling around of integer computation is very deliberate, and having to put the result in float-based vectors, is also necessary...

I could change eg. font_glyph_size to a float, so casting becomes implicit, but it makes more sense for it to be a discrete amount of pixels, so int...

Can this code be made prettier?

答:
You can use c stryle cast.

int a = 1;
float b = (float) a;

Also you can do just

int a = 1;
float b = a;

Body:
I'm a .NET developer trying to do c++ (ahem) and I encountered a compiler warning in here:

const auto u = (textel.character % font_glyph_column_count) * font_glyph_size; // <- all int
const auto v = (textel.character / font_glyph_column_count) * font_glyph_size; // <- all int
const auto top_left_uv = sf::Vector2f(u, v);

In the last line, where 'u' and 'v' are passed as args to the Vector ctor, the compiler says:

conversion from 'const int' to 'T', possible loss of data

Ok, .NET doesn't do this, but i looked it up and i understand that not all int32 can be represented by a float. (Now I wonder why .NET doesn't warn about this :) )

So, my .NET inspired solution is - apparently called - a "C cast", which my Resharper complains about: so, i change it to a  static_cast. Okido...

const auto u = static_cast<float>(textel.character % font_glyph_column_count) * font_glyph_size;
const auto v = static_cast<float>(textel.character / font_glyph_column_count) * font_glyph_size;
const auto top_left_uv = sf::Vector2f(u, v);

But yuk! now my arithmetic code gets littered with these casts, while the juggling around of integer computation is very deliberate, and having to put the result in float-based vectors, is also necessary...

I could change eg. font_glyph_size to a float, so casting becomes implicit, but it makes more sense for it to be a discrete amount of pixels, so int...

Can this code be made prettier?


问:
ajp/1.3 port no is not showing in apache tomcat
I was running my web program in eclipse ide using apache tomcat but while changing my port number I didn't find ajp/1.3 port, I think in past while solving an error I tried to change it and now it's not there, I tried to reinstall apache tomcat but still, it's not coming.

 please help me

答:
Go to the Tomcat server conf($Tomcat_Home/conf) directory and check the AJP connector available or not in server.xml. If not the add below entry in server.xml after HTTP connector. </p>

```<code><Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
</code>```

Body:
Go to the Tomcat server conf($Tomcat_Home/conf) directory and check the AJP connector available or not in server.xml. If not the add below entry in server.xml after HTTP connector.

<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


问:
Problem with reading from a json file when refreshing th page Angular
I have an angular application and the client wants the path of the Backend in a json file, so he can change it easily whithout needing of another deployment.

Well i did it, but when i refresh the page or close the app and reopen it, the app don't detect the path of the backend, it is like a problem of retard or synchronisation.

This is the error in the console :

```<code> http://***/undefinedapi/Leave/GetlistLeave
</code>```

This is how i did it :
The json file :

```<code>    {
      "ApiRoot": "http://***/"
    }
</code>```

How i read from the constant from the json file :

```<code>     import { Injectable } from '@angular/core';
     import { Http, Response } from '@angular/http';
     import { Observable } from 'rxjs';
     import { apiRoot } from '../model/model.apiRoot';
     import { map } from 'rxjs/operators';

     @Injectable({
     providedIn: 'root'
     })
     export class apiRootService {
    static apiRoot: string;
     constructor(private http: Http) { }
     public initialiseApiRoot()
     {

         this.http.get('./assets/apiRoot/apiRoot.json').pipe(map((response: Response) =>
      <apiRoot>response.json())).subscribe(data => {
          apiRootService.apiRoot = data['ApiRoot'];
      })

     }
   }
</code>```

and then i call this function in the constructor of app.component.ts like this :

```<code>        this.apiRootService.initialiseApiRoot();
</code>```

and change the call of the api in every servic elike this :

```<code>       return this.http.get(apiRootService.apiRoot + .....
</code>```

Any hlp and thanks

答: because you are going with wrong approach. you are seeting url after application is initialized. Refer :- https://medium.com/voobans-tech-stories/multiple-environments-with-angular-and-docker-2512e342ab5a. this will give general idea how to achieve build once and deploy anywhere</p>

Body:
I have an angular application and the client wants the path of the Backend in a json file, so he can change it easily whithout needing of another deployment.

Well i did it, but when i refresh the page or close the app and reopen it, the app don't detect the path of the backend, it is like a problem of retard or synchronisation.

This is the error in the console :

 http://***/undefinedapi/Leave/GetlistLeave

This is how i did it :
The json file :

    {
      "ApiRoot": "http://***/"
    }

How i read from the constant from the json file :

     import { Injectable } from '@angular/core';
     import { Http, Response } from '@angular/http';
     import { Observable } from 'rxjs';
     import { apiRoot } from '../model/model.apiRoot';
     import { map } from 'rxjs/operators';

     @Injectable({
     providedIn: 'root'
     })
     export class apiRootService {
    static apiRoot: string;
     constructor(private http: Http) { }
     public initialiseApiRoot()
     {

         this.http.get('./assets/apiRoot/apiRoot.json').pipe(map((response: Response) =>
      <apiRoot>response.json())).subscribe(data => {
          apiRootService.apiRoot = data['ApiRoot'];
      })

     }
   }

and then i call this function in the constructor of app.component.ts like this :

        this.apiRootService.initialiseApiRoot();

and change the call of the api in every servic elike this :

       return this.http.get(apiRootService.apiRoot + .....

Any hlp and thanks


问:
Facade\Ignition\Exceptions\ViewException Trying to get property 'id' of non-object
I've been trying to fetch all the rows where the user id is. then I got this error. Please help me.

CONTROLLER:

```<code>    public function index()
    {
        $user_id = Auth::user()->id;

        $applications = application::where('user_id', '=', $user_id)->first();

        if (empty($applications)) {
            $applications = "0";
            return view('user.application.index',compact('applications'));
        }
        else{
        return view('user.application.index',compact('applications'));
        }
    }
</code>```

blade file

```<code> @foreach ($applications as $application)
  <tr>
    <td>{{ $loop->index +1 }}</td>
    <td>{{ $application->id }}</td>
    <td>{{ $application->created_at }}</td>
    <td>{{ $application->surname }}, {{ $application->firstname }} {{ $application->middlename }}</td>
    @if ($application->status == 1)
    <td><p style="color:green;">APPROVED</p></td>
    @elseif ($application->status == 0)
    <td><p style="color:rgb(243, 180, 8);">PENDING</p></td>
    @else
    <td><p style="color:RED;">DISAPPROVED</p></td>
    @endif
    <td><a href = "{{ route('user.application.show', $application->id)}}"><img src = {{ asset('assets/img/eye.ico') }}/></a>
    </td>
  </tr>
</code>```

答: Try replacing $applications='0' with $applications=[] and see if it works ;)

Body:
I've been trying to fetch all the rows where the user id is. then I got this error. Please help me.

CONTROLLER:

    public function index()
    {
        $user_id = Auth::user()->id;

        $applications = application::where('user_id', '=', $user_id)->first();

        if (empty($applications)) {
            $applications = "0";
            return view('user.application.index',compact('applications'));
        }
        else{
        return view('user.application.index',compact('applications'));
        }
    }

blade file

 @foreach ($applications as $application)

    {{ $loop->index +1 }}
    {{ $application->id }}
    {{ $application->created_at }}
    {{ $application->surname }}, {{ $application->firstname }} {{ $application->middlename }}
    @if ($application->status == 1)

APPROVED

    @elseif ($application->status == 0)

PENDING

    @else

DISAPPROVED

    @endif
    id)}}">


问:
How to use PageTransitionsBuilder when navigating to a different screen?
```<code>final builder = OpenUpwardsPageTransitionsBuilder();

Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (_, __, ___) => Page2(),
    transitionsBuilder: builder, // error
  ),
);
</code>```

What I understand is, I can only setup PageTransitionsBuilder inside a Theme, is there any way to use it inside Navigator?

答:
```<code>Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (ctx, a1, a2) => Screen2(),
    transitionsBuilder: (ctx, anim, a2, child) => FadeTransition(opacity: anim, child: child),
    transitionDuration: Duration(milliseconds: 3000),
  ),
);
</code>```

You can vary milliseconds time, as per your need in-app.

Body:
final builder = OpenUpwardsPageTransitionsBuilder();

Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (_, __, ___) => Page2(),
    transitionsBuilder: builder, // error
  ),
);

What I understand is, I can only setup PageTransitionsBuilder inside a Theme, is there any way to use it inside Navigator?

Body:
Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (ctx, a1, a2) => Screen2(),
    transitionsBuilder: (ctx, anim, a2, child) => FadeTransition(opacity: anim, child: child),
    transitionDuration: Duration(milliseconds: 3000),
  ),
);

You can vary milliseconds time, as per your need in-app.


问:
I am not allowed to run a python executable on other pcs
I was doing a game in tkinter, then I make it executable with PyInstaller and sent it to my friends so they can run it and tell me how it feels.
It seems that they could download the file, but can't open it because windows forbade them telling that it's not secure and not letting them choose to assume the risk or something.
They tried to run as administrator and still nothing changed.

What should I do or what I should add to my code so that windows can open it without problem and why windows opens other executable files without saying that(current error that my executable gets)?

答:
I finally figured out what I had to done

When the dialog appeared u need to click more info and then it will display a Run Anyway button


问:
Getting issue in props as"Cannot read property 'map' of undefined"
I am new to react. i have getting issue while passing the array containing object as props from one component to another component. Can u guys help me out in this ,

here is the code of card information component where i am passing value as prop

const CardsInformation = () => {
    const Baba = [
        {
            id: 'b1',
            header: 'Book 1 Name',
            image: 'https://www.google.com/search?q=engineering+books&rlz=1C1CHBF_enIN862IN862&sxsrf=ALeKk01jlMEcOr-2Vd0ev6RaoZZSAqMADg:1589729471894&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjO9dfjm7vpAhV8yjgGHR-zDCoQ_AUoAXoECBMQAw&biw=1536&bih=763#imgrc=OzVmsuZIvusEJM',
            discription: 'This book steps beyond the simple functions of the Clapper, introducing you to a number of products that can be used for everything from controlling lighting levels, watering your lawn, closing your drapes, and managing sundry appliances in your home.',
        }
    ];

    return (

            <Card_tabs book={Baba}/>

    )
}```
</div>
</div>
</p>

<p>here is another component where i am using the props and getting the issue as"Cannot read property 'map' of undefined" at {props.book.map}</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Card_tabs = (props) => {

            {props.book.map(user=>{
                return(<h1>{user.header}</h1>)
            })}

}</code>```

答:
```<code>import ReactDOM from "react-dom";
import React from "react";

const App = () => {
  const Baba = [
    {
      id: "b1",
      header: "Book 1 Name",
      image:
        "https://www.google.com/search?q=engineering+books&rlz=1C1CHBF_enIN862IN862&sxsrf=ALeKk01jlMEcOr-2Vd0ev6RaoZZSAqMADg:1589729471894&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjO9dfjm7vpAhV8yjgGHR-zDCoQ_AUoAXoECBMQAw&biw=1536&bih=763#imgrc=OzVmsuZIvusEJM",
      discription:
        "This book steps beyond the simple functions of the Clapper, introducing you to a number of products that can be used for everything from controlling lighting levels, watering your lawn, closing your drapes, and managing sundry appliances in your home."
    }
  ];

  return (
    <div>
      <CardTabs book={Baba} />
    </div>
  );
};

const CardTabs = ({ book }) => {
  return book.map(user => {
    return <h1>{user.header}</h1>;
  });
};

ReactDOM.render(<App />, document.getElementById("root"));

</code>```

Body:
I am new to react. i have getting issue while passing the array containing object as props from one component to another component. Can u guys help me out in this ,

here is the code of card information component where i am passing value as prop

const CardsInformation = () => {
    const Baba = [
        {
            id: 'b1',
            header: 'Book 1 Name',
            image: 'https://www.google.com/search?q=engineering+books&rlz=1C1CHBF_enIN862IN862&sxsrf=ALeKk01jlMEcOr-2Vd0ev6RaoZZSAqMADg:1589729471894&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjO9dfjm7vpAhV8yjgGHR-zDCoQ_AUoAXoECBMQAw&biw=1536&bih=763#imgrc=OzVmsuZIvusEJM',
            discription: 'This book steps beyond the simple functions of the Clapper, introducing you to a number of products that can be used for everything from controlling lighting levels, watering your lawn, closing your drapes, and managing sundry appliances in your home.',
        }
    ];

    return (

            <Card_tabs book={Baba}/>

    )
}

here is another component where i am using the props and getting the issue as"Cannot read property 'map' of undefined" at {props.book.map}

const Card_tabs = (props) => {

            {props.book.map(user=>{
                return(
{user.header}
)
            })}

}


问:
Problems with GAMS model
I've been experiencing with GAMS but I still haven't got a clue what I'm doing.
Can someone take a look at this short model and try to point me in the right direction?
I have problems in the compilation at the equations, getting a few of these:
  Dimension different - The symbol is referenced with more/less
       indices as declared
Uncontrolled set entered as constant</p>

```<code>Sets
        i months / 1, 2, 3 /
        j months / 1, 2, 3 /;

Parameters
         cp(i)  production cost in month i
         /        1     1.08
                  2     1.11
                  3     1.10
                                   /

         rh(i)  number of necessary workers in month i
         /        1     3
                  2     4
                  3     6
                                     /

        cap(i)  production capacity in month i
         /        1     25
                  2     20
                  3     25
                                       /
         q(j)  number of motors to deliver in month j
         /        1     10
                  2     15
                  3     25
                                 /

Scalar ca  cost to store motors for a month /0.15/ ;

variables
    mc(i,j) cost of production of motors in month i to be delivered in month j
    x(i,j)  number of motors produced in month i to be delivered in month j;

free variables
    wf workforce

    z cost of production
    hr human resources;

Equations
    cost cost
    human_resources human resources
    r1 restriction1
    r2 restriction2 ;

cost .. z  =e=  sum((i,j), (cp(i)+(j-i)*ca)*x(i,j)) ;
human_resources .. hr =e= sum(i, sum(j, rh(i)*x(i, j))) ;
*lower than
r1..   sum(j, x(i,j))  =l=  cap(i) ;
*greater than
r2.. sum(i, x(i,j))  =g=  q(j) ;

Model
    motors 'temp' /all/;

Solve motors using mip minimizing mc;

Display mc, x;
</code>```

答:
This works but check the solution. I added the positive variable x because otherwise  you would have negative productions.
The main problem was the fact that you were optimizing a variable that is declared but that you never use in the equations. Also, the variable you are optimizing cannot have to dimensions (I think).
Then, for constraints r1 and r2 you need to add an index because they must be verified for each month, so r1(i) and r2(j). They are actually a "family of constraints".
You cannot subtract the indexes of the months (can't explain why), but you can subtract their order in the set.<br>
And finally, calculate the mc(i,j) as a parameter after you have obtained the solution.  </p>

```<code>Sets
        i months / 1, 2, 3 /
        j months / 1, 2, 3 /;

Parameters
         cp(i)  production cost in month i
         /        1     1.08
                  2     1.11
                  3     1.10
                                   /

         rh(i)  number of necessary workers in month i
         /        1     3
                  2     4
                  3     6
                                     /

        cap(i)  production capacity in month i
         /        1     25
                  2     20
                  3     25
                                       /
         q(j)  number of motors to deliver in month j
         /        1     10
                  2     15
                  3     25
                                 /

Scalar ca  cost to store motors for a month /0.15/ ;

variables
*    mc(i,j) cost of production of motors in month i to be delivered in month j
    x(i,j)  number of motors produced in month i to be delivered in month j;

positive variable x;
free variables
    wf workforce

    z cost of production
    hr human resources;

Equations
    cost cost
    human_resources human resources
    r1(i) restriction1
    r2(j) restriction2 ;

cost .. z  =e=  sum((i,j), (cp(i)+(ord(j)-ord(i))*ca)*x(i,j)) ;
human_resources .. hr =e= sum(i, sum(j, rh(i)*x(i, j))) ;
*lower than
r1(i)..   sum(j, x(i,j))  =l=  cap(i) ;
*greater than
r2(j).. sum(i, x(i,j))  =g=  q(j) ;

Model
    motors 'temp' /all/;

Solve motors using mip minimizing z;

Parameter mc(i,j);
mc(i,j)= (cp(i)+(ord(j)-ord(i))*ca)*x.l(i,j);
Display mc, x.l;

</code>```

Title: Problems with GAMS model

Body:
I've been experiencing with GAMS but I still haven't got a clue what I'm doing.
Can someone take a look at this short model and try to point me in the right direction?
I have problems in the compilation at the equations, getting a few of these:
  Dimension different - The symbol is referenced with more/less
       indices as declared
Uncontrolled set entered as constant

Sets
        i months / 1, 2, 3 /
        j months / 1, 2, 3 /;

Parameters
         cp(i)  production cost in month i
         /        1     1.08
                  2     1.11
                  3     1.10
                                   /

         rh(i)  number of necessary workers in month i
         /        1     3
                  2     4
                  3     6
                                     /

        cap(i)  production capacity in month i
         /        1     25
                  2     20
                  3     25
                                       /
         q(j)  number of motors to deliver in month j
         /        1     10
                  2     15
                  3     25
                                 /

Scalar ca  cost to store motors for a month /0.15/ ;

variables
    mc(i,j) cost of production of motors in month i to be delivered in month j
    x(i,j)  number of motors produced in month i to be delivered in month j;

free variables
    wf workforce

    z cost of production
    hr human resources;

Equations
    cost cost
    human_resources human resources
    r1 restriction1
    r2 restriction2 ;

cost .. z  =e=  sum((i,j), (cp(i)+(j-i)*ca)*x(i,j)) ;
human_resources .. hr =e= sum(i, sum(j, rh(i)*x(i, j))) ;
*lower than
r1..   sum(j, x(i,j))  =l=  cap(i) ;
*greater than
r2.. sum(i, x(i,j))  =g=  q(j) ;

Model
    motors 'temp' /all/;

Solve motors using mip minimizing mc;

Display mc, x;

Body:
This works but check the solution. I added the positive variable x because otherwise  you would have negative productions.
The main problem was the fact that you were optimizing a variable that is declared but that you never use in the equations. Also, the variable you are optimizing cannot have to dimensions (I think).
Then, for constraints r1 and r2 you need to add an index because they must be verified for each month, so r1(i) and r2(j). They are actually a "family of constraints".
You cannot subtract the indexes of the months (can't explain why), but you can subtract their order in the set.

And finally, calculate the mc(i,j) as a parameter after you have obtained the solution.

Sets
        i months / 1, 2, 3 /
        j months / 1, 2, 3 /;

Parameters
         cp(i)  production cost in month i
         /        1     1.08
                  2     1.11
                  3     1.10
                                   /

         rh(i)  number of necessary workers in month i
         /        1     3
                  2     4
                  3     6
                                     /

        cap(i)  production capacity in month i
         /        1     25
                  2     20
                  3     25
                                       /
         q(j)  number of motors to deliver in month j
         /        1     10
                  2     15
                  3     25
                                 /

Scalar ca  cost to store motors for a month /0.15/ ;

variables
*    mc(i,j) cost of production of motors in month i to be delivered in month j
    x(i,j)  number of motors produced in month i to be delivered in month j;

positive variable x;
free variables
    wf workforce

    z cost of production
    hr human resources;

Equations
    cost cost
    human_resources human resources
    r1(i) restriction1
    r2(j) restriction2 ;

cost .. z  =e=  sum((i,j), (cp(i)+(ord(j)-ord(i))*ca)*x(i,j)) ;
human_resources .. hr =e= sum(i, sum(j, rh(i)*x(i, j))) ;
*lower than
r1(i)..   sum(j, x(i,j))  =l=  cap(i) ;
*greater than
r2(j).. sum(i, x(i,j))  =g=  q(j) ;

Model
    motors 'temp' /all/;

Solve motors using mip minimizing z;

Parameter mc(i,j);
mc(i,j)= (cp(i)+(ord(j)-ord(i))*ca)*x.l(i,j);
Display mc, x.l;


问:
specific handler method for dynamaically rendered form
I am having 3 materialUI TextFields which are render n number of times (n is an integer input from user before rendering the form field, here I stored it in a variable named groupMembersCount). I am using functional component in ReactJS defining an array with useState hooks as:

```<code>const [groupDetails, setGroupDetails] = React.useState([
    { fullName: "", phoneNo: "", gender: "" },
  ]);
</code>```

I am getting it dynamically rendered by this way:

```<code>export default function DynamicGroupMember() {
    const [groupMembersCount, setGroupMembersCount] = useState(0);
    const [show, setShow] = useState(false);
    const [groupDetails, setGroupDetails] = useState([
        {fullName: "", phoneNo: "", gender: ""},
    ]);
  function handleChange(event, index) {
        console.log(event.target.value, index);
        let newArr = [...groupDetails]; // copying the old datas array
        let item = newArr[index];
        item = {...item, [event.target.name]: event.target.value};
        newArr[index] = item;

        setGroupDetails(newArr);
    }

    return (
        <div>
            Number of Group: <TextField name="groupMembersCount" onChange={(event) => {
            setGroupMembersCount(event.target.value)
        }}/>
            {Array.apply(null, {length: groupMembersCount}).map(
                (e, i) => (
                    <div key={i}>
                        <strong>Member #{i + 1}</strong>
                        <div className="getIndex" name={i + 1}>
                            <TextField
                                id={`name${i + 1}`}
                                name="fullName"
                                variant="outlined"
                                margin="none"
                                label="Name"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            />
                            <TextField
                                id={`phoneNo${i + 1}`}
                                name="phoneNo"
                                variant="outlined"
                                margin="none"
                                label="Mobile Number"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            />
                            <Select
                                id={`gender${i + 1}`}
                                name="gender"
                                variant="outlined"
                                margin="none"
                                label="Gender"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            >
                                <option value="MALE">Male</option>
                                <option value="FEMALE">Female</option>
                                <option value="OTHER">Other</option>
                            </Select>
                        </div>
                    </div>
                )
            )}
            <Button onClick={() => {
                setShow(true)
            }}>Show</Button>
            {
                show ?
                    groupDetails.map(member =>
                        <Card>
                        <CardContent>
                            <Typography color="textSecondary" gutterBottom>
                                {member.fullName}
                            </Typography>
                            <Typography variant="h5" component="h2">
                                {member.phoneNo}
                            </Typography>
                            <Typography color="textSecondary">
                                {member.gender}
                            </Typography>
                        </CardContent>
                    </Card>) : null
            }
        </div>
    );
}
</code>```

I want to make one onChange handler on a dynamically rendered form field (phoneNo) to check what user is typing, and within that handler method I will add two props "error" to make the mobile number field red, and "helperText" to display a message (eg. incorrect number, if user type alphabet in number).
now if i am checking the validation of the number field, error and helperText are appearing in all the mobile number input fields (in n times rendered rows). I want it specific to the row in which the user is entering.

I hope I explained the problem statement well, if not please ask for any information.

答:
here is an example to validate input those are dynamically generated.</p>

```<code>import TextField from "@material-ui/core/TextField";
import React, {useState} from "react";
import Select from "@material-ui/core/Select";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";

export default function DynamicGroupMember2() {
    const [groupMembersCount, setGroupMembersCount] = useState(0);
    const [show, setShow] = useState(false);
    const [errorText, setErrorText] = useState([]);
    const [showState, setShowState] = useState(false);
    const [groupDetails, setGroupDetails] = useState([
        {fullName: "", phoneNo: "", gender: ""},
    ]);
    const [state, setState] = React.useState({
        idProof: "",
        noOfPeople: "",
        bookingId: "",
        detailsOfPeople: [],
    });

    function handleChange(event, index) {
        event.preventDefault();
        console.log(errorText.length, 'length');
        if (event.target.name === "phoneNo") {
            // do validation here
            let valid = false;
            if (isNaN(event.target.value)) {
                let arr = [...errorText];
                arr[index] = 'Invalid ' + event.target.name;
                setErrorText(arr);
            }
            else {
                let arr = [...errorText];
                arr[index] = '';
                setErrorText(arr);
            }
        }

        let newArr = [...groupDetails]; // copying the old datas array
        let item = newArr[index];
        item = {...item, [event.target.name]: event.target.value};
        newArr[index] = item;
        setGroupDetails(newArr);
    }

    return (
        <div>
            Number of Group: <TextField name="groupMembersCount" onChange={(event) => {
                if(isNaN(event.target.value)){
                    alert('Please enter number');
                    return;
                }
                if(event.target.value !== '') {
                    let errors = new Array(parseInt(event.target.value));
                    setErrorText(errors);
                    setGroupMembersCount(event.target.value);
                    console.log(errorText[1], 'errorText[i]')
                }
        }}/>
            {Array.apply(null, {length: groupMembersCount}).map(

                (e, i) => (
                    <div key={i}>
                        <strong>Member #{i + 1}</strong>
                        <div className="getIndex" name={i + 1}>
                            <TextField
                                id={`name${i + 1}`}
                                name="fullName"
                                variant="outlined"
                                margin="none"
                                label="Name"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            />
                            <TextField
                                id={`phoneNo${i + 1}`}
                                name="phoneNo"
                                variant="outlined"
                                margin="none"
                                label="Mobile Number"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                                error={errorText[i] !== '' && errorText[i] !== undefined}
                                helperText={errorText[i]}
                            />
                            <Select
                                id={`gender${i + 1}`}
                                name="gender"
                                variant="outlined"
                                margin="none"
                                label="Gender"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            >
                                <option value="MALE">Male</option>
                                <option value="FEMALE">Female</option>
                                <option value="OTHER">Other</option>
                            </Select>
                        </div>
                    </div>
                )
            )}
            <Button onClick={() => {
                setShow(true)
            }}>Show</Button>
            {
                show ?
                    groupDetails.map((member, index) =>
                        <Card key={index}>
                            <CardContent>
                                <Typography color="textSecondary" gutterBottom>
                                    {member.fullName}
                                </Typography>
                                <Typography variant="h5" component="h2">
                                    {member.phoneNo}
                                </Typography>
                                <Typography color="textSecondary">
                                    {member.gender}
                                </Typography>
                            </CardContent>
                        </Card>) : null
            }
            <Button onClick={() => {
                console.log(groupDetails, 'groupDetails');
                setState({
                    idProof: "XYZ123",
                    noOfPeople: groupDetails.length,
                    bookingId: "boking-4434",
                    detailsOfPeople: groupDetails
                });
                console.log(groupDetails, 'groupDetails');
                setShowState(true);

            }}>Show STATE</Button>
            {
                showState ?
                    <Card>
                        <CardContent>
                            <Typography color="textSecondary" gutterBottom>
                                Id Proof: {state.idProof}
                            </Typography>
                            <Typography variant="h5" component="h2">
                                No Of People: {state.noOfPeople}
                            </Typography>
                            <Typography color="textSecondary">
                                Booking Id: {state.bookingId}
                            </Typography>
                        </CardContent>
                    </Card> : null
            }
        </div>
    );
}
</code>```

Body:
I am having 3 materialUI TextFields which are render n number of times (n is an integer input from user before rendering the form field, here I stored it in a variable named groupMembersCount). I am using functional component in ReactJS defining an array with useState hooks as:

const [groupDetails, setGroupDetails] = React.useState([
    { fullName: "", phoneNo: "", gender: "" },
  ]);

I am getting it dynamically rendered by this way:

export default function DynamicGroupMember() {
    const [groupMembersCount, setGroupMembersCount] = useState(0);
    const [show, setShow] = useState(false);
    const [groupDetails, setGroupDetails] = useState([
        {fullName: "", phoneNo: "", gender: ""},
    ]);
  function handleChange(event, index) {
        console.log(event.target.value, index);
        let newArr = [...groupDetails]; // copying the old datas array
        let item = newArr[index];
        item = {...item, [event.target.name]: event.target.value};
        newArr[index] = item;

        setGroupDetails(newArr);
    }

    return (

            Number of Group: <TextField name="groupMembersCount" onChange={(event) => {
            setGroupMembersCount(event.target.value)
        }}/>
            {Array.apply(null, {length: groupMembersCount}).map(
                (e, i) => (

                        Member #{i + 1}

                            <TextField
                                id={`name${i + 1}`}
                                name="fullName"
                                variant="outlined"
                                margin="none"
                                label="Name"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            />
                            <TextField
                                id={`phoneNo${i + 1}`}
                                name="phoneNo"
                                variant="outlined"
                                margin="none"
                                label="Mobile Number"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            />
                            <Select
                                id={`gender${i + 1}`}
                                name="gender"
                                variant="outlined"
                                margin="none"
                                label="Gender"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            >
                                <option value="MALE">Male</option>
                                <option value="FEMALE">Female</option>
                                <option value="OTHER">Other</option>
                            </Select>

                )
            )}
            <Button onClick={() => {
                setShow(true)
            }}>Show</Button>
            {
                show ?
                    groupDetails.map(member =>
                        <Card>
                        <CardContent>
                            <Typography color="textSecondary" gutterBottom>
                                {member.fullName}
                            </Typography>
                            <Typography variant="h5" component="h2">
                                {member.phoneNo}
                            </Typography>
                            <Typography color="textSecondary">
                                {member.gender}
                            </Typography>
                        </CardContent>
                    </Card>) : null
            }

    );
}

I want to make one onChange handler on a dynamically rendered form field (phoneNo) to check what user is typing, and within that handler method I will add two props "error" to make the mobile number field red, and "helperText" to display a message (eg. incorrect number, if user type alphabet in number).
now if i am checking the validation of the number field, error and helperText are appearing in all the mobile number input fields (in n times rendered rows). I want it specific to the row in which the user is entering.

I hope I explained the problem statement well, if not please ask for any information.

Body:
here is an example to validate input those are dynamically generated.

import TextField from "@material-ui/core/TextField";
import React, {useState} from "react";
import Select from "@material-ui/core/Select";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";

export default function DynamicGroupMember2() {
    const [groupMembersCount, setGroupMembersCount] = useState(0);
    const [show, setShow] = useState(false);
    const [errorText, setErrorText] = useState([]);
    const [showState, setShowState] = useState(false);
    const [groupDetails, setGroupDetails] = useState([
        {fullName: "", phoneNo: "", gender: ""},
    ]);
    const [state, setState] = React.useState({
        idProof: "",
        noOfPeople: "",
        bookingId: "",
        detailsOfPeople: [],
    });

    function handleChange(event, index) {
        event.preventDefault();
        console.log(errorText.length, 'length');
        if (event.target.name === "phoneNo") {
            // do validation here
            let valid = false;
            if (isNaN(event.target.value)) {
                let arr = [...errorText];
                arr[index] = 'Invalid ' + event.target.name;
                setErrorText(arr);
            }
            else {
                let arr = [...errorText];
                arr[index] = '';
                setErrorText(arr);
            }
        }

        let newArr = [...groupDetails]; // copying the old datas array
        let item = newArr[index];
        item = {...item, [event.target.name]: event.target.value};
        newArr[index] = item;
        setGroupDetails(newArr);
    }

    return (
        <div>
            Number of Group: <TextField name="groupMembersCount" onChange={(event) => {
                if(isNaN(event.target.value)){
                    alert('Please enter number');
                    return;
                }
                if(event.target.value !== '') {
                    let errors = new Array(parseInt(event.target.value));
                    setErrorText(errors);
                    setGroupMembersCount(event.target.value);
                    console.log(errorText[1], 'errorText[i]')
                }
        }}/>
            {Array.apply(null, {length: groupMembersCount}).map(

                (e, i) => (
                    <div key={i}>
                        <strong>Member #{i + 1}</strong>
                        <div className="getIndex" name={i + 1}>
                            <TextField
                                id={`name${i + 1}`}
                                name="fullName"
                                variant="outlined"
                                margin="none"
                                label="Name"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            />
                            <TextField
                                id={`phoneNo${i + 1}`}
                                name="phoneNo"
                                variant="outlined"
                                margin="none"
                                label="Mobile Number"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                                error={errorText[i] !== '' && errorText[i] !== undefined}
                                helperText={errorText[i]}
                            />
                            <Select
                                id={`gender${i + 1}`}
                                name="gender"
                                variant="outlined"
                                margin="none"
                                label="Gender"
                                onChange={(event) => {
                                    handleChange(event, i)
                                }}
                            >
                                <option value="MALE">Male</option>
                                <option value="FEMALE">Female</option>
                                <option value="OTHER">Other</option>
                            </Select>
                        </div>
                    </div>
                )
            )}
            <Button onClick={() => {
                setShow(true)
            }}>Show</Button>
            {
                show ?
                    groupDetails.map((member, index) =>
                        <Card key={index}>
                            <CardContent>
                                <Typography color="textSecondary" gutterBottom>
                                    {member.fullName}
                                </Typography>
                                <Typography variant="h5" component="h2">
                                    {member.phoneNo}
                                </Typography>
                                <Typography color="textSecondary">
                                    {member.gender}
                                </Typography>
                            </CardContent>
                        </Card>) : null
            }
            <Button onClick={() => {
                console.log(groupDetails, 'groupDetails');
                setState({
                    idProof: "XYZ123",
                    noOfPeople: groupDetails.length,
                    bookingId: "boking-4434",
                    detailsOfPeople: groupDetails
                });
                console.log(groupDetails, 'groupDetails');
                setShowState(true);

            }}>Show STATE</Button>
            {
                showState ?
                    <Card>
                        <CardContent>
                            <Typography color="textSecondary" gutterBottom>
                                Id Proof: {state.idProof}
                            </Typography>
                            <Typography variant="h5" component="h2">
                                No Of People: {state.noOfPeople}
                            </Typography>
                            <Typography color="textSecondary">
                                Booking Id: {state.bookingId}
                            </Typography>
                        </CardContent>
                    </Card> : null
            }
        </div>
    );
}


问:
How do I convert Enter to Tab (with focus change) in IE9? It worked in IE8
I have a text input with an onkeydown event handler that converts <Enter> to <Tab> by changing the event's keyCode from 13 to 9.

```<code><input type="text" onkeydown="enterToTab(event);" onchange="changeEvent(this);"
       name="" value="" />
<!-- Other inputs exist as created via the DOM, but they are not sibling elements. -->
</code>```

Javascript:

```<code>function enterToTab(myEvent) {
    if (myEvent.keyCode == 13) {
        myEvent.keyCode = 9;
    }
}
function changeEvent(myInput) { var test = "hello"; }
</code>```

In IE8, this caused the onchange event to fire, but that doesn't happen in IE9. Instead, the input field retains focus. How I can I make that happen? (It works in Firefox 3.6 and Chrome 10.0.) This even works in Browser Mode IE9 if I set the Document Mode to "IE8 standards". But it won't work with a Document Mode of "IE9 standards". (My DocType is XHTML 1.0 Transitional.)

Since it works in IE7 & 8, could this be a bug in IE9 that will get fixed?

Please note: I cannot use input.blur() or manually set a new focus, which is advised by all the other solutions that I've read. I've already tried onkeypress and onkeyup with no luck. I need a generic solution that will cause the web app to literally behave as though I'd hit <Tab>. Also, I don't have jQuery, however, Dojo 1.5 is available to me.

Also note: I KNOW this is "wrong" behavior, and that Enter ought to submit the form. However, my client's staff originally come from a green screen environment where Enter moves them between fields. We must retain the same UI. It is what it is.

UPDATE: I found a difference between IE8 & IE9. In IE8, my setting of myEvent.keyCode holds. In IE9, it does NOT. I can update window.event.keyCode, and it will hold, but that won't affect what happens later. Argh... Any ideas?

答:
A <button> element on a page will cause this problem.

In IE9 a <button> element takes the focus when Enter is pressed. Any submit or reset button will cause the problem too. If you are not using submit/reset then you can fix this by changing all buttons to <input type="button"> or by setting the button's type attribute to button. i.e.

```<code><button type="button">Click me!</button>
</code>```

Alternatively as per KooiInc's answer, you can edit your javascript to use event.preventDefault(); to prevent the Enter key acting this way, and explicitly call focus() on the next element in the tab order.

Here is some test code I wrote that demonstrates the problem with the button element (note the blue focus ring on button3 in IE9):

```<code><!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>IE problem with Enter key and <button> elements</title>
</head>

<body>
    <script>
        function press(event) {
            if (event.keyCode == 13) {
                document.getElementById('input2').focus();
                // In IE9 the focus shifts to the <button> unless we call preventDefault(). Uncomment following line for IE9 fix. Alternatively set type="button" on all button elements and anything else that is a submit or reset too!.
                // event.preventDefault && event.preventDefault();
            }
        }
    </script>
    <input id="input1" type="text" onkeypress="press(event)" value="input1. Press enter here." /><br />
    <input id="input2" type="text" value="input2. Press enter here." /><br />
    <input  id="button1" type="button" value='I am an <input type="button">' /><br />
    <button id="button2" type="button">I am a <button type="button"></button><br />
    <button id="button3">I am a <button>. I get focus when enter key pressed in IE9 - wooot!</button><span>As per Microsoft docs on <a target="_tab" href="http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx">BUTTON.type</a> it is because type defaults to submit.</span>
</body>
</html>
</code>```

Body:
I have a text input with an onkeydown event handler that converts <Enter> to <Tab> by changing the event's keyCode from 13 to 9.

<input type="text" onkeydown="enterToTab(event);" onchange="changeEvent(this);"
       name="" value="" />

Javascript:

function enterToTab(myEvent) {
    if (myEvent.keyCode == 13) {
        myEvent.keyCode = 9;
    }
}
function changeEvent(myInput) { var test = "hello"; }

In IE8, this caused the onchange event to fire, but that doesn't happen in IE9. Instead, the input field retains focus. How I can I make that happen? (It works in Firefox 3.6 and Chrome 10.0.) This even works in Browser Mode IE9 if I set the Document Mode to "IE8 standards". But it won't work with a Document Mode of "IE9 standards". (My DocType is XHTML 1.0 Transitional.)

Since it works in IE7 & 8, could this be a bug in IE9 that will get fixed?

Please note: I cannot use input.blur() or manually set a new focus, which is advised by all the other solutions that I've read. I've already tried onkeypress and onkeyup with no luck. I need a generic solution that will cause the web app to literally behave as though I'd hit <Tab>. Also, I don't have jQuery, however, Dojo 1.5 is available to me.

Also note: I KNOW this is "wrong" behavior, and that Enter ought to submit the form. However, my client's staff originally come from a green screen environment where Enter moves them between fields. We must retain the same UI. It is what it is.

UPDATE: I found a difference between IE8 & IE9. In IE8, my setting of myEvent.keyCode holds. In IE9, it does NOT. I can update window.event.keyCode, and it will hold, but that won't affect what happens later. Argh... Any ideas?

Body:
A <button> element on a page will cause this problem.

In IE9 a <button> element takes the focus when Enter is pressed. Any submit or reset button will cause the problem too. If you are not using submit/reset then you can fix this by changing all buttons to <input type="button"> or by setting the button's type attribute to button. i.e.

<button type="button">Click me!</button>

Alternatively as per KooiInc's answer, you can edit your javascript to use event.preventDefault(); to prevent the Enter key acting this way, and explicitly call focus() on the next element in the tab order.

Here is some test code I wrote that demonstrates the problem with the button element (note the blue focus ring on button3 in IE9):

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>IE problem with Enter key and &lt;button&gt; elements</title>
</head>

<body>
    <script>
        function press(event) {
            if (event.keyCode == 13) {
                document.getElementById('input2').focus();
                // In IE9 the focus shifts to the <button> unless we call preventDefault(). Uncomment following line for IE9 fix. Alternatively set type="button" on all button elements and anything else that is a submit or reset too!.
                // event.preventDefault && event.preventDefault();
            }
        }
    </script>
    <input id="input1" type="text" onkeypress="press(event)" value="input1. Press enter here." /><br />
    <input id="input2" type="text" value="input2. Press enter here." /><br />
    <input  id="button1" type="button" value='I am an <input type="button">' /><br />
    <button id="button2" type="button">I am a &lt;button type="button"&gt;</button><br />
    <button id="button3">I am a &lt;button&gt;. I get focus when enter key pressed in IE9 - wooot!</button><span>As per Microsoft docs on <a target="_tab" href="http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx">BUTTON.type</a> it is because type defaults to submit.</span>
</body>
</html>


问:
How to retrieve/fetch items from Firebase Real Time Database
I am New to Programming, Started with Flutter, Following Some Tutorials Making Progress Slowly.

i am adding data on Firebase Real Time Database with the help of this URL:

final url = 'https://MyFirebaseLink.firebaseio.com/orders/$userId.json?auth=$authToken';

All Items are saving under orders>Unique-uid-Stirng>Key>Fields

i am able to retrieve Single item with this URL:

final url = 'https://MyFirebaseLink.firebaseio.com/orders/(e.g uid Sting)XYZABC123AnXYZABC.json?auth=$authToken';

How i can retrieve all records saved under different uids tried these URLs:

Below first two url retrieving only logged in users Fields

final url = 'https://MyFirebaseLink.firebaseio.com/orders.json?auth=$authToken';

final url = 'https://MyFirebaseLink.firebaseio.com/orders/.json?auth=$authToken';

Looking for solution like below URLs:

final url = 'https://MyFirebaseLink.firebaseio.com/orders/*.json?auth=$authToken';

final url = 'https://MyFirebaseLink.firebaseio.com/orders/*/.json?auth=$authToken';

Or is there any alternate way where i can achieve the same (Edited: Only looking for Real Database Solutions).

Would appreciate your answers Thanks.

答:
```<code>final db = FirebaseDatabase.instance.reference().child("orders");
db.orderByKey().once().then((DataSnapshot snapshot){
  var uids = snapshot.value.keys;
  var data = snapshot.value;
    for (var key in uids) {
      var newList = data[key];
      print(newList);
    }
</code>```

Above code solved the Problem that I have asked as an alternate way.

Below is the full code to fetch order as an admin user to change order status:

```<code>Future<void> fetchAndSetAdminOrders() async {
List<OrderItem> orderList = [];
    final db = FirebaseDatabase.instance.reference().child("orders");
db.orderByKey().once().then((DataSnapshot snapshot){
  var uids = snapshot.value.keys;
  var data = snapshot.value;
    for (var key in uids) {
      var newList = data[key];
      print(newList);

  newList.forEach((orderId, orderData) {
    orderList.add(
      OrderItem(
        id: orderId,
        amount: orderData['amount'],
        status: orderData['status'],
        dateTime: DateTime.parse(orderData['dateTime']),
        products: (orderData['products'] as List<dynamic>)
            .map((item) => CartItem(
          id: item['id'],
          price: item['price'],
          quantity: item['quantity'],
          title: item['title'],
        ))
            .toList(),
      ),
    );

  });
    }
  _orders = orderList.reversed.toList();
  notifyListeners();
});}
</code>```

It is Working Well and displaying all orders with their status, except few errors like below.

```<code>E/flutter (10256): A Orders was used after being disposed.
E/flutter (10256): Once you have called dispose() on a Orders, it can no longer be used.
</code>```

Body:
final db = FirebaseDatabase.instance.reference().child("orders");
db.orderByKey().once().then((DataSnapshot snapshot){
  var uids = snapshot.value.keys;
  var data = snapshot.value;
    for (var key in uids) {
      var newList = data[key];
      print(newList);
    }

Above code solved the Problem that I have asked as an alternate way.

Below is the full code to fetch order as an admin user to change order status:

Future<void> fetchAndSetAdminOrders() async {
List<OrderItem> orderList = [];
    final db = FirebaseDatabase.instance.reference().child("orders");
db.orderByKey().once().then((DataSnapshot snapshot){
  var uids = snapshot.value.keys;
  var data = snapshot.value;
    for (var key in uids) {
      var newList = data[key];
      print(newList);

  newList.forEach((orderId, orderData) {
    orderList.add(
      OrderItem(
        id: orderId,
        amount: orderData['amount'],
        status: orderData['status'],
        dateTime: DateTime.parse(orderData['dateTime']),
        products: (orderData['products'] as List<dynamic>)
            .map((item) => CartItem(
          id: item['id'],
          price: item['price'],
          quantity: item['quantity'],
          title: item['title'],
        ))
            .toList(),
      ),
    );

  });
    }
  _orders = orderList.reversed.toList();
  notifyListeners();
});}

It is Working Well and displaying all orders with their status, except few errors like below.

E/flutter (10256): A Orders was used after being disposed.
E/flutter (10256): Once you have called dispose() on a Orders, it can no longer be used.


问:
Setting HttpReferrer In Unit Tests
In my view.py I have the following check on several consecutive pages:

```<code>if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
            return redirect('page1')
</code>```

This is performed on every page, checking that the user was redirected from the previous page, so (for example), if a user tries to enter the url for page4 in the address bar, the test will fail and he will be sent to page3, then that pages test will fail and he will fall back to page2, and so on.

Im doing this because I have several pages linked together which users must visit consecutively.

The problem comes when I want to unit test.  The following test would throw an error because it fails the redirect test and therefore cannot test the logic of the page which im trying to test:

```<code>def test_user_information_updated_on_validation_success(self):
        user = User.objects.create_superuser('username')
        self.client.force_login(user)

        self.client.post(reverse('page_4'), {
            'exampleQuestion': 'exampleAnswer'
        })
        user.refresh_from_db()

        self.assertEqual(user.exampleform.somefield, 'exampleAnswer')
</code>```

How can I access the page within a unit test as if it had been redirected.

Thank you.

答:
A request in the test client accepts keywords that are mapped to WSGI environment variables. Environment variables that start with HTTP and are all uppercase, with dashes mapped to underscores - are Http headers, so the short version is that we can set HTTP headers as such:

# Wrong: Generates absolute paths without hosts
self.client.post(
    reverse('page_4'), {'exampleQuestion': 'exampleAnswer'},
    HTTP_REFERER=reverse('page_3')
)
```

<p>Edit:
It's a little too simple, because HTTP referrers are fully qualified, so we need:</p>

<pre class="lang-py prettyprint-override"><code>
referer = 'http://testserver{}'.format(reverse('page_3'))
self.client.post(
    reverse('page_4'), {'exampleQuestion': 'exampleAnswer'},
    HTTP_REFERER=referer
)
</code>```

FYI: The protocol (wsgi.scheme) and host name (HTTP_SERVER) come from djang.test.client.RequestFactory._base_environ(). If you use a modified client that changes servername and/or protocol, you should adjust accordingly. In that case it would be wise to override _base_environ in your modified test client and derive values from that.

Title: Setting HttpReferrer In Unit Tests

Body:
In my view.py I have the following check on several consecutive pages:

if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
            return redirect('page1')

This is performed on every page, checking that the user was redirected from the previous page, so (for example), if a user tries to enter the url for page4 in the address bar, the test will fail and he will be sent to page3, then that pages test will fail and he will fall back to page2, and so on.

Im doing this because I have several pages linked together which users must visit consecutively.

The problem comes when I want to unit test.  The following test would throw an error because it fails the redirect test and therefore cannot test the logic of the page which im trying to test:

def test_user_information_updated_on_validation_success(self):
        user = User.objects.create_superuser('username')
        self.client.force_login(user)

        self.client.post(reverse('page_4'), {
            'exampleQuestion': 'exampleAnswer'
        })
        user.refresh_from_db()

        self.assertEqual(user.exampleform.somefield, 'exampleAnswer')

How can I access the page within a unit test as if it had been redirected.

Thank you.

Body:
A request in the test client accepts keywords that are mapped to WSGI environment variables. Environment variables that start with HTTP and are all uppercase, with dashes mapped to underscores - are Http headers, so the short version is that we can set HTTP headers as such:

# Wrong: Generates absolute paths without hosts
self.client.post(
    reverse('page_4'), {'exampleQuestion': 'exampleAnswer'},
    HTTP_REFERER=reverse('page_3')
)

Edit:
It's a little too simple, because HTTP referrers are fully qualified, so we need:

referer = 'http://testserver{}'.format(reverse('page_3'))
self.client.post(
    reverse('page_4'), {'exampleQuestion': 'exampleAnswer'},
    HTTP_REFERER=referer
)

FYI: The protocol (wsgi.scheme) and host name (HTTP_SERVER) come from djang.test.client.RequestFactory._base_environ(). If you use a modified client that changes servername and/or protocol, you should adjust accordingly. In that case it would be wise to override _base_environ in your modified test client and derive values from that.


问:
COUNT CASE and WHEN statement in MySQL
How to use COUNT CASE and WHEN statement in MySQL query, to count when data is NULL and when it is not NULL in one MySQL query?</p>

答:
You can exploit the fact that COUNT only counts non-null values:

```<code>SELECT COUNT(IFNULL(t.your_column, 1)) AS numNull,
       COUNT(t.your_column) AS numNotNull
  FROM YOUR_TABLE t
</code>```

Another approach is to use the fact that logical conditions get evaluated to numeric 0 and 1, so this will also work:

```<code>SELECT IFNULL(SUM(t.your_column IS NULL), 0) AS numNull,
       IFNULL(SUM(t.your_column IS NOT NULL), 0) AS numNotNull
  FROM YOUR_TABLE t
</code>```

Please note that SUM will return NULL if there are no rows selected (i.e. the table is empty or a where condition excludes all rows), this is the reason for the IFNULL statements.

Title: COUNT CASE and WHEN statement in MySQL

Body:
You can exploit the fact that COUNT only counts non-null values:

SELECT COUNT(IFNULL(t.your_column, 1)) AS numNull,
       COUNT(t.your_column) AS numNotNull
  FROM YOUR_TABLE t

Another approach is to use the fact that logical conditions get evaluated to numeric 0 and 1, so this will also work:

SELECT IFNULL(SUM(t.your_column IS NULL), 0) AS numNull,
       IFNULL(SUM(t.your_column IS NOT NULL), 0) AS numNotNull
  FROM YOUR_TABLE t

Please note that SUM will return NULL if there are no rows selected (i.e. the table is empty or a where condition excludes all rows), this is the reason for the IFNULL statements.


问:
GenericAPIView should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
```<code>class GenericAPIView(generics.GenericAPIView,mixins.ListModelMixin):
  queryset=Article.objects.all()
  serilizer_class=ArticleSerializer
  def get(self,request):
      return self.list(request)
</code>```

答:
Most straightforward is to override the serializer_class attribute of GenericAPIView:

```<code>class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin):

    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    def get (self,request):
        return self.list(request)
</code>```

Alternatively you can override the get_serializer_class() method of GenericAPIView:

```<code>class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin):

    queryset = Article.objects.all()

    def get_serializer_class(self):
        return ArticleSerializer

    def get (self,request):
        return self.list(request)
</code>```

Second solution will be better if you need to use different serializers depending on the situation that might occur.

Body:
Most straightforward is to override the serializer_class attribute of GenericAPIView:

class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin):

    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    def get (self,request):
        return self.list(request)

Alternatively you can override the get_serializer_class() method of GenericAPIView:

class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin):

    queryset = Article.objects.all()

    def get_serializer_class(self):
        return ArticleSerializer

    def get (self,request):
        return self.list(request)

Second solution will be better if you need to use different serializers depending on the situation that might occur.


问:
C++ Cross Platform MP3 Decoder?
I have searched high and low, and cannot find any decent MP3 decoders =/

I need one that will compile under gcc/linux.

The closest thing i could find was libmad, which has no documentation at all, and the only example I could find was the one on their home page, which is really complicated.

Does anyone know where I can find one?

答: ffmpeg should be able to handle MP3s without difficulty. How easy it is to actually access that functionality though, I cannot say.</p>

Title: C++ Cross Platform MP3 Decoder?


问:
How can I get the weight of an undirected edge in networkx?
```<code>import networkx as nx

G=nx.Graph()

connections = [(0, 1, 4), (0, 7, 8), (1, 7, 11),(1, 2, 8), (2, 8, 2), (7, 8, 7),
               (7, 6, 1), (8, 6, 6), (2, 5, 4), (6, 5, 2), (2, 3, 7), (3, 5, 14),
               (3, 4, 9), (5, 4, 10), ]

G.add_weighted_edges_from(connections)
</code>```

In this code, how can I get the weight between two nodes? (i.e) 5 and 4 ?

Body:
import networkx as nx

G=nx.Graph()

connections = [(0, 1, 4), (0, 7, 8), (1, 7, 11),(1, 2, 8), (2, 8, 2), (7, 8, 7),
               (7, 6, 1), (8, 6, 6), (2, 5, 4), (6, 5, 2), (2, 3, 7), (3, 5, 14),
               (3, 4, 9), (5, 4, 10), ]

G.add_weighted_edges_from(connections)

In this code, how can I get the weight between two nodes? (i.e) 5 and 4 ?

Body:
For one edge:

G.edges[5,4]['weight']
> 4

For all edges of one node:

G.edges(5, data=True)
> EdgeDataView([(5, 2, {'weight': 4}), (5, 6, {'weight': 2}), (5, 3, {'weight': 14}), (5, 4, {'weight': 10})])

For all edges:

for u, v, w in G.edges(data=True):
    print(u, v, w['weight'])

> 0 1 4
> 0 7 8
> 1 7 11
> 1 2 8
> 7 8 7
> 7 6 1
> 2 8 2
> 2 5 4
> 2 3 7
> 8 6 6
> 6 5 2
> 5 3 14
> 5 4 10
> 3 4 9


问:
Evaluate factorial(n) in SQL Server?
How can I evaluate a math expression like k! in SQL Server 2012?

答:
Try it :

CREATE FUNCTION Factorial ( @i int )

RETURNS INT
AS
BEGIN
DECLARE @i  int

    IF @i <= 1
        SET @i = 1
    ELSE
        SET @i = @i * Factorial( @i - 1 )
RETURN (@i)
END
```

Title: Evaluate factorial(n) in SQL Server?


问:
Vuetify 2 skeleton-loader with manipulating "loading" in Vuex store
I am using the Vuetify v-skeleton-loader component wrapping a v-data-table component.

The data-table component is using server-side pagination and sorting.

To accomplish the server-side pagination, documentation suggests to watch the options object of the data-table and make a new API call with the changed options.

In my store module I set state.loading = true before the API request starts and state.loading = false right after the response is committed to the state.

On the data-table component I read that state for the :loading prop.

On its own this works fine.

When I now wrap the data-table with v-skeleton-loader and put the prop :loading="loading" I get an infinite loop of API requests and rendering of the skeleton-loader.

My hunch is that after the request got resolved and state.loading = false is set, the skeleton-loader unmounts and data-table mounts, changing the options which are being watched and a new API request is fired which sets state.loading = true and the skeleton-loader is being mounted again while data-table is unmounted. Which continues infinetely.

If that is correct, how do I resolve that issue?

Minimal example:

<template>

    <v-card>
      <v-skeleton-loader
        :loading="loading"
        transition="scale-transition"
        height="500"
        type="table"
      >
        <v-data-table
          :headers="headers"
          :items="orders"
          :fixed-header="true"
          :server-items-length="totalItems"
          :options.sync="options"
        >
        </v-data-table>
      </v-skeleton-loader>
    </v-card>

</template>

```

<p>And the store module:</p>

<pre class="lang-js prettyprint-override"><code>const namespaced = true;

const state = {
  orders: [],
  loading: false,
};

const getters = {
  loading: (state) => state.loading,
  orders: (state) => state.orders.items,
};
const actions = {
  getOrdersCustom({ commit }, query) {
    commit("GET_ORDERS_REQUEST");

    return orderService.getOrdersCustom(query).then(
      (data) => commit("GET_ORDERS_SUCCESS", data),
      (error) => commit("GET_ORDERS_FAILURE", error)
    );
  },
}
const mutations = {
  GET_ORDERS_REQUEST(state) {
    state.loading = true;
  },
  GET_ORDERS_SUCCESS(state, data) {
    Vue.set(state.orders, "items", data["hydra:member"]);
    state.data = data;
    state.loading = false;
  },
}
</code>```

答:
I think what I would do in this situation is have a separate variable in the local component state to track the initial loading state, and display the skeleton loader based on that.

Once the initial data set is loaded, I would use the data table component's built-in loading indicator for paginating/sorting the data.. it makes less sense to revert to the skeleton view, as you already have something rendered for the user to look at.

Body:
I am using the Vuetify v-skeleton-loader component wrapping a v-data-table component.

The data-table component is using server-side pagination and sorting.

To accomplish the server-side pagination, documentation suggests to watch the options object of the data-table and make a new API call with the changed options.

In my store module I set state.loading = true before the API request starts and state.loading = false right after the response is committed to the state.

On the data-table component I read that state for the :loading prop.

On its own this works fine.

When I now wrap the data-table with v-skeleton-loader and put the prop :loading="loading" I get an infinite loop of API requests and rendering of the skeleton-loader.

My hunch is that after the request got resolved and state.loading = false is set, the skeleton-loader unmounts and data-table mounts, changing the options which are being watched and a new API request is fired which sets state.loading = true and the skeleton-loader is being mounted again while data-table is unmounted. Which continues infinetely.

If that is correct, how do I resolve that issue?

Minimal example:

<template>

    <v-card>
      <v-skeleton-loader
        :loading="loading"
        transition="scale-transition"
        height="500"
        type="table"
      >
        <v-data-table
          :headers="headers"
          :items="orders"
          :fixed-header="true"
          :server-items-length="totalItems"
          :options.sync="options"
        >
        </v-data-table>
      </v-skeleton-loader>
    </v-card>

</template>

And the store module:

const namespaced = true;

const state = {
  orders: [],
  loading: false,
};

const getters = {
  loading: (state) => state.loading,
  orders: (state) => state.orders.items,
};
const actions = {
  getOrdersCustom({ commit }, query) {
    commit("GET_ORDERS_REQUEST");

    return orderService.getOrdersCustom(query).then(
      (data) => commit("GET_ORDERS_SUCCESS", data),
      (error) => commit("GET_ORDERS_FAILURE", error)
    );
  },
}
const mutations = {
  GET_ORDERS_REQUEST(state) {
    state.loading = true;
  },
  GET_ORDERS_SUCCESS(state, data) {
    Vue.set(state.orders, "items", data["hydra:member"]);
    state.data = data;
    state.loading = false;
  },
}


问:
JavaFX- Button Height Doesn't Get Smaller?
```<code>.button
{
    -fx-background-image: url("mapDefault.png");
    -fx-pref-width: 10px;
    -fx-pref-height: 10px;
}
</code>```

My button looks like this, and theoretically, it should fit the image (10x10) exactly. However

It returns that the button is about 30px in height, despite that I changed it. The button is declared like
Button beachButton = new Button();
and does not have any text values in it.

Any possible causes to this increase/min-cap in height?

答:
The offset of the icon(or text) from the buttons border may be the problem. A Button with text in default font type & size cannot get smaller in height than 25px (using setPrefHeight() or setStyle(...)). To make the height the same as other controls the padding could be reduced as in the following example:

```<code>import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class SmallerButtons  extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Label  label1= new Label ("Label1");
        Label  label2= new Label ("Label2");

        CheckBox  checkBox1= new CheckBox ("CheckBox1");
        CheckBox  checkBox2= new CheckBox ("CheckBox2");

        Button  button1= new Button ("Button1");
        Button  button2= new Button ("Button2");
        Button  button3= new Button ("Button3");

        button3.setOnAction(a-> System.out.println(label1.getHeight() + " / " +checkBox1.getHeight() + " / " +button1.getHeight()));

        label1.setStyle("-fx-font-size:10");
        button1.setPadding(new Insets(0,3,0,3)); // <----- this one works. Standard value is 5.0.
        button1.setMaxWidth(200);
        button2.setPrefHeight(17); // no effect
        button3.setStyle("-fx-pref-height:35px"); // or also setPrefHeight(35)

        VBox vb1=new VBox(label1,label2);
        VBox vb2=new VBox(checkBox1,checkBox2);
        VBox vb3=new VBox(button1, button2, button3);
        vb3.setMaxWidth(80);

        vb1.setSpacing(1);
        vb2.setSpacing(1);
        vb3.setSpacing(1);
        HBox hb = new HBox(vb1,vb2,vb3);
        hb.setSpacing(15);
        Scene scene = new Scene(hb);
        stage.setOnCloseRequest((e)->System.exit(0));
        stage.setScene(scene);
        stage.show();
    }
}
</code>```

One catch: With one buttons padding adjusted  all other buttons need the padding explicitly set, too.

Body:
.button
{
    -fx-background-image: url("mapDefault.png");
    -fx-pref-width: 10px;
    -fx-pref-height: 10px;
}

My button looks like this, and theoretically, it should fit the image (10x10) exactly. However

It returns that the button is about 30px in height, despite that I changed it. The button is declared like
Button beachButton = new Button();
and does not have any text values in it.

Any possible causes to this increase/min-cap in height?

Body:
The offset of the icon(or text) from the buttons border may be the problem. A Button with text in default font type & size cannot get smaller in height than 25px (using setPrefHeight() or setStyle(...)). To make the height the same as other controls the padding could be reduced as in the following example:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class SmallerButtons  extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Label  label1= new Label ("Label1");
        Label  label2= new Label ("Label2");

        CheckBox  checkBox1= new CheckBox ("CheckBox1");
        CheckBox  checkBox2= new CheckBox ("CheckBox2");

        Button  button1= new Button ("Button1");
        Button  button2= new Button ("Button2");
        Button  button3= new Button ("Button3");

        button3.setOnAction(a-> System.out.println(label1.getHeight() + " / " +checkBox1.getHeight() + " / " +button1.getHeight()));

        label1.setStyle("-fx-font-size:10");
        button1.setPadding(new Insets(0,3,0,3)); // <----- this one works. Standard value is 5.0.
        button1.setMaxWidth(200);
        button2.setPrefHeight(17); // no effect
        button3.setStyle("-fx-pref-height:35px"); // or also setPrefHeight(35)

        VBox vb1=new VBox(label1,label2);
        VBox vb2=new VBox(checkBox1,checkBox2);
        VBox vb3=new VBox(button1, button2, button3);
        vb3.setMaxWidth(80);

        vb1.setSpacing(1);
        vb2.setSpacing(1);
        vb3.setSpacing(1);
        HBox hb = new HBox(vb1,vb2,vb3);
        hb.setSpacing(15);
        Scene scene = new Scene(hb);
        stage.setOnCloseRequest((e)->System.exit(0));
        stage.setScene(scene);
        stage.show();
    }
}

One catch: With one buttons padding adjusted  all other buttons need the padding explicitly set, too.


问:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 3 recorded
I know that it has been asked multiple times on this platform. I also checked the solution provided that either use all raw parameters or all Matcher arguments. In my case Argument Matcher(any, anyString) has been used for all parameters but still getting the error.

Code:

```<code>Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(Mockito.any(TermReq.class));
Mockito.when(utils.sendPOSTRequest(Mockito.anyString(),Mockito.anyString())).thenReturn(Mockito.anyString());
</code>```

Error on the above line is:

```<code>org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 3 recorded:
</code>```

Can somebody point out what may be the issue.

Thanks,

答:
If you desire mock the return value of a method, you should decide what object will return after the when clause. You can not return a new argument matcher. I advise to return new mocking object in your test scenario like this one:

```<code>TermReq termReq = Mockito.mock(TermReq.class);  // create mock
Mockito.when(termReq.getId()).thenReturn(1L) // mock required get methods
Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(termReq); // then return in case of the service method call
</code>```

With this style of usage you can handle or compare the results with mock objects.

Body:
I know that it has been asked multiple times on this platform. I also checked the solution provided that either use all raw parameters or all Matcher arguments. In my case Argument Matcher(any, anyString) has been used for all parameters but still getting the error.

Code:

Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(Mockito.any(TermReq.class));
Mockito.when(utils.sendPOSTRequest(Mockito.anyString(),Mockito.anyString())).thenReturn(Mockito.anyString());

Error on the above line is:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 3 recorded:

Can somebody point out what may be the issue.

Thanks,

Body:
If you desire mock the return value of a method, you should decide what object will return after the when clause. You can not return a new argument matcher. I advise to return new mocking object in your test scenario like this one:

TermReq termReq = Mockito.mock(TermReq.class);  // create mock
Mockito.when(termReq.getId()).thenReturn(1L) // mock required get methods
Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(termReq); // then return in case of the service method call

With this style of usage you can handle or compare the results with mock objects.