问:
Failed assertion: line 3927 pos 14: '_dependents.isEmpty': is not true
I am back again with the issue related to the question already posted by me on stack overflow Error: '_elements.contains(element)': is not true

this issue has been plaguing me but i was unable to reproduce the same issue and now i have somehow tried to repro again and I have posted the code for everyone to figure out what is it that i am doing wrong that's throwing up this assertion error and crashing the app.

I am new to programming and any help would be greatly appreciated. I have trimmed down the code and I am aware of the some of the bugs. But, the only main concern is the Failed assertion: line 3927 pos 14: '_dependents.isEmpty': is not true. and Failed assertion: line 1766 pos 12: '_elements.contains(element)': is not true.

Steps to reproduce.

main.dart

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:untitled1/addnewbranch.dart';

void main() {
  runApp(
    new MaterialApp(
      home: new Branches(),
    ),
  );
}

class ProjectModel {
  BranchSetUpModelData branchesModel;
  ProjectModel(this.branchesModel);
}

class BranchSetUpModelData {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetUpModelData(this.branchName, this.hostelType, this.area, this.city);
}

DatabaseReference _branchesRef;
List<ProjectModel> projectModel = new List();
Map data = {};

List<String> mapKeys = new List();

DataSnapshot dataSnapshot;

class Branches extends StatefulWidget {
  //const BranchView({ Key key }) : super(key: key);
  const Branches({Key key}) : super(key: key);
  @override
  _BranchesState createState() => new _BranchesState();
}

class _BranchesState extends State<Branches> {
  String userUid = '';
  String text;
  int noOfBranches = 0;
  int itemCount;

  Future<Null> getUserUid() async {
    try {
      //FirebaseUser user = await FirebaseAuth.instance.currentUser();
      //userUid = user.uid;
      //print(userUid);
      _branchesRef =
          FirebaseDatabase.instance.reference().child('data').child('branches');
      print('branchesref = $_branchesRef');

      if (_branchesRef != null) {
        try {
          _branchesRef.once().then((DataSnapshot snapShot) {
            dataSnapshot = snapShot;
            print(snapShot is Map);

            print(dataSnapshot.value);
            data = dataSnapshot.value;
            print(data is Map);
            print(data);

            data.forEach((key, value) {
              mapKeys.add(key);
            });
            print('no of branches = $noOfBranches');
            projectModel.clear();
            mapKeys.forEach((value) {
              _branchesRef.child(value).once().then((DataSnapshot b) {
                data = b.value;
                data.keys.forEach((k) {
                  BranchSetUpModelData x = new BranchSetUpModelData(
                    b.value['branchDetails']['branchName'],
                    b.value['branchDetails']['hostelType'],
                    b.value['branchDetails']['area'],
                    b.value['branchDetails']['city'],
                  );
                  print('details from for each loop');
                  ProjectModel projectModelData = new ProjectModel(x);

                  projectModel.add(projectModelData);
                });
                print('projectmodel length = ${projectModel.length}');
              });
            });
            setState(() {
              noOfBranches = mapKeys.length;
              itemCount = noOfBranches;
            });
            print('no of branches = $noOfBranches');

            data.keys.forEach((k) {
              print('inside this foreach loop');
              print(k);
            });
          });
        } catch (Exception) {
          showDialog(
              context: context,
              child: new AlertDialog(
                  content: new Text(Exception.message.toString())));
        }
      } else {
        print('user does not exist');
      }
    } catch (Exception) {
      print(Exception.toString());
      showDialog(
          context: context,
          child: new AlertDialog(
            content: new Text(Exception.toString()),
          ));
    }
  }

  @override
  void initState() {
    super.initState();
    mapKeys.clear();
    FirebaseDatabase.instance.setPersistenceEnabled(true);
    FirebaseDatabase.instance.setPersistenceCacheSizeBytes(10000000);
    getUserUid();
    /*setState((){
      noOfBranches = mapKeys.length;
    });*/
    print('noOfBranches in init state= $noOfBranches');
  }

