问:
Retrofit: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path
Trouble to read JSON string from Android retrofit.

This is my JSON

```<code>{
    "error": false,
    "message": "Data Found.",
    "company": [
        {
            "SUPP_ID": "4",
            "SUPP_CODE": "CO_000004",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Chalakudy Suppliers",
            "SUPP_SHORT_NAME": "CS",
            "SUPP_MOBILE_1": "987654321",
            "SUPP_MOBILE_2": "+1 ",
            "SUPP_PHONE_1": "(456) 123-4561",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "chalakudi@gmail.com",
            "SUPP_ADDR_1": "Chalakudi",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1864",
            "SUPP_CITY_NAME": "Chalakudi",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "2",
            "SUPP_PT_CODE": "Debit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-06 15:40:07",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-06 15:41:41",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        },
        {
            "SUPP_ID": "3",
            "SUPP_CODE": "CO_000003",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Aluva Suppliers",
            "SUPP_SHORT_NAME": "Aluva",
            "SUPP_MOBILE_1": "+91 9876543210",
            "SUPP_MOBILE_2": "+919876543210",
            "SUPP_PHONE_1": "(456) 123-123_",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "aluva@gmail.com",
            "SUPP_ADDR_1": "aluva",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1849",
            "SUPP_CITY_NAME": "Aluva",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "1",
            "SUPP_PT_CODE": "Credit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-06 15:37:39",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-06 15:38:00",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        },
        {
            "SUPP_ID": "2",
            "SUPP_CODE": "CO_000002",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Angamaly Suppliers",
            "SUPP_SHORT_NAME": "AS",
            "SUPP_MOBILE_1": "+91 6543216540",
            "SUPP_MOBILE_2": "+1 ",
            "SUPP_PHONE_1": "(456) 123-4560",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "as@gmail.com",
            "SUPP_ADDR_1": "6, Aluva Main Road\r\nAngamaly",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1851",
            "SUPP_CITY_NAME": "Angamaly",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "1",
            "SUPP_PT_CODE": "Credit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-02 10:55:46",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-06 15:38:17",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        },
        {
            "SUPP_ID": "1",
            "SUPP_CODE": "CO_000001",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Koratty Suppliers",
            "SUPP_SHORT_NAME": "KS",
            "SUPP_MOBILE_1": "+91 9876543210",
            "SUPP_MOBILE_2": "+1 ",
            "SUPP_PHONE_1": "(987) 654-3210",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "koratty@gmail.com",
            "SUPP_ADDR_1": "4/2, Ernakulam High way,\r\nKoratty",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1940",
            "SUPP_CITY_NAME": "Koratty",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "1",
            "SUPP_PT_CODE": "Credit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-02 10:41:16",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-02 10:43:35",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        }
    ]
}
</code>```

This is my Pojo

```<code>public class ApiResponse {

    public boolean error;
    public String message;

    @SerializedName("company")
    public List<Company> companyList;

}

class Company {

    @SerializedName("SUPP_ID")
    public int suppId;

    @SerializedName("SUPP_CODE")
    public String suppCode;

    @SerializedName("CO_ID")
    public String coID;

    @SerializedName("CO_NAME")
    public String coName;

    @SerializedName("SUPP_NAME")
    public String suppName;

    @SerializedName("SUPP_SHORT_NAME")
    public String suppShName;

    @SerializedName("SUPP_MOBILE_1")
    public String suppMobile1;

    @SerializedName("SUPP_MOBILE_2")
    public String suppMobile2;

    @SerializedName("SUPP_PHONE_1")
    public String suppPhone1;

    @SerializedName("SUPP_PHONE_2")
    public String getSuppPhone2;

    @SerializedName("SUPP_EMAIL")
    public String suppEmail;

    @SerializedName("SUPP_ADDR_1")
    public String suppAddr1;

    @SerializedName("SUPP_ADDR_2")
    public String getSuppAddr2;

    @SerializedName("SUPP_ADDR_3")
    public String suppAddr3;

    @SerializedName("SUPP_ADDR_4")
    public String suppAddr4;

    @SerializedName("SUPP_ADDR_5")
    public String suppAddr5;

    @SerializedName("SUPP_CITY_ID")
    public String suppCityId;

    @SerializedName("SUPP_CITY_NAME")
    public String suppCityName;

    @SerializedName("SUPP_STATE_ID")
    public String suppStateId;

    @SerializedName("SUPP_STATE_NAME")
    public String suppStateName;

    @SerializedName("SUPP_COUNTRY_ID")
    public String suppCountryId;

    @SerializedName("SUPP_COUNTYR_NAME")
    public String suppCountryName;

    @SerializedName("SUPP_DF_PT_ID")
    public int suppDfPtId;

    @SerializedName("SUPP_PT_CODE")
    public String suppPtCode;

    @SerializedName("SUPP_CR_UID")
    public int suppCrUid;

    @SerializedName("SUPP_CR_DT")
    public String suppCrDt;
    //"2019-05-06 15:40:07"

    @SerializedName("SUPP_UP_UID")
    public int suppUpUid;

    @SerializedName("SUPP_UP_DT")
    public String suppUpDt;

    @SerializedName("SUPP_FRZ_YN")
    public int suppFrzYn;

    @SerializedName("SUPP_IS_DELETED")
    public int suppIsDeleted;

}
</code>```

答:
With the following code you expect something else from the json, then you actually get.

public interface ApiInterface {
   @FormUrlEncoded @POST("index.php")
   Call<List<ApiResponse>> getSupplier(@Field("action") String action);
 }
```
<p>change it to:</p>
<pre class="lang-java prettyprint-override"><code>public interface ApiInterface {
   @FormUrlEncoded @POST("index.php")
   Call<ApiResponse> getSupplier(@Field("action") String action);
 }
</code>```

and you are good to go :)

Explanation:

With the return type Call<List<ApiResponse>> you "tell" Retrofit that the result you expect, will be an array/list. So Retrofit also expect the incoming json to be an array.

So this would be the json, retrofit expects from your notation:

```<code>[
  {"error": false,
    "message": "Data Found.",
    "company": [...]
  },
  {"error": false,
    "message": "Data Found.",
    "company": [...]
  }
  ...
]
</code>```

Body:
Trouble to read JSON string from Android retrofit.

This is my JSON

