问:
Running winform application without .net framework
am developing a flash copy protect software with c#. The software is to remain on the flash drive(can not be transfered out or installed in the computer), it is a click and run software, no installation. I know that for it to work on other computers, the computer must have .net framework installed in it.  I was thinking if it can be possible to add .net framework dll to the startup path of the application. If it will work, pls let me know and how to do it.

If there are other methods besides switching my project to C or C++, pls let me know. Thanks.

答:
In normal .NET compilation (regardless of source language), the product is a (MS)IL - (Microsoft) Intermediate Language - dll. In case of executeables, it is given some native bootstrap code, a entry point, but it is still stricly tied to the Framework installation and works for nearly everything like a .NET dll. The Framework has to do the final IL -> Native Code translation. IL is a concept very similar to Java Bytecode, but with about 5 years of what works and does not work in Java.

.NET Native does not compile IL. It compiles hard, native code. Similar to the one any Native C++ (not to be mistaken with C++ .NET) compiler would make. The same a Delphi compiler would make. The same the Framework itself is written in. The final programm will have local copies of all the .NET .dll's it accesses. It is fully independant of any .NET Framework installation.


来源: stackexchange

问:
conditional formatting by comparing dynamic values : Excel
My code :

=IF(AND(B2="Lodavan-Boleropickup",C2<"30"),CELL("color",D2),"")

It didn't work.

Please refer the below table. I need to highlight the cells under "Mileage" column.

Example:

"Lodavan-Boleropickup" (target mileage is 30) I need to highlight the cells in "Mileage" column which are below 44. "Suzuki-Fabric" (target mileage is 50) I need to highlight the cells in "Mileage" column which are below 55.

The condition is it has to refer the column "Vehicle Name" and then check the value "Mileage", then it has to compare with the target value and then highlight. Any possible easy way is fine.

Either compare the pre-defined table like:

My requirement: If the variable from "Vehicle Name" column is "Loadvan-Boleropicup" Then it has to compare the value from "Mileage column" with the "Target" which we need to define and then it has to highlight the cells.

答:
may be these two solutions help you:

solution 1)
insert a column named selected_names in first table and write this formula in first cell init and fill-down to copy.
=SetColor(IF(INDEX($C$2:$C$12;MATCH(F2;$B$2:$B$12;0))>G2;F2;"");IF(INDEX($C$2:$C$12;MATCH(F2;$B$2:$B$12;0))>G2;F2;""))

and you need write this function in VBA editor:

```<code>    Option Explicit

    Declare PtrSafe Function SetTimer Lib "user32" (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr, ByVal uElapse As Long, ByVal lpTimerFunc As LongPtr) As LongPtr
    Declare PtrSafe Function KillTimer Lib "user32" (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr) As Long
    Declare PtrSafe Function GlobalAddAtom Lib "kernel32" Alias "GlobalAddAtomA" (ByVal lpString As String) As Integer
    Declare PtrSafe Function GlobalGetAtomName Lib "kernel32" Alias "GlobalGetAtomNameA" (ByVal nAtom As Integer, ByVal lpBuffer As String, ByVal nSize As Long) As Long

Public Function SetColor(ByVal Value As Variant, ByVal BackGroundColor As String) As Variant
    SetTimer Application.hwnd, GlobalAddAtom(Application.Caller.Address(External:=True) & "*" & BackGroundColor), 0, AddressOf ChangeColor
    SetColor = Value
End Function

Sub ChangeColor(ByVal hwnd As Long, ByVal uMsg As Long, ByVal nIDEvent As Long, ByVal dwTimer As Long)
    Dim sBuffer As String, lRet As Long, lColorIndex As Long

    On Error Resume Next
    KillTimer hwnd, nIDEvent
    sBuffer = Space(256)
    lRet = GlobalGetAtomName(nIDEvent, sBuffer, Len(sBuffer))
    sBuffer = Left(sBuffer, lRet)
    Select Case LCase(Split(sBuffer, "*")(1))
        Case "name1"
            lColorIndex = 17
        Case "name2"
            lColorIndex = 18
        Case "name3"
            lColorIndex = 19
        Case "name4"
            lColorIndex = 20
        Case "name5"
            lColorIndex = 21
        Case "name6"
            lColorIndex = 22
        Case "name7"
            lColorIndex = 23
        Case "name8"
            lColorIndex = 24
        Case "name9"
            lColorIndex = 25
        Case "name10"
            lColorIndex = 26
        Case "name11"
            lColorIndex = 27
        Case ""
            lColorIndex = xlColorIndexNone
    End Select
    Range(Split(sBuffer, "*")(0)).Interior.colorIndex = lColorIndex
End Sub
</code>```

refrence link for setting cell color :https://www.mrexcel.com/board/threads/change-cell-color-inside-formula.1050178/

solution 2)
you can insert column selected_names and use this formula in first cell and fill-down to copy to all cells.
=IF(INDEX($C$2:$C$12;MATCH(F2;$B$2:$B$12;0))>G2;F2;"")
all conditional rows will be marked, then you can filter them by similar name, and no need to VBA function for coloring match names (this way is better in my idea).

ContentLicense: CC BY-SA 4.0

Body:
may be these two solutions help you:

solution 1)
insert a column named selected_names in first table and write this formula in first cell init and fill-down to copy.
=SetColor(IF(INDEX($C$2:$C$12;MATCH(F2;$B$2:$B$12;0))>G2;F2;"");IF(INDEX($C$2:$C$12;MATCH(F2;$B$2:$B$12;0))>G2;F2;""))

and you need write this function in VBA editor:

    Option Explicit

    Declare PtrSafe Function SetTimer Lib "user32" (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr, ByVal uElapse As Long, ByVal lpTimerFunc As LongPtr) As LongPtr
    Declare PtrSafe Function KillTimer Lib "user32" (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr) As Long
    Declare PtrSafe Function GlobalAddAtom Lib "kernel32" Alias "GlobalAddAtomA" (ByVal lpString As String) As Integer
    Declare PtrSafe Function GlobalGetAtomName Lib "kernel32" Alias "GlobalGetAtomNameA" (ByVal nAtom As Integer, ByVal lpBuffer As String, ByVal nSize As Long) As Long

Public Function SetColor(ByVal Value As Variant, ByVal BackGroundColor As String) As Variant
    SetTimer Application.hwnd, GlobalAddAtom(Application.Caller.Address(External:=True) & "*" & BackGroundColor), 0, AddressOf ChangeColor
    SetColor = Value
End Function

Sub ChangeColor(ByVal hwnd As Long, ByVal uMsg As Long, ByVal nIDEvent As Long, ByVal dwTimer As Long)
    Dim sBuffer As String, lRet As Long, lColorIndex As Long

    On Error Resume Next
    KillTimer hwnd, nIDEvent
    sBuffer = Space(256)
    lRet = GlobalGetAtomName(nIDEvent, sBuffer, Len(sBuffer))
    sBuffer = Left(sBuffer, lRet)
    Select Case LCase(Split(sBuffer, "*")(1))
        Case "name1"
            lColorIndex = 17
        Case "name2"
            lColorIndex = 18
        Case "name3"
            lColorIndex = 19
        Case "name4"
            lColorIndex = 20
        Case "name5"
            lColorIndex = 21
        Case "name6"
            lColorIndex = 22
        Case "name7"
            lColorIndex = 23
        Case "name8"
            lColorIndex = 24
        Case "name9"
            lColorIndex = 25
        Case "name10"
            lColorIndex = 26
        Case "name11"
            lColorIndex = 27
        Case ""
            lColorIndex = xlColorIndexNone
    End Select
    Range(Split(sBuffer, "*")(0)).Interior.colorIndex = lColorIndex
End Sub

refrence link for setting cell color :https://www.mrexcel.com/board/threads/change-cell-color-inside-formula.1050178/

solution 2)
you can insert column selected_names and use this formula in first cell and fill-down to copy to all cells.
=IF(INDEX($C$2:$C$12;MATCH(F2;$B$2:$B$12;0))>G2;F2;"")
all conditional rows will be marked, then you can filter them by similar name, and no need to VBA function for coloring match names (this way is better in my idea).


问:
networkx - change color/width according to edge attributes - inconsistent result
I managed to produce the graph correctly, but with some more testing noted inconsistent result for the following two different line of codes:

```<code>colors = [h.edge[i][j]['color'] for (i,j) in h.edges_iter()]
widths = [h.edge[i][j]['width'] for (i,j) in h.edges_iter()]
nx.draw_circular(h, edge_color=colors, width=widths)
</code>```

This approach results in consistent output, while the following produces wrong color/size per the orders of edges:

```<code>colors = list(nx.get_edge_attributes(h,'color').values())
widths = list(nx.get_edge_attributes(h,'width').values())
nx.draw_circular(h, edge_color=colors, width=widths)
</code>```

However, it looks to me the above two lines both rely on the function call to return the attributes per the order of edges. Why the different results?

It looks a bit clumsy to me to access attributes with  h[][][]; is it possible to access it by dot convention, e.g. edge.color for edge in h.edges().

Or did I miss anything?

答:
Dictionaries are the underlying data structure used for NetworkX graphs, and as of Python 3.7+ they maintain insertion order.
This means that we can safely use nx.get_edge_attributes to retrieve edge attributes since we are guaranteed to have the same edge order in every run of Graph.edges() (which is internally called by get_edge_attributes).

So when plotting, we can directly set attributes such as edge_color and width from the result returned by get_edge_attributes. Here's an example:

```<code>G = nx.Graph()
G.add_edge(0,1,color='r',weight=2)
G.add_edge(1,2,color='g',weight=4)
G.add_edge(2,3,color='b',weight=6)
G.add_edge(3,4,color='y',weight=3)
G.add_edge(4,0,color='m',weight=1)

colors = nx.get_edge_attributes(G,'color').values()
weights = nx.get_edge_attributes(G,'weight').values()

pos = nx.circular_layout(G)
nx.draw(G, pos,
        edge_color=colors,
        width=list(weights),
        with_labels=True,
        node_color='lightgreen')
</code>```

Body:
I managed to produce the graph correctly, but with some more testing noted inconsistent result for the following two different line of codes:

colors = [h.edge[i][j]['color'] for (i,j) in h.edges_iter()]
widths = [h.edge[i][j]['width'] for (i,j) in h.edges_iter()]
nx.draw_circular(h, edge_color=colors, width=widths)

