问:
Add a column of buttons over an image in Flutter
I have a flutter app that I want to add "stories" to, but I am unable to do so cause I can't place 3 buttons over an image.

That's my desired look...

And this is what I can do so far...

And this is my code:-

```<code>

child: GestureDetector(
          child: Center(
            child: Stack(
              alignment: Alignment.bottomRight,
              children: [
                Image.network(
                  widget.url,
                ),
                Container(
                  child: Column(children: [
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    )
                  ]),
                )
              ],
            ),
          ),
          onTap: () => controller.next(),
        ),

</code>```

How can I achieve this effect?

Am I doing something with the Stack widget?

答:
Using Positioned inside Stack can solve your problem, Below code may work for you, You can position the Container where you want it to be.

Widget build(BuildContext context) {
    var ScreenHeight = MediaQuery.of(context).size.height;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Expenses App"),
          backgroundColor: Colors.pink[900],
          actions: [
            IconButton(
              icon: Icon(Icons.add),
              // onPressed: () => startAddNewTransaction(context),
            ),
          ],
        ),
        body: GestureDetector(
      child: Center(
      child: Stack(
        // alignment: Alignment.bottomRight,
        children: [
          Image.network(
            'https://picsum.photos/250?image=9',
          ),
          Positioned(
            top: ScreenHeight * 0.17,
            child: Container(
              child: Column(children: [
                Container(
                  color: Colors.grey,
                  child:
                  Column(children: [Icon(Icons.share), Text('مشاركة')]),
                ),
                SizedBox(height: ScreenHeight * 0.01),
                Container(
                  color: Colors.grey,
                  child:
                  Column(children: [Icon(Icons.share), Text('مشاركة')]),
                ),
                SizedBox(height: ScreenHeight * 0.01),
                Container(
                  color: Colors.grey,
                  child:
                  Column(children: [Icon(Icons.share), Text('مشاركة')]),
                )
              ]),
            ),
          )
        ],
      ),
    ),
    // onTap: () => controller.next(),
    ),

      ),
    );
  }
```

Body:
I have a flutter app that I want to add "stories" to, but I am unable to do so cause I can't place 3 buttons over an image.

That's my desired look...

And this is what I can do so far...

And this is my code:-

child: GestureDetector(
          child: Center(
            child: Stack(
              alignment: Alignment.bottomRight,
              children: [
                Image.network(
                  widget.url,
                ),
                Container(
                  child: Column(children: [
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    )
                  ]),
                )
              ],
            ),
          ),
          onTap: () => controller.next(),
        ),

How can I achieve this effect?

Am I doing something with the Stack widget?


来源: stackexchange

问:
Redux dispatch fires with correct payload, but state is not updated
I'm building a game using react-redux and TypeScript. I've got TS and React down, but redux... less so.

When the player clicks the start game button, the main menu is hidden via manipulation of redux state and the "gameState" is generated. "gameState" contains all the relevant information for the game world and entities therein, and is several thousand lines of serializable JSON. This part is definitely working, the problem comes when I try to dispatch to update it. I can see from the Redux browser extension that the payload being sent to the reducer function updateGameState is correct, but after the dispatch has been completed it's as if it never happened.

My question is simple: what am I doing wrong?

The code for the previously-mentioned dispatch is:

    let nGS = gameStateGenerator.create(scene)
    dispatch(updateGameState(nGS))
```
<p>The layout of this part of the redux logic is as shown below. The four children of multiverse, universes, species, connections, and players, should all be populated, but are not.</p>
<p><img src="https://i.stack.imgur.com/wudZz.png" alt="layout of redux state tree" /></p>
<p>I'm using combined reducers, as follows. I've not used ES6 notation for the reducer object properties as part of my attempts to rule out causes (which hopefully speaks to my level of desperation).</p>
<p>store.ts (top level)</p>
<pre class="lang-js prettyprint-override"><code>import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import gameState from '../features/gameState/gameState';

