问:
Deleting post with React Redux api delete request
When i console log this.props i get an array with post.id and i want to make onClick function to remove this item from the list and do not show on the page
What is wrong with my code there?

so this is what i have

```<code>export const deletePost = id => dispatch => {
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: "DELETE"
  })
    .then(res => res.json())
    .then(post =>
      dispatch({
        type: DELETE_POST,
        payload: id
      }),
    );
};

my reducer:

const initialState = {
  items: [],
  item: {}
};
    case FETCH_POSTS:
      return {
        ...state,
        items: action.payload
      };
    case DELETE_POST:
      return {
        ...state,
        items: action.payload
      };

Component contains of

const mapStateToProps = state => ({
  posts: state.postsReducer.items,
});

const mapDispatchToProps = {
  fetchPosts, deletePost
}

And Delete button on each post:

<button key={post.id} onClick={()=>this.props.deletePost()}>X</button>```

```

答:
I'm seeing a couple of things here that you should take a look at, and hopefully they'll help you to solve your issue.

First of all, note that your deletePost function expects a parameter with the post id. However, in the JSX code you posted for your button, you're not passing any value to the function at all. This means that the property payload will have an undefined value by the time the action is dispatched.

Make sure you update your view to pass it an id, so you call the proper endpoint (your DELETE request is probably pointing to https://jsonplaceholder.typicode.com/posts/undefined right now) and the reducer actually receives the id of the post you want to remove:

```<code><button key={post.id} onClick={()=>this.props.deletePost(post.id)}>X</button>
</code>```

The second thing you have to check is the implementation of your reducer. From what I've understood in your message and the code for the deletePost method, action.payload should contain a number.

That being the case, how your reducer is handling the DELETE_POST action in the reducer doesn't make too much sense to me.

```<code>case DELETE_POST:
    return {
        ...state,
        items: action.payload
    };
</code>```

Reducers are supposed to be pure functions that, for a given state and action, returns an entirely new state based on the action it receives. Remember too that the state you receive cannot be altered at all: if the original instance is mutated in any way, your code will not work.

In this case, you need to return a new state where your items property is replaced by a new list where the id you want to remove is missing. In the piece of code you wrote, however, you're replacing the items array by a number. This is not what was supposed to happen, starting by the fact that items should still be an array of numbers.

What you actually need to do is to create a new array that does not include the item you wanted to remove. You may use the filter method to achieve this:

```<code>case DELETE_POST:
    return {
        ...state,
        items: state.items.filter(item => item !== action.payload)
    };
</code>```

This code should do exactly what you want: here we are assigning the items property in your state an entirely new array where the deleted post is not included.

filter returns an array with the items for which the specified function returns true. In this case, the arrow function we're passing to filter returns true for every item that's different from the id of the post you want to remove.

By using this method you will also have no problems with the initial state.items value being mutated somehow, as filter returns a new instance of Array and does not alter the original.

Body:
When i console log this.props i get an array with post.id and i want to make onClick function to remove this item from the list and do not show on the page
What is wrong with my code there?

so this is what i have

export const deletePost = id => dispatch => {
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: "DELETE"
  })
    .then(res => res.json())
    .then(post =>
      dispatch({
        type: DELETE_POST,
        payload: id
      }),
    );
};

my reducer:

const initialState = {
  items: [],
  item: {}
};
    case FETCH_POSTS:
      return {
        ...state,
        items: action.payload
      };
    case DELETE_POST:
      return {
        ...state,
        items: action.payload
      };

Component contains of

const mapStateToProps = state => ({
  posts: state.postsReducer.items,
});

const mapDispatchToProps = {
  fetchPosts, deletePost
}

And Delete button on each post:

<button key={post.id} onClick={()=>this.props.deletePost()}>X</button>```

Body:
I'm seeing a couple of things here that you should take a look at, and hopefully they'll help you to solve your issue.

First of all, note that your deletePost function expects a parameter with the post id. However, in the JSX code you posted for your button, you're not passing any value to the function at all. This means that the property payload will have an undefined value by the time the action is dispatched.

Make sure you update your view to pass it an id, so you call the proper endpoint (your DELETE request is probably pointing to https://jsonplaceholder.typicode.com/posts/undefined right now) and the reducer actually receives the id of the post you want to remove:

<button key={post.id} onClick={()=>this.props.deletePost(post.id)}>X</button>

The second thing you have to check is the implementation of your reducer. From what I've understood in your message and the code for the deletePost method, action.payload should contain a number.

That being the case, how your reducer is handling the DELETE_POST action in the reducer doesn't make too much sense to me.

case DELETE_POST:
    return {
        ...state,
        items: action.payload
    };

Reducers are supposed to be pure functions that, for a given state and action, returns an entirely new state based on the action it receives. Remember too that the state you receive cannot be altered at all: if the original instance is mutated in any way, your code will not work.

In this case, you need to return a new state where your items property is replaced by a new list where the id you want to remove is missing. In the piece of code you wrote, however, you're replacing the items array by a number. This is not what was supposed to happen, starting by the fact that items should still be an array of numbers.

What you actually need to do is to create a new array that does not include the item you wanted to remove. You may use the filter method to achieve this:

case DELETE_POST:
    return {
        ...state,
        items: state.items.filter(item => item !== action.payload)
    };

This code should do exactly what you want: here we are assigning the items property in your state an entirely new array where the deleted post is not included.

filter returns an array with the items for which the specified function returns true. In this case, the arrow function we're passing to filter returns true for every item that's different from the id of the post you want to remove.

By using this method you will also have no problems with the initial state.items value being mutated somehow, as filter returns a new instance of Array and does not alter the original.


来源: stackexchange

问:
Invalid LOC header (bad signature) when opening Excel file
We met an error while trying to open an Excel file with Apache POI. Calling new XSSFWorkbook(excelFile) resulted in:

```<code> org.apache.poi.openxml4j.exceptions.InvalidFormatException: invalid LOC header (bad signature)
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:369) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:164) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:132) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:561) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:109) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:80) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:125) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.ZipPackagePart.<init>(ZipPackagePart.java:78) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:241) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:684) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:254) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:201) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:301) ~[tika-app-1.11.jar!/:1.11]
</code>```

However, it's not with all files. Some work just fine.

The Excel files are on a server we cannot fully accessed, so it's difficult to know what is different about the ones that worked and the ones that failed. We thought it could be password protection but nope, a password encrypted file gives us another error.

Does anyone have a hint about what in certain of these Excel files could trigger this exception?

答:
An Excel file uploaded via FTP as text, hence transforming \r\n into \n. Instead of the type binary data it is.

This can be seen when the upload happens on Windows and the uploaded file is a couple of bytes smaller, statistically by 0.4%.

ContentLicense: CC BY-SA 4.0

Body:
We met an error while trying to open an Excel file with Apache POI. Calling new XSSFWorkbook(excelFile) resulted in:

 org.apache.poi.openxml4j.exceptions.InvalidFormatException: invalid LOC header (bad signature)
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:369) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:164) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:132) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:561) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:109) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:80) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:125) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.ZipPackagePart.<init>(ZipPackagePart.java:78) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:241) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:684) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:254) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:201) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:301) ~[tika-app-1.11.jar!/:1.11]

However, it's not with all files. Some work just fine.

The Excel files are on a server we cannot fully accessed, so it's difficult to know what is different about the ones that worked and the ones that failed. We thought it could be password protection but nope, a password encrypted file gives us another error.

Does anyone have a hint about what in certain of these Excel files could trigger this exception?


问:
COM on 64 Bit Platform
I'm using a 3rd party COM Library with C#, all works fine on 32 bit XP. I use tlbimp to create the wrapper, add a reference all works. However, when porting to our Server environment which is 64 bit Windows Server 2008, I've run into a road block.

The code below only runs properly when I right click and test it, ie run within the VS environment. The code does not work when compiled to a Console App, nor does the code work in an Assembly whether in test or called from a console App. In an attempt to get it working I'm running as Administrator and in a 32bit command window - still nothing grouper is always null, and no exception is thrown, indicating that GrpSvr.GrpCall is a valid Com Library name.

```<code>    string sMessage = "no grouper";
    GrpSvr.GrpCall grouper = Activator.CreateInstance(
        Type.GetTypeFromProgID("GrpSvr.GrpCall")) as GrpSvr.GrpCall;
    if (grouper != null)
        sMessage = grouper.GroupInit(@"C:\CmdGrp.txt", true, true);

    Console.WriteLine(sMessage);
</code>```

答: Try using COM+ as host, and keep your application compiled for 64 bits. For more info see this link</p>

ContentLicense: CC BY-SA 3.0

Title: COM on 64 Bit Platform

Body:
I'm using a 3rd party COM Library with C#, all works fine on 32 bit XP. I use tlbimp to create the wrapper, add a reference all works. However, when porting to our Server environment which is 64 bit Windows Server 2008, I've run into a road block.

The code below only runs properly when I right click and test it, ie run within the VS environment. The code does not work when compiled to a Console App, nor does the code work in an Assembly whether in test or called from a console App. In an attempt to get it working I'm running as Administrator and in a 32bit command window - still nothing grouper is always null, and no exception is thrown, indicating that GrpSvr.GrpCall is a valid Com Library name.

    string sMessage = "no grouper";
    GrpSvr.GrpCall grouper = Activator.CreateInstance(
        Type.GetTypeFromProgID("GrpSvr.GrpCall")) as GrpSvr.GrpCall;
    if (grouper != null)
        sMessage = grouper.GroupInit(@"C:\CmdGrp.txt", true, true);

    Console.WriteLine(sMessage);


问:
Create a dynamic SQL Where clause that both parts of the where statement are passed in parameters? i.e. Where Variable1 = Variable2
I have seen many examples of dynamic where clauses but none ever covered the issue I am having. Is it even possible?</p>