This approach results in consistent output, while the following produces wrong color/size per the orders of edges:

colors = list(nx.get_edge_attributes(h,'color').values())
widths = list(nx.get_edge_attributes(h,'width').values())
nx.draw_circular(h, edge_color=colors, width=widths)

However, it looks to me the above two lines both rely on the function call to return the attributes per the order of edges. Why the different results?

It looks a bit clumsy to me to access attributes with  h[][][]; is it possible to access it by dot convention, e.g. edge.color for edge in h.edges().

Or did I miss anything?

Body:
Dictionaries are the underlying data structure used for NetworkX graphs, and as of Python 3.7+ they maintain insertion order.
This means that we can safely use nx.get_edge_attributes to retrieve edge attributes since we are guaranteed to have the same edge order in every run of Graph.edges() (which is internally called by get_edge_attributes).

So when plotting, we can directly set attributes such as edge_color and width from the result returned by get_edge_attributes. Here's an example:

G = nx.Graph()
G.add_edge(0,1,color='r',weight=2)
G.add_edge(1,2,color='g',weight=4)
G.add_edge(2,3,color='b',weight=6)
G.add_edge(3,4,color='y',weight=3)
G.add_edge(4,0,color='m',weight=1)

colors = nx.get_edge_attributes(G,'color').values()
weights = nx.get_edge_attributes(G,'weight').values()

pos = nx.circular_layout(G)
nx.draw(G, pos,
        edge_color=colors,
        width=list(weights),
        with_labels=True,
        node_color='lightgreen')


问:
How to take unique IDs and convert each row of another column into another column in R and Python
My data has the form:

```<code>groups <- c("4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)
</code>```

How do I get this?:

```<code>ID       col_1   col_2   col_3   col_4     col_5
samp_1   4       4.2     4.2.1   4.2.1.1   NA
samp_2   1       1.2     1.2.1   1.2.1.2   1.2.1.2.1
</code>```

Each column will be determined by the length of the string, so all data in column 4 will have length 4 (or length 7 including the dots).

I am looking for the most general solution to this (e.g. using loops; using as few packages as possible) because I need to implement this in both R and Python.

答:
You can try this in python:

```<code>import pandas as pd
import numpy as np
df= pd.DataFrame({'ID':np.repeat(["samp_1","samp_2"],[4,5]),
                 'groups':["4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1"],})
df['entry']=df.groupby(['ID']).cumcount()+1
</code>```

We provide like a number per group, and add it as entry column. Below we do pivoting like in R, with that column to provide the column names, and last we reset the index:

```<code>df.pivot(values='groups',columns='entry',index='ID').reset_index()

entry   ID  1   2   3   4   5
0   samp_1  4   4.2 4.2.1   4.2.1.1 NaN
1   samp_2  1   1.2 1.2.1   1.2.1.2 1.2.1.2.1
</code>```

Body:
My data has the form:

groups <- c("4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)

How do I get this?:

ID       col_1   col_2   col_3   col_4     col_5
samp_1   4       4.2     4.2.1   4.2.1.1   NA
samp_2   1       1.2     1.2.1   1.2.1.2   1.2.1.2.1

Each column will be determined by the length of the string, so all data in column 4 will have length 4 (or length 7 including the dots).

I am looking for the most general solution to this (e.g. using loops; using as few packages as possible) because I need to implement this in both R and Python.

Body:
You can try this in python:

import pandas as pd
import numpy as np
df= pd.DataFrame({'ID':np.repeat(["samp_1","samp_2"],[4,5]),
                 'groups':["4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1"],})
df['entry']=df.groupby(['ID']).cumcount()+1

We provide like a number per group, and add it as entry column. Below we do pivoting like in R, with that column to provide the column names, and last we reset the index:

df.pivot(values='groups',columns='entry',index='ID').reset_index()

entry   ID  1   2   3   4   5
0   samp_1  4   4.2 4.2.1   4.2.1.1 NaN
1   samp_2  1   1.2 1.2.1   1.2.1.2 1.2.1.2.1


问:
How to remove response headers when sending a json response in php?
I am making an ajax request to a php page e.g page1.php. In page1.php I have a header("Location:page2.php?password=1234") code which redirects to page2.php with the password as a GET parameter. page2.php gives a json response.
The problem is that when I do inspect element and check the resources in Safari browser, I am able to see the location page2.php?password=1234" in the response header part.
This is a security issue. Please suggest how can I remove the response headers when sending the json response? I am using PHP 5.2.6.

答: Why just don't use SESSION for logged user? Or plain simple Cookie?</p>

ContentLicense: CC BY-SA 3.0


问:
Spring security session timeout for spring reactive
I have a Reactive Application with Spring Security integrated, it was created by spring initilizer with mainly thre3 packages(spring boot, spring security and webflux).

I was trying to configure the session timeout by following configuration in application.properties:

```<code>spring.session.timeout=1m
</code>```

after starting the application with mvn spring-boot:run, It can be accessed by http://localhost:8080 and it asked me to login(by default security setting). I can use the username user and the password generated on the console to login.

Per my configuration, I expected that after 1 minutes idle time, when I refresh the page http://localhost:8080 again, it can ask me to re-login. But in fact it didn't , until 30 minutes later

So I suspect the above configuration is not working

Did I used the wrong configuration?

the reproduce repo can be found here: https://github.com/ZhuBicen/ReactiveSpringSecurity.git

答:
The parameter you have configured has nothing to do with the cookie session you have with the web-browser.

That parameter configures Spring Session which is a way to handle session between services, rest api's and such by providing a session through a header.

https://spring.io/projects/spring-session

Session cookies are historically bound to threads in threadlocal, which doesn't work in reactive applications. So in order to store sessions, you need be able to store the sessions somewhere else. Redis is one example ofwhere you can store websessions.

Here is a tutorial of using webflux, redis and spring session to manage websessions.

https://www.baeldung.com/spring-session-reactive

Body:
I have a Reactive Application with Spring Security integrated, it was created by spring initilizer with mainly thre3 packages(spring boot, spring security and webflux).

I was trying to configure the session timeout by following configuration in application.properties:

spring.session.timeout=1m

after starting the application with mvn spring-boot:run, It can be accessed by http://localhost:8080 and it asked me to login(by default security setting). I can use the username user and the password generated on the console to login.

Per my configuration, I expected that after 1 minutes idle time, when I refresh the page http://localhost:8080 again, it can ask me to re-login. But in fact it didn't , until 30 minutes later

So I suspect the above configuration is not working

Did I used the wrong configuration?

the reproduce repo can be found here: https://github.com/ZhuBicen/ReactiveSpringSecurity.git


问:
Azure Data Factory Rest API pagination issue
I am new to Azure Data Factory and i am trying to copy data from JIRA to Azure Storage using Data Factory.
I am trying the JIRA REST API to fetch the data, but unfortunately i am struggling with pagination. Can Someone help me how to use the pagination in this case.

Request URL:
https://jira.abc.com/rest/api/3/search?jql=&startAt=0&maxResult=10

Sample response from JIRA:

```<code>{
    "startAt" : 0,
    "maxResults" : 10,
    "total": 200,
    "isLast": false,
    "values": [
        { /* result 0 */ },
        { /* result 1 */ },
        { /* result 2 */ }
    ]
}
</code>```

答:
Click on the Copy Data activity (the block) in your pipeline

Click on
the Source tab

Scroll down to Pagination rules and click the plus
sign to add a rule

As highlighted below, put AbsoluteURL in the first box
and then, for JIRA it appears (according to their docs) that you need to put $._links.next instead of $.next_page in my screenshot.  (This is the reference to the part of the JSON doc returned by JIRA containing the URL of the next page.)

Please comment if it works for you.

Refs:

MS data factory docs

JIRA API docs

Body:
I am new to Azure Data Factory and i am trying to copy data from JIRA to Azure Storage using Data Factory.
I am trying the JIRA REST API to fetch the data, but unfortunately i am struggling with pagination. Can Someone help me how to use the pagination in this case.

Request URL:
https://jira.abc.com/rest/api/3/search?jql=&startAt=0&maxResult=10

Sample response from JIRA:

{
    "startAt" : 0,
    "maxResults" : 10,
    "total": 200,
    "isLast": false,
    "values": [
        { /* result 0 */ },
        { /* result 1 */ },
        { /* result 2 */ }
    ]
}


问:
Faster way to sort the array by finding the position of the first non-zero element in each row
I have a matrix in which I would like to sort this matrix based on the position of the first non-zero element in each row. For example, I would like to rearrange A in to B.

```<code>import numpy as np

A = np.array([[0, 0, 8, 7, 8],
              [0, 2, 2, 8, 9],
              [0, 0, 0, 6, 10],
              [5, 4, 4, 8, 10]])

B = np.array([[5, 4, 4, 8, 10],
              [0, 2, 2, 8, 9],
              [0, 0, 8, 7, 8],
              [0, 0, 0, 6, 10]])
</code>```

To do so, I first find the position of the first non-zero element in each row: I first define the function position and then rearrange A based the permutation position(A).

```<code>def position(A):
    num_rows = A.shape[0]
    num_cols = A.shape[1]
    B = np.zeros(num_rows)
    # Access each row
    for i in range(num_rows):
      # Find the position of the first non-zero element
      for j in range(num_cols):
        if A[i, j] != 0:
          break
      B[i] = j
    return B

position(A)

array([2., 1., 3., 0.])
</code>```

My matrix is of very large dimension and the procedure is repeated several times. My function position contains loops that I think could be replaced with more optimized code.

I would like to ask for a faster way to achieve my goal. Thank you so much!

Body:
I have a matrix in which I would like to sort this matrix based on the position of the first non-zero element in each row. For example, I would like to rearrange A in to B.

import numpy as np

A = np.array([[0, 0, 8, 7, 8],
              [0, 2, 2, 8, 9],
              [0, 0, 0, 6, 10],
              [5, 4, 4, 8, 10]])

B = np.array([[5, 4, 4, 8, 10],
              [0, 2, 2, 8, 9],
              [0, 0, 8, 7, 8],
              [0, 0, 0, 6, 10]])

To do so, I first find the position of the first non-zero element in each row: I first define the function position and then rearrange A based the permutation position(A).

def position(A):
    num_rows = A.shape[0]
    num_cols = A.shape[1]
    B = np.zeros(num_rows)
    # Access each row
    for i in range(num_rows):
      # Find the position of the first non-zero element
      for j in range(num_cols):
        if A[i, j] != 0:
          break
      B[i] = j
    return B

position(A)

array([2., 1., 3., 0.])

My matrix is of very large dimension and the procedure is repeated several times. My function position contains loops that I think could be replaced with more optimized code.

I would like to ask for a faster way to achieve my goal. Thank you so much!

Body:
One way based on masking and argsort -

In [58]: m = A!=0

In [59]: A[m.argmax(1).argsort()]
Out[59]:
array([[ 5,  4,  4,  8, 10],
       [ 0,  2,  2,  8,  9],
       [ 0,  0,  8,  7,  8],
       [ 0,  0,  0,  6, 10]])

If any row has all 0s, we need to modify the last step like so -

In [41]: A[0] = 0

In [42]: A[np.where(m.any(1),m.argmax(1),m.shape[1]-1).argsort()]
Out[42]:
array([[ 5,  4,  4,  8, 10],
       [ 0,  2,  2,  8,  9],
       [ 0,  0,  0,  6, 10],
       [ 0,  0,  0,  0,  0]])


问:
ASP.NET WebApi2 OData handling of queries with slash /
I have made a "standard" Web Api 2 OData project with convention model routing. Following OData queries are working:

/odata/Users

/odata/Users(123)

/odata/$metadata

/odata/Users?$select=Username

So everything seemed to be fine until I tried this, which I think is also a legal OData query:

/odata/Users(123)/Username

Slash / in query breaks everything and it does not hit the controller class and OData authentication flow at all. Should this be supported at all in Microsoft ASP.NET OData implementation? Or is this supported only if I define explicit methods with correct routes for every single property like Username? Any suggestions to fix this? I have tried explicit {*rest} routes etc.

答:
AFAIK, the built-in routing conventions don't include one for property access. You'd be required to add many actions for every property access.

However, based on this resource here, it's not all that difficult to add a custom routing convention to handle the property access path template: ~/entityset/key/property

Here's a custom routing convention adapted from the link I shared above

Assembly used: Microsoft.AspNet.OData 7.4.1 - the approach would be the same for any other OData Web API library you might be using

Class used for illustration

public class Product
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}
```

<p>Add routing convention for property access</p>

<pre class="lang-cs prettyprint-override"><code>// Usings
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNet.OData.Routing.Conventions;
using System;
using System.Linq;
using System.Web.Http.Controllers;
// ...

public class CustomPropertyRoutingConvention : NavigationSourceRoutingConvention
{
    private const string ActionName = "GetProperty";

    public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
    {
        if (odataPath == null || controllerContext == null || actionMap == null)
        {
            return null;
        }

        if (odataPath.PathTemplate == "~/entityset/key/property" ||
            odataPath.PathTemplate == "~/entityset/key/cast/property" ||
            odataPath.PathTemplate == "~/singleton/property" ||
            odataPath.PathTemplate == "~/singleton/cast/property")
        {
            var segment = odataPath.Segments.OfType<Microsoft.OData.UriParser.PropertySegment>().LastOrDefault();

            if (segment != null)
            {
                string actionName = FindMatchingAction(actionMap, ActionName);

                if (actionName != null)
                {
                    if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
                    {
                        var keySegment = odataPath.Segments.OfType<Microsoft.OData.UriParser.KeySegment>().FirstOrDefault();
                        if (keySegment == null || !keySegment.Keys.Any())
                            throw new InvalidOperationException("This link does not contain a key.");

                        controllerContext.RouteData.Values[ODataRouteConstants.Key] = keySegment.Keys.First().Value;
                    }

                    controllerContext.RouteData.Values["propertyName"] = segment.Property.Name;

                    return actionName;
                }
            }
        }

        return null;
    }

    public static string FindMatchingAction(ILookup<string, HttpActionDescriptor> actionMap, params string[] targetActionNames)
    {
        foreach (string targetActionName in targetActionNames)
        {
            if (actionMap.Contains(targetActionName))
            {
                return targetActionName;
            }
        }

        return null;
    }
}
</code>```