export const store = configureStore({
  reducer: {
    gameState: gameState
  },
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;
</code>```

gameState.ts (first and so far only child of root)

import { combineReducers, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { GameState } from '../../interfaces/GameState';
import flags, { initialState as flagsInitialState} from '../flags/flags';
import multiverse, { initialState as multiverseInitialState } from '../multiverse/multiverse';

export const initialState: GameState = {
  multiverse: multiverseInitialState,
  flags: flagsInitialState
};

export const gameState = createSlice({
  name: 'gameState',
  initialState,
  reducers: {
    updateGameState: (state: GameState, action: PayloadAction<GameState>) => {
      return Object.assign({}, state, action.payload)
    }
  }
});

export const { updateGameState } = gameState.actions;

export default combineReducers({
  flags: flags,
  multiverse: multiverse
})
```
<p>flags.ts</p>
<pre class="lang-js prettyprint-override"><code>import { createSlice } from '@reduxjs/toolkit';
import { FlagsState } from '../../interfaces/Flags';

export const initialState: FlagsState = {
  ui: {
    showMainMenu: true,
    showWelcome: true,
    gameStarted: false,
    gameLoading: false,
    gameLoaded: false
  }
};

export const flags = createSlice({
  name: 'flags',
  initialState,
  reducers: {
    startGame: (state: Required<FlagsState>) => {
      return Object.assign({}, state, {
        ui: {
          ...state.ui,
          showMainMenu: false,
          gameStarted: true,
          gameLoading: true
        }
      })
    },
    gameLoaded: (state: Required<FlagsState>) => {
      return Object.assign({}, state, {
        ui: {
          ...state.ui,
          gameLoaded: true
        }
      })
    }
  }
});

export const { startGame, gameLoaded } = flags.actions;
export const getState = (state: FlagsState) => state;

export default flags.reducer;
</code>```

And finally multiverse.ts

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Multiverse } from '../../interfaces/Multiverse';
import { Universe } from './../../interfaces/Universes';

export const initialState: Multiverse = {
  universes: [],
  species: [],
  connections: [],
  players: []
};

export const multiverse = createSlice({
  name: 'multiverse',
  initialState,
  reducers: {
    setUniverses: (state: Required<Multiverse>, action: PayloadAction<Universe[]>) => {
      return Object.assign({}, state, { universes: action.payload })
    }
  }
});

export const { setUniverses } = multiverse.actions;
export const getState = (state: Multiverse) => state;

export default multiverse.reducer;
```

答:
I'm think the trouble comes from your reducer, you use Object assign and return.
Redux-Toolkit uses Immer to change the state with no mutating like this :

```<code>(state, action) => state.value = action.payload
</code>```

See the doc, https://redux-toolkit.js.org/usage/immer-reducers#immutable-updates-with-immer

So for you, you can do something like :

```<code>state.univers = {...state.univers, ... action.payload}
</code>```

with no return.

ContentLicense: CC BY-SA 4.0

Body:
I'm building a game using react-redux and TypeScript. I've got TS and React down, but redux... less so.

When the player clicks the start game button, the main menu is hidden via manipulation of redux state and the "gameState" is generated. "gameState" contains all the relevant information for the game world and entities therein, and is several thousand lines of serializable JSON. This part is definitely working, the problem comes when I try to dispatch to update it. I can see from the Redux browser extension that the payload being sent to the reducer function updateGameState is correct, but after the dispatch has been completed it's as if it never happened.

My question is simple: what am I doing wrong?

The code for the previously-mentioned dispatch is:

    let nGS = gameStateGenerator.create(scene)
    dispatch(updateGameState(nGS))

The layout of this part of the redux logic is as shown below. The four children of multiverse, universes, species, connections, and players, should all be populated, but are not.

I'm using combined reducers, as follows. I've not used ES6 notation for the reducer object properties as part of my attempts to rule out causes (which hopefully speaks to my level of desperation).

store.ts (top level)

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import gameState from '../features/gameState/gameState';

export const store = configureStore({
  reducer: {
    gameState: gameState
  },
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

gameState.ts (first and so far only child of root)

import { combineReducers, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { GameState } from '../../interfaces/GameState';
import flags, { initialState as flagsInitialState} from '../flags/flags';
import multiverse, { initialState as multiverseInitialState } from '../multiverse/multiverse';

export const initialState: GameState = {
  multiverse: multiverseInitialState,
  flags: flagsInitialState
};

export const gameState = createSlice({
  name: 'gameState',
  initialState,
  reducers: {
    updateGameState: (state: GameState, action: PayloadAction<GameState>) => {
      return Object.assign({}, state, action.payload)
    }
  }
});

export const { updateGameState } = gameState.actions;

export default combineReducers({
  flags: flags,
  multiverse: multiverse
})

flags.ts

import { createSlice } from '@reduxjs/toolkit';
import { FlagsState } from '../../interfaces/Flags';

export const initialState: FlagsState = {
  ui: {
    showMainMenu: true,
    showWelcome: true,
    gameStarted: false,
    gameLoading: false,
    gameLoaded: false
  }
};

export const flags = createSlice({
  name: 'flags',
  initialState,
  reducers: {
    startGame: (state: Required<FlagsState>) => {
      return Object.assign({}, state, {
        ui: {
          ...state.ui,
          showMainMenu: false,
          gameStarted: true,
          gameLoading: true
        }
      })
    },
    gameLoaded: (state: Required<FlagsState>) => {
      return Object.assign({}, state, {
        ui: {
          ...state.ui,
          gameLoaded: true
        }
      })
    }
  }
});

export const { startGame, gameLoaded } = flags.actions;
export const getState = (state: FlagsState) => state;

export default flags.reducer;

And finally multiverse.ts

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Multiverse } from '../../interfaces/Multiverse';
import { Universe } from './../../interfaces/Universes';

export const initialState: Multiverse = {
  universes: [],
  species: [],
  connections: [],
  players: []
};

export const multiverse = createSlice({
  name: 'multiverse',
  initialState,
  reducers: {
    setUniverses: (state: Required<Multiverse>, action: PayloadAction<Universe[]>) => {
      return Object.assign({}, state, { universes: action.payload })
    }
  }
});

export const { setUniverses } = multiverse.actions;
export const getState = (state: Multiverse) => state;

export default multiverse.reducer;

Body:
I'm think the trouble comes from your reducer, you use Object assign and return.
Redux-Toolkit uses Immer to change the state with no mutating like this :

(state, action) => state.value = action.payload

See the doc, https://redux-toolkit.js.org/usage/immer-reducers#immutable-updates-with-immer

So for you, you can do something like :

state.univers = {...state.univers, ... action.payload}

with no return.


问:
EF - AND NOT EXISTS (SELECT 1 ...) with Entity Framework
I am trying to run this query using Entity Framework in my ASP.NET MVC project but I am not succeeding. Could anyone help me do this using LINQ?

```<code>SELECT p.*
FROM Produtos p
WHERE p.enterpriseID = '00000000000191' and p.productId <> '14'
AND NOT EXISTS (SELECT 1 FROM SimilarProducts sp WHERE sp.similarId =
p.productId)
</code>```

TABLES:

```<code>PRODUCT                        SIMILARPRODUCTS
productId|enterpriseId         id|productId|similarId
</code>```

答:
EF Contains => sql in() : iterate all items (slower)

EF Any => sql exists() : iterate until conditions return true (faster)

```<code> await appDbContext.MasterTable
.Where(m => !m.DetailTable.Any(d => d.MasterId == m.Id))
.ToListAsync();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run this query using Entity Framework in my ASP.NET MVC project but I am not succeeding. Could anyone help me do this using LINQ?

SELECT p.*
FROM Produtos p
WHERE p.enterpriseID = '00000000000191' and p.productId <> '14'
AND NOT EXISTS (SELECT 1 FROM SimilarProducts sp WHERE sp.similarId =
p.productId)

TABLES:

PRODUCT                        SIMILARPRODUCTS
productId|enterpriseId         id|productId|similarId

Body:
EF Contains => sql in() : iterate all items (slower)

EF Any => sql exists() : iterate until conditions return true (faster)

 await appDbContext.MasterTable
.Where(m => !m.DetailTable.Any(d => d.MasterId == m.Id))
.ToListAsync();


问:
Audio and Video file
I am using mono 2.10.4 and monobjc. I want to be able to play H264 video file and an mp3 file. Monotouch has examples of playing the same on their web site(http://wiki.ios.xamarin.com/HowTo/Video/HowTo%3a_Playback_a_Video.).
But can the same be accomplished using mono and monobjc ?. What would be the libraries that I would need ?.</p>

答: There is a sample application named QTKitPlayer that demonstrate how to play a movie by using the QuickTime API; it is part of the Monobjc distribution.</p>

Title: Audio and Video file


问:
is there pybind11 method that has similar properties of PyString_AsString
I am trying to convert the c++ project  from boost to pybind11</p>
```<code>QString r = QString(PyString_AsString(result));"

QString r = QString(py::str(result));
</code>```

答:
In Pybind11 think you need to go through a std::string

```<code>QString r = QString(result.cast<std::string>().c_str());"
</code>```

You could of course just use PyString_AsString yourself:

```<code>QString r = QString(PyString_AsString(result.ptr());
</code>```

PyString_AsString is from a Python version that has been completely unsupported for >2 years. You should consider whether you should be using it at all.

Body:
I am trying to convert the c++ project  from boost to pybind11

QString r = QString(PyString_AsString(result));"

QString r = QString(py::str(result));

Body:
In Pybind11 think you need to go through a std::string

QString r = QString(result.cast<std::string>().c_str());"

You could of course just use PyString_AsString yourself:

QString r = QString(PyString_AsString(result.ptr());

PyString_AsString is from a Python version that has been completely unsupported for >2 years. You should consider whether you should be using it at all.


问:
How to use single Icon button to play and pause audio in flutter
How I can use single IconButton to play and pause the audio in flutter, using audio play package. Also if Icon I click on single list item it should change only one icon not all list icons. </p>

<p>And if anyone can suggest best audio player package to play list with inline audio it will be helpful. </p>

```<code>import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gradient_app_bar/gradient_app_bar.dart';
import 'package:http/http.dart' as http;
import 'package:jummamubarak/Screens/HomeScreen.dart';
import 'package:jummamubarak/Screens/ViewTone.dart';

class TonesListScreen extends StatefulWidget {
  @override
  _TonesListScreenState createState() => _TonesListScreenState();
}

class _TonesListScreenState extends State<TonesListScreen> {
  final String data =
      "https://api.airtable.com/v0/appZeBnQJQ0OaVoPQ/Ringtones?maxRecords=100000&view=Tones";
  List toneTitle;
  List toneurl;
  ScrollController _controller = new ScrollController();

  @override
  void initState() {
    super.initState();
    this.getJsonData();
  }

  Future<String> getJsonData() async {
    var response = await http.get(
      Uri.encodeFull(data),
      headers: {
        HttpHeaders.contentTypeHeader: "application/json",
        HttpHeaders.authorizationHeader: "Bearer keyr05is7vPCWxmYM"
      },
      // headers: {"Accept": "application/json"},
    );

    print(response.body);

    setState(() {
      // ignore: non_constant_identifier_names
      var ConvertDataToJson = json.decode(response.body);
      toneTitle = ConvertDataToJson['records'];
    });

    setState(() {
      // ignore: non_constant_identifier_names
      var ConvertDataToJson = json.decode(response.body);
      toneurl = ConvertDataToJson['records'];
    });

    return "Success";
  }

  Widget _files() {
    if (toneTitle == null) {
      return SpinKitCircle(
        color: Color(0xff34495E),
        size: 50.0,
      );
    } else {
      return ListView.builder(
        physics: const AlwaysScrollableScrollPhysics(), // new
        controller: _controller,
        itemCount: toneTitle == null ? 0 : toneTitle.length,
        itemBuilder: (BuildContext context, int index) {
          return Padding(
            padding: const EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0),
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Flexible(
                      child: Text(
                        toneTitle.reversed.toList()[index]['fields']['Name'],
                        style: GoogleFonts.muli(
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    RadiantGradientMask(
                      child: IconButton(
                        icon: Icon(
                          Icons.play_circle_filled,
                          color: Colors.white,
                          size: 40.0,
                        ),
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => ViewTone(
                                toneTitle: toneTitle.reversed.toList()[index]
                                    ['fields']['Name'],
                                toneUrl: toneurl.reversed.toList()[index]
                                    ['fields']['Url'],
                              ),
                            ),
                          );
                        },
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: GradientAppBar(
        gradient: LinearGradient(
          colors: [
            Color(0xff14d5a3),
            Color(0xff039cc1),
          ],
        ),
        title: Text(
          'Islamic Tones',
          style: GoogleFonts.muli(
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: _files(),
    );
  }
}

``
</code>```

答:
An audio player plugin that you can use in Flutter is audioplayers plugin. Simply initialize AudioPlayer to use functions play(), pause(), resume(), and stop(). Determine when you're going to play the audio from start and when pause/resume will be called on your use case. You can initialize a Timer each when the audio is played. If Timer is still set to 0, play the audio from the beginning. Else, call play/resume.

AudioPlayer audioPlayer = AudioPlayer();

// Call to play audio from the beginning
_playStart() async {
  int result = await audioPlayer.play(url);
  if (result == 1) {
    // success
  }
}

// Call to pause and resume audio
_playPause(bool play) async {
  if(play){
    await audioPlayer.resume();
  } else {
    await audioPlayer.pause();
  }
}
```

Body:
How I can use single IconButton to play and pause the audio in flutter, using audio play package. Also if Icon I click on single list item it should change only one icon not all list icons.

And if anyone can suggest best audio player package to play list with inline audio it will be helpful.

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gradient_app_bar/gradient_app_bar.dart';
import 'package:http/http.dart' as http;
import 'package:jummamubarak/Screens/HomeScreen.dart';
import 'package:jummamubarak/Screens/ViewTone.dart';

class TonesListScreen extends StatefulWidget {
  @override
  _TonesListScreenState createState() => _TonesListScreenState();
}

class _TonesListScreenState extends State<TonesListScreen> {
  final String data =
      "https://api.airtable.com/v0/appZeBnQJQ0OaVoPQ/Ringtones?maxRecords=100000&view=Tones";
  List toneTitle;
  List toneurl;
  ScrollController _controller = new ScrollController();

  @override
  void initState() {
    super.initState();
    this.getJsonData();
  }

  Future<String> getJsonData() async {
    var response = await http.get(
      Uri.encodeFull(data),
      headers: {
        HttpHeaders.contentTypeHeader: "application/json",
        HttpHeaders.authorizationHeader: "Bearer keyr05is7vPCWxmYM"
      },
      // headers: {"Accept": "application/json"},
    );

    print(response.body);

    setState(() {
      // ignore: non_constant_identifier_names
      var ConvertDataToJson = json.decode(response.body);
      toneTitle = ConvertDataToJson['records'];
    });

    setState(() {
      // ignore: non_constant_identifier_names
      var ConvertDataToJson = json.decode(response.body);
      toneurl = ConvertDataToJson['records'];
    });

    return "Success";
  }

  Widget _files() {
    if (toneTitle == null) {
      return SpinKitCircle(
        color: Color(0xff34495E),
        size: 50.0,
      );
    } else {
      return ListView.builder(
        physics: const AlwaysScrollableScrollPhysics(), // new
        controller: _controller,
        itemCount: toneTitle == null ? 0 : toneTitle.length,
        itemBuilder: (BuildContext context, int index) {
          return Padding(
            padding: const EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0),
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Flexible(
                      child: Text(
                        toneTitle.reversed.toList()[index]['fields']['Name'],
                        style: GoogleFonts.muli(
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    RadiantGradientMask(
                      child: IconButton(
                        icon: Icon(
                          Icons.play_circle_filled,
                          color: Colors.white,
                          size: 40.0,
                        ),
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => ViewTone(
                                toneTitle: toneTitle.reversed.toList()[index]
                                    ['fields']['Name'],
                                toneUrl: toneurl.reversed.toList()[index]
                                    ['fields']['Url'],
                              ),
                            ),
                          );
                        },
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: GradientAppBar(
        gradient: LinearGradient(
          colors: [
            Color(0xff14d5a3),
            Color(0xff039cc1),
          ],
        ),
        title: Text(
          'Islamic Tones',
          style: GoogleFonts.muli(
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: _files(),
    );
  }
}

``


问:
Filters in ASP.NET Core MVC
In ASP.NET MVC, I was using a controller for ActionExecuting, ActionExecuted, OnException, Dispose etc. which was derived from the System.Web.Mvc.Controller

But after changing the application to .NET Core that derives from Microsoft.AspNetCore.Mvc.Controller, I'm getting below errors.

'MyBaseController.OnActionExecuting(ActionExecutingContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuting(ActionExecutingContext)'

'MMBaseController.OnActionExecuted(ActionExecutedContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuted(ActionExecutedContext)'

```<code>public class MyBaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RequestContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RequestContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
        }
    }
}
</code>```

'ActionExecutedContext' does not contain a definition for 'RequestContext' and no accessible extension method 'RequestContext' accepting a first argument of type 'ActionExecutedContext' could be found (are you missing a using directive or an assembly reference?)

Now I tried below method, still not able to use filterContext.HttpContext.Request.IsAuthenticated and filterContext.HttpContext.Request.IsAjaxRequest(), getting below error:

```<code>public class CustomFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
            TempData["CurrentSessionErrorMessage"] = "Ajax Authentication Failed";
        }
    }
}
</code>```

'HttpRequest' does not contain a definition for 'IsAuthenticated' and no accessible extension method 'IsAuthenticated' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no accessible extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

Do we need to have entire code changes for this implementation in .NET Core.

答:
First, you have to create the filter separately:

```<code>  public class CustomFilter : ActionFilterAttribute
        {
         public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
            string controller = Convert.ToString(filterContext.RequestContext.RouteData.Values["controller"]);
            string action = Convert.ToString(filterContext.RequestContext.RouteData.Values["action"]);
            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
           }
         }

     }
</code>```

After that, you can use it on  your controller

```<code>[CustomFilter]
public class MyBaseController : Controller
{
//you logic here
}
</code>```

this answer from Custom Filters

Title: Filters in ASP.NET Core MVC

Body:
In ASP.NET MVC, I was using a controller for ActionExecuting, ActionExecuted, OnException, Dispose etc. which was derived from the System.Web.Mvc.Controller

But after changing the application to .NET Core that derives from Microsoft.AspNetCore.Mvc.Controller, I'm getting below errors.

'MyBaseController.OnActionExecuting(ActionExecutingContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuting(ActionExecutingContext)'

'MMBaseController.OnActionExecuted(ActionExecutedContext)': cannot change access modifiers when overriding 'public' inherited member 'Controller.OnActionExecuted(ActionExecutedContext)'

public class MyBaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RequestContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RequestContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
        }
    }
}

'ActionExecutedContext' does not contain a definition for 'RequestContext' and no accessible extension method 'RequestContext' accepting a first argument of type 'ActionExecutedContext' could be found (are you missing a using directive or an assembly reference?)

Now I tried below method, still not able to use filterContext.HttpContext.Request.IsAuthenticated and filterContext.HttpContext.Request.IsAjaxRequest(), getting below error:

public class CustomFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        string controller = Convert.ToString(filterContext.RouteData.Values["controller"]);
        string action = Convert.ToString(filterContext.RouteData.Values["action"]);
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
            TempData["CurrentSessionErrorMessage"] = "Ajax Authentication Failed";
        }
    }
}

'HttpRequest' does not contain a definition for 'IsAuthenticated' and no accessible extension method 'IsAuthenticated' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no accessible extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

Do we need to have entire code changes for this implementation in .NET Core.

Body:
First, you have to create the filter separately:

  public class CustomFilter : ActionFilterAttribute
        {
         public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
            string controller = Convert.ToString(filterContext.RequestContext.RouteData.Values["controller"]);
            string action = Convert.ToString(filterContext.RequestContext.RouteData.Values["action"]);
            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
            SmartLogger.Info("UnAuthenticated Request");

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                SmartLogger.Info("UnAuthenticated Ajax Request");
            }
           }
         }

     }

After that, you can use it on  your controller

[CustomFilter]
public class MyBaseController : Controller
{
//you logic here
}

this answer from Custom Filters


问:
How can I place TabBarView Widget correctly in a Column Widget?
There was an error placing TabBar and TabBarView in the Column Widget in the Scaffold.

My Source Code:

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CustomView(),
    );
  }
}

class CustomView extends StatelessWidget {
  const CustomView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
        child: Column(
          children: [
            CustomBox(),
            CustomTitle(),
            CustomMainText(),
            CustomButton(),
            CustomTabView(),
          ],
        ),
      ),
    );
  }
}

class CustomTabView extends StatelessWidget {
  const CustomTabView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Column(
        children: [
          TabBar(
            labelColor: Colors.black,
            tabs: [
              Tab(text: 'tab1'),
              Tab(text: 'tab2'),
            ],
          ),
          TabBarView( // Here is Line 132.
            children: [
              Container(),
              Container(),
            ],
          ),
        ],
      ),
    );
  }
}
</code>```

My Error:

```<code>======== Exception caught by rendering library =====================================================
The following assertion was thrown during performResize():
Horizontal viewport was given unbounded height.

Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
The relevant error-causing widget was:
  TabBarView TabBarView:file:///C:/Users/rbqls/AndroidStudioProjects/myfirstflutterproject/lib/main.dart:132:11
When the exception was thrown, this was the stack:
#0      RenderViewport.computeDryLayout.<anonymous closure> (package:flutter/src/rendering/viewport.dart:1424:15)
#1      RenderViewport.computeDryLayout (package:flutter/src/rendering/viewport.dart:1436:6)
#2      RenderBox.performResize (package:flutter/src/rendering/box.dart:2329:12)
#3      RenderObject.layout (package:flutter/src/rendering/object.dart:1831:9)
#4      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#5      RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#6      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#7      RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#8      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#9      RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#10     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#11     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#12     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#13     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#14     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#15     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#16     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#17     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#18     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#19     RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545:11)
#20     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#21     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#22     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#23     ChildLayoutHelper.layoutChild (package:flutter/src/rendering/layout_helper.dart:56:11)
#24     RenderFlex._computeSizes (package:flutter/src/rendering/flex.dart:829:43)
#25     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:931:32)
#26     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#27     ChildLayoutHelper.layoutChild (package:flutter/src/rendering/layout_helper.dart:56:11)
#28     RenderFlex._computeSizes (package:flutter/src/rendering/flex.dart:829:43)
#29     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:931:32)
#30     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#31     _RenderSingleChildViewport.performLayout (package:flutter/src/widgets/single_child_scroll_view.dart:504:14)
#32     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#33     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#34     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#35     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#36     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#37     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#38     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#39     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#40     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#41     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#42     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#43     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#44     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#45     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#46     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#47     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#48     RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545:11)
#49     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#50     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#51     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#52     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:171:12)
#53     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:1005:7)
#54     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:240:7)
#55     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:403:14)
#56     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#57     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#58     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#59     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#60     _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1376:11)
#61     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#62     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#63     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#64     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#65     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#66     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#67     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#68     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#69     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#70     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#71     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#72     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#73     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#74     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#75     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#76     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#77     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#78     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#79     RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3428:13)
#80     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#81     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#82     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#83     _RenderTheatre.performLayout (package:flutter/src/widgets/overlay.dart:751:15)
#84     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#85     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#86     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#87     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#88     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#89     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#90     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#91     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#92     RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545:11)
#93     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#94     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#95     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#96     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#97     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#98     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#99     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#100    RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#101    RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#102    RenderView.performLayout (package:flutter/src/rendering/view.dart:165:14)
#103    RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1707:7)
#104    PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:879:18)
#105    RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:497:19)
#106    WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:13)
#107    RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#108    SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1145:15)
#109    SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
#110    SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:863:7)
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)
The following RenderObject was being processed when the exception was fired: RenderViewport#0158c NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
...  needs compositing
...  parentData: <none> (can use size)
...  constraints: BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
...  size: MISSING
...  axisDirection: right
...  crossAxisDirection: down
...  offset: _PagePosition#8e104(range: null..null, viewport: null, ScrollableState, _ForceImplicitScrollPhysics -> PageScrollPhysics -> PageScrollPhysics -> ClampingScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#1422c, ScrollDirection.idle)
...  anchor: 0.0
RenderObject: RenderViewport#0158c NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
  needs compositing
  parentData: <none> (can use size)
  constraints: BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
  size: MISSING
  axisDirection: right
  crossAxisDirection: down
  offset: _PagePosition#8e104(range: null..null, viewport: null, ScrollableState, _ForceImplicitScrollPhysics -> PageScrollPhysics -> PageScrollPhysics -> ClampingScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#1422c, ScrollDirection.idle)
  anchor: 0.0
...  center child: _RenderSliverFractionalPadding#22595 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
...    parentData: paintOffset=Offset(0.0, 0.0)
...    constraints: MISSING
...    geometry: null
...    child: RenderSliverFillViewport#65bf0 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
...      parentData: paintOffset=Offset(0.0, 0.0)
...      constraints: MISSING
...      geometry: null
...      no children current live
====================================================================================================
</code>```

I was able to resolve the error with the fixed height value of TabBarView as shown in the code below:

```<code>...
SizedBox(
  height: MediaQuery.of(context).size.width,
  child: TabBarView(
    children: [
      Container(),
      Container(),
    ],
  ),
),
...
</code>```

However, because the size of the Container Widget in TabBarView changes dynamically, the height of the TabBarView must change dynamically to suit the size of the one of its children widget.

In addition, I have used various widgets such as Flexible, Expanded, and FittedBox, but I have not solved them.

Is there any other way than using a fixed height?

Thank you.

答:
Try Expanded widget-</p>
```<code>class CustomTabView extends StatelessWidget {
  const CustomTabView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Column(
        children: [
          TabBar(
            labelColor: Colors.black,
            tabs: [
              Tab(text: 'tab1'),
              Tab(text: 'tab2'),
            ],
          ),
       Expanded(child:   TabBarView( // Here is Line 132.
            children: [
              Container(),
              Container(),
            ],
          ),
),
        ],
      ),
    );
  }
}
</code>```

Body:
There was an error placing TabBar and TabBarView in the Column Widget in the Scaffold.

My Source Code:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CustomView(),
    );
  }
}

class CustomView extends StatelessWidget {
  const CustomView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
        child: Column(
          children: [
            CustomBox(),
            CustomTitle(),
            CustomMainText(),
            CustomButton(),
            CustomTabView(),
          ],
        ),
      ),
    );
  }
}

class CustomTabView extends StatelessWidget {
  const CustomTabView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Column(
        children: [
          TabBar(
            labelColor: Colors.black,
            tabs: [
              Tab(text: 'tab1'),
              Tab(text: 'tab2'),
            ],
          ),
          TabBarView( // Here is Line 132.
            children: [
              Container(),
              Container(),
            ],
          ),
        ],
      ),
    );
  }
}

My Error:

======== Exception caught by rendering library =====================================================
The following assertion was thrown during performResize():
Horizontal viewport was given unbounded height.

Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
The relevant error-causing widget was:
  TabBarView TabBarView:file:///C:/Users/rbqls/AndroidStudioProjects/myfirstflutterproject/lib/main.dart:132:11
When the exception was thrown, this was the stack:
#0      RenderViewport.computeDryLayout.<anonymous closure> (package:flutter/src/rendering/viewport.dart:1424:15)
#1      RenderViewport.computeDryLayout (package:flutter/src/rendering/viewport.dart:1436:6)
#2      RenderBox.performResize (package:flutter/src/rendering/box.dart:2329:12)
#3      RenderObject.layout (package:flutter/src/rendering/object.dart:1831:9)
#4      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#5      RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#6      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#7      RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#8      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#9      RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#10     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#11     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#12     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#13     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#14     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#15     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#16     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#17     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#18     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#19     RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545:11)
#20     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#21     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#22     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#23     ChildLayoutHelper.layoutChild (package:flutter/src/rendering/layout_helper.dart:56:11)
#24     RenderFlex._computeSizes (package:flutter/src/rendering/flex.dart:829:43)
#25     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:931:32)
#26     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#27     ChildLayoutHelper.layoutChild (package:flutter/src/rendering/layout_helper.dart:56:11)
#28     RenderFlex._computeSizes (package:flutter/src/rendering/flex.dart:829:43)
#29     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:931:32)
#30     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#31     _RenderSingleChildViewport.performLayout (package:flutter/src/widgets/single_child_scroll_view.dart:504:14)
#32     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#33     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#34     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#35     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#36     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#37     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#38     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#39     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#40     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#41     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#42     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#43     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#44     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#45     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#46     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#47     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#48     RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545:11)
#49     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#50     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#51     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#52     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:171:12)
#53     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:1005:7)
#54     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:240:7)
#55     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:403:14)
#56     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#57     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#58     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#59     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#60     _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1376:11)
#61     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#62     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#63     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#64     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#65     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#66     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#67     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#68     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#69     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#70     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#71     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#72     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#73     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#74     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#75     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#76     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#77     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#78     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#79     RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3428:13)
#80     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#81     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#82     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#83     _RenderTheatre.performLayout (package:flutter/src/widgets/overlay.dart:751:15)
#84     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#85     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#86     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#87     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#88     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#89     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#90     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#91     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#92     RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545:11)
#93     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#94     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#95     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#96     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#97     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#98     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#99     RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#100    RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#101    RenderObject.layout (package:flutter/src/rendering/object.dart:1852:7)
#102    RenderView.performLayout (package:flutter/src/rendering/view.dart:165:14)
#103    RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1707:7)
#104    PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:879:18)
#105    RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:497:19)
#106    WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:13)
#107    RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#108    SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1145:15)
#109    SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
#110    SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:863:7)
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)
The following RenderObject was being processed when the exception was fired: RenderViewport#0158c NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
...  needs compositing
...  parentData: <none> (can use size)
...  constraints: BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
...  size: MISSING
...  axisDirection: right
...  crossAxisDirection: down
...  offset: _PagePosition#8e104(range: null..null, viewport: null, ScrollableState, _ForceImplicitScrollPhysics -> PageScrollPhysics -> PageScrollPhysics -> ClampingScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#1422c, ScrollDirection.idle)
...  anchor: 0.0
RenderObject: RenderViewport#0158c NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
  needs compositing
  parentData: <none> (can use size)
  constraints: BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
  size: MISSING
  axisDirection: right
  crossAxisDirection: down
  offset: _PagePosition#8e104(range: null..null, viewport: null, ScrollableState, _ForceImplicitScrollPhysics -> PageScrollPhysics -> PageScrollPhysics -> ClampingScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#1422c, ScrollDirection.idle)
  anchor: 0.0
...  center child: _RenderSliverFractionalPadding#22595 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
...    parentData: paintOffset=Offset(0.0, 0.0)
...    constraints: MISSING
...    geometry: null
...    child: RenderSliverFillViewport#65bf0 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
...      parentData: paintOffset=Offset(0.0, 0.0)
...      constraints: MISSING
...      geometry: null
...      no children current live
====================================================================================================

I was able to resolve the error with the fixed height value of TabBarView as shown in the code below:

...
SizedBox(
  height: MediaQuery.of(context).size.width,
  child: TabBarView(
    children: [
      Container(),
      Container(),
    ],
  ),
),
...

However, because the size of the Container Widget in TabBarView changes dynamically, the height of the TabBarView must change dynamically to suit the size of the one of its children widget.

In addition, I have used various widgets such as Flexible, Expanded, and FittedBox, but I have not solved them.

Is there any other way than using a fixed height?

Thank you.

Body:
Try Expanded widget-

class CustomTabView extends StatelessWidget {
  const CustomTabView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Column(
        children: [
          TabBar(
            labelColor: Colors.black,
            tabs: [
              Tab(text: 'tab1'),
              Tab(text: 'tab2'),
            ],
          ),
       Expanded(child:   TabBarView( // Here is Line 132.
            children: [
              Container(),
              Container(),
            ],
          ),
),
        ],
      ),
    );
  }
}


问:
CakePHP where can I put this code for reuse?
I have a model called PageMetaData that contains a title and a description. This is to be tied to any other model and to be used as the title tag and meta description for the page.

So I have a model called Brand. Brand has a field called page_meta_data_id and Brand belongsTo PageMetaData

Now on the view for Brand I can run this code:

```<code>if(!empty($data['PageMetaData']['title']))
{
    $this->set('title_for_layout', $data['PageMetaData']['title']);
}
else if(!empty($data['Brand']['name']))
{
    $this->set('title_for_layout', $data['Brand']['name']);
}
if(!empty($data['PageMetaData']['description']))
{
    echo $this->Html->meta('description', $data['PageMetaData']['description'],array('inline'=>false));
}
else if(!empty($data['Brand']['description']))
{
    echo $this->Html->meta('description', $data['Brand']['description'],array('inline'=>false));
}
</code>```

And if a PageMetaData has been associated to the current Brand and has a value for title, it will set that as the page title, otherwise if the brand has a field called name it will us that. Same for description.

The problem is I don't want to have to diplicate this code in every view for every model that uses PageMetaData.

I cannot figure out where I can abstract the code to, to avoid duplication.

I cannot put it in a Behavior or a Helper because you cannot set the title from either. I cannot put it in a Component because it cannot access the data found from the model.

Is there somewhere I can put this code for reuse?

答:
Place the method in your AppModel. I assume the method accepts an id for it to return the appropriate data.

Place another method in your AppController's beforeRender method. Pass the id to this method; which in turn will call the method in AppModel; setting title_for_layout, meta_description and keywords.

You should also not echo out these values, but rather pass them to the view and output them there (or in the layout).

AppController and AppModels are application-wide; so any controller/model may access the methods.

I'm sure there's other methods; and this might not work as I haven't tested it.

Body:
I have a model called PageMetaData that contains a title and a description. This is to be tied to any other model and to be used as the title tag and meta description for the page.

So I have a model called Brand. Brand has a field called page_meta_data_id and Brand belongsTo PageMetaData

Now on the view for Brand I can run this code:

if(!empty($data['PageMetaData']['title']))
{
    $this->set('title_for_layout', $data['PageMetaData']['title']);
}
else if(!empty($data['Brand']['name']))
{
    $this->set('title_for_layout', $data['Brand']['name']);
}
if(!empty($data['PageMetaData']['description']))
{
    echo $this->Html->meta('description', $data['PageMetaData']['description'],array('inline'=>false));
}
else if(!empty($data['Brand']['description']))
{
    echo $this->Html->meta('description', $data['Brand']['description'],array('inline'=>false));
}

And if a PageMetaData has been associated to the current Brand and has a value for title, it will set that as the page title, otherwise if the brand has a field called name it will us that. Same for description.

The problem is I don't want to have to diplicate this code in every view for every model that uses PageMetaData.

I cannot figure out where I can abstract the code to, to avoid duplication.

I cannot put it in a Behavior or a Helper because you cannot set the title from either. I cannot put it in a Component because it cannot access the data found from the model.

Is there somewhere I can put this code for reuse?


问:
Reading the data written to s3 by Amazon Kinesis Firehose stream
I am writing record to Kinesis Firehose stream that is eventually written to a S3 file by Amazon Kinesis Firehose.

My record object looks like

```<code>ItemPurchase {
    String personId,
    String itemId
}
</code>```

The data is written to S3 looks like:

```<code>{"personId":"p-111","itemId":"i-111"}{"personId":"p-222","itemId":"i-222"}{"personId":"p-333","itemId":"i-333"}
</code>```

NO COMMA SEPERATION.

NO STARTING BRACKET as in a Json Array

```<code>[
</code>```

NO ENDING BRACKET as in a Json Array

```<code>]
</code>```

I want to read this data get a list of ItemPurchase objects.

```<code>List<ItemPurchase> purchases = getPurchasesFromS3(IOUtils.toString(s3ObjectContent))
</code>```

What is the correct way to read this data?

答:
This problem can be solved with a JSON parser that consumes objects one at a time from a stream. The raw_decode method of the JSONDecoder exposes just such a parser, but I've written a library that makes it straightforward to do this with a one-liner.

from firehose_sipper import sip

for entry in sip(bucket=..., key=...):
    do_something_with(entry)
```