```<code>Create Procedure ManualParse2
    (
        @Variable1 AS nvarchar(MAX)
        ,@Variable2 AS nvarchar(MAX)
    )
AS
    Select *
    From Faculty
    Where @Variable1
        Case
            When @Variable1 = 'Department' THEN Department
            When @Variable1 = 'Name' THEN Name
            When @Variable1 = 'Gender' THEN Gender
            When @Variable1 = 'FacultyID' THEN FacultyID
        END
        = @Variable2

EXEC ManualParse2 @Variable1 = 'Gender', @Variable2 = 'Male'
</code>```

答:
Reading between the lines, but I suspect what you actually want is:

```<code>CREATE PROC dbo.ManualParse2 @ColumnName sysname, @ColumnValue nvarchar(50) AS --You aren't going to have a department with 1 billion characters in it
                                                                               --sysname is the correct data type for object names (it's a synonym for nvarchar(128) NOT NULL)
BEGIN

    DECLARE @SQL nvarchar(MAX),
            @CRLF nchar(2) = NCHAR(13) + NCHAR(10);
    SET @SQL = N'SELECT *' + @CRLF + --This should reallty be a column list
               N'FROM dbo.Faculty' + @CRLF +
               N'WHERE ' + QUOTENAME(@ColumnName) + N' = @ColumnValue;';

    --PRINT @SQL; --Unlikely to be needed for such a simple statement, but your debugging friend
    EXEC sp_executesql @SQL, N'@ColumnValue nvarchar(50)', @ColumnValue;
END;
GO
</code>```

Body:
I have seen many examples of dynamic where clauses but none ever covered the issue I am having. Is it even possible?

Create Procedure ManualParse2
    (
        @Variable1 AS nvarchar(MAX)
        ,@Variable2 AS nvarchar(MAX)
    )
AS
    Select *
    From Faculty
    Where @Variable1
        Case
            When @Variable1 = 'Department' THEN Department
            When @Variable1 = 'Name' THEN Name
            When @Variable1 = 'Gender' THEN Gender
            When @Variable1 = 'FacultyID' THEN FacultyID
        END
        = @Variable2

EXEC ManualParse2 @Variable1 = 'Gender', @Variable2 = 'Male'

Body:
Reading between the lines, but I suspect what you actually want is:

CREATE PROC dbo.ManualParse2 @ColumnName sysname, @ColumnValue nvarchar(50) AS --You aren't going to have a department with 1 billion characters in it
                                                                               --sysname is the correct data type for object names (it's a synonym for nvarchar(128) NOT NULL)
BEGIN

    DECLARE @SQL nvarchar(MAX),
            @CRLF nchar(2) = NCHAR(13) + NCHAR(10);
    SET @SQL = N'SELECT *' + @CRLF + --This should reallty be a column list
               N'FROM dbo.Faculty' + @CRLF +
               N'WHERE ' + QUOTENAME(@ColumnName) + N' = @ColumnValue;';

    --PRINT @SQL; --Unlikely to be needed for such a simple statement, but your debugging friend
    EXEC sp_executesql @SQL, N'@ColumnValue nvarchar(50)', @ColumnValue;
END;
GO


问:
Using a ArrayAdapter won't work with fragment
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

```<code>public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}
</code>```

The fragment class:

```<code>public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}
</code>```

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

```<code>public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}
</code>```

}

The way I created the Parceable:

```<code>Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);
</code>```

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null

答:
Use getContext() instead of this. this refers to current object (Fragment), which is not subclass of Context.

Create adapter in onViewCreated(), because getContext() returns null in onCreateView().

Body:
I am trying to get an ArrayList from an activity and then display it inside a fragment  in a custom adapter. The problem it's that I cannot setAdapter to do so. The error it says the context it's wrong, when I created the Adapter.

Creare_istoricAdapter class:

public class Creare_istoricAdapter extends ArrayAdapter<Creare_istoric> {
    private static final String TAG = "Creareistoric_adapter";
    private Context mContext;
    int mResource;

    public Creare_istoricAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Creare_istoric> objects) {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        String id_alerta = getItem(position).getId_alerta();
        String tip_problema = getItem(position).getTip_problema();
        String data_ora= getItem(position).getData_ora();
        String stare_problema = getItem(position).getStare_problema();
        String descriere = getItem(position).getDescriere();
        Creare_istoric istoric = new Creare_istoric(id_alerta, tip_problema, data_ora, stare_problema, descriere);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView text_tip_alerta_istoric = convertView.findViewById(R.id.text_tip_alerta_istoric);
        TextView text_ora_alerta_istoric = convertView.findViewById(R.id.text_ora_alerta_istoric);
        TextView text_stare_alerta_istoric = convertView.findViewById(R.id.text_stare_alerta_istoric);
        text_tip_alerta_istoric.setText(tip_problema);
        text_ora_alerta_istoric.setText(data_ora);
        text_stare_alerta_istoric.setText(stare_problema);
        return convertView;
    }
}

The fragment class:

public class Fragment_alerte_trimise extends Fragment {
    public Fragment_alerte_trimise(){}
    ListView list_view_alerte_trimise;
    ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
        Bundle bundle_trimise;
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        Creare_istoricAdapter adapter = new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise);
        list_view_alerte_trimise.setAdapter(adapter);
    }

}

The problems it's in new Creare_istoricAdapter(this, R.layout.istoric_alerte_adapter, alerteTrimise) , about the context, and is also greyed out, saying it's redundant.

EDIT:

I have changed the code following the answers below, but now when I open the activity that uses the fragment, it does not show the list at all. It's only an blank screen.

The fragment code:

public class Fragment_alerte_trimise extends Fragment {
   public Fragment_alerte_trimise(){}
   private ListView list_view_alerte_trimise;
   ArrayList<Creare_istoric> alerteTrimise= new ArrayList<>();

   @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View alerte_trimise = inflater.inflate(R.layout.fragment_alerte_trimise,container, false);
        return alerte_trimise;
}

   @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle_trimise = getArguments();
        if (bundle_trimise != null) {
            alerteTrimise = bundle_trimise.getParcelableArrayList("alerte_trimise");
        }
        list_view_alerte_trimise =getView().findViewById(R.id.list_view_alerte_trimise);
        list_view_alerte_trimise.setAdapter(new Creare_istoricAdapter(getContext(), R.layout.istoric_alerte_adapter, alerteTrimise));
}

}

The way I created the Parceable:

Bundle bundle_trimise = new Bundle();
bundle_trimise.putParcelableArrayList("alerte_trimise", alerteTrimise);
Fragment_alerte_trimise fg = new Fragment_alerte_trimise();
fg.setArguments(bundle_trimise);

I have the ListView created in the layout that's inflated by the onCreateView, but when I use getView().findViewById it says that it may produce 'NullPointerException', and so does the getContext(), which says it might be null


问:
Split country code from the Phone number using SSIS
Im creating a SSIS package to check if the existing phone numbers country codes are matching with the its country.For that i need to split country code from the phone number and is there a way to split using any component is SSIS?

Thank You

答:
You can do that using SQL (if reading from database) using LEFT() or SUBSTRING() functions, as example if the first three characters are the country code you can use:

```<code>SELECT LEFT([PhoneNumber],3) FROM Table
</code>```

More info at:

LEFT (Transact-SQL)

SUBSTRING (Transact-SQL)

Within SSIS, you can achieve this using Derived column component, for the example aboveyou can use:

```<code>LEFT([PhoneNumber],3)
</code>```

SSIS Derived Columns with Multiple Expressions vs Multiple Transformations

Derived Column Transformation in SSIS

Derived Column Transformation

Body:
You can do that using SQL (if reading from database) using LEFT() or SUBSTRING() functions, as example if the first three characters are the country code you can use:

SELECT LEFT([PhoneNumber],3) FROM Table

More info at:

LEFT (Transact-SQL)

SUBSTRING (Transact-SQL)

Within SSIS, you can achieve this using Derived column component, for the example aboveyou can use:

LEFT([PhoneNumber],3)

SSIS Derived Columns with Multiple Expressions vs Multiple Transformations

Derived Column Transformation in SSIS

Derived Column Transformation


问:
Polybase: Azure Sql DB cannot import blob storage
Is it true that Azure SQL cannot import blob storage? (SQLDW can and also stand alone instance)

as given in this document, it cannot. But the document is from 2018. Has things changed after that?

答:
Azure SQL Database does not have Polybase but it does have BULK INSERT, eg

```<code>BULK INSERT Product
FROM 'data/product.dat'
WITH ( DATA_SOURCE = 'MyAzureBlobStorageAccount');
</code>```

See this question for more details and an example:

Create a table in Azure SQL Database from Blob Storage

Main page:

https://learn.microsoft.com/en-us/archive/blogs/sqlserverstorageengine/loading-files-from-azure-blob-storage-into-azure-sql-database

Body:
Azure SQL Database does not have Polybase but it does have BULK INSERT, eg

BULK INSERT Product
FROM 'data/product.dat'
WITH ( DATA_SOURCE = 'MyAzureBlobStorageAccount');

See this question for more details and an example:

Create a table in Azure SQL Database from Blob Storage

Main page:

https://learn.microsoft.com/en-us/archive/blogs/sqlserverstorageengine/loading-files-from-azure-blob-storage-into-azure-sql-database


问:
Spacing in exponential term in matplotlib
I got a problem about the spacing between plus sign in a^{++}.

If you look the figure below, the spacing is quite large.

I am wondering whether there is a way to make the spacing narrower.

```<code>#import libraries
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax  = plt.gca()

x = np.linspace(0,1,20)

plt.plot(x,x**2);
plt.plot(x,-x**2);
plt.text(0.1,0.7,"$a^{++}$",fontsize=25);
plt.text(0.1,-0.7,"$b^{--}$",fontsize=25);
</code>```

答:
When you write code inside $...$ you are using matplotlib's MathText engine. With this, spacings are the same as in usual TeX, such that e.g. \! will insert a negative thin space. The more \! you use, the closer will be the letters. Here's an example:

```<code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax  = plt.gca()

x = np.linspace(0,1,20)

plt.plot(x,x**2);
plt.plot(x,-x**2);
plt.text(0.1,0.7,"$a^{\!\!\! + \!\!\!\! +}$",fontsize=25);
plt.text(0.1,-0.7,"$b^{--}$",fontsize=25);
</code>```

Body:
I got a problem about the spacing between plus sign in a^{++}.

If you look the figure below, the spacing is quite large.

I am wondering whether there is a way to make the spacing narrower.

#import libraries
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax  = plt.gca()

x = np.linspace(0,1,20)

plt.plot(x,x**2);
plt.plot(x,-x**2);
plt.text(0.1,0.7,"$a^{++}$",fontsize=25);
plt.text(0.1,-0.7,"$b^{--}$",fontsize=25);

Body:
When you write code inside $...$ you are using matplotlib's MathText engine. With this, spacings are the same as in usual TeX, such that e.g. \! will insert a negative thin space. The more \! you use, the closer will be the letters. Here's an example:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax  = plt.gca()

x = np.linspace(0,1,20)

plt.plot(x,x**2);
plt.plot(x,-x**2);
plt.text(0.1,0.7,"$a^{\!\!\! + \!\!\!\! +}$",fontsize=25);
plt.text(0.1,-0.7,"$b^{--}$",fontsize=25);


问:
Retrieve .textContent including pseudo elements
Given

firstsecond

```

<p>and</p>

<pre class="lang-css prettyprint-override"><code>span + span::before {
  content: ', ';
}
</code>```

I'd like to retrieve the rendered string 'first, second' in JavaScript but .textContent ignores the content of the pseudo-element as it's not part of the DOM. Is there a way to get the actual rendered text?

Example: https://jsfiddle.net/silverwind/nyr5kohj/2/

答:
This doesn't get the rendered text but it imitates the behavior and produces the same string:

Step 1: Get the parent div

Step 2: Map through the children of the parent to get the text in an array

Step 3: Join the array to a string

firstsecond
```
</div>
</div>
</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 parent = document.getElementById("parent");
const childTextArray = [...parent.childNodes].map(child => child.innerText);
// => ["first", "second"]
const theStringYouAskedFor = childTextArray.join(", ");
// => "first, second"</code>```

Body:
Given

firstsecond

and

span + span::before {
  content: ', ';
}

I'd like to retrieve the rendered string 'first, second' in JavaScript but .textContent ignores the content of the pseudo-element as it's not part of the DOM. Is there a way to get the actual rendered text?

Example: https://jsfiddle.net/silverwind/nyr5kohj/2/

Body:
This doesn't get the rendered text but it imitates the behavior and produces the same string:

Step 1: Get the parent div

Step 2: Map through the children of the parent to get the text in an array

Step 3: Join the array to a string

<div id="parent"><span>first</span><span>second</span></div>

const parent = document.getElementById("parent");
const childTextArray = [...parent.childNodes].map(child => child.innerText);
// => ["first", "second"]
const theStringYouAskedFor = childTextArray.join(", ");
// => "first, second"


问:
Unmarshalling String XML with JAXB not working and returning just null values
I'm trying to unmarshall a String XML to a POJO Object without success. This is the code i am using

```<code>MyObject myobject = JAXB.unmarshal(new StringReader(myxmlstring), MyObject.class);
</code>```

The Xml is structured and object is structured as followed:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
    <SomePerson>
        <person>
            <name>joe</name>
        </person>
    </SomePerson>
</ns2:SomePerson>
</code>```

this is my Object:

```<code>@XmlRootElement(name="SomePerson")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {

    @XmlElement(name = "name")
    private String name;

    //getter and setters
}
</code>```

答:
Your class MyObject describes XML structure with root element named "SomePerson" containing child element "name" like following:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SomePerson>
    <name>joe</name>
</SomePerson>
</code>```

And XML you're trying to parse contains additional elements "SomePerson" and "person", which are not described in your JAXB class:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
    <SomePerson> <!-- definition missing -->
        <person> <!-- definition missing -->
            <name>joe</name>
        </person>
    </SomePerson>
</ns2:SomePerson>
</code>```

You should either fix the structure of your XML document or add missing fields to your JAXB classes definitions.

Body:
I'm trying to unmarshall a String XML to a POJO Object without success. This is the code i am using

MyObject myobject = JAXB.unmarshal(new StringReader(myxmlstring), MyObject.class);

The Xml is structured and object is structured as followed:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
    <SomePerson>
        <person>
            <name>joe</name>
        </person>
    </SomePerson>
</ns2:SomePerson>

this is my Object:

@XmlRootElement(name="SomePerson")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {

    @XmlElement(name = "name")
    private String name;

    //getter and setters
}

Body:
Your class MyObject describes XML structure with root element named "SomePerson" containing child element "name" like following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SomePerson>
    <name>joe</name>
</SomePerson>

And XML you're trying to parse contains additional elements "SomePerson" and "person", which are not described in your JAXB class:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
    <SomePerson> <!-- definition missing -->
        <person> <!-- definition missing -->
            <name>joe</name>
        </person>
    </SomePerson>
</ns2:SomePerson>

You should either fix the structure of your XML document or add missing fields to your JAXB classes definitions.


问:
My constraint foreign key is not working on my database
```<code>create table students (StudentId int primary key not null);

create table records (
     RecordId int primary key not null,
     StudentId int not null,
     constraint fk foreign key(StudentId) references students(StudentId));

 insert into students values (201810696);
 Query OK, 1 row affected (0.120 sec)

 insert into records values (1011, 20181313);
 Query OK, 1 row affected (0.004 sec)
</code>```

Why it keeps on accepting values that are not existing in table students?? I've already set my storage engine to innoDb on both of my tables in phpmyadmin localhost operations

btw I'm using the latest version of wampp and coding in cmd

答:
```<code>create table students (StudentId int primary key not null);

create table records (RecordId int primary key not null, StudentId int not null, constraint fk
foreign key(StudentId) references students(StudentId));

insert into records values(1, 1);
</code>```

I tried this in mysql 5.6, and insert is failed:

```<code>Cannot add or update a child row: a foreign key constraint fails (`db_9_cd6353`.`records`, CONSTRAINT `fk` FOREIGN KEY (`StudentId`) REFERENCES `students` (`StudentId`))
</code>```

You must be having corresponding data in Primary Table which you missed.

Body:
create table students (StudentId int primary key not null);

create table records (
     RecordId int primary key not null,
     StudentId int not null,
     constraint fk foreign key(StudentId) references students(StudentId));

 insert into students values (201810696);
 Query OK, 1 row affected (0.120 sec)

 insert into records values (1011, 20181313);
 Query OK, 1 row affected (0.004 sec)

Why it keeps on accepting values that are not existing in table students?? I've already set my storage engine to innoDb on both of my tables in phpmyadmin localhost operations

btw I'm using the latest version of wampp and coding in cmd

Body:
create table students (StudentId int primary key not null);

create table records (RecordId int primary key not null, StudentId int not null, constraint fk
foreign key(StudentId) references students(StudentId));

insert into records values(1, 1);

I tried this in mysql 5.6, and insert is failed:

Cannot add or update a child row: a foreign key constraint fails (`db_9_cd6353`.`records`, CONSTRAINT `fk` FOREIGN KEY (`StudentId`) REFERENCES `students` (`StudentId`))

You must be having corresponding data in Primary Table which you missed.


问:
JSON format to Data Frame in Python
I am reading API data from the cloud server in JSON format as shown here

How to write a code to store this data frame into the data frame in any database. How to convert JSON format to DataFrame?

The requirement output format is shown in table2

答:
check out the docs here

```<code>import pandas as pd
df = pd.read_json("http://some.com/blah.json")
</code>```

and as for storing it to a database you will need to know some things about your database connection.  docs here

```<code>tablename = "my_tablename"
connection_values = <your sql alchemy connection here>
df.to_sql(name=tablename, con=connection_values)
</code>```

Title: JSON format to Data Frame in Python

Body:
check out the docs here

import pandas as pd
df = pd.read_json("http://some.com/blah.json")

and as for storing it to a database you will need to know some things about your database connection.  docs here

tablename = "my_tablename"
connection_values = <your sql alchemy connection here>
df.to_sql(name=tablename, con=connection_values)


问:
List of multiple class to run same function name C++
I have multiple classes with same function as below

```<code>class A
{
  void display()
  {
    // display something
  }
};

class B
{
  void display()
  {
    // display something two
  }
};
</code>```

I want to store difference class at a list or a vector and loop to call the same function with same name

```<code>int main()
{
  A * a;

  B * b;

  //list or vector to store object

  std::vector < Something that can store different class > listofclass;

  listofclass.emplace_back(a);

  listofclass.emplace_back(b);

  for (int i = 0; i < listofclass.size(); i++)

  {

    listofclass[i].display();

  }
}
</code>```

Is that possible to do like this?
Because there is separate classes, having different purpose, and now i try to group them together
Or there is other alternative way to achieve something like this

答:
You have two solutions for this problem:

Use inheritance and just make a abstract class that will be a interface for your classes. In class A and class B just inherit from that interface and in std::vector hold pointer to base class.

```<code>#include <vector>
#include <iostream>
#include <memory>

class Interface_display {
public:
    virtual void display() = 0;
    virtual ~Interface_display(){};
};

class A : public Interface_display
{
public:

  void display() override
  {
    std::cout << "Display from A\n";
  }
  ~A() override = default;
};

class B : public Interface_display
{
public:

  void display() override
  {
    std::cout << "Display from B\n";
  }
  ~B() override = default;
};

int main(void)
{
    std::vector<std::unique_ptr<Interface_display>> v;

    v.emplace_back(std::make_unique<A>());
    v.emplace_back(std::make_unique<B>());

    for (const auto &element: v) {
        element->display();
    }
}
</code>```

And if you are using c++17, you could use std::variant and wrap objects of your class to std::variant:

```<code>#include <vector>
#include <iostream>
#include <variant>

