问:
Flutter PaginatedDataTable rowsPerPage
Can flutter PaginatedDataTable rowsPerPage be set to a number not divisible by 10?

UPDATE

Data used by the FutureBuilder is fetched from a local server. At first, the list contains 3 items which results into empty DataRows being created.

My Problem

I don't want the empty DataRows to be created

What I've Tried

Setting the rowsPerPage count to the length of the list IF the list-length is less than the defaultRowsPerPage ELSE set it (rowsPerPage) to defaultRowsPerPage.

SAMPLE CODE

```<code>import 'package:flutter/material.dart';
import 'package:nvip/constants.dart';
import 'package:nvip/data_repo/network/centers_repo.dart';
import 'package:nvip/data_repo/tables/data_source_centers.dart';
import 'package:nvip/models/vaccination_center.dart';

class VaccinationCentersTableScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) => _CentersScreenBody();
}

class _CentersScreenBody extends StatefulWidget {
  @override
  __CentersScreenBodyState createState() => __CentersScreenBodyState();
}

class __CentersScreenBodyState extends State<_CentersScreenBody> {
  int _rowsPerPage = PaginatedDataTable.defaultRowsPerPage; // This one works
  int _columnIndex = 1;
  bool _isSortAscending = true;
  Future<List<VaccineCenter>> _centers;
  CentersTableDataSource _tableDataSource;
  var _scaffoldKey = GlobalKey<ScaffoldState>();

  void _sort<T>(Comparable<T> getField(VaccineCenter c), int columnIndex,
      bool isSortAscending) {
    _tableDataSource?.sort(getField, isSortAscending);
    setState(() {
      _columnIndex = columnIndex;
      _isSortAscending = isSortAscending;
    });
  }

  @override
  void initState() {
    super.initState();
    _centers = VaccineCentersDataRepo().getCenters();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        Navigator.pushReplacementNamed(context, Routes.keyHome);
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text("Vaccination Centers"),
          centerTitle: true,
          leading: IconButton(
            icon: Icon(Constants.backIcon),
            onPressed: () {
              Navigator.pushReplacementNamed(context, Routes.keyHome);
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              tooltip: "Add vaccination center",
              onPressed: () {
                Navigator.pushReplacementNamed(context, Routes.keyPovAdd);
              },
            )
          ],
        ),
        body: FutureBuilder<List<VaccineCenter>>(
          future: _centers,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Constants.showHasNoDataWidget(
                context,
                "No vaccination center(s) / place(s) of vaccinations found. "
                    "Press the (+) sign to add a new record.",
              );
            } else {
              if (snapshot.hasData) {
                var centerList = snapshot.data;
                var centersCount = centerList.length;
                var defaultRowsPerPage = PaginatedDataTable.defaultRowsPerPage;
                _rowsPerPage = centersCount < defaultRowsPerPage
                    ? centersCount
                    : defaultRowsPerPage;
                _tableDataSource = CentersTableDataSource(centerList);
                return SingleChildScrollView(
                  child: PaginatedDataTable(
                    header: Text("Places of Vaccination"),
                    rowsPerPage: _rowsPerPage,
                    onRowsPerPageChanged: (rowCount) {
                      setState(() {
                        _rowsPerPage = rowCount;
                      });
                    },
                    sortColumnIndex: _columnIndex,
                    sortAscending: _isSortAscending,
                    onSelectAll: (isAllChecked) =>
                        _tableDataSource?.selectAll(isAllChecked),
                    actions: <Widget>[
                      IconButton(
                        icon: Icon(Icons.add),
                        tooltip: "Add vaccination center",
                        onPressed: () {
                          Navigator.pushReplacementNamed(
                              context, Routes.keyPovAdd);
                        },
                      ),
                      IconButton(
                        icon: Icon(Icons.delete_forever),
                        tooltip: "Delete vaccination center(s).",
                        onPressed: () {
                          Constants.showSnackBar(
                              _scaffoldKey, "Delete button clicked");
                        },
                      )
                    ],
                    columns: <DataColumn>[
                      DataColumn(
                        label: Text("No."),
                        numeric: true,
                        onSort: (ci, isSortAscending) => _sort<num>(
                            (c) => centerList.indexOf(c), ci, isSortAscending),
                      ),
                      DataColumn(
                        label: Text("Name"),
                        onSort: (ci, isSortAscending) =>
                            _sort<String>((c) => c.name, ci, isSortAscending),
                      ),
                    ],
                    source: _tableDataSource,
                  ),
                );
              }
            }

            return Center(child: CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}
</code>```

ERROR LOG

```<code>I/flutter ( 8474): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 8474): The following assertion was thrown building FutureBuilder<List<VaccineCenter>>(dirty, state:
I/flutter ( 8474): _FutureBuilderState<List<VaccineCenter>>#92379):
I/flutter ( 8474): 'package:flutter/src/material/paginated_data_table.dart': Failed assertion: line 87 pos 19:
I/flutter ( 8474): 'availableRowsPerPage != null && availableRowsPerPage.contains(rowsPerPage)': is not true.
I/flutter ( 8474):
I/flutter ( 8474): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 8474): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 8474): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 8474):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 8474):
I/flutter ( 8474): When the exception was thrown, this was the stack:
I/flutter ( 8474): #2      new PaginatedDataTable.<anonymous closure> (package:flutter/src/material/paginated_data_table.dart:87:19)
I/flutter ( 8474): #3      new PaginatedDataTable (package:flutter/src/material/paginated_data_table.dart:89:9)
I/flutter ( 8474): #4      __CentersScreenBodyState.build.<anonymous closure> (package:nvip/scenes/vaccination_centers/screen_center_table.dart:86:26)
I/flutter ( 8474): #5      _FutureBuilderState.build (package:flutter/src/widgets/async.dart)
I/flutter ( 8474): #6      StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 8474): #7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 8474): #8      Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8474): #9      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 8474): #10     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 8474): #11     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 8474): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 8474): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 8474): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 8474): #15     _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 8474): #16     _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 8474): (elided 2 frames from class _AssertionError)
I/flutter ( 8474): ════════════════════════════════════════════════════════════════════════════════════════════════════
</code>```

UPDATE 2

My DataTableSource

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

class CentersTableDataSource extends DataTableSource {
  final List<VaccineCenter> _centers;
  int _rowsSelectedCount = 0;

  CentersTableDataSource(this._centers);