I've added some more details in this blog post

Body:
I am writing record to Kinesis Firehose stream that is eventually written to a S3 file by Amazon Kinesis Firehose.

My record object looks like

ItemPurchase {
    String personId,
    String itemId
}

The data is written to S3 looks like:

{"personId":"p-111","itemId":"i-111"}{"personId":"p-222","itemId":"i-222"}{"personId":"p-333","itemId":"i-333"}

NO COMMA SEPERATION.

NO STARTING BRACKET as in a Json Array

[

NO ENDING BRACKET as in a Json Array

]

I want to read this data get a list of ItemPurchase objects.

List<ItemPurchase> purchases = getPurchasesFromS3(IOUtils.toString(s3ObjectContent))

What is the correct way to read this data?

Body:
This problem can be solved with a JSON parser that consumes objects one at a time from a stream. The raw_decode method of the JSONDecoder exposes just such a parser, but I've written a library that makes it straightforward to do this with a one-liner.

from firehose_sipper import sip

for entry in sip(bucket=..., key=...):
    do_something_with(entry)

I've added some more details in this blog post


问:
Getting Below Jackson exception while building the project
Getting Below build exception while migrating the Springboot project from spring 1.1.1 release to 2.3.12 release . Please help here.</p>
```<code>Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.introspect.AnnotatedMember.getType(Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:377)
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:183)
    at io.swagger.converter.ModelConverterContextImpl.resolve(ModelConverterContextImpl.java:100)
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:234)
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:183)
    at io.swagger.converter.ModelConverterContextImpl.resolve(ModelConverterContextImpl.java:100)
    at io.swagger.jackson.ModelResolver.resolveProperty(ModelResolver.java:159)
    at io.swagger.jackson.ModelResolver.resolveProperty(ModelResolver.java:110)
    at io.swagger.converter.ModelConverterContextImpl.resolveProperty(ModelConverterContextImpl.java:80)
    at io.swagger.converter.ModelConverters.readAsProperty(ModelConverters.java:58)
    at io.swagger.jaxrs.Reader.addResponse(Reader.java:1018)
    at io.swagger.jaxrs.Reader.parseMethod(Reader.java:940)
    at io.swagger.jaxrs.Reader.read(Reader.java:322)
    at io.swagger.jaxrs.Reader.read(Reader.java:172)
    at io.swagger.jaxrs.config.BeanConfig.scanAndRead(BeanConfig.java:242)
    at io.swagger.jaxrs.config.BeanConfig.setScan(BeanConfig.java:221)
    at org.apache.cxf.jaxrs.swagger.Swagger2Feature.initBeanConfig(Swagger2Feature.java:354)
    at org.apache.cxf.jaxrs.swagger.Swagger2Feature.addSwaggerResource(Swagger2Feature.java:201)
    at org.apache.cxf.jaxrs.swagger.AbstractSwaggerFeature.initialize(AbstractSwaggerFeature.java:68)
    at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.applyFeatures(JAXRSServerFactoryBean.java:252)
    at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:196)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig.jaxRsServer(ServiceConfig.java:138)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig$$EnhancerBySpringCGLIB$$62437023.CGLIB$jaxRsServer$3(<generated>)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig$$EnhancerBySpringCGLIB$$62437023$$FastClassBySpringCGLIB$$46d5367f.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig$$EnhancerBySpringCGLIB$$62437023.jaxRsServer(<generated>)
    at sun.reflect.GeneratedMethodAccessor334.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 68 common frames omitted
</code>```