class A
{
public:
  void display()
  {
    std::cout << "Display from A\n";
  }
};

class B
{
public:
  void display()
  {
    std::cout << "Display from B\n";
  }
};

int main(void)
{
    using variant_t = std::variant<A, B>;
    std::vector<variant_t> v;

    v.emplace_back(A());
    v.emplace_back(B());

    for (auto &element: v) {
        std::visit([](auto &x) { x.display(); }, element);
    }
}
</code>```

https://wandbox.org/permlink/8VBmziWzafbPZk99

Body:
I have multiple classes with same function as below

class A
{
  void display()
  {
    // display something
  }
};

class B
{
  void display()
  {
    // display something two
  }
};

I want to store difference class at a list or a vector and loop to call the same function with same name

int main()
{
  A * a;

  B * b;

  //list or vector to store object

  std::vector < Something that can store different class > listofclass;

  listofclass.emplace_back(a);

  listofclass.emplace_back(b);

  for (int i = 0; i < listofclass.size(); i++)

  {

    listofclass[i].display();

  }
}

Is that possible to do like this?
Because there is separate classes, having different purpose, and now i try to group them together
Or there is other alternative way to achieve something like this

Body:
You have two solutions for this problem:

Use inheritance and just make a abstract class that will be a interface for your classes. In class A and class B just inherit from that interface and in std::vector hold pointer to base class.

#include <vector>
#include <iostream>
#include <memory>

class Interface_display {
public:
    virtual void display() = 0;
    virtual ~Interface_display(){};
};

class A : public Interface_display
{
public:

  void display() override
  {
    std::cout << "Display from A\n";
  }
  ~A() override = default;
};

class B : public Interface_display
{
public:

  void display() override
  {
    std::cout << "Display from B\n";
  }
  ~B() override = default;
};

int main(void)
{
    std::vector<std::unique_ptr<Interface_display>> v;

    v.emplace_back(std::make_unique<A>());
    v.emplace_back(std::make_unique<B>());

    for (const auto &element: v) {
        element->display();
    }
}

And if you are using c++17, you could use std::variant and wrap objects of your class to std::variant:

#include <vector>
#include <iostream>
#include <variant>

class A
{
public:
  void display()
  {
    std::cout << "Display from A\n";
  }
};

class B
{
public:
  void display()
  {
    std::cout << "Display from B\n";
  }
};

int main(void)
{
    using variant_t = std::variant<A, B>;
    std::vector<variant_t> v;

    v.emplace_back(A());
    v.emplace_back(B());

    for (auto &element: v) {
        std::visit([](auto &x) { x.display(); }, element);
    }
}

https://wandbox.org/permlink/8VBmziWzafbPZk99


问:
Extract Domain Name from URL using Google RE2 Regexp for Data Studio
I have a list of URLs in an event action field, and need to extract only the domain name (without TLD) using Data studio:

```<code>https://example.com => example
https://www.example.com => example
https://subdomain.example.com => example
</code>```

Managed to extract everything but the non www version with this:

```<code>REGEXP_EXTRACT(Event Action, '^[^.]+.([^.]+)')
</code>```

Any ideas how extract the non www version as well?  Appreciate any help.

答:
This does the trick (Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate):

```<code>REGEXP_EXTRACT(Event Action, "(\\w+)\\.\\w+$")
</code>```

Body:
I have a list of URLs in an event action field, and need to extract only the domain name (without TLD) using Data studio:

https://example.com => example
https://www.example.com => example
https://subdomain.example.com => example

Managed to extract everything but the non www version with this:

REGEXP_EXTRACT(Event Action, '^[^.]+.([^.]+)')

Any ideas how extract the non www version as well?  Appreciate any help.

Body:
This does the trick (Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate):

REGEXP_EXTRACT(Event Action, "(\\w+)\\.\\w+$")


问:
C# MVC disable binding Controller Method Name to Action property of the model
The problem is - my controller binds method name to the "Action" property of my model and of course it causes error in my model state because Method Name is String and my Action property is Object. I want the Action property to be null when it is not present in my Formdata.

Form data:

Model state on processing POST request:

My controller action:

```<code>[HttpPost]
    public ActionResult RouteRoleActionsSave(TskRouteRoleAction model,List<TskAction.Actions> RoleActions = null)
    {
        using (var context = new SmartDbContext())
        {
            if (ModelState.IsValid)
            {
               return Json("ok");
            }
            return Json(ModelState);
        }
    }
</code>```

My Model:

```<code>[Table("TSK_ROUTE_ROLE_ACTIONS")]
public class TskRouteRoleAction
{
    [Key, Column("ROUTE_ID", Order = 0), ForeignKey("Route")]
    public decimal RouteId { get; set; }
    public TskRoute Route { get; set; }

    [Key, Column("ROLE_ID", TypeName = "numeric", Order = 1), ForeignKey("Role")]
    public TskRole.Roles? RoleId { get; set; }
    public TskRole Role { get; set; }

    [Key, Column("ACTION_ID", TypeName = "numeric", Order = 2), ForeignKey("Action")]
    public TskAction.Actions? ActionId { get; set; }
    public TskAction Action { get; set; }
}
</code>```

答:
After exploring the documentation i've noticed that the problem is caused by my route mapping that is using the "Action" parameter name in it, so it was conflicting with Action property of my model:

I've fixed it by adding a binding prefix to my Form, so no conflicting binding paramers longer exists:

Body:
The problem is - my controller binds method name to the "Action" property of my model and of course it causes error in my model state because Method Name is String and my Action property is Object. I want the Action property to be null when it is not present in my Formdata.

Form data:

Model state on processing POST request:

My controller action:

[HttpPost]
    public ActionResult RouteRoleActionsSave(TskRouteRoleAction model,List<TskAction.Actions> RoleActions = null)
    {
        using (var context = new SmartDbContext())
        {
            if (ModelState.IsValid)
            {
               return Json("ok");
            }
            return Json(ModelState);
        }
    }

My Model:

[Table("TSK_ROUTE_ROLE_ACTIONS")]
public class TskRouteRoleAction
{
    [Key, Column("ROUTE_ID", Order = 0), ForeignKey("Route")]
    public decimal RouteId { get; set; }
    public TskRoute Route { get; set; }

    [Key, Column("ROLE_ID", TypeName = "numeric", Order = 1), ForeignKey("Role")]
    public TskRole.Roles? RoleId { get; set; }
    public TskRole Role { get; set; }

    [Key, Column("ACTION_ID", TypeName = "numeric", Order = 2), ForeignKey("Action")]
    public TskAction.Actions? ActionId { get; set; }
    public TskAction Action { get; set; }
}


问:
How do I generate array values in Vue.js and show them?
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div>
        <h2> {{ player.ap }} </h2>
        <h2> {{ player.df }} </h2>
        <h2> {{ player.iq }} </h2>
    </div>
</template></code>```

答:
first you should call ngen  with this.ngen()

also your players are in array

```<code><template>
  <div>
    <h2>{{ player[0].ap }}</h2>
    <h2>{{ player[1].df }}</h2>
    <h2>{{ player[2].iq }}</h2>
  </div>
</template>
</code>```

see live example

https://codesandbox.io/s/elated-sunset-yphur

Body:
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}

<template>

 {{ player.ap }}

 {{ player.df }}

 {{ player.iq }}

</template>

Body:
first you should call ngen  with this.ngen()

also your players are in array

<template>
  <div>
    <h2>{{ player[0].ap }}</h2>
    <h2>{{ player[1].df }}</h2>
    <h2>{{ player[2].iq }}</h2>
  </div>
</template>

see live example

https://codesandbox.io/s/elated-sunset-yphur


问:
I should refresh browser to render my component using Routes | ReactJS
I have a menu with some routes. I want to show the component that correspond to his route while clicking on the menu. The issue is that, on the click, it changes me the url on my browser but the component displayed doesn't change. I have to refresh manually the page to render the good component. But my aim is to display the good component on the click without refreshing the page.

Here is my Menu.js code :

```<code><Router>
   <Link to={'/'} className="nav-link" id="homeLink">
      <div className="tableElement active" id="home">
        <FontAwesomeIcon icon={ faHome } className="icon"/>
      </div>
   </Link>

   <Link to={'/org'} className="nav-link" id="orgLink">
      <div className="tableElement" id="organisation">
        <FontAwesomeIcon icon={ faTasks } className="icon"/>
      </div>
   </Link>

   <Link to={'/users'} className="nav-link" id="usersLink">
      <div className="tableElement" id="user">
        <FontAwesomeIcon icon={ faUsers }  className="icon"/>
      </div>
   </Link>
</Router>
</code>```

Here is my render method App.js code :

```<code>render() {
 return (

   <Router>

    <div className="App">

      <LeftMenu/>

      <Switch>

         <Route exact path='/' component={Home}/>

         <Route path='/org'
                render={ (routeProps) => ( <Organisations {...routeProps} /> ) }
         />

         <Route path='/users'
                render={ (routeProps) => ( <UserTable {...routeProps} /> ) }
         />

      </Switch>

   </Router>
 );
}
</code>```

Thanks for your help !

答:
I resolved my issue, I just made a big mistake, my bad.

I just deleted <Router> tags that wrapped my code in Menu.js.

```<code><Link to={'/'} className="nav-link" id="homeLink">
  <div className="tableElement active" id="home">
    <FontAwesomeIcon icon={ faHome } className="icon"/>
  </div>
</Link>

<Link to={'/org'} className="nav-link" id="orgLink">
  <div className="tableElement" id="organisation">
    <FontAwesomeIcon icon={ faTasks } className="icon"/>
  </div>
</Link>

<Link to={'/users'} className="nav-link" id="usersLink">
  <div className="tableElement" id="user">
    <FontAwesomeIcon icon={ faUsers }  className="icon"/>
  </div>
</Link>
</code>```