  @override
  DataRow getRow(int index) {
    assert(index >= 0);
    if (index >= _centers.length) return null;
    final VaccineCenter center = _centers[index];
    return DataRow.byIndex(
      index: index,
      selected: center.isSelected,
      onSelectChanged: (selected) {
        if (center.isSelected != selected) {
          _rowsSelectedCount += selected ? 1 : -1;
          center.isSelected = selected;
          notifyListeners();
        }
      },
      cells: <DataCell>[
        DataCell(Text("${index + 1}")),
        DataCell(Text(center.name)),
      ],
    );
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => _centers.length;

  @override
  int get selectedRowCount => _rowsSelectedCount;

  void sort<T extends Object>(
      Comparable<T> getField(VaccineCenter d), bool isAscending) {
    _centers.sort((a, b) {
      if (isAscending) {
        final VaccineCenter c = a;
        a = b;
        b = c;
      }

      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    notifyListeners();
  }

  void selectAll(bool isAllChecked) {
    _centers.forEach((center) => center.isSelected = isAllChecked);
    _rowsSelectedCount = isAllChecked ? _centers.length : 0;
    notifyListeners();
  }
}
</code>```

答:
Let's say you have some method that fetches data from a remote server or locally and return a list of objects like this :

```<code>List<Map<String, String>> fetchedDataObj = [
  {
    "name": "Rami",
    "email": "dummyemail01@gmail.com"
  },
  {
    "name": "Kara",
    "email": "dummyemail02@gmail.com"
  },
  {
    "name": "Lina",
    "email": "dummyemail03@almakana.com"
  }
];
</code>```

in PaginatedDataTable widget set :

```<code>rowsPerPage: fetchedDataObj.length,
</code>```

and

```<code>onRowsPerPageChanged: (fetchedDataObj.length < PaginatedDataTable.defaultRowsPerPage) ? null : (r) {
          // setState(() {
          //   _rowsPerPage = r;
          // });
        },
      ),
</code>```

Hope this helps. Thanks

Title: Flutter PaginatedDataTable rowsPerPage

Body:
Can flutter PaginatedDataTable rowsPerPage be set to a number not divisible by 10?

UPDATE

Data used by the FutureBuilder is fetched from a local server. At first, the list contains 3 items which results into empty DataRows being created.

My Problem

I don't want the empty DataRows to be created

What I've Tried

Setting the rowsPerPage count to the length of the list IF the list-length is less than the defaultRowsPerPage ELSE set it (rowsPerPage) to defaultRowsPerPage.

SAMPLE CODE

import 'package:flutter/material.dart';
import 'package:nvip/constants.dart';
import 'package:nvip/data_repo/network/centers_repo.dart';
import 'package:nvip/data_repo/tables/data_source_centers.dart';
import 'package:nvip/models/vaccination_center.dart';

class VaccinationCentersTableScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) => _CentersScreenBody();
}

class _CentersScreenBody extends StatefulWidget {
  @override
  __CentersScreenBodyState createState() => __CentersScreenBodyState();
}

class __CentersScreenBodyState extends State<_CentersScreenBody> {
  int _rowsPerPage = PaginatedDataTable.defaultRowsPerPage; // This one works
  int _columnIndex = 1;
  bool _isSortAscending = true;
  Future<List<VaccineCenter>> _centers;
  CentersTableDataSource _tableDataSource;
  var _scaffoldKey = GlobalKey<ScaffoldState>();

  void _sort<T>(Comparable<T> getField(VaccineCenter c), int columnIndex,
      bool isSortAscending) {
    _tableDataSource?.sort(getField, isSortAscending);
    setState(() {
      _columnIndex = columnIndex;
      _isSortAscending = isSortAscending;
    });
  }

  @override
  void initState() {
    super.initState();
    _centers = VaccineCentersDataRepo().getCenters();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        Navigator.pushReplacementNamed(context, Routes.keyHome);
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text("Vaccination Centers"),
          centerTitle: true,
          leading: IconButton(
            icon: Icon(Constants.backIcon),
            onPressed: () {
              Navigator.pushReplacementNamed(context, Routes.keyHome);
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              tooltip: "Add vaccination center",
              onPressed: () {
                Navigator.pushReplacementNamed(context, Routes.keyPovAdd);
              },
            )
          ],
        ),
        body: FutureBuilder<List<VaccineCenter>>(
          future: _centers,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Constants.showHasNoDataWidget(
                context,
                "No vaccination center(s) / place(s) of vaccinations found. "
                    "Press the (+) sign to add a new record.",
              );
            } else {
              if (snapshot.hasData) {
                var centerList = snapshot.data;
                var centersCount = centerList.length;
                var defaultRowsPerPage = PaginatedDataTable.defaultRowsPerPage;
                _rowsPerPage = centersCount < defaultRowsPerPage
                    ? centersCount
                    : defaultRowsPerPage;
                _tableDataSource = CentersTableDataSource(centerList);
                return SingleChildScrollView(
                  child: PaginatedDataTable(
                    header: Text("Places of Vaccination"),
                    rowsPerPage: _rowsPerPage,
                    onRowsPerPageChanged: (rowCount) {
                      setState(() {
                        _rowsPerPage = rowCount;
                      });
                    },
                    sortColumnIndex: _columnIndex,
                    sortAscending: _isSortAscending,
                    onSelectAll: (isAllChecked) =>
                        _tableDataSource?.selectAll(isAllChecked),
                    actions: <Widget>[
                      IconButton(
                        icon: Icon(Icons.add),
                        tooltip: "Add vaccination center",
                        onPressed: () {
                          Navigator.pushReplacementNamed(
                              context, Routes.keyPovAdd);
                        },
                      ),
                      IconButton(
                        icon: Icon(Icons.delete_forever),
                        tooltip: "Delete vaccination center(s).",
                        onPressed: () {
                          Constants.showSnackBar(
                              _scaffoldKey, "Delete button clicked");
                        },
                      )
                    ],
                    columns: <DataColumn>[
                      DataColumn(
                        label: Text("No."),
                        numeric: true,
                        onSort: (ci, isSortAscending) => _sort<num>(
                            (c) => centerList.indexOf(c), ci, isSortAscending),
                      ),
                      DataColumn(
                        label: Text("Name"),
                        onSort: (ci, isSortAscending) =>
                            _sort<String>((c) => c.name, ci, isSortAscending),
                      ),
                    ],
                    source: _tableDataSource,
                  ),
                );
              }
            }

            return Center(child: CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}

ERROR LOG

I/flutter ( 8474): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 8474): The following assertion was thrown building FutureBuilder<List<VaccineCenter>>(dirty, state:
I/flutter ( 8474): _FutureBuilderState<List<VaccineCenter>>#92379):
I/flutter ( 8474): 'package:flutter/src/material/paginated_data_table.dart': Failed assertion: line 87 pos 19:
I/flutter ( 8474): 'availableRowsPerPage != null && availableRowsPerPage.contains(rowsPerPage)': is not true.
I/flutter ( 8474):
I/flutter ( 8474): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 8474): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 8474): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 8474):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 8474):
I/flutter ( 8474): When the exception was thrown, this was the stack:
I/flutter ( 8474): #2      new PaginatedDataTable.<anonymous closure> (package:flutter/src/material/paginated_data_table.dart:87:19)
I/flutter ( 8474): #3      new PaginatedDataTable (package:flutter/src/material/paginated_data_table.dart:89:9)
I/flutter ( 8474): #4      __CentersScreenBodyState.build.<anonymous closure> (package:nvip/scenes/vaccination_centers/screen_center_table.dart:86:26)
I/flutter ( 8474): #5      _FutureBuilderState.build (package:flutter/src/widgets/async.dart)
I/flutter ( 8474): #6      StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 8474): #7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 8474): #8      Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8474): #9      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 8474): #10     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 8474): #11     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 8474): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 8474): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 8474): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 8474): #15     _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 8474): #16     _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 8474): (elided 2 frames from class _AssertionError)
I/flutter ( 8474): ════════════════════════════════════════════════════════════════════════════════════════════════════

UPDATE 2

My DataTableSource

import 'package:flutter/material.dart';
import 'package:nvip/models/vaccination_center.dart';

class CentersTableDataSource extends DataTableSource {
  final List<VaccineCenter> _centers;
  int _rowsSelectedCount = 0;

  CentersTableDataSource(this._centers);

  @override
  DataRow getRow(int index) {
    assert(index >= 0);
    if (index >= _centers.length) return null;
    final VaccineCenter center = _centers[index];
    return DataRow.byIndex(
      index: index,
      selected: center.isSelected,
      onSelectChanged: (selected) {
        if (center.isSelected != selected) {
          _rowsSelectedCount += selected ? 1 : -1;
          center.isSelected = selected;
          notifyListeners();
        }
      },
      cells: <DataCell>[
        DataCell(Text("${index + 1}")),
        DataCell(Text(center.name)),
      ],
    );
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => _centers.length;

  @override
  int get selectedRowCount => _rowsSelectedCount;

  void sort<T extends Object>(
      Comparable<T> getField(VaccineCenter d), bool isAscending) {
    _centers.sort((a, b) {
      if (isAscending) {
        final VaccineCenter c = a;
        a = b;
        b = c;
      }

      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    notifyListeners();
  }

  void selectAll(bool isAllChecked) {
    _centers.forEach((center) => center.isSelected = isAllChecked);
    _rowsSelectedCount = isAllChecked ? _centers.length : 0;
    notifyListeners();
  }
}

Body:
Let's say you have some method that fetches data from a remote server or locally and return a list of objects like this :

List<Map<String, String>> fetchedDataObj = [
  {
    "name": "Rami",
    "email": "dummyemail01@gmail.com"
  },
  {
    "name": "Kara",
    "email": "dummyemail02@gmail.com"
  },
  {
    "name": "Lina",
    "email": "dummyemail03@almakana.com"
  }
];

in PaginatedDataTable widget set :

rowsPerPage: fetchedDataObj.length,

and

onRowsPerPageChanged: (fetchedDataObj.length < PaginatedDataTable.defaultRowsPerPage) ? null : (r) {
          // setState(() {
          //   _rowsPerPage = r;
          // });
        },
      ),

Hope this helps. Thanks


来源: stackexchange

问:
How do I set a boolean inside a for loop to true if a value is reached?
I want to set the boolean additionalLogging value to true inside a for loop if 2 has been reached. How can I set it to a "global" or "public" value outside of the brackets?

I just want it to be true for the next value 8.

Any ideas?

```<code>public class userAnalytic {

    public static void main(String[] args) {
        boolean additionalLogging = false;
        System.out.println(additionalLogging);
        for (int i = 0; i <= 10; i++) {
            System.out.println(i);
            if (i == 5) {
                if (additionalLogging == true) {
                    System.out.println("We found 5");
                    if (i == 2) {
                        additionalLogging = true;
                        if (i == 8) {
                            if (additionalLogging = true) {
                                System.out.println("8 has been found");
                            }

                        }
                    }

                }

            }

        }

    }
}
</code>```

Solved. Solution:

```<code>public class userAnalytic {

    public static void main(String[] args) {
        boolean additionalLogging = false;
        System.out.println(additionalLogging);
        for (int i = 0; i <= 10; i++) {
            System.out.println(i);
            if (i == 5) {
                if (additionalLogging == true) {
                    System.out.println("We found 5");
                }
            }
            if (i == 7) {
                additionalLogging = true;
                System.out.println("okay");
            }

            if (i == 8) {
                if (additionalLogging = true) {
                    System.out.println("8 has been found");
                }

            }
        }

    }

}
</code>```

答:
Your first if is (i == 5) and everything is inside this statement.
Probably, you want to do this:</p>
```<code>public class userAnalytic {

    public static void main(String[] args) {
       boolean additionalLogging = false;
       System.out.println(additionalLogging);
       for (int i = 0; i <= 10; i++) {
           System.out.println(i);
           if (i == 5) {
               if (additionalLogging == true) {
                   System.out.println("We found 5");
               }
           }
           if (i == 2) {
               additionalLogging = true;
           }
           if (i == 8) {
               if (additionalLogging = true) {
                   System.out.println("8 has been found");
               }
           }
       }
   }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to set the boolean additionalLogging value to true inside a for loop if 2 has been reached. How can I set it to a "global" or "public" value outside of the brackets?

I just want it to be true for the next value 8.

Any ideas?

public class userAnalytic {

    public static void main(String[] args) {
        boolean additionalLogging = false;
        System.out.println(additionalLogging);
        for (int i = 0; i <= 10; i++) {
            System.out.println(i);
            if (i == 5) {
                if (additionalLogging == true) {
                    System.out.println("We found 5");
                    if (i == 2) {
                        additionalLogging = true;
                        if (i == 8) {
                            if (additionalLogging = true) {
                                System.out.println("8 has been found");
                            }

                        }
                    }

                }

            }

        }

    }
}

Solved. Solution:

public class userAnalytic {

    public static void main(String[] args) {
        boolean additionalLogging = false;
        System.out.println(additionalLogging);
        for (int i = 0; i <= 10; i++) {
            System.out.println(i);
            if (i == 5) {
                if (additionalLogging == true) {
                    System.out.println("We found 5");
                }
            }
            if (i == 7) {
                additionalLogging = true;
                System.out.println("okay");
            }

            if (i == 8) {
                if (additionalLogging = true) {
                    System.out.println("8 has been found");
                }

            }
        }

    }

}

Body:
Your first if is (i == 5) and everything is inside this statement.
Probably, you want to do this:

public class userAnalytic {

    public static void main(String[] args) {
       boolean additionalLogging = false;
       System.out.println(additionalLogging);
       for (int i = 0; i <= 10; i++) {
           System.out.println(i);
           if (i == 5) {
               if (additionalLogging == true) {
                   System.out.println("We found 5");
               }
           }
           if (i == 2) {
               additionalLogging = true;
           }
           if (i == 8) {
               if (additionalLogging = true) {
                   System.out.println("8 has been found");
               }
           }
       }
   }


问:
Fix url in laravel
so I have done a AJAX call in Laravel project and in a method I want to return a output.

This is the output

```<code>$output = ' <div class="col-xs-12 col-width">
                                <div class="single-product mb-30">
                                    <div class="single-product-item clearfix">
                                        <div class="single-product-img clearfix">
                                            <a href=\"{{route(\'product_details\',' . $product->slug . ')}}\">
                                                <img class="primary-image" src="'.env('PRODUCT_URL'). $product->image . '" style="width: 200px;height: 240px" alt="">
                                            </a>
                                        </div>

                                        <div class="single-product-info clearfix">
                                            <h3><a href="{{route(\'product_details\','.$product->slug.')}}">' . $product->name . '</a></h3>
                                            <div class="pro-price">
                                          ' . $new . '
                                         </div>
                                        </div>
                                    </div>
                                    <div class="new-sale">
                                    ' . $offer . '
                                    </div>
                                </div>
                            </div>';
</code>```

When i click the product I see the route:

/"%7B%7Burl('product_details',test)%7D%7D/"

What should I do to fix the quotes ?

答:
you cannot use blade outside the blade templates, use standard php. so

```<code>'<a href=\"'.route('product_details',$product->slug).'\">'
</code>```

instead of

```<code>'<a href=\"{{route(\'product_details\',' . $product->slug . ')}}\">'
</code>```

Title: Fix url in laravel

Body:
so I have done a AJAX call in Laravel project and in a method I want to return a output.

This is the output

$output = '

                                            slug . ')}}\">
                                                image . '" style="width: 200px;height: 240px" alt="">

slug.')}}">' . $product->name . '

                                          ' . $new . '

                                    ' . $offer . '

';

When i click the product I see the route:

/"%7B%7Burl('product_details',test)%7D%7D/"

What should I do to fix the quotes ?

Body:
you cannot use blade outside the blade templates, use standard php. so

'<a href=\"'.route('product_details',$product->slug).'\">'

instead of

'<a href=\"{{route(\'product_details\',' . $product->slug . ')}}\">'


问:
PowerShell script to return versions of .NET Framework on a machine?
What would a PowerShell script be to return versions of the .NET Framework on a machine?

My first guess is something involving WMI. Is there something better?

It should be a one-liner to return only the latest version for each installation of .NET [on each line].

答:
This is a derivite of previous post, but this gets the latest version of the .net framework 4 in my tests.

```<code>get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL"
</code>```

Which will allow you to invoke-command to remote machine:

```<code>invoke-command -computername server01 -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release}
</code>```

Which sets up this possibility with ADModule and naming convention prefix:

```<code>get-adcomputer -Filter 'name -like "*prefix*"' | % {invoke-command -computername $_.name -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release}} | ft
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is a derivite of previous post, but this gets the latest version of the .net framework 4 in my tests.

get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL"

Which will allow you to invoke-command to remote machine:

invoke-command -computername server01 -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release}

Which sets up this possibility with ADModule and naming convention prefix:

get-adcomputer -Filter 'name -like "*prefix*"' | % {invoke-command -computername $_.name -scriptblock {get-itemproperty -name version,release "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\FULL" | select pscomputername,version,release}} | ft


问:
MaxLength for bootstrap-vue input number Vue.js
I try to implement a maxLength for an input from bootstrap-vue, but from what I read from their documentation they don't support max. If I remove type="number", it works , but is not a number anymore.

```<code>    <b-form-input
        size="sm"
        v-model="register_volume_first"
        type="number"
        maxlength=4
        placeholder="1902"
    ></b-form-input>
</code>```

答:
Try to use formatter prop as follows:

```<code><template>
  <div>
    <b-form-input size="sm" v-model="volume" type="number" :formatter="formatYear" placeholder="1902"></b-form-input>
       <div class="mt-2">Value: {{ volume }}</div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
       volume: '4'
      }
    },
methods:{
  formatYear(e){
     return String(e).substring(0,4);
  }
}
  }
</script>
</code>```

Body:
Try to use formatter prop as follows:

<template>
  <div>
    <b-form-input size="sm" v-model="volume" type="number" :formatter="formatYear" placeholder="1902"></b-form-input>
       <div class="mt-2">Value: {{ volume }}</div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
       volume: '4'
      }
    },
methods:{
  formatYear(e){
     return String(e).substring(0,4);
  }
}
  }
</script>


问:
Add vendor prefixes for inline css in React for background Linear Gradient
I want to use inline styles with a computed variable in my React Code - for background css property and the value is

```<code>const bkgStyle = {
  background: `linear-gradient(97.84deg, rgba(255, 255, 255, 0.2) 0%, rgba(0, 0, 0, 0.2) 100%), ${primaryColor}`,
  height: '165px',
};
</code>```

How can I add vendor prefix for this - nothing works. If i add multiple keys 'background' in bkgStyle then also it doesnt work. and the value for background - is also not accepting a string containing values for all vendors.

Help!!!

答:
You can add vendor prefixes by adding them to the value of the main key. EG:

const bkgStyle = {
    display: '-webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex'
}
```

Body:
I want to use inline styles with a computed variable in my React Code - for background css property and the value is

const bkgStyle = {
  background: `linear-gradient(97.84deg, rgba(255, 255, 255, 0.2) 0%, rgba(0, 0, 0, 0.2) 100%), ${primaryColor}`,
  height: '165px',
};

How can I add vendor prefix for this - nothing works. If i add multiple keys 'background' in bkgStyle then also it doesnt work. and the value for background - is also not accepting a string containing values for all vendors.

Help!!!


问:
How to select column content based on max value within groups of another column. Select marker name based of maximun value for each gene
I have the following df:

```<code>Gene pval  Marker
A      0.12     M1
A      0.11     M2
B      0.33     M3
B      0.55     M4
B      0.06     M5
D      0.03     M7
D      0.04     M8
</code>```

I want to get the marker name based on the maximum pvalue for each gene.
What I have tried:

```<code>peak_marker <-df[which.max(df[,2]),3]
</code>```

But the result is the marker name with the highest pvalue in the entire data frame not the marker name with the highest pval for each gene.

I also tried this with no success:

```<code>aggregate(df$pval, by = list(df$Gene), which.max)
</code>```

答:
Actually you are very close to make it with aggregate, but you perhaps need some additional help from merge.

Here is a base R solution, where aggregate + merge were used, i.e.,

```<code>dfout <- merge(aggregate(pval~Gene,df,max),df,all.x = T)
</code>```

such that

```<code>> dfout
  Gene pval Marker
1    A 0.12     M1
2    B 0.55     M4
3    D 0.04     M8
</code>```

DATA

```<code>df <- structure(list(Gene = c("A", "A", "B", "B", "B", "D", "D"), pval = c(0.12,
0.11, 0.33, 0.55, 0.06, 0.03, 0.04), Marker = c("M1", "M2", "M3",
"M4", "M5", "M7", "M8")), class = "data.frame", row.names = c(NA,
-7L))
</code>```

Body:
I have the following df:

Gene pval  Marker
A      0.12     M1
A      0.11     M2
B      0.33     M3
B      0.55     M4
B      0.06     M5
D      0.03     M7
D      0.04     M8

I want to get the marker name based on the maximum pvalue for each gene.
What I have tried:

peak_marker <-df[which.max(df[,2]),3]

But the result is the marker name with the highest pvalue in the entire data frame not the marker name with the highest pval for each gene.

I also tried this with no success:

aggregate(df$pval, by = list(df$Gene), which.max)

Body:
Actually you are very close to make it with aggregate, but you perhaps need some additional help from merge.

Here is a base R solution, where aggregate + merge were used, i.e.,

dfout <- merge(aggregate(pval~Gene,df,max),df,all.x = T)

such that

> dfout
  Gene pval Marker
1    A 0.12     M1
2    B 0.55     M4
3    D 0.04     M8

DATA

df <- structure(list(Gene = c("A", "A", "B", "B", "B", "D", "D"), pval = c(0.12,
0.11, 0.33, 0.55, 0.06, 0.03, 0.04), Marker = c("M1", "M2", "M3",
"M4", "M5", "M7", "M8")), class = "data.frame", row.names = c(NA,
-7L))


问:
AttributeError: 'Response' object has no attribute 'type'
Can anyone please help me out with this error. I am trying to save an image from query string imagle url. but got stuck with the following error.
My code below, please ignore unnecessary libraries

```<code>from flask_restful import Resource, Api
import requests
import uuid
from PIL import Image
import urllib.request as urllib
import io

app = Flask(__name__)
api = Api(app)

abc = uuid.uuid4().hex[:6].upper()

class Predict(Resource):
    def get(self):
        url = request.args['url']
        r = requests.get(url)
        fd = urllib.urlopen(r)
        image_file = io.BytesIO(fd.read())
        im = Image.open(image_file)
        return im.save(abc+".png")

api.add_resource(Predict, '/')

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

Output Error :

答: r = requests.get(url) returns a response object and you can read it's content by calling r.content, no need to try to open the response object with urlopen to then read it

Body:
Can anyone please help me out with this error. I am trying to save an image from query string imagle url. but got stuck with the following error.
My code below, please ignore unnecessary libraries

from flask_restful import Resource, Api
import requests
import uuid
from PIL import Image
import urllib.request as urllib
import io

app = Flask(__name__)
api = Api(app)

abc = uuid.uuid4().hex[:6].upper()

class Predict(Resource):
    def get(self):
        url = request.args['url']
        r = requests.get(url)
        fd = urllib.urlopen(r)
        image_file = io.BytesIO(fd.read())
        im = Image.open(image_file)
        return im.save(abc+".png")

api.add_resource(Predict, '/')

if __name__ == "__main__":
    app.run("", port=7999, debug=True)

Output Error :


问:
Ajax is not defined - Grails jQuery plugin
I'm using jQuery in my project by the jQuery and jQuery-ui plugins. I have a simple form which I want to submit in Ajax call to the controller. The thing is, when I put the <g:submitToRemote /> tag and then click it, firebug shows error that Ajax is not defined. What can I do to make it work?

答: you can also add <g:setProvider library="jquery"/> on the view needed


问:
Mongo Go Driver is getting interface conversion error when SetSort used
I would like to change order my documents in Mongo DB using Go. I have valid json string code and i can marshal it successfully in to map[string]int. The sample of this type just like:
[{year 1}, {lastupdated -1}]. The value presents order year field ascending and lastupdated field descending. This struct is aspect of MongoDB understands. Also I'm pass this data into bson.D type. Here is my code:

if queries["order"] != nil {
        var unmarshalledOrder map[string]int
        json.Unmarshal(queries["order"].([]byte), &unmarshalledOrder)

        docRes := make(bson.D, 0)
        for field, sort := range unmarshalledOrder {
            docRes = append(docRes, bson.DocElem{field, sort})
        }

        log.Println(docRes)
    }
```

When I print docRes, everthing goes well. But i pass the data to options.Sort function, the function throws interface conversion: interface {} is runtime.errorString, not string panic. Is it a bug on mongo go driver or am i wrong?

答: Can you post the code you've written which uses the driver? Based on the use of bson.DocElem, I think you're using mgo, but mgo's Query.Sort method takes strings, not documents (https://pkg.go.dev/github.com/globalsign/mgo?tab=doc#Query.Sort).

Body:
I would like to change order my documents in Mongo DB using Go. I have valid json string code and i can marshal it successfully in to map[string]int. The sample of this type just like:
[{year 1}, {lastupdated -1}]. The value presents order year field ascending and lastupdated field descending. This struct is aspect of MongoDB understands. Also I'm pass this data into bson.D type. Here is my code:

if queries["order"] != nil {
        var unmarshalledOrder map[string]int
        json.Unmarshal(queries["order"].([]byte), &unmarshalledOrder)

        docRes := make(bson.D, 0)
        for field, sort := range unmarshalledOrder {
            docRes = append(docRes, bson.DocElem{field, sort})
        }

        log.Println(docRes)
    }

When I print docRes, everthing goes well. But i pass the data to options.Sort function, the function throws interface conversion: interface {} is runtime.errorString, not string panic. Is it a bug on mongo go driver or am i wrong?


问:
Insert multiple images randomly into different table cells using Javascript
I'm pretty new in Javascript/Jquery, currently still learning and so here I am seeking help. I would like to insert different images randomly (the location changes everytime i refresh the page) into table cells using Javascript/Jquery and not touching HTML/CSS.

I have tried using append to insert the images, however every image appears in all table cells which weren't what I wanted. I have also tried backgroundrepeat: no repeat but it doesn't work. It would be good if there's some simple coding that would work, so it will be easier for me to understand.

I can't use getElementById cause my separated js file can't detect the ID from the HTML file

HTML:

```<code><table id="Image">
<tr>
<td><div class="ImageHere" value=1></div></td>
<td><div class="ImageHere" value=2></div></td>
<td><div class="ImageHere" value=3></div></td>
<td><div class="ImageHere" value=4></div></td>
<td><div class="ImageHere" value=5></div></td>
</tr>
<tr>
<td><div class="ImageHere" value=6></div></td>
<td><div class="ImageHere" value=7></div></td>
<td><div class="ImageHere" value=8></div></td>
<td><div class="ImageHere" value=9></div></td>
<td><div class="ImageHere" value=10></div></td>
</tr>
</table>
</code>```

my jQuery best try:

```<code>$(document).ready(function(){
    $(".ImageHere").append("<img src='images/card.jpg' width='100%' height='100%' />" ) });
});
</code>```

答:
Your HTML is invalid. HTMLDivElement does not have a valueattribute. Use data-value instead.

Here's an example. For the sake of simplicity, this inserts
 instead of images. Adjust at your own pleasure.

const imageDivs = document.querySelectorAll('#Image .ImageHere');

document.getElementById('foo').addEventListener('click', insertRandomHr)

function insertRandomHr() {
  imageDivs[Math.floor(Math.random()*imageDivs.length)].innerHTML += '
';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#Image { width: 100%; }

.ImageHere::before { content: attr(data-value); }</code>```

<button id="foo" type="button">Insert
 into random div</button>```

Hint: If the sole reason to have those invalid value attributes in the first place was to use that for randomly assigning the image to a div, you don't need that.

Body:
I'm pretty new in Javascript/Jquery, currently still learning and so here I am seeking help. I would like to insert different images randomly (the location changes everytime i refresh the page) into table cells using Javascript/Jquery and not touching HTML/CSS.

I have tried using append to insert the images, however every image appears in all table cells which weren't what I wanted. I have also tried backgroundrepeat: no repeat but it doesn't work. It would be good if there's some simple coding that would work, so it will be easier for me to understand.

I can't use getElementById cause my separated js file can't detect the ID from the HTML file

HTML:

my jQuery best try:

$(document).ready(function(){
    $(".ImageHere").append("" ) });
});

