问:
swagger-ui hangs on big responses
One of my endpoints returns a JSON (not huge, around 2MB). Trying to run GET on this endpoint in swagger-ui results in the browser hanging for a few minutes. After this time, it finally displays the JSON.

Is there a way to define that the response shouldn't be rendered but provided as a file to download instead?

I'm using OpenAPI 3, and I tried the following:

content:
    application/json:
        schema:
            type: string
            format: binary
```

taken from the documentation. Still, swagger-ui renders the response.

Has anyone had the same problem?

答:
Lex45x proposes in this github issue to disable syntax highlighting. In ASP.Net Core you can do this with

app.UseSwaggerUI(config =>
{
    config.ConfigObject.AdditionalItems["syntaxHighlight"] = new Dictionary<string, object>
    {
        ["activated"] = false
    };
});
```

This significantly improves render performance.

Title: swagger-ui hangs on big responses

Body:
One of my endpoints returns a JSON (not huge, around 2MB). Trying to run GET on this endpoint in swagger-ui results in the browser hanging for a few minutes. After this time, it finally displays the JSON.

Is there a way to define that the response shouldn't be rendered but provided as a file to download instead?

I'm using OpenAPI 3, and I tried the following:

content:
    application/json:
        schema:
            type: string
            format: binary

taken from the documentation. Still, swagger-ui renders the response.

Has anyone had the same problem?

Body:
Lex45x proposes in this github issue to disable syntax highlighting. In ASP.Net Core you can do this with

app.UseSwaggerUI(config =>
{
    config.ConfigObject.AdditionalItems["syntaxHighlight"] = new Dictionary<string, object>
    {
        ["activated"] = false
    };
});

This significantly improves render performance.


来源: stackexchange

问:
Hexagonal Architecture, do I violate its principles by reusing code between usecases?
Hello and thank you for taking the time to read my question :)

I have several usecases that need to download and upload files from and to s3. For that, I've created a port and an S3 adapter that I share between those usecases. Somehow I feel that this is a terrible idea but I don't want to duplicate code.

Does that mean that I've baldy designed my usecases?

What is the correct approach here?

答:
If you have multiple use cases, then you SHOULD have multiple root aggregates, one per use case. If you have multiple root aggregates, you SHOULD have multiple ports, each one handling persistance for a single use case. Since all use cases use the same S3 persistence backend, you MAY implement a single adapter, that implements all ports, and handles persistence for all use cases.

This allows you to move any use case to another persistence backend later, if needed, without breaking your existing code. You can do that by implementing a new persistence adapter for the new backend, and configuring your dependency injection to use this new adapter instead of the previous one for that port.

ContentLicense: CC BY-SA 4.0


问:
Disable multitouch in libgdx
I use Stage and Actors in my project. Can I disable and enable multitouch in runtime?
I'm using libgdx 0.9.7.

Sorry for my English.

答:
Set this as the first InputProcessor</p>
```<code>public class SingleTouchInputProcessor extends InputAdapter {

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        return pointer > 0;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return pointer > 0;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return pointer > 0;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Disable multitouch in libgdx

Body:
Set this as the first InputProcessor

public class SingleTouchInputProcessor extends InputAdapter {

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        return pointer > 0;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return pointer > 0;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return pointer > 0;
    }
}


问:
How can I change a url without reloading the page?
I am using ajax to display my contents. As I display my contents, I want to change the browser url dynamically without reloading the page. How can I proceed?

```<code>window.location.hash="Aboutus";
</code>```

The above code inserts a # sign. I do not want a hash sign in my url since my page can contains a similar id.

答: You can use History API that is being introduced in HTML5.  Here is a link to some examples - you can find links to more resources in the bottom.</p>

Body:
I am using ajax to display my contents. As I display my contents, I want to change the browser url dynamically without reloading the page. How can I proceed?

window.location.hash="Aboutus";

The above code inserts a # sign. I do not want a hash sign in my url since my page can contains a similar id.


问:
TypeError: undefined is not an object (evaluating '_expoModulesCore.NativeModulesProxy.ExpoSplashScreen')
I am getting this issue in react native. The things were working fine until I decicded to rerun the project doing yarn install

Here is complete error

TypeError: undefined is not an object (evaluating '_expoModulesCore.NativeModulesProxy.ExpoSplashScreen')
at node_modules\react-native\Libraries\LogBox\LogBox.js:148:8 in registerError
at node_modules\react-native\Libraries\LogBox\LogBox.js:59:8 in errorImpl
at node_modules\react-native\Libraries\LogBox\LogBox.js:33:4 in console.error
at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:104:6 in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:171:19 in handleException
at node_modules\react-native\Libraries\Core\setUpErrorHandling.js:24:6 in handleError
at node_modules\expo-error-recovery\build\ErrorRecovery.fx.js:12:21 in ErrorUtils.setGlobalHandler$argument_0
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:294:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:155:27 in invoke
at node_modules\regenerator-runtime\runtime.js:165:18 in PromiseImpl.resolve.then$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue

I have tried with update expo-cli, expo-splash-screen and with cache clear command expo r -c

Let me know if there is anyone who can help.

答:
I was having issues with expo-web-browser. So, just simply clear your cache with the following command on your terminal. You will not see errors like above again:

expo r -c


问:
Python: List in global namespace gets unintentionally modified through function
I have a propably very basic problem in Python. However, I would be very thankful, if someone could help me to understand, what is happening here:

My code is as follows:

```<code>purchaseprices = {'Stock_A': [[10, 4.21],[20, 5.23], [5, 8.32]],
                  'Stock_B': [[5, 8.23],[15, 7.42], [10, 7.53]]}

def update_purchaseprices(name, number_of_shares):
    remaining_number_of_shares = number_of_shares
    updated_purchaseprices = purchaseprices[name][:]
    indices_to_delete = []
    for i in range(len(updated_purchaseprices)):
        if updated_purchaseprices[i][0] < remaining_number_of_shares:
            remaining_number_of_shares -= updated_purchaseprices[i][0]
            indices_to_delete.append(i)
        else:
            updated_purchaseprices[i][0] = updated_purchaseprices[i][0] - remaining_number_of_shares
            break
    updated_purchaseprices = [i for j, i in enumerate(updated_purchaseprices) if j not in indices_to_delete]
    return updated_purchaseprices

name = "Stock_A"
number_of_shares = 34

print(purchaseprices['Stock_A'])
updated_purchaseprices = update_purchaseprices(name, number_of_shares)
print(updated_purchaseprices) # this works as expected
print(purchaseprices['Stock_A']) # why did the original list got changed as well?
</code>```

Here is, what I wanted to do: I have an original list, which is stored in a dictionary called purchaseprices. This list can be accessed by purchaseprices['Stock_A’]. Now I tried to write a function to return a list called updated_purchaseprices, which is basically a modified version of the original list. In order to leave the original list unchanged, I made a copy of it by including updated_purchaseprices = purchaseprices[name]:. Unfortunately my code nevertheless also changes the original list. Can someone please tell me why this is happening?

答:
As you probably know because you used [:], a list is mutable and you need to take a copy in your function. But the copy still contains the original objects (sublists).

You need to copy those too!

Replace:

```<code>updated_purchaseprices = purchaseprices[name][:]
</code>```

with:

```<code>updated_purchaseprices = [l.copy() for l in purchaseprices[name]]
</code>```

or:

```<code>import copy
updated_purchaseprices = copy.deepcopy(purchaseprices[name])
</code>```

Body:
I have a propably very basic problem in Python. However, I would be very thankful, if someone could help me to understand, what is happening here:

My code is as follows:

purchaseprices = {'Stock_A': [[10, 4.21],[20, 5.23], [5, 8.32]],
                  'Stock_B': [[5, 8.23],[15, 7.42], [10, 7.53]]}

def update_purchaseprices(name, number_of_shares):
    remaining_number_of_shares = number_of_shares
    updated_purchaseprices = purchaseprices[name][:]
    indices_to_delete = []
    for i in range(len(updated_purchaseprices)):
        if updated_purchaseprices[i][0] < remaining_number_of_shares:
            remaining_number_of_shares -= updated_purchaseprices[i][0]
            indices_to_delete.append(i)
        else:
            updated_purchaseprices[i][0] = updated_purchaseprices[i][0] - remaining_number_of_shares
            break
    updated_purchaseprices = [i for j, i in enumerate(updated_purchaseprices) if j not in indices_to_delete]
    return updated_purchaseprices

name = "Stock_A"
number_of_shares = 34

print(purchaseprices['Stock_A'])
updated_purchaseprices = update_purchaseprices(name, number_of_shares)
print(updated_purchaseprices) # this works as expected
print(purchaseprices['Stock_A']) # why did the original list got changed as well?

Here is, what I wanted to do: I have an original list, which is stored in a dictionary called purchaseprices. This list can be accessed by purchaseprices['Stock_A’]. Now I tried to write a function to return a list called updated_purchaseprices, which is basically a modified version of the original list. In order to leave the original list unchanged, I made a copy of it by including updated_purchaseprices = purchaseprices[name]:. Unfortunately my code nevertheless also changes the original list. Can someone please tell me why this is happening?

Body:
As you probably know because you used [:], a list is mutable and you need to take a copy in your function. But the copy still contains the original objects (sublists).

You need to copy those too!

Replace:

updated_purchaseprices = purchaseprices[name][:]

with:

updated_purchaseprices = [l.copy() for l in purchaseprices[name]]

or:

import copy
updated_purchaseprices = copy.deepcopy(purchaseprices[name])


问:
Matching files using python program
I have to two files as follows

```<code>File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....
</code>```

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

```<code>CIDS9289  8.9  -9873
....
</code>```

to acheive this wrote python script as follows

```<code>infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line
</code>```

but i gives following error

```<code>Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file
</code>```

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI

答:
Use the following:

```<code>print [line for id in searchTxtData for line in inFileData if id.strip() in line]
</code>```

Or using with statement:

```<code>ids = [id.strip() for id in open("file1.txt","r") if id.strip()]

with open("file2.txt","r") as dataFile:
    for line in dataFile:
        if line.strip() and line.split()[0] in ids:
           print line