  @override
  Widget build(BuildContext context) {
    print('noof branches inside widget build = $noOfBranches');
    //if(noOfBranches!=0) {
    return new MaterialApp(
      title: 'Branches',
      theme: new ThemeData(
        primaryColor: const Color(0xFF229E9C),
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Branches'),
          backgroundColor: Colors.teal[300],
        ),
        floatingActionButton: new FloatingActionButton(
          heroTag: 'branchesHeroTag',
          child: new Icon(Icons.add),
          backgroundColor: Colors.teal[300],
          onPressed: (() {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (_) => new AddNewBranch(),
              ),
            );
          }),
          tooltip: 'Add Branch',
        ),
        body: new Container(
          child: new ListView.builder(
            padding: const EdgeInsets.only(
              left: 4.0,
              right: 4.0,
            ),
            itemCount: itemCount,
            itemBuilder: (BuildContext context, int index) {
              if (noOfBranches != 0) {
                // children: <Widget>[

                return new InkWell(
                  onTap: (() {
                    /*Navigate here to a different page*/
                  }),
                  child: new Card(
                    child: new Column(
                      children: <Widget>[
                        new Container(
                          //margin: const EdgeInsets.only(top:16.0),
                          padding: const EdgeInsets.only(top: 16.0),
                          child: new Row(
                            children: <Widget>[
                              new Expanded(
                                child: new Row(
                                  children: <Widget>[
                                    new Container(
                                        margin: const EdgeInsets.only(
                                            left: 16.0,
                                            right: 8.0,
                                            top: 4.0,
                                            bottom: 4.0),
                                        child: new IconButton(
                                            icon: new Icon(Icons.call),
                                            onPressed: (() {}))),
                                    new Container(
                                      child: new Text(
                                        '80/125',
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              new Expanded(
                                child: new Row(
                                  textDirection: TextDirection.rtl,
                                  children: [
                                    new Container(
                                      margin:
                                          const EdgeInsets.only(right: 16.0),
                                      child: new Text(
                                        projectModel[index]
                                            .branchesModel
                                            .hostelType,
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        new Container(
                          margin:
                              const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 4.0),
                          child: new Row(children: <Widget>[
                            new Text(
                              projectModel[index].branchesModel.branchName,
                              style: new TextStyle(
                                fontSize: 24.0,
                              ),
                            ),
                          ]),
                        ),
                        new Container(
                          margin: const EdgeInsets.only(
                              left: 16.0, right: 16.0, bottom: 8.0),
                          child: new Row(
                            children: <Widget>[
                              new Text(projectModel[index].branchesModel.city),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ); // InkWell ends here so this has to go into ListView.builder
              } else {
                itemCount = 1;

                return new Center(
                  child: new Column(
//            mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,

                    children: <Widget>[
                      new Text(
                        'Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 24.0,
                          color: Colors.grey[400],
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      new Text(
                        'Please click below + icon to Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 16.0,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  ),
                );
              }
            },
          ), // ListView.builder ends here.
        ),
      ),
    );
  }
}
</code>```

globals.dart

```<code>library my_app.globals;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';

final FirebaseAuth auth = FirebaseAuth.instance;
final DatabaseReference databaseReference = FirebaseDatabase.instance.reference();
</code>```

addnewbranch.dart

```<code>import 'dart:async';
import 'package:meta/meta.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:untitled1/main.dart';
import './globals.dart' as gl;

class BranchSetupModel {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetupModel(this.branchName, this.hostelType, this.area, this.city);
}

BranchSetupModel branchSetupModel =
    new BranchSetupModel('', 'Hostel Type', '', '');

class AddNewBranch extends StatefulWidget {
  const AddNewBranch({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _AddNewBranchState();
  }
}

class _AddNewBranchState extends State<AddNewBranch> {
  String actionsString = 'Next';
  String userUid;

  TextEditingController _branchNameController = new TextEditingController();
  TextEditingController _areaController = new TextEditingController();
  TextEditingController _cityController = new TextEditingController();

  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  bool _formWasEdited = false;
  bool _autovalidate = false;
  String dropDownvalue = 'Hostel Type';

  //FocusNode _branchManagerNameFocusNode = new FocusNode();

  String _validateName(String value) {
    _formWasEdited = true;
    if (value.isEmpty) return 'Name is required.';
    final RegExp nameExp = new RegExp(r'^[A-Za-z ]+$');
    if (!nameExp.hasMatch(value))
      return 'Please enter only alphabetical characters and spaces.';
    return null;
  }

  Future<Null> getUserUid() async {
    try {
      FirebaseUser user = await FirebaseAuth.instance.currentUser();
      userUid = user.uid;
      print(userUid);
    } catch (Exception) {
      print(Exception.toString());
    }
  }

  @override
  void initState() {
    super.initState();
    getUserUid();
    _branchNameController =
        new TextEditingController(text: branchSetupModel.branchName);
    _areaController = new TextEditingController(text: branchSetupModel.area);
    _cityController = new TextEditingController(text: branchSetupModel.city);
    dropDownvalue = branchSetupModel.hostelType;
    branchSetupModel = new BranchSetupModel('', 'Hostel Type', '', '');
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.teal,
      ),
      title: 'Branch Setup',
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Add New Branch'),
          backgroundColor: Colors.teal[300],
          leading: new IconButton(
            icon: new Icon(Icons.arrow_back),
            onPressed: (() {
              print('back button clicked');
              //to be removed and to include functionality here
              Navigator.push(
                context,
                new MaterialPageRoute(
                  builder: (_) => new Branches(),
                ),
              );
            }),
          ),
          actions: <Widget>[
            new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new FlatButton(
                    child: new Text(
                      actionsString,
                      style: new TextStyle(
                        fontSize: 20.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                    onPressed: () {
                      print('Save button clicked');

                      String pushKey = gl.databaseReference
                          .child('data')
                          .child('branches')
                          .push()
                          .key;
                      gl.databaseReference
                          .child('data')
                          .child('branches')
                          .child(pushKey)
                          .child('branchDetails')
                          .set({
                        "branchName": branchSetupModel.branchName,
                        "hostelType": branchSetupModel.hostelType,
                        "area": branchSetupModel.area,
                        "city": branchSetupModel.city,
                        "pushKey": pushKey
                      });
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                          builder: (_) => new Branches(),
                        ),
                      );
                    },
                    splashColor: const Color(0xFF229E9C),
                  ),
                ],
              ),
            ),
          ],
        ),
        body: new Form(
          key: _formKey,
          child: new ListView(
            children: <Widget>[
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Text('Hostel Type'),
                  ],
                ),
              ),
              new Container(
                //height: 56.0,
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Column(
                  children: <Widget>[
                    new DropdownButton<String>(
                      //key: _dropDownKey,
                      hint: new Text(dropDownvalue),

                      items: <String>[
                        'Mens',
                        'Womens',
                      ].map(
                        (String value) {
                          return new DropdownMenuItem<String>(
                            value: value,
                            child: new Text(value),
                          );
                        },
                      ).toList(),
                      onChanged: (String value) {
                        setState(() {
                          dropDownvalue = value;
                          branchSetupModel.hostelType = value;
                          print(branchSetupModel.hostelType);
                        });
                      },
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        autocorrect: false,
                        decoration: new InputDecoration(
                          labelText: 'Branch Name',
                        ),
                        controller: _branchNameController,
                        onChanged: (String value) {
                          branchSetupModel.branchName =
                              _branchNameController.text;
                          print(branchSetupModel.branchName);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'Area/Location',
                        ),
                        controller: _areaController,
                        onChanged: (String value) {
                          branchSetupModel.area = value;
                          print(branchSetupModel.area);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                ),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'City',
                        ),
                        controller: _cityController,
                        onChanged: (String value) {
                          branchSetupModel.city = value;
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

pubspec.yaml

```<code>name: untitled1
description: A new Flutter project.

dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^1.0.1
  firebase_analytics: ^0.1.1
  firebase_auth: ^0.3.1
  firebase_database: ^0.1.2
  firebase_storage: ^0.0.7

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
</code>```

Please integrate the firebase app to run the code before trying to reproduce the error and make sure the read and write access set to 'true' as I have not added any authentication.

As far as I know the error only occurs in the main.dart file.It works fine for a few times and then the errors start coming in. First, it throws up the error RangeError (index): Invalid value: Valid value range is empty: 0 this error is for the ListView.builder() and then the other two assertion errors come up.

Please can someone tell me what I am doing wrong or is there a different way to achieve the same goal without these errors.

output from flutter doctor command.

```<code>    [√] Flutter (on Microsoft Windows [Version 10.0.15063], locale en-GB, channel alpha)
    • Flutter at C:\Users\Prayuta\flutter
    • Framework revision e8aa40eddd (3 weeks ago), 2017-10-17 15:42:40 -0700
    • Engine revision 7c4142808c
    • Tools Dart version 1.25.0-dev.11.0

[√] Android toolchain - develop for Android devices (Android SDK 27.0.0)
    • Android SDK at C:\Users\Prayuta\AppData\Local\Android\sdk
    • Platform android-27, build-tools 27.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] Android Studio (version 3.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] IntelliJ IDEA Community Edition (version 2017.2)
    • Flutter plugin version 18.4
    • Dart plugin version 172.4343.25

[√] Connected devices
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.1.1 (API 25) (emulator)

Process finished with exit code 0.
</code>```

答:
This error happens due to incorrect widget configuration, so in other words it's not an error itself, but a symptom of another error.

For OP

OP has already found a solution so I won't elaborate on it. Fixing the error in your ListView should do the trick.

TL;DR

Try:

Calling super.initState() inside all your StatefulWidgets.initState() overrides.

Making sure all your Widget.keys are unique.

Making sure all your widgets that use a builder function have no errors. These widgets include AnimatedBuilder, LayoutBuilder, and external packages like GetX or Provider that have a builder, and any packages that depend on them (like Bloc). With these builder widgets, the exception usually occurs when you build the same Widget with different instance members based on some passed value. For example:

```<code>...
BlocBuilder<MyBloc, MyState>(
  builder: (context, state) => Container(
    color: state is SomeState ? Colors.blue : Colors.red, // Something along these lines
  ),
)

// or
BlocBuilder<MyBloc, MyState>(
  builder: (context, state) => state is SomeState ? Container(color: Colors.red) : Container(color: Colors.blue),
)
....
</code>```

More Explanation

First of all, I want to note that while the exception message is a bit misleading, the flutter team had a couple TODOs to make the exception clearer and refer specifically to the faulty widget.

As the message mentions, the error is related to duplicate GlobalKeys within the widget tree. Usually, this doesn't happen due to directly using the same Key on two different widgets (because devs are usually aware of that). Instead, it hides itself behind other issues such as the ones mentioned above. They all produce similar effect, however: They cause errors in the widget's lifecycle state.

Forgetting to call initState, for instance, messes up the widget's lifecycle state update. I'm not exactly sure exactly where this happens, but it seems that the framework creates duplicate element/widget to the same widget with the same GlobalKey if the widget's lifecycle state is tampered with. This needs further investigation and confirmation.

The thing with builder widgets is that if the first widget to be returned from the builder has an exception, the framework will mount it, but for some reason, the lifecycle change will not occur when the second widget to be returned from builder is inserted in the tree, and both the first and the second widgets end up with the same Key.

In both cases, when the framework unmounts currently active widgets, it checks widgets' lifecycle state, determines which ones are inactive, and ignores them. However, because lifecycle states of some widgets are wrong, it might treat an inactive widget as active, compare it to currently active widgets only to find duplicates, and then throw the exception.

If you want to check that yourself, you can read src/widgets/framework.dart file referred to in the error message, starting from BuilderOwner.finalizeTree() function.

Body:
I am back again with the issue related to the question already posted by me on stack overflow Error: '_elements.contains(element)': is not true

this issue has been plaguing me but i was unable to reproduce the same issue and now i have somehow tried to repro again and I have posted the code for everyone to figure out what is it that i am doing wrong that's throwing up this assertion error and crashing the app.

I am new to programming and any help would be greatly appreciated. I have trimmed down the code and I am aware of the some of the bugs. But, the only main concern is the Failed assertion: line 3927 pos 14: '_dependents.isEmpty': is not true. and Failed assertion: line 1766 pos 12: '_elements.contains(element)': is not true.

Steps to reproduce.

main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:untitled1/addnewbranch.dart';

void main() {
  runApp(
    new MaterialApp(
      home: new Branches(),
    ),
  );
}

class ProjectModel {
  BranchSetUpModelData branchesModel;
  ProjectModel(this.branchesModel);
}

class BranchSetUpModelData {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetUpModelData(this.branchName, this.hostelType, this.area, this.city);
}

DatabaseReference _branchesRef;
List<ProjectModel> projectModel = new List();
Map data = {};

List<String> mapKeys = new List();

DataSnapshot dataSnapshot;

class Branches extends StatefulWidget {
  //const BranchView({ Key key }) : super(key: key);
  const Branches({Key key}) : super(key: key);
  @override
  _BranchesState createState() => new _BranchesState();
}

class _BranchesState extends State<Branches> {
  String userUid = '';
  String text;
  int noOfBranches = 0;
  int itemCount;

  Future<Null> getUserUid() async {
    try {
      //FirebaseUser user = await FirebaseAuth.instance.currentUser();
      //userUid = user.uid;
      //print(userUid);
      _branchesRef =
          FirebaseDatabase.instance.reference().child('data').child('branches');
      print('branchesref = $_branchesRef');

      if (_branchesRef != null) {
        try {
          _branchesRef.once().then((DataSnapshot snapShot) {
            dataSnapshot = snapShot;
            print(snapShot is Map);

            print(dataSnapshot.value);
            data = dataSnapshot.value;
            print(data is Map);
            print(data);

            data.forEach((key, value) {
              mapKeys.add(key);
            });
            print('no of branches = $noOfBranches');
            projectModel.clear();
            mapKeys.forEach((value) {
              _branchesRef.child(value).once().then((DataSnapshot b) {
                data = b.value;
                data.keys.forEach((k) {
                  BranchSetUpModelData x = new BranchSetUpModelData(
                    b.value['branchDetails']['branchName'],
                    b.value['branchDetails']['hostelType'],
                    b.value['branchDetails']['area'],
                    b.value['branchDetails']['city'],
                  );
                  print('details from for each loop');
                  ProjectModel projectModelData = new ProjectModel(x);

                  projectModel.add(projectModelData);
                });
                print('projectmodel length = ${projectModel.length}');
              });
            });
            setState(() {
              noOfBranches = mapKeys.length;
              itemCount = noOfBranches;
            });
            print('no of branches = $noOfBranches');

            data.keys.forEach((k) {
              print('inside this foreach loop');
              print(k);
            });
          });
        } catch (Exception) {
          showDialog(
              context: context,
              child: new AlertDialog(
                  content: new Text(Exception.message.toString())));
        }
      } else {
        print('user does not exist');
      }
    } catch (Exception) {
      print(Exception.toString());
      showDialog(
          context: context,
          child: new AlertDialog(
            content: new Text(Exception.toString()),
          ));
    }
  }

  @override
  void initState() {
    super.initState();
    mapKeys.clear();
    FirebaseDatabase.instance.setPersistenceEnabled(true);
    FirebaseDatabase.instance.setPersistenceCacheSizeBytes(10000000);
    getUserUid();
    /*setState((){
      noOfBranches = mapKeys.length;
    });*/
    print('noOfBranches in init state= $noOfBranches');
  }

  @override
  Widget build(BuildContext context) {
    print('noof branches inside widget build = $noOfBranches');
    //if(noOfBranches!=0) {
    return new MaterialApp(
      title: 'Branches',
      theme: new ThemeData(
        primaryColor: const Color(0xFF229E9C),
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Branches'),
          backgroundColor: Colors.teal[300],
        ),
        floatingActionButton: new FloatingActionButton(
          heroTag: 'branchesHeroTag',
          child: new Icon(Icons.add),
          backgroundColor: Colors.teal[300],
          onPressed: (() {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (_) => new AddNewBranch(),
              ),
            );
          }),
          tooltip: 'Add Branch',
        ),
        body: new Container(
          child: new ListView.builder(
            padding: const EdgeInsets.only(
              left: 4.0,
              right: 4.0,
            ),
            itemCount: itemCount,
            itemBuilder: (BuildContext context, int index) {
              if (noOfBranches != 0) {
                // children: <Widget>[

                return new InkWell(
                  onTap: (() {
                    /*Navigate here to a different page*/
                  }),
                  child: new Card(
                    child: new Column(
                      children: <Widget>[
                        new Container(
                          //margin: const EdgeInsets.only(top:16.0),
                          padding: const EdgeInsets.only(top: 16.0),
                          child: new Row(
                            children: <Widget>[
                              new Expanded(
                                child: new Row(
                                  children: <Widget>[
                                    new Container(
                                        margin: const EdgeInsets.only(
                                            left: 16.0,
                                            right: 8.0,
                                            top: 4.0,
                                            bottom: 4.0),
                                        child: new IconButton(
                                            icon: new Icon(Icons.call),
                                            onPressed: (() {}))),
                                    new Container(
                                      child: new Text(
                                        '80/125',
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              new Expanded(
                                child: new Row(
                                  textDirection: TextDirection.rtl,
                                  children: [
                                    new Container(
                                      margin:
                                          const EdgeInsets.only(right: 16.0),
                                      child: new Text(
                                        projectModel[index]
                                            .branchesModel
                                            .hostelType,
                                        style: new TextStyle(
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        new Container(
                          margin:
                              const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 4.0),
                          child: new Row(children: <Widget>[
                            new Text(
                              projectModel[index].branchesModel.branchName,
                              style: new TextStyle(
                                fontSize: 24.0,
                              ),
                            ),
                          ]),
                        ),
                        new Container(
                          margin: const EdgeInsets.only(
                              left: 16.0, right: 16.0, bottom: 8.0),
                          child: new Row(
                            children: <Widget>[
                              new Text(projectModel[index].branchesModel.city),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ); // InkWell ends here so this has to go into ListView.builder
              } else {
                itemCount = 1;

                return new Center(
                  child: new Column(
//            mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,

                    children: <Widget>[
                      new Text(
                        'Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 24.0,
                          color: Colors.grey[400],
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      new Text(
                        'Please click below + icon to Setup your Hostel',
                        style: new TextStyle(
                          fontSize: 16.0,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  ),
                );
              }
            },
          ), // ListView.builder ends here.
        ),
      ),
    );
  }
}

globals.dart

library my_app.globals;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';

final FirebaseAuth auth = FirebaseAuth.instance;
final DatabaseReference databaseReference = FirebaseDatabase.instance.reference();

addnewbranch.dart

import 'dart:async';
import 'package:meta/meta.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:untitled1/main.dart';
import './globals.dart' as gl;

class BranchSetupModel {
  String branchName;
  String hostelType;
  String area;
  String city;
  BranchSetupModel(this.branchName, this.hostelType, this.area, this.city);
}

BranchSetupModel branchSetupModel =
    new BranchSetupModel('', 'Hostel Type', '', '');

class AddNewBranch extends StatefulWidget {
  const AddNewBranch({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _AddNewBranchState();
  }
}

class _AddNewBranchState extends State<AddNewBranch> {
  String actionsString = 'Next';
  String userUid;

  TextEditingController _branchNameController = new TextEditingController();
  TextEditingController _areaController = new TextEditingController();
  TextEditingController _cityController = new TextEditingController();

  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  bool _formWasEdited = false;
  bool _autovalidate = false;
  String dropDownvalue = 'Hostel Type';

  //FocusNode _branchManagerNameFocusNode = new FocusNode();

  String _validateName(String value) {
    _formWasEdited = true;
    if (value.isEmpty) return 'Name is required.';
    final RegExp nameExp = new RegExp(r'^[A-Za-z ]+$');
    if (!nameExp.hasMatch(value))
      return 'Please enter only alphabetical characters and spaces.';
    return null;
  }

  Future<Null> getUserUid() async {
    try {
      FirebaseUser user = await FirebaseAuth.instance.currentUser();
      userUid = user.uid;
      print(userUid);
    } catch (Exception) {
      print(Exception.toString());
    }
  }

  @override
  void initState() {
    super.initState();
    getUserUid();
    _branchNameController =
        new TextEditingController(text: branchSetupModel.branchName);
    _areaController = new TextEditingController(text: branchSetupModel.area);
    _cityController = new TextEditingController(text: branchSetupModel.city);
    dropDownvalue = branchSetupModel.hostelType;
    branchSetupModel = new BranchSetupModel('', 'Hostel Type', '', '');
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.teal,
      ),
      title: 'Branch Setup',
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Add New Branch'),
          backgroundColor: Colors.teal[300],
          leading: new IconButton(
            icon: new Icon(Icons.arrow_back),
            onPressed: (() {
              print('back button clicked');
              //to be removed and to include functionality here
              Navigator.push(
                context,
                new MaterialPageRoute(
                  builder: (_) => new Branches(),
                ),
              );
            }),
          ),
          actions: <Widget>[
            new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new FlatButton(
                    child: new Text(
                      actionsString,
                      style: new TextStyle(
                        fontSize: 20.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                    onPressed: () {
                      print('Save button clicked');

                      String pushKey = gl.databaseReference
                          .child('data')
                          .child('branches')
                          .push()
                          .key;
                      gl.databaseReference
                          .child('data')
                          .child('branches')
                          .child(pushKey)
                          .child('branchDetails')
                          .set({
                        "branchName": branchSetupModel.branchName,
                        "hostelType": branchSetupModel.hostelType,
                        "area": branchSetupModel.area,
                        "city": branchSetupModel.city,
                        "pushKey": pushKey
                      });
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                          builder: (_) => new Branches(),
                        ),
                      );
                    },
                    splashColor: const Color(0xFF229E9C),
                  ),
                ],
              ),
            ),
          ],
        ),
        body: new Form(
          key: _formKey,
          child: new ListView(
            children: <Widget>[
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Text('Hostel Type'),
                  ],
                ),
              ),
              new Container(
                //height: 56.0,
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Column(
                  children: <Widget>[
                    new DropdownButton<String>(
                      //key: _dropDownKey,
                      hint: new Text(dropDownvalue),

                      items: <String>[
                        'Mens',
                        'Womens',
                      ].map(
                        (String value) {
                          return new DropdownMenuItem<String>(
                            value: value,
                            child: new Text(value),
                          );
                        },
                      ).toList(),
                      onChanged: (String value) {
                        setState(() {
                          dropDownvalue = value;
                          branchSetupModel.hostelType = value;
                          print(branchSetupModel.hostelType);
                        });
                      },
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        autocorrect: false,
                        decoration: new InputDecoration(
                          labelText: 'Branch Name',
                        ),
                        controller: _branchNameController,
                        onChanged: (String value) {
                          branchSetupModel.branchName =
                              _branchNameController.text;
                          print(branchSetupModel.branchName);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'Area/Location',
                        ),
                        controller: _areaController,
                        onChanged: (String value) {
                          branchSetupModel.area = value;
                          print(branchSetupModel.area);
                        },
                        //validator: _validateName,
                      ),
                    ),
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                ),
                child: new Row(
                  children: <Widget>[
                    new Expanded(
                      child: new TextField(
                        decoration: new InputDecoration(
                          labelText: 'City',
                        ),
                        controller: _cityController,
                        onChanged: (String value) {
                          branchSetupModel.city = value;
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

pubspec.yaml

name: untitled1
description: A new Flutter project.

dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^1.0.1
  firebase_analytics: ^0.1.1
  firebase_auth: ^0.3.1
  firebase_database: ^0.1.2
  firebase_storage: ^0.0.7

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

Please integrate the firebase app to run the code before trying to reproduce the error and make sure the read and write access set to 'true' as I have not added any authentication.

As far as I know the error only occurs in the main.dart file.It works fine for a few times and then the errors start coming in. First, it throws up the error RangeError (index): Invalid value: Valid value range is empty: 0 this error is for the ListView.builder() and then the other two assertion errors come up.

Please can someone tell me what I am doing wrong or is there a different way to achieve the same goal without these errors.

output from flutter doctor command.

    [√] Flutter (on Microsoft Windows [Version 10.0.15063], locale en-GB, channel alpha)
    • Flutter at C:\Users\Prayuta\flutter
    • Framework revision e8aa40eddd (3 weeks ago), 2017-10-17 15:42:40 -0700
    • Engine revision 7c4142808c
    • Tools Dart version 1.25.0-dev.11.0

[√] Android toolchain - develop for Android devices (Android SDK 27.0.0)
    • Android SDK at C:\Users\Prayuta\AppData\Local\Android\sdk
    • Platform android-27, build-tools 27.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] Android Studio (version 3.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[√] IntelliJ IDEA Community Edition (version 2017.2)
    • Flutter plugin version 18.4
    • Dart plugin version 172.4343.25

[√] Connected devices
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.1.1 (API 25) (emulator)

Process finished with exit code 0.

Body:
This error happens due to incorrect widget configuration, so in other words it's not an error itself, but a symptom of another error.

For OP

OP has already found a solution so I won't elaborate on it. Fixing the error in your ListView should do the trick.

TL;DR

Try:

Calling super.initState() inside all your StatefulWidgets.initState() overrides.

Making sure all your Widget.keys are unique.

Making sure all your widgets that use a builder function have no errors. These widgets include AnimatedBuilder, LayoutBuilder, and external packages like GetX or Provider that have a builder, and any packages that depend on them (like Bloc). With these builder widgets, the exception usually occurs when you build the same Widget with different instance members based on some passed value. For example:

...
BlocBuilder<MyBloc, MyState>(
  builder: (context, state) => Container(
    color: state is SomeState ? Colors.blue : Colors.red, // Something along these lines
  ),
)

// or
BlocBuilder<MyBloc, MyState>(
  builder: (context, state) => state is SomeState ? Container(color: Colors.red) : Container(color: Colors.blue),
)
....

More Explanation

First of all, I want to note that while the exception message is a bit misleading, the flutter team had a couple TODOs to make the exception clearer and refer specifically to the faulty widget.

As the message mentions, the error is related to duplicate GlobalKeys within the widget tree. Usually, this doesn't happen due to directly using the same Key on two different widgets (because devs are usually aware of that). Instead, it hides itself behind other issues such as the ones mentioned above. They all produce similar effect, however: They cause errors in the widget's lifecycle state.

Forgetting to call initState, for instance, messes up the widget's lifecycle state update. I'm not exactly sure exactly where this happens, but it seems that the framework creates duplicate element/widget to the same widget with the same GlobalKey if the widget's lifecycle state is tampered with. This needs further investigation and confirmation.

The thing with builder widgets is that if the first widget to be returned from the builder has an exception, the framework will mount it, but for some reason, the lifecycle change will not occur when the second widget to be returned from builder is inserted in the tree, and both the first and the second widgets end up with the same Key.

In both cases, when the framework unmounts currently active widgets, it checks widgets' lifecycle state, determines which ones are inactive, and ignores them. However, because lifecycle states of some widgets are wrong, it might treat an inactive widget as active, compare it to currently active widgets only to find duplicates, and then throw the exception.

If you want to check that yourself, you can read src/widgets/framework.dart file referred to in the error message, starting from BuilderOwner.finalizeTree() function.


来源: stackexchange

问:
index-error: string out of range in wordle similar game
So i'm making a Wordle clone and i keep getting a "indexerror: string is out of range" and i dont know what to do and every time i do the second guess it will say indexerrror string is out off range
at line 30</p>
```<code>import random

def Wordle():

    position = 0
    clue = ""

    print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")

    user_name = input("Enter your name:")

    valid_words = ['sweet','shark','about','maybe','tweet','shard','pleat','elder','table','birds','among','share','label','frame','water','earth','winds','empty','audio','pilot','radio','steel','words','chair','drips','mouse','moose','beach','cloud','yours','house','holes','short','small','large','glass','ruler','boxes','charm','tools']

    TheAnswer = random.choice(valid_words)

    print(TheAnswer)

    number_of_guesses = 1

    guessed_correct = False

    while number_of_guesses < 7 and not guessed_correct:
        print('       ')
        TheGuess = input('Enter your guess (it have to be a 5-letter word and not captalied letters):')
        if len(TheGuess) > 5:
            print('word is not acceptable')
        else:
            print('    ')
        for letter in TheGuess:
            if letter == TheAnswer[position]:
                clue += ' V'
            elif letter in TheAnswer:
                clue += ' O'
            else:
                 clue += ' F'
            position += 1
        print(clue)
        if TheGuess == TheAnswer:
            guessed_correct = True
        else:
            guessed_correct = False
            number_of_guesses += 1
        clue = ""

    if guessed_correct:
        print('Congradulations', user_name,', you won and only used', number_of_guesses,'guesses, :D')
    else:
        print(user_name,'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)
</code>```

答:
You are indexing TheAnswer[position] which basically means if TheAnswer is x length long, then the position should be,

But since the position variable is a local variable of the function, it continuously increases on each guess. Does not get reset on each guess.

Try moving the

position = 0
```
<p>Into top of the while loop.</p>
<h3>Code,</h3>
<pre class="lang-py prettyprint-override"><code>import random

def Wordle():
    clue = ""
    print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")
    user_name = input("Enter your name:")

    valid_words = ['sweet', 'shark', 'about', 'maybe', 'tweet', 'shard', 'pleat', 'elder', 'table', 'birds', 'among', 'share', 'label', 'frame', 'water', 'earth', 'winds', 'empty', 'audio',
                   'pilot', 'radio', 'steel', 'words', 'chair', 'drips', 'mouse', 'moose', 'beach', 'cloud', 'yours', 'house', 'holes', 'short', 'small', 'large', 'glass', 'ruler', 'boxes', 'charm', 'tools']
    TheAnswer = random.choice(valid_words)

    print(TheAnswer)
    number_of_guesses = 1
    guessed_correct = False

    while number_of_guesses < 7 and not guessed_correct:
        position = 0
        print('       ')
        TheGuess = input(
            'Enter your guess (it have to be a 5-letter word and not captalied letters):')
        if len(TheGuess) > 5:
            print('word is not acceptable')
        else:
            print('    ')
        for letter in TheGuess:
            if letter == TheAnswer[position]:
                clue += ' V'
            elif letter in TheAnswer:
                clue += ' O'
            else:
                clue += ' F'
            position += 1
        print(clue)
        if TheGuess == TheAnswer:
            guessed_correct = True
        else:
            guessed_correct = False
            number_of_guesses += 1
        clue = ""

    if guessed_correct:
        print('Congradulations', user_name, ', you won and only used',
              number_of_guesses, 'guesses, :D')
    else:
        print(
            user_name, 'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)
</code>```

Thanks!

ContentLicense: CC BY-SA 4.0

Body:
So i'm making a Wordle clone and i keep getting a "indexerror: string is out of range" and i dont know what to do and every time i do the second guess it will say indexerrror string is out off range
at line 30

import random

def Wordle():

    position = 0
    clue = ""

    print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")

    user_name = input("Enter your name:")

    valid_words = ['sweet','shark','about','maybe','tweet','shard','pleat','elder','table','birds','among','share','label','frame','water','earth','winds','empty','audio','pilot','radio','steel','words','chair','drips','mouse','moose','beach','cloud','yours','house','holes','short','small','large','glass','ruler','boxes','charm','tools']

    TheAnswer = random.choice(valid_words)

    print(TheAnswer)

    number_of_guesses = 1

    guessed_correct = False

    while number_of_guesses < 7 and not guessed_correct:
        print('       ')
        TheGuess = input('Enter your guess (it have to be a 5-letter word and not captalied letters):')
        if len(TheGuess) > 5:
            print('word is not acceptable')
        else:
            print('    ')
        for letter in TheGuess:
            if letter == TheAnswer[position]:
                clue += ' V'
            elif letter in TheAnswer:
                clue += ' O'
            else:
                 clue += ' F'
            position += 1
        print(clue)
        if TheGuess == TheAnswer:
            guessed_correct = True
        else:
            guessed_correct = False
            number_of_guesses += 1
        clue = ""

    if guessed_correct:
        print('Congradulations', user_name,', you won and only used', number_of_guesses,'guesses, :D')
    else:
        print(user_name,'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)

Body:
You are indexing TheAnswer[position] which basically means if TheAnswer is x length long, then the position should be,

But since the position variable is a local variable of the function, it continuously increases on each guess. Does not get reset on each guess.

Try moving the

position = 0

Into top of the while loop.

Code,

import random

def Wordle():
    clue = ""
    print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")
    user_name = input("Enter your name:")

    valid_words = ['sweet', 'shark', 'about', 'maybe', 'tweet', 'shard', 'pleat', 'elder', 'table', 'birds', 'among', 'share', 'label', 'frame', 'water', 'earth', 'winds', 'empty', 'audio',
                   'pilot', 'radio', 'steel', 'words', 'chair', 'drips', 'mouse', 'moose', 'beach', 'cloud', 'yours', 'house', 'holes', 'short', 'small', 'large', 'glass', 'ruler', 'boxes', 'charm', 'tools']
    TheAnswer = random.choice(valid_words)

    print(TheAnswer)
    number_of_guesses = 1
    guessed_correct = False

    while number_of_guesses < 7 and not guessed_correct:
        position = 0
        print('       ')
        TheGuess = input(
            'Enter your guess (it have to be a 5-letter word and not captalied letters):')
        if len(TheGuess) > 5:
            print('word is not acceptable')
        else:
            print('    ')
        for letter in TheGuess:
            if letter == TheAnswer[position]:
                clue += ' V'
            elif letter in TheAnswer:
                clue += ' O'
            else:
                clue += ' F'
            position += 1
        print(clue)
        if TheGuess == TheAnswer:
            guessed_correct = True
        else:
            guessed_correct = False
            number_of_guesses += 1
        clue = ""

    if guessed_correct:
        print('Congradulations', user_name, ', you won and only used',
              number_of_guesses, 'guesses, :D')
    else:
        print(
            user_name, 'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)

Thanks!


问:
Issues with threading in c#
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

```<code>private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}
</code>```

I tried threading it out like this:

```<code>System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));
</code>```

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

答:
The System.Threading.Thread constructor takes a delegate as it's parameter.
Try </p>

```<code>newThread = new System.Threading.Thread(new ParameterizedThreadStart(callValueEng));
newThread.start(translatedParams);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Issues with threading in c#

Body:
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}

I tried threading it out like this:

System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

Body:
The System.Threading.Thread constructor takes a delegate as it's parameter.
Try

newThread = new System.Threading.Thread(new ParameterizedThreadStart(callValueEng));
newThread.start(translatedParams);


问:
Handle a view visibility change without overriding the view
Is there a way to handle a view visibility change (say, from GONE to VISIBLE) without overriding the view?

Something like View.setOnVisibilityChangeListener();?

答:
In addition to @string.Empty's solution, this is an extension implementation for Kotlin.

```<code>fun View.visibilityChanged(action: (View) -> Unit) {
    this.viewTreeObserver.addOnGlobalLayoutListener {
        val newVis: Int = this.visibility
        if (this.tag as Int? != newVis) {
            this.tag = this.visibility

            // visibility has changed
            action(this)
        }
    }
}
</code>```

Implement it like this

```<code>myView.visibilityChanged { view ->
    when (view.visibility) {
        VISIBLE -> { /* Do something here */ }
        GONE -> { /* or here */ }
    }

}
</code>```

Body:
In addition to @string.Empty's solution, this is an extension implementation for Kotlin.

fun View.visibilityChanged(action: (View) -> Unit) {
    this.viewTreeObserver.addOnGlobalLayoutListener {
        val newVis: Int = this.visibility
        if (this.tag as Int? != newVis) {
            this.tag = this.visibility

            // visibility has changed
            action(this)
        }
    }
}

Implement it like this

myView.visibilityChanged { view ->
    when (view.visibility) {
        VISIBLE -> { /* Do something here */ }
        GONE -> { /* or here */ }
    }

}


问:
Angular 11 any/undefined types warnings
I upgraded my app from Angular v10 to v11 and now I get multiple errors and warnings because some (maybe all) fields can be undefined in a time:

for example:

```<code>const savedToken = new Token(JSON.parse(localStorage.getItem(AuthInterceptor.tokenKey)));
</code>```

must become:

```<code>const savedToken = new Token(JSON.parse(<string>localStorage.getItem(AuthInterceptor.tokenKey)));
</code>```

warning:

```<code>Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'
// I know the localStorage value can be null in this case.
</code>```

another example:

```<code>public user$: Observable<User>;
// Property 'user$' has no initializer and is not definitely assigned in the constructor.
</code>```

because the user$ is initialized in ngOnInit() as this.user$ = this.store.pipe()...

How did you solve it?

Even if I deactivate strict from angular.json, the result is same:

```<code>"@schematics/angular:application": {
    "strict": false
}
</code>```

I really need to update all my app code line by line to angular 11? thanks

答:
in ts.config file you just have to change strict:"true" to strict:"false"

"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": false,

THEN IF IT STILL SHOWS ERROR RESTART VISUAL STUDIO CODE IDE!!!

Title: Angular 11 any/undefined types warnings

Body:
I upgraded my app from Angular v10 to v11 and now I get multiple errors and warnings because some (maybe all) fields can be undefined in a time:

for example:

const savedToken = new Token(JSON.parse(localStorage.getItem(AuthInterceptor.tokenKey)));

must become:

const savedToken = new Token(JSON.parse(<string>localStorage.getItem(AuthInterceptor.tokenKey)));

warning:

Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'
// I know the localStorage value can be null in this case.

another example:

public user$: Observable<User>;
// Property 'user$' has no initializer and is not definitely assigned in the constructor.

because the user$ is initialized in ngOnInit() as this.user$ = this.store.pipe()...

How did you solve it?

Even if I deactivate strict from angular.json, the result is same:

"@schematics/angular:application": {
    "strict": false
}

I really need to update all my app code line by line to angular 11? thanks


问:
Prediction Interval for Neural Net in Python
I'm currently using keras to create a neural net in python. I have a basic model and the code looks like this:

```<code>    from keras.layers import Dense
    from keras.models import Sequential

    model = Sequential()
    model.add(Dense(23, input_dim=23, kernel_initializer='normal', activation='relu'))
    model.add(Dense(500, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal', activation="relu"))
    model.compile(loss='mean_squared_error', optimizer='adam')
</code>```

It works well and gives me good predictions for my use case. However, I would like to be able to use a Variational Gaussian Process layer to give me an estimate for the prediction interval as well. I'm new to this type of layer and am struggling a bit to implement it. The tensorflow documentation on it can be found here:

https://www.tensorflow.org/probability/api_docs/python/tfp/layers/VariationalGaussianProcess

However, I'm not seeing that same layer in the keras library. For further reference, I'm trying to do something similar to what was done in this article:

https://blog.tensorflow.org/2019/03/regression-with-probabilistic-layers-in.html

There seems to be a bit more complexity when you have 23 inputs vs one that I'm not understanding. I'm also open to other methods to achieving the target objective. Any examples on how to do this or insights on other approaches would be greatly appreciated!

答:
tensorflow_probability is a separate library but suitable to use with Keras and TensorFlow. You can add those custom layers in your code and change it to a probabilistic model. If your goal is just to get a prediction interval it would be simpler to use the DistributionLambda layer. So your code would be as follows:

from keras.layers import Dense
from keras.models import Sequential
from sklearn.datasets import make_regression
import tensorflow_probability as tfp
import tensorflow as tf
tfd = tfp.distributions

# Sample data
X, y = make_regression(n_samples=100, n_features=23, noise=4.0, bias=15)

# loss function Negative log likelyhood
negloglik = lambda y, p_y: -p_y.log_prob(y)

# Model
model = Sequential()
model.add(Dense(23, input_dim=23, kernel_initializer='normal', activation='relu'))
model.add(Dense(500, kernel_initializer='normal', activation='relu'))
model.add(Dense(2))
model.add(tfp.layers.DistributionLambda(
      lambda t: tfd.Normal(loc=t[..., :1],
                           scale=1e-3 + tf.math.softplus(0.05 * t[..., 1:]))))

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

model.fit(X,y, epochs=250, verbose=None)
```
<p><img src="https://i.stack.imgur.com/6uVRe.png" alt="enter image description here" /></p>
<p>After training your model, you can get your prediction distribution with the following lines:</p>
<pre class="lang-py prettyprint-override"><code>yhat = model(X) # make predictions
means = yhat.mean() # prediction means
stds = yhat.stddev() # prediction standard deviation
</code>```

Body:
I'm currently using keras to create a neural net in python. I have a basic model and the code looks like this:

    from keras.layers import Dense
    from keras.models import Sequential

    model = Sequential()
    model.add(Dense(23, input_dim=23, kernel_initializer='normal', activation='relu'))
    model.add(Dense(500, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal', activation="relu"))
    model.compile(loss='mean_squared_error', optimizer='adam')

It works well and gives me good predictions for my use case. However, I would like to be able to use a Variational Gaussian Process layer to give me an estimate for the prediction interval as well. I'm new to this type of layer and am struggling a bit to implement it. The tensorflow documentation on it can be found here:

https://www.tensorflow.org/probability/api_docs/python/tfp/layers/VariationalGaussianProcess

However, I'm not seeing that same layer in the keras library. For further reference, I'm trying to do something similar to what was done in this article:

https://blog.tensorflow.org/2019/03/regression-with-probabilistic-layers-in.html

There seems to be a bit more complexity when you have 23 inputs vs one that I'm not understanding. I'm also open to other methods to achieving the target objective. Any examples on how to do this or insights on other approaches would be greatly appreciated!

Body:
tensorflow_probability is a separate library but suitable to use with Keras and TensorFlow. You can add those custom layers in your code and change it to a probabilistic model. If your goal is just to get a prediction interval it would be simpler to use the DistributionLambda layer. So your code would be as follows:

from keras.layers import Dense
from keras.models import Sequential
from sklearn.datasets import make_regression
import tensorflow_probability as tfp
import tensorflow as tf
tfd = tfp.distributions

# Sample data
X, y = make_regression(n_samples=100, n_features=23, noise=4.0, bias=15)

# loss function Negative log likelyhood
negloglik = lambda y, p_y: -p_y.log_prob(y)

# Model
model = Sequential()
model.add(Dense(23, input_dim=23, kernel_initializer='normal', activation='relu'))
model.add(Dense(500, kernel_initializer='normal', activation='relu'))
model.add(Dense(2))
model.add(tfp.layers.DistributionLambda(
      lambda t: tfd.Normal(loc=t[..., :1],
                           scale=1e-3 + tf.math.softplus(0.05 * t[..., 1:]))))

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

model.fit(X,y, epochs=250, verbose=None)

After training your model, you can get your prediction distribution with the following lines:

yhat = model(X) # make predictions
means = yhat.mean() # prediction means
stds = yhat.stddev() # prediction standard deviation


问:
How to specify output name of cc_binary target
I'd like to build a simple application and to specify its output name: for debug version 'd' prefix should be added. I tried to use genrule for it, but I don't know how to change this option in different compilation modes. However I suppose that using genrule is not correct way.

So, how to specify output name?

```<code>cc_binary(
    name = "TestApp",
    srcs = [
        "src/TestApp/main.cpp",
    ],
)

genrule(
    name = "output_name_rule",
    srcs = [":TestApp"],
    outs = ["TestAppd.exe"],
    output_to_bindir = True,
    cmd_bat = "rename $(location TestApp) TestAppd.exe"
    )

config_setting(
    name = "release_build",
    values = {
        "compilation_mode":"opt"
    }
)

config_setting(
    name = "debug_build",
    values = {
        "compilation_mode":"dbg"
    }
)
</code>```

答:
genrule.outs is documented as nonconfigurable, so you can't use it directly. I would create a genrule that copies the file that exists in all configurations, and then choose between the genrule and the original cc_binary based on the configuration. Something like this:

genrule(
    name = "copy_with_d",
    srcs = [":TestApp"],
    outs = ["TestAppd.exe"],
    output_to_bindir = True,
    cmd_bat = "rename $(location TestApp) TestAppd.exe"
)

alias(
    name = "maybe_with_d",
    actual = select({
        ":debug_build": "TestAppd.exe",
        "//conditions:default": "TestApp.exe",
    }),
)
```

Some notes on things to tweak for your use case:

On Linux, I would write cmd = "cp $< $@". I'm not sure how Windows rename handles the input not being writable. You can definitely write $< and $@ instead of repeating the filenames though, they are Bazel "Make" variables.

I put the non-d version as //conditions:default so it applies in fastbuild too, up to you which way you want as the default.

Up to you whether you use TestApp.exe or :TestApp.exe or :TestApp in alias.actual to refer to that version, they're all equivalent. Same with TestAppd.exe vs copy_with_d or :copy_with_d, etc.

Body:
I'd like to build a simple application and to specify its output name: for debug version 'd' prefix should be added. I tried to use genrule for it, but I don't know how to change this option in different compilation modes. However I suppose that using genrule is not correct way.

So, how to specify output name?

cc_binary(
    name = "TestApp",
    srcs = [
        "src/TestApp/main.cpp",
    ],
)

genrule(
    name = "output_name_rule",
    srcs = [":TestApp"],
    outs = ["TestAppd.exe"],
    output_to_bindir = True,
    cmd_bat = "rename $(location TestApp) TestAppd.exe"
    )

config_setting(
    name = "release_build",
    values = {
        "compilation_mode":"opt"
    }
)

config_setting(
    name = "debug_build",
    values = {
        "compilation_mode":"dbg"
    }
)

Body:
genrule.outs is documented as nonconfigurable, so you can't use it directly. I would create a genrule that copies the file that exists in all configurations, and then choose between the genrule and the original cc_binary based on the configuration. Something like this:

genrule(
    name = "copy_with_d",
    srcs = [":TestApp"],
    outs = ["TestAppd.exe"],
    output_to_bindir = True,
    cmd_bat = "rename $(location TestApp) TestAppd.exe"
)

alias(
    name = "maybe_with_d",
    actual = select({
        ":debug_build": "TestAppd.exe",
        "//conditions:default": "TestApp.exe",
    }),
)

Some notes on things to tweak for your use case:

On Linux, I would write cmd = "cp $< $@". I'm not sure how Windows rename handles the input not being writable. You can definitely write $< and $@ instead of repeating the filenames though, they are Bazel "Make" variables.

I put the non-d version as //conditions:default so it applies in fastbuild too, up to you which way you want as the default.

Up to you whether you use TestApp.exe or :TestApp.exe or :TestApp in alias.actual to refer to that version, they're all equivalent. Same with TestAppd.exe vs copy_with_d or :copy_with_d, etc.


问:
Including White Space in a Path, Powershell
I am interfacing Powershell to Subversion, and I am having an issue, where Powershell is not completeling my url for Subversion, due to a space being in the path.

```<code>$Source = C:\Users\'+env:USERNAME+'\Desktop\FileDownloadLocation'
$SVNPath = 'http://subversion/svn/MainDirectory/SecondaryDirectory/Directory with a Space/subdirectory/finalLocation'

TortoiseProc.exe /command:checkout /url:$SVNPath /path:$Source /closeend:2
</code>```

What shows up in the Subversion Checkout Window is:

```<code>'http://subversion/svn/MainDirectory/SecondaryDirectory/Directory '
</code>```

I need to pass the remaining portion of the URL to Subversion.  Is there a way for me to do this in Powershell, and how would I have to go about including whitespaces into my URL Paths for Subversion, in Powershell?

答:
enclosing the path in triple quotes worked for me:</p>
```<code>$path="""path to folder/file with spaces"""
TortoiseProc.exe /command:update /path:$path /closeend:1
</code>```

Body:
I am interfacing Powershell to Subversion, and I am having an issue, where Powershell is not completeling my url for Subversion, due to a space being in the path.

$Source = C:\Users\'+env:USERNAME+'\Desktop\FileDownloadLocation'
$SVNPath = 'http://subversion/svn/MainDirectory/SecondaryDirectory/Directory with a Space/subdirectory/finalLocation'

TortoiseProc.exe /command:checkout /url:$SVNPath /path:$Source /closeend:2

What shows up in the Subversion Checkout Window is:

'http://subversion/svn/MainDirectory/SecondaryDirectory/Directory '

I need to pass the remaining portion of the URL to Subversion.  Is there a way for me to do this in Powershell, and how would I have to go about including whitespaces into my URL Paths for Subversion, in Powershell?

Body:
enclosing the path in triple quotes worked for me:

$path="""path to folder/file with spaces"""
TortoiseProc.exe /command:update /path:$path /closeend:1


问:
Ansible nested for loop with dynamic key lookup
```<code>ansible [core 2.11.5]
  python version = 3.9.6 (default, Jun 29 2021, 05:25:02) [Clang 12.0.5 (clang-1205.0.22.9)]
  jinja version = 3.0.2
  libyaml = True
</code>```

I am writing an Ansible playbook with the purpose of querying a list of EC2 instances and deregistering from Target Groups. Some nodes are registered to both NLB target groups and ALB target groups, so the playbook should be able to determine how to deregister accordingly based on the target group.

Assume I have the following data:

```<code># instances_dict contains instance data from ec2_instance_info module
# target_group_dict is a dict as such:
# assume that vars type and deploy_env are known

service_nodes:
  node_one:
    target_group_names:
      - "{{ type }}-{{ deploy_env }}-tcp"
      - "{{ type }}-{{ deploy_env }}-http"
  node_two:
    target_group_names:
      - "{{ type }}-{{ deploy_env }}-tcp"
      - "{{ type }}-{{ deploy_env }}-http"
</code>```

The general python-ish psuedocode equivalent of what I am trying to do is:

```<code>for instance in instances_dict['instances']:
  for tg in service_nodes[instance.Name]['target_group_names']:
    if 'tcp' in tg.Name:
      tg.deregister(instance.private_ip)
    if 'http' in tg.Name:
      tg.deregister(instance.instance_id)
</code>```

I am having trouble figuring out if it is possible to use Ansible's various looping features to nest for loops as such. It seems you can loop through known dictionaries or known lists at once, but having a dynamic key lookup based on iterating through another dictionary seems tricky. Has anyone tried to do something similar?

答:
After quite a bit of experimenting I wasn't able to get this to work in the way that I wanted with raw Ansible.  Perhaps there's still a way.

I ended up solving this problem by invoking the playbook within a Bash for-loop that iterates over a list of the known node names.

Bash script:

```<code>SERVICES=(
  'node1'
  'node2'
)

for SERVICE_TYPE in "${SERVICES[@]}"; do
  ANSIBLE_STDOUT_CALLBACK=yaml \
  ansible-playbook teardown.yml \
  --extra-vars \
  "service_type=$SERVICE_TYPE \
  etc..."
done
</code>```

Test playbook:

```<code># assume the above service_nodes dict from question above

tasks:
    - name: Gather information about any instance with Name including {{ uuid }}
      ec2_instance_info:
        region: "{{ ec2_region }}"
        filters:
          "tag:Name": "{{ type }}-{{ deploy_env }}-{{ service_type }}-{{ uuid }}"
          instance-state-name: [ "running"]
      register: running_node

    - name: Print target groups and types
      debug:
        msg: "Removing {{ running_node.instances[0].instance_id if 'webhttp' in item else running_node.instances[0].private_ip_address }} from {{ item }}"
      with_items: "{{ service_nodes[service_type]['target_group_names'] }}"
</code>```

Snippet of output showing results:

```<code>TASK [Print target groups and types] ***********************************************************************************************************************************
Friday 11 February 2022  14:34:48 -0500 (0:00:01.775)       0:00:01.824 *******
ok: [localhost] => (item=node-sandbox-webhttp) =>
  msg: Removing i-xxxxxxxxxxx from node-sandbox-webhttp
ok: [localhost] => (item=node-sandbox-webtcp) =>
  msg: Removing 10.227.1.217 from node-sandbox-webtcp
</code>```

This makes the output a bit more visually cumbersome but for now I think it'll do the trick.

Body:
ansible [core 2.11.5]
  python version = 3.9.6 (default, Jun 29 2021, 05:25:02) [Clang 12.0.5 (clang-1205.0.22.9)]
  jinja version = 3.0.2
  libyaml = True

I am writing an Ansible playbook with the purpose of querying a list of EC2 instances and deregistering from Target Groups. Some nodes are registered to both NLB target groups and ALB target groups, so the playbook should be able to determine how to deregister accordingly based on the target group.

Assume I have the following data:

# instances_dict contains instance data from ec2_instance_info module
# target_group_dict is a dict as such:
# assume that vars type and deploy_env are known

service_nodes:
  node_one:
    target_group_names:
      - "{{ type }}-{{ deploy_env }}-tcp"
      - "{{ type }}-{{ deploy_env }}-http"
  node_two:
    target_group_names:
      - "{{ type }}-{{ deploy_env }}-tcp"
      - "{{ type }}-{{ deploy_env }}-http"

The general python-ish psuedocode equivalent of what I am trying to do is:

for instance in instances_dict['instances']:
  for tg in service_nodes[instance.Name]['target_group_names']:
    if 'tcp' in tg.Name:
      tg.deregister(instance.private_ip)
    if 'http' in tg.Name:
      tg.deregister(instance.instance_id)

I am having trouble figuring out if it is possible to use Ansible's various looping features to nest for loops as such. It seems you can loop through known dictionaries or known lists at once, but having a dynamic key lookup based on iterating through another dictionary seems tricky. Has anyone tried to do something similar?

Body:
After quite a bit of experimenting I wasn't able to get this to work in the way that I wanted with raw Ansible.  Perhaps there's still a way.

I ended up solving this problem by invoking the playbook within a Bash for-loop that iterates over a list of the known node names.

Bash script:

SERVICES=(
  'node1'
  'node2'
)

for SERVICE_TYPE in "${SERVICES[@]}"; do
  ANSIBLE_STDOUT_CALLBACK=yaml \
  ansible-playbook teardown.yml \
  --extra-vars \
  "service_type=$SERVICE_TYPE \
  etc..."
done

Test playbook:

# assume the above service_nodes dict from question above

tasks:
    - name: Gather information about any instance with Name including {{ uuid }}
      ec2_instance_info:
        region: "{{ ec2_region }}"
        filters:
          "tag:Name": "{{ type }}-{{ deploy_env }}-{{ service_type }}-{{ uuid }}"
          instance-state-name: [ "running"]
      register: running_node

    - name: Print target groups and types
      debug:
        msg: "Removing {{ running_node.instances[0].instance_id if 'webhttp' in item else running_node.instances[0].private_ip_address }} from {{ item }}"
      with_items: "{{ service_nodes[service_type]['target_group_names'] }}"

Snippet of output showing results:

TASK [Print target groups and types] ***********************************************************************************************************************************
Friday 11 February 2022  14:34:48 -0500 (0:00:01.775)       0:00:01.824 *******
ok: [localhost] => (item=node-sandbox-webhttp) =>
  msg: Removing i-xxxxxxxxxxx from node-sandbox-webhttp
ok: [localhost] => (item=node-sandbox-webtcp) =>
  msg: Removing 10.227.1.217 from node-sandbox-webtcp

This makes the output a bit more visually cumbersome but for now I think it'll do the trick.


问:
SQL join is duplicating data
```<code>`SELECT
t2.Date,
t2.CampaignID,
t1.CampaignName,
SUM(t2.Impressions) AS Impressions,
SUM(t2.Clicks) AS Clicks,
SUM(t2.Cost/1000000) AS Cost,
SUM(t2.Conversions) AS Conversions
FROM "table_1.Campaign_5333142620" t1
LEFT JOIN "table_1.CampaignBasicStats_5333142620" t2 USING (CampaignId)
WHERE t2.DATE = '2022-02-09' AND t2.CampaignID = 15917662281
GROUP BY t2.Date, t1.CampaignName, t2.CampaignID
LIMIT 10`
</code>```

Hey all,

I am having an issue whereby my data is exactly duplicated for each row when performing this join. Without the join, using the table "CampaignBasicStats", the data is not duplicated, but joining to the other table creates the duplication...

Any help greatly appreciated!

答:
You can try on this way..

SELECT  t2.Date,  t2.CampaignID, t1.CampaignName, SUM(t2.Impressions) AS Impressions, SUM(t2.Clicks) AS Clicks, SUM(t2.Cost/1000000) AS Cost, SUM(t2.Conversions) AS Conversions FROM "table_1.Campaign_5333142620" t1 LEFT JOIN "table_1.CampaignBasicStats_5333142620" t2 ON t2.CampaignId = t1.CampaignId AND t2.DATE = '2022-02-09' AND t2.CampaignID = 15917662281 GROUP BY t2.Date, t1.CampaignName, t2.CampaignID LIMIT 10

Title: SQL join is duplicating data

Body:
`SELECT
t2.Date,
t2.CampaignID,
t1.CampaignName,
SUM(t2.Impressions) AS Impressions,
SUM(t2.Clicks) AS Clicks,
SUM(t2.Cost/1000000) AS Cost,
SUM(t2.Conversions) AS Conversions
FROM "table_1.Campaign_5333142620" t1
LEFT JOIN "table_1.CampaignBasicStats_5333142620" t2 USING (CampaignId)
WHERE t2.DATE = '2022-02-09' AND t2.CampaignID = 15917662281
GROUP BY t2.Date, t1.CampaignName, t2.CampaignID
LIMIT 10`

Hey all,

I am having an issue whereby my data is exactly duplicated for each row when performing this join. Without the join, using the table "CampaignBasicStats", the data is not duplicated, but joining to the other table creates the duplication...

Any help greatly appreciated!


问:
Why htmx trigger only work once in django
I am using htmx to trigger a field in Django ModelForm with the following codes.
Everything works as it supposed to the first time around, but after that when you change the option select field nothing happen, no trigger whatsoever. I have to reset and go back to url 'listing' for it to respond again. I want the code to trigger the result everytime I change the option select field before I finally submit. Any help is well appreciated.</p>
```<code>class Listing(model.Model):
   option=models.ForeignKey(Option,on_delete=models.CASCADE)
   package=models.ForeignKey(Package,on_delete=models.CASCADE,blank=True,null=True)
   number=models.ForeignKey(Number,on_delete=models.CASCADE,blank=True,null=True)
   period=models.ForeignKey(Period,on_delete=models.CASCADE,blank=True,null=True)
   title=models.CharField(max_length=20)

class ListingForm(ModelForm):
   class Meta:
      model=Listing
      fields='__all__'

class ListingCreateView(CreateView):
   model=Listing
   form_class=ListingForm
   template_name='listing_form.html'
   success_url='/forms/listing/'

def option(request):
   option=request.GET.get('option')
   form=ListingForm
   context={'option':option,'form':form}
   return render(request,'partial_option.html',context)

urlpatterns=[
   path('',ListingCreateView.as_view(),name='listing-create'),
   path('option/',option,name='option'),
]

listing_form.html
{% load widget_tweaks %}
<!DOCTYPE html>
<html>
    <head>
         <script src="https://unpkg.com/htmx.org@1.6.1"></script>
    </head>
    <body>
        <h1>Listing Form</h1>
        <form method="post">
            {% csrf_token %}
            <div>
                {{ form.option.label_tag }}
                {% render_field form.option hx-get="/forms/option"
                hx-trigger="change" hx-target="#option" hx-swap="outerHTML" %}
            </div>
            <div id="option"></div>
            <input type="submit" value="Send">
         </form>
         <script>
             document.body.addEventListener('htmx:configRequest', (event) =>
             {
                 event.detail.headers['X-CSRFToken']='{{csrf_token}}';
             })
         </script>
     </body>
 </html>

 partial_option.html:
 {% if option %}
    {% if option =='1' %}
        <p>You have chosen option 1</p>
    {% elif option == '2' %}
        <p>You have chosen option 2</p>
        {{ form.package.label_tag }}
        {{ form.package }}
    {% elif option == '3' %}
        <p>You have chosen option 3</p>
        {{ form.number.label_tag }}
        {{ form.number }}
        {{form.period.label_tag }}
        {{ form.period }}
    {% endif %}
 {% else %}
    <p>You have no option</p>
 {% endif %}
 {{ form.title.label_tag }}
 {{ form.title }}
</code>```

答:
You have set the hx-swap="outerHTML" method, so HTMX will replace the target element with the response. Since your response does not contain a new
 element, after the first request/swap cycle HTMX cannot find the target.

To solve this issue, change the swap method to innerHTML or embed the response in a

 element.

Body:
I am using htmx to trigger a field in Django ModelForm with the following codes.
Everything works as it supposed to the first time around, but after that when you change the option select field nothing happen, no trigger whatsoever. I have to reset and go back to url 'listing' for it to respond again. I want the code to trigger the result everytime I change the option select field before I finally submit. Any help is well appreciated.

class Listing(model.Model):
   option=models.ForeignKey(Option,on_delete=models.CASCADE)
   package=models.ForeignKey(Package,on_delete=models.CASCADE,blank=True,null=True)
   number=models.ForeignKey(Number,on_delete=models.CASCADE,blank=True,null=True)
   period=models.ForeignKey(Period,on_delete=models.CASCADE,blank=True,null=True)
   title=models.CharField(max_length=20)

class ListingForm(ModelForm):
   class Meta:
      model=Listing
      fields='__all__'

class ListingCreateView(CreateView):
   model=Listing
   form_class=ListingForm
   template_name='listing_form.html'
   success_url='/forms/listing/'

def option(request):
   option=request.GET.get('option')
   form=ListingForm
   context={'option':option,'form':form}
   return render(request,'partial_option.html',context)

urlpatterns=[
   path('',ListingCreateView.as_view(),name='listing-create'),
   path('option/',option,name='option'),
]

listing_form.html
{% load widget_tweaks %}
<!DOCTYPE html>

Listing Form

        <form method="post">
            {% csrf_token %}

                {{ form.option.label_tag }}
                {% render_field form.option hx-get="/forms/option"
                hx-trigger="change" hx-target="#option" hx-swap="outerHTML" %}

            <input type="submit" value="Send">
         </form>

 partial_option.html:
 {% if option %}
    {% if option =='1' %}

You have chosen option 1

    {% elif option == '2' %}

You have chosen option 2

        {{ form.package.label_tag }}
        {{ form.package }}
    {% elif option == '3' %}

You have chosen option 3

        {{ form.number.label_tag }}
        {{ form.number }}
        {{form.period.label_tag }}
        {{ form.period }}
    {% endif %}
 {% else %}

You have no option

 {% endif %}
 {{ form.title.label_tag }}
 {{ form.title }}

Body:
You have set the hx-swap="outerHTML" method, so HTMX will replace the target element with the response. Since your response does not contain a new <div id="option"> element, after the first request/swap cycle HTMX cannot find the target.

To solve this issue, change the swap method to innerHTML or embed the response in a <div id="option"></div> element.


答: There is no constructor in System.Threading.Thread class which take delegate of the type you have passed. you can only pass threadstart or paramererizedthreadstart type delegate.</p>

Title: Issues with threading in c#


问:
ECDF Function seems to be broken in R
Code and Image

I am working on a problem which requires I create an ECDF from data. All was working well, and then it seems that all of a sudden my ECDF function started returning nonsense. To prove this I wrote the following lines of code:

```<code>set.seed(19191)
x <- rnorm(50)
x; ecdf(x)
plot(ecdf(x))
</code>```

when I run these lines, I get what seems to be nonsense, as shown in the image I attached. This example is from this link: https://statisticsglobe.com/empirical-cumulative-distribution-function-ecdf-r

Can anyone help me?

答: When I ran the same code in R it worked, so I realized it was an issue with RStudio. After updating RStudio, everything worked perfectly.</p>

Title: ECDF Function seems to be broken in R

Body:
Code and Image

I am working on a problem which requires I create an ECDF from data. All was working well, and then it seems that all of a sudden my ECDF function started returning nonsense. To prove this I wrote the following lines of code:

set.seed(19191)
x <- rnorm(50)
x; ecdf(x)
plot(ecdf(x))

when I run these lines, I get what seems to be nonsense, as shown in the image I attached. This example is from this link: https://statisticsglobe.com/empirical-cumulative-distribution-function-ecdf-r

Can anyone help me?