问:
How to save page state on revisit in flutter
I have 2 screens and I am trying to achieve understand how to achieve page state. For example, in the below screen, I have 4 options, and all of them take the user to the same screen the only difference is API getting called for each of them is different to build a list. I am trying to handle back arrow action, and that's where I am having issues.

Use Case -
When user is on screen 2 he is playing the song, now on back press song continues to play. Now when the user again chooses the same option from screen 1 I want to show the same list without reload and selection. If user selects any other option it should behave normal, which is working.

Solution -

I can hardcode loaded songs list and send back to screen 1 and then again get that back with the selection but this will take lot of resources.

AutomaticKeepAliveClientMixin i tried this tutorial but that didn't help or kept state active.

PageStorage is 3rd option i saw but i found majority of the time this is being used on app where we have a tab.

Screen 1 -

```<code>class Dashboard  extends StatefulWidget {
  int playingId;
  Dashboard({this.playingId});
  @override
  _DashboardState createState() => _DashboardState(playingId);

}

class _DashboardState extends State<Dashboard> {
  String appname;
  int playingId = 0;
  _DashboardState(this.playingId);
  // print('${playingId}');

  @override
  void initState() {
    appname="";
    // playingId=0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: AppColors.darkBlue,
        centerTitle: true,
        title: Text("Tirthankar",
        style: TextStyle(color: Colors.white),),
      ),

      backgroundColor: AppColors.styleColor,
      body: Column(
        children: <Widget>[
          // SizedBox(height: 5),
          Padding(
            padding: const EdgeInsets.all(20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                CustomGridWidget(
                  child: Icon(
                        Icons.file_download,
                        size: 100,
                        color: AppColors.styleColor,
                      ),

                  // image: 'assets/bhaktambar.png',
                  sizew: MediaQuery.of(context).size.width * .4,
                  sizeh: MediaQuery.of(context).size.width * .5,
                  borderWidth: 2,
                  label: "Bhakti",
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => ListPage(appname: "Kids",playingId: playingId,),

                      ),
                    );
                  },
                ),
                CustomGridWidget(
                  child: Icon(
                        Icons.file_download,
                        size: 100,
                        color: AppColors.styleColor,
                      ),

                  // image: 'assets/bhaktambar.png',
                  sizew: MediaQuery.of(context).size.width * .4,
                  sizeh: MediaQuery.of(context).size.width * .5,
                  borderWidth: 2,
                  label: "Kids",
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => ListPage(appname: "Kids",playingId: playingId,),

                      ),
                    );
                  },
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 20,
              right: 20,
              bottom: 20),
          child: Row(

              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                CustomGridWidget(
                  child: Icon(
                        Icons.favorite,
                        size: 100,
                        color: AppColors.styleColor,
                      ),
                  // image: 'assets/kids.jpg',
                  sizew: MediaQuery.of(context).size.width * .4,
                  sizeh: MediaQuery.of(context).size.width * .5,
                  borderWidth: 2,
                  label: "Favorite",
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => ListPage(appname: "Songs"),
                      ),
                    );
                  },
                ),
                Align(
                  alignment: Alignment.center,
                    child: CustomGridWidget(
                    child: Icon(
                          Icons.book,
                          size: 100,
                          color: AppColors.styleColor,
                        ),
                    // image: 'assets/vidyasagar.jpg',
                    sizew: MediaQuery.of(context).size.width * .4,
                    sizeh: MediaQuery.of(context).size.width * .5,
                    borderWidth: 2,
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (_) => ListPage(appname: "Bhajan"),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ]
      ),

    );
  }
  Material boxTiles(IconData icon, String name){
    return Material(

      color: AppColors.mainColor,
      elevation: 14.0,
      shadowColor: AppColors.styleColor,
      borderRadius: BorderRadius.circular(24.0),
      child: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
        child:Row(
          mainAxisAlignment: MainAxisAlignment.center,

          children: <Widget>[
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                InkWell(
                    onTap: (){print("tapped");   /*  or any action you want */ },
                    child: Container(
                        width: 130.0,
                        height: 10.0,
                        color : Colors.transparent,
                      ), // container
                ), //
                //Text
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(name,
                  style:TextStyle(
                    color: AppColors.styleColor,
                    fontSize: 20.0,
                    )
                  ),
                ),
                //Icon
                Material(
                  color: AppColors.styleColor,
                  borderRadius: BorderRadius.circular(50.0),
                  child: Padding(padding: const EdgeInsets.all(10.0),
                    child: Icon(icon, color: AppColors.lightBlue,size: 30,),
                  ),
                ),
              ],
            )
          ],
        )
      ),
      )
    );
  }

}
</code>```

Screen 2 -