Add single method in your controller to handle request for any property

public class ProductsController : ODataController
{
    // ...
    [HttpGet]
    public IHttpActionResult GetProperty(int key, string propertyName)
    {
        var product = _db.Products.FirstOrDefault(d => d.Id.Equals(key));
        if (product == null)
        {
            return NotFound();
        }

        PropertyInfo info = typeof(Product).GetProperty(propertyName);

        object value = info.GetValue(product);

        return Ok(value, value.GetType());
    }

    private IHttpActionResult Ok(object content, Type type)
    {
        var resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);
        return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;
    }
    // ...
}
```

<p>In your <em>WebApiConfig.cs</em> (or equivalent place where you configure the service)</p>

<pre class="lang-cs prettyprint-override"><code>var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Product>("Products");

var routingConventions = ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata", configuration);
routingConventions.Insert(0, new CustomPropertyRoutingConvention());

configuration.MapODataServiceRoute("odata", "odata", modelBuilder.GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
configuration.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
configuration.EnsureInitialized();
</code>```

Request for Name property: /Products(1)/Name

Request for Id property: /Products(1)/Id

Body:
AFAIK, the built-in routing conventions don't include one for property access. You'd be required to add many actions for every property access.

However, based on this resource here, it's not all that difficult to add a custom routing convention to handle the property access path template: ~/entityset/key/property

Here's a custom routing convention adapted from the link I shared above

Assembly used: Microsoft.AspNet.OData 7.4.1 - the approach would be the same for any other OData Web API library you might be using

Class used for illustration

public class Product
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

Add routing convention for property access

// Usings
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNet.OData.Routing.Conventions;
using System;
using System.Linq;
using System.Web.Http.Controllers;
// ...

public class CustomPropertyRoutingConvention : NavigationSourceRoutingConvention
{
    private const string ActionName = "GetProperty";

    public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
    {
        if (odataPath == null || controllerContext == null || actionMap == null)
        {
            return null;
        }

        if (odataPath.PathTemplate == "~/entityset/key/property" ||
            odataPath.PathTemplate == "~/entityset/key/cast/property" ||
            odataPath.PathTemplate == "~/singleton/property" ||
            odataPath.PathTemplate == "~/singleton/cast/property")
        {
            var segment = odataPath.Segments.OfType<Microsoft.OData.UriParser.PropertySegment>().LastOrDefault();

            if (segment != null)
            {
                string actionName = FindMatchingAction(actionMap, ActionName);

                if (actionName != null)
                {
                    if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
                    {
                        var keySegment = odataPath.Segments.OfType<Microsoft.OData.UriParser.KeySegment>().FirstOrDefault();
                        if (keySegment == null || !keySegment.Keys.Any())
                            throw new InvalidOperationException("This link does not contain a key.");

                        controllerContext.RouteData.Values[ODataRouteConstants.Key] = keySegment.Keys.First().Value;
                    }

                    controllerContext.RouteData.Values["propertyName"] = segment.Property.Name;

                    return actionName;
                }
            }
        }

        return null;
    }

    public static string FindMatchingAction(ILookup<string, HttpActionDescriptor> actionMap, params string[] targetActionNames)
    {
        foreach (string targetActionName in targetActionNames)
        {
            if (actionMap.Contains(targetActionName))
            {
                return targetActionName;
            }
        }

        return null;
    }
}

Add single method in your controller to handle request for any property

public class ProductsController : ODataController
{
    // ...
    [HttpGet]
    public IHttpActionResult GetProperty(int key, string propertyName)
    {
        var product = _db.Products.FirstOrDefault(d => d.Id.Equals(key));
        if (product == null)
        {
            return NotFound();
        }

        PropertyInfo info = typeof(Product).GetProperty(propertyName);

        object value = info.GetValue(product);

        return Ok(value, value.GetType());
    }

    private IHttpActionResult Ok(object content, Type type)
    {
        var resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);
        return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;
    }
    // ...
}

In your WebApiConfig.cs (or equivalent place where you configure the service)

var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Product>("Products");

var routingConventions = ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata", configuration);
routingConventions.Insert(0, new CustomPropertyRoutingConvention());

