问:
My changenotifierprovider is not updating. Not sure why
Here is my change Notifier class.

class UserChamaNotifier with ChangeNotifier {
    final List<UserChama> _userChamaList = [];

      UnmodifiableListView<UserChama> get userchamaListy =>
          UnmodifiableListView(_userChamaList);

      void addUserChama(UserChama userchama) {
        _userChamaList.add(userchama);
        notifyListeners();
      }
 }
```
<p>I have created the provider in main.dart:</p>
```Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => _appStateManger,
        ),
        ChangeNotifierProvider(
          create: (context) => _profileManager,
        ),
        ChangeNotifierProvider(
          create: (context) => UserChamaNotifier(),
        )
      ],
```
<p>Then I proceed to add a chama object to my list:</p>
```UserChama userChama =
          UserChama(id: s['Id'], phone: s['Phone'], name: s['Name']);
      print(userChama.phone);
      Provider.of<UserChamaNotifier>(context).addUserChama(userChama);
```
<p>Here i try to access the list through the provider:</p>
```class ChamaList extends StatelessWidget {
  const ChamaList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    UserChamaNotifier userChamaNotifier =
        Provider.of<UserChamaNotifier>(context, listen: true);
    return Text(userChamaNotifier.userchamaListy.length.toString());
  }
}
```

At this point, i have experimented alot and i still don't have the correct way of implementation.

答:
While adding data, set listen:false

  Provider.of<UserChamaNotifier>(context,listen:false)
          .addUserChama(userChama);
```

Check more how listen: false works when used with Provider.of(context, listen: false).

Body:
Here is my change Notifier class.

class UserChamaNotifier with ChangeNotifier {
    final List<UserChama> _userChamaList = [];

      UnmodifiableListView<UserChama> get userchamaListy =>
          UnmodifiableListView(_userChamaList);

      void addUserChama(UserChama userchama) {
        _userChamaList.add(userchama);
        notifyListeners();
      }
 }

I have created the provider in main.dart:

Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => _appStateManger,
        ),
        ChangeNotifierProvider(
          create: (context) => _profileManager,
        ),
        ChangeNotifierProvider(
          create: (context) => UserChamaNotifier(),
        )
      ],

Then I proceed to add a chama object to my list:

UserChama userChama =
          UserChama(id: s['Id'], phone: s['Phone'], name: s['Name']);
      print(userChama.phone);
      Provider.of<UserChamaNotifier>(context).addUserChama(userChama);

Here i try to access the list through the provider:

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

  @override
  Widget build(BuildContext context) {
    UserChamaNotifier userChamaNotifier =
        Provider.of<UserChamaNotifier>(context, listen: true);
    return Text(userChamaNotifier.userchamaListy.length.toString());
  }
}

At this point, i have experimented alot and i still don't have the correct way of implementation.

Body:
While adding data, set listen:false

  Provider.of<UserChamaNotifier>(context,listen:false)
          .addUserChama(userChama);

Check more how listen: false works when used with Provider.of(context, listen: false).


来源: stackexchange

问:
getting duplicate paths in my vscode integrated terminal
I have written a code where I am looking for a environment variable called SQLCONFIGPATH in my computer.  Then reading a config.ini file.

I went to .zprofile and the path variable.  When I call the file from my integrated shell, I get the following error:

```<code> /Users/Me/Documents/research/Home/python/my-lab/sql_config/Users/Me/Documents/research/Home/python/my-lab/sql_config/config.ini
</code>```

But when I go to my regular shell (not in my vscode), I cd into the directory where the file is located and am able to call the file with no issues.

How do I call this within vscode's integrated shell? It seems there is a duplicate being created here.  Also when I go into vscode's coderunner and run the file, it runs with no issues.

The code is supposed to read this path:

```<code>Users/Me/Documents/research/Home/python/my-lab/sql_config/config.ini
</code>```

Thanks

答:
You could fiddle with your .zshrc and .zprofile to ensure that a directory is not added redundantly to your PATH. A much easier approach would be to use a

```<code>typeset -aU path
</code>```

This would ensure that zsh itself keeps duplicates out from PATH.

ContentLicense: CC BY-SA 4.0

Body:
I have written a code where I am looking for a environment variable called SQLCONFIGPATH in my computer.  Then reading a config.ini file.

I went to .zprofile and the path variable.  When I call the file from my integrated shell, I get the following error:

 /Users/Me/Documents/research/Home/python/my-lab/sql_config/Users/Me/Documents/research/Home/python/my-lab/sql_config/config.ini

But when I go to my regular shell (not in my vscode), I cd into the directory where the file is located and am able to call the file with no issues.

How do I call this within vscode's integrated shell? It seems there is a duplicate being created here.  Also when I go into vscode's coderunner and run the file, it runs with no issues.

The code is supposed to read this path:

Users/Me/Documents/research/Home/python/my-lab/sql_config/config.ini

Thanks

Body:
You could fiddle with your .zshrc and .zprofile to ensure that a directory is not added redundantly to your PATH. A much easier approach would be to use a

typeset -aU path

This would ensure that zsh itself keeps duplicates out from PATH.


问:
SendInput Keys in Win32 & Win64 machines
I have used sendInput() under xp 32bits using webservices to push F5 of current focused windows. Now under Vista win64 i can´t obtain this result. Some articles point uint problems using 4bits or 8bits but this is not fixing the problem under vista with differential compilation and FieldOffset(4)or(8). Others speak about no more interaction beetween Vista screen and the window using this SendInput() method. Can someone point the solution to push F5 in win32 and win64 machines. Thanks.</p>

```<code>uint intReturn = 0;
NativeWIN32.INPUT structInput;
structInput = new NativeWIN32.INPUT();
structInput.type = (uint)1;
structInput.ki.wScan = 0;
structInput.ki.time = 0;
structInput.ki.dwFlags = 0;
structInput.ki.dwExtraInfo = IntPtr.Zero;

// Key down the actual key-code
structInput.ki.wVk = (ushort)NativeWIN32.VK.F5;
//vk;
intReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
// Key up the actual key-code
structInput.ki.dwFlags = NativeWIN32.KEYEVENTF_KEYUP;
structInput.ki.wVk = (ushort)NativeWIN32.VK.F5;
//vk;
intReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));

public class NativeWIN32
{
    public const ushort KEYEVENTF_KEYUP = 0x0002;
    public enum VK : ushort
    {
        F5                   = 0x74,
    }

    public struct KEYBDINPUT
    {
        public ushort wVk;
        public ushort wScan;
        public uint dwFlags;
        public long time;
        public uint dwExtraInfo;
    };
    [StructLayout(LayoutKind.Explicit,Size=28)]
    public struct INPUT
    {
        [FieldOffset(0)]
        public uint type;
        #if x86
    //32bit
    [FieldOffset(4)]
        #else
        //64bit
        [FieldOffset(8)]
        #endif
        public KEYBDINPUT ki;
    };

    [DllImport("user32.dll")]
    public static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
</code>```

<p>} </p>

答:
Compile your project for 32 bit would fix this.
Please refer to : http://social.msdn.microsoft.com/Forums/en-SG/Vsexpressvb/thread/69e5529e-372b-4d70-bb94-556507a2358e</p>

ContentLicense: CC BY-SA 2.5

Body:
I have used sendInput() under xp 32bits using webservices to push F5 of current focused windows. Now under Vista win64 i can´t obtain this result. Some articles point uint problems using 4bits or 8bits but this is not fixing the problem under vista with differential compilation and FieldOffset(4)or(8). Others speak about no more interaction beetween Vista screen and the window using this SendInput() method. Can someone point the solution to push F5 in win32 and win64 machines. Thanks.

uint intReturn = 0;
NativeWIN32.INPUT structInput;
structInput = new NativeWIN32.INPUT();
structInput.type = (uint)1;
structInput.ki.wScan = 0;
structInput.ki.time = 0;
structInput.ki.dwFlags = 0;
structInput.ki.dwExtraInfo = IntPtr.Zero;

// Key down the actual key-code
structInput.ki.wVk = (ushort)NativeWIN32.VK.F5;
//vk;
intReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
// Key up the actual key-code
structInput.ki.dwFlags = NativeWIN32.KEYEVENTF_KEYUP;
structInput.ki.wVk = (ushort)NativeWIN32.VK.F5;
//vk;
intReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));

public class NativeWIN32
{
    public const ushort KEYEVENTF_KEYUP = 0x0002;
    public enum VK : ushort
    {
        F5                   = 0x74,
    }

    public struct KEYBDINPUT
    {
        public ushort wVk;
        public ushort wScan;
        public uint dwFlags;
        public long time;
        public uint dwExtraInfo;
    };
    [StructLayout(LayoutKind.Explicit,Size=28)]
    public struct INPUT
    {
        [FieldOffset(0)]
        public uint type;
        #if x86
    //32bit
    [FieldOffset(4)]
        #else
        //64bit
        [FieldOffset(8)]
        #endif
        public KEYBDINPUT ki;
    };

    [DllImport("user32.dll")]
    public static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

}

ContentLicense: CC BY-SA 3.0


问:
Python pandas datafram drop colums where correlation abovethreshold
I have a pandas dataframe (adjusted_data) containing many independent variables and a target variable called RainTomorrow. I found out how I can get the correlation between the independent variables and the target variable by using:

```<code>adjusted_data.corr()['RainTomorrow'][:].abs()
</code>```

I would like to create a new dataframe (adjusted_data_narrowed) that only consists of columns where the correlation value is above a certain threshold. What is the best way to do that?

答:
The following should work. It might not be the best solution or the most convenient, but I think it will do for now. You can replace the threshold with the correlation that you want. For example if you only want columns where the correlation is higher than 0.5 or lower than -0.5, use 0.5 instead of threshold.

```<code>from itertools import combinations

corr = adjust_data.corr()
passed = set()
for (r,c) in combinations(corr.columns, 2):
    if (abs(corr.loc[r,c]) >= threshold):
        passed.add(r)
        passed.add(c)
passed = sorted(passed)
corr = corr.loc[passed, passed]
</code>```

corr is now your correlation matrix where you can see which column does not meet your requirement. Now you can filter your dataframe via:

```<code>df_adjusted = df_adjusted[corr.columns]
</code>```

Body:
I have a pandas dataframe (adjusted_data) containing many independent variables and a target variable called RainTomorrow. I found out how I can get the correlation between the independent variables and the target variable by using:

adjusted_data.corr()['RainTomorrow'][:].abs()

I would like to create a new dataframe (adjusted_data_narrowed) that only consists of columns where the correlation value is above a certain threshold. What is the best way to do that?