{
    "error": false,
    "message": "Data Found.",
    "company": [
        {
            "SUPP_ID": "4",
            "SUPP_CODE": "CO_000004",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Chalakudy Suppliers",
            "SUPP_SHORT_NAME": "CS",
            "SUPP_MOBILE_1": "987654321",
            "SUPP_MOBILE_2": "+1 ",
            "SUPP_PHONE_1": "(456) 123-4561",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "chalakudi@gmail.com",
            "SUPP_ADDR_1": "Chalakudi",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1864",
            "SUPP_CITY_NAME": "Chalakudi",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "2",
            "SUPP_PT_CODE": "Debit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-06 15:40:07",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-06 15:41:41",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        },
        {
            "SUPP_ID": "3",
            "SUPP_CODE": "CO_000003",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Aluva Suppliers",
            "SUPP_SHORT_NAME": "Aluva",
            "SUPP_MOBILE_1": "+91 9876543210",
            "SUPP_MOBILE_2": "+919876543210",
            "SUPP_PHONE_1": "(456) 123-123_",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "aluva@gmail.com",
            "SUPP_ADDR_1": "aluva",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1849",
            "SUPP_CITY_NAME": "Aluva",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "1",
            "SUPP_PT_CODE": "Credit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-06 15:37:39",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-06 15:38:00",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        },
        {
            "SUPP_ID": "2",
            "SUPP_CODE": "CO_000002",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Angamaly Suppliers",
            "SUPP_SHORT_NAME": "AS",
            "SUPP_MOBILE_1": "+91 6543216540",
            "SUPP_MOBILE_2": "+1 ",
            "SUPP_PHONE_1": "(456) 123-4560",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "as@gmail.com",
            "SUPP_ADDR_1": "6, Aluva Main Road\r\nAngamaly",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1851",
            "SUPP_CITY_NAME": "Angamaly",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "1",
            "SUPP_PT_CODE": "Credit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-02 10:55:46",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-06 15:38:17",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        },
        {
            "SUPP_ID": "1",
            "SUPP_CODE": "CO_000001",
            "CO_ID": "1",
            "CO_NAME": "Carrots",
            "SUPP_NAME": "Koratty Suppliers",
            "SUPP_SHORT_NAME": "KS",
            "SUPP_MOBILE_1": "+91 9876543210",
            "SUPP_MOBILE_2": "+1 ",
            "SUPP_PHONE_1": "(987) 654-3210",
            "SUPP_PHONE_2": "",
            "SUPP_EMAIL": "koratty@gmail.com",
            "SUPP_ADDR_1": "4/2, Ernakulam High way,\r\nKoratty",
            "SUPP_ADDR_2": "",
            "SUPP_ADDR_3": "",
            "SUPP_ADDR_4": "",
            "SUPP_ADDR_5": "",
            "SUPP_CITY_ID": "1940",
            "SUPP_CITY_NAME": "Koratty",
            "SUPP_STATE_ID": "19",
            "SUPP_STATE_NAME": "Kerala",
            "SUPP_COUNTRY_ID": "101",
            "SUPP_COUNTYR_NAME": "India",
            "SUPP_DF_PT_ID": "1",
            "SUPP_PT_CODE": "Credit",
            "SUPP_CR_UID": "1",
            "SUPP_CR_DT": "2019-05-02 10:41:16",
            "SUPP_UP_UID": "1",
            "SUPP_UP_DT": "2019-05-02 10:43:35",
            "SUPP_FRZ_YN": "0",
            "SUPP_IS_DELETED": "0"
        }
    ]
}

This is my Pojo

public class ApiResponse {

    public boolean error;
    public String message;

    @SerializedName("company")
    public List<Company> companyList;

}

class Company {

    @SerializedName("SUPP_ID")
    public int suppId;

    @SerializedName("SUPP_CODE")
    public String suppCode;

    @SerializedName("CO_ID")
    public String coID;

    @SerializedName("CO_NAME")
    public String coName;

    @SerializedName("SUPP_NAME")
    public String suppName;

    @SerializedName("SUPP_SHORT_NAME")
    public String suppShName;

    @SerializedName("SUPP_MOBILE_1")
    public String suppMobile1;

    @SerializedName("SUPP_MOBILE_2")
    public String suppMobile2;

    @SerializedName("SUPP_PHONE_1")
    public String suppPhone1;

    @SerializedName("SUPP_PHONE_2")
    public String getSuppPhone2;

    @SerializedName("SUPP_EMAIL")
    public String suppEmail;

    @SerializedName("SUPP_ADDR_1")
    public String suppAddr1;

    @SerializedName("SUPP_ADDR_2")
    public String getSuppAddr2;

    @SerializedName("SUPP_ADDR_3")
    public String suppAddr3;

    @SerializedName("SUPP_ADDR_4")
    public String suppAddr4;

    @SerializedName("SUPP_ADDR_5")
    public String suppAddr5;

    @SerializedName("SUPP_CITY_ID")
    public String suppCityId;

    @SerializedName("SUPP_CITY_NAME")
    public String suppCityName;

    @SerializedName("SUPP_STATE_ID")
    public String suppStateId;

    @SerializedName("SUPP_STATE_NAME")
    public String suppStateName;

    @SerializedName("SUPP_COUNTRY_ID")
    public String suppCountryId;

    @SerializedName("SUPP_COUNTYR_NAME")
    public String suppCountryName;

    @SerializedName("SUPP_DF_PT_ID")
    public int suppDfPtId;

    @SerializedName("SUPP_PT_CODE")
    public String suppPtCode;

    @SerializedName("SUPP_CR_UID")
    public int suppCrUid;

    @SerializedName("SUPP_CR_DT")
    public String suppCrDt;
    //"2019-05-06 15:40:07"

    @SerializedName("SUPP_UP_UID")
    public int suppUpUid;

    @SerializedName("SUPP_UP_DT")
    public String suppUpDt;

    @SerializedName("SUPP_FRZ_YN")
    public int suppFrzYn;

    @SerializedName("SUPP_IS_DELETED")
    public int suppIsDeleted;

}

Body:
With the following code you expect something else from the json, then you actually get.

public interface ApiInterface {
   @FormUrlEncoded @POST("index.php")
   Call<List<ApiResponse>> getSupplier(@Field("action") String action);
 }

change it to:

public interface ApiInterface {
   @FormUrlEncoded @POST("index.php")
   Call<ApiResponse> getSupplier(@Field("action") String action);
 }

and you are good to go :)

Explanation:

With the return type Call<List<ApiResponse>> you "tell" Retrofit that the result you expect, will be an array/list. So Retrofit also expect the incoming json to be an array.

So this would be the json, retrofit expects from your notation:

[
  {"error": false,
    "message": "Data Found.",
    "company": [...]
  },
  {"error": false,
    "message": "Data Found.",
    "company": [...]
  }
  ...
]


来源: stackexchange

问:
How to start Apache and MySQL automatically when Windows 8 comes up
I am using XAMPP, version 3.2.1. I just installed it on Windows 8. Every time I need to go to the XAMPP Control Panel to start services (MySQL, Apache,...); in Windows 7 it started automatically when Windows came up.

Is there a way I can make it auto-start in Windows 8 too?

答:
You can do it via cmd.

For Apache

Open cmd in administrator mode. Change directory to C:/xampp/apache/bin. Run the command as httpd.exe -k install.
Your Apache server service will be installed. You can start it from services.

For MySQL

Change directory to C:/xampp/mysql/bin. Run the command as mysqld --install. Your MySQL service will be installed. You can start it from services.

Note: Make sure the selected Apache and MySQL services are set to start automatically.

You're done. There isn't any need to launch the XAMPP control panel

ContentLicense: CC BY-SA 4.0


问:
Windows Mobile - Internet Usage C#
I need to monitor internet traffic (both upload and download) on windows mobile. Is there any API available to monitor internet data traffic on windows mobile (C#)? I am using OpenNetCF in my project. I can also use API from OpenNetCF is it is available.</p>

答: Unfortunately no, there is no API to monitor traffic (in managed or native code).  The best solution is to create an NDIS intermediate filter driver that does all of the computations, stores the results and exposes an API for retrieving those results.  That has to be written in C.</p>

ContentLicense: CC BY-SA 3.0

Title: Windows Mobile - Internet Usage C#


问:
Using Fabric8 to Deploy a Java Project
I am trying to use Fabric8 to build an image for my Java application. However, I am new and this could be a duplicate question.

I have docker installed and the fabric8 library added via maven.

Below is my initial setup for the fabric maven plugin.

```<code><plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                        <configuration>
                            <dockerHost>/var/run/docker.sock</dockerHost>
                            <images>
                                <image>
                                    <alias>${project.artifactId}</alias>
                                    <name></name>
                                    <build>
                                        <from>java:8</from>
                                        <maintainer>${project.maintainer}</maintainer>
                                        <dockerFile>${project.basedir}/Dockerfile</dockerFile>
                                        <dockerHost>/var/run/docker.sock</dockerHost>
                                        <ports>
                                            <port>8080</port>
                                            <port>8081</port>
                                        </ports>
                                    </build>
                                </image>
                            </images>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

Below is the error message I am getting.

```<code>Unable to parse configuration of mojo io.fabric8:docker-maven-plugin:0.30.0:build for parameter dockerHost: Cannot find 'dockerHost' in class io.fabric8.maven.docker.config.BuildImageConfiguration
</code>```

答:
Try to remove the dockerHost element from the image build configuration. There is no such option for the build configuration.

dockerHost specifies the connection to the Docker host, i.e the machine where the image is going to be built and eventually run. This option is not actually needed
unless the plugin cannot determine it by itself. The discovery sequence is detailed in the Global Configuration section of the docs.

If you build with maven on the machine where the docker daemon runs, you normally don't need this configuration. The plugin will connect to the unix socket /var/run/docker.sock which is the default URL of the docker daemon.

If the requirement is to run the image on a remote host, then you either specify the dockerHost option or the DOCKER_HOST environment variable. On the host, the docker daemon must be configured for remote access.

I hope this helps.

Title: Using Fabric8 to Deploy a Java Project

Body:
I am trying to use Fabric8 to build an image for my Java application. However, I am new and this could be a duplicate question.

I have docker installed and the fabric8 library added via maven.

Below is my initial setup for the fabric maven plugin.

<plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                        <configuration>
                            <dockerHost>/var/run/docker.sock</dockerHost>
                            <images>
                                <image>
                                    <alias>${project.artifactId}</alias>
                                    <name></name>
                                    <build>
                                        <from>java:8</from>
                                        <maintainer>${project.maintainer}</maintainer>
                                        <dockerFile>${project.basedir}/Dockerfile</dockerFile>
                                        <dockerHost>/var/run/docker.sock</dockerHost>
                                        <ports>
                                            <port>8080</port>
                                            <port>8081</port>
                                        </ports>
                                    </build>
                                </image>
                            </images>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Below is the error message I am getting.

Unable to parse configuration of mojo io.fabric8:docker-maven-plugin:0.30.0:build for parameter dockerHost: Cannot find 'dockerHost' in class io.fabric8.maven.docker.config.BuildImageConfiguration


问:
Inno Setup: Inherited OLE-Object properties not accessible?
I followed this question's accepted answer to query the machines network adapters. It finally worked but I still face a problem reading the values of these properties:

Win32_NetworkAdapterConfiguration.Caption

Win32_NetworkAdapterConfiguration.Description

Every time the code reaches this line where networkAdapter.Caption is called a runtime error is produced saying:

Runtime error (at 60:8952): Unknown method.

This is my code, adopted from the above mentioned Stack Overflow question:

Log('Querying WMI for network adapter data...');
query := 'SELECT IPEnabled, IPAddress, MACAddress, InterfaceIndex FROM Win32_NetworkAdapterConfiguration';
networkAdapters := wbemServices.ExecQuery(query);
if not VarIsNull(networkAdapters) then
begin
  for i := 0 to networkAdapters.Count - 1 do
  begin
    networkAdapter := networkAdapters.ItemIndex(i);

    if (not VarIsNull(networkAdapter.MACAddress)) and networkAdapter.IPEnabled and (not VarIsNull(networkAdapter.IPAddress)) then
    begin
      SetArrayLength(sysInfo.networkAdapters, GetArrayLength(sysInfo.networkAdapters) + 1);

      nicRec := sysInfo.networkAdapters[adapterIndex];

      { Adapter name }
      nicRec.name := defaultIfNull(networkAdapter.Caption, Format('Adapter %d', [i]));
      Log(Format('    NIC[%d] name........: %s', [adapterIndex, nicRec.name]));
      { Adapter index }
      nicRec.index := defaultIfNull(networkAdapter.InterfaceIndex, adapterIndex);
      Log(Format('    NIC[%d] index.......: %d', [adapterIndex, nicRec.index]));
      { Adapter MAC address }
      nicRec.macAddress := defaultIfNull(networkAdapter.MACAddress, '');
      Log(Format('    NIC[%d] MAC address.: %s', [adapterIndex, nicRec.macAddress]));
      { Adapter ip address(es) }
      nicRec.ipAddresses := TStringList.Create;
      if not VarIsNull(networkAdapter.IPAddress) then
      begin
        ips := networkAdapter.IPAddress;
        for j := 0 to GetArrayLength(ips) - 1 do
        begin
          nicRec.ipAddresses.Add(ips[j]);
          Log(Format('    NIC[%d] IPv4 address: %s', [adapterIndex, nicRec.ipAddresses.Strings[j]]));
        end;
      end;

      adapterIndex := adapterIndex + 1;
    end;
  end;
end;
```

After some reading in the Microsoft docs, I came across the description of these properties. It states, that the Win32_NetworkAdapterConfiguration class extends the CIM_Setting class. The properties Caption and Description are defined there. Is this an issue with the Inno Setup compiler (I am using the latest 6.0.2) or do I have to apply some sort of cast to may variant variable?

答:
Of course that inherited properties are accessible. Actually Inno Setup does not even care what class is that. It uses late binding. Property name resolution is delegated to the class itself.

But you are not working with Win32_NetworkAdapterConfiguration. IWbemServices.ExecQuery returns IEnumWbemClassObject, which in turn enumerates IWbemClassObject. And that contains results of your query. Your query does not ask for Caption and Description properties, so the result set naturally does not contain them.

Add the properties to the query:

Query := 'SELECT IPEnabled, IPAddress, MACAddress, InterfaceIndex, Caption, Description FROM Win32_NetworkAdapterConfiguration';
```

Body:
I followed this question's accepted answer to query the machines network adapters. It finally worked but I still face a problem reading the values of these properties:

Win32_NetworkAdapterConfiguration.Caption

Win32_NetworkAdapterConfiguration.Description

Every time the code reaches this line where networkAdapter.Caption is called a runtime error is produced saying:

Runtime error (at 60:8952): Unknown method.

This is my code, adopted from the above mentioned Stack Overflow question:

Log('Querying WMI for network adapter data...');
query := 'SELECT IPEnabled, IPAddress, MACAddress, InterfaceIndex FROM Win32_NetworkAdapterConfiguration';
networkAdapters := wbemServices.ExecQuery(query);
if not VarIsNull(networkAdapters) then
begin
  for i := 0 to networkAdapters.Count - 1 do
  begin
    networkAdapter := networkAdapters.ItemIndex(i);

    if (not VarIsNull(networkAdapter.MACAddress)) and networkAdapter.IPEnabled and (not VarIsNull(networkAdapter.IPAddress)) then
    begin
      SetArrayLength(sysInfo.networkAdapters, GetArrayLength(sysInfo.networkAdapters) + 1);

      nicRec := sysInfo.networkAdapters[adapterIndex];

      { Adapter name }
      nicRec.name := defaultIfNull(networkAdapter.Caption, Format('Adapter %d', [i]));
      Log(Format('    NIC[%d] name........: %s', [adapterIndex, nicRec.name]));
      { Adapter index }
      nicRec.index := defaultIfNull(networkAdapter.InterfaceIndex, adapterIndex);
      Log(Format('    NIC[%d] index.......: %d', [adapterIndex, nicRec.index]));
      { Adapter MAC address }
      nicRec.macAddress := defaultIfNull(networkAdapter.MACAddress, '');
      Log(Format('    NIC[%d] MAC address.: %s', [adapterIndex, nicRec.macAddress]));
      { Adapter ip address(es) }
      nicRec.ipAddresses := TStringList.Create;
      if not VarIsNull(networkAdapter.IPAddress) then
      begin
        ips := networkAdapter.IPAddress;
        for j := 0 to GetArrayLength(ips) - 1 do
        begin
          nicRec.ipAddresses.Add(ips[j]);
          Log(Format('    NIC[%d] IPv4 address: %s', [adapterIndex, nicRec.ipAddresses.Strings[j]]));
        end;
      end;

      adapterIndex := adapterIndex + 1;
    end;
  end;
end;

After some reading in the Microsoft docs, I came across the description of these properties. It states, that the Win32_NetworkAdapterConfiguration class extends the CIM_Setting class. The properties Caption and Description are defined there. Is this an issue with the Inno Setup compiler (I am using the latest 6.0.2) or do I have to apply some sort of cast to may variant variable?


问:
Calling preload method of Angular PreloadingStrategy by hand
assume, we have 2 modules named(Careworker/Client). In the Client module, we have one module called(Client-Profile). In this way, SelectiveStrategyService does not load modules will only store the name of that module. that's why it can not access the name of (client-profile-module).

In the following service (SelectiveStrategyService ), we will keep track of these routes, but instead of calling the load function immediately, we will store it in a dictionary so we can access it later

```<code>import { Injectable } from '@angular/core';
import { Route, PreloadingStrategy } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Injectable()
export class SelectiveStrategyService implements PreloadingStrategy {
  routes: { [name: string]: { route: Route; load: Function } } = {};

  preload(route: Route, load: Function): Observable<any> {

    if (route.data && route.data['preload']) {
      // load();
      this.routes[route.data.name] = {
        route,
        load
      };
    }

    return Observable.of(null);
  }

  preLoadRoute(name: string) {
    const route = this.routes[name];
    if (route) {
      route.load();
    }
  }

}
</code>```

app.routing.module.ts :

```<code>const routes: Routes = [
  {
    path: "careworker", loadChildren: "app/careworker/careworker.module#CareworkerModule",
    data: { preload: false, name: "careworker-module" }
  },
  {
    path: "client", loadChildren: "app/client/client.module#ClientModule",
    data: { preload: true, name: "client-module" }
  }
];
</code>```

client.routing.module.ts :

```<code>const routes: Routes = [
  {
    path: "index", component: ClientIndexComponent
  },
  {
    path: "profile",
    loadChildren: "app/client/client-profile/client-profile.module#ClientProfileModule",
    data: { preload: true, name: "client-profile-module" }
  }
];
</code>```

SelectiveStrategyService are just services, so they can be injected into our components like any other service:

```<code>constructor(private loader: SelectiveStrategyService) {}

</code>```

Update :

in the routes Dictionary, there must be 3 keys (careworker-module,client-module , client-profile-module) , but just there are 2 keys(careworker-module,client-module). that's why I can not call the Client Profile module by hand like:

```<code>ngOnInit() {
  this.loader.preLoadRoute('client-profile-module');
}
</code>```

needless to say I can call preLoadRoute ('client-module;) so easily and it works

```<code>  this.loader.preLoadRoute('client-module');
</code>```

答:
You need to implement a custom preloading strategy of your own. Create a class that implements PreloadingStrategy interface and add your logic there. You can read the data object from route do some logic based on that.

```<code>export class AppPreloadingStrategy implements PreloadingStrategy {
    preload(route: Route, load: Function): Observable<any> {
        const loadRoute = (delay) => delay
            ? timer(150).pipe(flatMap(_ => load()))
            : load();
        return route.data && route.data.preload
            ? loadRoute(route.data.delay)
            : of(null);
      }
}
</code>```

then use this new strategy in your code like

```<code>RouterModule.forRoot(routes, {
   preloadingStrategy: AppPreloadingStrategy
})
</code>```

If a load of module happens there is no point to undo. You can manually invoke the preloading of routes that haven't been loaded yet.

Body:
assume, we have 2 modules named(Careworker/Client). In the Client module, we have one module called(Client-Profile). In this way, SelectiveStrategyService does not load modules will only store the name of that module. that's why it can not access the name of (client-profile-module).

In the following service (SelectiveStrategyService ), we will keep track of these routes, but instead of calling the load function immediately, we will store it in a dictionary so we can access it later

import { Injectable } from '@angular/core';
import { Route, PreloadingStrategy } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Injectable()
export class SelectiveStrategyService implements PreloadingStrategy {
  routes: { [name: string]: { route: Route; load: Function } } = {};

  preload(route: Route, load: Function): Observable<any> {

    if (route.data && route.data['preload']) {
      // load();
      this.routes[route.data.name] = {
        route,
        load
      };
    }

    return Observable.of(null);
  }

  preLoadRoute(name: string) {
    const route = this.routes[name];
    if (route) {
      route.load();
    }
  }

}

app.routing.module.ts :

const routes: Routes = [
  {
    path: "careworker", loadChildren: "app/careworker/careworker.module#CareworkerModule",
    data: { preload: false, name: "careworker-module" }
  },
  {
    path: "client", loadChildren: "app/client/client.module#ClientModule",
    data: { preload: true, name: "client-module" }
  }
];

client.routing.module.ts :

const routes: Routes = [
  {
    path: "index", component: ClientIndexComponent
  },
  {
    path: "profile",
    loadChildren: "app/client/client-profile/client-profile.module#ClientProfileModule",
    data: { preload: true, name: "client-profile-module" }
  }
];

SelectiveStrategyService are just services, so they can be injected into our components like any other service:

constructor(private loader: SelectiveStrategyService) {}

Update :

in the routes Dictionary, there must be 3 keys (careworker-module,client-module , client-profile-module) , but just there are 2 keys(careworker-module,client-module). that's why I can not call the Client Profile module by hand like:

ngOnInit() {
  this.loader.preLoadRoute('client-profile-module');
}

needless to say I can call preLoadRoute ('client-module;) so easily and it works

  this.loader.preLoadRoute('client-module');

Body:
You need to implement a custom preloading strategy of your own. Create a class that implements PreloadingStrategy interface and add your logic there. You can read the data object from route do some logic based on that.

export class AppPreloadingStrategy implements PreloadingStrategy {
    preload(route: Route, load: Function): Observable<any> {
        const loadRoute = (delay) => delay
            ? timer(150).pipe(flatMap(_ => load()))
            : load();
        return route.data && route.data.preload
            ? loadRoute(route.data.delay)
            : of(null);
      }
}

then use this new strategy in your code like

RouterModule.forRoot(routes, {
   preloadingStrategy: AppPreloadingStrategy
})

If a load of module happens there is no point to undo. You can manually invoke the preloading of routes that haven't been loaded yet.


问:
Filter state that is set from onClick as data- in react
Two main issues.
(1) onClick needs to update two items in my state
(2) I need to filter state #2 to count the number of times a string appears and render it if it equals the length of state#1

More Detail:

I am mapping through my objects and rendering a button for each. I need the onClick to setState of two different attributes so i pass value={item.item} to update state selectedItems , and data-matches={item.matches} to update state of matchesList.

-- note that item.item is a string and item.matches is an array of strings.

When I call onClick to update the state, the value works fine, but the data-matches creates a weird object which i cant iterate over and this is why thats a problem...

I need to map through the data-matches state and count each instance of a string, if the count of that particular string is equal to the length of selectedItems state, then I need to render that.

If this is confusing to you, it's because I am completely lost and new to this. Maybe its worth mentioning that my props are coming from Redux..

Example of some objects for reference

```<code>{
'item': 'apple',
'matches': ['beef', 'bacon', 'cheese', 'carrot'],
},
{
'item': 'carrot',
'matches': ['apple', 'bacon', 'goat'],
},
</code>```

```<code>export class Items extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedItems: [],
      firstStep: true,
      matchesList: []
    };
    this.selectItems = this.selectItems.bind(this);
    this.filterMatches = this.filterMatches.bind(this);
  }
</code>```

```<code>selectItems(event) {
    this.setState({
      selectedItems: [...this.state.selectedItems, event.target.value],
      firstStep: false,
      matchesList: [...this.state.matchesList, event.target.dataset.matches]
    });
  }
</code>```

Below, in the col 'All", I am mapping through my state selectedItems which is an array, so I can grab the actual object from props which is the same name. I then map over the matches array of that object, and grab the actual object that has the same name as the matches...

in the col 'Cross Referenced", I am mapping over the state updated from the onClick. This is where I need to filter.. I'll show you my attempt at that after this code block.

```<code>render() {
    return (
      <Fragment>
<div className="col">
              <div className="row">
                <div className="col-5">
                  <h1>All</h1>
                  {this.state.selectedItems.map(selected =>
                    this.props.items.map(item =>
                      item.item == selected
                        ? item.matches.map(match =>
                            this.props.items.map(item =>
                              item.item == match ? (
                                <div>
                                  <p>{item.item}</p>

                                  <button
                                    key={item.item}
                                    value={item.item}
                                    data-matches={item.matches}
                                    onClick={this.selectItems}
                                  >
                                    Select
                                  </button>
                                </div>
                              ) : null
                            )
                          )
                        : null
                    )
                  )}
                </div>
                <div className="col-5">
                  <h1>Cross Referenced</h1>
                  {this.state.matchesList.map(matches => (
                    <p>{matches}</p>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </Fragment>
    );
  }
}
</code>```

My attempt at filtering, even though the matchesList is not right.

```<code>  filterMatches(matchesList, selectedItems) {
    let arr1 = matchesList;
    let arr2 = selectedItems;

    let obj = arr1.reduce((op, inp) => {
      let key = inp;
      op[key] = op[key] || 0;
      op[key]++;
      return op;
    }, {});

    let final = Object.keys(obj).filter(key => {
      return obj[key] === arr2.length;
    });
    return final;
  }
</code>```

in the render

```<code><div className="col-5">
  <h1>cross referenced</h1>{this.state.matchesList.filter(this.filterMatches(this.state.matchesList, this.state.selectedItems)).map(matches => (
  <p>{matches}</p>
  ))}
  </div>
</div>
</code>```

答:
I tried out the data-matches thing, and it looks to me like event.target.dataset.matches was coming out to be a string (Not an array of strings, one big CSV string). Try doing it the following way:

class YourComponent extends React.Component {

  state = {...};

  selectItems = (item, matches) => {
    this.setState({
      selectedItems: [...this.state.selectedItems, item],
      firstStep: false,
      matchesList: [...this.state.matchesList, ...matches]
    });
  }

  render() {
   return (
      {...}
      {this.props.items.map(item => (
        <button
          key={item.item}
          value={item.item}
          onClick={() => this.selectItems(item.item, item.matches)}
        >
          Select
        </button>
      ))}
      {...}
    );
  }

}```
</div>
</div>
</p>

<p>Actually I think I see what your issue is, the filter is working fine and it's already giving you your array of <code>["bacon"]</code>. Try getting rid of the outer filter, I don't see a point to it being there.</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-js lang-js prettyprint-override"><code>const YourComponent = props => (
  {...}
  {this.filterMatches(this.state.matchesList, this.state.selectedItems).map(matches => (
   <p>{matches}</p>
  ))}
  {...}
);</code>```

Body:
Two main issues.
(1) onClick needs to update two items in my state
(2) I need to filter state #2 to count the number of times a string appears and render it if it equals the length of state#1

More Detail:

I am mapping through my objects and rendering a button for each. I need the onClick to setState of two different attributes so i pass value={item.item} to update state selectedItems , and data-matches={item.matches} to update state of matchesList.

-- note that item.item is a string and item.matches is an array of strings.

When I call onClick to update the state, the value works fine, but the data-matches creates a weird object which i cant iterate over and this is why thats a problem...

I need to map through the data-matches state and count each instance of a string, if the count of that particular string is equal to the length of selectedItems state, then I need to render that.

If this is confusing to you, it's because I am completely lost and new to this. Maybe its worth mentioning that my props are coming from Redux..

Example of some objects for reference

{
'item': 'apple',
'matches': ['beef', 'bacon', 'cheese', 'carrot'],
},
{
'item': 'carrot',
'matches': ['apple', 'bacon', 'goat'],
},

export class Items extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedItems: [],
      firstStep: true,
      matchesList: []
    };
    this.selectItems = this.selectItems.bind(this);
    this.filterMatches = this.filterMatches.bind(this);
  }

selectItems(event) {
    this.setState({
      selectedItems: [...this.state.selectedItems, event.target.value],
      firstStep: false,
      matchesList: [...this.state.matchesList, event.target.dataset.matches]
    });
  }

Below, in the col 'All", I am mapping through my state selectedItems which is an array, so I can grab the actual object from props which is the same name. I then map over the matches array of that object, and grab the actual object that has the same name as the matches...

in the col 'Cross Referenced", I am mapping over the state updated from the onClick. This is where I need to filter.. I'll show you my attempt at that after this code block.

render() {
    return (
      <Fragment>

All

                  {this.state.selectedItems.map(selected =>
                    this.props.items.map(item =>
                      item.item == selected
                        ? item.matches.map(match =>
                            this.props.items.map(item =>
                              item.item == match ? (

{item.item}

                                  <button
                                    key={item.item}
                                    value={item.item}
                                    data-matches={item.matches}
                                    onClick={this.selectItems}
                                  >
                                    Select
                                  </button>

                              ) : null
                            )
                          )
                        : null
                    )
                  )}

Cross Referenced

                  {this.state.matchesList.map(matches => (

{matches}

                  ))}

          )}

      </Fragment>
    );
  }
}

My attempt at filtering, even though the matchesList is not right.

  filterMatches(matchesList, selectedItems) {
    let arr1 = matchesList;
    let arr2 = selectedItems;

    let obj = arr1.reduce((op, inp) => {
      let key = inp;
      op[key] = op[key] || 0;
      op[key]++;
      return op;
    }, {});

    let final = Object.keys(obj).filter(key => {
      return obj[key] === arr2.length;
    });
    return final;
  }

in the render

cross referenced
{this.state.matchesList.filter(this.filterMatches(this.state.matchesList, this.state.selectedItems)).map(matches => (

{matches}

  ))}

Body:
I tried out the data-matches thing, and it looks to me like event.target.dataset.matches was coming out to be a string (Not an array of strings, one big CSV string). Try doing it the following way:

class YourComponent extends React.Component {

  state = {...};

  selectItems = (item, matches) => {
    this.setState({
      selectedItems: [...this.state.selectedItems, item],
      firstStep: false,
      matchesList: [...this.state.matchesList, ...matches]
    });
  }

  render() {
   return (
      {...}
      {this.props.items.map(item => (
        <button
          key={item.item}
          value={item.item}
          onClick={() => this.selectItems(item.item, item.matches)}
        >
          Select
        </button>
      ))}
      {...}
    );
  }

}

Actually I think I see what your issue is, the filter is working fine and it's already giving you your array of ["bacon"]. Try getting rid of the outer filter, I don't see a point to it being there.

const YourComponent = props => (
  {...}
  {this.filterMatches(this.state.matchesList, this.state.selectedItems).map(matches => (
   <p>{matches}</p>
  ))}
  {...}
);


问:
.net library does not pick keys from app.config
I am working on a error reporting library in c#, and its a static class.
When I am running this library from other applications by adding a reference. It does not pick the AppSetting Keys from app.config.

In that case I need to add the keys to all main applications to make it working.

Are their any other solution to sortout this problem?

Thanks and Regards

答:
As an alternative to the app.config, if your library needs it's own configuration, or if you just don't want to use app.config, you can use a Settings file instead of rolling your own. Here is an overview, this is a bit old, but works the same way.

http://msdn.microsoft.com/en-us/library/aa730869.aspx


问:
Edit and save other jar while running
Currently I am trying to update an old project.
The problem is, that in one of my sources (bungeecord) they have changed two fileds (see enum "protocol") from public final to final modifier. To make the project work again I need to access these two fields.

As a reason of this I try to "inject" the project. This works great, so the modifier changes but I am currently not able to save it to the jar file. But this is necessary.

The process of saving works perfectly for the "userconnection" (see enum below). In this case I edit a class modifier.

If you need any more Information please let me know.

When the "injection" (enum: protocol) is done and I check the modifier type of these fileds I see that there have been some changes.
But when I restart the system and check the filed modifiers again before the "injection" they are as there were no changes.

```<code>public static int inject(InjectionType type) {
    try{

        System.out.println("Starting  injection.");
        System.out.println(type.getInfo());

        ClassPool cp = ClassPool.getDefault();
        CtClass clazz = cp.getCtClass(type.getClazz().getName());

        switch (type) {
            case USERCONNECTION:
                int modifier = UserConnection.class.getModifiers();
                if (!Modifier.isFinal(modifier) && Modifier.isPublic(modifier)) {
                    return -1;
                }
                clazz.setModifiers(Modifier.PUBLIC);
                break;
            case PROTOCOL:
                CtField field = clazz.getField("TO_CLIENT");
                field.setModifiers(Modifier.PUBLIC + Modifier.FINAL);
                field = clazz.getField("TO_SERVER");
                field.setModifiers(Modifier.PUBLIC + Modifier.FINAL);
                break;
            default:
                return -1;  //no data
        }

        ByteArrayOutputStream bout;
        DataOutputStream out = new DataOutputStream(bout = new ByteArrayOutputStream());
        clazz.getClassFile().write(out);

        InputStream[] streams = { new ByteArrayInputStream(bout.toByteArray()) };
        File bungee_file = new File(BungeeCord.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        updateZipFile(bungee_file, type, streams);
        return 1;
    }catch (Exception e){
        e.printStackTrace();
    }
    return 0;
}

private static void updateZipFile(File zipFile, InjectionType type, InputStream[] ins) throws IOException {
    File tempFile = File.createTempFile(zipFile.getName(), null);
    if (!tempFile.delete()) {
        System.out.println("Warn: Cant delete temp file.");
    }
    if (tempFile.exists()) {
        System.out.println("Warn: Temp target file alredy exist!");
    }
    if (!zipFile.exists()) {
        throw new RuntimeException("Could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath() + " (Src. not found!)");
    }
    int renameOk = zipFile.renameTo(tempFile) ? 1 : 0;
    if (renameOk == 0) {
        tempFile = new File(zipFile.toString() + ".copy");
        com.google.common.io.Files.copy(zipFile, tempFile);
        renameOk = 2;
        if (zipFile.delete()) {
            System.out.println("Warn: Src file cant delete.");
            renameOk = -1;
        }
    }
    if (renameOk == 0) {
        throw new RuntimeException("Could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath() + " (Directory read only? (Temp:[R:" + (tempFile.canRead() ? 1 : 0) + ";W:" + (tempFile.canWrite() ? 1 : 0) + ",D:" + (tempFile.canExecute() ? 1 : 0) + "],Src:[R:" + (zipFile.canRead() ? 1 : 0) + ";W:" + (zipFile.canWrite() ? 1 : 0) + ",D:" + (zipFile.canExecute() ? 1 : 0) + "]))");
    }
    if (renameOk != 1) {
        System.out.println("Warn: Cant create temp file. Use .copy file");
    }
    byte[] buf = new byte[Configuration.getLoadingBufferSize()];
    System.out.println("Buffer size: " + buf.length);
    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String path_name = entry.getName().replaceAll("/", "\\.");
        boolean notReplace = true;
        for (String f : type.getNames()) {
            if (f.equals(path_name)) {
                notReplace = false;
                break;
            }
        }
        if (notReplace) {
            out.putNextEntry(new ZipEntry(entry.getName()));
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    zin.close();
    for (int i = 0; i < type.getNames().length; i++) {
        InputStream in = ins[i];
        int index = type.getNames()[i].lastIndexOf('.');
        out.putNextEntry(new ZipEntry(type.getNames()[i].substring(0, index).replaceAll("\\.", "/") + type.getNames()[i].substring(index)));
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
    out.close();
    tempFile.delete();
    if (renameOk == -1) {
        System.exit(-1);
    }
}
}

@Getter
public enum InjectionType {
    USERCONNECTION(UserConnection.class, new String[] {"net.md_5.bungee.UserConnection.class"}, "Set modifiers for class UserConnection.class to \"public\""),
    PROTOCOL(Protocol.class, new String[] {"net.md_5.bungee.protocol.Protocol"}, "Set modifiers for class Protocol.class to \"public\"");

    private Class<?> clazz;
    private String[] names;
    private String info;

    InjectionType (Class<?> clazz, String[] names, String info) {
        this.clazz = clazz;
        this.names = names;
        this.info = info;
    }
}
</code>```

答:
When the "injection" (enum: protocol) is done and I check the modifier type of these fileds I see that there have been some changes. But when I restart the system and check the filed modifiers again before the "injection" they are as there were no changes.

What you're trying to do is permanently modify field's access in a jar file using Java reflection. This cannot work as reflection modifies things in runtime only:

Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at runtime.

Excerpt taken from this page.

What you need to do is physically edit the jar itself if you want the changes to be permanent. I know you said that you are not able to do that, but as far as I know that is the only possible way. The file itself has to be physically changed if you want the changes to stick after the application has terminated and be applied before the program has started.

Read the official documentation about Java reflection here.

However I don't really understand why is it important that the changes persists after you've restarted the system. The reason you need to change the access is so you can access and perhaps manipulate the class in some way during runtime. What you are doing is correct, one of the more important apsects of reflection is to manipulate data without actually having to modify the physical files themselves and end up using custom distributions.

EDIT: Read this question, it's comments and the accepted answer. They pretty much say the same thing that you can't edit a jar file that is currently being used by JVM, it's locked in a read-only state.

Title: Edit and save other jar while running

Body:
Currently I am trying to update an old project.
The problem is, that in one of my sources (bungeecord) they have changed two fileds (see enum "protocol") from public final to final modifier. To make the project work again I need to access these two fields.

As a reason of this I try to "inject" the project. This works great, so the modifier changes but I am currently not able to save it to the jar file. But this is necessary.

The process of saving works perfectly for the "userconnection" (see enum below). In this case I edit a class modifier.

If you need any more Information please let me know.

When the "injection" (enum: protocol) is done and I check the modifier type of these fileds I see that there have been some changes.
But when I restart the system and check the filed modifiers again before the "injection" they are as there were no changes.

public static int inject(InjectionType type) {
    try{

        System.out.println("Starting  injection.");
        System.out.println(type.getInfo());

        ClassPool cp = ClassPool.getDefault();
        CtClass clazz = cp.getCtClass(type.getClazz().getName());

        switch (type) {
            case USERCONNECTION:
                int modifier = UserConnection.class.getModifiers();
                if (!Modifier.isFinal(modifier) && Modifier.isPublic(modifier)) {
                    return -1;
                }
                clazz.setModifiers(Modifier.PUBLIC);
                break;
            case PROTOCOL:
                CtField field = clazz.getField("TO_CLIENT");
                field.setModifiers(Modifier.PUBLIC + Modifier.FINAL);
                field = clazz.getField("TO_SERVER");
                field.setModifiers(Modifier.PUBLIC + Modifier.FINAL);
                break;
            default:
                return -1;  //no data
        }

        ByteArrayOutputStream bout;
        DataOutputStream out = new DataOutputStream(bout = new ByteArrayOutputStream());
        clazz.getClassFile().write(out);

        InputStream[] streams = { new ByteArrayInputStream(bout.toByteArray()) };
        File bungee_file = new File(BungeeCord.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        updateZipFile(bungee_file, type, streams);
        return 1;
    }catch (Exception e){
        e.printStackTrace();
    }
    return 0;
}

private static void updateZipFile(File zipFile, InjectionType type, InputStream[] ins) throws IOException {
    File tempFile = File.createTempFile(zipFile.getName(), null);
    if (!tempFile.delete()) {
        System.out.println("Warn: Cant delete temp file.");
    }
    if (tempFile.exists()) {
        System.out.println("Warn: Temp target file alredy exist!");
    }
    if (!zipFile.exists()) {
        throw new RuntimeException("Could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath() + " (Src. not found!)");
    }
    int renameOk = zipFile.renameTo(tempFile) ? 1 : 0;
    if (renameOk == 0) {
        tempFile = new File(zipFile.toString() + ".copy");
        com.google.common.io.Files.copy(zipFile, tempFile);
        renameOk = 2;
        if (zipFile.delete()) {
            System.out.println("Warn: Src file cant delete.");
            renameOk = -1;
        }
    }
    if (renameOk == 0) {
        throw new RuntimeException("Could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath() + " (Directory read only? (Temp:[R:" + (tempFile.canRead() ? 1 : 0) + ";W:" + (tempFile.canWrite() ? 1 : 0) + ",D:" + (tempFile.canExecute() ? 1 : 0) + "],Src:[R:" + (zipFile.canRead() ? 1 : 0) + ";W:" + (zipFile.canWrite() ? 1 : 0) + ",D:" + (zipFile.canExecute() ? 1 : 0) + "]))");
    }
    if (renameOk != 1) {
        System.out.println("Warn: Cant create temp file. Use .copy file");
    }
    byte[] buf = new byte[Configuration.getLoadingBufferSize()];
    System.out.println("Buffer size: " + buf.length);
    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String path_name = entry.getName().replaceAll("/", "\\.");
        boolean notReplace = true;
        for (String f : type.getNames()) {
            if (f.equals(path_name)) {
                notReplace = false;
                break;
            }
        }
        if (notReplace) {
            out.putNextEntry(new ZipEntry(entry.getName()));
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    zin.close();
    for (int i = 0; i < type.getNames().length; i++) {
        InputStream in = ins[i];
        int index = type.getNames()[i].lastIndexOf('.');
        out.putNextEntry(new ZipEntry(type.getNames()[i].substring(0, index).replaceAll("\\.", "/") + type.getNames()[i].substring(index)));
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
    out.close();
    tempFile.delete();
    if (renameOk == -1) {
        System.exit(-1);
    }
}
}

@Getter
public enum InjectionType {
    USERCONNECTION(UserConnection.class, new String[] {"net.md_5.bungee.UserConnection.class"}, "Set modifiers for class UserConnection.class to \"public\""),
    PROTOCOL(Protocol.class, new String[] {"net.md_5.bungee.protocol.Protocol"}, "Set modifiers for class Protocol.class to \"public\"");

    private Class<?> clazz;
    private String[] names;
    private String info;

    InjectionType (Class<?> clazz, String[] names, String info) {
        this.clazz = clazz;
        this.names = names;
        this.info = info;
    }
}


问:
Offline Promise Handling in Angularfire2
As per my understanding, Angularfire2 returns a Promise < void > whenever a query runs successfully(except fetch when it returns data).

Functionality:

I have a application where when a item is saved a function is called inside which if the set query is run successfully(i.e it receives a Promise< void >) it navigates to the previous page.
It works perfectly when app is online but the app also needs to work offline. I have enabled persistence and configured service workers for the same

Issue

But when offline the code after the query returns a Promise is not called.So what should be the expected logic or behaviour during offline.

```<code>                this._itemService.setItem(item).then(()=>{
                    const message = item.name + saveMessage;
                    this.snackBar.open(message," ",{duration:2000});
                    this.location.back();

                }
</code>```

答:
The code after the promise isn't called cause you get an Error, as you cann't access the source when you are offline.
Add an ErrorHandling after the Promise, as described here:
Using success/error/finally/catch with Promises in AngularJS

In the ErrorHandling you can add the behaviour of the app, when it is offline.

```<code>this._itemService.setItem(item).then(()=>{
    const message = item.name + saveMessage;
    this.snackBar.open(message," ",{duration:2000});
    this.location.back();
).catch((e) => {
    //Do what you want when you don't get the Promise
    this.location.back();
});
</code>```

Body:
As per my understanding, Angularfire2 returns a Promise < void > whenever a query runs successfully(except fetch when it returns data).

Functionality:

I have a application where when a item is saved a function is called inside which if the set query is run successfully(i.e it receives a Promise< void >) it navigates to the previous page.
It works perfectly when app is online but the app also needs to work offline. I have enabled persistence and configured service workers for the same

Issue

But when offline the code after the query returns a Promise is not called.So what should be the expected logic or behaviour during offline.

                this._itemService.setItem(item).then(()=>{
                    const message = item.name + saveMessage;
                    this.snackBar.open(message," ",{duration:2000});
                    this.location.back();

                }

Body:
The code after the promise isn't called cause you get an Error, as you cann't access the source when you are offline.
Add an ErrorHandling after the Promise, as described here:
Using success/error/finally/catch with Promises in AngularJS

In the ErrorHandling you can add the behaviour of the app, when it is offline.

this._itemService.setItem(item).then(()=>{
    const message = item.name + saveMessage;
    this.snackBar.open(message," ",{duration:2000});
    this.location.back();
).catch((e) => {
    //Do what you want when you don't get the Promise
    this.location.back();
});


问:
How can I use atexit() function to cleanup function call?
I am using atexit() function inside my code to cleanup function call, but it's not working.

```<code>#include<stdio.h>
void ftn(void)
{
    printf(" Function called --> exit\n");
    return;
}
int main(void)
{
    int x = 0;
    atexit(ftn);
    for(;x<0xffffff;x++);
    _exit(0);
}
</code>```

Any help regarding this will be appreciated.

答:
Quoting the man page for _exit()

The _Exit() and _exit() functions shall not call functions registered with atexit() nor any registered signal handlers. Whether open streams are flushed or closed, or temporary files are removed is implementation-defined. Finally, the calling process is terminated with the consequences described below.

So what you're seeing is expected behavior.

That said, you should include unistd.h (for _exit())and stdlib.h (for atexit()) headers for including the prototype.

If you want the functions registered by atexit() to be invoked, you should call exit() instead.

The exit() function shall first call all functions registered by atexit(), in the reverse order of their registration, [....]

Body:
I am using atexit() function inside my code to cleanup function call, but it's not working.

#include<stdio.h>
void ftn(void)
{
    printf(" Function called --> exit\n");
    return;
}
int main(void)
{
    int x = 0;
    atexit(ftn);
    for(;x<0xffffff;x++);
    _exit(0);
}

Any help regarding this will be appreciated.


问:
How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
  File "/usr/local/bin/wok", line 4, in
    Engine()
  File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 104, in init
    self.load_pages()
  File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 238, in load_pages
    p = Page.from_file(os.path.join(root, f), self.options, self, renderer)
  File "/usr/local/lib/python2.7/site-packages/wok/page.py", line 111, in from_file
    page.meta['content'] = page.renderer.render(page.original)
  File "/usr/local/lib/python2.7/site-packages/wok/renderers.py", line 46, in render
    return markdown(plain, Markdown.plugins)
  File "/usr/local/lib/python2.7/site-packages/markdown/init.py", line 419, in markdown
    return md.convert(text)
  File "/usr/local/lib/python2.7/site-packages/markdown/init.py", line 281, in convert
    source = unicode(source)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 1: ordinal not in range(128). -- Note: Markdown only accepts unicode input!
```

How to fix it?

In some other python-based static blog apps, Chinese post can be published successfully.
Such as this app: http://github.com/vrypan/bucket3. In my site http://bc3.brite.biz/, Chinese post can be published successfully.

答:
Got a same error and this solved my error. Thanks!
python 2 and python 3 differing in unicode handling is making pickled files quite incompatible to load. So Use python pickle's encoding argument. Link below helped me solve the similar problem when I was trying to open pickled data from my python 3.7, while my file was saved originally in python 2.x version.
https://blog.modest-destiny.com/posts/python-2-and-3-compatible-pickle-save-and-load/
I copy the load_pickle function in my script and called the load_pickle(pickle_file) while loading my input_data like this:

```<code>input_data = load_pickle("my_dataset.pkl")
</code>```

The load_pickle function is here:

```<code>def load_pickle(pickle_file):
    try:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f)
    except UnicodeDecodeError as e:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f, encoding='latin1')
    except Exception as e:
        print('Unable to load data ', pickle_file, ':', e)
        raise
    return pickle_data
</code>```

Body:
as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
  File "/usr/local/bin/wok", line 4, in
    Engine()
  File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 104, in init
    self.load_pages()
  File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 238, in load_pages
    p = Page.from_file(os.path.join(root, f), self.options, self, renderer)
  File "/usr/local/lib/python2.7/site-packages/wok/page.py", line 111, in from_file
    page.meta['content'] = page.renderer.render(page.original)
  File "/usr/local/lib/python2.7/site-packages/wok/renderers.py", line 46, in render
    return markdown(plain, Markdown.plugins)
  File "/usr/local/lib/python2.7/site-packages/markdown/init.py", line 419, in markdown
    return md.convert(text)
  File "/usr/local/lib/python2.7/site-packages/markdown/init.py", line 281, in convert
    source = unicode(source)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 1: ordinal not in range(128). -- Note: Markdown only accepts unicode input!

How to fix it?

In some other python-based static blog apps, Chinese post can be published successfully.
Such as this app: http://github.com/vrypan/bucket3. In my site http://bc3.brite.biz/, Chinese post can be published successfully.

Body:
Got a same error and this solved my error. Thanks!
python 2 and python 3 differing in unicode handling is making pickled files quite incompatible to load. So Use python pickle's encoding argument. Link below helped me solve the similar problem when I was trying to open pickled data from my python 3.7, while my file was saved originally in python 2.x version.
https://blog.modest-destiny.com/posts/python-2-and-3-compatible-pickle-save-and-load/
I copy the load_pickle function in my script and called the load_pickle(pickle_file) while loading my input_data like this:

input_data = load_pickle("my_dataset.pkl")

The load_pickle function is here:

def load_pickle(pickle_file):
    try:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f)
    except UnicodeDecodeError as e:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f, encoding='latin1')
    except Exception as e:
        print('Unable to load data ', pickle_file, ':', e)
        raise
    return pickle_data


问:
What's the VERSION column in BATCH_JOB_INSTANCE of Spring batch meta tables?
I implemented some codes with spring batch.
After my batch worked, data have been stored in metadata tables.

I figured out that BATCH_JOB_INSTANCE and BATCH_JOB_EXECUTION have VERSION column and their version columns differ.

Could you tell me what version mean?

答: Spring Batch employs an optimistic locking strategy when dealing with database updates, and this is where the version column comes to play. This is explained in details in the Appendix A: Meta-Data Schema.


问:
How to generate Azure Active Directory (AAD) authentication token for Graph API without interactive login screen for console/native application?
How to generate Azure Active Directory (AAD) authentication token for Graph API without interactive login screen for console/native application?

Details:
I am using Graph API to read emails with Azure Active Directory (AAD) with ‘’Delegated’’ permissions.

”Application” permission allows a user to read other mailboxes and there is no admin consent for this approach due to security concerns, so I am using ‘’Delegated’’ permissions.

My console/native application is registered to AAD.

Since AAD generates OAuth Authentication token for a specific account using:
1.  Client ID
2.  Tenant ID
3.  Client Secret (Key/password for the application)
4.  Login credentials of a specific account.

I can generate a token using an interactive login screen.

However, I want a mechanism where I can generate AAD token for Graph API (resource) without an interactive login screen within code using C# or.NET

答:
Its seems you are trying to get your token without prompting the sign in page.

Yeah, you can do it using client_credentials grant authentication flow within C#.Net

See the following code snippet:

Access Token Class:

 public  class AccessTokenClass
        {
            public string access_token { get; set; }
            public string token_type { get; set; }
            public long expires_in { get; set; }
        }
```

<p><strong><em>Token Request Method:</em></strong></p>

<pre class="lang-cs prettyprint-override"><code>private async Task<string> GetYourTokenWithClientCredentialsFlow()
        {
            string tokenUrl = $"https://login.microsoftonline.com/YourTenant/oauth2/token";
            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "client_credentials",
                ["client_id"] = "5f14dea0-5cd---Your_Client_Id----8950-4f646829f870",
                ["client_secret"] = "031Fnwih---Your_Client_Secret----Fx+Ase3V65lpWQ=",
                ["resource"] = "https://graph.microsoft.com" // https://management.azure.com/ Or Any Resource You Want
            });

            dynamic json;
            dynamic token;
            HttpClient client = new HttpClient();

            var tokenResponse = await client.SendAsync(tokenRequest);

            json = await tokenResponse.Content.ReadAsStringAsync();
            token = JsonConvert.DeserializeObject<AccessTokenClass>(json);
            Console.WriteLine("Your Access Token {0}",token.access_token);
            return token;
        }
</code>```

Generated Token Response:

Once you have set all of your required credentials you would get the token in response. See the screen shot below:

Note: This authentication flow would generate token for you without interactive login screen. If you still have any query feel free to share in comment. Thanks and happy coding!

Update:

To assign dedicated permission for reading mail. Follow the below steps:

Azure active directory

App registration

Select your app

API permissions

Add a permission

Microsoft graph

Delegated permissions

Mail

Mail.Read (read user mail)

Add permission

Grant admin consent

See the screen shot:

Body:
Its seems you are trying to get your token without prompting the sign in page.

Yeah, you can do it using client_credentials grant authentication flow within C#.Net

See the following code snippet:

Access Token Class:

 public  class AccessTokenClass
        {
            public string access_token { get; set; }
            public string token_type { get; set; }
            public long expires_in { get; set; }
        }

Token Request Method:

private async Task<string> GetYourTokenWithClientCredentialsFlow()
        {
            string tokenUrl = $"https://login.microsoftonline.com/YourTenant/oauth2/token";
            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "client_credentials",
                ["client_id"] = "5f14dea0-5cd---Your_Client_Id----8950-4f646829f870",
                ["client_secret"] = "031Fnwih---Your_Client_Secret----Fx+Ase3V65lpWQ=",
                ["resource"] = "https://graph.microsoft.com" // https://management.azure.com/ Or Any Resource You Want
            });

            dynamic json;
            dynamic token;
            HttpClient client = new HttpClient();

            var tokenResponse = await client.SendAsync(tokenRequest);

            json = await tokenResponse.Content.ReadAsStringAsync();
            token = JsonConvert.DeserializeObject<AccessTokenClass>(json);
            Console.WriteLine("Your Access Token {0}",token.access_token);
            return token;
        }

Generated Token Response:

Once you have set all of your required credentials you would get the token in response. See the screen shot below:

Note: This authentication flow would generate token for you without interactive login screen. If you still have any query feel free to share in comment. Thanks and happy coding!

Update:

To assign dedicated permission for reading mail. Follow the below steps:

Azure active directory

App registration

Select your app

API permissions

Add a permission

Microsoft graph

Delegated permissions

Mail

Mail.Read (read user mail)

Add permission

Grant admin consent

See the screen shot:


问:
Jquery Fade in fade out, with pause or delay
If have the following code but i cant get a pause AFTER ever fade in   and fade out:</p>

```<code>$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            img.animate({
                opacity: .3
            }, 400, function ()

            {
                // When finished, animate it back to solid.
                img.animate({
                    opacity: 1
                }, 400);

            });

            // Clear the interval once we've reached 1000.
            if (++img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});
</code>```

答:
This achieves what you want. You could also use delay as suggested by others, but I'd be worried about the interval triggering while the previous animation is still running. This code instead trigger the interval at (e.g.) every 1000 ms and fades in and out every other time, oves 200 ms.

Please note that I've moved the ++!

```<code><script>
$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            if (++img[0].$count % 2) {
              img.animate({opacity: .3}, 200)
            }else{
              img.animate({opacity: 1}, 200)
            }

            // Clear the interval once we've reached 1000.
            if (img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});
</script>
</code>```

Body:
If have the following code but i cant get a pause AFTER ever fade in   and fade out:

$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            img.animate({
                opacity: .3
            }, 400, function ()

            {
                // When finished, animate it back to solid.
                img.animate({
                    opacity: 1
                }, 400);

            });

            // Clear the interval once we've reached 1000.
            if (++img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});

Body:
This achieves what you want. You could also use delay as suggested by others, but I'd be worried about the interval triggering while the previous animation is still running. This code instead trigger the interval at (e.g.) every 1000 ms and fades in and out every other time, oves 200 ms.

Please note that I've moved the ++!

<script>
$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            if (++img[0].$count % 2) {
              img.animate({opacity: .3}, 200)
            }else{
              img.animate({opacity: 1}, 200)
            }

            // Clear the interval once we've reached 1000.
            if (img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});
</script>


问:
What happens if arguments passed to sscanf are cast
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

```<code>struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}
</code>```

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.

答:
In this case from the pointer point of view nothing as on the all modern machines pointers are the same for all types.

But because you use wrong formats - the scanf will write outside the memory allocated to the variables and it is an Undefined Behaviour.

Body:
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.


问:
How to fix 'System.NullReferenceException: 'Object reference not set to an instance of an object.'
I am new to Xml and Linq and I have been following a tutorial on youtube on how to use it.

Link to the video: https://www.youtube.com/watch?v=OsfVJ485RY4

The problem is that when I run the code to either change the value or delete it, I always get the following error:

```<code>System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XElement.Attribute(...) returned null.
</code>```

First of all I load my document:

```<code>XDocument xmlDocument = XDocument.Load(@"C:\Users\matpl\source\repos\LinqToXML\LinqToXML\Data.xml");
</code>```

The part where I want to change the value of the Xml document

```<code>xmlDocument.Element("Students")
           .Elements("Student")
           .Where(x => x.Attribute("Id").Value == "101").FirstOrDefault()
           .SetElementValue("TotalMarks", "999");
</code>```

When I want to delete an element:

```<code>xmlDocument.Root.Elements().Where(x => x.Attribute("Id").Value == "104").Remove();
</code>```

XML file:

```<code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Comment Updated-->
<Students>
  <Student>
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student>
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>
</code>```

Thank you,

答:
There is one more Student element between Students and Student-101. It looks like you have wrong xml:

```<code><Students>
  <Student> //WHAT IS IT?
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student> //WHAT IS IT?
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>
</code>```

Check this https://dotnetfiddle.net/14js9r. It works without errors with proper xml.

Body:
I am new to Xml and Linq and I have been following a tutorial on youtube on how to use it.

Link to the video: https://www.youtube.com/watch?v=OsfVJ485RY4

The problem is that when I run the code to either change the value or delete it, I always get the following error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XElement.Attribute(...) returned null.

First of all I load my document:

XDocument xmlDocument = XDocument.Load(@"C:\Users\matpl\source\repos\LinqToXML\LinqToXML\Data.xml");

The part where I want to change the value of the Xml document

xmlDocument.Element("Students")
           .Elements("Student")
           .Where(x => x.Attribute("Id").Value == "101").FirstOrDefault()
           .SetElementValue("TotalMarks", "999");

When I want to delete an element:

xmlDocument.Root.Elements().Where(x => x.Attribute("Id").Value == "104").Remove();

XML file:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<Students>
  <Student>
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student>
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>

Thank you,

Body:
There is one more Student element between Students and Student-101. It looks like you have wrong xml:

<Students>
  <Student> //WHAT IS IT?
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student> //WHAT IS IT?
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>

Check this https://dotnetfiddle.net/14js9r. It works without errors with proper xml.


问:
Unit Test Challenge For a Function
In my Unit test file using Nunit, I am attempting to write test cases so as to test for all of the if/else branches.
Is there a way to inject a specific DateTime.Now inside this method while calling it in the unit test?

The method takes Opening/Closing times for a restaurant.

```<code>public void LunchDinnerBummer(string openingTime, string closingTime)
{
    //Based on the current time, alerts the user
    //if it is lunch/dinner time or outside of
    //business hours
    var openTime = DateTime.Parse(openingTime);
    var closeTime = DateTime.Parse(closingTime);

    //End of lunch time
    var lunchTime = DateTime.Parse("3:00 PM");

    //For lunch time
    if (openTime < DateTime.Now && DateTime.Now < lunchTime)
        Console.WriteLine("It is time to go to Ted’s for lunch!");

    //For dinner time
    else if (DateTime.Now > lunchTime && DateTime.Now < closeTime)
        Console.WriteLine("It is time to go to Ted’s for dinner!");

    //If outside of business hour before Opening Time for today
    else if (DateTime.Now < openTime)
    {
        TimeSpan span = openTime.Subtract(DateTime.Now);
        Console.WriteLine("Bummer, Ted’s is closed");
        Console.WriteLine("Ted’s will open in: " + span.Hours + " hour " + " and " + span.Minutes + " minutes ");
    }
    //If outside of business hours past closing time for today
    //Calculate for the hours and minutes left till opening time for next day
    else
    {
        var openTimeNextDay = openTime.AddDays(1);
        TimeSpan span = openTimeNextDay.Subtract(DateTime.Now);
        Console.WriteLine("Bummer, Ted’s is closed");
        Console.WriteLine("Ted’s will open in: " + span.Hours + " hour " + " and " + span.Minutes + " minutes ");
    }
}
</code>```

答:
One way (IMO the best) is to simply pass the current time as an argument.

public void LunchDinnerBummer(string openingTime, string closingTime, DateTime now)
...
```

Then your tests can use all sorts of different times, while your production code can pass DateTime.Now.

Going beyond the question as asked, I would guess that LunchDinnerBummer may be a method of some class that represents a restaurant. If that's the case, I would initialize open and close times in the constructor, simplifying LunchDinnerBummer to a single argument.

More stuff you didn't ask :-) ... Why use string as an argument rather than DateTime?

Title: Unit Test Challenge For a Function

Body:
In my Unit test file using Nunit, I am attempting to write test cases so as to test for all of the if/else branches.
Is there a way to inject a specific DateTime.Now inside this method while calling it in the unit test?

The method takes Opening/Closing times for a restaurant.

public void LunchDinnerBummer(string openingTime, string closingTime)
{
    //Based on the current time, alerts the user
    //if it is lunch/dinner time or outside of
    //business hours
    var openTime = DateTime.Parse(openingTime);
    var closeTime = DateTime.Parse(closingTime);

    //End of lunch time
    var lunchTime = DateTime.Parse("3:00 PM");

    //For lunch time
    if (openTime < DateTime.Now && DateTime.Now < lunchTime)
        Console.WriteLine("It is time to go to Ted’s for lunch!");

    //For dinner time
    else if (DateTime.Now > lunchTime && DateTime.Now < closeTime)
        Console.WriteLine("It is time to go to Ted’s for dinner!");

    //If outside of business hour before Opening Time for today
    else if (DateTime.Now < openTime)
    {
        TimeSpan span = openTime.Subtract(DateTime.Now);
        Console.WriteLine("Bummer, Ted’s is closed");
        Console.WriteLine("Ted’s will open in: " + span.Hours + " hour " + " and " + span.Minutes + " minutes ");
    }
    //If outside of business hours past closing time for today
    //Calculate for the hours and minutes left till opening time for next day
    else
    {
        var openTimeNextDay = openTime.AddDays(1);
        TimeSpan span = openTimeNextDay.Subtract(DateTime.Now);
        Console.WriteLine("Bummer, Ted’s is closed");
        Console.WriteLine("Ted’s will open in: " + span.Hours + " hour " + " and " + span.Minutes + " minutes ");
    }
}

Body:
One way (IMO the best) is to simply pass the current time as an argument.

public void LunchDinnerBummer(string openingTime, string closingTime, DateTime now)
...

Then your tests can use all sorts of different times, while your production code can pass DateTime.Now.

Going beyond the question as asked, I would guess that LunchDinnerBummer may be a method of some class that represents a restaurant. If that's the case, I would initialize open and close times in the constructor, simplifying LunchDinnerBummer to a single argument.

More stuff you didn't ask :-) ... Why use string as an argument rather than DateTime?


问:
Checking if bitmap is recycled doesn't help to solve "RuntimeException: Canvas: trying to use a recycled bitmap"
I send bitmaps to my activity from Service (using LocalBroadcastManager and intent bitmap extra)

I set them to ImageView in activity like this:

```<code>if (!bitmap.isRecycled) {
    imageView.setImageBitmap(bitmap)
}
</code>```

When I don't need the service anymore I close it and release bitmap object kept in that service

But when I close the service I usually get the following error:

```<code>java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@fc4b896
</code>```

Sobitmap.isRecycled condition doesn't help here

Is there any safe method to set Bitmap to ImageView?

答: When you are using imageView.setImageBitmap(bitmap), you should not recycle the bitmap after setImageBitmap because your imageView is still referencing and using that bitmap. You can recycle it when activity/fragment/view is destroyed.

Body:
I send bitmaps to my activity from Service (using LocalBroadcastManager and intent bitmap extra)

I set them to ImageView in activity like this:

if (!bitmap.isRecycled) {
    imageView.setImageBitmap(bitmap)
}

When I don't need the service anymore I close it and release bitmap object kept in that service

But when I close the service I usually get the following error:

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@fc4b896

Sobitmap.isRecycled condition doesn't help here

Is there any safe method to set Bitmap to ImageView?


问:
Accessing a Rails model name from within a lib file of the same method
This may seem like a silly question but I have a model named Ad and I have a library name auto which contains a class Ad(lib/auto.rb).

```<code>#auto.rb lib file
module auto
 class Ad
   def initialize
    ...
   end

   def convert
    # here I would like to access my model class Ad
    # ::Ad does not work. Requiring it does not work either.
   end

 end
end
</code>```

Does Rails 3 store models under some global namespace?

答:
I think that you can't get it straight from your external class. But you can pass it from your exact model.

I think this can be useful

http://guides.rubyonrails.org/plugins.html#add-an-acts_as-method-to-active-record

Body:
This may seem like a silly question but I have a model named Ad and I have a library name auto which contains a class Ad(lib/auto.rb).

#auto.rb lib file
module auto
 class Ad
   def initialize
    ...
   end

   def convert
    # here I would like to access my model class Ad
    # ::Ad does not work. Requiring it does not work either.
   end

 end
end

Does Rails 3 store models under some global namespace?


问:
How do I create a superuser account in Django 1.9.6
I am reading a book ("Learning Django Web Development" by Sanjeev Jaiswal and Ratan Kumar) on Django, but the book is based on an earlier version of Django (prior to version 1.9).  In order to populate the database with tables, the book uses the syncdb command:

```<code>$ python manage.py syncdb
</code>```

Then the book says that terminal will prompt you to create a superuser account.

the syncdb command is no longer used in Django version 1.9 and up.  After some research, it seems as if the migrate command populates the databse with tables, but it does not prompt the creation of a superuser account. How can I do this in Django 1.9.6?

答:
you create superuser with this :

```<code>python manage.py createsuperuser
</code>```

this will create superuser for you and you can create many superuser .
but notice before you can make super user you must run these command :

```<code>python manage.py makemigrations
</code>```

and them :

```<code>python manage.py migrate
</code>```

Body:
I am reading a book ("Learning Django Web Development" by Sanjeev Jaiswal and Ratan Kumar) on Django, but the book is based on an earlier version of Django (prior to version 1.9).  In order to populate the database with tables, the book uses the syncdb command:

$ python manage.py syncdb

Then the book says that terminal will prompt you to create a superuser account.

the syncdb command is no longer used in Django version 1.9 and up.  After some research, it seems as if the migrate command populates the databse with tables, but it does not prompt the creation of a superuser account. How can I do this in Django 1.9.6?

Body:
you create superuser with this :

python manage.py createsuperuser

this will create superuser for you and you can create many superuser .
but notice before you can make super user you must run these command :

python manage.py makemigrations

and them :

python manage.py migrate