configuration.MapODataServiceRoute("odata", "odata", modelBuilder.GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
configuration.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
configuration.EnsureInitialized();

Request for Name property: /Products(1)/Name

Request for Id property: /Products(1)/Id


问:
Sorting a list out with several parameters
I have spent the whole afternoon trying to figure this out... but I can't! I have a DataFrame that needs to be sorted in a specific way. This is from census data in the US. I have first reduced the list by filtering through county level (SUMLEV = 50). I think that's the only part of the code I got right (I think). Then I need to grab the three most populous counties for each state. However, I do not need all the states to display. Those three values representing the most populous counties will have to be summed to display the three most populous states based on the three most populous counties. Phew! Sorry for the long explanation. Here's the code:

```<code>SUMLEV  REGION  DIVISION    STATE   COUNTY  STNAME  CTYNAME CENSUS2010POP   ESTIMATESBASE2010   POPESTIMATE2010 ... RDOMESTICMIG2011    RDOMESTICMIG2012    RDOMESTICMIG2013    RDOMESTICMIG2014    RDOMESTICMIG2015    RNETMIG2011 RNETMIG2012 RNETMIG2013 RNETMIG2014 RNETMIG2015
0   40  3   6   1   0   Alabama Alabama 4779736 4780127 4785161 ... 0.002295    -0.193196   0.381066    0.582002    -0.467369   1.030015    0.826644    1.383282    1.724718    0.712594
1   50  3   6   1   1   Alabama Autauga County  54571   54571   54660   ... 7.242091    -2.915927   -3.012349   2.265971    -2.530799   7.606016    -2.626146   -2.722002   2.592270    -2.187333
2   50  3   6   1   3   Alabama Baldwin County  182265  182265  183193  ... 14.832960   17.647293   21.845705   19.243287   17.197872   15.844176   18.559627   22.727626   20.317142   18.293499
3   50  3   6   1   5   Alabama Barbour County  27457   27457   27341   ... -4.728132   -2.500690   -7.056824   -3.904217   -10.543299  -4.874741   -2.758113   -7.167664   -3.978583   -10.543299
4   50  3   6   1   7   Alabama Bibb County 22915
</code>```

And this the code I started (gives an error):

```<code>census_df[census_df['SUMLEV'] == 50].groupby('CTYNAME')['STNAME'].apply(pd.DataFrame.sort_values, 'CENSUS2010POP', ascending=False)
</code>```

答:
Some usable sample data:

```<code>   SUMLEV  REGION  DIVISION  STATE  COUNTY   STNAME         CTYNAME  CENSUS2010POP
0      40       3         6      1       0  Alabama         Alabama        4779736
1      50       3         6      1       1  Alabama  Autauga County          54571
2      50       3         6      1       3  Alabama  Baldwin County         182265
3      50       3         6      1       5  Alabama  Barbour County          27457
4      50       3         6      1       7  Alabama     Bibb County          22915
5      50       4         5      6       7  Florida      Miami-Dade          44567
</code>```

The Code:

```<code>df = df[df['SUMLEV']==50].sort_values(by='CENSUS2010POP', ascending=False).groupby('STATE').apply(lambda x:x.head(3))

df = df.reset_index(drop=True)

df = df.groupby('STNAME')['CENSUS2010POP'].sum().reset_index().sort_values(by='CENSUS2010POP', ascending=False)

df.head(3)
</code>```

Output

```<code>   STNAME          CENSUS2010POP
0  Alabama         264293
1  Florida          44567
</code>```

Body:
I have spent the whole afternoon trying to figure this out... but I can't! I have a DataFrame that needs to be sorted in a specific way. This is from census data in the US. I have first reduced the list by filtering through county level (SUMLEV = 50). I think that's the only part of the code I got right (I think). Then I need to grab the three most populous counties for each state. However, I do not need all the states to display. Those three values representing the most populous counties will have to be summed to display the three most populous states based on the three most populous counties. Phew! Sorry for the long explanation. Here's the code:

SUMLEV  REGION  DIVISION    STATE   COUNTY  STNAME  CTYNAME CENSUS2010POP   ESTIMATESBASE2010   POPESTIMATE2010 ... RDOMESTICMIG2011    RDOMESTICMIG2012    RDOMESTICMIG2013    RDOMESTICMIG2014    RDOMESTICMIG2015    RNETMIG2011 RNETMIG2012 RNETMIG2013 RNETMIG2014 RNETMIG2015
0   40  3   6   1   0   Alabama Alabama 4779736 4780127 4785161 ... 0.002295    -0.193196   0.381066    0.582002    -0.467369   1.030015    0.826644    1.383282    1.724718    0.712594
1   50  3   6   1   1   Alabama Autauga County  54571   54571   54660   ... 7.242091    -2.915927   -3.012349   2.265971    -2.530799   7.606016    -2.626146   -2.722002   2.592270    -2.187333
2   50  3   6   1   3   Alabama Baldwin County  182265  182265  183193  ... 14.832960   17.647293   21.845705   19.243287   17.197872   15.844176   18.559627   22.727626   20.317142   18.293499
3   50  3   6   1   5   Alabama Barbour County  27457   27457   27341   ... -4.728132   -2.500690   -7.056824   -3.904217   -10.543299  -4.874741   -2.758113   -7.167664   -3.978583   -10.543299
4   50  3   6   1   7   Alabama Bibb County 22915

And this the code I started (gives an error):

census_df[census_df['SUMLEV'] == 50].groupby('CTYNAME')['STNAME'].apply(pd.DataFrame.sort_values, 'CENSUS2010POP', ascending=False)

Body:
Some usable sample data:

   SUMLEV  REGION  DIVISION  STATE  COUNTY   STNAME         CTYNAME  CENSUS2010POP
0      40       3         6      1       0  Alabama         Alabama        4779736
1      50       3         6      1       1  Alabama  Autauga County          54571
2      50       3         6      1       3  Alabama  Baldwin County         182265
3      50       3         6      1       5  Alabama  Barbour County          27457
4      50       3         6      1       7  Alabama     Bibb County          22915
5      50       4         5      6       7  Florida      Miami-Dade          44567

The Code:

df = df[df['SUMLEV']==50].sort_values(by='CENSUS2010POP', ascending=False).groupby('STATE').apply(lambda x:x.head(3))

df = df.reset_index(drop=True)

df = df.groupby('STNAME')['CENSUS2010POP'].sum().reset_index().sort_values(by='CENSUS2010POP', ascending=False)

df.head(3)

Output

   STNAME          CENSUS2010POP
0  Alabama         264293
1  Florida          44567


问:
packet_write_wait: Connection to xxx.xxx.xxx.xxx: Broken pipe
What does it mean when the terminal throw this error and how to solve it?

```<code>packet_write_wait: Connection to xxx.xxx.xxx.xxx: Broken pipe
</code>```

It was just happen today. After it work normally for year.
My terminal keep disconnect at a certain time. I had already search on google but most of it is about   "Write failed: Broken pipe."

Which I already solved that for years. I just found this new annoyed problems today

答:
ServerAliveInterval seems to be the most common strategy to keep a connection alive. To prevent the broken pipe problem, here is the ssh config I useed in my .ssh/ssh_config file (may be named as /etc/ssh/config or sshd_config):

```<code>Host myhostshortcut
     HostName myhost.com
     User barthelemy
     ServerAliveInterval 60
     ServerAliveCountMax 10
</code>```

Body:
What does it mean when the terminal throw this error and how to solve it?

packet_write_wait: Connection to xxx.xxx.xxx.xxx: Broken pipe

It was just happen today. After it work normally for year.
My terminal keep disconnect at a certain time. I had already search on google but most of it is about   "Write failed: Broken pipe."

Which I already solved that for years. I just found this new annoyed problems today

Body:
ServerAliveInterval seems to be the most common strategy to keep a connection alive. To prevent the broken pipe problem, here is the ssh config I useed in my .ssh/ssh_config file (may be named as /etc/ssh/config or sshd_config):

Host myhostshortcut
     HostName myhost.com
     User barthelemy
     ServerAliveInterval 60
     ServerAliveCountMax 10


问:
KotlinNullPointerException In toLedgerTransaction()
What reasons can be, that i get KotlinNullPointerException when i try to use txBuilder.toLedgerTransaction(getServiceHub())? I used verify() and then i realised that problem is in toLedgerTransaction(). This problem appeared when i add  new fields to State. They had co.paralleluniverse.common.util.Pair type and i think that there are some problems with serialization. Error message:

```<code>"stackTrace": [
    {
        "methodName": "reportGet",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.util.concurrent.CompletableFuture",
        "nativeMethod": false
    },
    {
        "methodName": "get",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.util.concurrent.CompletableFuture",
        "nativeMethod": false
    },
    {
        "methodName": "get",
        "fileName": "CordaFutureImpl.kt",
        "lineNumber": -1,
        "className": "net.corda.core.internal.concurrent.CordaFutureImpl",
        "nativeMethod": false
    },
    {
        "methodName": "createProject",
        "fileName": "ClientHttpApi.java",
        "lineNumber": 136,
        "className": "com.template.api.ClientHttpApi",
        "nativeMethod": false
    },
    {
        "methodName": "invoke0",
        "fileName": null,
        "lineNumber": -2,
        "className": "sun.reflect.NativeMethodAccessorImpl",
        "nativeMethod": true
    },
    {
        "methodName": "invoke",
        "fileName": null,
        "lineNumber": -1,
        "className": "sun.reflect.NativeMethodAccessorImpl",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": null,
        "lineNumber": -1,
        "className": "sun.reflect.DelegatingMethodAccessorImpl",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.lang.reflect.Method",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": "ResourceMethodInvocationHandlerFactory.java",
        "lineNumber": 81,
        "className": "org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "AbstractJavaResourceMethodDispatcher.java",
        "lineNumber": 144,
        "className": "org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": "AbstractJavaResourceMethodDispatcher.java",
        "lineNumber": 161,
        "className": "org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher",
        "nativeMethod": false
    },
    {
        "methodName": "doDispatch",
        "fileName": "JavaResourceMethodDispatcherProvider.java",
        "lineNumber": 160,
        "className": "org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "dispatch",
        "fileName": "AbstractJavaResourceMethodDispatcher.java",
        "lineNumber": 99,
        "className": "org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": "ResourceMethodInvoker.java",
        "lineNumber": 389,
        "className": "org.glassfish.jersey.server.model.ResourceMethodInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "apply",
        "fileName": "ResourceMethodInvoker.java",
        "lineNumber": 347,
        "className": "org.glassfish.jersey.server.model.ResourceMethodInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "apply",
        "fileName": "ResourceMethodInvoker.java",
        "lineNumber": 102,
        "className": "org.glassfish.jersey.server.model.ResourceMethodInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "ServerRuntime.java",
        "lineNumber": 326,
        "className": "org.glassfish.jersey.server.ServerRuntime$2",
        "nativeMethod": false
    },
    {
        "methodName": "call",
        "fileName": "Errors.java",
        "lineNumber": 271,
        "className": "org.glassfish.jersey.internal.Errors$1",
        "nativeMethod": false
    },
    {
        "methodName": "call",
        "fileName": "Errors.java",
        "lineNumber": 267,
        "className": "org.glassfish.jersey.internal.Errors$1",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "Errors.java",
        "lineNumber": 315,
        "className": "org.glassfish.jersey.internal.Errors",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "Errors.java",
        "lineNumber": 297,
        "className": "org.glassfish.jersey.internal.Errors",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "Errors.java",
        "lineNumber": 267,
        "className": "org.glassfish.jersey.internal.Errors",
        "nativeMethod": false
    },
    {
        "methodName": "runInScope",
        "fileName": "RequestScope.java",
        "lineNumber": 317,
        "className": "org.glassfish.jersey.process.internal.RequestScope",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "ServerRuntime.java",
        "lineNumber": 305,
        "className": "org.glassfish.jersey.server.ServerRuntime",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "ApplicationHandler.java",
        "lineNumber": 1154,
        "className": "org.glassfish.jersey.server.ApplicationHandler",
        "nativeMethod": false
    },
    {
        "methodName": "serviceImpl",
        "fileName": "WebComponent.java",
        "lineNumber": 473,
        "className": "org.glassfish.jersey.servlet.WebComponent",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "WebComponent.java",
        "lineNumber": 427,
        "className": "org.glassfish.jersey.servlet.WebComponent",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "ServletContainer.java",
        "lineNumber": 388,
        "className": "org.glassfish.jersey.servlet.ServletContainer",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "ServletContainer.java",
        "lineNumber": 341,
        "className": "org.glassfish.jersey.servlet.ServletContainer",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "ServletContainer.java",
        "lineNumber": 228,
        "className": "org.glassfish.jersey.servlet.ServletContainer",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "ServletHolder.java",
        "lineNumber": 841,
        "className": "org.eclipse.jetty.servlet.ServletHolder",
        "nativeMethod": false
    },
    {
        "methodName": "doHandle",
        "fileName": "ServletHandler.java",
        "lineNumber": 535,
        "className": "org.eclipse.jetty.servlet.ServletHandler",
        "nativeMethod": false
    },
    {
        "methodName": "nextHandle",
        "fileName": "ScopedHandler.java",
        "lineNumber": 188,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "doHandle",
        "fileName": "ContextHandler.java",
        "lineNumber": 1253,
        "className": "org.eclipse.jetty.server.handler.ContextHandler",
        "nativeMethod": false
    },
    {
        "methodName": "nextScope",
        "fileName": "ScopedHandler.java",
        "lineNumber": 168,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "doScope",
        "fileName": "ServletHandler.java",
        "lineNumber": 473,
        "className": "org.eclipse.jetty.servlet.ServletHandler",
        "nativeMethod": false
    },
    {
        "methodName": "nextScope",
        "fileName": "ScopedHandler.java",
        "lineNumber": 166,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "doScope",
        "fileName": "ContextHandler.java",
        "lineNumber": 1155,
        "className": "org.eclipse.jetty.server.handler.ContextHandler",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "ScopedHandler.java",
        "lineNumber": 141,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "HandlerCollection.java",
        "lineNumber": 126,
        "className": "org.eclipse.jetty.server.handler.HandlerCollection",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "HandlerWrapper.java",
        "lineNumber": 132,
        "className": "org.eclipse.jetty.server.handler.HandlerWrapper",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "Server.java",
        "lineNumber": 561,
        "className": "org.eclipse.jetty.server.Server",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "HttpChannel.java",
        "lineNumber": 334,
        "className": "org.eclipse.jetty.server.HttpChannel",
        "nativeMethod": false
    },
    {
        "methodName": "onFillable",
        "fileName": "HttpConnection.java",
        "lineNumber": 251,
        "className": "org.eclipse.jetty.server.HttpConnection",
        "nativeMethod": false
    },
    {
        "methodName": "succeeded",
        "fileName": "AbstractConnection.java",
        "lineNumber": 279,
        "className": "org.eclipse.jetty.io.AbstractConnection$ReadCallback",
        "nativeMethod": false
    },
    {
        "methodName": "fillable",
        "fileName": "FillInterest.java",
        "lineNumber": 104,
        "className": "org.eclipse.jetty.io.FillInterest",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "ChannelEndPoint.java",
        "lineNumber": 124,
        "className": "org.eclipse.jetty.io.ChannelEndPoint$2",
        "nativeMethod": false
    },
    {
        "methodName": "runJob",
        "fileName": "QueuedThreadPool.java",
        "lineNumber": 679,
        "className": "org.eclipse.jetty.util.thread.QueuedThreadPool",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "QueuedThreadPool.java",
        "lineNumber": 597,
        "className": "org.eclipse.jetty.util.thread.QueuedThreadPool$2",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.lang.Thread",
        "nativeMethod": false
    }
],
"localizedMessage": "kotlin.KotlinNullPointerException: net.corda.core.contracts.TransactionState -> data(net.corda.core.contracts.ContractState) -> null",
"message": "kotlin.KotlinNullPointerException: net.corda.core.contracts.TransactionState -> data(net.corda.core.contracts.ContractState) -> null",
"suppressed": []
</code>```

Stack trace ends with a call of flow through CordaRPCOps, so it's not useful.

答:
I believe you are implementing an old syntax of verifying the transaction. With the later versions of Corda, the TransactionBuilder object is already able to call the verify() method.

For example:

```<code>// Build the transaction, add the output state and the command to the transaction.
        TransactionBuilder transactionBuilder = new TransactionBuilder(notary)
                .addOutputState(output)
                .addCommand(new AssetContract.Commands.CreateAsset(),
                            Arrays.asList(getOurIdentity().getOwningKey())); // Required Signers

// Verify the transaction
transactionBuilder.verify(getServiceHub());
</code>```

Full codes at:
https://github.com/corda/samples-java/blob/master/Advanced/auction-cordapp/workflows/src/main/java/net/corda/samples/flows/CreateAssetFlow.java#L59

Body:
What reasons can be, that i get KotlinNullPointerException when i try to use txBuilder.toLedgerTransaction(getServiceHub())? I used verify() and then i realised that problem is in toLedgerTransaction(). This problem appeared when i add  new fields to State. They had co.paralleluniverse.common.util.Pair type and i think that there are some problems with serialization. Error message:

"stackTrace": [
    {
        "methodName": "reportGet",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.util.concurrent.CompletableFuture",
        "nativeMethod": false
    },
    {
        "methodName": "get",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.util.concurrent.CompletableFuture",
        "nativeMethod": false
    },
    {
        "methodName": "get",
        "fileName": "CordaFutureImpl.kt",
        "lineNumber": -1,
        "className": "net.corda.core.internal.concurrent.CordaFutureImpl",
        "nativeMethod": false
    },
    {
        "methodName": "createProject",
        "fileName": "ClientHttpApi.java",
        "lineNumber": 136,
        "className": "com.template.api.ClientHttpApi",
        "nativeMethod": false
    },
    {
        "methodName": "invoke0",
        "fileName": null,
        "lineNumber": -2,
        "className": "sun.reflect.NativeMethodAccessorImpl",
        "nativeMethod": true
    },
    {
        "methodName": "invoke",
        "fileName": null,
        "lineNumber": -1,
        "className": "sun.reflect.NativeMethodAccessorImpl",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": null,
        "lineNumber": -1,
        "className": "sun.reflect.DelegatingMethodAccessorImpl",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.lang.reflect.Method",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": "ResourceMethodInvocationHandlerFactory.java",
        "lineNumber": 81,
        "className": "org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "AbstractJavaResourceMethodDispatcher.java",
        "lineNumber": 144,
        "className": "org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": "AbstractJavaResourceMethodDispatcher.java",
        "lineNumber": 161,
        "className": "org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher",
        "nativeMethod": false
    },
    {
        "methodName": "doDispatch",
        "fileName": "JavaResourceMethodDispatcherProvider.java",
        "lineNumber": 160,
        "className": "org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "dispatch",
        "fileName": "AbstractJavaResourceMethodDispatcher.java",
        "lineNumber": 99,
        "className": "org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher",
        "nativeMethod": false
    },
    {
        "methodName": "invoke",
        "fileName": "ResourceMethodInvoker.java",
        "lineNumber": 389,
        "className": "org.glassfish.jersey.server.model.ResourceMethodInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "apply",
        "fileName": "ResourceMethodInvoker.java",
        "lineNumber": 347,
        "className": "org.glassfish.jersey.server.model.ResourceMethodInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "apply",
        "fileName": "ResourceMethodInvoker.java",
        "lineNumber": 102,
        "className": "org.glassfish.jersey.server.model.ResourceMethodInvoker",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "ServerRuntime.java",
        "lineNumber": 326,
        "className": "org.glassfish.jersey.server.ServerRuntime$2",
        "nativeMethod": false
    },
    {
        "methodName": "call",
        "fileName": "Errors.java",
        "lineNumber": 271,
        "className": "org.glassfish.jersey.internal.Errors$1",
        "nativeMethod": false
    },
    {
        "methodName": "call",
        "fileName": "Errors.java",
        "lineNumber": 267,
        "className": "org.glassfish.jersey.internal.Errors$1",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "Errors.java",
        "lineNumber": 315,
        "className": "org.glassfish.jersey.internal.Errors",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "Errors.java",
        "lineNumber": 297,
        "className": "org.glassfish.jersey.internal.Errors",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "Errors.java",
        "lineNumber": 267,
        "className": "org.glassfish.jersey.internal.Errors",
        "nativeMethod": false
    },
    {
        "methodName": "runInScope",
        "fileName": "RequestScope.java",
        "lineNumber": 317,
        "className": "org.glassfish.jersey.process.internal.RequestScope",
        "nativeMethod": false
    },
    {
        "methodName": "process",
        "fileName": "ServerRuntime.java",
        "lineNumber": 305,
        "className": "org.glassfish.jersey.server.ServerRuntime",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "ApplicationHandler.java",
        "lineNumber": 1154,
        "className": "org.glassfish.jersey.server.ApplicationHandler",
        "nativeMethod": false
    },
    {
        "methodName": "serviceImpl",
        "fileName": "WebComponent.java",
        "lineNumber": 473,
        "className": "org.glassfish.jersey.servlet.WebComponent",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "WebComponent.java",
        "lineNumber": 427,
        "className": "org.glassfish.jersey.servlet.WebComponent",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "ServletContainer.java",
        "lineNumber": 388,
        "className": "org.glassfish.jersey.servlet.ServletContainer",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "ServletContainer.java",
        "lineNumber": 341,
        "className": "org.glassfish.jersey.servlet.ServletContainer",
        "nativeMethod": false
    },
    {
        "methodName": "service",
        "fileName": "ServletContainer.java",
        "lineNumber": 228,
        "className": "org.glassfish.jersey.servlet.ServletContainer",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "ServletHolder.java",
        "lineNumber": 841,
        "className": "org.eclipse.jetty.servlet.ServletHolder",
        "nativeMethod": false
    },
    {
        "methodName": "doHandle",
        "fileName": "ServletHandler.java",
        "lineNumber": 535,
        "className": "org.eclipse.jetty.servlet.ServletHandler",
        "nativeMethod": false
    },
    {
        "methodName": "nextHandle",
        "fileName": "ScopedHandler.java",
        "lineNumber": 188,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "doHandle",
        "fileName": "ContextHandler.java",
        "lineNumber": 1253,
        "className": "org.eclipse.jetty.server.handler.ContextHandler",
        "nativeMethod": false
    },
    {
        "methodName": "nextScope",
        "fileName": "ScopedHandler.java",
        "lineNumber": 168,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "doScope",
        "fileName": "ServletHandler.java",
        "lineNumber": 473,
        "className": "org.eclipse.jetty.servlet.ServletHandler",
        "nativeMethod": false
    },
    {
        "methodName": "nextScope",
        "fileName": "ScopedHandler.java",
        "lineNumber": 166,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "doScope",
        "fileName": "ContextHandler.java",
        "lineNumber": 1155,
        "className": "org.eclipse.jetty.server.handler.ContextHandler",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "ScopedHandler.java",
        "lineNumber": 141,
        "className": "org.eclipse.jetty.server.handler.ScopedHandler",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "HandlerCollection.java",
        "lineNumber": 126,
        "className": "org.eclipse.jetty.server.handler.HandlerCollection",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "HandlerWrapper.java",
        "lineNumber": 132,
        "className": "org.eclipse.jetty.server.handler.HandlerWrapper",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "Server.java",
        "lineNumber": 561,
        "className": "org.eclipse.jetty.server.Server",
        "nativeMethod": false
    },
    {
        "methodName": "handle",
        "fileName": "HttpChannel.java",
        "lineNumber": 334,
        "className": "org.eclipse.jetty.server.HttpChannel",
        "nativeMethod": false
    },
    {
        "methodName": "onFillable",
        "fileName": "HttpConnection.java",
        "lineNumber": 251,
        "className": "org.eclipse.jetty.server.HttpConnection",
        "nativeMethod": false
    },
    {
        "methodName": "succeeded",
        "fileName": "AbstractConnection.java",
        "lineNumber": 279,
        "className": "org.eclipse.jetty.io.AbstractConnection$ReadCallback",
        "nativeMethod": false
    },
    {
        "methodName": "fillable",
        "fileName": "FillInterest.java",
        "lineNumber": 104,
        "className": "org.eclipse.jetty.io.FillInterest",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "ChannelEndPoint.java",
        "lineNumber": 124,
        "className": "org.eclipse.jetty.io.ChannelEndPoint$2",
        "nativeMethod": false
    },
    {
        "methodName": "runJob",
        "fileName": "QueuedThreadPool.java",
        "lineNumber": 679,
        "className": "org.eclipse.jetty.util.thread.QueuedThreadPool",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": "QueuedThreadPool.java",
        "lineNumber": 597,
        "className": "org.eclipse.jetty.util.thread.QueuedThreadPool$2",
        "nativeMethod": false
    },
    {
        "methodName": "run",
        "fileName": null,
        "lineNumber": -1,
        "className": "java.lang.Thread",
        "nativeMethod": false
    }
],
"localizedMessage": "kotlin.KotlinNullPointerException: net.corda.core.contracts.TransactionState -> data(net.corda.core.contracts.ContractState) -> null",
"message": "kotlin.KotlinNullPointerException: net.corda.core.contracts.TransactionState -> data(net.corda.core.contracts.ContractState) -> null",
"suppressed": []

Stack trace ends with a call of flow through CordaRPCOps, so it's not useful.

Body:
I believe you are implementing an old syntax of verifying the transaction. With the later versions of Corda, the TransactionBuilder object is already able to call the verify() method.

For example:

// Build the transaction, add the output state and the command to the transaction.
        TransactionBuilder transactionBuilder = new TransactionBuilder(notary)
                .addOutputState(output)
                .addCommand(new AssetContract.Commands.CreateAsset(),
                            Arrays.asList(getOurIdentity().getOwningKey())); // Required Signers

// Verify the transaction
transactionBuilder.verify(getServiceHub());

Full codes at:
https://github.com/corda/samples-java/blob/master/Advanced/auction-cordapp/workflows/src/main/java/net/corda/samples/flows/CreateAssetFlow.java#L59


问:
Spring Kafka or Kafka streams for a high volume data processing Spring boot application
I am working on to create a high volume JSON data processing application for a bank using Spring boot, Kafka and QuickFIX/J. This is my first time play with technologies like Kafka and QuickFIX/J and unable to decide that should I use plain Kafka spring or Kafka streams or spring cloud streams.
Here is the requirement:

Read data from multiple Kafka topics

Process and send the data to a QuickFIX/J initiator that further sends it to an external FIX engine

A QuickFIX/J acceptor receives the data from external FIX engine and write it back again to multiple Kafka topics, but different ones this time

I have gone through tutorials/articles that say Kafka streams or spring cloud stream is good if you have both consumer/producer, performing high volume data streaming and want to achieve exactly once processing. But, here I need to send data to an external party after processing, receive it and then write to Kafka topics.

Is using Kafka stream a good choice? or shall I use spring kafka with normal producers & consumers?

答:
Spring Cloud Stream is just a higher level, opinionated, abstraction on top of Spring for Apache Kafka. It can handle your use case (there are several "sink" sample applications).

Similarly, Kafka Streams does not necessarily have to produce output to Kafka (although that's what it is designed to do).

Probably the fastest on-ramp is Spring Cloud Stream (or Spring for Apache Kafka with Spring Boot) because most cookie-cutter configuration is provided for you and you can just concentrate on your business logic.


问:
Angular 9 ng new stuck at installing packages
I have just installed the node version 12.16.1 the  LTS and
 angular cli version 9.0.3.
 At the time of creating new project with cli all files in root folder are generating but it is stuck at the part of installing node packages.

Is anybody facing the same issue? Please help how can we resolve it.

答:
Run command npm i -g npm@latest

Run command npm i -g @angular/cli@latest

It worked for me.


问:
Difference between two methods in django
What's difference between two methods and which is better for long run ? Is there any advantage one over other?

To add a staff:

(1st Method)

views.py

```<code>
def add_staff(request):
    return render(request, 'hod_template/add_staff_template.html')

def add_staff_save(request):
    if request.method != 'POST':
        return HttpResponse('Method not allowed')
    else:
        first_name = request.GET.get('first_name')
        last_name = request.GET.get('last_name')
        username = request.GET.get('username')
        email = request.GET.get('email')
        password = request.GET.get('password')
        address = request.GET.get('address')
        try:
            user = CustomUser.objects.create_user(username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=2)
            user.staffs.address = address
            user.save()
            messages.success(request, 'Staff Added Successfully')
            return HttpResponseRedirect('/add_staff')
        except:
            messages.error(request, 'Failed to Add Staff')
            return HttpResponseRedirect('/add_staff')
</code>```

urls.py

```<code>    path('add_staff/', add_staff),
    path('add_staff_save/', add_staff_save),
</code>```

add_staff.html

```<code>    <form role="form" action="/add_staff_save">
        {% csrf_token %}
        <div class="card-body">
            <div class="form-group">
                <label>Email address</label>
                <input type="email" class="form-control" name="email" placeholder="Enter email">
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" class="form-control" placeholder="Password" name="password">
            </div>

            <!-- same for first_name, last_name, username, address -->
            <div class="card-footer">
                <button type="submit" class="btn btn-primary btn-block">Add Staff</button>
            </div>
        </div>
    </form>
</code>```

(2nd Method)

make a form in forms.py of all fields first_name, last_name, username, address
and then call in view and validate it.
forms.py

```<code>    class StaffForm(forms.ModelForm):
        class Meta:
            model = Staff
            fields = ('first_name', 'last_name', 'username', 'address')
</code>```

views.py

```<code>def add_staff(request):
    if request.method == 'POST':
        form = StaffForm(data=request.POST)
        if form.is_valid():
            messages.success(request, 'Staff Added Successfully')
            form.save()
    else:
        form = StaffForm()
    return render(request, 'staff.html', {'form':form})
</code>```

urls.py
 path('add_staff/', add_staff),

staff.html

```<code>    <form role="form" action="/">
        {% csrf_token %}
        {{ form.as_p }} <!-- render form as paragraph -->
    </form>
</code>```

Both methods work well and staff model have all the required field.
Sorry for long question since its getting too long I'm not adding staff model. If you need plz let me know.

答:
of course the second method is much way better than the first one
because you should do cleaning and validation in other files like forms.py in each individual section

and also you can add more options and other things that maybe will be useful after a time
and you should be aware of that and predict some changes for improvement too!
and with making forms and use generics , you will write less code than doing it by yourself in hardcode in views.

so don't hesitate and choose method2

Body:
What's difference between two methods and which is better for long run ? Is there any advantage one over other?

To add a staff:

(1st Method)

views.py

def add_staff(request):
    return render(request, 'hod_template/add_staff_template.html')

def add_staff_save(request):
    if request.method != 'POST':
        return HttpResponse('Method not allowed')
    else:
        first_name = request.GET.get('first_name')
        last_name = request.GET.get('last_name')
        username = request.GET.get('username')
        email = request.GET.get('email')
        password = request.GET.get('password')
        address = request.GET.get('address')
        try:
            user = CustomUser.objects.create_user(username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=2)
            user.staffs.address = address
            user.save()
            messages.success(request, 'Staff Added Successfully')
            return HttpResponseRedirect('/add_staff')
        except:
            messages.error(request, 'Failed to Add Staff')
            return HttpResponseRedirect('/add_staff')

urls.py

    path('add_staff/', add_staff),
    path('add_staff_save/', add_staff_save),

add_staff.html

    <form role="form" action="/add_staff_save">
        {% csrf_token %}

                Email address
                <input type="email" class="form-control" name="email" placeholder="Enter email">

                Password
                <input type="password" class="form-control" placeholder="Password" name="password">

                <button type="submit" class="btn btn-primary btn-block">Add Staff</button>

    </form>

(2nd Method)

make a form in forms.py of all fields first_name, last_name, username, address
and then call in view and validate it.
forms.py

    class StaffForm(forms.ModelForm):
        class Meta:
            model = Staff
            fields = ('first_name', 'last_name', 'username', 'address')

views.py

def add_staff(request):
    if request.method == 'POST':
        form = StaffForm(data=request.POST)
        if form.is_valid():
            messages.success(request, 'Staff Added Successfully')
            form.save()
    else:
        form = StaffForm()
    return render(request, 'staff.html', {'form':form})

urls.py
 path('add_staff/', add_staff),

staff.html

    <form role="form" action="/">
        {% csrf_token %}
        {{ form.as_p }}
    </form>

Both methods work well and staff model have all the required field.
Sorry for long question since its getting too long I'm not adding staff model. If you need plz let me know.


问:
center the dots of the unorder list in html
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

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

<p>It should look like below (here * represents bullets):</p>

```                                * first
                                * second
                                * third
```

答:
Try using flex to align the items inside the toolbar to the center and then the ul text to the left. Is that what you need?

.toolbar {
  display: flex;
  flex-direction: column;
  align-items: center;
}
ul {
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toolbar">
<h1>Header Label</h1>
<ul>
<li>first</li>
<li>second</li>
<li>three</li>
</ul>
</div></code>```

Body:
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

It should look like below (here * represents bullets):

                                * first
                                * second
                                * third

Body:
Try using flex to align the items inside the toolbar to the center and then the ul text to the left. Is that what you need?

.toolbar {
  display: flex;
  flex-direction: column;
  align-items: center;
}
ul {
  text-align: left;
}

<div class="toolbar">
<h1>Header Label</h1>
<ul>
<li>first</li>
<li>second</li>
<li>three</li>
</ul>
</div>


问:
Ignore a template error in angular for build
I am using this lib

tl;dr : How to ignore a "property not defined" in typescript

In order to create a custom plonter the doc say to look at their implementation and I copied their basic code and the template looks like this =>

```<code><ac-html *ngIf="plonterService.plonterShown" [props]="{
  position: plonterPosition
}">
  <div class="plonter-context-menu">
    <div *ngFor="let entity of plonterService.entitesToPlonter">
      <div class="plonter-item" (click)="chooseEntity(entity)">

        {{ entity?.name || entity?.id }}
      </div>
    </div>
  </div>
</ac-html>
</code>```

the component

```<code>import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CoordinateConverter, PlonterService } from 'angular-cesium';

@Component({
  selector: 'app-entity-plonter',
  templateUrl: './entity-plonter.component.html',
  styleUrls: ['./entity-plonter.component.less'],
  providers: [CoordinateConverter],
})
export class EntityPlonterComponent implements OnInit {

  constructor(public plonterService: PlonterService,
              private chandeDetector: ChangeDetectorRef,
              private coordinateConverter: CoordinateConverter) { }

  ngOnInit() {
    this.plonterService.plonterChangeNotifier.subscribe(() => this.chandeDetector.detectChanges());
  }

  get plonterPosition() {
    if (this.plonterService.plonterShown) {
      const screenPos = this.plonterService.plonterClickPosition.endPosition;
      return this.coordinateConverter.screenToCartesian3(screenPos);
    }
  }

  chooseEntity(entity: any) {
    this.plonterService.resolvePlonter(entity);
  }
}
</code>```

now, I have an error in the template on the line

```<code>{{ entity?.name || entity?.id }}
</code>```

AcEntity doesn't have a property name and id.

this is because in the lib, AcEntity is defined like this

```<code>/**
 * Angular Cesium parent entity, all entities should inherit from it.
 * ```typescript
 * entity= new AcEntity({
 *      id: 0,
 *      name: 'click me',
 *      position: Cesium.Cartesian3.fromRadians(0.5, 0.5),
 * });
 * ```
 */
export class AcEntity {

  /**
   * Creates entity from a json
   * @param json entity object
   * @returns entity as AcEntity
   */
  static create(json?: any) {
    if (json) {
      return Object.assign(new AcEntity(), json);
    }
    return new AcEntity();
  }

  /**
   * Creates entity from a json
   * @param json (Optional) entity object
   */
  constructor(json?: any) {
    Object.assign(this, json);
  }
}
</code>```

now, I know the error is legit, but I would like to ignore it for the compile and for the builds. Since I have no control over the library directly and the value is coming from a service of the library.

Is it possible ?

答:
I don't know if anyone is still looking for an answer for this, but just thought I'd add an answer that I found for it. You can skirt the template error by wrapping the object with $any(object). So, in this case, it would look like:</p>

```<code><div *ngFor="let entity of $any(plonterService).entitesToPlonter">
</code>```

Body:
I am using this lib

tl;dr : How to ignore a "property not defined" in typescript

In order to create a custom plonter the doc say to look at their implementation and I copied their basic code and the template looks like this =>

<ac-html *ngIf="plonterService.plonterShown" [props]="{
  position: plonterPosition
}">

        {{ entity?.name || entity?.id }}

</ac-html>

the component

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CoordinateConverter, PlonterService } from 'angular-cesium';

@Component({
  selector: 'app-entity-plonter',
  templateUrl: './entity-plonter.component.html',
  styleUrls: ['./entity-plonter.component.less'],
  providers: [CoordinateConverter],
})
export class EntityPlonterComponent implements OnInit {

  constructor(public plonterService: PlonterService,
              private chandeDetector: ChangeDetectorRef,
              private coordinateConverter: CoordinateConverter) { }

  ngOnInit() {
    this.plonterService.plonterChangeNotifier.subscribe(() => this.chandeDetector.detectChanges());
  }

  get plonterPosition() {
    if (this.plonterService.plonterShown) {
      const screenPos = this.plonterService.plonterClickPosition.endPosition;
      return this.coordinateConverter.screenToCartesian3(screenPos);
    }
  }

  chooseEntity(entity: any) {
    this.plonterService.resolvePlonter(entity);
  }
}

now, I have an error in the template on the line

{{ entity?.name || entity?.id }}

AcEntity doesn't have a property name and id.

this is because in the lib, AcEntity is defined like this

/**
 * Angular Cesium parent entity, all entities should inherit from it.
 * ```typescript
 * entity= new AcEntity({
 *      id: 0,
 *      name: 'click me',
 *      position: Cesium.Cartesian3.fromRadians(0.5, 0.5),
 * });
 * ```
 */
export class AcEntity {

  /**
   * Creates entity from a json
   * @param json entity object
   * @returns entity as AcEntity
   */
  static create(json?: any) {
    if (json) {
      return Object.assign(new AcEntity(), json);
    }
    return new AcEntity();
  }

  /**
   * Creates entity from a json
   * @param json (Optional) entity object
   */
  constructor(json?: any) {
    Object.assign(this, json);
  }
}

now, I know the error is legit, but I would like to ignore it for the compile and for the builds. Since I have no control over the library directly and the value is coming from a service of the library.

Is it possible ?

Body:
I don't know if anyone is still looking for an answer for this, but just thought I'd add an answer that I found for it. You can skirt the template error by wrapping the object with $any(object). So, in this case, it would look like:

<div *ngFor="let entity of $any(plonterService).entitesToPlonter">


问:
Need to find corresponding endpoints for API integration of DocuSign, ideas?
Endpoints for:
- Download document based off unique ID
- Create new document
- Upload document
- Update existing document (e-Signature)

I can not find anything of use here (https://developers.docusign.com/esign-rest-api/reference) or any true examples.

答:
Based on your questions, I think it would be helpful to explain the basic DocuSign object model. The highest order object is the Envelope. Envelopes contain one or more documents, which have recipients (such as signers or carbon copy). These recipients, in turn, may have tabs assigned to them. For more information on the object model, check out this guide.

Now to answer your questions:

1) Downloading envelope documents (here are code examples):

```<code>GET /envelopes/{envelope_id}/documents/{doc_id}
</code>```

Here is the associated reference documentation

2) Create a new envelope containing a document (here is a code example)

```<code>POST /envelopes
</code>```

Here is the associated reference documentation.

3) Uploading a document to an existing envelope

```<code>PUT /restapi/v2.1/accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}
</code>```

Here is the associated reference documentation.

Body:
Based on your questions, I think it would be helpful to explain the basic DocuSign object model. The highest order object is the Envelope. Envelopes contain one or more documents, which have recipients (such as signers or carbon copy). These recipients, in turn, may have tabs assigned to them. For more information on the object model, check out this guide.

Now to answer your questions:

1) Downloading envelope documents (here are code examples):

GET /envelopes/{envelope_id}/documents/{doc_id}

Here is the associated reference documentation

2) Create a new envelope containing a document (here is a code example)

POST /envelopes

Here is the associated reference documentation.

3) Uploading a document to an existing envelope

PUT /restapi/v2.1/accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}

Here is the associated reference documentation.


问:
How can I detect the element(s) at an arbitrary mouse position (x,y)?

Possible Duplicate:

Get element at specified position - JavaScript

How can I detect the elements at an arbitrary mouse position (x,y)?

I am using mouseenter/mouseleave to highlight hovered items. Unfortunately neither of these fire when the mouse moves implicitly and this leads to the wrong item being highlighted. An example of moving the mouse implicitly would be scrolling the page with arrow keys or track pad.

You can see a working demo with comments here: http://jsfiddle.net/bkG2K/6/

My idea for a workaround is to check the mouse's position every so often, or just after scrolling if possible, and update the hover state based on the current mouse co-ordinates. But I'm not sure how I can find DOM elements given an X,Y.

Ideas? If you have a better solution to the root problem, feel free!

答:
You can use the native JavaScript elementFromPoint(x, y) method, that returns the element at coordinates x,y in the viewport.

See the elementFromPoint w3c draft

And, a code sample:

```<code><html>
<head>
<title>elementFromPoint example</title>