Body:
Your HTML is invalid. HTMLDivElement does not have a valueattribute. Use data-value instead.

Here's an example. For the sake of simplicity, this inserts <hr /> instead of images. Adjust at your own pleasure.

const imageDivs = document.querySelectorAll('#Image .ImageHere');

document.getElementById('foo').addEventListener('click', insertRandomHr)

function insertRandomHr() {
  imageDivs[Math.floor(Math.random()*imageDivs.length)].innerHTML += '<hr />';
}

#Image { width: 100%; }

.ImageHere::before { content: attr(data-value); }

<table id="Image">
  <tr>
    <td>
      <div class="ImageHere" data-value=1></div>
    </td>
    <td>
      <div class="ImageHere" data-value=2></div>
    </td>
    <td>
      <div class="ImageHere" data-value=3></div>
    </td>
    <td>
      <div class="ImageHere" data-value=4></div>
    </td>
    <td>
      <div class="ImageHere" data-value=5></div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="ImageHere" data-value=6></div>
    </td>
    <td>
      <div class="ImageHere" data-value=7></div>
    </td>
    <td>
      <div class="ImageHere" data-value=8></div>
    </td>
    <td>
      <div class="ImageHere" data-value=9></div>
    </td>
    <td>
      <div class="ImageHere" data-value=10></div>
    </td>
  </tr>