Body:
The following should work. It might not be the best solution or the most convenient, but I think it will do for now. You can replace the threshold with the correlation that you want. For example if you only want columns where the correlation is higher than 0.5 or lower than -0.5, use 0.5 instead of threshold.

from itertools import combinations

corr = adjust_data.corr()
passed = set()
for (r,c) in combinations(corr.columns, 2):
    if (abs(corr.loc[r,c]) >= threshold):
        passed.add(r)
        passed.add(c)
passed = sorted(passed)
corr = corr.loc[passed, passed]

corr is now your correlation matrix where you can see which column does not meet your requirement. Now you can filter your dataframe via:

df_adjusted = df_adjusted[corr.columns]


问:
can't extract value from xpath-extract using mule variables
I have a set LocationProperties variable as its Location-465697646-800339871 value. Based on the value of a variable, I want to select a node in the payload.

Mule 3:

```<code>xpath3('//DTOLocation[@id=\'' + flowVars.LocationProperties.LocationRef + '\'][1]/DTOLocationDetail[@DetailTypeCd=\'CommercialPropertyLocationDetail\'][1]/@ProtectionClassCd',flowVars.domPayload)
xpath3('//DTOLocation[@id=' + flowVars.LocationProperties.LocationRef + '][1]/@LocationCounterNumber',flowVars.domPayload)
</code>```

Mule 4 flow:

```<code><flow name="var_xpath_testFlow" doc:id="406270fb-17e7-48e9-a33a-f7a0197f8e05" >
        <http:listener doc:name="Listener" doc:id="662f2277-859f-4516-974b-de7cceeb5b40" config-ref="HTTP_Listener_config" path="/vartest"/>
        <set-variable value="#[payload]" doc:name="Set domPayload" doc:id="2495ac98-b976-41e0-9dcf-398574e54ffa" variableName="domPayload"/>
        <set-variable value="Location-465697646-800339871" doc:name="Set Variable" doc:id="12370458-bb32-4709-b509-acc1e5f50b94" variableName="LocationProperties"/>
        <xml-module:xpath-extract xpath="#["/DTOApplication/DTOLocation[@id='" ++ vars.LocationProperties ++ "'][1]"/DTOLocationDetail[@DetailTypeCd='CommercialPropertyLocationDetail'][1]/@ProtectionClassCd]" target="xvalue1" config-ref="XML_Config"/>
        <xml-module:xpath-extract xpath="#["/DTOApplication/DTOLocation[@id='" ++ vars.LocationProperties ++ "'][1]"/@LocationCounterNumber]" config-ref="XML_Config" target="xvalue2"/>
        <logger level="INFO" doc:name="Logger" doc:id="f495b0bf-f8cb-43be-b4d9-d069758e4028" message="#[vars.xvalue]"/>
    </flow>
</code>```

Input payload: https://github.com/Manikandan99/rate-dtostep/blob/master/request.xml

Expected output is the variable :

xvalue1 returns 3,

xvalue2 returns 1.

If I give values directly in xpath, it's work.

When I'm trying to use variables inside an xpath,it throws error like : https://github.com/Manikandan99/rate-dtostep/blob/master/xapth_error.txt

How to extract value using variables in XPath Mule 4?

答:
The error is because you have not added double code correctly in the expression of XPath

I have done some corrections as below

```<code>
    <flow name="var_xpath_testFlow" doc:id="406270fb-17e7-48e9-a33a-f7a0197f8e05" >
        <http:listener doc:name="Listener" doc:id="662f2277-859f-4516-974b-de7cceeb5b40" config-ref="HTTP_Listener_config" path="/vartest"/>
        <set-variable value="#[payload]" doc:name="Set domPayload" doc:id="2495ac98-b976-41e0-9dcf-398574e54ffa" variableName="domPayload"/>
        <set-variable value="Location-465697646-800339871" doc:name="Set Variable" doc:id="12370458-bb32-4709-b509-acc1e5f50b94" variableName="LocationProperties"/>
        <xml-module:xpath-extract doc:name="Xpath extract" doc:id="4a8ce1ed-3c1c-48f7-95dd-664654c6a66b" xpath="#["/DTOApplication/DTOLocation[@id='" ++ vars.LocationProperties ++ "'][1]/DTOLocationDetail[@DetailTypeCd='CommercialPropertyLocationDetail'][1]/@ProtectionClassCd"]"/>
        <xml-module:xpath-extract doc:name="Xpath extract" doc:id="6287299e-aae5-411b-b6d5-936e6c6be5fb" xpath="#["/DTOApplication/DTOLocation[@id='" ++ vars.LocationProperties ++ "'][1]/@LocationCounterNumber"]"/>
        <logger level="INFO" doc:name="Logger" doc:id="f495b0bf-f8cb-43be-b4d9-d069758e4028" message="#[vars.xvalue]"/>
    </flow>
</code>```

With this, your error will get resolved, which is mentioned in your question. Also, I am not sure why are you setting the payload initially in a variable called domPayload, because you are not using it. Please look into that

as per our discussion in comments, for your expected output use below dataweave code just after second Xpath extractor

```<code>%dw 2.0
output application/json
---
(vars.xvalue1 default [] ++ vars.xvalue2 default []) joinBy ","
</code>```

the o/p will be:- "3,1"

Body:
I have a set LocationProperties variable as its Location-465697646-800339871 value. Based on the value of a variable, I want to select a node in the payload.

Mule 3:

xpath3('//DTOLocation[@id=\'' + flowVars.LocationProperties.LocationRef + '\'][1]/DTOLocationDetail[@DetailTypeCd=\'CommercialPropertyLocationDetail\'][1]/@ProtectionClassCd',flowVars.domPayload)
xpath3('//DTOLocation[@id=' + flowVars.LocationProperties.LocationRef + '][1]/@LocationCounterNumber',flowVars.domPayload)

Mule 4 flow:

<flow name="var_xpath_testFlow" doc:id="406270fb-17e7-48e9-a33a-f7a0197f8e05" >
        <http:listener doc:name="Listener" doc:id="662f2277-859f-4516-974b-de7cceeb5b40" config-ref="HTTP_Listener_config" path="/vartest"/>
        <set-variable value="#[payload]" doc:name="Set domPayload" doc:id="2495ac98-b976-41e0-9dcf-398574e54ffa" variableName="domPayload"/>
        <set-variable value="Location-465697646-800339871" doc:name="Set Variable" doc:id="12370458-bb32-4709-b509-acc1e5f50b94" variableName="LocationProperties"/>
        <xml-module:xpath-extract xpath="#["/DTOApplication/DTOLocation[@id='" ++ vars.LocationProperties ++ "'][1]"/DTOLocationDetail[@DetailTypeCd='CommercialPropertyLocationDetail'][1]/@ProtectionClassCd]" target="xvalue1" config-ref="XML_Config"/>
        <xml-module:xpath-extract xpath="#["/DTOApplication/DTOLocation[@id='" ++ vars.LocationProperties ++ "'][1]"/@LocationCounterNumber]" config-ref="XML_Config" target="xvalue2"/>
        <logger level="INFO" doc:name="Logger" doc:id="f495b0bf-f8cb-43be-b4d9-d069758e4028" message="#[vars.xvalue]"/>
    </flow>

Input payload: https://github.com/Manikandan99/rate-dtostep/blob/master/request.xml

Expected output is the variable :

xvalue1 returns 3,

xvalue2 returns 1.

If I give values directly in xpath, it's work.

When I'm trying to use variables inside an xpath,it throws error like : https://github.com/Manikandan99/rate-dtostep/blob/master/xapth_error.txt

How to extract value using variables in XPath Mule 4?

Body:
The error is because you have not added double code correctly in the expression of XPath

I have done some corrections as below

    <flow name="var_xpath_testFlow" doc:id="406270fb-17e7-48e9-a33a-f7a0197f8e05" >
        <http:listener doc:name="Listener" doc:id="662f2277-859f-4516-974b-de7cceeb5b40" config-ref="HTTP_Listener_config" path="/vartest"/>
        <set-variable value="#[payload]" doc:name="Set domPayload" doc:id="2495ac98-b976-41e0-9dcf-398574e54ffa" variableName="domPayload"/>
        <set-variable value="Location-465697646-800339871" doc:name="Set Variable" doc:id="12370458-bb32-4709-b509-acc1e5f50b94" variableName="LocationProperties"/>
        <xml-module:xpath-extract doc:name="Xpath extract" doc:id="4a8ce1ed-3c1c-48f7-95dd-664654c6a66b" xpath="#[&quot;/DTOApplication/DTOLocation[@id='&quot; ++ vars.LocationProperties ++ &quot;'][1]/DTOLocationDetail[@DetailTypeCd='CommercialPropertyLocationDetail'][1]/@ProtectionClassCd&quot;]"/>
        <xml-module:xpath-extract doc:name="Xpath extract" doc:id="6287299e-aae5-411b-b6d5-936e6c6be5fb" xpath="#[&quot;/DTOApplication/DTOLocation[@id='&quot; ++ vars.LocationProperties ++ &quot;'][1]/@LocationCounterNumber&quot;]"/>
        <logger level="INFO" doc:name="Logger" doc:id="f495b0bf-f8cb-43be-b4d9-d069758e4028" message="#[vars.xvalue]"/>
    </flow>

With this, your error will get resolved, which is mentioned in your question. Also, I am not sure why are you setting the payload initially in a variable called domPayload, because you are not using it. Please look into that

as per our discussion in comments, for your expected output use below dataweave code just after second Xpath extractor

%dw 2.0
output application/json
---
(vars.xvalue1 default [] ++ vars.xvalue2 default []) joinBy ","

the o/p will be:- "3,1"


问:
I am having a problem to fetch and display a single item in Flutter from API
I have an endpoint that returns data in the following JSON format.

```<code>{
    "data": [
        {
            "balance": "40.000000"
        }
    ]
}
</code>```

I want to display the above balance into a wallet UI. I am having difficulty to display a single element that is not using controller formfield.
Below is additional code:

wallet_service.dart

```<code>Future<ApiResponse> getWalletBalance() async {
  ApiResponse apiResponse = ApiResponse();
  try {
    String token = await getToken();
    final response = await http.get(Uri.parse(wallet),
        headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer $token'
        });

    switch(response.statusCode){
      case 200:
        apiResponse.data = Wallet.fromJson(jsonDecode(response.body));

        break;
      case 401:
        apiResponse.error = unauthorized;
        break;
      default:
        apiResponse.error = somethingWentWrong;
        break;
    }
  }
  catch (e){
    apiResponse.error = serverError;
  }
  return apiResponse;
}
</code>```

walletui.dart