答: Updating the Swagger version from 1.5.13 to 1.6.5 the issue has been sollved.</p>

Body:
Getting Below build exception while migrating the Springboot project from spring 1.1.1 release to 2.3.12 release . Please help here.

Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.introspect.AnnotatedMember.getType(Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType;
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:377)
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:183)
    at io.swagger.converter.ModelConverterContextImpl.resolve(ModelConverterContextImpl.java:100)
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:234)
    at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:183)
    at io.swagger.converter.ModelConverterContextImpl.resolve(ModelConverterContextImpl.java:100)
    at io.swagger.jackson.ModelResolver.resolveProperty(ModelResolver.java:159)
    at io.swagger.jackson.ModelResolver.resolveProperty(ModelResolver.java:110)
    at io.swagger.converter.ModelConverterContextImpl.resolveProperty(ModelConverterContextImpl.java:80)
    at io.swagger.converter.ModelConverters.readAsProperty(ModelConverters.java:58)
    at io.swagger.jaxrs.Reader.addResponse(Reader.java:1018)
    at io.swagger.jaxrs.Reader.parseMethod(Reader.java:940)
    at io.swagger.jaxrs.Reader.read(Reader.java:322)
    at io.swagger.jaxrs.Reader.read(Reader.java:172)
    at io.swagger.jaxrs.config.BeanConfig.scanAndRead(BeanConfig.java:242)
    at io.swagger.jaxrs.config.BeanConfig.setScan(BeanConfig.java:221)
    at org.apache.cxf.jaxrs.swagger.Swagger2Feature.initBeanConfig(Swagger2Feature.java:354)
    at org.apache.cxf.jaxrs.swagger.Swagger2Feature.addSwaggerResource(Swagger2Feature.java:201)
    at org.apache.cxf.jaxrs.swagger.AbstractSwaggerFeature.initialize(AbstractSwaggerFeature.java:68)
    at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.applyFeatures(JAXRSServerFactoryBean.java:252)
    at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:196)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig.jaxRsServer(ServiceConfig.java:138)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig$$EnhancerBySpringCGLIB$$62437023.CGLIB$jaxRsServer$3(<generated>)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig$$EnhancerBySpringCGLIB$$62437023$$FastClassBySpringCGLIB$$46d5367f.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
    at com.daimler.icon2.contractcreation.general.service.config.ServiceConfig$$EnhancerBySpringCGLIB$$62437023.jaxRsServer(<generated>)
    at sun.reflect.GeneratedMethodAccessor334.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 68 common frames omitted