</code>```

Title: Matching files using python program

Body:
I have to two files as follows

File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

CIDS9289  8.9  -9873
....

to acheive this wrote python script as follows

infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line

but i gives following error

Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI

Body:
Use the following:

print [line for id in searchTxtData for line in inFileData if id.strip() in line]

Or using with statement:

ids = [id.strip() for id in open("file1.txt","r") if id.strip()]

with open("file2.txt","r") as dataFile:
    for line in dataFile:
        if line.strip() and line.split()[0] in ids:
           print line


问:
Implement a function to create dropdown butttons in flutter
im new to dart programming i want to implement a function to create dropdown buttons.
Contitons are:
-Dropdown button value should be taken as a variable.

Example function call:

```<code>buildDropdownField(dropdownHeader:"tank 1", dropdownValue:_tank2)
</code>```

expected output of this function is to create a dropdown button and store its value into _tank2 so i can use it later on. So far ive tried different methods but i cant seem to get it right.
Heres my final function which does not display the value on screen but saves it tho the value given.

```<code>Widget buildDropdownField(
      {required String dropdownHeader,
        required String? dropdownValue,
      required VoidCallback? OnChanged(Value)}) {
    return Column(
      children: <Widget>[
        Text(dropdownHeader),
        const SizedBox(
          height: 10,
        ),
        StatefulBuilder(
          builder: (_, setDropState) {
            return DropdownButton<String>(
              value: dropdownValue,
              icon: const Icon(Icons.arrow_downward),
              elevation: 16,
              style: const TextStyle(color: Colors.deepPurple),
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              onChanged: (value){
                OnChanged(value);
              },
              items: <String>['-', 'Geçti', 'Kaldı', 'Belirsiz']
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            );
          },
        )
      ],
    );
  }
</code>```

And lastly heres the function call of my final function iteration:

```<code>buildDropdownField(dropdownHeader:"tank 1", dropdownValue:_tank2, OnChanged: (Value) {
                      setState(() {
                       tank1 = Value;
                    });
                    })
</code>```

答:
This is a custom expansion tile I used in a project of mine. It comes from the code from a package, slightly to my needs.</p>
```<code>import 'package:flutter/material.dart';

const Duration _kExpand = Duration(milliseconds: 200);

class CustomExpansionTile extends StatefulWidget {
  const CustomExpansionTile({
    Key key,
    this.leading,
    @required this.title,
    this.backgroundColor,
    this.children = const <Widget>[],
    this.trailing,
    @required this.expandedItem,
    @required this.expansionCallback,
    @required this.onHeaderClick,
    this.subtitleWidget,
  }) : super(key: key);

  /// A widget to display before the title.
  ///
  /// Typically a [CircleAvatar] widget.
  final Widget leading;

  /// The primary content of the list item.
  ///
  /// Typically a [Text] widget.
  final Widget title;

  final Widget subtitleWidget;

  /// The widgets that are displayed when the tile expands.
  ///
  /// Typically [ListTile] widgets.
  final List<Widget> children;

  /// The color to display behind the sublist when expanded.
  final Color backgroundColor;

  /// A widget to display instead of a rotating arrow icon.
  final Widget trailing;

  final ValueNotifier<Key> expandedItem;

  final Function(bool hasExpanded) expansionCallback;

  final Function() onHeaderClick;

  @override
  _CustomExpansionTileState createState() => _CustomExpansionTileState();
}