```<code>class _DashboardState extends State<Dashboard> {

  Wallet? wallet;
  bool loading = true;
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  //TextEditingController txtBalanceController = TextEditingController();
  //int mybalance=0;

  // get user detail
  void getUserWallet() async {
    ApiResponse response = await getWalletBalance();
    if(response.error == null) {
      setState(() {
        wallet = response.data as Wallet;
        //log('data: $wallet');
        loading = false;
        //txtBalanceController.text = wallet?.balance?? '';

      });
    }
    else if(response.error == unauthorized){
      logout().then((value) => {
        Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>Login()), (route) => false)
      });
    }
    else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text('${response.error}')
      ));
    }
  }

  @override
  void initState() {
    getUserWallet();

    super.initState();
  }
}
</code>```

Wallet Model Class

```<code>class Wallet {
  int? id;
  String? balance;

  Wallet({
    this.id,
    this.balance,
  });

  factory Wallet.fromJson(Map<String, dynamic> json){
    return Wallet(
      id: json['id'],
      balance: json['balance'],
    );
  }
}
</code>```

My goal is to store the balance in a variable wallet that I can execute in the UI and display that value.

答:
Please follow this link call for api:https://github.com/JayswalViraj/Flutter-Login-With-Rest-API

Please you understand after implemente.

Body:
I have an endpoint that returns data in the following JSON format.

{
    "data": [
        {
            "balance": "40.000000"
        }
    ]
}

I want to display the above balance into a wallet UI. I am having difficulty to display a single element that is not using controller formfield.
Below is additional code:

wallet_service.dart

Future<ApiResponse> getWalletBalance() async {
  ApiResponse apiResponse = ApiResponse();
  try {
    String token = await getToken();
    final response = await http.get(Uri.parse(wallet),
        headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer $token'
        });

    switch(response.statusCode){
      case 200:
        apiResponse.data = Wallet.fromJson(jsonDecode(response.body));

        break;
      case 401:
        apiResponse.error = unauthorized;
        break;
      default:
        apiResponse.error = somethingWentWrong;
        break;
    }
  }
  catch (e){
    apiResponse.error = serverError;
  }
  return apiResponse;
}

walletui.dart

class _DashboardState extends State<Dashboard> {

  Wallet? wallet;
  bool loading = true;
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  //TextEditingController txtBalanceController = TextEditingController();
  //int mybalance=0;

  // get user detail
  void getUserWallet() async {
    ApiResponse response = await getWalletBalance();
    if(response.error == null) {
      setState(() {
        wallet = response.data as Wallet;
        //log('data: $wallet');
        loading = false;
        //txtBalanceController.text = wallet?.balance?? '';

      });
    }
    else if(response.error == unauthorized){
      logout().then((value) => {
        Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>Login()), (route) => false)
      });
    }
    else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text('${response.error}')
      ));
    }
  }

  @override
  void initState() {
    getUserWallet();

    super.initState();
  }
}

Wallet Model Class

class Wallet {
  int? id;
  String? balance;

  Wallet({
    this.id,
    this.balance,
  });

  factory Wallet.fromJson(Map<String, dynamic> json){
    return Wallet(
      id: json['id'],
      balance: json['balance'],
    );
  }
}

My goal is to store the balance in a variable wallet that I can execute in the UI and display that value.


问:
Problem with position of new view using presentModalViewController
I am trying to add a new view to my app using presentModalViewController.

```<code>ASpotImageViewController *aSpotImage = [[ASpotImageViewController alloc] initWithNibName:@"ASpotImageView" bundle:nil spotID:spotid];
aSpotImage.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//NSLog(@"frame is %@", aSpotImage.view.frame);
//NSLog(@"origin is %@", aSpotImage.view.frame.origin);
NSLog(@"description is %@", aSpotImage.description);
[aSpotImage setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentModalViewController:aSpotImage animated:YES];
</code>```

But when I use this, the new view appears about 40 pixels or so down the screen, and the bottom is cut off. What could be causing this? I don't have this problem in other cases where I use this code.

答: Your current container is having frame of (320,440,0,40) hence when you present on it it appears to be offset'ed by that much amount, although in reality its just adding it to the location (0,0) with respect to the parent container. The fix would be to readjust the frame accordingly of your current view or the parent view.

Body:
I am trying to add a new view to my app using presentModalViewController.

ASpotImageViewController *aSpotImage = [[ASpotImageViewController alloc] initWithNibName:@"ASpotImageView" bundle:nil spotID:spotid];
aSpotImage.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//NSLog(@"frame is %@", aSpotImage.view.frame);
//NSLog(@"origin is %@", aSpotImage.view.frame.origin);
NSLog(@"description is %@", aSpotImage.description);
[aSpotImage setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentModalViewController:aSpotImage animated:YES];

But when I use this, the new view appears about 40 pixels or so down the screen, and the bottom is cut off. What could be causing this? I don't have this problem in other cases where I use this code.


问:
Caused by: java.lang.IllegalStateException: at android.os.Parcel.createExceptionOrNull
I am getting following exception in production environment. It is related with parcelable classes. But it is not showing which class is problematic. Below is detailed log trace:

```<code>java.lang.RuntimeException:
  at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args (LoadedApk.java:1726)
  at android.app.-$$Lambda$LoadedApk$ReceiverDispatcher$Args$_BumDX2UKsnxLVrE6UJsJZkotuA.run (Unknown Source:2)
  at android.os.Handler.handleCallback (Handler.java:938)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at android.os.Looper.loop (Looper.java:264)
  at android.app.ActivityThread.main (ActivityThread.java:8306)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:632)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1049)
Caused by: java.lang.IllegalStateException:     at android.os.Parcel.createExceptionOrNull(Parcel.java:2397)
  at android.os.Parcel.createException(Parcel.java:2373)
  at android.os.Parcel.readException(Parcel.java:2356)
  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:190)
  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:142)
  at android.content.ContentProviderProxy.call(ContentProviderNative.java:733)
  at android.content.ContentResolver.call(ContentResolver.java:2435)
  at android.provider.DocumentsContract.moveDocument(DocumentsContract.java:1514)
  at com.package.name.FullScreenFace$f.a(:1)
  at c.d.a.d.a$a.onReceive(Unknown Source:249)
  at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1691)
  ... 8 more
</code>```

This is my Code for Model class using Parcelable:

```<code>public class Model implements Parcelable {

String author,language,type,gifFile,binFile;
String downloads,binFileName,gifFileName;
String id;
Timestamp addedon;

protected Model(Parcel in) {
    author = in.readString();
    language = in.readString();
    type = in.readString();
    gifFile = in.readString();
    binFile = in.readString();
    downloads = in.readString();
    binFileName = in.readString();
    gifFileName = in.readString();
    id = in.readString();
    addedon = in.readParcelable(Timestamp.class.getClassLoader());
}

public static final Creator<Model> CREATOR = new Creator<Model>() {
    @Override
    public Model createFromParcel(Parcel in) {
        return new Model(in);
    }

    @Override
    public Model[] newArray(int size) {
        return new Model[size];
    }
};

@Override
public int describeContents() {
    return 0;
}

public boolean equals(Object object) {
    if (object != null && object instanceof Model) {
        return ((Model)object).id.equals((Object)this.id);
    }
    return super.equals(object);
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(author);
    parcel.writeString(language);
    parcel.writeString(type);
    parcel.writeString(gifFile);
    parcel.writeString(binFile);
    parcel.writeString(downloads);
    parcel.writeString(binFileName);
    parcel.writeString(gifFileName);
    parcel.writeString(id);
    parcel.writeParcelable(addedon, i);
}
}
</code>```

This is my Code for Proguard-rules files:

```<code>-keepattributes Signature

-keep class * implements android.os.Parcelable {
   *;
}
</code>```

Can anybody help in solving this error?

答: From what I see the problem may be that some of the values are null. I recommend that before you add readString() and readParcelable to add a conditional to make sure that the values are not null.

Body:
I am getting following exception in production environment. It is related with parcelable classes. But it is not showing which class is problematic. Below is detailed log trace:

java.lang.RuntimeException:
  at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args (LoadedApk.java:1726)
  at android.app.-$$Lambda$LoadedApk$ReceiverDispatcher$Args$_BumDX2UKsnxLVrE6UJsJZkotuA.run (Unknown Source:2)
  at android.os.Handler.handleCallback (Handler.java:938)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at android.os.Looper.loop (Looper.java:264)
  at android.app.ActivityThread.main (ActivityThread.java:8306)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:632)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1049)
Caused by: java.lang.IllegalStateException:     at android.os.Parcel.createExceptionOrNull(Parcel.java:2397)
  at android.os.Parcel.createException(Parcel.java:2373)
  at android.os.Parcel.readException(Parcel.java:2356)
  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:190)
  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:142)
  at android.content.ContentProviderProxy.call(ContentProviderNative.java:733)
  at android.content.ContentResolver.call(ContentResolver.java:2435)
  at android.provider.DocumentsContract.moveDocument(DocumentsContract.java:1514)
  at com.package.name.FullScreenFace$f.a(:1)
  at c.d.a.d.a$a.onReceive(Unknown Source:249)
  at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1691)
  ... 8 more

This is my Code for Model class using Parcelable:

public class Model implements Parcelable {

String author,language,type,gifFile,binFile;
String downloads,binFileName,gifFileName;
String id;
Timestamp addedon;

protected Model(Parcel in) {
    author = in.readString();
    language = in.readString();
    type = in.readString();
    gifFile = in.readString();
    binFile = in.readString();
    downloads = in.readString();
    binFileName = in.readString();
    gifFileName = in.readString();
    id = in.readString();
    addedon = in.readParcelable(Timestamp.class.getClassLoader());
}

public static final Creator<Model> CREATOR = new Creator<Model>() {
    @Override
    public Model createFromParcel(Parcel in) {
        return new Model(in);
    }

    @Override
    public Model[] newArray(int size) {
        return new Model[size];
    }
};

@Override
public int describeContents() {
    return 0;
}

public boolean equals(Object object) {
    if (object != null && object instanceof Model) {
        return ((Model)object).id.equals((Object)this.id);
    }
    return super.equals(object);
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(author);
    parcel.writeString(language);
    parcel.writeString(type);
    parcel.writeString(gifFile);
    parcel.writeString(binFile);
    parcel.writeString(downloads);
    parcel.writeString(binFileName);
    parcel.writeString(gifFileName);
    parcel.writeString(id);
    parcel.writeParcelable(addedon, i);
}
}

This is my Code for Proguard-rules files:

-keepattributes Signature

-keep class * implements android.os.Parcelable {
   *;
}

Can anybody help in solving this error?


问:
How to count the number of a specific value within a 2D array
Say I have the 2D array