问:
How do I refresh a page in Angular?
How do I refresh a page in Angular after a click event, without reloading it?
I'm developing an ecommerce frontend in Angular material. I want that after the following click event on the button Remove, the page is refreshed in order to not see the element removed anymore. It's important for me that the page isn't reloaded, because if it were reloaded I would lose all the operations done before the click event.

```<code><a mat-raised-button  routerLink="." color="accent" (click)="deleteProduct(productInCart.product.id, currentUser.id, productInCart.quantity, productInCart.product.price)" routerLink="/carts/cart_by_user"  routerLinkActive="active">Remove</a>
</code>```

答:
You don't need to refresh the page - your concern should instead be to change the data behind it and have Angular update the UI automatically, without refreshing the page, as a result.
My suggestion is to follow the Tour Of Heroes tutorial at https://angular.io/tutorial - it covers the scenario you describe and also introduces other Angular concepts you need to grasp.</p>

Title: How do I refresh a page in Angular?

Body:
How do I refresh a page in Angular after a click event, without reloading it?
I'm developing an ecommerce frontend in Angular material. I want that after the following click event on the button Remove, the page is refreshed in order to not see the element removed anymore. It's important for me that the page isn't reloaded, because if it were reloaded I would lose all the operations done before the click event.

Remove


问:
Dynamic react toggle button for multiple elements
I need to toggle multiple blocks with true/false in react state, but true and false works for all blocks at the same time.</p>
```<code>import { useState } from "react";
...
const [toggleThisElement, setToggleThisElement] = useState(false);
...

{
    data.map((d, id) => {
        return (
            <div className="single-history" key={id}>
                <div className="h-head">
                    click this div for toggle h-info block
                </div>

                <div className="h-info">toggling block</div>
            </div>
        )
    })
}
</code>```