I believed that <Link> tags should be wrapped by <Router> tags to work. So if you have the same issue, just check if you wrapped your <Link> tags by <Router> tags, and delete them.

Body:
I have a menu with some routes. I want to show the component that correspond to his route while clicking on the menu. The issue is that, on the click, it changes me the url on my browser but the component displayed doesn't change. I have to refresh manually the page to render the good component. But my aim is to display the good component on the click without refreshing the page.

Here is my Menu.js code :

<Router>
   <Link to={'/'} className="nav-link" id="homeLink">

        <FontAwesomeIcon icon={ faHome } className="icon"/>

   </Link>

   <Link to={'/org'} className="nav-link" id="orgLink">

        <FontAwesomeIcon icon={ faTasks } className="icon"/>

   </Link>

   <Link to={'/users'} className="nav-link" id="usersLink">

        <FontAwesomeIcon icon={ faUsers }  className="icon"/>

   </Link>
</Router>

Here is my render method App.js code :

render() {
 return (

   <Router>

      <LeftMenu/>

      <Switch>

         <Route exact path='/' component={Home}/>

         <Route path='/org'
                render={ (routeProps) => ( <Organisations {...routeProps} /> ) }
         />

         <Route path='/users'
                render={ (routeProps) => ( <UserTable {...routeProps} /> ) }
         />

      </Switch>

   </Router>
 );
}

Thanks for your help !

Body:
I resolved my issue, I just made a big mistake, my bad.

I just deleted <Router> tags that wrapped my code in Menu.js.

<Link to={'/'} className="nav-link" id="homeLink">
  <div className="tableElement active" id="home">
    <FontAwesomeIcon icon={ faHome } className="icon"/>
  </div>
</Link>

<Link to={'/org'} className="nav-link" id="orgLink">
  <div className="tableElement" id="organisation">
    <FontAwesomeIcon icon={ faTasks } className="icon"/>
  </div>
</Link>

<Link to={'/users'} className="nav-link" id="usersLink">
  <div className="tableElement" id="user">
    <FontAwesomeIcon icon={ faUsers }  className="icon"/>
  </div>
</Link>

I believed that <Link> tags should be wrapped by <Router> tags to work. So if you have the same issue, just check if you wrapped your <Link> tags by <Router> tags, and delete them.


问:
How to avoid Cache restore time outs
I do a cache of the maven repository using Cache@2 to prevent additional downloads especially since Maven Central may yield zero byte files.

However, I am getting events such as this on my build log and when it occurs it significantly slows down the build step.