```<code>X X X O O O
O O O O O O
O O O O O O
X X X X O O
O O O O O O
O O O O O O
</code>```

I want to count the number of X's recurring within the 2D array. In this case it should be 7. I want to return a true/false boolean value. How would I go about doing this?

答:
The most basic solution would be, to have a Methode, that needs a 2D-Array and the value that you are expecting. Then you iterate through the array using two for-loops. Every time you find an x, you add plus one onto an int variable. After you iterated through the 2D-Array, you compare that counter with the expected value and return a true if the numbers are the same and a false if this is not the case.
Something like this:</p>
```<code>public boolean countX (char[][] array, int expectation){
        int counter = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if(array[i][j] == 'x'){
                    counter++;
                }
            }
        }
        return counter == expectation;
    }
</code>```

Body:
Say I have the 2D array

X X X O O O
O O O O O O
O O O O O O
X X X X O O
O O O O O O
O O O O O O

I want to count the number of X's recurring within the 2D array. In this case it should be 7. I want to return a true/false boolean value. How would I go about doing this?

Body:
The most basic solution would be, to have a Methode, that needs a 2D-Array and the value that you are expecting. Then you iterate through the array using two for-loops. Every time you find an x, you add plus one onto an int variable. After you iterated through the 2D-Array, you compare that counter with the expected value and return a true if the numbers are the same and a false if this is not the case.
Something like this:

public boolean countX (char[][] array, int expectation){
        int counter = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if(array[i][j] == 'x'){
                    counter++;
                }
            }
        }
        return counter == expectation;
    }


问:
Cake script works locally, but fails on docker env - error CS0117
I have added few lines to working cake build script. It executes properly on my local machine, but when trying to implement it on docker, where it worked fine till now - it gives me error:

error CS0117: 'NUnit3Settings' does not contain a definition for 'HandleExitCode'

This is what was added:

```<code>        var settings = new NUnit3Settings
        {
        HandleExitCode = exitCode => exitCode switch {
        0 => true,
        1 => throw new CakeException("Failed unit tests"),
        _ => false // everything else will throw via default implementation
        }
</code>```

What am I missing in docker env?

答: The HandleExitCode was added for the Cake 1.0.0 release. My guess would be that you are using a Cake version before 1.0.0 in your docker environment.

Body:
I have added few lines to working cake build script. It executes properly on my local machine, but when trying to implement it on docker, where it worked fine till now - it gives me error:

error CS0117: 'NUnit3Settings' does not contain a definition for 'HandleExitCode'