```<code>// import 'dart:js';

class ListPage extends StatefulWidget {
  String appname;
  int playingId;
  ListPage({this.appname,this.playingId});
  @override
  _ListPageState createState() => _ListPageState(appname,playingId);
}

class _ListPageState extends State<ListPage>
    with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin<ListPage> {
  String appname;
  int playingId;
  bool isPlaying = false;
  _ListPageState(this.appname,playingId);
  // List<MusicModel> _list1;
  List<MusicData> _list;

  var _value;
  int _playId;
  int _songId;
  String _playURL;

  bool _isRepeat;
  bool _isShuffle;
  bool _isFavorite;
  String _startTime;
  String _endTime;
  AnimationController _controller;
  Duration _duration = new Duration();
  Duration _position = new Duration();
  final _random = new Random();
  AudioPlayer _audioPlayer = AudioPlayer();
  @override
  void initState() {
    _playId = 0;
    // _list1 = MusicModel.list;
    this._fileUpdate();
    // _list = _list1;
    _controller =
        AnimationController(vsync: this, duration: Duration(microseconds: 250));
    _value = 0.0;
    _startTime = "0.0";
    _endTime = "0.0";
    _isRepeat = false;
    _isShuffle = false;
    _isFavorite = false;

    _audioPlayer.onAudioPositionChanged.listen((Duration duration) {
      setState(() {
        // _startTime = duration.toString().split(".")[0];
        _startTime = duration.toString().split(".")[0];
        _duration = duration;

        // _position = duration.toString().split(".")[0];
      });
    });
    _audioPlayer.onDurationChanged.listen((Duration duration) {
      setState(() {
        _endTime = duration.toString().split(".")[0];
        _position = duration;
      });
    });
    _audioPlayer.onPlayerCompletion.listen((event) {
      setState(() {
        isPlaying = false;
        _position = _duration;
        if (_isRepeat) {
          _songId = _songId;
        } else {
          if (_isShuffle) {
            var element = _list[_random.nextInt(_list.length)];
            _songId = element.id;
          } else {
            _songId = _songId + 1;
          }
        }
        _player(_songId);
      });
    });

    super.initState();
  }

  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: AppColors.mainColor,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: (){
            Navigator.of(context).push(
               MaterialPageRoute(
                  builder: (_) => Dashboard(playingId: _songId),
                ),
            );
          },
        ),
        title: Text(
          appname,
          style: TextStyle(color: AppColors.styleColor),
        ),
      ),

      backgroundColor: AppColors.mainColor,
      body: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(24.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    CustomButtonWidget(
                      child: Icon(
                        Icons.favorite,
                        color: AppColors.styleColor,
                      ),
                      size: 50,
                      onTap: () {},
                    ),
                    CustomButtonWidget(
                      image: 'assets/logo.jpg',
                      size: 100,
                      borderWidth: 5,
                      onTap: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (_) => DetailPage(),
                          ),
                        );
                      },
                    ),
                    CustomButtonWidget(
                      child: Icon(
                        Icons.menu,
                        color: AppColors.styleColor,
                      ),
                      size: 50,
                      onTap: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (_) => HomePage(),
                          ),
                        );
                      },
                    )
                  ],
                ),
              ),
              slider(),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    IconButton(
                      icon: Icon(
                        _isRepeat ? Icons.repeat_one : Icons.repeat,
                        color: _isRepeat ? Colors.brown : AppColors.styleColor,
                      ),
                      onPressed: () {
                        if (_isRepeat) {
                          _isRepeat = false;
                        } else {
                          _isRepeat = true;
                        }
                      },
                    ),
                    IconButton(
                        icon: Icon(
                          isPlaying ? Icons.pause : Icons.play_arrow,
                          color: AppColors.styleColor,
                        ),
                        onPressed: () {
                          if (isPlaying) {
                            _audioPlayer.pause();
                            setState(() {
                              isPlaying = false;
                            });
                          } else {
                            if (!isPlaying){
                              _audioPlayer.resume();
                              setState(() {
                                isPlaying = true;
                              });
                            }

                          }
                        }),
                    IconButton(
                        icon: Icon(
                          Icons.stop,
                          color: AppColors.styleColor,
                        ),
                        onPressed: () {
                          if (isPlaying){
                            _audioPlayer.stop();
                            setState(() {
                              isPlaying = false;
                              _duration = new Duration();
                            });
                          }

                          // isPlaying = false;
                        }),
                    IconButton(
                        icon: Icon(
                          Icons.shuffle,
                          color:
                              _isShuffle ? Colors.brown : AppColors.styleColor,
                        ),
                        onPressed: () {
                          if (_isShuffle) {
                            _isShuffle = false;
                          } else {
                            _isShuffle = true;
                          }
                        }),
                  ],
                ),
              ),

              Expanded(
                //This is added so we can see overlay else this will be over button
                child: ListView.builder(
                  physics:
                      BouncingScrollPhysics(), //This line removes the dark flash when you are at the begining or end of list menu. Just uncomment for
                  // itemCount: _list.length,
                  itemCount: _list == null ? 0 : _list.length,
                  padding: EdgeInsets.all(12),
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () {
                        _songId = index;
                        _player(index);
                      },
                      child: AnimatedContainer(
                        duration: Duration(milliseconds: 500),
                        //This below code will change the color of sected area or song being played.
                        decoration: BoxDecoration(
                          color: _list[index].id == _playId
                              ? AppColors.activeColor
                              : AppColors.mainColor,
                          borderRadius: BorderRadius.all(
                            Radius.circular(20),
                          ),
                        ),
                        //End of row color change
                        child: Padding(
                          padding: const EdgeInsets.all(
                              16), //This will all padding around all size
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment
                                .spaceBetween, //This will allign button to left, else button will be infront of name
                            children: <Widget>[
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    _list[index].title,
                                    style: TextStyle(
                                      color: AppColors.styleColor,
                                      fontSize: 16,
                                    ),
                                  ),
                                  Text(
                                    _list[index].album,
                                    style: TextStyle(
                                      color: AppColors.styleColor.withAlpha(90),
                                      fontSize: 16,
                                    ),
                                  ),
                                ],
                              ),
                              IconButton(
                                  icon: Icon(_isFavorite
                                      ? Icons.favorite
                                      : Icons.favorite_border),
                                  onPressed: () {
                                    if (_isFavorite) {
                                      _isFavorite = false;
                                    } else {
                                      _isFavorite = true;
                                    }
                                  })
                              //Diabled Play button and added fav button.
                              // CustomButtonWidget(
                              //   //This is Play button functionality on list page.
                              //   child: Icon(
                              //     _list[index].id == _playId
                              //         ? Icons.pause
                              //         : Icons.play_arrow,
                              //     color: _list[index].id == _playId
                              //         ? Colors.white
                              //         : AppColors.styleColor,
                              //   ),
                              //   size: 50,

                              //   isActive: _list[index].id == _playId,
                              //   onTap: () async {
                              //     _songId = index;
                              //     _player(index);
                              //   },
                              // )
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
              )
            ],
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              height: 50,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                colors: [
                  AppColors.mainColor.withAlpha(0),
                  AppColors.mainColor,
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              )),
            ),
          )
        ],
      ),
      // floatingActionButton: FloatingActionButton(
      //   child: Icon(Icons.music_note),
      //   onPressed: () async {      // String filePath = await FilePicker.getFilePath();

      //     int status = await _audioPlayer.play("https://traffic.libsyn.com/voicebot/Jan_Konig_on_the_Jovo_Open_Source_Framework_for_Voice_App_Development_-_Voicebot_Podcast_Ep_56.mp3");
      //     if (status == 1){
      //        setState(() {
      //          isPlaying = true;
      //        });
      //     }
      //   },
      // )
    );
  }

  Widget slider() {
    return Slider(
        activeColor: AppColors.styleColor,
        inactiveColor: Colors.lightBlue,
        value: _duration.inSeconds.toDouble(),
        min: 0.0,
        max: _position.inSeconds.toDouble(),
        divisions: 10,
        onChangeStart: (double value) {
          print('Start value is ' + value.toString());
        },
        onChangeEnd: (double value) {
          print('Finish value is ' + value.toString());
        },
        onChanged: (double value) {
          setState(() {
            seekToSecond(value.toInt());
            value = value;
          });
        });
  }

  Future<Void> _fileUpdate() async {
    String url =
        "azonaws.com/input.json";
    String arrayObjsText = "";
    try {
      eos.Response response;
      Dio dio = new Dio();
      response = await dio.get(url,options: Options(
        responseType: ResponseType.plain,
      ),);
       arrayObjsText = response.data;
       print(response.data.toString());
    } catch (e) {
      print(e);
    }
    var tagObjsJson = jsonDecode(arrayObjsText)['tags'] as List;
    this.setState(() {
      _list = tagObjsJson.map((tagJson) => MusicData.fromJson(tagJson)).toList();
    });

    // return _list;
    // print(_list);
  }

  Future<void> _player(int index) async {
    if (isPlaying) {
      if (_playId == _list[index].id) {
        int status = await _audioPlayer.pause();
        if (status == 1) {
          setState(() {
            isPlaying = false;
          });
        }
      } else {
        _playId = _list[index].id;
        _playURL = _list[index].songURL;
        _audioPlayer.stop();
        int status = await _audioPlayer.play(_playURL);
        if (status == 1) {
          setState(() {
            isPlaying = true;
          });
        }
      }

    } else {
      _playId = _list[index].id;
      _playURL = _list[index].songURL;
      int status = await _audioPlayer.play(_playURL);
      if (status == 1) {
        setState(() {
          isPlaying = true;
        });
      }
    }
  }

  String _printDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }

  void seekToSecond(int second) {
    Duration newDuration = Duration(seconds: second);
    _audioPlayer.seek(newDuration);
  }

  }
</code>```

答:
PageStorage is 3rd option i saw but i found majority of the time this is being used on app where we have a tab.

You still can use this approach with what you want, with or without Tab/ bottom navigation bar.

PageViewClass

```<code>class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin{
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    super.dispose();
    _pageController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: PageView(
            controller: _pageController,
            physics: NeverScrollableScrollPhysics(), // so the user cannot scroll, only animating when they select an option
            children: <Widget>[
              Dashboard(playingId: 1, key: PageStorageKey<String>('MyPlayList'), pageController: _pageController), //or the name you want, but you need to give them a key to all the child so it can save the Scroll Position
              ListPage(appname: "FirstButton",playingId: 1, key: PageStorageKey<String>('FirstButton'), pageController: _pageController),
              ListPage(appname: "SecondButton",playingId: 1, key: PageStorageKey<String>('SecondButton'), pageController: _pageController),
              ListPage(appname: "ThirdButton",playingId: 1, key: PageStorageKey<String>('ThirdButton'), pageController: _pageController),
              ListPage(appname: "FourthButton",playingId: 1, key: PageStorageKey<String>('FourthButton'), pageController: _pageController)
            ],
          ),
        )
    );
  }
}
</code>```

Now you pass the PageController to all children (add a key and PageController attribute to Screen 1 and 2)  and in DashBoard (Screen 1) you can change the onTap of the buttons from the MaterialRoute to this

```<code>onTap: () => widget.pageController.jumpToPage(x), //where x is the index of the children of the PageView you want to see (between 0 and 4 in this case)
</code>```

In Screen 2 you wrap all your Scaffold with a WillPopScope so when the user tap back instead of closing the route it goes back to the Dashboard Widget at index 0

```<code>@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        widget.pageController.jumpToPage(0); // Move back to dashboard (index 0)
        return false;
      }
      child: Scaffold(...)
    );

  }
</code>```

You can use other methods of PageController if you want some effects like animations (animateTo, nextPage, previousPage, etc.)

Body:
I have 2 screens and I am trying to achieve understand how to achieve page state. For example, in the below screen, I have 4 options, and all of them take the user to the same screen the only difference is API getting called for each of them is different to build a list. I am trying to handle back arrow action, and that's where I am having issues.

Use Case -
When user is on screen 2 he is playing the song, now on back press song continues to play. Now when the user again chooses the same option from screen 1 I want to show the same list without reload and selection. If user selects any other option it should behave normal, which is working.

Solution -

I can hardcode loaded songs list and send back to screen 1 and then again get that back with the selection but this will take lot of resources.

AutomaticKeepAliveClientMixin i tried this tutorial but that didn't help or kept state active.

PageStorage is 3rd option i saw but i found majority of the time this is being used on app where we have a tab.

Screen 1 -

class Dashboard  extends StatefulWidget {
  int playingId;
  Dashboard({this.playingId});
  @override
  _DashboardState createState() => _DashboardState(playingId);

}

class _DashboardState extends State<Dashboard> {
  String appname;
  int playingId = 0;
  _DashboardState(this.playingId);
  // print('${playingId}');

  @override
  void initState() {
    appname="";
    // playingId=0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: AppColors.darkBlue,
        centerTitle: true,
        title: Text("Tirthankar",
        style: TextStyle(color: Colors.white),),
      ),