```<code>2020-02-14T03:24:14.9261543Z Information, Downloaded 340.2 MB out of 447.6 MB (76%).
2020-02-14T03:24:18.3130567Z Warning, [https://37bvsblobprodcus311.blob.core.windows.net/db184fb09aee8f4ae39869ebeab81ab1ad/7FE2B04FAB9DCB08C78F137CCA2FDA2D5E37B05B5DBCA1D7EDD23F7DB5D580B301?sv=2017-04-17&sr=b&sig=mZZ1kK00Gc2cg5m6dyRB3XUYVB40dxJkvBMbXW4D3cM%3D&spr=https&se=2020-02-15T03%3A29%3A57Z&sp=r&rscl=x-e2eid-c561122c-76784a8c-be2cb59f-c79091dc-session-eacd1913-b0014305-a33f0081-46cabc28] Try 1/5, non-retryable exception caught. Throwing. Details:
2020-02-14T03:24:18.3131821Z Task was requested to be canceled. System.Threading.Tasks.TaskCanceledException: A task was canceled.
2020-02-14T03:24:18.3132112Z    at System.IO.Stream.CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
2020-02-14T03:24:18.3132355Z    at System.Net.Http.NoWriteNoSeekStreamContent.<>c.<SerializeToStreamAsync>b__4_0(Task t, Object s)
2020-02-14T03:24:18.3132630Z    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
2020-02-14T03:24:18.3133177Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3133445Z    at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
2020-02-14T03:24:18.3133903Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3134179Z    at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
2020-02-14T03:24:18.3134413Z    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
2020-02-14T03:24:18.3134691Z    at Microsoft.VisualStudio.Services.Common.TaskCancellationExtensions.EnforceCancellation[TResult](Task`1 task, CancellationToken cancellationToken, Func`1 makeMessage, String file, String member, Int32 line)
2020-02-14T03:24:18.3134970Z    at Microsoft.VisualStudio.Services.BlobStore.WebApi.DedupStoreHttpClient.<>c__DisplayClass57_0.<<GetRedirectResponseAsync>b__0>d.MoveNext()
2020-02-14T03:24:18.3135439Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3135708Z    at Microsoft.VisualStudio.Services.Content.Common.AsyncHttpRetryHelper`1.InvokeAsync(CancellationToken cancellationToken)
2020-02-14T03:24:18.3150625Z Warning, [https://37bvsblobprodcus311.blob.core.windows.net/db184fb09aee8f4ae39869ebeab81ab1ad/7FE2B04FAB9DCB08C78F137CCA2FDA2D5E37B05B5DBCA1D7EDD23F7DB5D580B301?sv=2017-04-17&sr=b&sig=mZZ1kK00Gc2cg5m6dyRB3XUYVB40dxJkvBMbXW4D3cM%3D&spr=https&se=2020-02-15T03%3A29%3A57Z&sp=r&rscl=x-e2eid-c561122c-76784a8c-be2cb59f-c79091dc-session-eacd1913-b0014305-a33f0081-46cabc28] Try 1/5, retryable exception caught. Retrying in 00:00:01. System.Threading.Tasks.TaskCanceledException: A task was canceled.
2020-02-14T03:24:18.3151412Z    at System.IO.Stream.CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
2020-02-14T03:24:18.3151697Z    at System.Net.Http.NoWriteNoSeekStreamContent.<>c.<SerializeToStreamAsync>b__4_0(Task t, Object s)
2020-02-14T03:24:18.3151962Z    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
2020-02-14T03:24:18.3152497Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3152771Z    at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
2020-02-14T03:24:18.3153248Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3153496Z    at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
2020-02-14T03:24:18.3153749Z    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
2020-02-14T03:24:18.3154100Z    at Microsoft.VisualStudio.Services.Common.TaskCancellationExtensions.EnforceCancellation[TResult](Task`1 task, CancellationToken cancellationToken, Func`1 makeMessage, String file, String member, Int32 line)
2020-02-14T03:24:18.3154606Z    at Microsoft.VisualStudio.Services.BlobStore.WebApi.DedupStoreHttpClient.<>c__DisplayClass57_0.<<GetRedirectResponseAsync>b__0>d.MoveNext()
2020-02-14T03:24:18.3155603Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3155739Z    at Microsoft.VisualStudio.Services.Content.Common.AsyncHttpRetryHelper`1.InvokeAsync(CancellationToken cancellationToken)
2020-02-14T03:24:18.3155929Z    at Microsoft.VisualStudio.Services.BlobStore.WebApi.DedupStoreHttpClient.<>c__DisplayClass60_0.<<HandleRedirectAsync>b__0>d.MoveNext()
2020-02-14T03:24:18.3159451Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3159789Z    at Microsoft.VisualStudio.Services.Content.Common.AsyncHttpRetryHelper`1.InvokeAsync(CancellationToken cancellationToken)
2020-02-14T03:24:19.9319176Z Information, Downloaded 340.2 MB out of 447.6 MB (76%).
2020-02-14T03:24:24.9323050Z Information, Downloaded 352.6 MB out of 447.6 MB (79%).
</code>```

Is there any way of avoiding that?  I have also checked https://status.dev.azure.com/ and there is no indication of any issues with it.  These are with the paid Azure Devops agent pool not a private agent pool.

答:
There is a similar issue that has been open here. You can join in the discussion of this thread or open new issue for above case.

you can try the workaround of using continueOnError: true on the cache task to prevent it from failing the build.

```<code>- task: Cache@2
  inputs:
    key: 'npm | "$(Agent.OS)" | package-lock.json'
    restoreKeys: |
       npm | "$(Agent.OS)"
       npm
    path: $(npm_config_cache)
  displayName: Cache npm

  continueOnError: true
</code>```

Title: How to avoid Cache restore time outs

Body:
I do a cache of the maven repository using Cache@2 to prevent additional downloads especially since Maven Central may yield zero byte files.

However, I am getting events such as this on my build log and when it occurs it significantly slows down the build step.

2020-02-14T03:24:14.9261543Z Information, Downloaded 340.2 MB out of 447.6 MB (76%).
2020-02-14T03:24:18.3130567Z Warning, [https://37bvsblobprodcus311.blob.core.windows.net/db184fb09aee8f4ae39869ebeab81ab1ad/7FE2B04FAB9DCB08C78F137CCA2FDA2D5E37B05B5DBCA1D7EDD23F7DB5D580B301?sv=2017-04-17&sr=b&sig=mZZ1kK00Gc2cg5m6dyRB3XUYVB40dxJkvBMbXW4D3cM%3D&spr=https&se=2020-02-15T03%3A29%3A57Z&sp=r&rscl=x-e2eid-c561122c-76784a8c-be2cb59f-c79091dc-session-eacd1913-b0014305-a33f0081-46cabc28] Try 1/5, non-retryable exception caught. Throwing. Details:
2020-02-14T03:24:18.3131821Z Task was requested to be canceled. System.Threading.Tasks.TaskCanceledException: A task was canceled.
2020-02-14T03:24:18.3132112Z    at System.IO.Stream.CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
2020-02-14T03:24:18.3132355Z    at System.Net.Http.NoWriteNoSeekStreamContent.<>c.<SerializeToStreamAsync>b__4_0(Task t, Object s)
2020-02-14T03:24:18.3132630Z    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
2020-02-14T03:24:18.3133177Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3133445Z    at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
2020-02-14T03:24:18.3133903Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3134179Z    at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
2020-02-14T03:24:18.3134413Z    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
2020-02-14T03:24:18.3134691Z    at Microsoft.VisualStudio.Services.Common.TaskCancellationExtensions.EnforceCancellation[TResult](Task`1 task, CancellationToken cancellationToken, Func`1 makeMessage, String file, String member, Int32 line)
2020-02-14T03:24:18.3134970Z    at Microsoft.VisualStudio.Services.BlobStore.WebApi.DedupStoreHttpClient.<>c__DisplayClass57_0.<<GetRedirectResponseAsync>b__0>d.MoveNext()
2020-02-14T03:24:18.3135439Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3135708Z    at Microsoft.VisualStudio.Services.Content.Common.AsyncHttpRetryHelper`1.InvokeAsync(CancellationToken cancellationToken)
2020-02-14T03:24:18.3150625Z Warning, [https://37bvsblobprodcus311.blob.core.windows.net/db184fb09aee8f4ae39869ebeab81ab1ad/7FE2B04FAB9DCB08C78F137CCA2FDA2D5E37B05B5DBCA1D7EDD23F7DB5D580B301?sv=2017-04-17&sr=b&sig=mZZ1kK00Gc2cg5m6dyRB3XUYVB40dxJkvBMbXW4D3cM%3D&spr=https&se=2020-02-15T03%3A29%3A57Z&sp=r&rscl=x-e2eid-c561122c-76784a8c-be2cb59f-c79091dc-session-eacd1913-b0014305-a33f0081-46cabc28] Try 1/5, retryable exception caught. Retrying in 00:00:01. System.Threading.Tasks.TaskCanceledException: A task was canceled.
2020-02-14T03:24:18.3151412Z    at System.IO.Stream.CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
2020-02-14T03:24:18.3151697Z    at System.Net.Http.NoWriteNoSeekStreamContent.<>c.<SerializeToStreamAsync>b__4_0(Task t, Object s)
2020-02-14T03:24:18.3151962Z    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
2020-02-14T03:24:18.3152497Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3152771Z    at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
2020-02-14T03:24:18.3153248Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3153496Z    at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
2020-02-14T03:24:18.3153749Z    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
2020-02-14T03:24:18.3154100Z    at Microsoft.VisualStudio.Services.Common.TaskCancellationExtensions.EnforceCancellation[TResult](Task`1 task, CancellationToken cancellationToken, Func`1 makeMessage, String file, String member, Int32 line)
2020-02-14T03:24:18.3154606Z    at Microsoft.VisualStudio.Services.BlobStore.WebApi.DedupStoreHttpClient.<>c__DisplayClass57_0.<<GetRedirectResponseAsync>b__0>d.MoveNext()
2020-02-14T03:24:18.3155603Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3155739Z    at Microsoft.VisualStudio.Services.Content.Common.AsyncHttpRetryHelper`1.InvokeAsync(CancellationToken cancellationToken)
2020-02-14T03:24:18.3155929Z    at Microsoft.VisualStudio.Services.BlobStore.WebApi.DedupStoreHttpClient.<>c__DisplayClass60_0.<<HandleRedirectAsync>b__0>d.MoveNext()
2020-02-14T03:24:18.3159451Z --- End of stack trace from previous location where exception was thrown ---
2020-02-14T03:24:18.3159789Z    at Microsoft.VisualStudio.Services.Content.Common.AsyncHttpRetryHelper`1.InvokeAsync(CancellationToken cancellationToken)
2020-02-14T03:24:19.9319176Z Information, Downloaded 340.2 MB out of 447.6 MB (76%).
2020-02-14T03:24:24.9323050Z Information, Downloaded 352.6 MB out of 447.6 MB (79%).

Is there any way of avoiding that?  I have also checked https://status.dev.azure.com/ and there is no indication of any issues with it.  These are with the paid Azure Devops agent pool not a private agent pool.

Body:
There is a similar issue that has been open here. You can join in the discussion of this thread or open new issue for above case.

you can try the workaround of using continueOnError: true on the cache task to prevent it from failing the build.

- task: Cache@2
  inputs:
    key: 'npm | "$(Agent.OS)" | package-lock.json'
    restoreKeys: |
       npm | "$(Agent.OS)"
       npm
    path: $(npm_config_cache)
  displayName: Cache npm

  continueOnError: true


问:
POST json to external API in .NET Core - Unsupported Media Type
I'm trying to code a middleman API that logs calls and other details from internal users to an external API.

When I try to POST to the external API from my Controller, I get 415 unsupported media type.

I set up my client in the controller constructor like this:

```<code>client.BaseAddress = new Uri("https://restapi.***.com/customers/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-AppSecretToken", Auth.APPSECRETTOKEN);
client.DefaultRequestHeaders.Add("X-AgreementGrantToken", Auth.AGREEMENTGRANTTOKEN);
</code>```

My POST method looks like this:

```<code>var json = JsonConvert.SerializeObject(customer, Formatting.Indented);

using (var stringContent = new StringContent(json))
{
   stringContent.Headers.ContentType.CharSet = "";
   HttpResponseMessage response = await client.PostAsync(client.BaseAddress, stringContent);

   if (!response.IsSuccessStatusCode)
   {
      return StatusCode((int)response.StatusCode);
   }
}

return CreatedAtAction("GetCustomer", new { id = customer.ID }, customer);
</code>```

I've been looking around and found a lot of comments telling me to use Stringcontent, but I also found a couple of responses saying ByteArrayContent - none of them work.

Can anyone help me?

EDIT: When I run the code with breakpoints it seems like some of the properties in the incoming customer object are set even though I didn't set them in my Postman call.

Example; the external API returns a customernumber when I give it the 5 properties that are obligatory. But when I call my internal API from Postman, sending only those 5 obligatory properties, it autopopulates the customernumber with a 0.

Could this be the source of the error? and how do I tell .net core to not autopopulate the customernumber?

EDIT2: I changed my stringContent to include encoding and used a different overload, so the using line now says

```<code>using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
</code>```

And I removed

```<code>stringContent.Headers.ContentType.Charset = "";
</code>```

to reflect the fact that I tried setting the encoding.

The return code changed from 415 to 400 Bad Request when I changed that.

EDIT3:

Tried NOT serializing with Json.Net, and instead used JObjects and Jproperties;

```<code>public async Task<ActionResult<Customer>> PostCustomer([FromBody]Customer customer)
{
   JObject payload = new JObject(
   new JProperty("currency", customer.Currency),
   new JProperty("name", customer.Name),
   new JProperty("customergroup",
       new JObject(new JProperty("customergroupNumber",
                   customer.CustomerGroup.CustomerGroupNumber)
                  )),
   new JProperty("paymentTerms",
       new JObject(new JProperty("paymentTermsNumber",
                   customer.PaymentTerms.PaymentTermsNumber)
                  )),
   new JProperty("vatZone",
       new JObject(new JProperty("vatZoneNumber",
                   customer.VatZone.VatZoneNumber)
                  ))
   );

using (var stringContent = new StringContent(payload.ToString(), Encoding.UTF8, "application/json"))
   {
    HttpResponseMessage response = await client.PostAsync(client.BaseAddress, stringContent);

    if (!response.IsSuccessStatusCode)
    {
       return StatusCode((int)response.StatusCode);
                }
    }

return CreatedAtAction("GetCustomer", new { id = customer.CustomerNumber }, customer);
}
</code>```

Still 400 Bad Request

答:
This is a case of capitalizing - simple really.

My POST request JSON had an object named customergroup - changed it to customerGroup, and it worked.

Body:
I'm trying to code a middleman API that logs calls and other details from internal users to an external API.

When I try to POST to the external API from my Controller, I get 415 unsupported media type.

I set up my client in the controller constructor like this:

client.BaseAddress = new Uri("https://restapi.***.com/customers/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-AppSecretToken", Auth.APPSECRETTOKEN);
client.DefaultRequestHeaders.Add("X-AgreementGrantToken", Auth.AGREEMENTGRANTTOKEN);

My POST method looks like this:

var json = JsonConvert.SerializeObject(customer, Formatting.Indented);

using (var stringContent = new StringContent(json))
{
   stringContent.Headers.ContentType.CharSet = "";
   HttpResponseMessage response = await client.PostAsync(client.BaseAddress, stringContent);

   if (!response.IsSuccessStatusCode)
   {
      return StatusCode((int)response.StatusCode);
   }
}

return CreatedAtAction("GetCustomer", new { id = customer.ID }, customer);

I've been looking around and found a lot of comments telling me to use Stringcontent, but I also found a couple of responses saying ByteArrayContent - none of them work.

Can anyone help me?

EDIT: When I run the code with breakpoints it seems like some of the properties in the incoming customer object are set even though I didn't set them in my Postman call.

Example; the external API returns a customernumber when I give it the 5 properties that are obligatory. But when I call my internal API from Postman, sending only those 5 obligatory properties, it autopopulates the customernumber with a 0.

Could this be the source of the error? and how do I tell .net core to not autopopulate the customernumber?

EDIT2: I changed my stringContent to include encoding and used a different overload, so the using line now says

using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))

And I removed

stringContent.Headers.ContentType.Charset = "";

to reflect the fact that I tried setting the encoding.

The return code changed from 415 to 400 Bad Request when I changed that.

EDIT3:

Tried NOT serializing with Json.Net, and instead used JObjects and Jproperties;