答:
Currently, all your toggle items share the same state. To avoid that create a separate component for toggling logic called ToggleItem as below.

```<code>import { useState } from "react";

const ToggleItem = ({ discription, id }) => {
  const [toggleThisElement, setToggleThisElement] = useState(false);
  return (
    <div className="single-history" key={id}>
      <button
        className="h-head"
        onClick={() => setToggleThisElement((prev) => !prev)}
      >
        click this btn for toggle h-info block {id}
      </button>

      {toggleThisElement && <div className="h-info">{discription}</div>}
    </div>
  );
};

export default function App() {
  const data = ["first", "second", "third"];

  return (
    <>
      {data.map((d, id) => {
        return <ToggleItem id={id} discription={d} />;
      })}
    </>
  );
}
</code>```

Body:
I need to toggle multiple blocks with true/false in react state, but true and false works for all blocks at the same time.

import { useState } from "react";
...
const [toggleThisElement, setToggleThisElement] = useState(false);
...

{
    data.map((d, id) => {
        return (

                    click this div for toggle h-info block

toggling block

        )
    })
}

Body:
Currently, all your toggle items share the same state. To avoid that create a separate component for toggling logic called ToggleItem as below.

import { useState } from "react";

const ToggleItem = ({ discription, id }) => {
  const [toggleThisElement, setToggleThisElement] = useState(false);
  return (
    <div className="single-history" key={id}>
      <button
        className="h-head"
        onClick={() => setToggleThisElement((prev) => !prev)}
      >
        click this btn for toggle h-info block {id}
      </button>

      {toggleThisElement && <div className="h-info">{discription}</div>}
    </div>
  );
};