      backgroundColor: AppColors.styleColor,
      body: Column(
        children: <Widget>[
          // SizedBox(height: 5),
          Padding(
            padding: const EdgeInsets.all(20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                CustomGridWidget(
                  child: Icon(
                        Icons.file_download,
                        size: 100,
                        color: AppColors.styleColor,
                      ),

                  // image: 'assets/bhaktambar.png',
                  sizew: MediaQuery.of(context).size.width * .4,
                  sizeh: MediaQuery.of(context).size.width * .5,
                  borderWidth: 2,
                  label: "Bhakti",
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => ListPage(appname: "Kids",playingId: playingId,),

                      ),
                    );
                  },
                ),
                CustomGridWidget(
                  child: Icon(
                        Icons.file_download,
                        size: 100,
                        color: AppColors.styleColor,
                      ),

                  // image: 'assets/bhaktambar.png',
                  sizew: MediaQuery.of(context).size.width * .4,
                  sizeh: MediaQuery.of(context).size.width * .5,
                  borderWidth: 2,
                  label: "Kids",
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => ListPage(appname: "Kids",playingId: playingId,),

                      ),
                    );
                  },
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 20,
              right: 20,
              bottom: 20),
          child: Row(

              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                CustomGridWidget(
                  child: Icon(
                        Icons.favorite,
                        size: 100,
                        color: AppColors.styleColor,
                      ),
                  // image: 'assets/kids.jpg',
                  sizew: MediaQuery.of(context).size.width * .4,
                  sizeh: MediaQuery.of(context).size.width * .5,
                  borderWidth: 2,
                  label: "Favorite",
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => ListPage(appname: "Songs"),
                      ),
                    );
                  },
                ),
                Align(
                  alignment: Alignment.center,
                    child: CustomGridWidget(
                    child: Icon(
                          Icons.book,
                          size: 100,
                          color: AppColors.styleColor,
                        ),
                    // image: 'assets/vidyasagar.jpg',
                    sizew: MediaQuery.of(context).size.width * .4,
                    sizeh: MediaQuery.of(context).size.width * .5,
                    borderWidth: 2,
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (_) => ListPage(appname: "Bhajan"),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ]
      ),

    );
  }
  Material boxTiles(IconData icon, String name){
    return Material(

      color: AppColors.mainColor,
      elevation: 14.0,
      shadowColor: AppColors.styleColor,
      borderRadius: BorderRadius.circular(24.0),
      child: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
        child:Row(
          mainAxisAlignment: MainAxisAlignment.center,

          children: <Widget>[
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                InkWell(
                    onTap: (){print("tapped");   /*  or any action you want */ },
                    child: Container(
                        width: 130.0,
                        height: 10.0,
                        color : Colors.transparent,
                      ), // container
                ), //
                //Text
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(name,
                  style:TextStyle(
                    color: AppColors.styleColor,
                    fontSize: 20.0,
                    )
                  ),
                ),
                //Icon
                Material(
                  color: AppColors.styleColor,
                  borderRadius: BorderRadius.circular(50.0),
                  child: Padding(padding: const EdgeInsets.all(10.0),
                    child: Icon(icon, color: AppColors.lightBlue,size: 30,),
                  ),
                ),
              ],
            )
          ],
        )
      ),
      )
    );
  }

}

Screen 2 -

// import 'dart:js';

class ListPage extends StatefulWidget {
  String appname;
  int playingId;
  ListPage({this.appname,this.playingId});
  @override
  _ListPageState createState() => _ListPageState(appname,playingId);
}

class _ListPageState extends State<ListPage>
    with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin<ListPage> {
  String appname;
  int playingId;
  bool isPlaying = false;
  _ListPageState(this.appname,playingId);
  // List<MusicModel> _list1;
  List<MusicData> _list;

  var _value;
  int _playId;
  int _songId;
  String _playURL;

  bool _isRepeat;
  bool _isShuffle;
  bool _isFavorite;
  String _startTime;
  String _endTime;
  AnimationController _controller;
  Duration _duration = new Duration();
  Duration _position = new Duration();
  final _random = new Random();
  AudioPlayer _audioPlayer = AudioPlayer();
  @override
  void initState() {
    _playId = 0;
    // _list1 = MusicModel.list;
    this._fileUpdate();
    // _list = _list1;
    _controller =
        AnimationController(vsync: this, duration: Duration(microseconds: 250));
    _value = 0.0;
    _startTime = "0.0";
    _endTime = "0.0";
    _isRepeat = false;
    _isShuffle = false;
    _isFavorite = false;

    _audioPlayer.onAudioPositionChanged.listen((Duration duration) {
      setState(() {
        // _startTime = duration.toString().split(".")[0];
        _startTime = duration.toString().split(".")[0];
        _duration = duration;

        // _position = duration.toString().split(".")[0];
      });
    });
    _audioPlayer.onDurationChanged.listen((Duration duration) {
      setState(() {
        _endTime = duration.toString().split(".")[0];
        _position = duration;
      });
    });
    _audioPlayer.onPlayerCompletion.listen((event) {
      setState(() {
        isPlaying = false;
        _position = _duration;
        if (_isRepeat) {
          _songId = _songId;
        } else {
          if (_isShuffle) {
            var element = _list[_random.nextInt(_list.length)];
            _songId = element.id;
          } else {
            _songId = _songId + 1;
          }
        }
        _player(_songId);
      });
    });

    super.initState();
  }

  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: AppColors.mainColor,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: (){
            Navigator.of(context).push(
               MaterialPageRoute(
                  builder: (_) => Dashboard(playingId: _songId),
                ),
            );
          },
        ),
        title: Text(
          appname,
          style: TextStyle(color: AppColors.styleColor),
        ),
      ),

      backgroundColor: AppColors.mainColor,
      body: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(24.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    CustomButtonWidget(
                      child: Icon(
                        Icons.favorite,
                        color: AppColors.styleColor,
                      ),
                      size: 50,
                      onTap: () {},
                    ),
                    CustomButtonWidget(
                      image: 'assets/logo.jpg',
                      size: 100,
                      borderWidth: 5,
                      onTap: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (_) => DetailPage(),
                          ),
                        );
                      },
                    ),
                    CustomButtonWidget(
                      child: Icon(
                        Icons.menu,
                        color: AppColors.styleColor,
                      ),
                      size: 50,
                      onTap: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (_) => HomePage(),
                          ),
                        );
                      },
                    )
                  ],
                ),
              ),
              slider(),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    IconButton(
                      icon: Icon(
                        _isRepeat ? Icons.repeat_one : Icons.repeat,
                        color: _isRepeat ? Colors.brown : AppColors.styleColor,
                      ),
                      onPressed: () {
                        if (_isRepeat) {
                          _isRepeat = false;
                        } else {
                          _isRepeat = true;
                        }
                      },
                    ),
                    IconButton(
                        icon: Icon(
                          isPlaying ? Icons.pause : Icons.play_arrow,
                          color: AppColors.styleColor,
                        ),
                        onPressed: () {
                          if (isPlaying) {
                            _audioPlayer.pause();
                            setState(() {
                              isPlaying = false;
                            });
                          } else {
                            if (!isPlaying){
                              _audioPlayer.resume();
                              setState(() {
                                isPlaying = true;
                              });
                            }

                          }
                        }),
                    IconButton(
                        icon: Icon(
                          Icons.stop,
                          color: AppColors.styleColor,
                        ),
                        onPressed: () {
                          if (isPlaying){
                            _audioPlayer.stop();
                            setState(() {
                              isPlaying = false;
                              _duration = new Duration();
                            });
                          }

                          // isPlaying = false;
                        }),
                    IconButton(
                        icon: Icon(
                          Icons.shuffle,
                          color:
                              _isShuffle ? Colors.brown : AppColors.styleColor,
                        ),
                        onPressed: () {
                          if (_isShuffle) {
                            _isShuffle = false;
                          } else {
                            _isShuffle = true;
                          }
                        }),
                  ],
                ),
              ),

              Expanded(
                //This is added so we can see overlay else this will be over button
                child: ListView.builder(
                  physics:
                      BouncingScrollPhysics(), //This line removes the dark flash when you are at the begining or end of list menu. Just uncomment for
                  // itemCount: _list.length,
                  itemCount: _list == null ? 0 : _list.length,
                  padding: EdgeInsets.all(12),
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () {
                        _songId = index;
                        _player(index);
                      },
                      child: AnimatedContainer(
                        duration: Duration(milliseconds: 500),
                        //This below code will change the color of sected area or song being played.
                        decoration: BoxDecoration(
                          color: _list[index].id == _playId
                              ? AppColors.activeColor
                              : AppColors.mainColor,
                          borderRadius: BorderRadius.all(
                            Radius.circular(20),
                          ),
                        ),
                        //End of row color change
                        child: Padding(
                          padding: const EdgeInsets.all(
                              16), //This will all padding around all size
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment
                                .spaceBetween, //This will allign button to left, else button will be infront of name
                            children: <Widget>[
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    _list[index].title,
                                    style: TextStyle(
                                      color: AppColors.styleColor,
                                      fontSize: 16,
                                    ),
                                  ),
                                  Text(
                                    _list[index].album,
                                    style: TextStyle(
                                      color: AppColors.styleColor.withAlpha(90),
                                      fontSize: 16,
                                    ),
                                  ),
                                ],
                              ),
                              IconButton(
                                  icon: Icon(_isFavorite
                                      ? Icons.favorite
                                      : Icons.favorite_border),
                                  onPressed: () {
                                    if (_isFavorite) {
                                      _isFavorite = false;
                                    } else {
                                      _isFavorite = true;
                                    }
                                  })
                              //Diabled Play button and added fav button.
                              // CustomButtonWidget(
                              //   //This is Play button functionality on list page.
                              //   child: Icon(
                              //     _list[index].id == _playId
                              //         ? Icons.pause
                              //         : Icons.play_arrow,
                              //     color: _list[index].id == _playId
                              //         ? Colors.white
                              //         : AppColors.styleColor,
                              //   ),
                              //   size: 50,

                              //   isActive: _list[index].id == _playId,
                              //   onTap: () async {
                              //     _songId = index;
                              //     _player(index);
                              //   },
                              // )
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
              )
            ],
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              height: 50,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                colors: [
                  AppColors.mainColor.withAlpha(0),
                  AppColors.mainColor,
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              )),
            ),
          )
        ],
      ),
      // floatingActionButton: FloatingActionButton(
      //   child: Icon(Icons.music_note),
      //   onPressed: () async {      // String filePath = await FilePicker.getFilePath();

      //     int status = await _audioPlayer.play("https://traffic.libsyn.com/voicebot/Jan_Konig_on_the_Jovo_Open_Source_Framework_for_Voice_App_Development_-_Voicebot_Podcast_Ep_56.mp3");
      //     if (status == 1){
      //        setState(() {
      //          isPlaying = true;
      //        });
      //     }
      //   },
      // )
    );
  }

  Widget slider() {
    return Slider(
        activeColor: AppColors.styleColor,
        inactiveColor: Colors.lightBlue,
        value: _duration.inSeconds.toDouble(),
        min: 0.0,
        max: _position.inSeconds.toDouble(),
        divisions: 10,
        onChangeStart: (double value) {
          print('Start value is ' + value.toString());
        },
        onChangeEnd: (double value) {
          print('Finish value is ' + value.toString());
        },
        onChanged: (double value) {
          setState(() {
            seekToSecond(value.toInt());
            value = value;
          });
        });
  }

  Future<Void> _fileUpdate() async {
    String url =
        "azonaws.com/input.json";
    String arrayObjsText = "";
    try {
      eos.Response response;
      Dio dio = new Dio();
      response = await dio.get(url,options: Options(
        responseType: ResponseType.plain,
      ),);
       arrayObjsText = response.data;
       print(response.data.toString());
    } catch (e) {
      print(e);
    }
    var tagObjsJson = jsonDecode(arrayObjsText)['tags'] as List;
    this.setState(() {
      _list = tagObjsJson.map((tagJson) => MusicData.fromJson(tagJson)).toList();
    });

    // return _list;
    // print(_list);
  }

  Future<void> _player(int index) async {
    if (isPlaying) {
      if (_playId == _list[index].id) {
        int status = await _audioPlayer.pause();
        if (status == 1) {
          setState(() {
            isPlaying = false;
          });
        }
      } else {
        _playId = _list[index].id;
        _playURL = _list[index].songURL;
        _audioPlayer.stop();
        int status = await _audioPlayer.play(_playURL);
        if (status == 1) {
          setState(() {
            isPlaying = true;
          });
        }
      }

    } else {
      _playId = _list[index].id;
      _playURL = _list[index].songURL;
      int status = await _audioPlayer.play(_playURL);
      if (status == 1) {
        setState(() {
          isPlaying = true;
        });
      }
    }
  }

  String _printDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }

  void seekToSecond(int second) {
    Duration newDuration = Duration(seconds: second);
    _audioPlayer.seek(newDuration);
  }

  }