public async Task<ActionResult<Customer>> PostCustomer([FromBody]Customer customer)
{
   JObject payload = new JObject(
   new JProperty("currency", customer.Currency),
   new JProperty("name", customer.Name),
   new JProperty("customergroup",
       new JObject(new JProperty("customergroupNumber",
                   customer.CustomerGroup.CustomerGroupNumber)
                  )),
   new JProperty("paymentTerms",
       new JObject(new JProperty("paymentTermsNumber",
                   customer.PaymentTerms.PaymentTermsNumber)
                  )),
   new JProperty("vatZone",
       new JObject(new JProperty("vatZoneNumber",
                   customer.VatZone.VatZoneNumber)
                  ))
   );

using (var stringContent = new StringContent(payload.ToString(), Encoding.UTF8, "application/json"))
   {
    HttpResponseMessage response = await client.PostAsync(client.BaseAddress, stringContent);

    if (!response.IsSuccessStatusCode)
    {
       return StatusCode((int)response.StatusCode);
                }
    }

return CreatedAtAction("GetCustomer", new { id = customer.CustomerNumber }, customer);
}

Still 400 Bad Request


问:
No next button when importing Maven projects in IntelliJ
I am trying to follow a tutorial on spring boot, first step is to import a maven project in intelliJ, generated by spring initializer, but when I try to do so, I have no next button in the import window, only "finish". And when I click on finish, it does not seem to detect packages. Any idea ?

答: Import from Maven dialog was replaced with single open action and now takes all the defaults without showing any additional dialogs with many various settings: IDEA-223880.</p>


问:
Divi Wordpress Theme: Top Parent Level Not Clickable & Does not Link to Page on Mobile Menu with Collapse Nested Items
Divi automatically presents mobile menu when the media screen width is less than 1025px. By default, all menu items, including sub-menu items, are displayed in full expanded view with all menu items on the list.

Problem is, the parent level menu item no longer linkable to its own web page. In other words, tapping on the parent menu item that has nested sub-menus only expand or collapse the sub-menus, even though the parent menu itself leads to a valid web page URL, essentially preventing visitors to access the web page.

I've already tried this fix I found online, but it doesn't work.

 #main-header .et_mobile_menu .menu-item-has-children > a:after { font-size: 16px; content: '4c'; top: 13px; right: 10px; }
    #main-header .et_mobile_menu .menu-item-has-children.visible > a:after { content: '4d'; }
    #main-header .et_mobile_menu ul.sub-menu { display: none !important; visibility: hidden !important;  transition: all 1.5s ease-in-out;}
    #main-header .et_mobile_menu .visible > ul.sub-menu { display: block !important; visibility: visible !important; }

    (function($) {

```<code>    function setup_collapsible_submenus() {
        var $menu = $('#mobile_menu'),
            top_level_link = '#mobile_menu .menu-item-has-children > a';

        $menu.find('a').each(function() {
            $(this).off('click');

            if ( $(this).is(top_level_link) ) {
                if ($(this).parent().hasClass('always-visitable')) {
                    $('<a class="hover-link"></div>')
                    .attr('href', $(this).attr('href'))
                    .on('click', function(e){ e.stopPropagation(); })
                    .appendTo($(this));
                }

                $(this).attr('href', '#');
            }

            if ( ! $(this).siblings('.sub-menu').length ) {
                $(this).on('click', function(event) {
                    $(this).parents('.mobile_nav').trigger('click');
                });
            } else {
                $(this).on('click', function(event) {
                    event.preventDefault();
                    $(this).parent().toggleClass('visible');
                });
            }
        });
    }

    $(window).load(function() {
        setTimeout(function() {
            setup_collapsible_submenus();
        }, 700);
    });

})(jQuery);
</script>

**Also the CSS:**

#main-header .et_mobile_menu .always-visitable {
    position: relative;
}
#main-header .et_mobile_menu .always-visitable .hover-link {
    position: absolute;
    top: 0; left: 0; bottom: 0;
    right: 60px; /* right area continues to expand or collapse */
</code>```

答: Go to Divi theme options > Navigation > General Settings > Disable top tier dropdown menu links.</p>

Body:
Divi automatically presents mobile menu when the media screen width is less than 1025px. By default, all menu items, including sub-menu items, are displayed in full expanded view with all menu items on the list.

Problem is, the parent level menu item no longer linkable to its own web page. In other words, tapping on the parent menu item that has nested sub-menus only expand or collapse the sub-menus, even though the parent menu itself leads to a valid web page URL, essentially preventing visitors to access the web page.

I've already tried this fix I found online, but it doesn't work.

 #main-header .et_mobile_menu .menu-item-has-children > a:after { font-size: 16px; content: '4c'; top: 13px; right: 10px; }
    #main-header .et_mobile_menu .menu-item-has-children.visible > a:after { content: '4d'; }
    #main-header .et_mobile_menu ul.sub-menu { display: none !important; visibility: hidden !important;  transition: all 1.5s ease-in-out;}
    #main-header .et_mobile_menu .visible > ul.sub-menu { display: block !important; visibility: visible !important; }

    (function($) {

    function setup_collapsible_submenus() {
        var $menu = $('#mobile_menu'),
            top_level_link = '#mobile_menu .menu-item-has-children > a';

        $menu.find('a').each(function() {
            $(this).off('click');

            if ( $(this).is(top_level_link) ) {
                if ($(this).parent().hasClass('always-visitable')) {
                    $('
')
                    .attr('href', $(this).attr('href'))
                    .on('click', function(e){ e.stopPropagation(); })
                    .appendTo($(this));
                }

                $(this).attr('href', '#');
            }

            if ( ! $(this).siblings('.sub-menu').length ) {
                $(this).on('click', function(event) {
                    $(this).parents('.mobile_nav').trigger('click');
                });
            } else {
                $(this).on('click', function(event) {
                    event.preventDefault();
                    $(this).parent().toggleClass('visible');
                });
            }
        });
    }

    $(window).load(function() {
        setTimeout(function() {
            setup_collapsible_submenus();
        }, 700);
    });

})(jQuery);
</script>

**Also the CSS:**

#main-header .et_mobile_menu .always-visitable {
    position: relative;
}
#main-header .et_mobile_menu .always-visitable .hover-link {
    position: absolute;
    top: 0; left: 0; bottom: 0;
    right: 60px; /* right area continues to expand or collapse */


问:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '9'
I have two DateTimePickers (dateStart and dateStop) in a winform. I've set dateStart and dateSop's format like this:

```<code>    dateStart.Format = DateTimePickerFormat.Custom;
    dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
    dateStop.Format = DateTimePickerFormat.Custom;
    dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";
</code>```

I want to count number of rows from my datebase's table between dateStart and dateStop.
My select string:

```<code>string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value);
</code>```

And it's result:

This is how link DateStart and DateStop paramaters of my datebase with DateTimePickers.

```<code> cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;// new DateTime(dateStart.Value);
 cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;// new DateTime(2020, 02, 05, 13, 12, 25, 703);//2020, 02, 05, 13, 12, 25, 703   //2020, 02, 05, 13, 06, 50, 700
</code>```

The row counting works perfectly without WHERE clause.

```<code>count = (int)cmdCount.ExecuteScalar();//this is how I count the rows
</code>```

I'm getting here a 'System.Data.SqlClient.SqlException: Incorect syntax near 9'.

I kinda don't understand why if dateStart's format is  "yyyy:MM:dd HH:mm:ss", dateStart.value is returned in another format. On my UI, dateStart is displayed in the right format (the one from the code above). But I might have done something faulty in my stmt string.
Any thoughts on what is wrong?

EDIT 1 (my entire code):

```<code> private void button_Click(object sender, EventArgs e)
    {
        dateStart.Format = DateTimePickerFormat.Custom;
        dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        dateStop.Format = DateTimePickerFormat.Custom;
        dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  @DataStart AND @DataStop";         // WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value)
       // string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  '" + Convert.ToString(dateStart.Value) + "' AND '" + Convert.ToString(dateStop.Value) + "'";
        int count = 0;

        using (SqlConnection connection = new SqlConnection(@"Data Source=DESKTOP-JQSJAF8\SQLEXPRESS;Initial Catalog=TRTF_TagLogging;Integrated Security=True; MultipleActiveResultSets = true"))
        {
            using (SqlCommand cmd = new SqlCommand("PS_TagLogging", connection))// used for stored proc
            {
                using (SqlCommand cmdCount = new SqlCommand(stmt, connection))//used to count number of rows of my table
                {
                    //yyyy:MM:dd hh:mm:ss
                    connection.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
                    cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
                    var values = new List<double>();
                    var valData = new List<DateTime>();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        // values.Add(reader.GetInt64(0));//reads the values of first column (ID) from DB
                        values.Add(reader.GetFloat(1));//reads the values of second column (Tag1) from DB
                        valData.Add(reader.GetDateTime(2));//reads the values of third column (DateTime) from DB
                    }

                    arrDate = valData.ToArray();
                    arrVal = values.ToArray();

                    count = (int)cmdCount.ExecuteScalar();
                    plot1.XAxes[0].ScaleDisplay.TextFormatting.Style = Iocomp.Types.TextFormatDoubleStyle.DateTime;
                    plot1.XAxes[0].ScaleRange.Span = 1.0 / 120.0 ; //30sec Span;

                    for (int i=0; i<count; i++)
                    {
                        plot1.Channels.Trace[0].AddXY(arrDate[i], arrVal[i]);
                    }

                    connection.Close();
                }
            }
        }
        MessageBox.Show("Nr. lines: " + count);
         Random().NextDouble() * 100);
    }
</code>```

答:
Everything people told is ok, but i think there are missing quotes. Try:</p>

```<code>string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  '" + Convert.ToString(dateStart.Value) + "' AND '" + Convert.ToString(dateStop.Value) + "'";
</code>```

Body:
I have two DateTimePickers (dateStart and dateStop) in a winform. I've set dateStart and dateSop's format like this:

    dateStart.Format = DateTimePickerFormat.Custom;
    dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
    dateStop.Format = DateTimePickerFormat.Custom;
    dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";

I want to count number of rows from my datebase's table between dateStart and dateStop.
My select string:

string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value);

And it's result:

This is how link DateStart and DateStop paramaters of my datebase with DateTimePickers.

 cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;// new DateTime(dateStart.Value);
 cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;// new DateTime(2020, 02, 05, 13, 12, 25, 703);//2020, 02, 05, 13, 12, 25, 703   //2020, 02, 05, 13, 06, 50, 700

The row counting works perfectly without WHERE clause.

count = (int)cmdCount.ExecuteScalar();//this is how I count the rows

I'm getting here a 'System.Data.SqlClient.SqlException: Incorect syntax near 9'.

I kinda don't understand why if dateStart's format is  "yyyy:MM:dd HH:mm:ss", dateStart.value is returned in another format. On my UI, dateStart is displayed in the right format (the one from the code above). But I might have done something faulty in my stmt string.
Any thoughts on what is wrong?

EDIT 1 (my entire code):

 private void button_Click(object sender, EventArgs e)
    {
        dateStart.Format = DateTimePickerFormat.Custom;
        dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        dateStop.Format = DateTimePickerFormat.Custom;
        dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  @DataStart AND @DataStop";         // WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value)
       // string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  '" + Convert.ToString(dateStart.Value) + "' AND '" + Convert.ToString(dateStop.Value) + "'";
        int count = 0;

        using (SqlConnection connection = new SqlConnection(@"Data Source=DESKTOP-JQSJAF8\SQLEXPRESS;Initial Catalog=TRTF_TagLogging;Integrated Security=True; MultipleActiveResultSets = true"))
        {
            using (SqlCommand cmd = new SqlCommand("PS_TagLogging", connection))// used for stored proc
            {
                using (SqlCommand cmdCount = new SqlCommand(stmt, connection))//used to count number of rows of my table
                {
                    //yyyy:MM:dd hh:mm:ss
                    connection.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
                    cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
                    var values = new List<double>();
                    var valData = new List<DateTime>();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        // values.Add(reader.GetInt64(0));//reads the values of first column (ID) from DB
                        values.Add(reader.GetFloat(1));//reads the values of second column (Tag1) from DB
                        valData.Add(reader.GetDateTime(2));//reads the values of third column (DateTime) from DB
                    }

                    arrDate = valData.ToArray();
                    arrVal = values.ToArray();

                    count = (int)cmdCount.ExecuteScalar();
                    plot1.XAxes[0].ScaleDisplay.TextFormatting.Style = Iocomp.Types.TextFormatDoubleStyle.DateTime;
                    plot1.XAxes[0].ScaleRange.Span = 1.0 / 120.0 ; //30sec Span;

                    for (int i=0; i<count; i++)
                    {
                        plot1.Channels.Trace[0].AddXY(arrDate[i], arrVal[i]);
                    }

                    connection.Close();
                }
            }
        }
        MessageBox.Show("Nr. lines: " + count);
         Random().NextDouble() * 100);
    }