</table>
<button id="foo" type="button">Insert &lt;hr /&gt; into random div</button>

Hint: If the sole reason to have those invalid value attributes in the first place was to use that for randomly assigning the image to a div, you don't need that.


问:
Cannot do routing within Redux Observable epic
There are very similar problems asked already but none of them works or they are different from my case.

My goal: I want to change the '/login' route to '/' route within my redux Observable epic. I'd like to do a simple login and when the authentication is success then it should go to the home page.

What I already tried:
Simply used { push } from 'connected-react-router'; method like mapTo(push('/login')) but the location changed but stuck on login page.
I also managed to inject the history object but I've got "TypeError: Cannot read property 'type' of undefined" error.
I also tried to downgrade the connected-react-router version how it was suggested in other thread but that didn't help either.

I'm very new in Redux Observable so I might miss a very basic stuff here but I couldn't really find good examples.

Here is the related code from my epic:

```<code>const login: Epic = action$ =>
    action$.pipe(
        ofType(LOGIN),
        mergeMap(({ payload }) =>
            from(API.post<LoginResult>('/oauth/token', $.param({...payload, grant_type: "password"}),
                ({auth: {
                    username: 'xxxx',
                    password: 'xxxx'
                }})
            )).pipe(
                map(({ data }) => loginSuccessAction(data)),
                catchError(err => of(loginErrorAction(err)))
            )
        )
    );

const loginSuccess: Epic = (action$) =>
    action$.pipe(
        ofType(LOGIN_SUCCESS),
        map(({ data }) => fetchProfileAction(data))
    );

const fetchProfile: Epic = (action$, state$) =>
        action$.pipe(
        ofType(FETCH_PROFILE_REQUEST),
        mergeMap(({ payload }) =>
            from(API.get<Profile>('/REST/v1/profile', {headers: {'Authorization': "Bearer " + state$.value.auth.auth.accessToken}}
            )).pipe(
                map(({ data }) => fetchProfileSuccessAction(data)),
                catchError(err => of(loginErrorAction(err)))
            )
        )
    );

const fetchProfileSuccess: Epic = action$ =>
    action$.pipe(
        ofType(FETCH_PROFILE_SUCCESS),
        tap(({action}) => {console.log(action$); debugger;}),
        //mapTo(push('/login')) // if I do this then the url changes to '/' but I'm still stucked on the login page
        mapTo(history.push('/login')) // if I do this then I've got "TypeError: Cannot read property 'type' of undefined" error
    );

</code>```

cofigureStore.ts:

```<code>export function configureStore() {
    const epicMiddleware = createEpicMiddleware<
        AllActions,
        AllActions,
        AppState
    >();

    const store = createStore(
        rootReducer(history),
        composeWithDevTools(
            applyMiddleware(epicMiddleware, routerMiddleware(history))
        )
    );

    epicMiddleware.run(rootEpic);
    return store;
}
</code>```

history.ts:

```<code>import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();
</code>```

App.ts:

```<code>export default function App() {

    let configureStore: Function;

    configureStore = require('./store/cofigureStore').configureStore;

    const store = configureStore();

    return (
        <Provider store={store}>
            <BrowserRouter basename={basename}>
                <Routes />
            </BrowserRouter>
        </Provider>
    );
}
</code>```

Many thanks for any help!

答:
It seems that I missed something basic. The solution was that I used BrowserRouter in my App.tsx: </p>

```<code>        <Provider store={store}>
            <BrowserRouter basename={basename}>
                <Routes />
            </BrowserRouter>
        </Provider>
</code>```

<p>But I should've used ConnectedRouter like this: </p>

```<code>        <Provider store={store}>
            <ConnectedRouter history={history}>
                <Routes />
            </ConnectedRouter>
        </Provider>
</code>```

Body:
There are very similar problems asked already but none of them works or they are different from my case.

My goal: I want to change the '/login' route to '/' route within my redux Observable epic. I'd like to do a simple login and when the authentication is success then it should go to the home page.

What I already tried:
Simply used { push } from 'connected-react-router'; method like mapTo(push('/login')) but the location changed but stuck on login page.
I also managed to inject the history object but I've got "TypeError: Cannot read property 'type' of undefined" error.
I also tried to downgrade the connected-react-router version how it was suggested in other thread but that didn't help either.