This is what was added:

        var settings = new NUnit3Settings
        {
        HandleExitCode = exitCode => exitCode switch {
        0 => true,
        1 => throw new CakeException("Failed unit tests"),
        _ => false // everything else will throw via default implementation
        }

What am I missing in docker env?


问:
Is there a way to clear all data within a CSV file in order to fill it up again with new data?
I am trying to create an IOT weather station where in a Python file it would receive data from a temperature sensor and save it in a CSV along with the second(s) it was received.

Since this is going to be plotted in a graph in real time, I can't have it save new data without clearing the CSV file out first since if I did, the line in the graph will overlap, because of the eventual repetition of seconds in the CSV file.

This is a sample of what is saved in the CSV file:

Celcius,Time
56,20.50
57,20.50
58,20.50
59,20.50
00,20.50
```
<p>I want the code to clear the CSV file once the seconds reach 60 (or 00), so it can be repopulated with new data.</p>
<p>This is what I have come up with so far:</p>
```with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if (secondsNow[2] == "00"):
        print("CLEAR CLEAR CLEAR")
        csv_file.close()
    else:
        csv_writer.writerow(info)
```

答:
You're opening the CSV file in append mode during the minute to add data to the end, what you could then do is close and re-open it in write mode at the end of the minute to start with a fresh file:

while True:
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if secondsNow[2] == '00':
        # open in write mode to start again with a blank file
        with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'w') as csv_file:
            csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            csv_writer.writerow(info)
    else:
        # open in append mode to add data to the end
        with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
            csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            csv_writer.writerow(info)
```

Body:
I am trying to create an IOT weather station where in a Python file it would receive data from a temperature sensor and save it in a CSV along with the second(s) it was received.

Since this is going to be plotted in a graph in real time, I can't have it save new data without clearing the CSV file out first since if I did, the line in the graph will overlap, because of the eventual repetition of seconds in the CSV file.

This is a sample of what is saved in the CSV file:

Celcius,Time
56,20.50
57,20.50
58,20.50
59,20.50
00,20.50

I want the code to clear the CSV file once the seconds reach 60 (or 00), so it can be repopulated with new data.

This is what I have come up with so far:

with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if (secondsNow[2] == "00"):
        print("CLEAR CLEAR CLEAR")
        csv_file.close()
    else:
        csv_writer.writerow(info)


问:
Ozone CFD modelling UDF ansys fluent NMAKE : fatal error U1077 : return code '0x2'
I am using CFD model to study ozone water interaction

Ozone mass transfer and dissolved ozone decomposition process in water were treated as two user-defined functions (UDF)which are programmed by C language then the two UDFs were loaded into the Ansys Fluent solver. On compilation of codes i am getting error
UDF codes that are used :

```<code>#include "udf.h"
#define vr 0.0025
#define dg 0.003
#define kl 0.0005
#define cn 6.0

DEFINE_VR_RATE(vol_reac_rate, c, t, r, mw, yi, rr, rr_t)
{
    real *rr
    real yi[0] = C_YI(cell,thread,0)

    *rr = vr*C_VOF(c,t)*C_R(c,t)*yi[0]/mw[0];

    return *rr;
}
 /*define ozone decay volume reaction rate */

DEFINE_MASS_TRANSFER (liq_gas_transfer, cell, thread, from_index,from_species_index, to_index, to_species_index)
{
    real m_lg;
    Thread *gas, *liq;
    gas = THREAD_SUB_THREAD(thread, from_species_index);
    liq = THREAD_SUB_THREAD(thread, to_species_index);

        m_lg = kl*cn/dg *C_VOF(cell,gas); /*unit:[s^-1] */

    return (m_lg);
} /*define ozone mass transfer rate */
</code>```

ERROR that I am getting:

```<code>mass_transfer_udf.c
..\..\src\mass_transfer_udf.c(10): error C2082: redefinition of formal parameter 'rr'
..\..\src\mass_transfer_udf.c(10): error C2146: syntax error: missing ';' before identifier 'real'
..\..\src\mass_transfer_udf.c(10): error C2275: 'real': illegal use of this type as an expression
C:\PROGRA~1\ANSYSI~1\ANSYSS~1\v221\fluent\fluent22.1.0\src\main\global.h(198): note: see declaration of 'real'
..\..\src\mass_transfer_udf.c(10): error C2146: syntax error: missing ';' before identifier 'yi'
..\..\src\mass_transfer_udf.c(10): error C2065: 'thread': undeclared identifier
..\..\src\mass_transfer_udf.c(10): error C2223: left of '->storageArray' must point to struct/union
..\..\src\mass_transfer_udf.c(10): error C2065: 'cell': undeclared identifier
..\..\src\mass_transfer_udf.c(14): warning C4098: 'vol_reac_rate': 'void' function returning a value
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.EXE"' : return code '0x2'
Stop.Error Object: #f
</code>```

How to solve these errors. I am really new at C language.

答:
The error/warning list is fairly literal.  If you read each description, it tells you the problem it is flagging, and typically, where exactly in your code the problem was flagged.

So for example regarding "redefinition of formal parameter"
In most C compilers, a parameter that is not explicitly typed defaults to  int.   So in the following:

```<code>DEFINE_VR_RATE(vol_reac_rate, c, t, r, mw, yi, rr, rr_t)...
</code>```

all o fthe parameters are being defaulted int int.  And the error: redefinition of formal parameter 'rr' is telling you that rr  defined as int in the parameter list,  and real *rr is attempting to redefine it as real.

To silence the error, precede each of the parameters with a C type such as int, float, double, char, and real (if it is defined in your environment).  Eg:

```<code>typedef  float real; //(your system may already have this type)

DEFINE_VR_RATE(real vol_reac_rate, int c, int t, int r, real mw, real yi[r], real rr, real rr_t)
</code>```

Note: I am guessing at actual types needed above, change as needed.  Also, because yi[0] is used in code, the parameter has to be typed to either an array, or a pointer.  Here I have chosen array, and randomly used r as the parameter to size yi:  yi[r]

Regarding "syntax error: missing ';'":
This is simply flagging a missing ; statement terminator.  Edit this:

```<code>    real *rr
    real yi[0] = C_YI(cell,thread,0)
</code>```

To this:

```<code>    //real *rr;  //will already be defined in your parameter list
    yi[0] = C_YI(cell,thread,0); //ditto
</code>```

Regarding _"'real': illegal use of this type as an expression"

real is seen as a type in your environment, as such should be used only to type a variable, but you are using it in an expression like a variable.  This error is likely piggy backing off of one of the previous errors mentioned, and will cease to exist once your function parameters are typed, and the ; are placed.

Regarding _"'thread': undeclared identifier"  (also 'cell')
thread is not declared anywhere within the scope of where it is being used in the function C_YI().  It may be in a header file, or in another .C file, but not in this compiler unit.

Regarding -"left of '->storageArray' must point to struct/union"

a struct or union type must occupy the left side of the statement ->storageArray.  In your code it evidently does not.

Regarding "'vol_reac_rate': 'void' function returning a value"

The function vol_reac_rate(...) is evidently typed as a void, but in the body of the function you have a return x statement.

Body:
I am using CFD model to study ozone water interaction

Ozone mass transfer and dissolved ozone decomposition process in water were treated as two user-defined functions (UDF)which are programmed by C language then the two UDFs were loaded into the Ansys Fluent solver. On compilation of codes i am getting error
UDF codes that are used :

#include "udf.h"
#define vr 0.0025
#define dg 0.003
#define kl 0.0005
#define cn 6.0

DEFINE_VR_RATE(vol_reac_rate, c, t, r, mw, yi, rr, rr_t)
{
    real *rr
    real yi[0] = C_YI(cell,thread,0)

    *rr = vr*C_VOF(c,t)*C_R(c,t)*yi[0]/mw[0];

    return *rr;
}
 /*define ozone decay volume reaction rate */

DEFINE_MASS_TRANSFER (liq_gas_transfer, cell, thread, from_index,from_species_index, to_index, to_species_index)
{
    real m_lg;
    Thread *gas, *liq;
    gas = THREAD_SUB_THREAD(thread, from_species_index);
    liq = THREAD_SUB_THREAD(thread, to_species_index);

        m_lg = kl*cn/dg *C_VOF(cell,gas); /*unit:[s^-1] */

    return (m_lg);
} /*define ozone mass transfer rate */

ERROR that I am getting:

mass_transfer_udf.c
..\..\src\mass_transfer_udf.c(10): error C2082: redefinition of formal parameter 'rr'
..\..\src\mass_transfer_udf.c(10): error C2146: syntax error: missing ';' before identifier 'real'
..\..\src\mass_transfer_udf.c(10): error C2275: 'real': illegal use of this type as an expression
C:\PROGRA~1\ANSYSI~1\ANSYSS~1\v221\fluent\fluent22.1.0\src\main\global.h(198): note: see declaration of 'real'
..\..\src\mass_transfer_udf.c(10): error C2146: syntax error: missing ';' before identifier 'yi'
..\..\src\mass_transfer_udf.c(10): error C2065: 'thread': undeclared identifier
..\..\src\mass_transfer_udf.c(10): error C2223: left of '->storageArray' must point to struct/union
..\..\src\mass_transfer_udf.c(10): error C2065: 'cell': undeclared identifier
..\..\src\mass_transfer_udf.c(14): warning C4098: 'vol_reac_rate': 'void' function returning a value
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.EXE"' : return code '0x2'
Stop.Error Object: #f

How to solve these errors. I am really new at C language.

Body:
The error/warning list is fairly literal.  If you read each description, it tells you the problem it is flagging, and typically, where exactly in your code the problem was flagged.

So for example regarding "redefinition of formal parameter"
In most C compilers, a parameter that is not explicitly typed defaults to  int.   So in the following:

DEFINE_VR_RATE(vol_reac_rate, c, t, r, mw, yi, rr, rr_t)...

all o fthe parameters are being defaulted int int.  And the error: redefinition of formal parameter 'rr' is telling you that rr  defined as int in the parameter list,  and real *rr is attempting to redefine it as real.

To silence the error, precede each of the parameters with a C type such as int, float, double, char, and real (if it is defined in your environment).  Eg:

typedef  float real; //(your system may already have this type)

DEFINE_VR_RATE(real vol_reac_rate, int c, int t, int r, real mw, real yi[r], real rr, real rr_t)

Note: I am guessing at actual types needed above, change as needed.  Also, because yi[0] is used in code, the parameter has to be typed to either an array, or a pointer.  Here I have chosen array, and randomly used r as the parameter to size yi:  yi[r]

Regarding "syntax error: missing ';'":
This is simply flagging a missing ; statement terminator.  Edit this:

    real *rr
    real yi[0] = C_YI(cell,thread,0)

To this:

    //real *rr;  //will already be defined in your parameter list
    yi[0] = C_YI(cell,thread,0); //ditto

Regarding _"'real': illegal use of this type as an expression"

real is seen as a type in your environment, as such should be used only to type a variable, but you are using it in an expression like a variable.  This error is likely piggy backing off of one of the previous errors mentioned, and will cease to exist once your function parameters are typed, and the ; are placed.

Regarding _"'thread': undeclared identifier"  (also 'cell')
thread is not declared anywhere within the scope of where it is being used in the function C_YI().  It may be in a header file, or in another .C file, but not in this compiler unit.

Regarding -"left of '->storageArray' must point to struct/union"

a struct or union type must occupy the left side of the statement ->storageArray.  In your code it evidently does not.

Regarding "'vol_reac_rate': 'void' function returning a value"

The function vol_reac_rate(...) is evidently typed as a void, but in the body of the function you have a return x statement.


问:
HTTP Error 503. The service is unavailable. App pool stops on accessing website
There are number of posts on this and I have tried many a things by now. But to no avail. Myself a Winforms Developer basically, started working on this Web stuff few days back as my company is taking Web initiatives.

I have a ASP.Net project and I want to host it on local IIS. In Project properties -> Web settings I chose Use Local IIS Server and gave a url as localhost/MyApp. I tried accessing it on my firefox browser and received error as HTTP Error 503. The service is unavailable.

Previously I got many other errors and I one by one fixed them all. But struck with this one. These are the settings I have in my project

Application Pool set to ASP.Net v4.0 Classic

App Pool Enable 32 bit Application property is true

App Pool is started

Project build property set to Any CPU for Target framework

But I would like to mention a weird behavior. Following is something that I am facing

Application Pool is Started

I try to access my local website (by giving url as localhost/MyApp)

I receive the error as HTTP Error 503. The service is unavailable

Application Pool is Stopped

I have seen following link and I have already tried it. For the above behavior I reached here. According to this link, Computer name should not have . in it. I don't have any . in my Computer name but do have - in it. Also my domain name contains . in it. Moreover I can't change these settings as its my office laptop and our TFS settings are bound to our Domain and Computer Names.

Can anyone help me to understand whats happening? Please guide me. Thanks.

Edit

I have following code in Global.asax. Application_BeginRequest method is empty in same file.

```<code>protected override void Application_Start(object sender, EventArgs e)
{
    base.Application_Start(sender, e);
    String _path = String.Concat(System.AppDomain.CurrentDomain.RelativeSearchPath, ";",
                                         System.Environment.GetEnvironmentVariable("PATH"));
    System.Environment.SetEnvironmentVariable("PATH", _path, EnvironmentVariableTarget.Process);
    MyAppLog.Initialize();
    MyAppLog.WriteMessage("Application Started");
}
</code>```

Update

As per the suggestions in Comment, I am able to run the website from Cassini.

答:
Such 503 errors were encountered on our side on Windows Server 2019 while setting up a fresh new Classic ASP website.

In fact, in the App Pool, setting ".NET CLR Version" to "No Managed code" caused the App Pool to stops 2 seconds after being started, thus generating WAS 5002 and 5021 errors in the Windows Event Log.

The solution was to put "v4.0", even if no .NET is used.

Body:
There are number of posts on this and I have tried many a things by now. But to no avail. Myself a Winforms Developer basically, started working on this Web stuff few days back as my company is taking Web initiatives.

I have a ASP.Net project and I want to host it on local IIS. In Project properties -> Web settings I chose Use Local IIS Server and gave a url as localhost/MyApp. I tried accessing it on my firefox browser and received error as HTTP Error 503. The service is unavailable.

Previously I got many other errors and I one by one fixed them all. But struck with this one. These are the settings I have in my project

Application Pool set to ASP.Net v4.0 Classic

App Pool Enable 32 bit Application property is true

App Pool is started

Project build property set to Any CPU for Target framework

But I would like to mention a weird behavior. Following is something that I am facing

Application Pool is Started

I try to access my local website (by giving url as localhost/MyApp)

I receive the error as HTTP Error 503. The service is unavailable

Application Pool is Stopped

I have seen following link and I have already tried it. For the above behavior I reached here. According to this link, Computer name should not have . in it. I don't have any . in my Computer name but do have - in it. Also my domain name contains . in it. Moreover I can't change these settings as its my office laptop and our TFS settings are bound to our Domain and Computer Names.

Can anyone help me to understand whats happening? Please guide me. Thanks.

Edit

I have following code in Global.asax. Application_BeginRequest method is empty in same file.

protected override void Application_Start(object sender, EventArgs e)
{
    base.Application_Start(sender, e);
    String _path = String.Concat(System.AppDomain.CurrentDomain.RelativeSearchPath, ";",
                                         System.Environment.GetEnvironmentVariable("PATH"));
    System.Environment.SetEnvironmentVariable("PATH", _path, EnvironmentVariableTarget.Process);
    MyAppLog.Initialize();
    MyAppLog.WriteMessage("Application Started");
}

Update

As per the suggestions in Comment, I am able to run the website from Cassini.


问:
Use / deep / bug in Vue
I used SCSS in vue-lic3, but there was a strange bug, using / deep / will report errors, I don't want to see it.

Code Running Environment
vue-cli3 + vant + scss

css

```<code>/deep/ .van-tabs__content.van-tabs__content--animated,
  .van-tabs--line,
  .van-pull-refresh,
  .van-pull-refresh__track {
    height: 100%;
  }
</code>```

vue.config.js

```<code>css: {
    loaderOptions: {
      sass: {
        data: `@import "~@/style/module.scss";`
      }
    }
  },
</code>```

error

```<code>Failed to compile with 1 errors                                                                                14:14:46
 error  in ./src/views/RankingList.vue?vue&type=style&index=0&lang=scss&

Module build failed (from ./node_modules/sass-loader/lib/loader.js):

  .van-tabs--line,
 ^
      Expected selector.
    ╷
274 │   /deep/ .van-tabs__content.van-tabs__content--animated,
    │   ^
    ╵
  stdin 274:3  root stylesheet
      in F:\web\project-a\src\views\RankingList.vue (line 274, column 3)

 @ ./node_modules/vue-style-loader??ref--8-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/lib/loader.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/views/RankingList.vue?vue&type=style&index=0&lang=scss& 4:14-444 14:3-18:5 15:22-452
 @ ./src/views/RankingList.vue?vue&type=style&index=0&lang=scss&
 @ ./src/views/RankingList.vue
 @ ./src/router.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://192.168.100.15:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
</code>```

答:
You could use ::ng-deep

Instead of:

```<code>.my-pagination /deep/ .ngx-pagination .current {
  background: #737373;
}
</code>```

Try:

```<code>.my-pagination ::ng-deep.ngx-pagination .current {
  background: #737373;
}
</code>```

Title: Use / deep / bug in Vue

Body:
I used SCSS in vue-lic3, but there was a strange bug, using / deep / will report errors, I don't want to see it.

Code Running Environment
vue-cli3 + vant + scss

css

/deep/ .van-tabs__content.van-tabs__content--animated,
  .van-tabs--line,
  .van-pull-refresh,
  .van-pull-refresh__track {
    height: 100%;
  }

vue.config.js

css: {
    loaderOptions: {
      sass: {
        data: `@import "~@/style/module.scss";`
      }
    }
  },

error

Failed to compile with 1 errors                                                                                14:14:46
 error  in ./src/views/RankingList.vue?vue&type=style&index=0&lang=scss&

Module build failed (from ./node_modules/sass-loader/lib/loader.js):

  .van-tabs--line,
 ^
      Expected selector.
    ╷
274 │   /deep/ .van-tabs__content.van-tabs__content--animated,
    │   ^
    ╵
  stdin 274:3  root stylesheet
      in F:\web\project-a\src\views\RankingList.vue (line 274, column 3)

 @ ./node_modules/vue-style-loader??ref--8-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/lib/loader.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/views/RankingList.vue?vue&type=style&index=0&lang=scss& 4:14-444 14:3-18:5 15:22-452
 @ ./src/views/RankingList.vue?vue&type=style&index=0&lang=scss&
 @ ./src/views/RankingList.vue
 @ ./src/router.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://192.168.100.15:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

Body:
You could use ::ng-deep

Instead of:

.my-pagination /deep/ .ngx-pagination .current {
  background: #737373;
}

Try:

.my-pagination ::ng-deep.ngx-pagination .current {
  background: #737373;
}


答:
You could probably use Lambda expression for this. But, for you might be easier to understand iterating over your 2D array and collect the count in a map.

```<code>public class CountDemo {

    public static void main(String[] args) {
        char[][] matrix = {
                { 'X', 'X', 'X', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'X', 'X', 'X', 'X', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' }};

        Map<Character, Integer> charCount = new HashMap<>();
        for (char[] characters : matrix) {
            for (char character : characters) {
                Integer count = charCount.get(character);
                if (count == null) {
                    charCount.put(character, 1);
                } else {
                    charCount.put(character, ++count);
                }
            }
        }
        System.out.println("Character count");
        System.out.println("X's: " + charCount.get('X'));
        System.out.println("O's: " + charCount.get('O'));
    }
}
</code>```

The output of this program is

```<code>Character count
X's: 7
O's: 29
</code>```

The explanation of the code:

The outer for-loop iterates over each array of characters while the inner loop iterates over the characters in the current array.

Once you have a character, you will "get" the current (count) value for the given key (character). If no matched character is found, the get() function will return null. In that case, you found the first instance of that character; so  you just enter the value of "1" for the count and save it in the map. Otherwise, you increment the current count and you put back the updated count in the map.

Once you finish iterating over the matrix, you are ready to display the stats. Since I knew this example was just 'X' and 'O', I just called the get() directly. When you don't know the contents of the map, the correct solution is to iterate over the map's entries and get whatever is there. So, the System.out statements in the code above should be replaced with the following code snippet:

```<code>Iterator<Map.Entry<Character, Integer>> iter = charCount.entrySet().iterator();

System.out.println("Character count");
while(iter.hasNext()) {
    Entry<Character, Integer> entry = iter.next();
    System.out.println(entry.getKey() + "'s: " + entry.getValue());
}
</code>```

If you were to change your character matrix as follows

```<code>        char[][] matrix = {
                { 'X', 'X', 'X', 'O', 'E', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'E', 'O', 'O', 'O', 'O', 'O' },
                { 'X', 'X', 'X', 'X', 'E', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'E', 'O' }};
</code>```

The output of the program using the EntrySet solution will be as follows

```<code>Character count
E's: 4
X's: 7
O's: 25
</code>```

Title: How to count the number of a specific value within a 2D array

Body:
You could probably use Lambda expression for this. But, for you might be easier to understand iterating over your 2D array and collect the count in a map.

public class CountDemo {

    public static void main(String[] args) {
        char[][] matrix = {
                { 'X', 'X', 'X', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'X', 'X', 'X', 'X', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' }};

        Map<Character, Integer> charCount = new HashMap<>();
        for (char[] characters : matrix) {
            for (char character : characters) {
                Integer count = charCount.get(character);
                if (count == null) {
                    charCount.put(character, 1);
                } else {
                    charCount.put(character, ++count);
                }
            }
        }
        System.out.println("Character count");
        System.out.println("X's: " + charCount.get('X'));
        System.out.println("O's: " + charCount.get('O'));
    }
}

The output of this program is

Character count
X's: 7
O's: 29

The explanation of the code:

The outer for-loop iterates over each array of characters while the inner loop iterates over the characters in the current array.

Once you have a character, you will "get" the current (count) value for the given key (character). If no matched character is found, the get() function will return null. In that case, you found the first instance of that character; so  you just enter the value of "1" for the count and save it in the map. Otherwise, you increment the current count and you put back the updated count in the map.

Once you finish iterating over the matrix, you are ready to display the stats. Since I knew this example was just 'X' and 'O', I just called the get() directly. When you don't know the contents of the map, the correct solution is to iterate over the map's entries and get whatever is there. So, the System.out statements in the code above should be replaced with the following code snippet:

Iterator<Map.Entry<Character, Integer>> iter = charCount.entrySet().iterator();

System.out.println("Character count");
while(iter.hasNext()) {
    Entry<Character, Integer> entry = iter.next();
    System.out.println(entry.getKey() + "'s: " + entry.getValue());
}

If you were to change your character matrix as follows

        char[][] matrix = {
                { 'X', 'X', 'X', 'O', 'E', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'E', 'O', 'O', 'O', 'O', 'O' },
                { 'X', 'X', 'X', 'X', 'E', 'O' },
                { 'O', 'O', 'O', 'O', 'O', 'O' },
                { 'O', 'O', 'O', 'O', 'E', 'O' }};

The output of the program using the EntrySet solution will be as follows

Character count
E's: 4
X's: 7
O's: 25


问:
TortoiseGit save user authentication / credentials
Is there a way to save GITHUB's user credentials with TortoiseGit?

It prompts me the below dialog every time whenever I do a push/pull.

I would like to save my user credential information somewhere like how I did with TortoiseSVN.

答:
When updating to Git for Windows 2.35.1.windows.2 from a older major version, you might want to do the following:

Start Git CMD

Run: git credential-manager-core configure

This should give a response like:

Configuring component 'Git Credential Manager'...

Configuring component 'Azure Repos provider'...

Now when starting the next Git operation, Git will ask you for selecting an account only once, store it and reuse it for the next operation.


问:
Using pd.read_html to return a specific table from a webpage of multiple tables
I am trying to return a specific table from this webpage.

I have tried to scrape it using beautifulsoup but that got way too complicated so I an trying to use pd.read_html instead. The table I'm after is the one with "XYZ Substantial Shareholders" (note that this is just one particular page, I would be using this code to return tables from other stocks as well).

This is the code that I'm currently using to search for the tables - my initial idea was to find the word 'Holding' in the header of the title I'm after, but it has also picked up another table which I didn't want because the word 'Holdings' appeared in an earlier table.

```<code>
# Scrape the Substantial Shareholder table if it exists
sub_table = pd.read_html(current_url, match='Holding')
print(sub_table)
</code>```

Current output

```<code>                    Company   Mkt Cap         2018 A  2019 A   2020 A    2018 A     2019 A    2020 A             2018 A 2019 A 2020 A
0              Altium (ALU)   $4,528M         0.1377  0.3989   0.2353   96.9595    69.3097   56.1095              1.55%  1.28%  1.46%
1  Brainchip Holdings (BRN)   $2,974M         0.6838  0.0000   0.0000    0.0000     0.0000    0.0000              0.00%  0.00%  0.00%
2      Technology One (TNE)   $3,299M         0.1484  0.1679   0.1574   45.3375    38.8213   33.5414              1.36%  1.59%  1.84%
3     Wisetech Global (WTC)  $14,241M         1.2490  0.3624   0.2610  124.5434    91.4118   72.4917              0.15%  0.20%  0.30%
4                Xero (XRO)  $16,610M         2.6697 -0.8109  18.9607  920.3138  4866.8122  243.8197              0.00%  0.00%  0.00%,                 Holding                                        Name
0  176,305,508 (10.82%)                          Peter Van Der Made
1   119,205,377 (7.31%)  Merrill Lynch (Australia) Nominees Pty Ltd
2      114,093,915 (7%)   HSBC Custody Nominees (Australia) Limited]

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

Desired output

```<code>Holding                                        Name
0  176,305,508 (10.82%)                          Peter Van Der Made
1   119,205,377 (7.31%)  Merrill Lynch (Australia) Nominees Pty Ltd
2      114,093,915 (7%)   HSBC Custody Nominees (Australia) Limited]

</code>```

Is there a way for me to specifically match only looking at headers rather than the entire page content?

答:
You simply need to do this:

```<code>current_url = 'https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd'

sub_table = pd.read_html(current_url, match='Holding')
print(sub_table[1])
</code>```

Which returns:

```<code>          Holding                                        Name
0  176,305,508 (10.82%)                          Peter Van Der Made
1   119,205,377 (7.31%)  Merrill Lynch (Australia) Nominees Pty Ltd
2      114,093,915 (7%)   HSBC Custody Nominees (Australia) Limited

</code>```

while

```<code>current_url = 'https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd'

sub_table = pd.read_html(current_url, match='Holding')
print(sub_table[0])
</code>```

gives

```<code>               Company   Mkt Cap EPS Growth (%)                   \
                    Company   Mkt Cap         2018 A  2019 A   2020 A
0              Altium (ALU)   $4,536M         0.1377  0.4001   0.2353
1  Brainchip Holdings (BRN)   $2,794M         0.6838  0.0000   0.0000
2      Technology One (TNE)   $3,296M         0.1484  0.1679   0.1574
3     Wisetech Global (WTC)  $14,456M         1.2490  0.3624   0.2610
4                Xero (XRO)  $16,684M         2.6697 -0.8101  18.8826

    P/E (%)                      Dividend Yield (%)
     2018 A     2019 A    2020 A             2018 A 2019 A 2020 A
0   97.1284    69.3746   56.1615              1.54%  1.28%  1.46%
1    0.0000     0.0000    0.0000              0.00%  0.00%  0.00%
2   45.2931    38.7833   33.5085              1.36%  1.60%  1.84%
3  126.4269    92.7943   73.5880              0.15%  0.20%  0.29%
4  924.4426  4867.3913  244.8065              0.00%  0.00%  0.00%

</code>```

Body:
I am trying to return a specific table from this webpage.

I have tried to scrape it using beautifulsoup but that got way too complicated so I an trying to use pd.read_html instead. The table I'm after is the one with "XYZ Substantial Shareholders" (note that this is just one particular page, I would be using this code to return tables from other stocks as well).

This is the code that I'm currently using to search for the tables - my initial idea was to find the word 'Holding' in the header of the title I'm after, but it has also picked up another table which I didn't want because the word 'Holdings' appeared in an earlier table.

# Scrape the Substantial Shareholder table if it exists
sub_table = pd.read_html(current_url, match='Holding')
print(sub_table)

Current output

                    Company   Mkt Cap         2018 A  2019 A   2020 A    2018 A     2019 A    2020 A             2018 A 2019 A 2020 A
0              Altium (ALU)   $4,528M         0.1377  0.3989   0.2353   96.9595    69.3097   56.1095              1.55%  1.28%  1.46%
1  Brainchip Holdings (BRN)   $2,974M         0.6838  0.0000   0.0000    0.0000     0.0000    0.0000              0.00%  0.00%  0.00%
2      Technology One (TNE)   $3,299M         0.1484  0.1679   0.1574   45.3375    38.8213   33.5414              1.36%  1.59%  1.84%
3     Wisetech Global (WTC)  $14,241M         1.2490  0.3624   0.2610  124.5434    91.4118   72.4917              0.15%  0.20%  0.30%
4                Xero (XRO)  $16,610M         2.6697 -0.8109  18.9607  920.3138  4866.8122  243.8197              0.00%  0.00%  0.00%,                 Holding                                        Name
0  176,305,508 (10.82%)                          Peter Van Der Made
1   119,205,377 (7.31%)  Merrill Lynch (Australia) Nominees Pty Ltd
2      114,093,915 (7%)   HSBC Custody Nominees (Australia) Limited]

Process finished with exit code 0

Desired output

Holding                                        Name
0  176,305,508 (10.82%)                          Peter Van Der Made
1   119,205,377 (7.31%)  Merrill Lynch (Australia) Nominees Pty Ltd
2      114,093,915 (7%)   HSBC Custody Nominees (Australia) Limited]

Is there a way for me to specifically match only looking at headers rather than the entire page content?

Body:
You simply need to do this:

current_url = 'https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd'

sub_table = pd.read_html(current_url, match='Holding')
print(sub_table[1])

Which returns:

          Holding                                        Name
0  176,305,508 (10.82%)                          Peter Van Der Made
1   119,205,377 (7.31%)  Merrill Lynch (Australia) Nominees Pty Ltd
2      114,093,915 (7%)   HSBC Custody Nominees (Australia) Limited

while

current_url = 'https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd'

sub_table = pd.read_html(current_url, match='Holding')
print(sub_table[0])

gives

               Company   Mkt Cap EPS Growth (%)                   \
                    Company   Mkt Cap         2018 A  2019 A   2020 A
0              Altium (ALU)   $4,536M         0.1377  0.4001   0.2353
1  Brainchip Holdings (BRN)   $2,794M         0.6838  0.0000   0.0000
2      Technology One (TNE)   $3,296M         0.1484  0.1679   0.1574
3     Wisetech Global (WTC)  $14,456M         1.2490  0.3624   0.2610
4                Xero (XRO)  $16,684M         2.6697 -0.8101  18.8826

    P/E (%)                      Dividend Yield (%)
     2018 A     2019 A    2020 A             2018 A 2019 A 2020 A
0   97.1284    69.3746   56.1615              1.54%  1.28%  1.46%
1    0.0000     0.0000    0.0000              0.00%  0.00%  0.00%
2   45.2931    38.7833   33.5085              1.36%  1.60%  1.84%
3  126.4269    92.7943   73.5880              0.15%  0.20%  0.29%
4  924.4426  4867.3913  244.8065              0.00%  0.00%  0.00%


问:
Unexpected shell interpretation behavior
I generated some options using shell script, echo $NLB_EIPS resulting in -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

I need to append this option to my original command of docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0". Thus, my final goal is to run docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

However, using the shell script below results in unintended behavior. Though ${NLB_EIPS[@]} holds -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255", log shows me that shell script only interpreted -p "route , completely ignoring the part after the whitespace.

```<code>#!/bin/bash

ADDITIONAL_IPS="1.1.1.1 2.2.2.2 3.3.3.3"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p \"route $IP 255.255.255.255\""
done

echo "Added additional routes to NLB_EIP."
echo "NLB_EIPS: $NLB_EIPS"

docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" ${NLB_EIPS[@]}
</code>```

Any help would be greatful!

答:
```<code>#!/bin/bash

additional_ips=( 1.1.1.1 2.2.2.2 3.3.3.3 )
nlb_eips=()
for ip in "${additional_ips[@]}"; do
  nlb_eips+=( -p "route $ip 255.255.255.255" )
done

echo "Added additional routes to NLB_EIP."
printf '%q ' "${nlb_eips[@]}"; echo

docker run <SOME_OTHER_OPTIONS...> \
  -p "route 192.0.0.0 255.255.0.0" \
  -p "route 10.0.0.0 255.255.0.0" \
  "${nlb_eips[@]}"
</code>```

What's different?

We're building commands using arrays instead of string concatenation. For an in-depth discussion of how string concatenation is inherently unfit for the purpose, see BashFAQ #50.

We're quoting our array on expansion, ensuring that its boundaries are respected.

We're using lower-case names for application-defined variables in accordance with POSIX convention.

Body:
I generated some options using shell script, echo $NLB_EIPS resulting in -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

I need to append this option to my original command of docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0". Thus, my final goal is to run docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

However, using the shell script below results in unintended behavior. Though ${NLB_EIPS[@]} holds -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255", log shows me that shell script only interpreted -p "route , completely ignoring the part after the whitespace.

#!/bin/bash

ADDITIONAL_IPS="1.1.1.1 2.2.2.2 3.3.3.3"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p \"route $IP 255.255.255.255\""
done

echo "Added additional routes to NLB_EIP."
echo "NLB_EIPS: $NLB_EIPS"

docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" ${NLB_EIPS[@]}

Any help would be greatful!

Body:
#!/bin/bash

additional_ips=( 1.1.1.1 2.2.2.2 3.3.3.3 )
nlb_eips=()
for ip in "${additional_ips[@]}"; do
  nlb_eips+=( -p "route $ip 255.255.255.255" )
done

echo "Added additional routes to NLB_EIP."
printf '%q ' "${nlb_eips[@]}"; echo

docker run <SOME_OTHER_OPTIONS...> \
  -p "route 192.0.0.0 255.255.0.0" \
  -p "route 10.0.0.0 255.255.0.0" \
  "${nlb_eips[@]}"

What's different?

We're building commands using arrays instead of string concatenation. For an in-depth discussion of how string concatenation is inherently unfit for the purpose, see BashFAQ #50.

We're quoting our array on expansion, ensuring that its boundaries are respected.

We're using lower-case names for application-defined variables in accordance with POSIX convention.


问:
Unable to connect to Vault Error unsealing: Put "https://127.0.0.1:8200/v1/sys/unseal": dial tcp 127.0.0.1:8200: connect: connection refused
I am unable to connect to value. This is the error log:

```<code>default:

 Error! Failed writing data: Put
"http://127.0.0.1:8500/v1/kv/cobalt/cluster/status": dial tcp
 127.0.0.1:8500: connect: connection refused
    default: Checking and intializing vault if needed
    default: Error initializing: Put "https://127.0.0.1:8200/v1/sys/init": dial tcp 127.0.0.1:8200:
 connect: connection refused
   default: Unseal Key (will be hidden):
     default: An error occurred attempting to ask for an unseal key. The raw error message
    default: is shown below, but usually this is because you attempted to pipe a value
   default: into the unseal command or you are executing outside of a terminal (tty). You
   default: should run the unseal command from a terminal for maximum security. If this
    default: is not an option, the unseal key can be provided as the first argument to the
    default: unseal command. The raw error was:  file descriptor 0 is not a terminal
</code>```

When I tried running echo VAULT_ADDR I am getting this: https://127.0.0.1:8200

Anyone having any clue on why I am not able to connect to vault?

答: If you are using any CNI. Check for global network policy.</p>

Body:
I am unable to connect to value. This is the error log:

default:

 Error! Failed writing data: Put
"http://127.0.0.1:8500/v1/kv/cobalt/cluster/status": dial tcp
 127.0.0.1:8500: connect: connection refused
    default: Checking and intializing vault if needed
    default: Error initializing: Put "https://127.0.0.1:8200/v1/sys/init": dial tcp 127.0.0.1:8200:
 connect: connection refused
   default: Unseal Key (will be hidden):
     default: An error occurred attempting to ask for an unseal key. The raw error message
    default: is shown below, but usually this is because you attempted to pipe a value
   default: into the unseal command or you are executing outside of a terminal (tty). You
   default: should run the unseal command from a terminal for maximum security. If this
    default: is not an option, the unseal key can be provided as the first argument to the
    default: unseal command. The raw error was:  file descriptor 0 is not a terminal

When I tried running echo VAULT_ADDR I am getting this: https://127.0.0.1:8200

Anyone having any clue on why I am not able to connect to vault?


问:
Manifest: Line: 1, column: 1, Syntax error on Chrome browser
I have a react app that built through npm run build. GET and POST request from the front-end to back-end gives status 200 but I am getting a weird error that may cause all the images from my files not appear on localhost.

I have already tried to reinstall node, added 'manifest_version': 2 as it is the current version of chrome manifest.

Click here for inspect screenshot

Manifest: Line: 1, column: 1, Syntax error.
Below is my index.html file

```<code><!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>Django React Boilerplate</title>
    <link href="/static/css/2.87ad9c80.chunk.css" rel="stylesheet">
</head>

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script>
        ! function(l) {
            function e(e) {
                for (var r, t, n = e[0], o = e[1], u = e[2], f = 0, i = []; f < n.length; f++) t = n[f], p[t] && i.push(p[t][0]), p[t] = 0;
                for (r in o) Object.prototype.hasOwnProperty.call(o, r) && (l[r] = o[r]);
                for (s && s(e); i.length;) i.shift()();
                return c.push.apply(c, u || []), a()
            }

            function a() {
                for (var e, r = 0; r < c.length; r++) {
                    for (var t = c[r], n = !0, o = 1; o < t.length; o++) {
                        var u = t[o];
                        0 !== p[u] && (n = !1)
                    }
                    n && (c.splice(r--, 1), e = f(f.s = t[0]))
                }
                return e
            }
            var t = {},
                p = {
                    1: 0
                },
                c = [];

            function f(e) {
                if (t[e]) return t[e].exports;
                var r = t[e] = {
                    i: e,
                    l: !1,
                    exports: {}
                };
                return l[e].call(r.exports, r, r.exports, f), r.l = !0, r.exports
            }
            f.m = l, f.c = t, f.d = function(e, r, t) {
                f.o(e, r) || Object.defineProperty(e, r, {
                    enumerable: !0,
                    get: t
                })
            }, f.r = function(e) {
                "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {
                    value: "Module"
                }), Object.defineProperty(e, "__esModule", {
                    value: !0
                })
            }, f.t = function(r, e) {
                if (1 & e && (r = f(r)), 8 & e) return r;
                if (4 & e && "object" == typeof r && r && r.__esModule) return r;
                var t = Object.create(null);
                if (f.r(t), Object.defineProperty(t, "default", {
                        enumerable: !0,
                        value: r
                    }), 2 & e && "string" != typeof r)
                    for (var n in r) f.d(t, n, function(e) {
                        return r[e]
                    }.bind(null, n));
                return t
            }, f.n = function(e) {
                var r = e && e.__esModule ? function() {
                    return e.default
                } : function() {
                    return e
                };
                return f.d(r, "a", r), r
            }, f.o = function(e, r) {
                return Object.prototype.hasOwnProperty.call(e, r)
            }, f.p = "/";
            var r = window.webpackJsonp = window.webpackJsonp || [],
                n = r.push.bind(r);
            r.push = e, r = r.slice();
            for (var o = 0; o < r.length; o++) e(r[o]);
            var s = n;
            a()
        }([])
    </script>
    <script src="/static/js/2.e5ee7667.chunk.js"></script>
    <script src="/static/js/main.9f678b97.chunk.js"></script>