<script type="text/javascript">

function changeColor(newColor)
{
 elem = document.elementFromPoint(2, 2);
 elem.style.color = newColor;
}
</script>
</head>

<body>
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
</html>
</code>```

You can use setInterval() to continuously check the element's hover event but it's not recommended, try to use .hover(...) and css instead to enhance the application performance.

Body:
You can use the native JavaScript elementFromPoint(x, y) method, that returns the element at coordinates x,y in the viewport.

See the elementFromPoint w3c draft

And, a code sample:

<html>
<head>
<title>elementFromPoint example</title>

<script type="text/javascript">

function changeColor(newColor)
{
 elem = document.elementFromPoint(2, 2);
 elem.style.color = newColor;
}
</script>
</head>

<body>
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
</html>

You can use setInterval() to continuously check the element's hover event but it's not recommended, try to use .hover(...) and css instead to enhance the application performance.


问:
nodejs/JS: Objects not being updated in array
Firstly, I am a complete noob to Javascript and Node.js.

I tried to write a simple program that creates an array of planes that all have the same values except in index, which should take on the value of each index in the for loop from 0 - 2.

Here is my code

```<code>var plane = {
    index: -1,
    name: "A380",
    seats: {
        first: 40,
        buisness: 90,
        economy: 300
    },
    wheels: 8,
}