I'm very new in Redux Observable so I might miss a very basic stuff here but I couldn't really find good examples.

Here is the related code from my epic:

const login: Epic = action$ =>
    action$.pipe(
        ofType(LOGIN),
        mergeMap(({ payload }) =>
            from(API.post<LoginResult>('/oauth/token', $.param({...payload, grant_type: "password"}),
                ({auth: {
                    username: 'xxxx',
                    password: 'xxxx'
                }})
            )).pipe(
                map(({ data }) => loginSuccessAction(data)),
                catchError(err => of(loginErrorAction(err)))
            )
        )
    );

const loginSuccess: Epic = (action$) =>
    action$.pipe(
        ofType(LOGIN_SUCCESS),
        map(({ data }) => fetchProfileAction(data))
    );

const fetchProfile: Epic = (action$, state$) =>
        action$.pipe(
        ofType(FETCH_PROFILE_REQUEST),
        mergeMap(({ payload }) =>
            from(API.get<Profile>('/REST/v1/profile', {headers: {'Authorization': "Bearer " + state$.value.auth.auth.accessToken}}
            )).pipe(
                map(({ data }) => fetchProfileSuccessAction(data)),
                catchError(err => of(loginErrorAction(err)))
            )
        )
    );

const fetchProfileSuccess: Epic = action$ =>
    action$.pipe(
        ofType(FETCH_PROFILE_SUCCESS),
        tap(({action}) => {console.log(action$); debugger;}),
        //mapTo(push('/login')) // if I do this then the url changes to '/' but I'm still stucked on the login page
        mapTo(history.push('/login')) // if I do this then I've got "TypeError: Cannot read property 'type' of undefined" error
    );

cofigureStore.ts:

export function configureStore() {
    const epicMiddleware = createEpicMiddleware<
        AllActions,
        AllActions,
        AppState
    >();

    const store = createStore(
        rootReducer(history),
        composeWithDevTools(
            applyMiddleware(epicMiddleware, routerMiddleware(history))
        )
    );

    epicMiddleware.run(rootEpic);
    return store;
}

history.ts:

import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

App.ts:

export default function App() {

    let configureStore: Function;

    configureStore = require('./store/cofigureStore').configureStore;

    const store = configureStore();

    return (
        <Provider store={store}>
            <BrowserRouter basename={basename}>
                <Routes />
            </BrowserRouter>
        </Provider>
    );
}

Many thanks for any help!

Body:
It seems that I missed something basic. The solution was that I used BrowserRouter in my App.tsx:

        <Provider store={store}>
            <BrowserRouter basename={basename}>
                <Routes />
            </BrowserRouter>
        </Provider>

But I should've used ConnectedRouter like this:

        <Provider store={store}>
            <ConnectedRouter history={history}>
                <Routes />
            </ConnectedRouter>
        </Provider>


问:
Deep_search in big json object by method ruby
I have a problem with filtering JSON object in ruby!
 1. My JSON object is a big array of two hashes.
 2. That hashes includes another hashes that include another arrays and hashes (oh god! :c).
My goal is to output Big hash that contains concrete value!
Examples down below:
JSON file just like in

[#That's hash 0{
        "id": 0,
        "firstName": "",
        "lastName": "",
        "middleName": null,
        "email": "",
        "phones": [
            null,
            null
        ],
        "groups": [{
            "id": 0,
            "name": ""
        }],
        "disabled": "",
        "technologies": [{
            "id": 0,
            "name": "",
            "children": [{
                "id": 1,
                "name": "",
                "children": [{
                    "id": 2,
                    "name": "Farmer",
                    "children": []
                }]
            }]
        }],
        "fullName": ""
    },
 #That's hash1{
        "id": 0,
        "firstName": "",
        "lastName": "",
        "middleName": null,
        "email": "",
        "phones": [
            null,
            null
        ],
        "groups": [{
            "id": 0,
            "name": ""
        }],
        "disabled": "",
        "technologies": [{
            "id": 0,
            "name": "",
            "children": [{
                "id": 1,
                "name": "",
                "children": [{
                    "id": 2,
                    "name": "Not Farmer",
                    "children": []
                }]
            }]
        }],
        "fullName": ""
    }
]
```

<p>Pseudocode on ruby (what I want to):</p>

<pre class="lang-rb prettyprint-override"><code>file = File.read("example.json") #=> Reading JSON file
data_hash = JSON.parse(file, object_class: Hash)  #=> Parsing JSON file

data = data_hash.filter #=> filter that hash if "technologies" is not empty!
data.get_hash_by_value(value) #=> For example i put "Not Farmer" in value, and that method must search in all data that (value) and output hash1 for me (because hash0 not include "Not Farmer")

</code>```

That's big problem, i don't know what to do!!!
My thoughts is a recursive finding method..

答:
I wrote my own functions. Maybe it can help someone.

def check_children(item)
  return true if item["name"] == "Farmer"
  item["children"].each do |child_item|
    break if check_children(child_item)
  end
  return false
end

data_hash.each do |item|
  next if item["technologies"].empty?
  item["technologies"].each do |technologies_item|
    next if technologies_item["children"].empty?
    technologies_item["children"].each do |children_item|
      data << item if check_children(children_item)
    end
  end
end
```

Body:
I have a problem with filtering JSON object in ruby!
 1. My JSON object is a big array of two hashes.
 2. That hashes includes another hashes that include another arrays and hashes (oh god! :c).
My goal is to output Big hash that contains concrete value!
Examples down below:
JSON file just like in

[#That's hash 0{
        "id": 0,
        "firstName": "",
        "lastName": "",
        "middleName": null,
        "email": "",
        "phones": [
            null,
            null
        ],
        "groups": [{
            "id": 0,
            "name": ""
        }],
        "disabled": "",
        "technologies": [{
            "id": 0,
            "name": "",
            "children": [{
                "id": 1,
                "name": "",
                "children": [{
                    "id": 2,
                    "name": "Farmer",
                    "children": []
                }]
            }]
        }],
        "fullName": ""
    },
 #That's hash1{
        "id": 0,
        "firstName": "",
        "lastName": "",
        "middleName": null,
        "email": "",
        "phones": [
            null,
            null
        ],
        "groups": [{
            "id": 0,
            "name": ""
        }],
        "disabled": "",
        "technologies": [{
            "id": 0,
            "name": "",
            "children": [{
                "id": 1,
                "name": "",
                "children": [{
                    "id": 2,
                    "name": "Not Farmer",
                    "children": []
                }]
            }]
        }],
        "fullName": ""
    }
]

Pseudocode on ruby (what I want to):

file = File.read("example.json") #=> Reading JSON file
data_hash = JSON.parse(file, object_class: Hash)  #=> Parsing JSON file

data = data_hash.filter #=> filter that hash if "technologies" is not empty!
data.get_hash_by_value(value) #=> For example i put "Not Farmer" in value, and that method must search in all data that (value) and output hash1 for me (because hash0 not include "Not Farmer")

That's big problem, i don't know what to do!!!
My thoughts is a recursive finding method..


问:
Nth salary in SQL
I'm trying to understand below query, how its working.

```<code>SELECT *
FROM Employee Emp1
WHERE (N-1) = (
               SELECT COUNT(DISTINCT(Emp2.Salary))
               FROM Employee Emp2
               WHERE Emp2.Salary > Emp1.Salary
               )
</code>```

Lets say I have 5 distinct salaries and want to get 3rd largest salary. So Inner query will run first and then outer query ?

I'm getting confused how its being done in sql engine. Curious to know. Becasue if its 3rd largest then 3-1 = 2, so that 2 needs to be matched with inner count as well. How inner count is being operated.

Can anyone explain the how its working .. ?

答:
It is easier to understand when you run this query:

```<code>select e1.*,
       (select count(distinct e2.salary)
          from employee e2
          where e2.salary > e1.salary) as n
  from employee e1
</code>```

This is my sample table:

```<code>create table employee(salary) as (
  select * from table(sys.odcinumberlist(1500, 1200, 1400, 1500, 1100)));
</code>```

so my output is:

```<code>    SALARY          N
---------- ----------
      1500          0
      1200          2
      1400          1
      1500          0
      1100          3
</code>```

As you can see that subquery counts, for each row, salaries which are greater than salary in current row. So for instance, for 1400 there is one DISTINCT greater salary (1500). 1500 appears twice in my table, but distinct makes that it is counted once. So 1400 is second in order.

Your query has this count moved to the where part and compared with required value. We have to substract one, because for highest salary there is no higher value, for second salary one row etc.

It's one of the methods used to find such values, newer Oracle versions introduced analytic functions (rank, row_number, dense_rank) which eliminates the need of using subqueries for such purposes. They are faster, more efficient. For your query dense_rank() would be useful.

Title: Nth salary in SQL

Body:
I'm trying to understand below query, how its working.

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
               SELECT COUNT(DISTINCT(Emp2.Salary))
               FROM Employee Emp2
               WHERE Emp2.Salary > Emp1.Salary
               )

Lets say I have 5 distinct salaries and want to get 3rd largest salary. So Inner query will run first and then outer query ?

I'm getting confused how its being done in sql engine. Curious to know. Becasue if its 3rd largest then 3-1 = 2, so that 2 needs to be matched with inner count as well. How inner count is being operated.

Can anyone explain the how its working .. ?

Body:
It is easier to understand when you run this query:

select e1.*,
       (select count(distinct e2.salary)
          from employee e2
          where e2.salary > e1.salary) as n
  from employee e1

This is my sample table:

create table employee(salary) as (
  select * from table(sys.odcinumberlist(1500, 1200, 1400, 1500, 1100)));

so my output is:

    SALARY          N
---------- ----------
      1500          0
      1200          2
      1400          1
      1500          0
      1100          3

As you can see that subquery counts, for each row, salaries which are greater than salary in current row. So for instance, for 1400 there is one DISTINCT greater salary (1500). 1500 appears twice in my table, but distinct makes that it is counted once. So 1400 is second in order.

Your query has this count moved to the where part and compared with required value. We have to substract one, because for highest salary there is no higher value, for second salary one row etc.

It's one of the methods used to find such values, newer Oracle versions introduced analytic functions (rank, row_number, dense_rank) which eliminates the need of using subqueries for such purposes. They are faster, more efficient. For your query dense_rank() would be useful.


问:
FUSE mapping to Google Persistent Disks
Is it possible to mount the FUSE storage to a Google Persistent Disk(Standard persistent disk)?</p>

答:
You could use Cloud Storage FUSE, which is a FUSE adapter that allows you to mount buckets as file systems on Linux or macOS systems.

Cloud Storage FUSE can be run anywhere with connectivity to Cloud Storage, including Google Compute Engine VMs or on-premises systems. So it probably will suit whichever needs your system have.

If this is the way you choose to go, you can find more information on how it works and how to set it up in this documentation.

Title: FUSE mapping to Google Persistent Disks


问:
Android: put two lists into a ScrollView
I know that ListView objects shouldn't be put into a ScrollView. However, I can't come up with a proper approach to this situation: I have two layouts, both including a ListView, one directly below the other. I want all elements of both lists to be output; naturally, that should take more than the screen can offer, so I want to make the result scrollable, so, as I thought, I should put both into a ScrollView, but this doesn't work well with ListView (they only display one item each) and is considered a bad practice. How do I go about this?

Here's a mock up of what I mean:

Two lists, and the entirety of the second list can't fit into the screen, so I'd like to scroll it, and when I do, the second header ('Example2') scrolls up and doesn't stay in place, as opposed to the default behaviour of having the second list content scrolled.

What I have now is:

```<code>    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/example1_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <ListView
                android:id="@+id/example1_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/example1_header" />

        </RelativeLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/example2_header />

            <ListView
                android:id="@+id/example2_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </LinearLayout>