export default function App() {
  const data = ["first", "second", "third"];

  return (
    <>
      {data.map((d, id) => {
        return <ToggleItem id={id} discription={d} />;
      })}
    </>
  );
}


问:
How do I install Rails?
I am completely new to Ruby and need to use Ruby on Rails 2.3.5 on Windows. I have downloaded the zip from GitHub here: https://github.com/rails/rails/tree/v2.3.5

There was no gem file so I tried rake in the extracted directory. It took ages and seemed to have a lot of errors, but it did eventually complete.

There was no gem file created (is this even what rake is supposed to do?). And rails is not installed (typing rails at the command prompt doesnt work).

Any ideas what I am doing wrong?

EDIT: I cannot use gem install rails -v "2.3.5" as I am behind a firewall. I think I need to install it from local files.

答: Do not install instant rails, as it is outdated and unmaintained. Use RailsInstaller http://railsinstaller.org/</p>

Title: How do I install Rails?


问:
How to upgrade Python venv version
I installed Python3.10 and I have a venv in a project I have been working on. I don't understand how to upgrade this easily. My background is mostly in Node and JS which is must simpler and more straightforward to change versions.

I was just trying to create a new venv but that didn't work

```<code>mpaccione@T430:~/Projects/investing/react-flask-app/server$ python3.10 -m venv ~/Projects/investing/react-flask-app/server
Error: Command '['/home/mpaccione/Projects/investing/react-flask-app/server/bin/python3.10', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.
</code>```

I also thought maybe I could change the pyvenv config could be changed but that didn't work either

```<code>home = /usr/bin
include-system-site-packages = false
version = 3.8
</code>```

to

```<code>home = /usr/bin/python3.10
include-system-site-packages = false
version = 3.10
</code>```

Is there just a simply straightforward way to change this? I'm sure it's a common use case!

答:
Locating in the directory with code.

Assuming ~/Projects/investing/react-flask-app/server for you.

Activate venv if it isn't (assume, venv using for current virtual environment):

```<code>$ source venv/bin/activate
</code>```

Save your current dependencies:

```<code>$ pip freeze > requirements.txt
</code>```

Deactivate current virtual environment:

```<code>$ deactivate
</code>```