var planeArray = []

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(plane)
  }

  console.log(planeArray)
</code>```

But when I print the output, the indices of all the planes are 2. Here is my output.

```<code>[
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]
</code>```

Here is my expected output.

```<code>[
  {
    index: 0,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 1,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]
</code>```

I don't understand why.
Could someone help me out. Also, any additional explanations/resources helpful for learning node.js would be greatly appreciated

答: You are always changing the same object with  plane.index = i. If you want to have three different entries in your array you need three different objects.

Body:
Firstly, I am a complete noob to Javascript and Node.js.

I tried to write a simple program that creates an array of planes that all have the same values except in index, which should take on the value of each index in the for loop from 0 - 2.

Here is my code

var plane = {
    index: -1,
    name: "A380",
    seats: {
        first: 40,
        buisness: 90,
        economy: 300
    },
    wheels: 8,
}

var planeArray = []

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(plane)
  }

  console.log(planeArray)

But when I print the output, the indices of all the planes are 2. Here is my output.

[
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]

Here is my expected output.

[
  {
    index: 0,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 1,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]

I don't understand why.
Could someone help me out. Also, any additional explanations/resources helpful for learning node.js would be greatly appreciated


问:
How to run job-to-job linking in multi-project pipelines on GitLab CI
Example:

I have 3 different pipelines (projects) in GitLab.
Each pipeline has multiple jobs, each targeting a different remote VM and set a different GitLab CI environment.
The jobs are all manually triggered (currently).
What I am trying to achieve is a linking (multi-project) pipeline that runs like this:
Once I trigger job "X" in the pipeline #1, upon succeeding, that will trigger ONLY job "X" in the pipeline #2 which then again, upon success, will trigger ONLY job "X" in pipeline #3.

By job "X" I mean a job that runs on a certain remote VM, I don't want the entire pipeline to run since I don't want to change all targets. All examples I found only work at a pipeline level, not at the job level. What am I missing?

PS: I'm new to the GitLab CI scene so please forgive my lack of understanding in case there's an easy solution that I've missed.

答:
It's possible yes. If I take your example, in job "X" from pipeline 1, you can trigger a pipeline from another project using Gitlab API :

```<code>script:
  - "curl --request POST --form token=TOKEN --form ref=master https://gitlab.example.com/api/v4/projects/9/trigger/pipeline"
</code>```

To ensure triggering only job "X" from pipeline 2, add use only keyword with api condition :

```<code>job_X:
  only:
    - api
</code>```

Body:
It's possible yes. If I take your example, in job "X" from pipeline 1, you can trigger a pipeline from another project using Gitlab API :

script:
  - "curl --request POST --form token=TOKEN --form ref=master https://gitlab.example.com/api/v4/projects/9/trigger/pipeline"

To ensure triggering only job "X" from pipeline 2, add use only keyword with api condition :

job_X:
  only:
    - api


问:
cannot find module /srv/server.js - gcloud app engine
The error I get when trying to deploy my service to app engine is:

```<code>Error: Cannot find module '/srv/server.js' at

`Function.Module._resolveFilename (module.js:548:15) at

Function.Module._load (module.js:475:25) at Function.Module.runMain

(module.js:694:10) at startup (bootstrap_node.js:204:16) at

bootstrap_node.js:625:3`
</code>```

I dont have a /srv/server.js and why would it look for it?!?!?

Thanks if you can help!

答:
Better late than never.

The error is coming up because you are loading the relative path.

Solution:

```<code>"scripts": {
    "start": "node ./app.js"
},
</code>```

Body:
The error I get when trying to deploy my service to app engine is:

Error: Cannot find module '/srv/server.js' at

`Function.Module._resolveFilename (module.js:548:15) at

Function.Module._load (module.js:475:25) at Function.Module.runMain

(module.js:694:10) at startup (bootstrap_node.js:204:16) at

bootstrap_node.js:625:3`

I dont have a /srv/server.js and why would it look for it?!?!?

Thanks if you can help!

Body:
Better late than never.

The error is coming up because you are loading the relative path.

Solution:

"scripts": {
    "start": "node ./app.js"
},


问:
How can i make the first col aligned to left and the rest aligned to center with kable table
I try to make table and want to make the first col aligned to left and the rest aligned to center. It seems like no align option for col_spec. how should I do?

Here are the sample codes that I made:

x<-data.frame("Name"=c("test", "try"),"SN"=1:2, "Age"=c(21, 15), "Salary"=c(1000,2000))

x %>% kable("html",  align="c") %>% kable_styling(full_width = FALSE, position="left" )%>% row_spec(0, background = "#F3E2A9")

答:
You can specify the alignment based on the order of the columns:

```<code>x<-data.frame("Name"=c("test", "try"),"SN"=1:2, "Age"=c(21, 15), "Salary"=c(1000,2000))
library(kableExtra)
library(knitr)
x %>%
  kable("html", align=c("l", 'c', 'c','c')) %>%
  kable_styling(full_width = FALSE, position="left")%>%
  row_spec(0, background = "#F3E2A9")
</code>```

In your example, the fist column is aligned to the left, the remaining three columns are aligned to the center.

Body:
You can specify the alignment based on the order of the columns:

x<-data.frame("Name"=c("test", "try"),"SN"=1:2, "Age"=c(21, 15), "Salary"=c(1000,2000))
library(kableExtra)
library(knitr)
x %>%
  kable("html", align=c("l", 'c', 'c','c')) %>%
  kable_styling(full_width = FALSE, position="left")%>%
  row_spec(0, background = "#F3E2A9")

In your example, the fist column is aligned to the left, the remaining three columns are aligned to the center.


问:
Show specific Quick Action for specific file extension
I am newbie with Applescript and Automator. I am trying to build a Quick Actions which will be able to propose different functions according to the type of file for example.
If the file is test.sh quick action will be a and b
If the file is document.pdf action will be c and d

I succeed in creating my actions but not to make them specific to file type. I don't know where to start as I don't see any possibility to make input conditional like if input = .sh do a and b.

Any help on how to proceed will be really appreciated.

Thank you,

答:
Quick Actions are meant to be type-specific, so in general the best practice is to write one Quick Action for each file type. These quick actions will only appear in the Finder when files of that type are selected.

In many cases you can specify the file type when you create or edit the Quick Action in Automator. For instance, to create a Quick Action that appears only when PDF files are selected, set the pulldown menus at the top of the workflow to say "Workflow receives current PDF files in Finder":

then complete and save the Quick Action.

If you want more fine-tuned control over what types of files the Quick Action 'sees', you can edit its info.plist file and change its file types. After you've saved the Quick Action, navigate to ~/Library/Services in the Finder (that's the Services folder in the Library folder of your Home folder). Find the package with the name of the Quick Action (e.g., "Open in Preview"), control-click on it to get the contextual menu, choose Show Package Contents, and then open the Contents folder. You'll see the following:

Open that info.plist file in a plain-text text editor — I prefer BBEdit, but TextEdit will work fine if you make sure 'rich text' is turned off — and look for the NSSendFileTypes key. It will look something like the following:

```<code>    <key>NSSendFileTypes</key>
    <array>
        <string>com.adobe.pdf</string>
    </array>
</code>```

com.adobe.pdf is a Uniform Type Identifier (UTI), and you can add or substitute in any system-recognized UTI. Here is the list of system-declared UTIs, but applications can declare their own UTIs and register them with the system, so this list is not necessarily exhaustive. For instance, if you want your Quick Action to send both PDFs and image files to Preview, you would search on the system-declared UTIs page and find that the base UTI for images is public.image, and then edit the info.plist to read:

```<code>    <key>NSSendFileTypes</key>
    <array>
        <string>com.adobe.pdf</string>
        <string>public.image</string>
    </array>
</code>```

Save this, and the Quick Action will now appear whenever you selected PDFs or images. Note that if you manually edit the info.plist file it might get overwritten if you edit and save the Quick Action in Automator.

Only the first two relevant Quick Actions will appear in the Finder window; any extras will be collapsed under the more button. To change the ordering so that the Quick Actions you use most are up first, open System Preferences, click the Extensions item, open the Finder section, and drag the items in the right-hand list into the order you prefer.

Body:
Quick Actions are meant to be type-specific, so in general the best practice is to write one Quick Action for each file type. These quick actions will only appear in the Finder when files of that type are selected.

In many cases you can specify the file type when you create or edit the Quick Action in Automator. For instance, to create a Quick Action that appears only when PDF files are selected, set the pulldown menus at the top of the workflow to say "Workflow receives current PDF files in Finder":

then complete and save the Quick Action.

If you want more fine-tuned control over what types of files the Quick Action 'sees', you can edit its info.plist file and change its file types. After you've saved the Quick Action, navigate to ~/Library/Services in the Finder (that's the Services folder in the Library folder of your Home folder). Find the package with the name of the Quick Action (e.g., "Open in Preview"), control-click on it to get the contextual menu, choose Show Package Contents, and then open the Contents folder. You'll see the following:

Open that info.plist file in a plain-text text editor — I prefer BBEdit, but TextEdit will work fine if you make sure 'rich text' is turned off — and look for the NSSendFileTypes key. It will look something like the following:

    <key>NSSendFileTypes</key>
    <array>
        <string>com.adobe.pdf</string>
    </array>

com.adobe.pdf is a Uniform Type Identifier (UTI), and you can add or substitute in any system-recognized UTI. Here is the list of system-declared UTIs, but applications can declare their own UTIs and register them with the system, so this list is not necessarily exhaustive. For instance, if you want your Quick Action to send both PDFs and image files to Preview, you would search on the system-declared UTIs page and find that the base UTI for images is public.image, and then edit the info.plist to read:

    <key>NSSendFileTypes</key>
    <array>
        <string>com.adobe.pdf</string>
        <string>public.image</string>
    </array>

Save this, and the Quick Action will now appear whenever you selected PDFs or images. Note that if you manually edit the info.plist file it might get overwritten if you edit and save the Quick Action in Automator.

Only the first two relevant Quick Actions will appear in the Finder window; any extras will be collapsed under the more button. To change the ordering so that the Quick Actions you use most are up first, open System Preferences, click the Extensions item, open the Finder section, and drag the items in the right-hand list into the order you prefer.