class _CustomExpansionTileState extends State<CustomExpansionTile>
    with SingleTickerProviderStateMixin {
  static final Animatable<double> _easeOutTween =
      CurveTween(curve: Curves.easeOut);
  static final Animatable<double> _easeInTween =
      CurveTween(curve: Curves.easeIn);
  static final Animatable<double> _halfTween =
      Tween<double>(begin: 0.0, end: 0.5);

  final ColorTween _borderColorTween = ColorTween();
  final ColorTween _headerColorTween = ColorTween();
  final ColorTween _iconColorTween = ColorTween();
  final ColorTween _backgroundColorTween = ColorTween();

  AnimationController _controller;
  Animation<double> _iconTurns;
  Animation<double> _heightFactor;
  Animation<Color> _borderColor;
  Animation<Color> _headerColor;
  Animation<Color> _iconColor;
  Animation<Color> _backgroundColor;

  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: _kExpand, vsync: this);
    _heightFactor = _controller.drive(_easeInTween);
    _iconTurns = _controller.drive(_halfTween.chain(_easeInTween));
    _borderColor = _controller.drive(_borderColorTween.chain(_easeOutTween));
    _headerColor = _controller.drive(_headerColorTween.chain(_easeInTween));
    _iconColor = _controller.drive(_iconColorTween.chain(_easeInTween));
    _backgroundColor =
        _controller.drive(_backgroundColorTween.chain(_easeOutTween));

    _isExpanded = widget.expandedItem.value == widget.key;
    if (_isExpanded) _controller.value = 1.0;

    widget.expandedItem.addListener(listener);
  }

  void listener() {
    setState(() {
      _changeState(widget.expandedItem.value == widget.key);
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    widget.expandedItem.removeListener(listener);
    super.dispose();
  }

  void _changeState(bool isExpanded) {
    setState(() {
      _isExpanded = isExpanded;
      if (_isExpanded) {
        _controller.forward();
      } else {
        _controller.reverse().then<void>((void value) {
          if (!mounted) return;
          setState(() {
            // Rebuild without widget.children.
          });
        });
      }
      PageStorage.of(context)?.writeState(context, _isExpanded);
    });
  }

  //action to perform when the "expand" icon is pressed
  void _onExpansionIconClick() {
    widget.expansionCallback(!_isExpanded);
    _changeState(!_isExpanded);
    widget.expandedItem.value = _isExpanded ? widget.key : null;
  }

  Widget _buildChildren(BuildContext context, Widget child) {
    final Color borderSideColor = _borderColor.value ?? Colors.transparent;

    return Container(
      decoration: BoxDecoration(
        color: _backgroundColor.value ?? Colors.transparent,
        border: Border(
          top: BorderSide(color: borderSideColor),
          bottom: BorderSide(color: borderSideColor),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ListTileTheme.merge(
            iconColor: _iconColor.value,
            textColor: _headerColor.value,
            child: ListTile(
              //if the list isExpanded, the click on the tile is disabled
              //otherwise the action defined for the callback
              //is performed
              onTap: () => _isExpanded ? null : widget.onHeaderClick(),
              leading: widget.leading,
              title: widget.title,
              subtitle: widget.subtitleWidget,
              //arrow icon
              trailing: InkWell(
                onTap: _onExpansionIconClick,
                child: Container(
                  padding: EdgeInsets.all(16),
                  //rotate arrow icon if the tile is expanded
                  child: widget.trailing ??
                      RotationTransition(
                        turns: _iconTurns,
                        child: const Icon(Icons.expand_more),
                      ),
                ),
              ),
              contentPadding: EdgeInsets.only(left: 16),
            ),
          ),
          ClipRect(
            child: Align(
              heightFactor: _heightFactor.value,
              child: child,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void didChangeDependencies() {
    final ThemeData theme = Theme.of(context);
    _borderColorTween..end = theme.dividerColor;
    _headerColorTween
      ..begin = theme.textTheme.subtitle1.color
      ..end = theme.accentColor;
    _iconColorTween
      ..begin = theme.unselectedWidgetColor
      ..end = theme.accentColor;
    _backgroundColorTween..end = widget.backgroundColor;
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final bool closed = !_isExpanded && _controller.isDismissed;
    return AnimatedBuilder(
      animation: _controller.view,
      builder: _buildChildren,
      child: closed ? null : Column(children: widget.children),
    );
  }
}
</code>```

Body:
im new to dart programming i want to implement a function to create dropdown buttons.
Contitons are:
-Dropdown button value should be taken as a variable.

Example function call:

buildDropdownField(dropdownHeader:"tank 1", dropdownValue:_tank2)

expected output of this function is to create a dropdown button and store its value into _tank2 so i can use it later on. So far ive tried different methods but i cant seem to get it right.
Heres my final function which does not display the value on screen but saves it tho the value given.

Widget buildDropdownField(
      {required String dropdownHeader,
        required String? dropdownValue,
      required VoidCallback? OnChanged(Value)}) {
    return Column(
      children: <Widget>[
        Text(dropdownHeader),
        const SizedBox(
          height: 10,
        ),
        StatefulBuilder(
          builder: (_, setDropState) {
            return DropdownButton<String>(
              value: dropdownValue,
              icon: const Icon(Icons.arrow_downward),
              elevation: 16,
              style: const TextStyle(color: Colors.deepPurple),
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              onChanged: (value){
                OnChanged(value);
              },
              items: <String>['-', 'Geçti', 'Kaldı', 'Belirsiz']
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            );
          },
        )
      ],
    );
  }

And lastly heres the function call of my final function iteration:

buildDropdownField(dropdownHeader:"tank 1", dropdownValue:_tank2, OnChanged: (Value) {
                      setState(() {
                       tank1 = Value;
                    });
                    })

Body:
This is a custom expansion tile I used in a project of mine. It comes from the code from a package, slightly to my needs.

import 'package:flutter/material.dart';

const Duration _kExpand = Duration(milliseconds: 200);

class CustomExpansionTile extends StatefulWidget {
  const CustomExpansionTile({
    Key key,
    this.leading,
    @required this.title,
    this.backgroundColor,
    this.children = const <Widget>[],
    this.trailing,
    @required this.expandedItem,
    @required this.expansionCallback,
    @required this.onHeaderClick,
    this.subtitleWidget,
  }) : super(key: key);

  /// A widget to display before the title.
  ///
  /// Typically a [CircleAvatar] widget.
  final Widget leading;

  /// The primary content of the list item.
  ///
  /// Typically a [Text] widget.
  final Widget title;

  final Widget subtitleWidget;

  /// The widgets that are displayed when the tile expands.
  ///
  /// Typically [ListTile] widgets.
  final List<Widget> children;

  /// The color to display behind the sublist when expanded.
  final Color backgroundColor;

  /// A widget to display instead of a rotating arrow icon.
  final Widget trailing;

  final ValueNotifier<Key> expandedItem;

  final Function(bool hasExpanded) expansionCallback;

  final Function() onHeaderClick;

  @override
  _CustomExpansionTileState createState() => _CustomExpansionTileState();
}

class _CustomExpansionTileState extends State<CustomExpansionTile>
    with SingleTickerProviderStateMixin {
  static final Animatable<double> _easeOutTween =
      CurveTween(curve: Curves.easeOut);
  static final Animatable<double> _easeInTween =
      CurveTween(curve: Curves.easeIn);
  static final Animatable<double> _halfTween =
      Tween<double>(begin: 0.0, end: 0.5);

  final ColorTween _borderColorTween = ColorTween();
  final ColorTween _headerColorTween = ColorTween();
  final ColorTween _iconColorTween = ColorTween();
  final ColorTween _backgroundColorTween = ColorTween();

  AnimationController _controller;
  Animation<double> _iconTurns;
  Animation<double> _heightFactor;
  Animation<Color> _borderColor;
  Animation<Color> _headerColor;
  Animation<Color> _iconColor;
  Animation<Color> _backgroundColor;

  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: _kExpand, vsync: this);
    _heightFactor = _controller.drive(_easeInTween);
    _iconTurns = _controller.drive(_halfTween.chain(_easeInTween));
    _borderColor = _controller.drive(_borderColorTween.chain(_easeOutTween));
    _headerColor = _controller.drive(_headerColorTween.chain(_easeInTween));
    _iconColor = _controller.drive(_iconColorTween.chain(_easeInTween));
    _backgroundColor =
        _controller.drive(_backgroundColorTween.chain(_easeOutTween));

    _isExpanded = widget.expandedItem.value == widget.key;
    if (_isExpanded) _controller.value = 1.0;

    widget.expandedItem.addListener(listener);
  }

  void listener() {
    setState(() {
      _changeState(widget.expandedItem.value == widget.key);
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    widget.expandedItem.removeListener(listener);
    super.dispose();
  }

  void _changeState(bool isExpanded) {
    setState(() {
      _isExpanded = isExpanded;
      if (_isExpanded) {
        _controller.forward();
      } else {
        _controller.reverse().then<void>((void value) {
          if (!mounted) return;
          setState(() {
            // Rebuild without widget.children.
          });
        });
      }
      PageStorage.of(context)?.writeState(context, _isExpanded);
    });
  }

  //action to perform when the "expand" icon is pressed
  void _onExpansionIconClick() {
    widget.expansionCallback(!_isExpanded);
    _changeState(!_isExpanded);
    widget.expandedItem.value = _isExpanded ? widget.key : null;
  }

  Widget _buildChildren(BuildContext context, Widget child) {
    final Color borderSideColor = _borderColor.value ?? Colors.transparent;

    return Container(
      decoration: BoxDecoration(
        color: _backgroundColor.value ?? Colors.transparent,
        border: Border(
          top: BorderSide(color: borderSideColor),
          bottom: BorderSide(color: borderSideColor),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ListTileTheme.merge(
            iconColor: _iconColor.value,
            textColor: _headerColor.value,
            child: ListTile(
              //if the list isExpanded, the click on the tile is disabled
              //otherwise the action defined for the callback
              //is performed
              onTap: () => _isExpanded ? null : widget.onHeaderClick(),
              leading: widget.leading,
              title: widget.title,
              subtitle: widget.subtitleWidget,
              //arrow icon
              trailing: InkWell(
                onTap: _onExpansionIconClick,
                child: Container(
                  padding: EdgeInsets.all(16),
                  //rotate arrow icon if the tile is expanded
                  child: widget.trailing ??
                      RotationTransition(
                        turns: _iconTurns,
                        child: const Icon(Icons.expand_more),
                      ),
                ),
              ),
              contentPadding: EdgeInsets.only(left: 16),
            ),
          ),
          ClipRect(
            child: Align(
              heightFactor: _heightFactor.value,
              child: child,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void didChangeDependencies() {
    final ThemeData theme = Theme.of(context);
    _borderColorTween..end = theme.dividerColor;
    _headerColorTween
      ..begin = theme.textTheme.subtitle1.color
      ..end = theme.accentColor;
    _iconColorTween
      ..begin = theme.unselectedWidgetColor
      ..end = theme.accentColor;
    _backgroundColorTween..end = widget.backgroundColor;
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final bool closed = !_isExpanded && _controller.isDismissed;
    return AnimatedBuilder(
      animation: _controller.view,
      builder: _buildChildren,
      child: closed ? null : Column(children: widget.children),
    );
  }
}


问:
Parse a string between 2 delimiters
I added the following line but I am getting an error "Invalid length parameter passed to the LEFT or SUBSTRING function":

```<code>substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
</code>```

It will work if I remove the ">", so i am at a lost of my next step

```<code>SELECT *
from RawAnalog RA
CROSS APPLY (
            VALUES(
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2)),
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3)),
                substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
                )
            )
                V(TYPE,POINT,SITE )
Where
          V.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlvCmd','SaStP', 'SaCFM')
          and ra.UTCDateTime = '2021-01-01 00:15:00.000'
ORDER by V.POINT asc
</code>```

Desired output would be except for site I would just want "Skyline":
output

答:
Another variation:</p>
```<code>SELECT SUBSTRING(t,PATINDEX('%:%',t)+1,PATINDEX('%-%',t) - PATINDEX('%:%',t) - 1)
FROM (VALUES ('XRDCWPDBSADX02:SKYLINE-NAE04/FC-1.041020FE.ChwVlvCmd.#85 ')) tbl(t);
</code>```

Title: Parse a string between 2 delimiters

Body:
I added the following line but I am getting an error "Invalid length parameter passed to the LEFT or SUBSTRING function":

substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)

It will work if I remove the ">", so i am at a lost of my next step

SELECT *
from RawAnalog RA
CROSS APPLY (
            VALUES(
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2)),
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3)),
                substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
                )
            )
                V(TYPE,POINT,SITE )
Where
          V.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlvCmd','SaStP', 'SaCFM')
          and ra.UTCDateTime = '2021-01-01 00:15:00.000'
ORDER by V.POINT asc

Desired output would be except for site I would just want "Skyline":
output

Body:
Another variation:

SELECT SUBSTRING(t,PATINDEX('%:%',t)+1,PATINDEX('%-%',t) - PATINDEX('%:%',t) - 1)
FROM (VALUES ('XRDCWPDBSADX02:SKYLINE-NAE04/FC-1.041020FE.ChwVlvCmd.#85 ')) tbl(t);


问:
sending variables from java to xml in android stodio
I want to make Column graph, that each Column is in fact int variable from my java.
I made all the buttons and Ijust have to put somehow the variables in the buttons's layout_height.

so anyone know how to do it?

答:
```<code>    Button btnFirst = findViewById(R.id.btnFirst);
    //change height
    btnFirst.setLayoutParams(new LinearLayout.LayoutParams(5, 5));
    //change text
    btnFirst.setText("your text");
</code>```


问:
Mocking ItemResponse in CosmosDB
I am writing unit tests using Moq in xUnit for a service that involves CosmosDB. There's a method GetVehicleInfo which returns ItemResponse<VehicleInfo> from CosmosDB. As ItemResponse has a protected constructor so I can't new it up. Therefore, I'm mocking the caller method and doing

```<code>var responseMock = new Mock<ItemResponse<VehicleInfo>>();
responseMock.Setup(x => x.Resource).Returns(expectedItem); //expectedItem is of VehicleInfo type
cosmoRepoServiceStub.Setup(service => service.GetVehicleInfo("a1", "a2").Result).Returns(responseMock.Object);
</code>```

The problem I face is that when GetVehicleInfo is called as below, it returns null always. I expect it to return ItemResponse<VehicleInfo> wherein Resource will contain expectedItem.

```<code>ItemResponse<VehicleInfo> response = await _cosmosRepo.GetVehicleInfo(plate, country);
if (response == null){ //... }
</code>```

答:
You should setup your cosmoRepoServiceStub like this:

```<code>cosmoRepoServiceStub
    .Setup(service => service.GetVehicleInfo(It.IsAny<string>(), It.IsAny<string>()))
    .ReturnsAsync(responseMock.Object);
</code>```

GetVehicleInfo parameters should any string in the setup method

Instead of calling the .Result inside the method selector please prefer ReturnsAsync

Or if you really need to anticipate "a1" as a first argument then define it as

```<code>const StringComparison comparison = StringComparison.OrdinalIgnoreCase;
cosmoRepoServiceStub
    .Setup(service => service.GetVehicleInfo(
       It.Is<string>(param1 => string.Equals(param1, "a1", comparison),
       It.Is<string>(param1 => string.Equals(param1, "a2", comparison)))
    .ReturnsAsync(responseMock.Object);
</code>```

UPDATE #1 Reflect to comment

Why does It.IsAny work whereas "a1" does not?

Moq uses uses object.Equals under the hood to check the Setup's argument against the actual invocation's argument.

This means that the comparison for value types and for strings are based on their values (not based on their references).

So, in your particular case that means either plate or country does not contain a1 or a2 strings respectively.

In short I should work, but as a general rule of thumb

Make your Setup as generic as possible

Make your Verify as specific as possible

Title: Mocking ItemResponse in CosmosDB

Body:
I am writing unit tests using Moq in xUnit for a service that involves CosmosDB. There's a method GetVehicleInfo which returns ItemResponse<VehicleInfo> from CosmosDB. As ItemResponse has a protected constructor so I can't new it up. Therefore, I'm mocking the caller method and doing

var responseMock = new Mock<ItemResponse<VehicleInfo>>();
responseMock.Setup(x => x.Resource).Returns(expectedItem); //expectedItem is of VehicleInfo type
cosmoRepoServiceStub.Setup(service => service.GetVehicleInfo("a1", "a2").Result).Returns(responseMock.Object);

The problem I face is that when GetVehicleInfo is called as below, it returns null always. I expect it to return ItemResponse<VehicleInfo> wherein Resource will contain expectedItem.

ItemResponse<VehicleInfo> response = await _cosmosRepo.GetVehicleInfo(plate, country);
if (response == null){ //... }

Body:
You should setup your cosmoRepoServiceStub like this:

cosmoRepoServiceStub
    .Setup(service => service.GetVehicleInfo(It.IsAny<string>(), It.IsAny<string>()))
    .ReturnsAsync(responseMock.Object);

GetVehicleInfo parameters should any string in the setup method

Instead of calling the .Result inside the method selector please prefer ReturnsAsync

Or if you really need to anticipate "a1" as a first argument then define it as

const StringComparison comparison = StringComparison.OrdinalIgnoreCase;
cosmoRepoServiceStub
    .Setup(service => service.GetVehicleInfo(
       It.Is<string>(param1 => string.Equals(param1, "a1", comparison),
       It.Is<string>(param1 => string.Equals(param1, "a2", comparison)))
    .ReturnsAsync(responseMock.Object);

UPDATE #1 Reflect to comment

Why does It.IsAny work whereas "a1" does not?

Moq uses uses object.Equals under the hood to check the Setup's argument against the actual invocation's argument.

This means that the comparison for value types and for strings are based on their values (not based on their references).

So, in your particular case that means either plate or country does not contain a1 or a2 strings respectively.

In short I should work, but as a general rule of thumb

Make your Setup as generic as possible

Make your Verify as specific as possible


问:
TypeError: 'str' object doesn't support item deletion
```<code>x = True
pizza = []
pizza_topping = []

while x:
    pizza_topping = input("Please enter your pizza toppings(type 'quit' to when you're done): ")

    if pizza_topping == 'quit':
        print(f'Thank you for your order. Your pizza toppings are: {pizza}')
        x = False
    else:
        pizza.append(pizza_topping)
        del pizza_topping[0]
</code>```

Dear people,

I get this error:

del pizza_topping[0] TypeError: 'str' object doesn't support item
deletion

What am I doing wrong?

Edit: I changed 'break' to x = False(this was my original code). It got mixed up.

答:
You may have instantiated pizza_topping as a list, but you immediately start using it as a str. It seems like you are trying to slam too many ideas together, and not considering them. You don't need toppings and a pizza. You just need a pizza and store the toppings in it.

Most of what you are trying to do can be done on one line. You don't need to delete anything, just keep overwriting the variable. Also, your loop should be tied to the 'quit' condition. I changed that condition, because typing 'quit' to quit is cumbersome. Just type nothing and press enter to quit.

```<code>s_msg = 'Enter your pizza topping or press return to quit: '
e_msg = 'Thank you for your order!\nYour toppings are:\t{}'

pizza = []

while (topping := input(s_msg)) != '':
    pizza.append(topping)

print(e_msg.format(', '.join(pizza)))
</code>```

There are more things to consider, though. What if the user quits, but wants to start over? What if the topping is not a valid topping? What if your user can't spell? How does your system know that pepperoni and peperony are the same thing? These are your real challenges.

Body:
x = True
pizza = []
pizza_topping = []

while x:
    pizza_topping = input("Please enter your pizza toppings(type 'quit' to when you're done): ")

    if pizza_topping == 'quit':
        print(f'Thank you for your order. Your pizza toppings are: {pizza}')
        x = False
    else:
        pizza.append(pizza_topping)
        del pizza_topping[0]

Dear people,

I get this error:

del pizza_topping[0] TypeError: 'str' object doesn't support item
deletion

What am I doing wrong?

Edit: I changed 'break' to x = False(this was my original code). It got mixed up.

Body:
You may have instantiated pizza_topping as a list, but you immediately start using it as a str. It seems like you are trying to slam too many ideas together, and not considering them. You don't need toppings and a pizza. You just need a pizza and store the toppings in it.

Most of what you are trying to do can be done on one line. You don't need to delete anything, just keep overwriting the variable. Also, your loop should be tied to the 'quit' condition. I changed that condition, because typing 'quit' to quit is cumbersome. Just type nothing and press enter to quit.

s_msg = 'Enter your pizza topping or press return to quit: '
e_msg = 'Thank you for your order!\nYour toppings are:\t{}'

pizza = []

while (topping := input(s_msg)) != '':
    pizza.append(topping)

print(e_msg.format(', '.join(pizza)))

There are more things to consider, though. What if the user quits, but wants to start over? What if the topping is not a valid topping? What if your user can't spell? How does your system know that pepperoni and peperony are the same thing? These are your real challenges.


问:
How to produce a time serie with geom_bar COUNTING INSTANCES in categoric variable?
My data frame (s1) has this structure:

PERIOD         : Date, format: "2019-02-01" "2019-02-01" "2019-02-01" "2019-02-01" ...

OPERATION      : chr  "SALE" "SALE" "SALE" "SALE"…

My goal: creating a plot showing the number of units sold each month between 2019-2021

When I try to produce it by means of ggplot :

```<code>ggplot(s1, aes(x= PERIOD, y= factor(OPERATION)))+
  geom_bar(stat="count", width=0.7, fill="steelblue")+
  theme_minimal()
</code>```

I get this message:

Error: stat_count() can only have an x or y aesthetic

My questions:

How can I manage to transfor “SALE” which is a categoric variable to become numeric  in order to plot the time serie?

Can you envisage a better solution to produce the desired plot?

Thanks in advance for your advices

答:
I made some toy data and created a month variable that distinguishes only month and year but not the day:

```<code>s1 <- data.frame(PERIOD = as.Date(c("2019-02-01", "2019-02-01", "2019-03-01", "2019-02-01",
                                    "2020-02-01", "2020-03-01", "2020-05-01", "2020-02-01")),
                 OPERATION = as.character(c("SALE", "SALE", "SALE", "SALE", "SALE", "SALE", "SALE", "SALE")))

s1$month <- paste(months(s1$PERIOD), format(as.Date(s1$PERIOD, format="%d/%m/%Y"),"%Y"), sep = "_")

library(ggplot2)

ggplot(s1, aes(x= month))+
  geom_bar(stat="count", width=0.7, fill="steelblue")+
  theme_minimal()
</code>```

Here is the output (I am sorry it is in German that`s my system language):

Body:
My data frame (s1) has this structure:

PERIOD         : Date, format: "2019-02-01" "2019-02-01" "2019-02-01" "2019-02-01" ...

OPERATION      : chr  "SALE" "SALE" "SALE" "SALE"…

My goal: creating a plot showing the number of units sold each month between 2019-2021

When I try to produce it by means of ggplot :

ggplot(s1, aes(x= PERIOD, y= factor(OPERATION)))+
  geom_bar(stat="count", width=0.7, fill="steelblue")+
  theme_minimal()

I get this message:

Error: stat_count() can only have an x or y aesthetic

My questions:

How can I manage to transfor “SALE” which is a categoric variable to become numeric  in order to plot the time serie?

Can you envisage a better solution to produce the desired plot?

Thanks in advance for your advices

Body:
I made some toy data and created a month variable that distinguishes only month and year but not the day:

s1 <- data.frame(PERIOD = as.Date(c("2019-02-01", "2019-02-01", "2019-03-01", "2019-02-01",
                                    "2020-02-01", "2020-03-01", "2020-05-01", "2020-02-01")),
                 OPERATION = as.character(c("SALE", "SALE", "SALE", "SALE", "SALE", "SALE", "SALE", "SALE")))

s1$month <- paste(months(s1$PERIOD), format(as.Date(s1$PERIOD, format="%d/%m/%Y"),"%Y"), sep = "_")

library(ggplot2)

ggplot(s1, aes(x= month))+
  geom_bar(stat="count", width=0.7, fill="steelblue")+
  theme_minimal()

Here is the output (I am sorry it is in German that`s my system language):


问:
Finding categories that make up 70% of total turnover in SQL
I want to find the categories that make up a certain percentage of sales, and segment them according to their percentages in SQL. To do this, I must first sort them by their revenues in descending order and then select the top N percent. For example, if the total revenue is 20M:

```<code>Category Revenue
1        6.000.000
2        4.000.000
3        4.000.000
4        3.000.000
5        1.500.000
6        500.000
7        400.000
8        300.000
9        200.000
10       100.000

Total    20.000.000
</code>```

-Categories that make up 70% (14M) of revenue - segment A

-Categories that make up 15% (3M) - segment B

-Categories that make up 10% (2M) - segment C

-Categories that make up 5% (1M) - segment D

So, the segments should be like this:

```<code>Category Segment
1        A
2        A
3        A
4        B
5        C
6        C
7        D
8        D
9        D
10       D

</code>```

答:
I'm sure there's a simpler way of getting this result, but here's one [rather long] query that classifies the categories in segments according to your logic:

```<code>with
q as (
  select *,
    sum(revenue) over(order by revenue desc) as acc_revenue,
    sum(revenue) over() as tot_revenue
  from t
),
a as (
  select * from q where acc_revenue <= 0.7 * tot_revenue
),
b as (
  select *
  from q
  where acc_revenue - (select max(acc_revenue) from a) <= 0.15 * tot_revenue
    and category not in (select category from a)
),
c as (
  select *
  from q
  where acc_revenue - (select max(acc_revenue) from b) <= 0.10 * tot_revenue
    and category not in (select category from a)
    and category not in (select category from b)
),
d as (
  select *
  from q
  where category not in (select category from a)
    and category not in (select category from b)
    and category not in (select category from c)
)
select *, 'A' as segment from a
union all select *, 'B' from b
union all select *, 'C' from c
union all select *, 'D' from d
</code>```

Result:

```<code> category  revenue  acc_revenue  tot_revenue  segment
 --------- -------- ------------ ------------ -------
 1         6000000  6000000      20000000     A
 2         4000000  14000000     20000000     A
 3         4000000  14000000     20000000     A
 4         3000000  17000000     20000000     B
 5         1500000  18500000     20000000     C
 6         500000   19000000     20000000     C
 7         400000   19400000     20000000     D
 8         300000   19700000     20000000     D
 9         200000   19900000     20000000     D
 10        100000   20000000     20000000     D
</code>```

See running example at DB Fiddle.

Body:
I want to find the categories that make up a certain percentage of sales, and segment them according to their percentages in SQL. To do this, I must first sort them by their revenues in descending order and then select the top N percent. For example, if the total revenue is 20M:

Category Revenue
1        6.000.000
2        4.000.000
3        4.000.000
4        3.000.000
5        1.500.000
6        500.000
7        400.000
8        300.000
9        200.000
10       100.000

Total    20.000.000

-Categories that make up 70% (14M) of revenue - segment A

-Categories that make up 15% (3M) - segment B

-Categories that make up 10% (2M) - segment C

-Categories that make up 5% (1M) - segment D

So, the segments should be like this:

Category Segment
1        A
2        A
3        A
4        B
5        C
6        C
7        D
8        D
9        D
10       D

Body:
I'm sure there's a simpler way of getting this result, but here's one [rather long] query that classifies the categories in segments according to your logic:

with
q as (
  select *,
    sum(revenue) over(order by revenue desc) as acc_revenue,
    sum(revenue) over() as tot_revenue
  from t
),
a as (
  select * from q where acc_revenue <= 0.7 * tot_revenue
),
b as (
  select *
  from q
  where acc_revenue - (select max(acc_revenue) from a) <= 0.15 * tot_revenue
    and category not in (select category from a)
),
c as (
  select *
  from q
  where acc_revenue - (select max(acc_revenue) from b) <= 0.10 * tot_revenue
    and category not in (select category from a)
    and category not in (select category from b)
),
d as (
  select *
  from q
  where category not in (select category from a)
    and category not in (select category from b)
    and category not in (select category from c)
)
select *, 'A' as segment from a
union all select *, 'B' from b
union all select *, 'C' from c
union all select *, 'D' from d

Result:

 category  revenue  acc_revenue  tot_revenue  segment
 --------- -------- ------------ ------------ -------
 1         6000000  6000000      20000000     A
 2         4000000  14000000     20000000     A
 3         4000000  14000000     20000000     A
 4         3000000  17000000     20000000     B
 5         1500000  18500000     20000000     C
 6         500000   19000000     20000000     C
 7         400000   19400000     20000000     D
 8         300000   19700000     20000000     D
 9         200000   19900000     20000000     D
 10        100000   20000000     20000000     D

See running example at DB Fiddle.


问:
Trying to access a join table which has no ID
I've got three tables which all join into one table. Here is the code:

```<code>class App < ActiveRecord::Base
  has_many :app_servers
  has_many :servers, :through => :app_servers
  has_many :environments, :through => :app_servers
end

class Server < ActiveRecord::Base
  has_many :app_servers
  has_many :apps, :through => :app_servers
  has_many :environments, :through => :app_servers
end

class Environment < ActiveRecord::Base
  has_many :app_servers
  has_many :apps, :through => :app_servers
  has_many :servers, :through => :app_servers
end

class AppServer < ActiveRecord::Base
  belongs_to :app
  belongs_to :server
  belongs_to :environment
end
</code>```

I've already used scaffold for the App and Server model and can access them, but when I created a scaffold for AppServer and tried accessing the index page, it gives me this error:

No route matches {:action=>"show", :controller=>"app_servers", :id=>#<AppServer app_id: 3, server_id: 1, environment_id: 2>}

I believe the reason for the error is because when I created the AppServer table, I specified that :id => false.

So what I'm really trying to do, is just have the create page, which then allows me to map currently saved Servers, with currently saved Application to a specific environment.
Any ideas on how I can overcome this problem?

Also, is it wrong for my join model to not have an ID, as it was originally a has_and_belongs_to_many model?

Thanks in advance

Edit Here is the index.html.erb file:

```<code><h1>Listing app_servers</h1>

<table>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @app_servers.each do |app_server| %>
  <tr>
<td><%= app_server%></td>
    <td><%= link_to 'Show', app_server %></td>
    <td><%= link_to 'Edit', edit_app_server_path(app_server) %></td>
<td><%= link_to 'Destroy', app_server, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New App server', new_app_server_path %>
</code>```

And also the app_servers_controller.rb file:

```<code>class AppServersController < ApplicationController
  # GET /app_servers
  # GET /app_servers.xml
  def index
    @app_servers =AppServer.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @app_servers }
    end
  end

  # GET /app_servers/1
  # GET /app_servers/1.xml
  def show
    @app_server = AppServer.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @app_server }
    end
  end

  # GET /app_servers/new
  # GET /app_servers/new.xml
  def new
    @app_server = AppServer.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @app_server }
    end
  end

  # GET /app_servers/1/edit
  def edit
    @app_server = AppServer.find(params[:id])
  end

  # POST /app_servers
  # POST /app_servers.xml
  def create
    @app_server = AppServer.new(params[:app_server])

    respond_to do |format|
      if @app_server.save
        format.html { redirect_to(@app_server, :notice => 'App server was successfully     created.') }
        format.xml  { render :xml => @app_server, :status => :created, :location =>     @app_server }
      else
    format.html { render :action => "new" }
        format.xml  { render :xml => @app_server.errors, :status =>     :unprocessable_entity }
      end
    end
  end

  # PUT /app_servers/1
  # PUT /app_servers/1.xml
  def update
    @app_server = AppServer.find(params[:id])

    respond_to do |format|
      if @app_server.update_attributes(params[:app_server])
        format.html { redirect_to(@app_server, :notice => 'App server was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @app_server.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /app_servers/1
  # DELETE /app_servers/1.xml
  def destroy
    @app_server = AppServer.find(params[:id])
    @app_server.destroy

    respond_to do |format|
      format.html { redirect_to(app_servers_url) }
      format.xml  { head :ok }
    end
  end
end
</code>```

答:
Ok. The simplesst solution here is to return id back. Or you should rewrite some standart routes like

```<code>get '/app_servers/show', :to => "app_servers#show", :as => :app_server
</code>```

and remove fetching by id from controllers.

I mean - return IDS back - that's easiear

UPD

Fast and dirty solution here is to add to AppServer model this small method:

```<code>def to_param
  "#{environment_it}_#{app_id}_#{server_id}"
end
</code>```

Body:
I've got three tables which all join into one table. Here is the code:

class App < ActiveRecord::Base
  has_many :app_servers
  has_many :servers, :through => :app_servers
  has_many :environments, :through => :app_servers
end

class Server < ActiveRecord::Base
  has_many :app_servers
  has_many :apps, :through => :app_servers
  has_many :environments, :through => :app_servers
end

class Environment < ActiveRecord::Base
  has_many :app_servers
  has_many :apps, :through => :app_servers
  has_many :servers, :through => :app_servers
end

class AppServer < ActiveRecord::Base
  belongs_to :app
  belongs_to :server
  belongs_to :environment
end

I've already used scaffold for the App and Server model and can access them, but when I created a scaffold for AppServer and tried accessing the index page, it gives me this error:

No route matches {:action=>"show", :controller=>"app_servers", :id=>#<AppServer app_id: 3, server_id: 1, environment_id: 2>}

I believe the reason for the error is because when I created the AppServer table, I specified that :id => false.

So what I'm really trying to do, is just have the create page, which then allows me to map currently saved Servers, with currently saved Application to a specific environment.
Any ideas on how I can overcome this problem?

Also, is it wrong for my join model to not have an ID, as it was originally a has_and_belongs_to_many model?

Thanks in advance

Edit Here is the index.html.erb file:

Listing app_servers

<% @app_servers.each do |app_server| %>

<%= app_server%>
    <%= link_to 'Show', app_server %>
    <%= link_to 'Edit', edit_app_server_path(app_server) %>
<%= link_to 'Destroy', app_server, :confirm => 'Are you sure?', :method => :delete %>

<% end %>

<%= link_to 'New App server', new_app_server_path %>

And also the app_servers_controller.rb file:

class AppServersController < ApplicationController
  # GET /app_servers
  # GET /app_servers.xml
  def index
    @app_servers =AppServer.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @app_servers }
    end
  end

  # GET /app_servers/1
  # GET /app_servers/1.xml
  def show
    @app_server = AppServer.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @app_server }
    end
  end

  # GET /app_servers/new
  # GET /app_servers/new.xml
  def new
    @app_server = AppServer.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @app_server }
    end
  end

  # GET /app_servers/1/edit
  def edit
    @app_server = AppServer.find(params[:id])
  end

  # POST /app_servers
  # POST /app_servers.xml
  def create
    @app_server = AppServer.new(params[:app_server])

    respond_to do |format|
      if @app_server.save
        format.html { redirect_to(@app_server, :notice => 'App server was successfully     created.') }
        format.xml  { render :xml => @app_server, :status => :created, :location =>     @app_server }
      else
    format.html { render :action => "new" }
        format.xml  { render :xml => @app_server.errors, :status =>     :unprocessable_entity }
      end
    end
  end

  # PUT /app_servers/1
  # PUT /app_servers/1.xml
  def update
    @app_server = AppServer.find(params[:id])

    respond_to do |format|
      if @app_server.update_attributes(params[:app_server])
        format.html { redirect_to(@app_server, :notice => 'App server was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @app_server.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /app_servers/1
  # DELETE /app_servers/1.xml
  def destroy
    @app_server = AppServer.find(params[:id])
    @app_server.destroy

    respond_to do |format|
      format.html { redirect_to(app_servers_url) }
      format.xml  { head :ok }
    end
  end
end

Body:
Ok. The simplesst solution here is to return id back. Or you should rewrite some standart routes like

get '/app_servers/show', :to => "app_servers#show", :as => :app_server

and remove fetching by id from controllers.

I mean - return IDS back - that's easiear

UPD

Fast and dirty solution here is to add to AppServer model this small method:

def to_param
  "#{environment_it}_#{app_id}_#{server_id}"
end


问:
Mimekit - Unable to cast object of type 'Org.BouncyCastle.Asn1.DerApplicationSpecific' to type 'Org.BouncyCastle.Asn1.Asn1SequenceParser'
I'm working with mimekit to encrypt and decrypt mime messages and I'm encountering this error everytime I try to decrypt a message:

Unexpected object reading content. BouncyCastle.Crypto  at Org.BouncyCastle.Cms.CmsContentInfoParser..ctor(Stream data) in //crypto/src/cms/CMSContentInfoParser.cs:line 35
at Org.BouncyCastle.Cms.CmsEnvelopedDataParser..ctor(Stream envelopedData) in //crypto/src/cms/CMSEnvelopedDataParser.cs:line 65
at MimeKit.Cryptography.BouncyCastleSecureMimeContext.d__50.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at PasarelaLibrary.Bases.GraphService.BaseGraphPasarela.d__11.MoveNext() in C:\Dev\Euroval\PasarelaAceuro\PasarelaLibrary\Bases\GraphService\BaseGraphPasarela.cs:line 302
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at PasarelaLibrary.Bases.GraphService.BaseGraphPasarela.d__9.MoveNext() in C:\Dev\Euroval\PasarelaAceuro\PasarelaLibrary\Bases\GraphService\BaseGraphPasarela.cs:line 237

Inner exception

Unable to cast object of type 'Org.BouncyCastle.Asn1.DerApplicationSpecific' to type 'Org.BouncyCastle.Asn1.Asn1SequenceParser'.    at Org.BouncyCastle.Cms.CmsContentInfoParser..ctor(Stream data) in /_/crypto/src/cms/CMSContentInfoParser.cs:line 27

the problem is I'm just trying to encrypt and decrypt a message to test the library and the flow of the application and I'm getting this error. Above you can find the code I'm using. I'm using a x509Certificate with a password that I'm importing in the TemporarySecureMimeContext.

```<code>using var context = new TemporarySecureMimeContext();
await context.ImportAsync(certificate);
var encryptedMessage = await GetEncryptedMessage(context, stream, fileroute, certificate, mailFrom, mailTo);
using var testencrypted = new MemoryStream();
await encryptedMessage.WriteToAsync(testencrypted);
testencrypted.Position = 0;
var dec = await context.DecryptAsync(testencrypted); //here it explodes :(

public static async Task<MimeMessage> GetEncryptedMessage(TemporarySecureMimeContext context, Stream stream, string subject, X509Certificate certificate, string mailFrom, string mailTo)
{
    stream.Position = 0;
    SecureMailboxAddress mailFromEncrypted = new SecureMailboxAddress("name", mailFrom, certificate.GetFingerprint());
    SecureMailboxAddress mailToEncrypted = new SecureMailboxAddress("name", mailTo, certificate.GetFingerprint());
    BodyBuilder bodyBuilder = new BodyBuilder();
    using StreamReader reader = new StreamReader(stream);
    bodyBuilder.TextBody = await reader.ReadToEndAsync();
    MimeMessage message = new MimeMessage(new List<InternetAddress> { mailFromEncrypted }, new List<InternetAddress> { mailToEncrypted }, subject, bodyBuilder.ToMessageBody());
    message.Date = DateTime.Now;
    message.MessageId = MimeUtils.GenerateMessageId();
    await message.EncryptAsync(context);
    return message;
}
</code>```

I already read other posts here and in other forums but nothing worked for this case scenario. Could someone help me with this?

答:
You're using it wrong :-)

You are trying to decrypt a MIME message stream. You can't do that.

The SecureMimeContext.Decrypt() and DecryptAsync() methods expect the encrypted content of the MIME message.

If your goal is to load the MimeMessage and decrypt it, you would change your code to this:

```<code>using var context = new TemporarySecureMimeContext();
await context.ImportAsync(certificate);

// get an encrypted message
var encryptedMessage = await GetEncryptedMessage(context, stream, fileroute, certificate, mailFrom, mailTo);

// write the encrypted message to a stream
using var testencrypted = new MemoryStream();
await encryptedMessage.WriteToAsync(testencrypted);
testencrypted.Position = 0;

// load the message from the stream
var loadedMessage = await MimeMessage.LoadAsync(testencrypted);

// get the encrypted body
var encryptedBody = (ApplicationPkcs7Mime) loadedMessage.Body;

// decrypt it
var decryptedBody = await encryptedBody.DecryptAsync(context);

// restore the message to the pre-encrypted state
loadedMessage.Body = decryptedBody;
</code>```

Body:
I'm working with mimekit to encrypt and decrypt mime messages and I'm encountering this error everytime I try to decrypt a message:

Unexpected object reading content. BouncyCastle.Crypto  at Org.BouncyCastle.Cms.CmsContentInfoParser..ctor(Stream data) in //crypto/src/cms/CMSContentInfoParser.cs:line 35
at Org.BouncyCastle.Cms.CmsEnvelopedDataParser..ctor(Stream envelopedData) in //crypto/src/cms/CMSEnvelopedDataParser.cs:line 65
at MimeKit.Cryptography.BouncyCastleSecureMimeContext.d__50.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at PasarelaLibrary.Bases.GraphService.BaseGraphPasarela.d__11.MoveNext() in C:\Dev\Euroval\PasarelaAceuro\PasarelaLibrary\Bases\GraphService\BaseGraphPasarela.cs:line 302
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at PasarelaLibrary.Bases.GraphService.BaseGraphPasarela.d__9.MoveNext() in C:\Dev\Euroval\PasarelaAceuro\PasarelaLibrary\Bases\GraphService\BaseGraphPasarela.cs:line 237

Inner exception

Unable to cast object of type 'Org.BouncyCastle.Asn1.DerApplicationSpecific' to type 'Org.BouncyCastle.Asn1.Asn1SequenceParser'.    at Org.BouncyCastle.Cms.CmsContentInfoParser..ctor(Stream data) in /_/crypto/src/cms/CMSContentInfoParser.cs:line 27

the problem is I'm just trying to encrypt and decrypt a message to test the library and the flow of the application and I'm getting this error. Above you can find the code I'm using. I'm using a x509Certificate with a password that I'm importing in the TemporarySecureMimeContext.

using var context = new TemporarySecureMimeContext();
await context.ImportAsync(certificate);
var encryptedMessage = await GetEncryptedMessage(context, stream, fileroute, certificate, mailFrom, mailTo);
using var testencrypted = new MemoryStream();
await encryptedMessage.WriteToAsync(testencrypted);
testencrypted.Position = 0;
var dec = await context.DecryptAsync(testencrypted); //here it explodes :(

public static async Task<MimeMessage> GetEncryptedMessage(TemporarySecureMimeContext context, Stream stream, string subject, X509Certificate certificate, string mailFrom, string mailTo)
{
    stream.Position = 0;
    SecureMailboxAddress mailFromEncrypted = new SecureMailboxAddress("name", mailFrom, certificate.GetFingerprint());
    SecureMailboxAddress mailToEncrypted = new SecureMailboxAddress("name", mailTo, certificate.GetFingerprint());
    BodyBuilder bodyBuilder = new BodyBuilder();
    using StreamReader reader = new StreamReader(stream);
    bodyBuilder.TextBody = await reader.ReadToEndAsync();
    MimeMessage message = new MimeMessage(new List<InternetAddress> { mailFromEncrypted }, new List<InternetAddress> { mailToEncrypted }, subject, bodyBuilder.ToMessageBody());
    message.Date = DateTime.Now;
    message.MessageId = MimeUtils.GenerateMessageId();
    await message.EncryptAsync(context);
    return message;
}

I already read other posts here and in other forums but nothing worked for this case scenario. Could someone help me with this?

Body:
You're using it wrong :-)

You are trying to decrypt a MIME message stream. You can't do that.

The SecureMimeContext.Decrypt() and DecryptAsync() methods expect the encrypted content of the MIME message.

If your goal is to load the MimeMessage and decrypt it, you would change your code to this:

using var context = new TemporarySecureMimeContext();
await context.ImportAsync(certificate);

// get an encrypted message
var encryptedMessage = await GetEncryptedMessage(context, stream, fileroute, certificate, mailFrom, mailTo);

// write the encrypted message to a stream
using var testencrypted = new MemoryStream();
await encryptedMessage.WriteToAsync(testencrypted);
testencrypted.Position = 0;

// load the message from the stream
var loadedMessage = await MimeMessage.LoadAsync(testencrypted);

// get the encrypted body
var encryptedBody = (ApplicationPkcs7Mime) loadedMessage.Body;

// decrypt it
var decryptedBody = await encryptedBody.DecryptAsync(context);

// restore the message to the pre-encrypted state
loadedMessage.Body = decryptedBody;


问:
Autheticate via Laravel Sanctum by passing token as a GET query parameter
I know the dangers of passing the token as a GET parameter. I've seen this and this. However, in my case there is no other way because the route will get called by a script which I have no influence on.

I think I should implement a custom Guard which extends the Illuminate\Auth\RequestGuard and override the public function user() method. What I don't understand is, where does $this->callback point to? dd says it's an instance of Laravel\Sanctum\Guard .. but which method?

```<code>Laravel\Sanctum\Guard {#265 ▼
  #auth: Illuminate\Auth\AuthManager {#267 ▶}
  #expiration: null
  #provider: null
}
</code>```

答:
I have a solution now.. I ended up extending Laravel\Sanctum\Guard and registering a new Illuminate\Auth\RequestGuard with the custom Sanctum Guard.

Here is the result:

app/Services/Auth/CustomSanctumGuard.php

<?php

namespace App\Services\Auth;

use Arr;
use Illuminate\Http\Request;
use Laravel\Sanctum\Events\TokenAuthenticated;
use Laravel\Sanctum\Guard;
use Laravel\Sanctum\Sanctum;
use Laravel\Sanctum\TransientToken;

class CustomSanctumGuard extends Guard
{
    /**
     * Retrieve the authenticated user for the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function __invoke(Request $request)
    {
        if ($token = $request->bearerToken() ?: $request->token) {
            $model = Sanctum::$personalAccessTokenModel;

            $accessToken = $model::findToken($token);

            if (! $this->isValidAccessToken($accessToken) ||
                ! $this->supportsTokens($accessToken->tokenable)) {
                return;
            }

            $tokenable = $accessToken->tokenable->withAccessToken(
                $accessToken
            );

            event(new TokenAuthenticated($accessToken));

            if (method_exists($accessToken->getConnection(), 'hasModifiedRecords') &&
                method_exists($accessToken->getConnection(), 'setRecordModificationState')) {
                tap($accessToken->getConnection()->hasModifiedRecords(), function ($hasModifiedRecords) use ($accessToken) {
                    $accessToken->forceFill(['last_used_at' => now()])->save();

                    $accessToken->getConnection()->setRecordModificationState($hasModifiedRecords);
                });
            } else {
                $accessToken->forceFill(['last_used_at' => now()])->save();
            }

            return $tokenable;
        }
    }
}
```
<p>app/Providers/AuthServiceProvider.php</p>
<pre class="lang-php prettyprint-override"><code><?php

namespace App\Providers;

use Auth;
use Illuminate\Auth\RequestGuard;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

use App\Services\Auth\CustomSanctumGuard;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Auth::resolved(function ($auth) {
            $auth->extend('custom', function ($app, $name, array $config) use ($auth) {
                return new RequestGuard(
                    new CustomSanctumGuard($auth, config('sanctum.expiration'), $config['provider']),
                    request(),
                    $auth->createUserProvider($config['provider'] ?? null)
                );
            });
        });
    }
}
</code>```

config/auth.php

<?php

return [

    // ...

    'guards' => [
        'custom' => [
            'driver' => 'custom',
            'provider' => 'users',
        ],
        // ...
    ],

    // ...

];
```
<p>config/sanctum.php</p>
<pre class="lang-php prettyprint-override"><code><?php

return [

    // ...

    'guard' => ['custom'],

    // ...
];
</code>```

Body:
I know the dangers of passing the token as a GET parameter. I've seen this and this. However, in my case there is no other way because the route will get called by a script which I have no influence on.

I think I should implement a custom Guard which extends the Illuminate\Auth\RequestGuard and override the public function user() method. What I don't understand is, where does $this->callback point to? dd says it's an instance of Laravel\Sanctum\Guard .. but which method?

Laravel\Sanctum\Guard {#265 ▼
  #auth: Illuminate\Auth\AuthManager {#267 ▶}
  #expiration: null
  #provider: null
}

Body:
I have a solution now.. I ended up extending Laravel\Sanctum\Guard and registering a new Illuminate\Auth\RequestGuard with the custom Sanctum Guard.

Here is the result:

app/Services/Auth/CustomSanctumGuard.php

<?php

namespace App\Services\Auth;

use Arr;
use Illuminate\Http\Request;
use Laravel\Sanctum\Events\TokenAuthenticated;
use Laravel\Sanctum\Guard;
use Laravel\Sanctum\Sanctum;
use Laravel\Sanctum\TransientToken;

class CustomSanctumGuard extends Guard
{
    /**
     * Retrieve the authenticated user for the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function __invoke(Request $request)
    {
        if ($token = $request->bearerToken() ?: $request->token) {
            $model = Sanctum::$personalAccessTokenModel;

            $accessToken = $model::findToken($token);

            if (! $this->isValidAccessToken($accessToken) ||
                ! $this->supportsTokens($accessToken->tokenable)) {
                return;
            }

            $tokenable = $accessToken->tokenable->withAccessToken(
                $accessToken
            );

            event(new TokenAuthenticated($accessToken));

            if (method_exists($accessToken->getConnection(), 'hasModifiedRecords') &&
                method_exists($accessToken->getConnection(), 'setRecordModificationState')) {
                tap($accessToken->getConnection()->hasModifiedRecords(), function ($hasModifiedRecords) use ($accessToken) {
                    $accessToken->forceFill(['last_used_at' => now()])->save();

                    $accessToken->getConnection()->setRecordModificationState($hasModifiedRecords);
                });
            } else {
                $accessToken->forceFill(['last_used_at' => now()])->save();
            }

            return $tokenable;
        }
    }
}

app/Providers/AuthServiceProvider.php

<?php

namespace App\Providers;

use Auth;
use Illuminate\Auth\RequestGuard;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

use App\Services\Auth\CustomSanctumGuard;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Auth::resolved(function ($auth) {
            $auth->extend('custom', function ($app, $name, array $config) use ($auth) {
                return new RequestGuard(
                    new CustomSanctumGuard($auth, config('sanctum.expiration'), $config['provider']),
                    request(),
                    $auth->createUserProvider($config['provider'] ?? null)
                );
            });
        });
    }
}

config/auth.php

<?php

return [

    // ...

    'guards' => [
        'custom' => [
            'driver' => 'custom',
            'provider' => 'users',
        ],
        // ...
    ],

    // ...

];

config/sanctum.php

<?php

return [

    // ...

    'guard' => ['custom'],

    // ...
];


问:
Python docs: confusing terminology of modules and submodules
The docs say: Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

A package is defined in the docs a dir with some either subdirs or files. Those subdirs would be subpackages, following this convention. A submodule then would be a module in the subdir, or the subpackage?

Would it be more clear to say module name A.B designates a module named B in a package named A?

And suppose dir A has a subdir C which contains file D, then one would say D, fully A.C.D, is a submodue of A?

答:
From the glossary on the term module:

An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing.

... and on the term package:

A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an __path__ attribute.

So every (sub-)package is also a module, but the opposite is not true.

Considering the package layout you gave as an example:

A
├── B.py
├── C
│   ├── D.py
│   └── __init__.py
└── __init__.py
```

Here, A, B, C, D are all modules (you can import them via their name: import A or import A.B or import A.C or import A.C.D). However only A, C are considered packages.

Body:
From the glossary on the term module:

An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing.

... and on the term package:

A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an __path__ attribute.

So every (sub-)package is also a module, but the opposite is not true.

Considering the package layout you gave as an example:

A
├── B.py
├── C
│   ├── D.py
│   └── __init__.py
└── __init__.py

Here, A, B, C, D are all modules (you can import them via their name: import A or import A.B or import A.C or import A.C.D). However only A, C are considered packages.


问:
Convert a folder containing asciidocs and pictures to pdf
I would like to convert this book Mastering the Lightning Network, which is freely available through GitHub to a pdf for personal use.

Unfortunately, I have only figured out how to "translate" single files using asciidoc or asciidoctor-pdf. The options for folders don't seem to work with the configuration of the repository.

There has to be an easy way to translate everything, including all files and pictures. Would be very thankful if somebody could help me out.

答:
You could try using imagemagick:
magick *.jpg out.pdf</p>


问:
Sweeping matrix by second matrix by group
I have a problem and I am unable to find similar results (also because I am not sure how to word the search itself).
I have a huge matrix with multiple columns.  This matrix also has a column that specifies the "identity" of each line.
I also have a second matrix with thresholds for each column for each identity.
I can simplify the problem with the following code (although, take in mind that I have many many columns).

```<code>temp_df=data.frame(a_name=rep(c("A","B", "C"), 20), matrix(rnorm(40),nrow=60, ncol=2))
</code>```

That contains:

```<code>> head(temp_df)
  a_name          X1         X2
1      A  0.31469191 -0.2763107
2      B -1.17477425 -0.2066650
3      C  0.10651550  0.1581325
4      A -1.88258477 -0.9280463
5      B -2.58260181  1.0322196
6      C  0.03027953  0.3110290
</code>```

And the threshold matrix:

```<code>temp_limits=data.frame(a_name=c("A", "B", "C"), X1=c(1, 0.5, 0), x2=c(-1, -0.5, -0.25))
</code>```

That contains:

```<code>> temp_limits
  a_name  X1    x2
1      A 1.0 -1.00
2      B 0.5 -0.50
3      C 0.0 -0.25
</code>```

I could process the matrix as follow to obtain what I want:

```<code>res_df=NULL
for(i in unique(temp_df$a_name)){
  tdf=temp_df[temp_df$a_name==i,]
  a_lim=temp_limits[temp_limits$a_name==i,]
  tdf[, 2:3]=sweep(as.matrix(tdf[, 2:3]), MARGIN=2, a_lim[, 2:3], FUN=">" )
  res_df=rbind(res_df, tdf)
}
</code>```

That gives what I want:

```<code>> head(res_df)
   a_name    X1    X2
1       A FALSE  TRUE
4       A FALSE  TRUE
7       A FALSE  TRUE
10      A FALSE  TRUE
13      A FALSE FALSE
16      A FALSE  TRUE
</code>```

But I believe this implementation is too long, cumbersome, and not optimal.
I am thinking I should use group_by, by I am unsure on how to proceed.
Any help?

答:
We may use a join here</p>
```<code>library(data.table)
setDT(temp_df)[temp_limits, .(a_name, X1 = X1 > i.X1, X2 = X2 > i.x2),
    on = .(a_name)]
</code>```

Body:
I have a problem and I am unable to find similar results (also because I am not sure how to word the search itself).
I have a huge matrix with multiple columns.  This matrix also has a column that specifies the "identity" of each line.
I also have a second matrix with thresholds for each column for each identity.
I can simplify the problem with the following code (although, take in mind that I have many many columns).

temp_df=data.frame(a_name=rep(c("A","B", "C"), 20), matrix(rnorm(40),nrow=60, ncol=2))

That contains:

> head(temp_df)
  a_name          X1         X2
1      A  0.31469191 -0.2763107
2      B -1.17477425 -0.2066650
3      C  0.10651550  0.1581325
4      A -1.88258477 -0.9280463
5      B -2.58260181  1.0322196
6      C  0.03027953  0.3110290

And the threshold matrix:

temp_limits=data.frame(a_name=c("A", "B", "C"), X1=c(1, 0.5, 0), x2=c(-1, -0.5, -0.25))

That contains:

> temp_limits
  a_name  X1    x2
1      A 1.0 -1.00
2      B 0.5 -0.50
3      C 0.0 -0.25

I could process the matrix as follow to obtain what I want:

res_df=NULL
for(i in unique(temp_df$a_name)){
  tdf=temp_df[temp_df$a_name==i,]
  a_lim=temp_limits[temp_limits$a_name==i,]
  tdf[, 2:3]=sweep(as.matrix(tdf[, 2:3]), MARGIN=2, a_lim[, 2:3], FUN=">" )
  res_df=rbind(res_df, tdf)
}

That gives what I want:

> head(res_df)
   a_name    X1    X2
1       A FALSE  TRUE
4       A FALSE  TRUE
7       A FALSE  TRUE
10      A FALSE  TRUE
13      A FALSE FALSE
16      A FALSE  TRUE

But I believe this implementation is too long, cumbersome, and not optimal.
I am thinking I should use group_by, by I am unsure on how to proceed.
Any help?

Body:
We may use a join here

library(data.table)
setDT(temp_df)[temp_limits, .(a_name, X1 = X1 > i.X1, X2 = X2 > i.x2),
    on = .(a_name)]


问:
Pulling keys out of typescript type/interface where the values are of type T
I'm working on a new library which will contain a set of callback functions. I want to implement a sort of "namespace" feature so interfaces and callback chains don't get so overwhelming.

My base callback / namespace with callback type looks like this:

```<code>type AnyFunction = (...args: any) => void;

type DefinedTypeMap = {
  [key: string]: AnyFunction | DefinedTypeMap;
};
</code>```

Where the then extended interfaces could look like this:

```<code>interface IMyCallbackFunctions extends DefinedTypeMap {
  namespace: {
    func: (msg: string) => void;
  };
  root: (msg: string) => void;
  otherRoot: (msg: string) => void;
}
</code>```

I'm working on a class function that will ONLY accept keys on the object if that value is an AnyFunction type ( Not a nested namespace ).

As the interfaces are defined by the developer using the library ( as long as they extend the required interface ) the accepted function parameters in this case would ONLY be "root" | "otherRoot" I have tried Omit<T, K> as well as looking high and low on stack overflow for a solution ( to no avail ).

This library uses Typescript@4.5.5

The current function (which does not support the in progress namespace feature) looks like this:

```<code>on<E extends keyof P2PConnectionEventMap<T>, F extends P2PConnectionEventMap<T>[E]>(event: E, callback: F) => void
</code>```

and should be modified to only allow the event param to accept keys where the values on the interface are of the callback type not the object type.

Thanks in advance for the help, this is making me want to pull my hair out.

答:
Let's define a type utility called FuncKeys<T> which takes an object type T and returns a union of keys where the type of the property at each such key is assignable to AnyFunction.  The goal is that FuncKeys<IMyCallbackFunctions> should evaluate to "root" | "otherRoot" and that it should not include "namespace" (which is a non-function object) or string (from the index signature on the extended DefinedTypeMap interface).

Just to be painfully clear, your IMyCallbackFunctions interface is equivalent to:

```<code>interface IMyCallbackFunctions {
  [key: string]: DefinedTypeMap | AnyFunction;
  namespace: {
    func: (msg: string) => void;
  };
  root: (msg: string) => void;
  otherRoot: (msg: string) => void;
}
</code>```

where I've just explicitly added the index signature.

Often when faced with a question like this I point to the KeysMatching<T, V> utility as given in the answer to In TypeScript, how to get the keys of an object type whose values are of a given type?.  But that utility doesn't work on types with string index signatures; the fact that every possible string is a valid key for the object type tends to "wash away" any results from the specific literal keys.  So we have to take a different approach.

Here's the implementation I'd go with for your use case:

```<code>type FuncKeys<T extends object> =
  keyof { [K in keyof T as T[K] extends AnyFunction ? K : never]: any };
</code>```

This uses key remapping to filter out keys where the property is not assignable to AnyFunction.  Each key K in the keys of the object type T is "remapped" to either itself (if the property type you get when [indexing into]https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html) T with a key of type K, a.k.a. T[K] is assignable to AnyFunction), or to the never type (otherwise).  This effectively keeps only the keys you want and removes the ones you don't.  Note that the mapped type we come up with has just any as its property types, but that doesn't matter because we are just grabbing the keys with the keyof type operator.

Let's walk through how this works with IMyCallbackFunctions.  It looks like

```<code>  keyof { [K in keyof IMyCallbackFunctions as IMyCallbackFunctions[K] extends AnyFunction ? K : never]: any };
</code>```

so K will iterate through string, "namespace", "root", and "otherRoot".  For string and "namespace", the test IMyCallbackFunctions[K] extends AnyFunction ? K : never will evaluate to never, since (DefinedTypeMap | AnyFunction) extends AnyFunction is not true and neither is {func: (msg: string) => void;} extends AnyFunction.  So those keys are dropped.  For "root" and "otherRoot", the test will evaluate to "root" and "otherRoot" respectively, since ((msg: string) => void) extends AnyFunction is true.

That means we now have

```<code>  keyof { root: any, otherRoot: any }
</code>```

which finally evaluates to "root" | "otherRoot" as desired.

You can then use FuncKeys<T> to make the on() method's call signature only accept keys whose values are function-typed.

Playground link to code

Body:
I'm working on a new library which will contain a set of callback functions. I want to implement a sort of "namespace" feature so interfaces and callback chains don't get so overwhelming.

My base callback / namespace with callback type looks like this:

type AnyFunction = (...args: any) => void;

type DefinedTypeMap = {
  [key: string]: AnyFunction | DefinedTypeMap;
};

Where the then extended interfaces could look like this:

interface IMyCallbackFunctions extends DefinedTypeMap {
  namespace: {
    func: (msg: string) => void;
  };
  root: (msg: string) => void;
  otherRoot: (msg: string) => void;
}

I'm working on a class function that will ONLY accept keys on the object if that value is an AnyFunction type ( Not a nested namespace ).

As the interfaces are defined by the developer using the library ( as long as they extend the required interface ) the accepted function parameters in this case would ONLY be "root" | "otherRoot" I have tried Omit<T, K> as well as looking high and low on stack overflow for a solution ( to no avail ).

This library uses Typescript@4.5.5

The current function (which does not support the in progress namespace feature) looks like this:

on<E extends keyof P2PConnectionEventMap<T>, F extends P2PConnectionEventMap<T>[E]>(event: E, callback: F) => void

and should be modified to only allow the event param to accept keys where the values on the interface are of the callback type not the object type.

Thanks in advance for the help, this is making me want to pull my hair out.

Body:
Let's define a type utility called FuncKeys<T> which takes an object type T and returns a union of keys where the type of the property at each such key is assignable to AnyFunction.  The goal is that FuncKeys<IMyCallbackFunctions> should evaluate to "root" | "otherRoot" and that it should not include "namespace" (which is a non-function object) or string (from the index signature on the extended DefinedTypeMap interface).

Just to be painfully clear, your IMyCallbackFunctions interface is equivalent to:

interface IMyCallbackFunctions {
  [key: string]: DefinedTypeMap | AnyFunction;
  namespace: {
    func: (msg: string) => void;
  };
  root: (msg: string) => void;
  otherRoot: (msg: string) => void;
}

where I've just explicitly added the index signature.

Often when faced with a question like this I point to the KeysMatching<T, V> utility as given in the answer to In TypeScript, how to get the keys of an object type whose values are of a given type?.  But that utility doesn't work on types with string index signatures; the fact that every possible string is a valid key for the object type tends to "wash away" any results from the specific literal keys.  So we have to take a different approach.

Here's the implementation I'd go with for your use case:

type FuncKeys<T extends object> =
  keyof { [K in keyof T as T[K] extends AnyFunction ? K : never]: any };

This uses key remapping to filter out keys where the property is not assignable to AnyFunction.  Each key K in the keys of the object type T is "remapped" to either itself (if the property type you get when [indexing into]https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html) T with a key of type K, a.k.a. T[K] is assignable to AnyFunction), or to the never type (otherwise).  This effectively keeps only the keys you want and removes the ones you don't.  Note that the mapped type we come up with has just any as its property types, but that doesn't matter because we are just grabbing the keys with the keyof type operator.

Let's walk through how this works with IMyCallbackFunctions.  It looks like

  keyof { [K in keyof IMyCallbackFunctions as IMyCallbackFunctions[K] extends AnyFunction ? K : never]: any };

so K will iterate through string, "namespace", "root", and "otherRoot".  For string and "namespace", the test IMyCallbackFunctions[K] extends AnyFunction ? K : never will evaluate to never, since (DefinedTypeMap | AnyFunction) extends AnyFunction is not true and neither is {func: (msg: string) => void;} extends AnyFunction.  So those keys are dropped.  For "root" and "otherRoot", the test will evaluate to "root" and "otherRoot" respectively, since ((msg: string) => void) extends AnyFunction is true.

That means we now have

  keyof { root: any, otherRoot: any }

which finally evaluates to "root" | "otherRoot" as desired.

You can then use FuncKeys<T> to make the on() method's call signature only accept keys whose values are function-typed.

<a href="https://www.typescriptlang.org/play?ts=4.5.4#code/C4TwDgpgBAggdiAYgVzgY2ASwPZygXigAoA6MgQwCcBzAZwC4pyEBKAgPigDdtMATANwAoIaEhQAIhABmmOBD4AVcBACy5MASgBvIVCgBtANYQQjWsEpzqAXUbwkqDDjwAfSTLkLlkdWGEAvsJCcsAQlNLkaNAAkqogAMLkADbJAEZRRijoWLi0UBAAHmFwfPlSsvJKKn46elBw5AC2ELRgURCMuvr60k6MRE201OaW1mz4nDz8wvpB9ZTY2MADQyNQFlZw1BNTvIL1ywAW4QBKSyvEa6NbOxzc+4EiQgD0AFQhcGERHVBxiSl0plss48nV9MZTDdrHYPJVvDUNFB3A4Qbk4LMGs1Wu1ol16r1+ldhtDtrsHjN6vN9ItlqsSRsxmT7tMDvpjmcLvT1ptxizHkIAkI3i9ni8XmJoABpUy0dTANBHawAHkUABooAA1TiEbSGKVQORQEwgbDSKCKGwAWgA-IxFAYpTYCsUIKV8pqoDaoAbGPIuOEoAFIabzZbhOLJVAQTKQLRVTqfbL5YqVerYAg0S52K8JSooAB5bBgfKEGOy5X-JKpDJoLJOdG0TjihoQAOUL0AQhEUfLcdVLpKZSg2DSACsIBhEyazTp9Ya8DOw0x8g6nYO3cPUQ2XF6fVA-W3wrDmCAgz38-Fq0C61ncLHS9GnA-K1fAbX6zkXE3c1Ao2+a2BHd71lLQACJaWAMDkSgMCOUoc5ljAkQgA" rel="nofollow noreferrer">Playground link to code


问:
How can I change a url without reloading the page?
I am using ajax to display my contents. As I display my contents, I want to change the browser url dynamically without reloading the page. How can I proceed?

```<code>window.location.hash="Aboutus";
</code>```

The above code inserts a # sign. I do not want a hash sign in my url since my page can contains a similar id.

答:
Use can use pushState(). Here's some information from Mozilla's developer site:

https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#The_pushState%28%29.c2.a0method

Body:
I am using ajax to display my contents. As I display my contents, I want to change the browser url dynamically without reloading the page. How can I proceed?

window.location.hash="Aboutus";

The above code inserts a # sign. I do not want a hash sign in my url since my page can contains a similar id.


问:
Automate AWS SSM document execution
I have an AWS SSM document shared from another account, to install a software on an EC2 instance. Since there are auto-scaled EC2 instances, depending on the demand, new instances spin up.

Requirement is to automate this document execution on all the SSM Managed EC2 instances every day at a specified time, so that no EC2 instance will be left out without the required software.

What are the ways I can use here? I tried using the Run Command feature, but the name of document does not show up in the list.

答:
Write a Lambda function

Fetch list of EC2 instances,

use SSM (SendCommand) to run your document on each of the instances.

Set up a Cloudwatch Event to invoke Lambda function daily at desired time.

Title: Automate AWS SSM document execution


问:
What does "AWS public service preview" mean?
I don't really understand what does AWS service preview mean. I have seen in AWS announcements, that the Redshift Serverless was released, but it is currently in a preview mode. In AWS Service Terms I have found that SLA does not apply to the service previews. So, my questions:

Are there any other limitations?

Can it happen, that they this service will just disappear after some time?

Are there any available timelines from AWS when this service will become generally available?

Thank you!

答:
I'm not aware of a formal definition of 'Preview' and it may vary from service to service.

Here is what I think it means, broadly:

don't use a preview for production workloads

APIs may change

documentation may be incomplete

features may change, be added, or be removed

I suppose it's theoretically possible that a Preview service might be withdrawn but it seems highly unlikely to me that this would happen.

AWS services do not typically indicate a date when they expect the service to move out of Preview and into General Availability.


问:
Automapper map from nested class to single (flatten)
This is my source:

```<code>public class User
{
    public int UserId { get; set; }

    public Address Address { get; set; }
}

public class Address
{
    public string Address { get; set; }
    public string State {get; set; }
}
</code>```

This is my destination:

```<code>public class UserVM
{
    public int UserId { get; set; }

    public string Address { get; set; }
    public string State { get; set; }
}
</code>```

How do I do the mapping? The normal create map doesn't work when they say flattening is automatic.

答:
I was stumped by this issue and this solved it for me. I assume in your code, AutoMapper is being injected by your DI container</p>
```<code>public class MappingProfile: Profile
{

    public MappingProfile()
    {
        CreateMap<User, UserVM>()
           .IncludeMembers(u => u.Address);
        CreateMap<Address, UserVM>();
    }
}
</code>```

Body:
This is my source:

public class User
{
    public int UserId { get; set; }

    public Address Address { get; set; }
}

public class Address
{
    public string Address { get; set; }
    public string State {get; set; }
}

This is my destination:

public class UserVM
{
    public int UserId { get; set; }

    public string Address { get; set; }
    public string State { get; set; }
}

How do I do the mapping? The normal create map doesn't work when they say flattening is automatic.

Body:
I was stumped by this issue and this solved it for me. I assume in your code, AutoMapper is being injected by your DI container

public class MappingProfile: Profile
{

    public MappingProfile()
    {
        CreateMap<User, UserVM>()
           .IncludeMembers(u => u.Address);
        CreateMap<Address, UserVM>();
    }
}