Body:
PageStorage is 3rd option i saw but i found majority of the time this is being used on app where we have a tab.

You still can use this approach with what you want, with or without Tab/ bottom navigation bar.

PageViewClass

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin{
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    super.dispose();
    _pageController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: PageView(
            controller: _pageController,
            physics: NeverScrollableScrollPhysics(), // so the user cannot scroll, only animating when they select an option
            children: <Widget>[
              Dashboard(playingId: 1, key: PageStorageKey<String>('MyPlayList'), pageController: _pageController), //or the name you want, but you need to give them a key to all the child so it can save the Scroll Position
              ListPage(appname: "FirstButton",playingId: 1, key: PageStorageKey<String>('FirstButton'), pageController: _pageController),
              ListPage(appname: "SecondButton",playingId: 1, key: PageStorageKey<String>('SecondButton'), pageController: _pageController),
              ListPage(appname: "ThirdButton",playingId: 1, key: PageStorageKey<String>('ThirdButton'), pageController: _pageController),
              ListPage(appname: "FourthButton",playingId: 1, key: PageStorageKey<String>('FourthButton'), pageController: _pageController)
            ],
          ),
        )
    );
  }
}

Now you pass the PageController to all children (add a key and PageController attribute to Screen 1 and 2)  and in DashBoard (Screen 1) you can change the onTap of the buttons from the MaterialRoute to this

onTap: () => widget.pageController.jumpToPage(x), //where x is the index of the children of the PageView you want to see (between 0 and 4 in this case)

In Screen 2 you wrap all your Scaffold with a WillPopScope so when the user tap back instead of closing the route it goes back to the Dashboard Widget at index 0

@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        widget.pageController.jumpToPage(0); // Move back to dashboard (index 0)
        return false;
      }
      child: Scaffold(...)
    );

  }

You can use other methods of PageController if you want some effects like animations (animateTo, nextPage, previousPage, etc.)


来源: stackexchange

问:
Can I force Kubernetes not to run more than X replicas of a pod in the same node?
I have a tiny Kubernetes cluster consisting of just two nodes running on t3a.micro AWS EC2 instances (to save money).

I have a small web app that I am trying to run in this cluster. I have a single Deployment for this app. This deployment has spec.replicas set to 4.

When I run this Deployment, I noticed that Kubernetes scheduled 3 of its pods in one node and 1 pod in the other node.

Is it possible to force Kubernetes to schedule at most 2 pods of this Deployment per node? Having 3 instances in the same pod puts me dangerously close to running out of memory in these tiny EC2 instances.

Thanks!

答:
The correct solution for this would be to set memory requests and limits correctly matching your steady state and burst RAM consumption levels on every pod, then the scheduler will do all this math for you.

But for the future and for others, there is a new feature which kind of allows this https://kubernetes.io/blog/2020/05/introducing-podtopologyspread/. It's not an exact match, you can't put a global cap, rather you can require pods be evenly spaced over the cluster subject to maximum skew caps.

ContentLicense: CC BY-SA 4.0


问:
Graceful way to link to item in Sitecore client?
I am looking for the best way to link to an item in the Sitecore client (not the external website). The link will be embedded in a broken links report email. The user should be able to click the link and launch the Sitecore content editor with that Item auto-selected in the tree.

I have found Mark Ursino's solution on his blog here, but unfortunately, it only works if you are actively logged into Sitecore (Otherwise, it brings you to the Sitecore Desktop after logging in).

I am running Sitecore.NET 6.4.1 (rev. 110324)

UPDATE

Just to close the loop on Marko's solution:

```<code>public void Process(LoggedInArgs args)
{
    string url = HttpUtility.UrlDecode(WebUtil.GetQueryString("url"));

    // Ensure we're dealing with the client login site and there is a URL to redirect to
    if (Sitecore.Context.GetSiteName() == "login" &&
        !String.IsNullOrEmpty(url))
    {
        var queryString = WebUtil.ParseQueryString(url);

        // Check for redirect param to prevent accidental redirections
        if (queryString.ContainsKey("redirectAfterLogin"))
                WebUtil.Redirect(url);
    }
}
</code>```

答:
Here's what I've used before:

There's an option in the sitecore web.config to send through raw url's. Set that on using this patch file

```<code><setting name="Authentication.SaveRawUrl">
  <patch:attribute name="value">true</patch:attribute>
</setting>
</code>```

Then, I added an additional processor into the loggedin processor after the CleanupUserProfile which reads the querystring parameter(s) and redirects to the appropriate page. This processor is called everytime, regardless of if the user has logged in before, or not.