Body:
Everything people told is ok, but i think there are missing quotes. Try:

string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  '" + Convert.ToString(dateStart.Value) + "' AND '" + Convert.ToString(dateStop.Value) + "'";


问:
SQL query to get the latest price from the data?
I have this data in my Oracle table:

In this table, I have multiple products with having product_id and price at a particular time.

I want to write a SQL query to get latest price of each product based on the TIME column (Oracle - Long Type).

But here is the problem, for our table price monitoring for the product starts at 23:00 previous date.

Output required: when I passed 2-Dec-2019 as parameter into the SQL query

How can I do this with a SQL query? Or do I need to write a stored procedure for it, based on if and else condition?

Thanks in advance.

答:
First of all you are storing date and time separately, which makes working with the date and time more complicated than needed.

One way to combine the two:

```<code>local_date + interval '1' second * (to_number(substr(time, 5, 2)) +
                                    to_number(substr(time, 3, 2)) * 60 +
                                    to_number(substr(time, 1, 2)) * 3600)
</code>```

Another:

```<code>to_date(to_char(local_date, 'yyyymmdd') || time, 'yyyymmddhh24miss')
</code>```

With this datetime you want something along the lines of

```<code>where the_time >= timestamp '2019-12-01 23:00:00' and the_time < date '2019-12-03'
</code>```

For some date yet unknown that will be provided when running the query:

```<code>where the_time >= :date - interval '1' hour and the_time < :date + interval '1' day
</code>```

For the current day, supposing there is no future data in the table:

```<code>where the_time >= trunc(sysdate) - interval '1' hour
</code>```

As to preferring a more current datetime over an older one, use a window function, e.g. MAX OVER.

```<code>with rows_with_datetime as
(
  select
    mytable.*,
    to_date(to_char(local_date, 'yyyymmdd') || time, 'yyyymmddhh24miss') as dt
  from mytable
)
, two_days_with_maxdatetime as
(
  select
    rows_with_datetime.*,
    max(dt) over (partition by product_id order by dt) as max_dt
  from rows_with_datetime
  where dt >= trunc(sysdate) - interval '1' hour
)
select *
from two_days_with_maxdatetime
where dt = max_dt
order by product_id;
</code>```

As the datetime gets calculated, no index will be used here and the query may be quite slow accordingly. So, you should better change the data model to have a datetime you can easily index and work with instead of separate date and time. If you can't, you may want to apply an additional redundant condition on the date alone:

```<code>where local_date >= trunc(sysdate) - interval '1' day
</code>```

Body:
First of all you are storing date and time separately, which makes working with the date and time more complicated than needed.

One way to combine the two:

local_date + interval '1' second * (to_number(substr(time, 5, 2)) +
                                    to_number(substr(time, 3, 2)) * 60 +
                                    to_number(substr(time, 1, 2)) * 3600)

Another:

to_date(to_char(local_date, 'yyyymmdd') || time, 'yyyymmddhh24miss')

With this datetime you want something along the lines of

where the_time >= timestamp '2019-12-01 23:00:00' and the_time < date '2019-12-03'

For some date yet unknown that will be provided when running the query:

where the_time >= :date - interval '1' hour and the_time < :date + interval '1' day

For the current day, supposing there is no future data in the table:

where the_time >= trunc(sysdate) - interval '1' hour

As to preferring a more current datetime over an older one, use a window function, e.g. MAX OVER.

with rows_with_datetime as
(
  select
    mytable.*,
    to_date(to_char(local_date, 'yyyymmdd') || time, 'yyyymmddhh24miss') as dt
  from mytable
)
, two_days_with_maxdatetime as
(
  select
    rows_with_datetime.*,
    max(dt) over (partition by product_id order by dt) as max_dt
  from rows_with_datetime
  where dt >= trunc(sysdate) - interval '1' hour
)
select *
from two_days_with_maxdatetime
where dt = max_dt
order by product_id;

As the datetime gets calculated, no index will be used here and the query may be quite slow accordingly. So, you should better change the data model to have a datetime you can easily index and work with instead of separate date and time. If you can't, you may want to apply an additional redundant condition on the date alone:

where local_date >= trunc(sysdate) - interval '1' day


问:
Replace click-once application with msix counterpart
I'am I trying to migrate an old legacy click-once application, written in. Net and winforms. I (think) want to lift it to msix and.net core. But there is something in click-once that seems impossible to do with msix.
The list of things that msix would need to do.

Install from web page(check)

Update or forced update from "web page"(check)

Possible to uninstall from client computer (check)

Start app from web page with arguments included (no?)

And it's the last part that give me the problem. The legacy app starts with a click on a link that contains information on which circumstances it has been started. Sure this can be entered when starting program, but it seems that going from something automatic to manual, is not a thing that will be appreciated.
Is this possible to autostart app with arguments?
What should look at?

答:
The MSIX shortcut arguments is a hot topic for the MSIX team. Multiple users have requested improvements, starting with support for command-line arguments. They promised to bring some native support in future releases.

Until then, you can partially address your scenario with workarounds, like the one we implemented in Advanced Installer (i.e. use a stub to pass the argument to your shortcut target). Many similar tools should provide this support by now, not just Advanced Installer.

However, this gives you a fixed command line for your shortcut. You cannot customize it from a download link on your website (if I understand correctly your requirement).

Here are more related topics on migrating from ClickOnce to MSIX:

Can a MSIX package use an external file for user settings?

How to create an MSIX package for WinForms app?

Disclaimer: I work on the team building Advanced Installer.


问:
How calling a column in a function is different from calling a column outside in pandas dataframe?
```<code>df=pd.DataFrame({"Age":[11,12,14,15,np.NaN,np.NaN],"Class":[10,11,10,11,9,9]})
df

def impute_age(cols):
    Age = cols[0]
    Class = cols[1]

    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age

df.apply(impute_age,axis=1)
</code>```

<p>Here in this impute_age function, it called first row as cols[0],but if we call a column of a dataframe outside the funcion by using cols[0], it will show error because we have to specify the column name. Why? </p>

答:
If check print(cols) it return each row of DataFrame like Series, so if want select by position use iat:

```<code>def impute_age(cols):
    print (cols)
    Age = cols.iat[0]
    Class = cols.iat[1]
    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age
</code>```

Or select by column name:

```<code>def impute_age(cols):
    print (cols)
    Age = cols['Age']
    Class = cols['Class']
    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age
</code>```

```<code>df = df.apply(impute_age,axis=1)
</code>```

Body:
df=pd.DataFrame({"Age":[11,12,14,15,np.NaN,np.NaN],"Class":[10,11,10,11,9,9]})
df

def impute_age(cols):
    Age = cols[0]
    Class = cols[1]

    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age

df.apply(impute_age,axis=1)

Here in this impute_age function, it called first row as cols[0],but if we call a column of a dataframe outside the funcion by using cols[0], it will show error because we have to specify the column name. Why?

Body:
If check print(cols) it return each row of DataFrame like Series, so if want select by position use iat:

def impute_age(cols):
    print (cols)
    Age = cols.iat[0]
    Class = cols.iat[1]
    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age

Or select by column name:

def impute_age(cols):
    print (cols)
    Age = cols['Age']
    Class = cols['Class']
    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age

df = df.apply(impute_age,axis=1)