</code>```

答: hi i think you should use NestedScrollView instead of using ScrollView and it will solve your problem </p>

Body:
I know that ListView objects shouldn't be put into a ScrollView. However, I can't come up with a proper approach to this situation: I have two layouts, both including a ListView, one directly below the other. I want all elements of both lists to be output; naturally, that should take more than the screen can offer, so I want to make the result scrollable, so, as I thought, I should put both into a ScrollView, but this doesn't work well with ListView (they only display one item each) and is considered a bad practice. How do I go about this?

Here's a mock up of what I mean:

Two lists, and the entirety of the second list can't fit into the screen, so I'd like to scroll it, and when I do, the second header ('Example2') scrolls up and doesn't stay in place, as opposed to the default behaviour of having the second list content scrolled.

What I have now is:

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/example1_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <ListView
                android:id="@+id/example1_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/example1_header" />

        </RelativeLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/example2_header />

            <ListView
                android:id="@+id/example2_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </LinearLayout>


问:
What is the best way to program C# on a free platform? (Compiler / IDE / Debugger / etc)
Preferably also on linux - if necessary I'll install a basic version of Windows XP</p>

答:
If you're considering serious (commercial) .NET development I wouldn't dive into products like Mono or Shardevelop.
One of the reasons why .NET might be a better option from Java, for example, is because Microsoft provides very nice and powerful tools for the development which makes the development process a lot easier. Using free/open tools  and implementations makes developing in .NET meaningless since Java in this area is much better.

Of course there's Express series, but those IDE are designated for learning mostly (you didn't say why do you need free tools). For the professional team development they are still not enough.

OwnerDisplayName: andy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Marcin Rybacki


问:
can I use ng template for a separate component and use its template reference in other html?
I am trying to use ng-template for a html which is a separate component ,and I am trying to use its reference in other html.. Is it possible? If so I have tried the below ways and would like to understand what is that I am going wrong with?

ng-template.html

```<code><ng-template #sample1>
  <p>ng template content</p>
</ng-template>
</code>```

display-template.html

```<code><div *ngIf="found;">
  <ng-container *ngTemplateOutlet="sample1"></ng-container>
</div>
</code>```

DisplayTemplateComponent.ts

```<code>export class DisplayTemplateComponent   {
    @ViewChild('sample1', {static: false}) sample1: ElementRef;
    found = true;
}
</code>```

答:
I think you should use a regular angular component instead of an ng-template if you want to use it globaly in your application.

I am not sure why you want to do it this way. Anyways this link may help you How to load the ng-template in separate file?.

Body:
I am trying to use ng-template for a html which is a separate component ,and I am trying to use its reference in other html.. Is it possible? If so I have tried the below ways and would like to understand what is that I am going wrong with?

ng-template.html

<ng-template #sample1>

ng template content

</ng-template>

display-template.html

  <ng-container *ngTemplateOutlet="sample1"></ng-container>

DisplayTemplateComponent.ts

export class DisplayTemplateComponent   {
    @ViewChild('sample1', {static: false}) sample1: ElementRef;
    found = true;
}


问:
User-defined infix operator
I know operators in Julia are just standard functions, and I can use them using
the ordinary prefix call syntax:

```<code>julia> +(1, 2)
3
</code>```

However, they are also special in the sense that they can be (and are usually)
used as infix operators:

```<code>julia> 1+2
3
</code>```

Could I define my own infix operator? If so, how?

For example:

```<code>julia> α(x, y) = x+y
α (generic function with 1 method)

julia> α(1, 2)
3 # as expected

julia> 1α2
# expected result: 3
ERROR: UndefVarError: α2 not defined
Stacktrace:
 [1] top-level scope at REPL[5]:1

julia> 1 α 2
# expected result: 3
ERROR: syntax: extra token "α" after end of expression
Stacktrace:
 [1] top-level scope at REPL[5]:0
</code>```

答:
As you said, operators are just standard functions, which you can define and
otherwise manipulate like any other function. However, Julia's parser is
configured to recognize a certain set of symbols as infix operators; if you
define a function whose name is one of these symbols, it will be parsed as an
infix operator.

For example:

```<code>julia> ⊕(x, y) = x+y
⊕ (generic function with 1 method)

# standard prefix function call
julia> ⊕(1, 2)
3

# infix operator call
julia> 1⊕2
3

julia> 1 ⊕ 2
3
</code>```

The list of symbols recognized as infix operators (and associated precedence) can be found in the Julia
parser source
code. For
the most part, this list is a subset of unicode category Sm(Symbol,
math).

At the moment, it includes for example:

parsed with the same precedence as +:

```<code>+ - ⊕ ⊖ ⊞ ⊟ ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦
⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣
</code>```

parsed with the same precedence as *:

```<code>* / ÷ % & ⋅ ∘ × ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇
⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻
⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗
</code>```

Title: User-defined infix operator

Body:
I know operators in Julia are just standard functions, and I can use them using
the ordinary prefix call syntax:

julia> +(1, 2)
3

However, they are also special in the sense that they can be (and are usually)
used as infix operators:

julia> 1+2
3

Could I define my own infix operator? If so, how?

For example:

julia> α(x, y) = x+y
α (generic function with 1 method)

julia> α(1, 2)
3 # as expected

julia> 1α2
# expected result: 3
ERROR: UndefVarError: α2 not defined
Stacktrace:
 [1] top-level scope at REPL[5]:1

julia> 1 α 2
# expected result: 3
ERROR: syntax: extra token "α" after end of expression
Stacktrace:
 [1] top-level scope at REPL[5]:0

Body:
As you said, operators are just standard functions, which you can define and
otherwise manipulate like any other function. However, Julia's parser is
configured to recognize a certain set of symbols as infix operators; if you
define a function whose name is one of these symbols, it will be parsed as an
infix operator.

For example:

julia> ⊕(x, y) = x+y
⊕ (generic function with 1 method)

# standard prefix function call
julia> ⊕(1, 2)
3

# infix operator call
julia> 1⊕2
3

julia> 1 ⊕ 2
3

The list of symbols recognized as infix operators (and associated precedence) can be found in the Julia
parser source
code. For
the most part, this list is a subset of unicode category Sm(Symbol,
math).

At the moment, it includes for example:

parsed with the same precedence as +:

+ - ⊕ ⊖ ⊞ ⊟ ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦
⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣

parsed with the same precedence as *:

* / ÷ % & ⋅ ∘ × ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇
⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻
⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗


问:
How can i write the code to do "When i click cancel in options windows , that field will hide."
I have a field in the Notes document , the field name is "reason".
if i click a button,will show a options windows , and the field will show out.
now i need to know how can i write the code to do "when i click cancel in options windows , that field will hide.".
the options windows is PROMPT_OKCANCELLIST.
the following codes is i write in the button:</p>

```<code>If uipr.FieldGetText("TRACK_MARK") = "" Then
    Call uipr.FieldSetText("TRACK_MARK" , "Y")
End If
askme = ws.prompt(PROMPT_OKCANCELLIST,"Track Reason","Please choose reason..." , data(0) , data())
If askme = "" Then
    If uipr.FieldGetText("TRACK_MARK") = "Y" Then
        Call uipr.FieldSetText("TRACK_MARK" ,"")
        Exit Sub
    End If