The signature for my custom logged in processor is

```<code>namespace [...]
{
    public class LoginModeSwitcher
    {
        public void Process(LoggedInArgs args)
        {
            // your code here
        }
    }
}
</code>```

This is the patch config I've used for the logged in processor:

```<code><processors>
  <loggedin>
    <processor patch:after="*[@type='Sitecore.Pipelines.LoggedIn.CleanupUserProfile, Sitecore.Kernel']" mode="on" type="[...].LoginModeSwitcher, [ASSEMBLY]" />
  </loggedin>
</processors>
</code>```

The links in the email link contain a querystring parameter to tell my code that we want to redirect after login and other querystring parameters to tell it where to redirect the user.

ContentLicense: CC BY-SA 3.0

Body:
I am looking for the best way to link to an item in the Sitecore client (not the external website). The link will be embedded in a broken links report email. The user should be able to click the link and launch the Sitecore content editor with that Item auto-selected in the tree.

I have found Mark Ursino's solution on his blog here, but unfortunately, it only works if you are actively logged into Sitecore (Otherwise, it brings you to the Sitecore Desktop after logging in).

I am running Sitecore.NET 6.4.1 (rev. 110324)

UPDATE

Just to close the loop on Marko's solution:

public void Process(LoggedInArgs args)
{
    string url = HttpUtility.UrlDecode(WebUtil.GetQueryString("url"));

    // Ensure we're dealing with the client login site and there is a URL to redirect to
    if (Sitecore.Context.GetSiteName() == "login" &&
        !String.IsNullOrEmpty(url))
    {
        var queryString = WebUtil.ParseQueryString(url);

        // Check for redirect param to prevent accidental redirections
        if (queryString.ContainsKey("redirectAfterLogin"))
                WebUtil.Redirect(url);
    }
}

Body:
Here's what I've used before:

There's an option in the sitecore web.config to send through raw url's. Set that on using this patch file

<setting name="Authentication.SaveRawUrl">
  <patch:attribute name="value">true</patch:attribute>
</setting>

Then, I added an additional processor into the loggedin processor after the CleanupUserProfile which reads the querystring parameter(s) and redirects to the appropriate page. This processor is called everytime, regardless of if the user has logged in before, or not.

The signature for my custom logged in processor is

namespace [...]
{
    public class LoginModeSwitcher
    {
        public void Process(LoggedInArgs args)
        {
            // your code here
        }
    }
}

This is the patch config I've used for the logged in processor:

<processors>
  <loggedin>
    <processor patch:after="*[@type='Sitecore.Pipelines.LoggedIn.CleanupUserProfile, Sitecore.Kernel']" mode="on" type="[...].LoginModeSwitcher, [ASSEMBLY]" />
  </loggedin>
</processors>

The links in the email link contain a querystring parameter to tell my code that we want to redirect after login and other querystring parameters to tell it where to redirect the user.


问:
Search in an ArrayList C#
```<code>class EmployeeDAL
{
    private ArrayList _employees;

    public EmployeeDAL()
    {
        _employees = new ArrayList();
        _employees.Add(new Employee { EmployeeID = 1, EmployeeName = "Ram", Salary = 50000 });
        _employees.Add(new Employee { EmployeeID = 2, EmployeeName = "Sahaym", Salary = 40000 });
        _employees.Add(new Employee { EmployeeID = 3, EmployeeName = "Gopi", Salary = 55000 });
        _employees.Add(new Employee { EmployeeID = 4, EmployeeName = "Prakash", Salary = 45000 });
        _employees.Add(new Employee { EmployeeID = 5, EmployeeName = "Dheeraj", Salary = 60000 });
        _employees.Add(new Employee { EmployeeID = 6, EmployeeName = "Shibhu", Salary = 50000 });
    }

    public bool DeleteEmployee(int id)
    {
        if (_employees.Contains(id))
        {
            _employees.Remove(id);
            return true;
        }
        else
            return false;
    }
}
</code>```

I want to delete an employee with specific id using DeleteEmployee(id) method. How can I do this in ArrayList ?

答:
Hi as an answer to your question you can use the code below :

```<code>public bool DeleteEmployee(int id)
{
        var employees = _employees.Cast<Employee>()
            .Where(e => e.EmployeeID == id)
            .Distinct();

        if (employees.Count() == 0)
            return false;
        else
            foreach (var employee in employees.ToList())
                _employees.Remove(employee);
        return true;
 }
</code>```

But in my opinion, if it's possible, you should use another type of collection like a List, it could be easier to handle than an ArrayList.

Title: Search in an ArrayList C#

Body:
class EmployeeDAL
{
    private ArrayList _employees;

    public EmployeeDAL()
    {
        _employees = new ArrayList();
        _employees.Add(new Employee { EmployeeID = 1, EmployeeName = "Ram", Salary = 50000 });
        _employees.Add(new Employee { EmployeeID = 2, EmployeeName = "Sahaym", Salary = 40000 });
        _employees.Add(new Employee { EmployeeID = 3, EmployeeName = "Gopi", Salary = 55000 });
        _employees.Add(new Employee { EmployeeID = 4, EmployeeName = "Prakash", Salary = 45000 });
        _employees.Add(new Employee { EmployeeID = 5, EmployeeName = "Dheeraj", Salary = 60000 });
        _employees.Add(new Employee { EmployeeID = 6, EmployeeName = "Shibhu", Salary = 50000 });
    }

    public bool DeleteEmployee(int id)
    {
        if (_employees.Contains(id))
        {
            _employees.Remove(id);
            return true;
        }
        else
            return false;
    }
}

I want to delete an employee with specific id using DeleteEmployee(id) method. How can I do this in ArrayList ?

Body:
Hi as an answer to your question you can use the code below :

public bool DeleteEmployee(int id)
{
        var employees = _employees.Cast<Employee>()
            .Where(e => e.EmployeeID == id)
            .Distinct();

        if (employees.Count() == 0)
            return false;
        else
            foreach (var employee in employees.ToList())
                _employees.Remove(employee);
        return true;
 }

But in my opinion, if it's possible, you should use another type of collection like a List, it could be easier to handle than an ArrayList.