</body>

</html>
</code>```

It appeared that the error starts from the beginning of my index.html file.

答: i put the manifest.json on the public file with the index.html

Body:
I have a react app that built through npm run build. GET and POST request from the front-end to back-end gives status 200 but I am getting a weird error that may cause all the images from my files not appear on localhost.

I have already tried to reinstall node, added 'manifest_version': 2 as it is the current version of chrome manifest.

Click here for inspect screenshot

Manifest: Line: 1, column: 1, Syntax error.
Below is my index.html file

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>Django React Boilerplate</title>
    <link href="/static/css/2.87ad9c80.chunk.css" rel="stylesheet">

    You need to enable JavaScript to run this app.

It appeared that the error starts from the beginning of my index.html file.


问:
ModuleNotFoundError: No module named 'gunicorn'
I followed a [DigitalOcean guide]((https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-debian-10) to set up my Django site. It usually works fine but lately I keep running into this.

```<code>root@localhost:/usr/bin# sudo systemctl status gunicorn
Jun 13 21:27:43 localhost systemd[1]: Started gunicorn daemon.
Jun 13 21:27:43 localhost gunicorn[20611]: Traceback (most recent call last):
Jun 13 21:27:43 localhost gunicorn[20611]:   File "/usr/bin/gunicorn", line 6, in <module>
Jun 13 21:27:43 localhost gunicorn[20611]:     from gunicorn.app.wsgiapp import run
Jun 13 21:27:43 localhost gunicorn[20611]: ModuleNotFoundError: No module named 'gunicorn'
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Failed with result 'exit-code'.
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Start request repeated too quickly.
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Failed with result 'exit-code'.
Jun 13 21:27:43 localhost systemd[1]: Failed to start gunicorn daemon.
</code>```

```<code>root@localhost:/home/development/django# which gunicorn
/usr/bin/gunicorn
</code>```

/etc/systemd/system/gunicorn.service

```<code>[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/home/development/django/
ExecStart=/usr/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          app.wsgi:application

[Install]
WantedBy=multi-user.target
</code>```

答:
I had the exact same problem and was going quite mad but here is what fixed it :

I guess systemd executes with sudo, but I did the pip install blabla without being in sudo.
Found out by doing sudo gunicorn --version and getting nothing.

So just doing sudo pip install gunicorn solved it for me !

Disclaimer : I am probably doing something not at all in the "best practices" so don't hesitate to correct me or give a more detailed response than mine : First time answering :D

Body:
I followed a [DigitalOcean guide]((https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-debian-10) to set up my Django site. It usually works fine but lately I keep running into this.

root@localhost:/usr/bin# sudo systemctl status gunicorn
Jun 13 21:27:43 localhost systemd[1]: Started gunicorn daemon.
Jun 13 21:27:43 localhost gunicorn[20611]: Traceback (most recent call last):
Jun 13 21:27:43 localhost gunicorn[20611]:   File "/usr/bin/gunicorn", line 6, in <module>
Jun 13 21:27:43 localhost gunicorn[20611]:     from gunicorn.app.wsgiapp import run
Jun 13 21:27:43 localhost gunicorn[20611]: ModuleNotFoundError: No module named 'gunicorn'
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Failed with result 'exit-code'.
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Start request repeated too quickly.
Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Failed with result 'exit-code'.
Jun 13 21:27:43 localhost systemd[1]: Failed to start gunicorn daemon.

root@localhost:/home/development/django# which gunicorn
/usr/bin/gunicorn

/etc/systemd/system/gunicorn.service

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/home/development/django/
ExecStart=/usr/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          app.wsgi:application

[Install]
WantedBy=multi-user.target


问:
Creating multiple load testing vegeta reports

Question

I am using the following targets file

```<code>GET https://foo.bar.com
GET https://bar.foo.com
GET https://zoo.lander.com
</code>```

and then issue

```<code>vegeta attack -targets=targetsFile -duration=2s | tee results.bin | vegeta report
</code>```

I then get an aggregated report in the likes of :

```<code>Requests      [total, rate, throughput]         100, 50.57, 24.76
Duration      [total, attack, wait]             3.837s, 1.978s, 1.859s
Latencies     [min, mean, 50, 90, 95, 99, max]  156.862ms, 583.523ms, 417.547ms, 832.023ms, 1.114s, 2.816s, 3.677s
Bytes In      [total, mean]                     20643, 206.43
Bytes Out     [total, mean]                     0, 0.00
Success       [ratio]                           95.00%
Status Codes  [code:count]                      200:95  404:5
Error Set:
404 Not Found
</code>```

Is there a way to get a distinct report (and perhaps plot) per target? Do I have to split the targets?

答:
I don't think Vegeta supports this. I think you can use Ddosify by passing a config file. It will print the metrics of each endpoint.

Example config file for your scenario;

{
    "request_count": 100,
    "load_type": "linear",
    "duration": 2,
    "output": "stdout",
    "steps": [
        {
            "id": 1,
            "url": "https://foo.bar.com",
            "protocol": "https",
            "method": "GET",
            "timeout": 3
        },
        {
            "id": 2,
            "url": "https://bar.foo.com",
            "protocol": "https",
            "method": "GET",
            "timeout": 3
        },
        {
            "id": 3,
            "url": "https://zoo.lander.com",
            "protocol": "https",
            "method": "GET",
            "timeout": 3
        }
    ]
}```
</div>
</div>
</p>
<p>Then run;</p>
```ddosify -config config.json
```
<p>Output;</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>RESULT
-------------------------------------

1. Step 1
---------------------------------
Success Count:    100   (100%)
Failed Count:     0     (0%)

Durations (Avg):
  DNS                  :0.0743s
  Connection           :0.0528s
  TLS                  :0.0734s
  Request Write        :0.0001s
  Server Processing    :0.0918s
  Response Read        :0.3214s
  Total                :0.6138s

Status Code (Message) :Count
  200 (OK)    :100

2. Step 2
---------------------------------
Success Count:    100   (100%)
Failed Count:     0     (0%)

Durations (Avg):
  DNS                  :0.0573s
  Connection           :0.0536s
  TLS                  :0.0747s
  Request Write        :0.0001s
  Server Processing    :0.0906s
  Response Read        :0.3065s
  Total                :0.5828s

Status Code (Message) :Count
  200 (OK)    :100

3. Step 3
---------------------------------
Success Count:    100   (100%)
Failed Count:     0     (0%)

Durations (Avg):
  DNS                  :0.0541s
  Connection           :0.0531s
  TLS                  :0.0753s
  Request Write        :0.0001s
  Server Processing    :0.0885s
  Response Read        :0.3167s
  Total                :0.5878s

Status Code (Message) :Count
  200 (OK)    :100</code>```

Body:
Question

I am using the following targets file

GET https://foo.bar.com
GET https://bar.foo.com
GET https://zoo.lander.com

and then issue

vegeta attack -targets=targetsFile -duration=2s | tee results.bin | vegeta report

I then get an aggregated report in the likes of :

Requests      [total, rate, throughput]         100, 50.57, 24.76
Duration      [total, attack, wait]             3.837s, 1.978s, 1.859s
Latencies     [min, mean, 50, 90, 95, 99, max]  156.862ms, 583.523ms, 417.547ms, 832.023ms, 1.114s, 2.816s, 3.677s
Bytes In      [total, mean]                     20643, 206.43
Bytes Out     [total, mean]                     0, 0.00
Success       [ratio]                           95.00%
Status Codes  [code:count]                      200:95  404:5
Error Set:
404 Not Found

Is there a way to get a distinct report (and perhaps plot) per target? Do I have to split the targets?

Body:
I don't think Vegeta supports this. I think you can use Ddosify by passing a config file. It will print the metrics of each endpoint.

Example config file for your scenario;

{
    "request_count": 100,
    "load_type": "linear",
    "duration": 2,
    "output": "stdout",
    "steps": [
        {
            "id": 1,
            "url": "https://foo.bar.com",
            "protocol": "https",
            "method": "GET",
            "timeout": 3
        },
        {
            "id": 2,
            "url": "https://bar.foo.com",
            "protocol": "https",
            "method": "GET",
            "timeout": 3
        },
        {
            "id": 3,
            "url": "https://zoo.lander.com",
            "protocol": "https",
            "method": "GET",
            "timeout": 3
        }
    ]
}

Then run;

ddosify -config config.json

Output;

RESULT
-------------------------------------

1. Step 1
---------------------------------
Success Count:    100   (100%)
Failed Count:     0     (0%)

Durations (Avg):
  DNS                  :0.0743s
  Connection           :0.0528s
  TLS                  :0.0734s
  Request Write        :0.0001s
  Server Processing    :0.0918s
  Response Read        :0.3214s
  Total                :0.6138s

Status Code (Message) :Count
  200 (OK)    :100

2. Step 2
---------------------------------
Success Count:    100   (100%)
Failed Count:     0     (0%)

Durations (Avg):
  DNS                  :0.0573s
  Connection           :0.0536s
  TLS                  :0.0747s
  Request Write        :0.0001s
  Server Processing    :0.0906s
  Response Read        :0.3065s
  Total                :0.5828s

Status Code (Message) :Count
  200 (OK)    :100

3. Step 3
---------------------------------
Success Count:    100   (100%)
Failed Count:     0     (0%)

Durations (Avg):
  DNS                  :0.0541s
  Connection           :0.0531s
  TLS                  :0.0753s
  Request Write        :0.0001s
  Server Processing    :0.0885s
  Response Read        :0.3167s
  Total                :0.5878s

Status Code (Message) :Count
  200 (OK)    :100


问:
Bot Composer Web Chat embed with secure token?
I have a Bot published from Bot Composer into Azure. The bot is a simple QnA Bot. I need to securely embed it within a webpage. The iframe embed code generated has the Bot Key embedded in the URL. How do I secure this so

users cant see the Key,

limit access to users from my tenant?

Thanks in advance.

答:
Generally speaking, if you want to hide something from the end user, you need to place it somewhere where they do not have access to. Normally, you create some kind of script that is running in the backend of your webpage and deals with creating the tokens with your secret key. These "non-critical" tokens need be to be passed to your Web Chat.
The limitation to your tenant user, you need to implement an authentication system.</p>