Delete the current venv folder (I don't how it is called in your machine).

Create a new venv folder (if python3.10 using for Python 3.10):

```<code>$ python3.10 -m venv venv
</code>```

Activate venv:

```<code>$ source venv/bin/activate
</code>```

Install saved dependencies:

```<code>$ pip install -r requirements.txt
</code>```

Title: How to upgrade Python venv version

Body:
I installed Python3.10 and I have a venv in a project I have been working on. I don't understand how to upgrade this easily. My background is mostly in Node and JS which is must simpler and more straightforward to change versions.

I was just trying to create a new venv but that didn't work

mpaccione@T430:~/Projects/investing/react-flask-app/server$ python3.10 -m venv ~/Projects/investing/react-flask-app/server
Error: Command '['/home/mpaccione/Projects/investing/react-flask-app/server/bin/python3.10', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.

I also thought maybe I could change the pyvenv config could be changed but that didn't work either

home = /usr/bin
include-system-site-packages = false
version = 3.8

to

home = /usr/bin/python3.10
include-system-site-packages = false
version = 3.10

Is there just a simply straightforward way to change this? I'm sure it's a common use case!

Body:
Locating in the directory with code.

Assuming ~/Projects/investing/react-flask-app/server for you.

Activate venv if it isn't (assume, venv using for current virtual environment):

$ source venv/bin/activate

Save your current dependencies:

$ pip freeze > requirements.txt

Deactivate current virtual environment:

$ deactivate

Delete the current venv folder (I don't how it is called in your machine).

Create a new venv folder (if python3.10 using for Python 3.10):

$ python3.10 -m venv venv

Activate venv:

$ source venv/bin/activate

Install saved dependencies:

$ pip install -r requirements.txt


问:
How do I narrow down this TypeScript interface?
I have a TypeScript interface like this:

```<code>export interface User {
  firstName?: string;
  lastName?: string;
  displayName?: string;
  photoURL?: string;
  email?: string;
  phoneNumber?: string;
  uid: string;
}
</code>```

And I have a variable that is typed like this:

```<code>const user: boolean | User
</code>```

Now I want to narrow it down using this:

```<code>if (typeof user === 'User') {
  //Do some things with the User object that are not possible with a boolean
}
</code>```

But I am getting this TypeScript error:

```<code>This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"User"' have no overlap. ts(2367)
</code>```

I have also tried this:

```<code>if (user instanceof 'User') {
   //Do some things with the User object that are not possible with a boolean
}
</code>```

But then it throws this TypeScript error:

```<code>The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type. ts(2359)
</code>```

How do I narrow the variable down for the User type?

答:
The typeof operator evaluates to expressions which include an enumeration of strings, amongst which "User" will never be included.

Reverse your conditional logic:

TS Playground

if (typeof user !== 'boolean') {
  user; // User
}
else {
  user; // boolean
}
```

While this works for your case, where the discrimination is binary, in the case where more types are possible, you will find that using a type predicate is quite helpful.

Body:
I have a TypeScript interface like this:

export interface User {
  firstName?: string;
  lastName?: string;
  displayName?: string;
  photoURL?: string;
  email?: string;
  phoneNumber?: string;
  uid: string;
}

And I have a variable that is typed like this:

const user: boolean | User

Now I want to narrow it down using this:

if (typeof user === 'User') {
  //Do some things with the User object that are not possible with a boolean
}

But I am getting this TypeScript error:

This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"User"' have no overlap. ts(2367)

I have also tried this:

if (user instanceof 'User') {
   //Do some things with the User object that are not possible with a boolean
}

But then it throws this TypeScript error:

The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type. ts(2359)

How do I narrow the variable down for the User type?

Body:
The typeof operator evaluates to expressions which include an enumeration of strings, amongst which "User" will never be included.

Reverse your conditional logic:

TS Playground

if (typeof user !== 'boolean') {
  user; // User
}
else {
  user; // boolean
}

While this works for your case, where the discrimination is binary, in the case where more types are possible, you will find that using a type predicate is quite helpful.


问:
C# API for Powershell Get-ADDomain
I am trying to find the relevant C# API for Powershell's Get-ADDomain. I don't want to invoke the Powershell commands in C#. Instead I am looking for one or multiple C# API with which I can retrieve all the values.

```<code>Get-ADDomain -Identity user.com
</code>```

I tried searching through DOT net API's but couldn't find a relevant one. I found Domain class. But I am not sure how to get all the info using GetDomain

```<code>System.DirectoryServices.ActiveDirectory.Domain.GetDomain(DirectoryContext)
</code>```

Can someone help in finding the relevant C# API that I can use to retrieve all the values of Get-ADDomain?

答:
If you want to get the domain info for the domain that the computer is a member of or the domain that the user running the script is a member of (if they are the same, flip a coin), you can use a different method on the same class you're already trying to use:

For computer's domain:

```<code>[System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
</code>```

For user's domain:

```<code>[System.DirectoryServices.ActiveDirectory.Domain]::GetUserDomain()
</code>```

...yes it's in PowerShell but just invoke the either of the two methods above and they internally pass in the DirectoryContext relative to what you're looking for.

You might also get more information you're looking for by going up to the forest and retrieving that info as well:

```<code>[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
</code>```

Title: C# API for Powershell Get-ADDomain

Body:
I am trying to find the relevant C# API for Powershell's Get-ADDomain. I don't want to invoke the Powershell commands in C#. Instead I am looking for one or multiple C# API with which I can retrieve all the values.

Get-ADDomain -Identity user.com

I tried searching through DOT net API's but couldn't find a relevant one. I found Domain class. But I am not sure how to get all the info using GetDomain

System.DirectoryServices.ActiveDirectory.Domain.GetDomain(DirectoryContext)

Can someone help in finding the relevant C# API that I can use to retrieve all the values of Get-ADDomain?

Body:
If you want to get the domain info for the domain that the computer is a member of or the domain that the user running the script is a member of (if they are the same, flip a coin), you can use a different method on the same class you're already trying to use:

For computer's domain:

[System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()

For user's domain:

[System.DirectoryServices.ActiveDirectory.Domain]::GetUserDomain()

...yes it's in PowerShell but just invoke the either of the two methods above and they internally pass in the DirectoryContext relative to what you're looking for.

You might also get more information you're looking for by going up to the forest and retrieving that info as well:

[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()


问:
bcp command outputting Chinese characters instead of table
I have a batch file that imports a delimited text file into SQL Server using BCP, runs some processing using SQLCMD, and then outputs the processed data via BCP. It currently gives a string of Chinese characters instead of a delimited text table. The weird thing is that it was working two days ago and I haven't changed anything.

I've confirmed that the input BCP and SQL Server processing steps work; the SQL Server table that holds the data for output is correct. I also tried using the -C option to specify a codepage as suggested here, with no change.

Here's the BCP code in question. I've split the lines for readability, the actual code is on one line as normal.  It's using union all to put the column names at the top of the file.

```<code>bcp
"select
    'MRN'
    ,'column name 2'
    ,[rest of the column names]
union all
select distinct
    iif(r.MRN is not null, cast(r.MRN as varchar), '') as MRN
    ,[rest of the columns]
from DATA_MANAGEMENT.dbo.Daily_inpat_out as d
left join DATA_MANAGEMENT.dbo.Roster_all_match as r
    on d.Subscriber_ID = r.SUB_ID
where
    r.MO_DLGTN_STA_DESC = 'DELEGATED'"
queryout "L:\Data_Management\Import_data\Daily_inpat\inpat_out_%mydate%_%mytime%.txt"
-c -S [servername] -U [user] -P [password] -t "|"
</code>```

Here's the first part of the Chinese character output, the full string is much longer:

```<code>前籎潇瑶偟潲牧浡䝼偒䥟籄䕍䉍剅也䵁籅䥂呒彈䅄䕔卼扵捳楲敢彲䑉呼彘䕓呔义彇䕄䍓
</code>```

Edit to add:

As mentioned in the comments the problem occurs in Notepad but displays correctly in other applications (Word, Excel, Notepad++), so this is an encoding issue.  I'm am still hoping to understand the cause of the issue and how to fix it.

答:
I was experiencing the same issue (also had a union between the data sets) but was building up my SQL statements

In my case i had selected '' as SomeField for known columns where there would be no data, in the top table satisfy the union.

I changed to NULL as SomeField, and changed my isnull checks to ISNULL(field,char(32))

```<code>SET @SQL = @SQL +'ISNULL('+@Cols+ ',CHAR(32))' + ' as '+@Cols+','
</code>```

the bcp output file was correct.

I suspect in the above case its the

iif(r.MRN is not null, cast(r.MRN as varchar), '') as MRN

that is causing the encoding issue, perhaps
iif(r.MRN is not null, cast(r.MRN as varchar), CHAR(32)) as MRN would have fixed the issue.

Body:
I have a batch file that imports a delimited text file into SQL Server using BCP, runs some processing using SQLCMD, and then outputs the processed data via BCP. It currently gives a string of Chinese characters instead of a delimited text table. The weird thing is that it was working two days ago and I haven't changed anything.

I've confirmed that the input BCP and SQL Server processing steps work; the SQL Server table that holds the data for output is correct. I also tried using the -C option to specify a codepage as suggested here, with no change.

Here's the BCP code in question. I've split the lines for readability, the actual code is on one line as normal.  It's using union all to put the column names at the top of the file.

bcp
"select
    'MRN'
    ,'column name 2'
    ,[rest of the column names]
union all
select distinct
    iif(r.MRN is not null, cast(r.MRN as varchar), '') as MRN
    ,[rest of the columns]
from DATA_MANAGEMENT.dbo.Daily_inpat_out as d
left join DATA_MANAGEMENT.dbo.Roster_all_match as r
    on d.Subscriber_ID = r.SUB_ID
where
    r.MO_DLGTN_STA_DESC = 'DELEGATED'"
queryout "L:\Data_Management\Import_data\Daily_inpat\inpat_out_%mydate%_%mytime%.txt"
-c -S [servername] -U [user] -P [password] -t "|"

Here's the first part of the Chinese character output, the full string is much longer:

前籎潇瑶偟潲牧浡䝼偒䥟籄䕍䉍剅也䵁籅䥂呒彈䅄䕔卼扵捳楲敢彲䑉呼彘䕓呔义彇䕄䍓

Edit to add:

As mentioned in the comments the problem occurs in Notepad but displays correctly in other applications (Word, Excel, Notepad++), so this is an encoding issue.  I'm am still hoping to understand the cause of the issue and how to fix it.

Body:
I was experiencing the same issue (also had a union between the data sets) but was building up my SQL statements

In my case i had selected '' as SomeField for known columns where there would be no data, in the top table satisfy the union.

I changed to NULL as SomeField, and changed my isnull checks to ISNULL(field,char(32))

SET @SQL = @SQL +'ISNULL('+@Cols+ ',CHAR(32))' + ' as '+@Cols+','

the bcp output file was correct.

I suspect in the above case its the

iif(r.MRN is not null, cast(r.MRN as varchar), '') as MRN

that is causing the encoding issue, perhaps
iif(r.MRN is not null, cast(r.MRN as varchar), CHAR(32)) as MRN would have fixed the issue.


问:
innerhtml not print full array
I'm using  innerhtmal for output but the problem is it shows 1 less value the array
I cant find the problem.

await fetch(urlbody, bodyrequestOptions)
  .then((response) => response.json())
  .then((payload) => {
      console.log(payload)

      payload.map(({
        TRANS_NO,
        TRANS_DATE,
        DR_AMT,
        CR_AMT,
        PARTICULAR
      }, index) => {
        /* Calculatation*/
        oprningbalance += CR_AMT
        oprningbalance -= DR_AMT

        document.getElementById('output2').innerHTML += `

          ${index + 1}
          ${moment(TRANS_DATE).format('LLL')}
          ${TRANS_NO}
          ${DR_AMT.toFixed(2)}
          ${CR_AMT.toFixed(2)}
          ${oprningbalance.toFixed(2)}
          ${PARTICULAR}

`
        total_dr += DR_AMT
        total_cr += CR_AMT
      })
```

答:
Try this instead

document.getElementById('output2').innerHTML = payload.map(({TRANS_NO,TRANS_DATE,DR_AMT,CR_AMT,PARTICULAR}, index) => {
  /* Calculatation*/
  oprningbalance += CR_AMT
  oprningbalance -= DR_AMT
  total_dr += DR_AMT
  total_cr += CR_AMT
  return `

          ${index + 1}
          ${moment(TRANS_DATE).format('LLL')}
          ${TRANS_NO}
          ${DR_AMT.toFixed(2)}
          ${CR_AMT.toFixed(2)}
          ${oprningbalance.toFixed(2)}
          ${PARTICULAR}

`
}).join("")
```

Title: innerhtml not print full array

Body:
Try this instead

document.getElementById('output2').innerHTML = payload.map(({TRANS_NO,TRANS_DATE,DR_AMT,CR_AMT,PARTICULAR}, index) => {
  /* Calculatation*/
  oprningbalance += CR_AMT
  oprningbalance -= DR_AMT
  total_dr += DR_AMT
  total_cr += CR_AMT
  return `<tr>
          <td>${index + 1}</td>
          <td class="text-tiny text-break">${moment(TRANS_DATE).format('LLL')}</td>
          <td class="text-tiny">${TRANS_NO}</td>
          <td class="text-tiny">${DR_AMT.toFixed(2)}</td>
          <td class="text-tiny">${CR_AMT.toFixed(2)}</td>
          <td class="text-tiny">${oprningbalance.toFixed(2)}</td>
          <td class="text-tiny text-break">${PARTICULAR}</td>
        </tr>`
}).join("")