问:
PartialView is not showing in Asp.net MVC?
I have an array which as the number(Id's of some tags) and I am passing this array to the action method using ajax call when this array passed to the controller action method(RawTagCreation) and then the numbers in this arrays are used to get data from database and then pass to another ViewModel object  (rawTagVMs) and then I am returning the partial view with this ViewModel object. The problem is that the partial view is not showing?
Basically success event of ajax call is also not fired.

```<code>function selectedValues() {
            var datas = [];
            $('#search_to option').each(function () {
                datas.push($(this).attr('value'));
            });
            console.log(datas);
            if (datas.length > 0) {
                $.ajax({
                    url: "@Url.Action("RawTagCreation", "SourceTagMapping")",
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({ 'selectedTags': datas }),
                    success: function (data) {
                        debugger;
                        $('#myModalContent').html(data);
                        $('#myModal').modal('show');
                    }
                });
            }
            else {
                alert('Please Select One or More Raw Tags')
            }
        }
</code>```

The action method is given here

```<code> public ActionResult RawTagCreation(int[] selectedTags)
        {
            List<RawTagVM> rawTagVMs = new List<RawTagVM>();
            if (ModelState.IsValid)
            {
                foreach (var item in selectedTags)
                {

                    var OldSourecTag = db.Real_Raw_Points.Where(x => x.Source_Tag_Id_Fk == item).FirstOrDefault();
                    var OPCTag = db.OPC_SourceTags.Where(x => x.Source_Tag_Id == item).FirstOrDefault();
                    if (OldSourecTag == null)
                    {
                        RawTagVM objToInsertRawTags = new RawTagVM();
                        objToInsertRawTags.Source_Tag_Id_Fk = item;
                        objToInsertRawTags.R_Tag_Name = "Provide Tag Name";
                        rawTagVMs.Add(objToInsertRawTags);

                    }
                }
                return PartialView("_Update_TagNames", rawTagVMs);
            }
            return View();
        }
</code>```

PartialView is here

```<code>@model List<OmniConnect.ViewModel.RawTagViews.RawTagVM>
<div class="modal-header">
    <h3 class="modal-title" id="exampleModalLabel">Update The Raw Tag Names</h3>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">×</span>
    </button>
</div>

<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary" onclick="Confirm()">Confirm Update</button>
</div>
</code>```

答:
when you try ajax call
you can't return partial view

if you want return a view you must use form like Html.Beginform
and submit

if you want return success method you must return a value may be string
and append it to a tag

```<code> public ActionResult RawTagCreation(int[] selectedTags)
    {
        List<RawTagVM> rawTagVMs = new List<RawTagVM>();
        if (ModelState.IsValid)
        {

            return Json("<div>any view</div");
        }
        return json("");
    }
</code>```

and then you can use like this:

```<code> $.ajax({
                url: "@Url.Action("RawTagCreation", "SourceTagMapping")",
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({ 'selectedTags': datas }),
                success: function (data) {
                    debugger;
                    $('#myModalContent').html(data);
                    $('#myModal').modal('show');
                }
            });
</code>```

Body:
I have an array which as the number(Id's of some tags) and I am passing this array to the action method using ajax call when this array passed to the controller action method(RawTagCreation) and then the numbers in this arrays are used to get data from database and then pass to another ViewModel object  (rawTagVMs) and then I am returning the partial view with this ViewModel object. The problem is that the partial view is not showing?
Basically success event of ajax call is also not fired.

function selectedValues() {
            var datas = [];
            $('#search_to option').each(function () {
                datas.push($(this).attr('value'));
            });
            console.log(datas);
            if (datas.length > 0) {
                $.ajax({
                    url: "@Url.Action("RawTagCreation", "SourceTagMapping")",
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({ 'selectedTags': datas }),
                    success: function (data) {
                        debugger;
                        $('#myModalContent').html(data);
                        $('#myModal').modal('show');
                    }
                });
            }
            else {
                alert('Please Select One or More Raw Tags')
            }
        }

The action method is given here

 public ActionResult RawTagCreation(int[] selectedTags)
        {
            List<RawTagVM> rawTagVMs = new List<RawTagVM>();
            if (ModelState.IsValid)
            {
                foreach (var item in selectedTags)
                {

                    var OldSourecTag = db.Real_Raw_Points.Where(x => x.Source_Tag_Id_Fk == item).FirstOrDefault();
                    var OPCTag = db.OPC_SourceTags.Where(x => x.Source_Tag_Id == item).FirstOrDefault();
                    if (OldSourecTag == null)
                    {
                        RawTagVM objToInsertRawTags = new RawTagVM();
                        objToInsertRawTags.Source_Tag_Id_Fk = item;
                        objToInsertRawTags.R_Tag_Name = "Provide Tag Name";
                        rawTagVMs.Add(objToInsertRawTags);

                    }
                }
                return PartialView("_Update_TagNames", rawTagVMs);
            }
            return View();
        }

PartialView is here

@model List<OmniConnect.ViewModel.RawTagViews.RawTagVM>

Update The Raw Tag Names

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        ×
    </button>

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary" onclick="Confirm()">Confirm Update</button>

Body:
when you try ajax call
you can't return partial view

if you want return a view you must use form like Html.Beginform
and submit

if you want return success method you must return a value may be string
and append it to a tag

 public ActionResult RawTagCreation(int[] selectedTags)
    {
        List<RawTagVM> rawTagVMs = new List<RawTagVM>();
        if (ModelState.IsValid)
        {

            return Json("<div>any view</div");
        }
        return json("");
    }

and then you can use like this:

 $.ajax({
                url: "@Url.Action("RawTagCreation", "SourceTagMapping")",
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({ 'selectedTags': datas }),
                success: function (data) {
                    debugger;
                    $('#myModalContent').html(data);
                    $('#myModal').modal('show');
                }
            });


问:
I need to count both vowels and consonants but i am stumped on the consonants
I can't figure out how to have both vowels and consonants. The vowels part of the code works fine. I have no idea how to add the consonants.

```<code>import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter some text: ");
      String str = in.nextLine();
      System.out.println(str);

System.out.print("your input has " + count_Vowels(str) + "vowels");
    }
 public static int count_Vowels(String str)
    {
        int vcount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            {
              vcount++;
            }
        }
        return vcount;
    }
public static int count_Consanants(String str)
    {
      int ccount = 0;
      for (int i = 0; i < str.length(); i++)
    {
      char ch = str.charAt(i);
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
      {
        vcount++;
      }
      else
      {
        consonants++;
      }
    }
  }
}
</code>```

I cannot seem to figure out the consonant part of the code

答:
Process of elimination

You said:

i am stumped on the consonants

The basic idea is that after you have tested for the character being (a) of the Latin-script, (b) being a letter (not a digit, punctuation, etc.), and (c) not a vowel, you can assume you have a consonant.

As you can see at the center of the code example below, we examine each character with a cascading if statement, summarized here as pseudo-code:

```<code>        if( … not part of the Latin script, such as Korean or emoji )
        {
            other++;
        }
        else if( … not a letter, such as digit or punctuation )
        {
            other++;
        }
        else if ( … definitely a vowel )
        {
            vowel++;
        }
        else if ( … maybe a vowel (`y`) )
        {
            maybeVowel++;
        }
        else  // Else definitely not a vowel, so it must be a consonant.
        {
            consonant++;
        }
</code>```

char is legacy

The first two Answers are basically right, but use the obsolete char type.  That type handles less than half of the over 140,000 characters defined in Unicode. And those Answers assume only English without diacriticals and such.

Unicode code point

Instead, make a habit of using code point integer numbers instead.

```<code>String input = " Face with Medical Mask" ;
</code>```

Make a stream of the code point numbers for each character in the text.

```<code>IntStream intStream = input.codePoints() ;
</code>```

Materialize an array from the stream.

```<code>int[] codePoints = intStream.toArray();
</code>```

Loop each code point.

```<code>for ( int codePoint : codePoints )
{
    …
}
</code>```

First see if the character is within the Latin script defined in Unicode. See Identify if a Unicode code point represents a character from a certain script such as the Latin script?.

```<code>if ( Character.UnicodeScript.LATIN.equals( Character.UnicodeScript.of( codePoint ) ) ) { … } else { other ++ ; )
</code>```

Next we must test if this character is a letter or not.

```<code> if ( Character.isLetter( codePoint ) ) { … } else { other ++ ; )
</code>```

To simplify our comparisons, we should convert to lowercase.

```<code>int lowercaseCodePoint = Character.toLowerCase( codePoint );
</code>```

Next test for vowels. I do not know that Java or Unicode provides a test for vowel versus consonant. So we must define a set of vowels ourselves. I do not know about all Latin-based languages, but I can at least cover English vowels. Of course, y is tricky, so I will count that as in a maybeVowel count.

```<code>int[] vowelCodePoints = "aeiou".codePoints().toArray();
int[] maybeVowelCodePoints = "y".codePoints().toArray();
</code>```

We will want to see if those arrays contain each character's code point number. So sort the arrays to enable a binary search.

```<code>Arrays.sort( vowelCodePoints );
Arrays.sort( maybeVowelCodePoints );
</code>```

Add a test for vowel.

```<code>String input = " Face with Medical Mask" ;
</code>```0

Add a test for maybe vowel.

```<code>String input = " Face with Medical Mask" ;
</code>```1

And if we get past both those vowel-related tests, we can assume our non-vowel lowercase Latin-script character is a consonant.

Put all the code together.

```<code>String input = " Face with Medical Mask" ;
</code>```2

Dump to console.

```<code>// Report
System.out.println( "RESULTS  ----------------------------------------------" );
System.out.println( "input = " + input );
System.out.println( "codePoints = " + Arrays.toString( codePoints ) );
System.out.println( "Count code points: " + codePoints.length );
System.out.println( "vowelCodePoints = " + Arrays.toString( vowelCodePoints ) );
System.out.println( "maybeVowelCodePoints = " + Arrays.toString( maybeVowelCodePoints ) );
System.out.println( "vowel = " + vowel );
System.out.println( "maybeVowel = " + maybeVowel );
System.out.println( "consonant = " + consonant );
System.out.println( "other = " + other );
System.out.println( "vowel + maybeVowel+consonant+other = " + ( vowel + maybeVowel + consonant + other ) );
System.out.println( "END  ----------------------------------------------" );
</code>```

Example usage

When run.

RESULTS  ----------------------------------------------
input =  Face with Medical Mask
codePoints = [128567, 32, 70, 97, 99, 101, 32, 119, 105, 116, 104, 32, 77, 101, 100, 105, 99, 97, 108, 32, 77, 97, 115, 107]
Count code points: 24
vowelCodePoints = [97, 101, 105, 111, 117]
maybeVowelCodePoints = [121]
vowel = 7
maybeVowel = 0
consonant = 12
other = 5
vowel + maybeVowel+consonant+other = 24
END  ----------------------------------------------
```

Tip: Read the humorous article, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).

Body:
I can't figure out how to have both vowels and consonants. The vowels part of the code works fine. I have no idea how to add the consonants.

import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter some text: ");
      String str = in.nextLine();
      System.out.println(str);

System.out.print("your input has " + count_Vowels(str) + "vowels");
    }
 public static int count_Vowels(String str)
    {
        int vcount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            {
              vcount++;
            }
        }
        return vcount;
    }
public static int count_Consanants(String str)
    {
      int ccount = 0;
      for (int i = 0; i < str.length(); i++)
    {
      char ch = str.charAt(i);
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
      {
        vcount++;
      }
      else
      {
        consonants++;
      }
    }
  }
}

I cannot seem to figure out the consonant part of the code

Body:
Process of elimination

You said:

i am stumped on the consonants

The basic idea is that after you have tested for the character being (a) of the Latin-script, (b) being a letter (not a digit, punctuation, etc.), and (c) not a vowel, you can assume you have a consonant.

As you can see at the center of the code example below, we examine each character with a cascading if statement, summarized here as pseudo-code:

        if( … not part of the Latin script, such as Korean or emoji )
        {
            other++;
        }
        else if( … not a letter, such as digit or punctuation )
        {
            other++;
        }
        else if ( … definitely a vowel )
        {
            vowel++;
        }
        else if ( … maybe a vowel (`y`) )
        {
            maybeVowel++;
        }
        else  // Else definitely not a vowel, so it must be a consonant.
        {
            consonant++;
        }

char is legacy

The first two Answers are basically right, but use the obsolete char type.  That type handles less than half of the over 140,000 characters defined in Unicode. And those Answers assume only English without diacriticals and such.

Unicode code point

Instead, make a habit of using code point integer numbers instead.

String input = " Face with Medical Mask" ;

Make a stream of the code point numbers for each character in the text.

IntStream intStream = input.codePoints() ;

Materialize an array from the stream.

int[] codePoints = intStream.toArray();

Loop each code point.

for ( int codePoint : codePoints )
{
    …
}

First see if the character is within the Latin script defined in Unicode. See Identify if a Unicode code point represents a character from a certain script such as the Latin script?.

if ( Character.UnicodeScript.LATIN.equals( Character.UnicodeScript.of( codePoint ) ) ) { … } else { other ++ ; )

Next we must test if this character is a letter or not.

 if ( Character.isLetter( codePoint ) ) { … } else { other ++ ; )

To simplify our comparisons, we should convert to lowercase.

int lowercaseCodePoint = Character.toLowerCase( codePoint );

Next test for vowels. I do not know that Java or Unicode provides a test for vowel versus consonant. So we must define a set of vowels ourselves. I do not know about all Latin-based languages, but I can at least cover English vowels. Of course, y is tricky, so I will count that as in a maybeVowel count.

int[] vowelCodePoints = "aeiou".codePoints().toArray();
int[] maybeVowelCodePoints = "y".codePoints().toArray();

We will want to see if those arrays contain each character's code point number. So sort the arrays to enable a binary search.

Arrays.sort( vowelCodePoints );
Arrays.sort( maybeVowelCodePoints );

Add a test for vowel.

 if ( Arrays.binarySearch( vowelCodePoints , lowercaseCodePoint ) >= 0 )

Add a test for maybe vowel.

else if ( Arrays.binarySearch( maybeVowelCodePoints , lowercaseCodePoint ) >= 0 )

And if we get past both those vowel-related tests, we can assume our non-vowel lowercase Latin-script character is a consonant.

Put all the code together.

String input = " Face with Medical Mask";

IntStream intStream = input.codePoints();

int[] codePoints = intStream.toArray();
int[] vowelCodePoints = "aeiou".codePoints().toArray();
int[] maybeVowelCodePoints = "y".codePoints().toArray();

// Sort those arrays to enable binary search.
Arrays.sort( vowelCodePoints );
Arrays.sort( maybeVowelCodePoints );

int vowel = 0;
int maybeVowel = 0;
int consonant = 0;
int other = 0;
for ( int codePoint : codePoints )
{
    if ( Character.UnicodeScript.LATIN.equals( Character.UnicodeScript.of( codePoint ) ) )
    {
        if ( Character.isLetter( codePoint ) )
        {
            int lowercaseCodePoint = Character.toLowerCase( codePoint );
            if ( Arrays.binarySearch( vowelCodePoints , lowercaseCodePoint ) >= 0 )
            {  // If definitely a vowel…
                vowel++;
            } else if ( Arrays.binarySearch( maybeVowelCodePoints , lowercaseCodePoint ) >= 0 )
            {  // Else if maybe a vowel…
                maybeVowel++;
            } else
            {  // Else this non-vowel lowercase letter from Latin-script must be a consonant.
                consonant++;
            }
        } else { other++; }  // Else not a letter.
    } else { other++; }      // Else not in Latin script.
}

Dump to console.

// Report
System.out.println( "RESULTS  ----------------------------------------------" );
System.out.println( "input = " + input );
System.out.println( "codePoints = " + Arrays.toString( codePoints ) );
System.out.println( "Count code points: " + codePoints.length );
System.out.println( "vowelCodePoints = " + Arrays.toString( vowelCodePoints ) );
System.out.println( "maybeVowelCodePoints = " + Arrays.toString( maybeVowelCodePoints ) );
System.out.println( "vowel = " + vowel );
System.out.println( "maybeVowel = " + maybeVowel );
System.out.println( "consonant = " + consonant );
System.out.println( "other = " + other );
System.out.println( "vowel + maybeVowel+consonant+other = " + ( vowel + maybeVowel + consonant + other ) );
System.out.println( "END  ----------------------------------------------" );

Example usage

When run.

RESULTS  ----------------------------------------------
input =  Face with Medical Mask
codePoints = [128567, 32, 70, 97, 99, 101, 32, 119, 105, 116, 104, 32, 77, 101, 100, 105, 99, 97, 108, 32, 77, 97, 115, 107]
Count code points: 24
vowelCodePoints = [97, 101, 105, 111, 117]
maybeVowelCodePoints = [121]
vowel = 7
maybeVowel = 0
consonant = 12
other = 5
vowel + maybeVowel+consonant+other = 24
END  ----------------------------------------------

Tip: Read the humorous article, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).


问:
How to compare two dictionaries in C#?

There are different count and different order of dictionaries

If the key of list A and list B match, I would like to bring the value of list B and modify the value of list A.

Sample Code :

```<code>public static List<Dictionary<string, string>> ListDicOne = new List<Dictionary<string, string>>();

public static List<Dictionary<string, string>> ListDicTwo = new List<Dictionary<string, string>>();

(...)
ListDicOne[0].Add("ABCD", "");          // empty value
ListDicOne[1].Add("ABCD", "");
ListDicOne[2].Add("EFGH", "test");

ListDicTwo[0].Add("AABC", "oooo");
ListDicTwo[1].Add("ABCD", "WOW");
ListDicTwo[2].Add("CCDD", "haha");
ListDicTwo[3].Add("CCDD", "haha");
</code>```

expected result value :

```<code>// Console Write key and value of ListDicA

ABCD \t WOW
ABCD \t WOW
EFGH \t test
</code>```

答:
I will take a guess and assume you really only want to deal with two dictionaries, and not two lists of many one-item dictionaries, which would not make any sense at all.

First, the dictionaries should be declared like this (I also assume they don't have to be public):

```<code>private static Dictionary<string, string> ListDicOne = new Dictionary<string, string>();

private static Dictionary<string, string> ListDicTwo = new Dictionary<string, string>();
</code>```

And then, the usage could be like this:

```<code>ListDicOne.Add("AABC", ""); // I changed the key, they must be unique
ListDicOne.Add("ABCD", "");
ListDicOne.Add("EFGH", "test");

ListDicTwo.Add("AABC", "oooo");
ListDicTwo.Add("ABCD", "WOW");
ListDicTwo.Add("CCDD", "haha");
ListDicTwo.Add("CCDE", "haha"); // I changed the key, they must be unique

foreach (var item in ListDicTwo)
{
    if (ListDicOne.ContainsKey(item.Key))
        ListDicOne[item.Key] = ListDicTwo[item.Key];
}
</code>```

The final state of ListDicOne is:

```<code>("AABC", "oooo")
("ABCD", "WOW")
("EFGH", "test")
</code>```

I hope you find this clarifying and useful.

** Update **

Considering a string-string list with non-unique keys:

```<code>private static List<Tuple<string, string>> ListOne = new List<Tuple<string, string>>();

private static List<Tuple<string, string>> ListTwo = new List<Tuple<string, string>>();

(...)

ListOne.Add(Tuple.Create("ABCD", ""));
ListOne.Add(Tuple.Create("ABCD", ""));
ListOne.Add(Tuple.Create("EFGH", "test"));

ListTwo.Add(Tuple.Create("AABC", "oooo"));
ListTwo.Add(Tuple.Create("ABCD", "WOW"));
ListTwo.Add(Tuple.Create("CCDD", "haha"));
ListTwo.Add(Tuple.Create("CCDD", "haha"));

foreach (var l2item in ListTwo)
{
    for (int i = 0; i < ListOne.Count; i++)
    {
        if (ListOne[i].Item1 == l2item.Item1)
            ListOne[i] = Tuple.Create(l2item.Item1, l2item.Item2);
    }
}
</code>```

Note 1: tuples are immutable, so you need to create a new one when changing Item2.

Note 2: You cannot use foreach when you need to alter the iterated list, therefore I used a for instead.

Note 3: If ListTwo happens to have a two different key-value combinations (supposedly won't happen), the second one will overwrite the first.

This is the end result with your test values:

```<code>("ABCD", "WOW")
("ABCD", "WOW")
("EFGH", "test")
</code>```

Title: How to compare two dictionaries in C#?

Body:
There are different count and different order of dictionaries

If the key of list A and list B match, I would like to bring the value of list B and modify the value of list A.

Sample Code :

public static List<Dictionary<string, string>> ListDicOne = new List<Dictionary<string, string>>();

public static List<Dictionary<string, string>> ListDicTwo = new List<Dictionary<string, string>>();

(...)
ListDicOne[0].Add("ABCD", "");          // empty value
ListDicOne[1].Add("ABCD", "");
ListDicOne[2].Add("EFGH", "test");

ListDicTwo[0].Add("AABC", "oooo");
ListDicTwo[1].Add("ABCD", "WOW");
ListDicTwo[2].Add("CCDD", "haha");
ListDicTwo[3].Add("CCDD", "haha");

expected result value :

// Console Write key and value of ListDicA

ABCD \t WOW
ABCD \t WOW
EFGH \t test

Body:
I will take a guess and assume you really only want to deal with two dictionaries, and not two lists of many one-item dictionaries, which would not make any sense at all.

First, the dictionaries should be declared like this (I also assume they don't have to be public):

private static Dictionary<string, string> ListDicOne = new Dictionary<string, string>();

private static Dictionary<string, string> ListDicTwo = new Dictionary<string, string>();

And then, the usage could be like this:

ListDicOne.Add("AABC", ""); // I changed the key, they must be unique
ListDicOne.Add("ABCD", "");
ListDicOne.Add("EFGH", "test");

ListDicTwo.Add("AABC", "oooo");
ListDicTwo.Add("ABCD", "WOW");
ListDicTwo.Add("CCDD", "haha");
ListDicTwo.Add("CCDE", "haha"); // I changed the key, they must be unique

foreach (var item in ListDicTwo)
{
    if (ListDicOne.ContainsKey(item.Key))
        ListDicOne[item.Key] = ListDicTwo[item.Key];
}

The final state of ListDicOne is:

("AABC", "oooo")
("ABCD", "WOW")
("EFGH", "test")

I hope you find this clarifying and useful.

** Update **

Considering a string-string list with non-unique keys:

private static List<Tuple<string, string>> ListOne = new List<Tuple<string, string>>();

private static List<Tuple<string, string>> ListTwo = new List<Tuple<string, string>>();

(...)

ListOne.Add(Tuple.Create("ABCD", ""));
ListOne.Add(Tuple.Create("ABCD", ""));
ListOne.Add(Tuple.Create("EFGH", "test"));

ListTwo.Add(Tuple.Create("AABC", "oooo"));
ListTwo.Add(Tuple.Create("ABCD", "WOW"));
ListTwo.Add(Tuple.Create("CCDD", "haha"));
ListTwo.Add(Tuple.Create("CCDD", "haha"));

foreach (var l2item in ListTwo)
{
    for (int i = 0; i < ListOne.Count; i++)
    {
        if (ListOne[i].Item1 == l2item.Item1)
            ListOne[i] = Tuple.Create(l2item.Item1, l2item.Item2);
    }
}

Note 1: tuples are immutable, so you need to create a new one when changing Item2.

Note 2: You cannot use foreach when you need to alter the iterated list, therefore I used a for instead.

Note 3: If ListTwo happens to have a two different key-value combinations (supposedly won't happen), the second one will overwrite the first.

This is the end result with your test values:

("ABCD", "WOW")
("ABCD", "WOW")
("EFGH", "test")


问:
Error: cannot find symbol import androidx.navigation.fragment.navArgs
I was doing the "Build Your First Android App in Java" from the website https://codelabs.developers.google.com/codelabs/build-your-first-android-app/#8.
Everything worked until I got to step 8, which was to import androidx.navigation.fragment.navArgs, but I got an error:

import androidx.navigation.fragment.navArgs;

How do I fix it? What does it mean?

答:
This is an error with the codelab, pulled in from the Kotlin version of the code lab which uses the by navArgs() Kotlin property delegate to retrieve the arguments (as explained in the Using Safe Args guide).

This isn't needed in Java, as you use the SecondFragmentArgs.fromBundle(getArguments()) method to retrieve the arguments class.

Therefore, you can just skip that import: it isn't used anywhere and can safely be ignored.


问:
Getting HttpResponse in Django from Javascript fetch
I have a django endpoint:

```<code>def endpoint(request):
    return HttpResponse("Hello!")
</code>```

I call it in JS like this:

```<code>fetch(baseUrl + "endpoint", {
      method: "POST",
    }).then(function(data) {
        // HOW DO I ACCESS THE "Hello!"?
    });
</code>```

How do i access the hello! in the .then part? Thanks!!

答:
Something like this:</p>

```<code>fetch(baseUrl + "endpoint", {
      method: "POST",
}).then(function(data) {
        data.text().then( text => console.log(text) );
});
</code>```

Body:
I have a django endpoint:

def endpoint(request):
    return HttpResponse("Hello!")

I call it in JS like this:

fetch(baseUrl + "endpoint", {
      method: "POST",
    }).then(function(data) {
        // HOW DO I ACCESS THE "Hello!"?
    });

How do i access the hello! in the .then part? Thanks!!

Body:
Something like this:

fetch(baseUrl + "endpoint", {
      method: "POST",
}).then(function(data) {
        data.text().then( text => console.log(text) );
});


问:
Equivalent of passing `-p zlib` argument to `nix-shell` in `shell.nix`
If I build my Haskell project under nix-shell it gives error about missing zlib.

If I build the project in nix-shell using nix-shell -p zlib then the project sees zlib and builds successfully.

How can I add the zlib package to shell.nix file so that passing -p zlib is no longer needed?

Note: the builds were done using cabal v2-build

For building with stack I had to do the following

This is how my shell.nix is currently defined:

```<code>{ nixpkgs ? import <nixpkgs> {}, compiler ? "default", doBenchmark ? false }:

let

  inherit (nixpkgs) pkgs;

  f = { mkDerivation, base, directory, stdenv, text, turtle, zlib }:
      mkDerivation {
        pname = "haskell-editor-setup";
        version = "0.1.0.0";
        src = ./.;
        isLibrary = false;
        isExecutable = true;
        executableHaskellDepends = [ base directory text turtle zlib ];
        description = "Terminal program that will set up Haskell environment with a target selected editor or IDE";
        license = stdenv.lib.licenses.gpl3;
      };

  haskellPackages = if compiler == "default"
                       then pkgs.haskellPackages
                       else pkgs.haskell.packages.${compiler};

  variant = if doBenchmark then pkgs.haskell.lib.doBenchmark else pkgs.lib.id;

  drv = variant (haskellPackages.callPackage f {});

in

  if pkgs.lib.inNixShell then drv.env else drv
</code>```

答:
You want to create a derivation which has those as dependencies. There's a trivial builder called runCommand which runs a script you give it. For shell.nix the builder won't actually be used, it's only for providing a shell, so you can give this an empty script:

with import <nixpkgs> { };

runCommand "my-shell" {
  buildInputs = [ zlib ];
} ""
```

Body:
If I build my Haskell project under nix-shell it gives error about missing zlib.

If I build the project in nix-shell using nix-shell -p zlib then the project sees zlib and builds successfully.

How can I add the zlib package to shell.nix file so that passing -p zlib is no longer needed?

Note: the builds were done using cabal v2-build

For building with stack I had to do the following

This is how my shell.nix is currently defined:

{ nixpkgs ? import <nixpkgs> {}, compiler ? "default", doBenchmark ? false }:

let

  inherit (nixpkgs) pkgs;

  f = { mkDerivation, base, directory, stdenv, text, turtle, zlib }:
      mkDerivation {
        pname = "haskell-editor-setup";
        version = "0.1.0.0";
        src = ./.;
        isLibrary = false;
        isExecutable = true;
        executableHaskellDepends = [ base directory text turtle zlib ];
        description = "Terminal program that will set up Haskell environment with a target selected editor or IDE";
        license = stdenv.lib.licenses.gpl3;
      };

  haskellPackages = if compiler == "default"
                       then pkgs.haskellPackages
                       else pkgs.haskell.packages.${compiler};

  variant = if doBenchmark then pkgs.haskell.lib.doBenchmark else pkgs.lib.id;

  drv = variant (haskellPackages.callPackage f {});

in

  if pkgs.lib.inNixShell then drv.env else drv