End If
</code>```

答:
In the Form with the Reason field, you will need to select the paragraph you wish to hide, then in the Properties box, select Hide paragraph if formula is true, and enter TRACK_MARK="Y" :

This will hide the paragraph once TRACK_MARK is set to "Y".

Body:
I have a field in the Notes document , the field name is "reason".
if i click a button,will show a options windows , and the field will show out.
now i need to know how can i write the code to do "when i click cancel in options windows , that field will hide.".
the options windows is PROMPT_OKCANCELLIST.
the following codes is i write in the button:

If uipr.FieldGetText("TRACK_MARK") = "" Then
    Call uipr.FieldSetText("TRACK_MARK" , "Y")
End If
askme = ws.prompt(PROMPT_OKCANCELLIST,"Track Reason","Please choose reason..." , data(0) , data())
If askme = "" Then
    If uipr.FieldGetText("TRACK_MARK") = "Y" Then
        Call uipr.FieldSetText("TRACK_MARK" ,"")
        Exit Sub
    End If
End If


答:
I hope that can help!

```<code>const divs = [...document.querySelectorAll('.ImageHere')];
const images =
[
'https://i.pinimg.com/originals/d4/7e/9e/d47e9e4a28894bfbd416b4f53ca15b95.jpg',
'https://fedoraproject.org/w/uploads/thumb/1/16/Sunset-in-pennsylvania-960px.jpg/285px-Sunset-in-pennsylvania-960px.jpg',
'https://fedoraproject.org/w/uploads/thumb/a/a0/F26-final-night-default-wallpaper-standard.png/300px-F26-final-night-default-wallpaper-standard.png',
'https://eldenring.wiki.fextralife.com/file/Elden-Ring/elden-ring-wiki-screenshot-art-trailer5.jpg?v=1560119240021',
'https://pbs.twimg.com/media/D9oueVsX4AAW3Wk.jpg',
'https://pub-static.haozhaopian.net/static/web/appv2/images/landscape29bb2ef5b72f60c71199d5c22c979eadc.jpg',
'https://images.unsplash.com/photo-1462899006636-339e08d1844e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80',
'https://picjumbo.com/wp-content/uploads/free-stock-images-1080x720.jpg',
'https://destinations.com.ua/storage/crop/articles/avatar_291_max.jpg',
'https://get.wallhere.com/photo/sunlight-women-outdoors-women-model-portrait-blonde-long-hair-nature-photography-dress-Xenia-Kokoreva-river-fashion-hair-white-clothing-spring-Person-skin-clothing-supermodel-girl-beauty-season-woman-lady-photograph-blond-portrait-photography-photo-shoot-brown-hair-art-model-320309.jpg'
];
const suffelImages = shuffle(images);

function shuffle(a) {
  for (let i = a.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

divs.forEach((div, i) => {
  div.innerHTML = `<img src="${suffelImages[i]}" />`;
});
</code>```

// CSS

```<code>img {
    width: 300px;
    height: 300px;
}
</code>```

Title: Insert multiple images randomly into different table cells using Javascript

Body:
I hope that can help!

const divs = [...document.querySelectorAll('.ImageHere')];
const images =
[
'https://i.pinimg.com/originals/d4/7e/9e/d47e9e4a28894bfbd416b4f53ca15b95.jpg',
'https://fedoraproject.org/w/uploads/thumb/1/16/Sunset-in-pennsylvania-960px.jpg/285px-Sunset-in-pennsylvania-960px.jpg',
'https://fedoraproject.org/w/uploads/thumb/a/a0/F26-final-night-default-wallpaper-standard.png/300px-F26-final-night-default-wallpaper-standard.png',
'https://eldenring.wiki.fextralife.com/file/Elden-Ring/elden-ring-wiki-screenshot-art-trailer5.jpg?v=1560119240021',
'https://pbs.twimg.com/media/D9oueVsX4AAW3Wk.jpg',
'https://pub-static.haozhaopian.net/static/web/appv2/images/landscape29bb2ef5b72f60c71199d5c22c979eadc.jpg',
'https://images.unsplash.com/photo-1462899006636-339e08d1844e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80',
'https://picjumbo.com/wp-content/uploads/free-stock-images-1080x720.jpg',
'https://destinations.com.ua/storage/crop/articles/avatar_291_max.jpg',
'https://get.wallhere.com/photo/sunlight-women-outdoors-women-model-portrait-blonde-long-hair-nature-photography-dress-Xenia-Kokoreva-river-fashion-hair-white-clothing-spring-Person-skin-clothing-supermodel-girl-beauty-season-woman-lady-photograph-blond-portrait-photography-photo-shoot-brown-hair-art-model-320309.jpg'
];
const suffelImages = shuffle(images);

function shuffle(a) {
  for (let i = a.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

divs.forEach((div, i) => {
  div.innerHTML = `<img src="${suffelImages[i]}" />`;
});

// CSS

img {
    width: 300px;
    height: 300px;
}


问:
When do Redis PUB/SUB events fire-and-forget?
Redis events are fire-and-forget. If no one is listening, they will just remain undetected. There's no history. But nowhere on the internet did I find anything that answers the following question (I'm using redis-py and aioredis for python):

Does the code actually need to LISTEN to the events to receive it or will the redis connection cache events for me?

Let's suppose I have this loop:

```<code>redis_db = Redis(...)

while True:
    print("Hey, I'm listening now!")
    msg = redis_db.blocking_subscribe("some_topic") # pseudo-code, because I'm using various libraries
    if msg == "calc":
        do_a_heavy_5_seconds_calculation()
        print("YAY, I was busy and am back up now!")
</code>```

So will I miss all events that occur in the 5s calculation or will my redis_db cache them for me?

In other words... does fire-and-forget apply if I don't have a connection or if I have a connection, but am not listening ?

答: It's a bit of both. You need a connection AND that connection must be in a "subscription" state. As soon as execute the "blocking_subscribe" method, you have effectively changed that connections state to the "subscription state" so redis will continue to buffer these messages for you regardless if your python thread is busy processing other messages at the same time. Now of course, if it crashes for any reason, then that connections server side buffer will be lost.</p>

Body:
Redis events are fire-and-forget. If no one is listening, they will just remain undetected. There's no history. But nowhere on the internet did I find anything that answers the following question (I'm using redis-py and aioredis for python):

Does the code actually need to LISTEN to the events to receive it or will the redis connection cache events for me?

Let's suppose I have this loop:

redis_db = Redis(...)

while True:
    print("Hey, I'm listening now!")
    msg = redis_db.blocking_subscribe("some_topic") # pseudo-code, because I'm using various libraries
    if msg == "calc":
        do_a_heavy_5_seconds_calculation()
        print("YAY, I was busy and am back up now!")

So will I miss all events that occur in the 5s calculation or will my redis_db cache them for me?

In other words... does fire-and-forget apply if I don't have a connection or if I have a connection, but am not listening ?


问:
Go fan-out, multiple broadcasts, unknown number of receivers
I need a way to signal from one main goroutine, an unknown number of other goroutines, multiple times. I also need for those other goroutines to select on multiple items, so busy waiting is (probably) not an option. I have come up with the following solution:

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

type signal struct {
    data     []int
    channels []chan struct{}
}

func newSignal() *signal {
    s := &signal{
        data:     make([]int, 0),
        channels: make([]chan struct{}, 1),
    }
    s.channels[0] = make(chan struct{})
    return s
}

func (s *signal) Broadcast(d int) {
    s.data = append(s.data, d)
    s.channels = append(s.channels, make(chan struct{}))
    close(s.channels[len(s.data)-1])
}

func test(s *signal, wg *sync.WaitGroup, id int, ctx context.Context) {
    for i := 0; ; i += 1 {
        select {
        case <-s.channels[i]:
            if id >= s.data[i] {
                fmt.Println("Goroutine completed:", id)
                wg.Done()
                return
            }
        case <-ctx.Done():
            fmt.Println("Goroutine completed:", id)
            wg.Done()
            return
        }
    }
}

func main() {
    s := newSignal()

    ctx, cancel := context.WithCancel(context.Background())
    wg := sync.WaitGroup{}
    wg.Add(3)
    go test(s, &wg, 3, ctx)
    go test(s, &wg, 2, ctx)
    go test(s, &wg, 1, ctx)

    s.Broadcast(3)
    time.Sleep(1 * time.Second)

    // multiple broadcasts is mandatory
    s.Broadcast(2)
    time.Sleep(1 * time.Second)

    // last goroutine
    cancel()

    wg.Wait()
}
```

Playground: https://play.golang.org/p/dGmlkTuj7Ty

Is there a more elegant way to do this? One that uses builtin libraries only. If not, is this a safe/ok to use solution? I believe it is safe at least, as it works for a large number of goroutines (I have done some testing with it).

To be concise, here is exactly what I want:

The main goroutine (call it M) must be able to signal with some data (call it d) some unknown number of other goroutines (call them n for 0...n), multiple times, with each goroutine taking an action based on d each time

M must be able to signal all of the other n goroutines with certain (numerical) data, multiple times

Every goroutine in n will either terminate on its own (based on a context) or after doing some operation with d and deciding its fate. It will be performing this check as many times as signaled until it dies.

I am not allowed to keep track of the n goroutines in any way (eg. having a map of channels to goroutines and iterating)

In my solution, the slices of channels do not represent goroutines: they actually represent signals that are being broadcast out. This means that if I broadcast twice, and then a goroutine spins up, it will check both signals before sleeping in the select block.

答:
It seems to me that you might want something like a fan-out pattern. Here's one source describing fan-in and fan-out, among other concurrency patterns. Here's a blog post on golang.org about this too. I think it's essentially a version of observer pattern using channels.

Basically, you want something, say Broadcaster, that keeps a list of channels. When you call Broadcaster.send(data), it loops over the list of channels sending data on each channel. Broadcaster must also have a way for goroutines to subscribe to Broadcaster. Goroutines must have a way to accept a channel from Broadcasteror give a channel to Broadcaster. That channel is the communication link.

If the work to be performed in the "observer" goroutines will take long, consider using buffered channels so that Broadcaster is not blocking during send and waiting on goroutines. If you don't care if a goroutine misses a data, you can use a non-blocking send (see below).

When a goroutine "dies", it can unsubscribe from Broadcaster which will remove the appropriate channel from its list. Or the channel can just remain full, and Broadcaster will have to use a non-blocking send to skip over full channels to dead goroutines.

I can't say what I described is comprehensive or 100% correct. It's just a quick description of the first general things I'd try based on your problem statement.

Body:
I need a way to signal from one main goroutine, an unknown number of other goroutines, multiple times. I also need for those other goroutines to select on multiple items, so busy waiting is (probably) not an option. I have come up with the following solution:

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

type signal struct {
    data     []int
    channels []chan struct{}
}

func newSignal() *signal {
    s := &signal{
        data:     make([]int, 0),
        channels: make([]chan struct{}, 1),
    }
    s.channels[0] = make(chan struct{})
    return s
}

func (s *signal) Broadcast(d int) {
    s.data = append(s.data, d)
    s.channels = append(s.channels, make(chan struct{}))
    close(s.channels[len(s.data)-1])
}

func test(s *signal, wg *sync.WaitGroup, id int, ctx context.Context) {
    for i := 0; ; i += 1 {
        select {
        case <-s.channels[i]:
            if id >= s.data[i] {
                fmt.Println("Goroutine completed:", id)
                wg.Done()
                return
            }
        case <-ctx.Done():
            fmt.Println("Goroutine completed:", id)
            wg.Done()
            return
        }
    }
}

func main() {
    s := newSignal()

    ctx, cancel := context.WithCancel(context.Background())
    wg := sync.WaitGroup{}
    wg.Add(3)
    go test(s, &wg, 3, ctx)
    go test(s, &wg, 2, ctx)
    go test(s, &wg, 1, ctx)

    s.Broadcast(3)
    time.Sleep(1 * time.Second)

    // multiple broadcasts is mandatory
    s.Broadcast(2)
    time.Sleep(1 * time.Second)

    // last goroutine
    cancel()

    wg.Wait()
}

Playground: https://play.golang.org/p/dGmlkTuj7Ty

Is there a more elegant way to do this? One that uses builtin libraries only. If not, is this a safe/ok to use solution? I believe it is safe at least, as it works for a large number of goroutines (I have done some testing with it).

To be concise, here is exactly what I want:

The main goroutine (call it M) must be able to signal with some data (call it d) some unknown number of other goroutines (call them n for 0...n), multiple times, with each goroutine taking an action based on d each time

M must be able to signal all of the other n goroutines with certain (numerical) data, multiple times

Every goroutine in n will either terminate on its own (based on a context) or after doing some operation with d and deciding its fate. It will be performing this check as many times as signaled until it dies.

I am not allowed to keep track of the n goroutines in any way (eg. having a map of channels to goroutines and iterating)

In my solution, the slices of channels do not represent goroutines: they actually represent signals that are being broadcast out. This means that if I broadcast twice, and then a goroutine spins up, it will check both signals before sleeping in the select block.


问:
Confluent schema registry SSL configuration
I am new to the kafka field.

I have kafka, zookeeper and schema registry all installed in a RHEL7 machine (hostname: kafka-confluent), it is not a cluster setup so there is only 1 broker.

Now I would like to configure SSL encryption for my setup. I have created ssl keys and certificate according to the docs.

Then I configured the properties files.

My (confluent platform install dir) /etc/kafka/server.properties:

```<code>ssl.truststore.location=/home/kafka/kafka.server.truststore.jks
ssl.truststore.password=password
ssl.keystore.location=/home/kafka/kafka.server.keystore.jks
ssl.keystore.password=password
ssl.key.password=password
security.inter.broker.protocol=SSL
ssl.client.auth=required
listeners=PLAINTEXT://:9092,SSL://:9093
</code>```

My (confluent platform install dir) /etc/schema-registry/schema-registry.properties:

```<code>listeners=http://0.0.0.0:8081,https://0.0.0.0:8082
ssl.truststore.location=/home/kafka/kafka.server.truststore.jks
ssl.truststore.password=password
ssl.keystore.location=/home/kafka/kafka.server.keystore.jks
ssl.keystore.password=password
ssl.key.password=password
ssl.client.auth=true

</code>```

I already have a topic test created before, when I publish the message in the server, it failed:

```<code>[kafka@kafka-confluent ~]$ echo "Hello, World" | /home/kafka/confluent-5.4.0/bin/kafka-console-producer --broker-list localhost:9093 --topic test > /dev/null

[2020-02-20 18:45:12,193] ERROR Error when sending message to topic test with key: null, value: 13 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Topic test not present in metadata after 60000 ms.

</code>```

Then I checked the server.log, it shows failed authentication:

```<code>[2020-02-20 18:45:47,754] INFO [SocketServer brokerId=0] Failed authentication with /127.0.0.1 (SSL handshake failed) (org.apache.kafka.common.network.Selector)
</code>```

答:
It is worth checking ssl.endpoint.identification.algorithm:

The endpoint identification algorithm used by clients to validate
  server host name. The default value is https. Clients including client
  connections created by the broker for inter-broker communication
  verify that the broker host name matches the host name in the broker’s
  certificate. Disable server host name verification by setting
  ssl.endpoint.identification.algorithm to an empty string

Therefore, setting ssl.endpoint.identification.algorithm to an empty string should do the trick:

```<code>ssl.endpoint.identification.algorithm=
</code>```

Note that this config prevents man-in-the-middle attacks therefore consider configuring it accordingly.

Body:
I am new to the kafka field.

I have kafka, zookeeper and schema registry all installed in a RHEL7 machine (hostname: kafka-confluent), it is not a cluster setup so there is only 1 broker.

Now I would like to configure SSL encryption for my setup. I have created ssl keys and certificate according to the docs.

Then I configured the properties files.

My (confluent platform install dir) /etc/kafka/server.properties:

ssl.truststore.location=/home/kafka/kafka.server.truststore.jks
ssl.truststore.password=password
ssl.keystore.location=/home/kafka/kafka.server.keystore.jks
ssl.keystore.password=password
ssl.key.password=password
security.inter.broker.protocol=SSL
ssl.client.auth=required
listeners=PLAINTEXT://:9092,SSL://:9093

My (confluent platform install dir) /etc/schema-registry/schema-registry.properties:

listeners=http://0.0.0.0:8081,https://0.0.0.0:8082
ssl.truststore.location=/home/kafka/kafka.server.truststore.jks
ssl.truststore.password=password
ssl.keystore.location=/home/kafka/kafka.server.keystore.jks
ssl.keystore.password=password
ssl.key.password=password
ssl.client.auth=true

I already have a topic test created before, when I publish the message in the server, it failed:

[kafka@kafka-confluent ~]$ echo "Hello, World" | /home/kafka/confluent-5.4.0/bin/kafka-console-producer --broker-list localhost:9093 --topic test > /dev/null

[2020-02-20 18:45:12,193] ERROR Error when sending message to topic test with key: null, value: 13 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Topic test not present in metadata after 60000 ms.

Then I checked the server.log, it shows failed authentication:

[2020-02-20 18:45:47,754] INFO [SocketServer brokerId=0] Failed authentication with /127.0.0.1 (SSL handshake failed) (org.apache.kafka.common.network.Selector)

Body:
It is worth checking ssl.endpoint.identification.algorithm:

The endpoint identification algorithm used by clients to validate
  server host name. The default value is https. Clients including client
  connections created by the broker for inter-broker communication
  verify that the broker host name matches the host name in the broker’s
  certificate. Disable server host name verification by setting
  ssl.endpoint.identification.algorithm to an empty string

Therefore, setting ssl.endpoint.identification.algorithm to an empty string should do the trick:

ssl.endpoint.identification.algorithm=

Note that this config prevents man-in-the-middle attacks therefore consider configuring it accordingly.


问:
How create data structure with similar numpy nd array
i have next function:

```<code>def check_smaller_zeros(v):
   return v < 0
</code>```

When i create array with numpy i can write next code for element-by-element measurement:

```<code>v_1 = numpy.array([1, 2, -4, -1])
result = check_smaller_zeros(v_1)
# result: [False, False, True, True]
</code>```

but when i try repeat it with tuple, set, frozenset and list/array reise next error:

```<code>TypeError: '<' not supported between instances of 'tuple' and 'int'
</code>```

what exactly allows numpy array to have the capability for this behavior? This looks convenient, but is a bit non-obvious

答:
np.array is very different from tuple, lists, etc.
If you want to generalize your function, you have to think about each case.

```<code>In [111]: def check_smaller_zeros(v):
     ...:    if type(v) is np.array:
     ...:        return v < 0
     ...:    elif type(v) in (list, tuple):
     ...:        return [x<0 for x in v]
     ...:

In [112]: check_smaller_zeros((-1,1,2,3,4,5))
Out[112]: [True, False, False, False, False, False]
</code>```

In some instance, you may can simply convert the object to a np.array. But it depends form the object and you have to define the use cases in advance.

```<code>In [114]: def check_smaller_zeros(v):
     ...:    if type(v) is np.array:
     ...:        return v < 0
     ...:    else:
     ...:        return np.array(v) < 0
     ...:
     ...:

In [115]: check_smaller_zeros((-1,1,2,3,4,5))
Out[115]: array([True, False, False, False, False, False])
</code>```

Body:
i have next function:

def check_smaller_zeros(v):
   return v < 0

When i create array with numpy i can write next code for element-by-element measurement:

v_1 = numpy.array([1, 2, -4, -1])
result = check_smaller_zeros(v_1)
# result: [False, False, True, True]

but when i try repeat it with tuple, set, frozenset and list/array reise next error:

TypeError: '<' not supported between instances of 'tuple' and 'int'

what exactly allows numpy array to have the capability for this behavior? This looks convenient, but is a bit non-obvious

Body:
np.array is very different from tuple, lists, etc.
If you want to generalize your function, you have to think about each case.

In [111]: def check_smaller_zeros(v):
     ...:    if type(v) is np.array:
     ...:        return v < 0
     ...:    elif type(v) in (list, tuple):
     ...:        return [x<0 for x in v]
     ...:

In [112]: check_smaller_zeros((-1,1,2,3,4,5))
Out[112]: [True, False, False, False, False, False]

In some instance, you may can simply convert the object to a np.array. But it depends form the object and you have to define the use cases in advance.

In [114]: def check_smaller_zeros(v):
     ...:    if type(v) is np.array:
     ...:        return v < 0
     ...:    else:
     ...:        return np.array(v) < 0
     ...:
     ...:

In [115]: check_smaller_zeros((-1,1,2,3,4,5))
Out[115]: array([True, False, False, False, False, False])


问:
Get list of field names from a ModelSerializer class
If I have a serializer such as:

```<code>class RandomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Random
        fields = ["id", "field_a", "field_b"]
</code>```

Is there a way to access Meta.fields without creating an instance of the serializer?

答:
```<code>SimpleCompanySerializer.Meta.fields
</code>```

does not create a new instance

```<code>SimpleCompanySerializer() or SimpleCompanySerializer.Meta()
</code>```

does

Body:
If I have a serializer such as:

class RandomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Random
        fields = ["id", "field_a", "field_b"]

Is there a way to access Meta.fields without creating an instance of the serializer?

Body:
SimpleCompanySerializer.Meta.fields

does not create a new instance

SimpleCompanySerializer() or SimpleCompanySerializer.Meta()

does