问:
How to fix 'Unchecked cast from MyClass to T'
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

```<code>private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}
</code>```

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.

答:
There are two ways in general to avoid this warning.

The first is to cast the object to the class:

```<code>public static <T> T castMe(Class<T> clazz, Object object) {

    return clazz.cast(object);
}
</code>```

The second one is to suppress the warning with an annotation. It's a bit of an unsure way about it but can safely be used when you absolutely know that that specific object can be cast to the generic type in question:

```<code>@SuppressWarnings("unchecked")
public static <T> T castMe(Class<T> clazz, Object object) {

    return (T) object;
}
</code>```

Body:
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.

Body:
There are two ways in general to avoid this warning.

The first is to cast the object to the class:

public static <T> T castMe(Class<T> clazz, Object object) {

    return clazz.cast(object);
}

The second one is to suppress the warning with an annotation. It's a bit of an unsure way about it but can safely be used when you absolutely know that that specific object can be cast to the generic type in question:

@SuppressWarnings("unchecked")
public static <T> T castMe(Class<T> clazz, Object object) {

    return (T) object;
}


来源: stackexchange

问:
How to sort table's column based on value of other column?
I have a Table from A:C column, in the column H, I have the same value on the column B in diffrent order, how to sort table based on the column H ?

```<code>Public Sub ReportSorting()
    Dim sht As Worksheet
    Dim LastRow As Long
    Dim sRange As Range
    Dim kRange  As Variant
    Dim nSort As Long

    Set sht = ActiveSheet
    LastRow = sht.Cells(sht.Rows.Count, "H").End(xlUp).Row

    Set sRange = sht.Range("H2:H" & LastRow)

    'Read values into array from range ActiveSheet
    kRange = sRange.Value

    Application.AddCustomList ListArray:=kRange
    nSort = Application.CustomListCount

    sht.Sort.SortFields.Clear
    sht.Sort.SortFields.Add Key:=Range("B1:B" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=nSort, DataOption:=xlSortNormal
    With sht.Sort
        .SetRange Range("A1:C" & LastRow)
        .Header = xlYes
        .MatchCase = True
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

End Sub
</code>```

I'm getting

Error 1004: The mothod Add AddCustomList for the object Application has failure!

A:C table name is: Req and H is out of the table.

```<code>A      B    C    ...   H
PID   ID   Name        SID
-     001  AAA         001
001   002  BBB         002
004   003  CCC         004
      004  DDD         003
....
</code>```

答:
the Application.AddCustomList method can hold only string and if you try to add numbers (Range) as in the example above , getting error!

I tried a simple tricks and add a helper column (from ID) and add also string "abc" in both column's values (D and H) like the following:

```<code> A     B    C      D    ...   H
PID   ID   Name   HID        SID
      001  AAA   abc001     abc001
001   002  BBB   abc002     abc002
004   003  CCC   abc003     abc004
      004  DDD   abc004     abc003
</code>```

and sort D column:

```<code>sht.Sort.SortFields.Clear
sht.Sort.SortFields.Add Key:=Range("D1:D" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=nSort, DataOption:=xlSortNormal
With sht.Sort
    .SetRange Range("A1:D" & LastRow)
    .Header = xlYes
    .MatchCase = True
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
</code>```

now it is working ;)

ContentLicense: CC BY-SA 4.0

Body:
I have a Table from A:C column, in the column H, I have the same value on the column B in diffrent order, how to sort table based on the column H ?

Public Sub ReportSorting()
    Dim sht As Worksheet
    Dim LastRow As Long
    Dim sRange As Range
    Dim kRange  As Variant
    Dim nSort As Long

    Set sht = ActiveSheet
    LastRow = sht.Cells(sht.Rows.Count, "H").End(xlUp).Row

    Set sRange = sht.Range("H2:H" & LastRow)

    'Read values into array from range ActiveSheet
    kRange = sRange.Value

    Application.AddCustomList ListArray:=kRange
    nSort = Application.CustomListCount

    sht.Sort.SortFields.Clear
    sht.Sort.SortFields.Add Key:=Range("B1:B" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=nSort, DataOption:=xlSortNormal
    With sht.Sort
        .SetRange Range("A1:C" & LastRow)
        .Header = xlYes
        .MatchCase = True
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

End Sub

I'm getting

Error 1004: The mothod Add AddCustomList for the object Application has failure!

A:C table name is: Req and H is out of the table.

A      B    C    ...   H
PID   ID   Name        SID
-     001  AAA         001
001   002  BBB         002
004   003  CCC         004
      004  DDD         003
....

Body:
the Application.AddCustomList method can hold only string and if you try to add numbers (Range) as in the example above , getting error!

I tried a simple tricks and add a helper column (from ID) and add also string "abc" in both column's values (D and H) like the following:

 A     B    C      D    ...   H
PID   ID   Name   HID        SID
      001  AAA   abc001     abc001
001   002  BBB   abc002     abc002
004   003  CCC   abc003     abc004
      004  DDD   abc004     abc003

and sort D column:

sht.Sort.SortFields.Clear
sht.Sort.SortFields.Add Key:=Range("D1:D" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=nSort, DataOption:=xlSortNormal
With sht.Sort
    .SetRange Range("A1:D" & LastRow)
    .Header = xlYes
    .MatchCase = True
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

now it is working ;)


问:
Wep API fails to return data from HttpClient call
I have not been able to figure out why the following issue is happening:

I have created a simple web api controller (.Net Framework 4.6.1)

```<code>public class TestController : ApiController
{
    // GET api/<controller>
    public async Task<string> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}
</code>```

When I run the code above I get the following error after about 20 seconds.

```<code>{
    "Message": "An error has occurred.",
    "ExceptionMessage": "An error occurred while sending the request.",
    "ExceptionType": "System.Net.Http.HttpRequestException",
    "StackTrace": "   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at restapitest2.Controllers.TestController.<Get>d__0.MoveNext() in C:\\restapitest2\\restapitest2\\Controllers\\TestController.cs:line 19\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Unable to connect to the remote server",
        "ExceptionType": "System.Net.WebException",
        "StackTrace": "   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 216.74.38.80:80",
            "ExceptionType": "System.Net.Sockets.SocketException",
            "StackTrace": "   at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)\r\n   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)\r\n   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)"
        }
    }
}
</code>```

When I create a dotnet core web api controller the same code works fine.

This is what the dot net core code looks like.

```<code>[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public async Task<ActionResult<string>> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}
</code>```

What is strange is that if I use an internal URL both api solutions return data.

Any help would be appreciated

答:
As others have pointed out that the code works, which could either be HTTPS issues or Proxy, I've re-written the code to the following to include HTTPS in the URL

```<code> [HttpGet]
    public async Task<ActionResult<string>> Get()
    {
        var url = "https://api.plos.org/search?q=title:DNA";

        var request = new HttpRequestMessage(HttpMethod.Get, url);

        var httpClient = new HttpClient();

        using (var response = await httpClient.SendAsync(request))
        {
            var content = response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            return Ok(content);
        }
    }
</code>```

But I would use IHttpClientFactory due to the problems it solves for sockets, not HttpClient.

In order to use the IHttpClientFactory do the following

Add the service to the ConfigureServices.cs

```<code>  services.AddHttpClient();
</code>```

then inject the call into the constructor

```<code>    private readonly IHttpClientFactory _clientFactory;

    public ValuesController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
</code>```

then your API call would be the following

```<code>var url = "https://api.plos.org/search?q=title:DNA";

        var request = new HttpRequestMessage(HttpMethod.Get, url);

        var httpClient = _clientFactory.CreateClient();

        using (var response = await httpClient.SendAsync(request))
        {
            var content = response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            return Ok(content);
        }
</code>```

Body:
I have not been able to figure out why the following issue is happening:

I have created a simple web api controller (.Net Framework 4.6.1)

public class TestController : ApiController
{
    // GET api/<controller>
    public async Task<string> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}

When I run the code above I get the following error after about 20 seconds.

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "An error occurred while sending the request.",
    "ExceptionType": "System.Net.Http.HttpRequestException",
    "StackTrace": "   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at restapitest2.Controllers.TestController.<Get>d__0.MoveNext() in C:\\restapitest2\\restapitest2\\Controllers\\TestController.cs:line 19\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Unable to connect to the remote server",
        "ExceptionType": "System.Net.WebException",
        "StackTrace": "   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 216.74.38.80:80",
            "ExceptionType": "System.Net.Sockets.SocketException",
            "StackTrace": "   at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)\r\n   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)\r\n   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)"
        }
    }
}

When I create a dotnet core web api controller the same code works fine.

This is what the dot net core code looks like.

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public async Task<ActionResult<string>> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}

What is strange is that if I use an internal URL both api solutions return data.

Any help would be appreciated

Body:
As others have pointed out that the code works, which could either be HTTPS issues or Proxy, I've re-written the code to the following to include HTTPS in the URL

 [HttpGet]
    public async Task<ActionResult<string>> Get()
    {
        var url = "https://api.plos.org/search?q=title:DNA";

        var request = new HttpRequestMessage(HttpMethod.Get, url);

        var httpClient = new HttpClient();

        using (var response = await httpClient.SendAsync(request))
        {
            var content = response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            return Ok(content);
        }
    }

But I would use IHttpClientFactory due to the problems it solves for sockets, not HttpClient.

In order to use the IHttpClientFactory do the following

Add the service to the ConfigureServices.cs

  services.AddHttpClient();

then inject the call into the constructor

    private readonly IHttpClientFactory _clientFactory;

    public ValuesController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

then your API call would be the following

var url = "https://api.plos.org/search?q=title:DNA";

        var request = new HttpRequestMessage(HttpMethod.Get, url);

        var httpClient = _clientFactory.CreateClient();

        using (var response = await httpClient.SendAsync(request))
        {
            var content = response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            return Ok(content);
        }


问:
Swift: How many of the same object in array
I have a CollectionView with items like...

```<code>Fruit(name: String, price: Int, imageUrl: String)
</code>```

The user can select multiple Fruits and then proceed to a "checkout" which is a UITableView with all the fruits selected.
The UITableViewCell contains: amountLabel, fruitLabel, priceLabel.

I want to show how many of each fruit and the total price is, in this view.

What is the best way to do this?

What I see now :

```<code>Banana - 1$
Orange - 3$
Banana - 1$
Apple - 2$
Apple - 2$
Banana - 1$
Orange - 3$
Orange - 3$

total: 16$
</code>```

What I want to see:

```<code>3x Banana - 3$
2x Apple - 4$
3x Orange - 9$

total: 16$
</code>```

答:
This is a perfect case for NSCountedSet.

You can see the documentation for NSCountedSet here.

You can create an NSCountedSet like...

```<code>let countedSet = NSCountedSet(array: fruits)
</code>```

and then get info out of it like...

```<code>countedSet.objectEnumerator.forEach {
    let count = countedSet.count(for: $0)

    print($0.name, count, count * $0.price)
}
</code>```

For your table view you can use countedSet.objectEnumerator.allObjects.count for the number of rows.

Body:
I have a CollectionView with items like...

Fruit(name: String, price: Int, imageUrl: String)

The user can select multiple Fruits and then proceed to a "checkout" which is a UITableView with all the fruits selected.
The UITableViewCell contains: amountLabel, fruitLabel, priceLabel.

I want to show how many of each fruit and the total price is, in this view.

What is the best way to do this?

What I see now :

Banana - 1$
Orange - 3$
Banana - 1$
Apple - 2$
Apple - 2$
Banana - 1$
Orange - 3$
Orange - 3$

total: 16$

What I want to see:

3x Banana - 3$
2x Apple - 4$
3x Orange - 9$

total: 16$

Body:
This is a perfect case for NSCountedSet.

You can see the documentation for NSCountedSet here.

You can create an NSCountedSet like...

let countedSet = NSCountedSet(array: fruits)

and then get info out of it like...

countedSet.objectEnumerator.forEach {
    let count = countedSet.count(for: $0)

    print($0.name, count, count * $0.price)
}

For your table view you can use countedSet.objectEnumerator.allObjects.count for the number of rows.


问:
Advantages and Disadvantages of static methods and functions
I know that functions are independent from any class and static methods are attached to a class. It looks like both of them achieve the same. This leads me to the following question: What are the advantages and disadvantages of them?

I want to create set of functions for offline PIN configuration like setPin, changePin, verifyPin. Do I have to wrap them inside a class as static methods or can I just create them as functions in a Dart file?

答:
There are no clear "Advantages and Disadvantage" of static methods versus functions.

As you have correctly pointed out, the only difference is that static members are connected to a class.

class A {
  static bool b() => false;
}

bool c() => true;
```

The only difference here would be that you need to access the static member via A.b and c can be accessed directly.

Static methods are not even inherited, meaning that class B extends A {} will not allow you to use B.b because b is a static member of A.

Having said that, @jamesdlin pointed out an article for writing good Dart design. This article describes that you should avoid creating classes with only static members and calls it bad design, i.e. not idiomatic Dart:

In idiomatic Dart, classes define kinds of objects. A type that is never instantiated is a code smell.

Coming back to your question, you should probably create your functions as top-level functions if they are not part of an object according to idiomatic Dart design based on the article from the Dart team.

However, you might consider changing the way you store your "PIN configuration" because this sounds like it would be ideal to store this information as an object.

Body:
There are no clear "Advantages and Disadvantage" of static methods versus functions.

As you have correctly pointed out, the only difference is that static members are connected to a class.

class A {
  static bool b() => false;
}

bool c() => true;

The only difference here would be that you need to access the static member via A.b and c can be accessed directly.

Static methods are not even inherited, meaning that class B extends A {} will not allow you to use B.b because b is a static member of A.

Having said that, @jamesdlin pointed out an article for writing good Dart design. This article describes that you should avoid creating classes with only static members and calls it bad design, i.e. not idiomatic Dart:

In idiomatic Dart, classes define kinds of objects. A type that is never instantiated is a code smell.

Coming back to your question, you should probably create your functions as top-level functions if they are not part of an object according to idiomatic Dart design based on the article from the Dart team.

However, you might consider changing the way you store your "PIN configuration" because this sounds like it would be ideal to store this information as an object.


问:
I need to skip three rows from the dataframe while loading from a CSV file in scala
I am loading my CSV file to a data frame and I can do that but I need to skip the starting three lines from the file.

I tried .option() command by giving header as true but it is ignoring the only first line.

```<code>val df = spark.sqlContext.read
    .schema(Myschema)
    .option("header",true)
    .option("delimiter", "|")
    .csv(path)
</code>```

I thought of giving header as 3 lines but I couldn't find the way to do that.

alternative thought: skip those 3 lines from the data frame

Please help me with this. Thanks in Advance.

答:
A generic way to handle your problem would be to index the dataframe and filter the indices that are greater than 2.

Straightforward approach:

As suggested in another answer, you may try adding an index with monotonically_increasing_id.

df.withColumn("Index",monotonically_increasing_id)
  .filter('Index > 2)
  .drop("Index")
```

<p>Yet, that's only going to work if the first 3 rows are in the first partition. Moreover, as mentioned in the comments, this is the case today but this code may break completely with further versions or spark and that would be very hard to debug. Indeed, the contract in the API is just "The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive". It is therefore not very sage to assume that they will always start from zero. There might even be other cases in the current version in which that does not work (I'm not sure though).</p>

<p>To illustrate my first concern, have a look at this:</p>

<pre class="lang-scala prettyprint-override"><code>scala> spark.range(4).withColumn("Index",monotonically_increasing_id()).show()
+---+----------+
| id|     Index|
+---+----------+
|  0|         0|
|  1|         1|
|  2|8589934592|
|  3|8589934593|
+---+----------+
</code>```

We would only remove two rows...

Safe approach:

The previous approach will work most of the time though but to be safe, you can use zipWithIndex from the RDD API to get consecutive indices.

def zipWithIndex(df : DataFrame, name : String) : DataFrame = {
  val rdd = df.rdd.zipWithIndex
    .map{ case (row, i) => Row.fromSeq(row.toSeq :+ i) }
  val newSchema = df.schema
    .add(StructField(name, LongType, false))
  df.sparkSession.createDataFrame(rdd, newSchema)
}
zipWithIndex(df, "index").where('index > 2).drop("index")
```

<p>We can check that it's safer:</p>

<pre class="lang-scala prettyprint-override"><code>scala> zipWithIndex(spark.range(4).toDF("id"), "index").show()
+---+-----+
| id|index|
+---+-----+
|  0|    0|
|  1|    1|
|  2|    2|
|  3|    3|
+---+-----+
</code>```

Body:
I am loading my CSV file to a data frame and I can do that but I need to skip the starting three lines from the file.

I tried .option() command by giving header as true but it is ignoring the only first line.

val df = spark.sqlContext.read
    .schema(Myschema)
    .option("header",true)
    .option("delimiter", "|")
    .csv(path)

I thought of giving header as 3 lines but I couldn't find the way to do that.

alternative thought: skip those 3 lines from the data frame

Please help me with this. Thanks in Advance.

Body:
A generic way to handle your problem would be to index the dataframe and filter the indices that are greater than 2.

Straightforward approach:

As suggested in another answer, you may try adding an index with monotonically_increasing_id.

df.withColumn("Index",monotonically_increasing_id)
  .filter('Index > 2)
  .drop("Index")

Yet, that's only going to work if the first 3 rows are in the first partition. Moreover, as mentioned in the comments, this is the case today but this code may break completely with further versions or spark and that would be very hard to debug. Indeed, the contract in the API is just "The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive". It is therefore not very sage to assume that they will always start from zero. There might even be other cases in the current version in which that does not work (I'm not sure though).

To illustrate my first concern, have a look at this:

scala> spark.range(4).withColumn("Index",monotonically_increasing_id()).show()
+---+----------+
| id|     Index|
+---+----------+
|  0|         0|
|  1|         1|
|  2|8589934592|
|  3|8589934593|
+---+----------+

We would only remove two rows...

Safe approach:

The previous approach will work most of the time though but to be safe, you can use zipWithIndex from the RDD API to get consecutive indices.

def zipWithIndex(df : DataFrame, name : String) : DataFrame = {
  val rdd = df.rdd.zipWithIndex
    .map{ case (row, i) => Row.fromSeq(row.toSeq :+ i) }
  val newSchema = df.schema
    .add(StructField(name, LongType, false))
  df.sparkSession.createDataFrame(rdd, newSchema)
}
zipWithIndex(df, "index").where('index > 2).drop("index")

We can check that it's safer:

scala> zipWithIndex(spark.range(4).toDF("id"), "index").show()
+---+-----+
| id|index|
+---+-----+
|  0|    0|
|  1|    1|
|  2|    2|
|  3|    3|
+---+-----+


问:
Facebook Event Json Mesage- how can i get it?
I would like to ask if someone know how to grab a facebook event json message. It doesnt matter if it has to happen programatically. I just want to be able to read the message one way or another.

thanks in advance.

P.s. Maybe an awful question but here you go !!!

答:
I once had to code a small chunk of code to parse a json-encapsulated message. However recently I found out there's a handy solution for it if you use Java

Resty is a small, convenient library
  to talk to RESTful services from Java.
  It’s surprisingly complex to do the
  simplest HTTP calls with the standard
  Java library. Resty hopes to change
  that.

http://beders.github.com/Resty/Resty/Overview.html

```<code>    Resty r = new Resty();
Object name = r.json("http://ws.geonames.org
   /postalCodeLookupJSON?postalcode=66780&country=DE")
  .get("postalcodes[0].placeName");
</code>```

Just import a small jar lib and you'll be surprised. I currently use this class for getting info from url API.

ContentLicense: CC BY-SA 3.0

Body:
I once had to code a small chunk of code to parse a json-encapsulated message. However recently I found out there's a handy solution for it if you use Java

Resty is a small, convenient library
  to talk to RESTful services from Java.
  It’s surprisingly complex to do the
  simplest HTTP calls with the standard
  Java library. Resty hopes to change
  that.

http://beders.github.com/Resty/Resty/Overview.html

    Resty r = new Resty();
Object name = r.json("http://ws.geonames.org
   /postalCodeLookupJSON?postalcode=66780&country=DE")
  .get("postalcodes[0].placeName");

Just import a small jar lib and you'll be surprised. I currently use this class for getting info from url API.


问:
Cann't give access to certificat and identifiers to my developer
Since the merge of user roles management between the appstoreconnect and apple developer accounts, i haven't been able to give access to my team on appstoreconnect to the certificats and identifiers.

It's always disabled and I can't check it.

答:
Simple answer: You can't invite people to resources over at https://developer.apple.com/account with a personal account. Therefore the checkbox is greyed out and not clickable.

Simply go over to https://developer.apple.com/account to check your enrollment. There you can find your "Entity Type" (> Membership)


问:
Specify specific certificate when encrypting web.config connection string section
Is there any possibility of encrypt sections in web.config with a specific certificate (not de default one), so I can read the same web.config in different machines?

Or... encrypt sections so two servers can decrypt automatically?

Both machines are Windows Server 2019

Thanks a lot.

答:
According to your descritpion, I suggest you could try to follow below steps to encrypt the web.config and decrypt the web.config by using certificate.

1.Create a certificate to encrypt the config file.

$cert = New-SelfSignedCertificate -Type DocumentEncryptionCert -Subject "CN=DevConfig" -KeyExportPolicy Exportable -KeySpec KeyExchange

```<code>Export-Certificate -Cert $cert -FilePath ".\DevConfig.cer"

$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText

Export-PfxCertificate -Cert $cert -FilePath ".\DevConfig.pfx" -Password $mypwd

$cert
</code>```

2.Improt the encypt certificate:

```<code>Import-Certificate -Filepath ".\DevConfig.cer" -CertStoreLocation cert:\LocalMachine\My
</code>```

3.Imprort the decrypt certificate:

```<code>$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText

Import-PfxCertificate -FilePath ".\DevConfig.pfx" -CertStoreLocation Cert:\LocalMachine\My -Password $mypwd
</code>```

4.Install the WebConfigEncrypter NuGet package.

```<code>Install-Package WebConfigEncrypter -Version 1.1.0
</code>```

5.Add below config into web.config file. Notice: you should find the thumbprint from the generated certificate file like below:

```<code>  <configProtectedData>
    <providers>
      <add name="Pkcs12Provider" thumbprint="91cb0b7c611e54f6bfd43c4d8d178b542bc6557e" type="WebConfigEncrypter.Pkcs12ProtectedConfigurationProvider, WebConfigEncrypter" storeLocation="LocalMachine"/>
    </providers>
  </configProtectedData>
</code>```

6.Run below command in the web.config file fodler:

```<code>aspnet_regiis -pef "connectionStrings" "." -prov "Pkcs12Provider"
</code>```

7.You will find your web.config is encrypted, but if you improt the decrypt certificatie in the remote server, you will find your application work well.

Body:
According to your descritpion, I suggest you could try to follow below steps to encrypt the web.config and decrypt the web.config by using certificate.

1.Create a certificate to encrypt the config file.

$cert = New-SelfSignedCertificate -Type DocumentEncryptionCert -Subject "CN=DevConfig" -KeyExportPolicy Exportable -KeySpec KeyExchange

Export-Certificate -Cert $cert -FilePath ".\DevConfig.cer"

$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText

Export-PfxCertificate -Cert $cert -FilePath ".\DevConfig.pfx" -Password $mypwd

$cert

2.Improt the encypt certificate:

Import-Certificate -Filepath ".\DevConfig.cer" -CertStoreLocation cert:\LocalMachine\My

3.Imprort the decrypt certificate:

$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText

Import-PfxCertificate -FilePath ".\DevConfig.pfx" -CertStoreLocation Cert:\LocalMachine\My -Password $mypwd

4.Install the WebConfigEncrypter NuGet package.

Install-Package WebConfigEncrypter -Version 1.1.0

5.Add below config into web.config file. Notice: you should find the thumbprint from the generated certificate file like below:

  <configProtectedData>
    <providers>
      <add name="Pkcs12Provider" thumbprint="91cb0b7c611e54f6bfd43c4d8d178b542bc6557e" type="WebConfigEncrypter.Pkcs12ProtectedConfigurationProvider, WebConfigEncrypter" storeLocation="LocalMachine"/>
    </providers>
  </configProtectedData>

6.Run below command in the web.config file fodler:

aspnet_regiis -pef "connectionStrings" "." -prov "Pkcs12Provider"

7.You will find your web.config is encrypted, but if you improt the decrypt certificatie in the remote server, you will find your application work well.


问:
Union-Find Algorithm (Finding Cycle) Without Using Malloc
I've been advised that using malloc in a c++ program shouldn't be done. How can I convert this to a non-malloc code? Thank you!

https://www.geeksforgeeks.org/union-find-algorithm-set-2-union-by-rank/

答:
In C++ you should use new operator instead of malloc. E.g. (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); should be new Edge[graph->E];. It reduces the boilerplate and makes code less error-prone.

Don't forget to use delete or delete[] instead of free. Otherwise the behaviour is undefined.


问:
get null response from node in angular7 using subscribe function
```<code>router.post('/login', function (req, res) {
  let username = req.body.username;
  let password = req.body.password;
  console.log(username, "===> username");
  console.log(password, "===> password");

      User.findOne({
        username: req.body.username,
        },function (err, user) {
        if (err) {
          res.status(502).send({
            "Message": "Db error",
            "error": err
          });
          console.log("login if");
        }
        //console.log("log",user)
            if (user) {
              if (user.username === req.body.username && user.password == req.body.password) {
                    var token = jwt.sign({
                      username: req.body.username,
                    },process.env.SECRET_KEY, {
                        expiresIn: parseInt(process.env.EXPIRY_TIME)
                      });
                    res.send({
                      Message: "logged in sucessfully",
                      Token: token
                    })
              }
            } else {
                res.status(404).send({
                Message: "not found",
                })
              }
      });

});
</code>```

//above code is of server side it sends response to postman and also sends true to client but cant send object

//and below code is of login.component.ts file

```<code> login() {
     this.loginservice.authenticate(this.username, this.password)
        .subscribe((res) => {
              console.log(" user is",res);
              localStorage.setItem("user",res.toString());
                this.router.navigate(['dashboard']);
            }, (error) => {
              console.log(error);
            });
}
</code>```

//and the last code is of service
  authenticate(username, password) {

```<code>  const url = environment.binanceserver + '/users/login';
    console.log("Endpoint being hit", url, username, password);
    const obj = {
      "username": username,
      "password": password
    }
    return this.http.post(url, obj);
</code>```

答: You need to enable CORS from the server side to accept request from other origins. You can use cors to enable CORS in express/node.</p>

Body:
router.post('/login', function (req, res) {
  let username = req.body.username;
  let password = req.body.password;
  console.log(username, "===> username");
  console.log(password, "===> password");

      User.findOne({
        username: req.body.username,
        },function (err, user) {
        if (err) {
          res.status(502).send({
            "Message": "Db error",
            "error": err
          });
          console.log("login if");
        }
        //console.log("log",user)
            if (user) {
              if (user.username === req.body.username && user.password == req.body.password) {
                    var token = jwt.sign({
                      username: req.body.username,
                    },process.env.SECRET_KEY, {
                        expiresIn: parseInt(process.env.EXPIRY_TIME)
                      });
                    res.send({
                      Message: "logged in sucessfully",
                      Token: token
                    })
              }
            } else {
                res.status(404).send({
                Message: "not found",
                })
              }
      });

});

//above code is of server side it sends response to postman and also sends true to client but cant send object

//and below code is of login.component.ts file

 login() {
     this.loginservice.authenticate(this.username, this.password)
        .subscribe((res) => {
              console.log(" user is",res);
              localStorage.setItem("user",res.toString());
                this.router.navigate(['dashboard']);
            }, (error) => {
              console.log(error);
            });
}

//and the last code is of service
  authenticate(username, password) {

  const url = environment.binanceserver + '/users/login';
    console.log("Endpoint being hit", url, username, password);
    const obj = {
      "username": username,
      "password": password
    }
    return this.http.post(url, obj);


问:
How to create unique Id per request for REST API in Spring-boot?
I need to make my logs (log4j engine) to be more informative with a unique id per request for my REST API in Spring-Boot application.

I want to avoid using a superclass which got requestId field and extend from it.

I tried to look for a good example over the web, but it wasn't so clear.

Is there any best practice that I can use?

答:
Using a field for such a feature would just cause problems during the integration testing on the first glance..

Ideally, just follow an SRP principle and include the generation logic inside a dedicated class which you could make an injectable @Component.. MyIdGenerator etc.

There you could have a synchronized method generateId().

Now you could use it in whichever controller it is needed and also you could set-up your integration test more easily and have more control over them.

Update:

You could take also advantage of HandleInterceptorAdapter if this should be a global strategy:

```<code>@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

    /* generate unique id here and log what is needed */

    }
</code>```

You can encapsulate the ID generation and logging inside this class.

Body:
Using a field for such a feature would just cause problems during the integration testing on the first glance..

Ideally, just follow an SRP principle and include the generation logic inside a dedicated class which you could make an injectable @Component.. MyIdGenerator etc.

There you could have a synchronized method generateId().

Now you could use it in whichever controller it is needed and also you could set-up your integration test more easily and have more control over them.

Update:

You could take also advantage of HandleInterceptorAdapter if this should be a global strategy:

@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

    /* generate unique id here and log what is needed */

    }

You can encapsulate the ID generation and logging inside this class.


问:
Which file to locate to see data of database in SQLite browser
I'm creating a database "UserDataBase.db" and while opening this in SQLite browser neither data nor tables is being shown if I am doing any CRUD operations then it works.I am providing images link also regarding which file I am locating in SQLite browser.First I am synchronizing these files and saving on Desktop and opening in SQLite browser.I have tried to fetch the data from the database it works fine.

答: As the database is just 4k and that the -wal file is 80.5k the data hasn't been written/comitted. You need to close the database or checkpoint the database and then copy the file. Or you could copy the -wal and -shm files into DB Browser open it and then close it and then re-open it.</p>


问:
Loading Multiple files Parallelly in ODI12c
I am working in ODI12c Project. I have a Scenario in which i need to load multiple files in a single table Parallelly.
I tried through file List and using Loop in ODI package,but its loading data in serial i.e. 1st file then 2nd file etc.
Please suggest how should i load data Parallelly.</p>

答: If you want to load multiple files in odi in one go you can merge all those files in one single file and load it in a single go. I'm considering all files have same structure. if you want to load them separately then creating separate model for each file will be headache and re usability of code will also compromised. You can run scenarios in asynchronous mode to made them run independent .  I believe this is my best answer till now.</p>


问:
move files that no not contain specific string
I would like to move files using mv that do not contain the letter S in the filename. Could not find anyhting in the mv manual. Maybe combination with find or grep? It has to be case-sensitive.

input:

```<code>  file1
  fileS1
  file2
  fileS2
</code>```

file to move:

```<code>  file1
  file2
</code>```

答:
You can do the selection in pure Bash without any extra software, if you enable extended globbing, which is off by default:

```<code>shopt -s extglob
mv !(*S*) /target/dir
</code>```

For more information, search for extglob in the bash(1) manual page (the info is at the second match).

Body:
I would like to move files using mv that do not contain the letter S in the filename. Could not find anyhting in the mv manual. Maybe combination with find or grep? It has to be case-sensitive.

input:

  file1
  fileS1
  file2
  fileS2

file to move:

  file1
  file2

Body:
You can do the selection in pure Bash without any extra software, if you enable extended globbing, which is off by default:

shopt -s extglob
mv !(*S*) /target/dir

For more information, search for extglob in the bash(1) manual page (the info is at the second match).


问:
How to fix os.PathSeparator unzipping files zipped on Windows?
I'm zipping files on Windows and when unzip on Linux, using the os default application, it doesn't create the folders along the path but a single file named "indexes\search.invcus\index_meta.json" e.g.:

```<code>unzip 2019-05-23_113735_data.zip -d xfolder
Archive:  2019-05-23_113735_data.zip
  inflating: xfolder/indexes\search.invcus\index_meta.json
  inflating: xfolder/indexes\search.invcus\store
  inflating: xfolder/indexes\search.items\index_meta.json
  inflating: xfolder/indexes\search.items\store
  inflating: xfolder/indexes\search.subjects\index_meta.json
  inflating: xfolder/indexes\search.subjects\store
  inflating: xfolder/indexes\search.users\index_meta.json
  inflating: xfolder/indexes\search.users\store
  inflating: xfolder/data.db
</code>```

I get the correct folders and files only if the zip file is created on Linux and unzipped on Windows using 7zip, etc...

```<code>func zipFiles(filename string, files []string) error {

    newZipFile, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer newZipFile.Close()

    zipWriter := zip.NewWriter(newZipFile)
    defer zipWriter.Close()

    // Add files to zip
    for _, file := range files {
        if err = addFileToZip(zipWriter, file); err != nil {
            return err
        }
    }
    return nil
}

func addFileToZip(zipWriter *zip.Writer, filename string) error {
    fileToZip, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer fileToZip.Close()

    // Get the file information
    info, err := fileToZip.Stat()
    if err != nil {
        return err
    }

    header, err := zip.FileInfoHeader(info)
    if err != nil {
        return err
    }

    // Using FileInfoHeader() above only uses the basename of the file. If we want
    // to preserve the folder structure we can overwrite this with the full path.
    header.Name = filename

    // Change to deflate to gain better compression
    // see http://golang.org/pkg/archive/zip/#pkg-constants
    header.Method = zip.Deflate

    writer, err := zipWriter.CreateHeader(header)
    if err != nil {
        return err
    }
    _, err = io.Copy(writer, fileToZip)
    return err
}

</code>```

I expect:

```<code> indexes (folder)
     search.invcus (folder)
         index_meta.json (file)

</code>```

答:
Did you check out convert a windows created zip to Linux internal paths issue? Seems like something gone wrong while creating that zip file.

Or alternatively, from those answers:

Use 7z rn to rename the files within the archive so that they have a forward slash. Then when you extract the archive, directories will be created.

Body:
I'm zipping files on Windows and when unzip on Linux, using the os default application, it doesn't create the folders along the path but a single file named "indexes\search.invcus\index_meta.json" e.g.:

unzip 2019-05-23_113735_data.zip -d xfolder
Archive:  2019-05-23_113735_data.zip
  inflating: xfolder/indexes\search.invcus\index_meta.json
  inflating: xfolder/indexes\search.invcus\store
  inflating: xfolder/indexes\search.items\index_meta.json
  inflating: xfolder/indexes\search.items\store
  inflating: xfolder/indexes\search.subjects\index_meta.json
  inflating: xfolder/indexes\search.subjects\store
  inflating: xfolder/indexes\search.users\index_meta.json
  inflating: xfolder/indexes\search.users\store
  inflating: xfolder/data.db

I get the correct folders and files only if the zip file is created on Linux and unzipped on Windows using 7zip, etc...

func zipFiles(filename string, files []string) error {

    newZipFile, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer newZipFile.Close()

    zipWriter := zip.NewWriter(newZipFile)
    defer zipWriter.Close()

    // Add files to zip
    for _, file := range files {
        if err = addFileToZip(zipWriter, file); err != nil {
            return err
        }
    }
    return nil
}

func addFileToZip(zipWriter *zip.Writer, filename string) error {
    fileToZip, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer fileToZip.Close()

    // Get the file information
    info, err := fileToZip.Stat()
    if err != nil {
        return err
    }

    header, err := zip.FileInfoHeader(info)
    if err != nil {
        return err
    }

    // Using FileInfoHeader() above only uses the basename of the file. If we want
    // to preserve the folder structure we can overwrite this with the full path.
    header.Name = filename

    // Change to deflate to gain better compression
    // see http://golang.org/pkg/archive/zip/#pkg-constants
    header.Method = zip.Deflate

    writer, err := zipWriter.CreateHeader(header)
    if err != nil {
        return err
    }
    _, err = io.Copy(writer, fileToZip)
    return err
}

I expect:

 indexes (folder)
     search.invcus (folder)
         index_meta.json (file)


问:
C# strange with DateTime
I got some strange result for:

```<code>Console.WriteLine(new DateTime(1296346155).ToString());
</code>```

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

答:
Ive found the following subject where there is a conversion between unix timestamp (the one you have) and .Net DateTime

How to convert a Unix timestamp to DateTime and vice versa?

Title: C# strange with DateTime

Body:
I got some strange result for:

Console.WriteLine(new DateTime(1296346155).ToString());

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))


问:
React js redirect not redirecting
For some reason, I can't understand redirect is not working.
I don't get any error.
The Redirect is called from react-router-dom library
in the console I see the xxx.

** added **
for some reason the redirect returns an error

this is the redirect block:

```<code>redirectUser = (json) => {
    console.log('json', json);
    console.log('state', this.state);
    if(this.state.auth == true){
        localStorage.setItem('userid', json.userid);
        localStorage.setItem('auth', this.state.auth);
        console.log('xxx');
        return <Redirect to='/biblist' />
    }
}
</code>```

this is the file data from chrome dev sources:

this is the entire component.

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { Redirect, Link } from 'react-router-dom';

import {
    Button,
    Form,
    FormGroup,
    FormControl,
    Col,
    Alert,
    Checkbox,
    ControlLabel,
    HelpBlock,
    Grid,
    Row
} from 'react-bootstrap';

import { userLogedIn } from '../../actions';

class LoginForm extends Component {
    constructor() {
        super();
        this.state={
            username: '',
            password: '',
            data: [],
            auth: false,
            usernameError: '',
            passwordError: '',
            EmptyUsernameError: '',
            EmptyPasswordError: ''
        }
        this.onSubmitLogin = this.onSubmitLogin.bind(this);
        this.onChange = this.onChange.bind(this);

    }

    componentWillMount(){
        console.log('mount', this.props);
    }
    componentDidUpdate(){
        console.log('Update', this.props);
        console.log('Update username',  this.props.userid);

    }

    clientValidate = () => {
        let isError = false;

        if(this.state.username === ''){
            isError = true;
            this.setState({EmptyUsernameError: 'לא הזנתם שם משתמש'});
        }
        if(this.state.password === ''){
            isError = true;
            this.setState({EmptyPasswordError: 'לא הזנתם סיסמה'});
        }

        return isError;
    }

    validate = () => {
        let isError = false;

        if(this.state.auth === false){
            isError = true;
            this.setState({usernameError: 'אחד הפרטים שהזנתם שגוי'});
        }

        return isError;
    }

    onSubmitLogin(event){
        event.preventDefault();

        if(this.clientValidate()){
            this.clientValidate();
        }else{
        fetch('http://127.0.0.1/bibli/api/user_switch/' + this.state.username +
        '/'+ this.state.password )
        .then(response => response.json())
        .then(json => {
            if(json.count > 0)
            {
                this.setState({auth: true});
                this.props.userLogedIn(json);
                this.redirectUser(json);
            }else{
                let isError = true;
                this.validate();
                this.setState({
                    auth: false,
                    data: null
                });
            }

        })
        .catch(error => console.log('parsing faild', error))
    }

    }

    redirectUser = (json) => {
        console.log('json', json);
        console.log('state', this.state);
        if(this.state.auth == true){
            localStorage.setItem('userid', json.userid);
            localStorage.setItem('auth', this.state.auth);
            console.log('xxx');
            debugger
            return <Redirect to='/biblist' />
        }
    }

    onChange(event){
        this.setState({
            [event.target.name]: event.target.value,
            auth: false,
            usernameError: '',
            EmptyPasswordError: '',
            EmptyUsernameError: ''
        })

    }

    render() {

        return (
            <Grid fluid id="LoginForm" className="yellow-bg">

                <Row className="show-grid">
                    <Col xsOffset={2} xs={8} mdOffset={3} md={6}>
                        <h2 className="text-center">כבר רשומים? התחברו!</h2>
                        <Form horizontal>
                            <FormGroup  controlId="formHorizontalusername">
                                <Col xs={12} sm={4}>
                                    <FormControl ref="username" name="username" type="text" onChange={this.onChange} placeholder="הקלד דואר אלקטרוני"/>

                                </Col>
                                <Col xs={12} sm={4}>
                                    <FormControl ref="password" name="password" type="password" onChange={this.onChange} placeholder="הקלד סיסמא"/>

                                </Col>

                                <Col  xs={12} sm={4} >

                                    <Button onClick={this.onSubmitLogin} type="submit" className="full-width-btn" id="loginSubmit">התחבר</Button>

                                    </Col>

                            </FormGroup>
                            {
                                this.state.EmptyUsernameError ?
                                <Alert variant="danger"> {this.state.EmptyUsernameError} </Alert> :
                                ''
                            }
                            {
                                this.state.EmptyPasswordError ?
                                <Alert variant="danger"> {this.state.EmptyPasswordError} </Alert> :
                                ''
                            }

                            {
                                this.state.usernameError ?
                                <Alert variant="danger"> {this.state.usernameError} </Alert> :
                                ''
                            }
                            <small><Link to="/register">אינך רשום? הרשם!</Link></small>
                        </Form>
                    </Col>
                </Row>
            </Grid>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        userLogedIn: (params) => dispatch(userLogedIn(params))
    };
};

const mapStateToProps = state => {
    return {
        userid: state.authReducer.userid,
        auth: state.authReducer.auth
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
</code>```

答:
You could try with "withRouter" HOC

Example :

```<code>import { withRouter } from 'react-router-dom'

const Button = ({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
)

export default withRouter(Button)
</code>```

Title: React js redirect not redirecting

Body:
For some reason, I can't understand redirect is not working.
I don't get any error.
The Redirect is called from react-router-dom library
in the console I see the xxx.

** added **
for some reason the redirect returns an error

this is the redirect block:

redirectUser = (json) => {
    console.log('json', json);
    console.log('state', this.state);
    if(this.state.auth == true){
        localStorage.setItem('userid', json.userid);
        localStorage.setItem('auth', this.state.auth);
        console.log('xxx');
        return <Redirect to='/biblist' />
    }
}

this is the file data from chrome dev sources:

this is the entire component.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { Redirect, Link } from 'react-router-dom';

import {
    Button,
    Form,
    FormGroup,
    FormControl,
    Col,
    Alert,
    Checkbox,
    ControlLabel,
    HelpBlock,
    Grid,
    Row
} from 'react-bootstrap';

import { userLogedIn } from '../../actions';

class LoginForm extends Component {
    constructor() {
        super();
        this.state={
            username: '',
            password: '',
            data: [],
            auth: false,
            usernameError: '',
            passwordError: '',
            EmptyUsernameError: '',
            EmptyPasswordError: ''
        }
        this.onSubmitLogin = this.onSubmitLogin.bind(this);
        this.onChange = this.onChange.bind(this);

    }

    componentWillMount(){
        console.log('mount', this.props);
    }
    componentDidUpdate(){
        console.log('Update', this.props);
        console.log('Update username',  this.props.userid);

    }

    clientValidate = () => {
        let isError = false;

        if(this.state.username === ''){
            isError = true;
            this.setState({EmptyUsernameError: 'לא הזנתם שם משתמש'});
        }
        if(this.state.password === ''){
            isError = true;
            this.setState({EmptyPasswordError: 'לא הזנתם סיסמה'});
        }

        return isError;
    }

    validate = () => {
        let isError = false;

        if(this.state.auth === false){
            isError = true;
            this.setState({usernameError: 'אחד הפרטים שהזנתם שגוי'});
        }

        return isError;
    }

    onSubmitLogin(event){
        event.preventDefault();

        if(this.clientValidate()){
            this.clientValidate();
        }else{
        fetch('http://127.0.0.1/bibli/api/user_switch/' + this.state.username +
        '/'+ this.state.password )
        .then(response => response.json())
        .then(json => {
            if(json.count > 0)
            {
                this.setState({auth: true});
                this.props.userLogedIn(json);
                this.redirectUser(json);
            }else{
                let isError = true;
                this.validate();
                this.setState({
                    auth: false,
                    data: null
                });
            }

        })
        .catch(error => console.log('parsing faild', error))
    }

    }

    redirectUser = (json) => {
        console.log('json', json);
        console.log('state', this.state);
        if(this.state.auth == true){
            localStorage.setItem('userid', json.userid);
            localStorage.setItem('auth', this.state.auth);
            console.log('xxx');
            debugger
            return <Redirect to='/biblist' />
        }
    }

    onChange(event){
        this.setState({
            [event.target.name]: event.target.value,
            auth: false,
            usernameError: '',
            EmptyPasswordError: '',
            EmptyUsernameError: ''
        })

    }

    render() {

        return (
            <Grid fluid id="LoginForm" className="yellow-bg">

                <Row className="show-grid">
                    <Col xsOffset={2} xs={8} mdOffset={3} md={6}>

כבר רשומים? התחברו!

                        <Form horizontal>
                            <FormGroup  controlId="formHorizontalusername">
                                <Col xs={12} sm={4}>
                                    <FormControl ref="username" name="username" type="text" onChange={this.onChange} placeholder="הקלד דואר אלקטרוני"/>

                                </Col>
                                <Col xs={12} sm={4}>
                                    <FormControl ref="password" name="password" type="password" onChange={this.onChange} placeholder="הקלד סיסמא"/>

                                </Col>

                                <Col  xs={12} sm={4} >

                                    <Button onClick={this.onSubmitLogin} type="submit" className="full-width-btn" id="loginSubmit">התחבר</Button>

                                    </Col>

                            </FormGroup>
                            {
                                this.state.EmptyUsernameError ?
                                <Alert variant="danger"> {this.state.EmptyUsernameError} </Alert> :
                                ''
                            }
                            {
                                this.state.EmptyPasswordError ?
                                <Alert variant="danger"> {this.state.EmptyPasswordError} </Alert> :
                                ''
                            }

                            {
                                this.state.usernameError ?
                                <Alert variant="danger"> {this.state.usernameError} </Alert> :
                                ''
                            }
                            <Link to="/register">אינך רשום? הרשם!</Link>
                        </Form>
                    </Col>
                </Row>
            </Grid>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        userLogedIn: (params) => dispatch(userLogedIn(params))
    };
};

const mapStateToProps = state => {
    return {
        userid: state.authReducer.userid,
        auth: state.authReducer.auth
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);

Body:
You could try with "withRouter" HOC

Example :

import { withRouter } from 'react-router-dom'

const Button = ({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
)

export default withRouter(Button)


问:
Changing CSS of a property via JQuery when toggling sidebar does not work
In my rails application, I am trying to change the margin of my div depending if sidebar is collapsed or not. I am using the .css() method of JQuery and I can't seem to make it work.

Here is my JS snippet:

```<code>document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    // This toggles my sidebar
    $('.collapsed-sidebar').toggleClass('displaynone');

    // Checks if the sidebar is collapsed
    if($('.collapsed-sidebar').is(":visible")){

      // So far I have verified that it triggers this alert
      // when I collapse my sidebar
      alert("collapsed sidebar is visible");

      // Class that I am trying to change the CSS Property
      $('.signedin').css({
        'margin-right': '50px !important'
      });
    }

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

Here is my HTML structure:

```<code><body>
    <div class="ui sidebar vertical left menu visible very thin icon">
        <div class="collapsed-sidebar displaynone"> // This is the element that I toggle
             // Sidebar content here
        </div>
    </div>
    <div class="pusher">
        <div class="row content">
            <div class="signedin"> // Element that I am trying to change the property
            </div>
        </div>
    </div>
</body
</code>```

Here is the CSS of my sidebar:

```<code>.displaynone {
  display: none !important;
}

.ui.sidebar.vertical.menu {
  -webkit-transition-duration: 0.1s;
  transition-duration: 0.1s;
}
</code>```

答:
I still haven't found the reason why $('.signedin').css("margin-right","50px !important"); does not work so after doing some digging, I found another approach which is similar to @emjr's answer above. This approach makes use of addClass() and removeClass() of JQuery.

So in my CSS, I added custom styles for increasing/decreasing the margin when the sidebar is collapsed or not.

```<code>.signedin {
  margin-top: 50px;
  margin-left: 50px;
  &.collapsed {
    margin-right: 100px !important;
  }
  &.uncollapsed {
    margin-right: 300px !important;
  }
}
</code>```

Then in my JS:

```<code>document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    $('.ui.sidebar').toggleClass('very thin icon');
    $('.collapsed-sidebar').toggleClass('displaynone');

    if($('.collapsed-sidebar').is(":visible")){
      $('.signedin').addClass('collapsed').removeClass('uncollapsed');
    }else{
      $('.signedin').addClass('uncollapsed').removeClass('collapsed');
    }
  });
});
</code>```

Then in my HTML:

```<code><body>
    <div class="ui sidebar vertical left menu visible very thin icon">
        <div class="collapsed-sidebar displaynone"> // This is the element that I toggle
             // Sidebar content here
        </div>
    </div>
    <div class="pusher">
        <div class="row content">
            <div class="signedin uncollapsed">
                // The uncollapsed class here is what is being removed and replaced
                //by collapsed and vice-versa depending on the state of the sidebar.
            </div>
        </div>
    </div>
</body
</code>```

So what happens is that it adds/removes the collapsed/uncollapsed classes as I toggle my sidebar.

I would still appreciate if anyone can figure out why the .css() approach didn't work and can point me to the right direction on that one.

Body:
In my rails application, I am trying to change the margin of my div depending if sidebar is collapsed or not. I am using the .css() method of JQuery and I can't seem to make it work.

Here is my JS snippet:

document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    // This toggles my sidebar
    $('.collapsed-sidebar').toggleClass('displaynone');

    // Checks if the sidebar is collapsed
    if($('.collapsed-sidebar').is(":visible")){

      // So far I have verified that it triggers this alert
      // when I collapse my sidebar
      alert("collapsed sidebar is visible");

      // Class that I am trying to change the CSS Property
      $('.signedin').css({
        'margin-right': '50px !important'
      });
    }

  });
});

Here is my HTML structure:

 // This is the element that I toggle
             // Sidebar content here

 // Element that I am trying to change the property

</body

Here is the CSS of my sidebar:

.displaynone {
  display: none !important;
}

.ui.sidebar.vertical.menu {
  -webkit-transition-duration: 0.1s;
  transition-duration: 0.1s;
}

Body:
I still haven't found the reason why $('.signedin').css("margin-right","50px !important"); does not work so after doing some digging, I found another approach which is similar to @emjr's answer above. This approach makes use of addClass() and removeClass() of JQuery.

So in my CSS, I added custom styles for increasing/decreasing the margin when the sidebar is collapsed or not.

.signedin {
  margin-top: 50px;
  margin-left: 50px;
  &.collapsed {
    margin-right: 100px !important;
  }
  &.uncollapsed {
    margin-right: 300px !important;
  }
}

Then in my JS:

document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    $('.ui.sidebar').toggleClass('very thin icon');
    $('.collapsed-sidebar').toggleClass('displaynone');

    if($('.collapsed-sidebar').is(":visible")){
      $('.signedin').addClass('collapsed').removeClass('uncollapsed');
    }else{
      $('.signedin').addClass('uncollapsed').removeClass('collapsed');
    }
  });
});

Then in my HTML:

<body>
    <div class="ui sidebar vertical left menu visible very thin icon">
        <div class="collapsed-sidebar displaynone"> // This is the element that I toggle
             // Sidebar content here
        </div>
    </div>
    <div class="pusher">
        <div class="row content">
            <div class="signedin uncollapsed">
                // The uncollapsed class here is what is being removed and replaced
                //by collapsed and vice-versa depending on the state of the sidebar.
            </div>
        </div>
    </div>
</body

So what happens is that it adds/removes the collapsed/uncollapsed classes as I toggle my sidebar.

I would still appreciate if anyone can figure out why the .css() approach didn't work and can point me to the right direction on that one.


问:
How to fix 'Unchecked cast from MyClass to T'
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

```<code>private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}
</code>```

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.

答:
As mentioned by Sweeper already in their answer, you can just change the type of sonarObject to T:

```<code>T sonarObject;
</code>```

You can also improve your code by using a do-while loop which reduces the redundancy you have:

```<code>private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> list) {
    int page = 1;
    T sonarObject;
    do {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        list.add(sonarObject);
    } while (sonarObject.canContinueLooping(++page));
}
</code>```

Body:
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.

Body:
As mentioned by Sweeper already in their answer, you can just change the type of sonarObject to T:

T sonarObject;

You can also improve your code by using a do-while loop which reduces the redundancy you have:

private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> list) {
    int page = 1;
    T sonarObject;
    do {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        list.add(sonarObject);
    } while (sonarObject.canContinueLooping(++page));
}


问:
Can I use the normal form of a value to avoid incomplete pattern matches in Agda?
In the following Agda program, I get a warning about a missing case in the definition of one, despite the fact that myList only fits the cons case.

open import Data.Nat

data List (A : Set) : Set where
  nil : List A
  cons : A → List A → List A

myList : List ℕ
myList = cons 1 (cons 2 (cons 3 nil))

one : ℕ
one with myList
... | (cons x xs) = x
```

<pre class="lang-none prettyprint-override"><code>Incomplete pattern matching for .test.with-16. Missing
cases:
  one | nil
</code>```

I know that this sounds a bit convoluted but is there a way to define one in terms of myList, without running into "incomplete pattern matching" errors?

This example is a simplification of my original problem, which is from a homework assignment and which uses slightly more complicated types. In that case, "myList" is a large value computed by a clever function from a small input. If I compute the normal form of "myList" using Emacs' Agda Mode (C-c C-n), I can grab the value of "one" from that and paste it into my program. However, this value takes dozens of lines when printed out so I was wandering if there is a way to directly define "one" in terms of "myList", without running into the incomplete pattern matching error.

答:
If you use with e then e gets abstracted (think lambda abstraction) from the goal and context, and you are asked to continue as if you had a variable there instead of e itself. So the following pattern matching doesn't take into account the value of myList at all (which is fairly counter-intutive, but with is just syntactic sugar for creating an auxiliary definition with one extra argument).

You can however write the following:

```<code>open import Agda.Builtin.List
open import Agda.Builtin.Nat renaming (Nat to ℕ)
open import Agda.Builtin.Equality

myList : List ℕ
myList = 1 ∷ 2 ∷ 3 ∷ []

head : {n : ℕ} {ns : List ℕ} (xs : List ℕ) → n ∷ ns ≡ xs → ℕ
head (x ∷ xs) refl = x

one : ℕ
one = head myList refl
</code>```

You can also look at the inspect pattern in the standard library for a more general solution to this problem.

Body:
In the following Agda program, I get a warning about a missing case in the definition of one, despite the fact that myList only fits the cons case.

open import Data.Nat

data List (A : Set) : Set where
  nil : List A
  cons : A → List A → List A

myList : List ℕ
myList = cons 1 (cons 2 (cons 3 nil))

one : ℕ
one with myList
... | (cons x xs) = x

Incomplete pattern matching for .test.with-16. Missing
cases:
  one | nil

I know that this sounds a bit convoluted but is there a way to define one in terms of myList, without running into "incomplete pattern matching" errors?

This example is a simplification of my original problem, which is from a homework assignment and which uses slightly more complicated types. In that case, "myList" is a large value computed by a clever function from a small input. If I compute the normal form of "myList" using Emacs' Agda Mode (C-c C-n), I can grab the value of "one" from that and paste it into my program. However, this value takes dozens of lines when printed out so I was wandering if there is a way to directly define "one" in terms of "myList", without running into the incomplete pattern matching error.

Body:
If you use with e then e gets abstracted (think lambda abstraction) from the goal and context, and you are asked to continue as if you had a variable there instead of e itself. So the following pattern matching doesn't take into account the value of myList at all (which is fairly counter-intutive, but with is just syntactic sugar for creating an auxiliary definition with one extra argument).

You can however write the following:

open import Agda.Builtin.List
open import Agda.Builtin.Nat renaming (Nat to ℕ)
open import Agda.Builtin.Equality

myList : List ℕ
myList = 1 ∷ 2 ∷ 3 ∷ []

head : {n : ℕ} {ns : List ℕ} (xs : List ℕ) → n ∷ ns ≡ xs → ℕ
head (x ∷ xs) refl = x

one : ℕ
one = head myList refl

You can also look at the inspect pattern in the standard library for a more general solution to this problem.


问:
Change Double format - dot to comma
I must change Double format from dot to comma. I try this:

```<code>DecimalFormat df = new DecimalFormat("#,00",
                   DecimalFormatSymbols.getInstance(Locale.GERMANY));
selectedSheet.addCell(new Number(selectedCellColumn,
                                 selectedCellRow,
                                 Double.valueOf(df.format(value)));
</code>```

but it`s not working. Have you got any ideas how you can change a dot to a comma?

答:
new Number() - I assume this takes double as the third argument? In that case, formatting the double value before you pass it in there is  impossible, you need to set the format on how the sheet will display numbers in the cell formatting settings.

Or is the problem that you have a string like "5,3" and want to convert it to double? It looks like the varaible value already has a double value in it.

Title: Change Double format - dot to comma

Body:
I must change Double format from dot to comma. I try this:

DecimalFormat df = new DecimalFormat("#,00",
                   DecimalFormatSymbols.getInstance(Locale.GERMANY));
selectedSheet.addCell(new Number(selectedCellColumn,
                                 selectedCellRow,
                                 Double.valueOf(df.format(value)));

but it`s not working. Have you got any ideas how you can change a dot to a comma?


问:
String comparison fails in python
I am trying to build a small web app in python3 with Flask and I have a problem comparing two strings. For some reason, even if the strings are identical my function returns a false.

This is what I am trying to do:

I created a (question) form in HTML and I expect an answer from a user. When the user clicks 'Submit' a function is triggered in python that is supposed to compare the answer to the correct answer. If answer == correct_answer then a message is displayed "Excellent!!" if not something like "Try again".

def compare(str1, str2):
   if str1==str2:
      message = 'Excellent'
   else:
      message = 'Try again'
   return message
```

<p>Then I retrieve the answer from the web form and also my correct answer from a .txt file (this is a temporary file that will only contain the correct answer) and call the function:
...</p>

```answer=request.args.get('answer') #this works - value from the webform
f = open('temp.txt', 'r') #this works
correct_answer=f.read() #this works
f.close()

result=compare(answer, correct_answer) # this one always returns 'Try again'
```

<p>So, the problem is that no matter what the answer is the result is always false.</p>

<p>Just to be sure that I have the same values I tried:</p>

```print(answer)
print(correct_answer)
```

<p>and I have the same value, but the function returns false</p>

<p>I tried:</p>

```print(type(answer))
print(type(correct_answer))
```

The result is 'str' for both print.

Any idea why this is not working?

答:
It's possible that there are leading or trailing whitespaces or newlines in either of the strings, hence it might be better to strip those characters are then compare.</p>

```<code>def compare(str1, str2):
   #Strip both strings before comparing
   str1 = str1.strip()
   str2 = str2.strip()
   if str1==str2:
      message = 'Excellent'
   else:
      message = 'Try again'
   return message
</code>```

Title: String comparison fails in python

Body:
I am trying to build a small web app in python3 with Flask and I have a problem comparing two strings. For some reason, even if the strings are identical my function returns a false.

This is what I am trying to do:

I created a (question) form in HTML and I expect an answer from a user. When the user clicks 'Submit' a function is triggered in python that is supposed to compare the answer to the correct answer. If answer == correct_answer then a message is displayed "Excellent!!" if not something like "Try again".

def compare(str1, str2):
   if str1==str2:
      message = 'Excellent'
   else:
      message = 'Try again'
   return message

Then I retrieve the answer from the web form and also my correct answer from a .txt file (this is a temporary file that will only contain the correct answer) and call the function:
...

answer=request.args.get('answer') #this works - value from the webform
f = open('temp.txt', 'r') #this works
correct_answer=f.read() #this works
f.close()

result=compare(answer, correct_answer) # this one always returns 'Try again'

So, the problem is that no matter what the answer is the result is always false.

Just to be sure that I have the same values I tried:

print(answer)
print(correct_answer)

and I have the same value, but the function returns false

I tried:

print(type(answer))
print(type(correct_answer))

The result is 'str' for both print.

Any idea why this is not working?

Body:
It's possible that there are leading or trailing whitespaces or newlines in either of the strings, hence it might be better to strip those characters are then compare.

def compare(str1, str2):
   #Strip both strings before comparing
   str1 = str1.strip()
   str2 = str2.strip()
   if str1==str2:
      message = 'Excellent'
   else:
      message = 'Try again'
   return message


问:
XPath not locating element
What is wrong with my path to select the following:

```<code><label class="form-control-label" for="profile_form_state">State</label>
</code>```

Xpath:

```<code>xpath = '//label[ends-with(@for, "_state")]'
</code>```

I am using rspec and capybara

```<code> expect(rendered).to have_xpath(xpath)
</code>```

Error:

```<code>   xmlXPathCompOpEval: function ends-with not found
</code>```

答:
Other possible Xpath

```<code>//label[contains(@for, '_state')]
</code>```

or

```<code>//label[text()='State']
</code>```

or

```<code>//label[contains(text(), 'State')]
</code>```

Title: XPath not locating element

Body:
What is wrong with my path to select the following:

State

Xpath:

xpath = '//label[ends-with(@for, "_state")]'

I am using rspec and capybara

 expect(rendered).to have_xpath(xpath)

Error:

   xmlXPathCompOpEval: function ends-with not found

Body:
Other possible Xpath

//label[contains(@for, '_state')]

or

//label[text()='State']

or

//label[contains(text(), 'State')]


问:
How can you tell when a Kafka Streams app is in the "running" state?
Given a recently started Kafka Streams app, how can one reliably determine that it has reached the "RUNNING" state? This is in the context of a test program that launches one or more streams apps and needs to wait until they are running before submitting test messages.

I know about the .setStateListener method but I'm wondering if there is a way of detecting this state from outside the app process. I thought it might be exposed as a jmx metric but I couldn't find one in VisualVM

答:
The state listener method is the way to go. There is no other out-of-the-box way to achieve what you want.

That said, you can do the following for example:

Expose a simple "health check" (or "running yes/no check") in your Kafka Streams application, e.g. via a REST endpoint (use whatever REST tooling you are familiar with).

The health check can be based on Kafka Streams' built-in state listener, which you already know about.

Your test program can then remotely query the health check endpoints of your various Kafka Streams application to determine when all of them are up and running.

Of course, you can use other ways to communicate readiness of a Kafka Streams application.  The REST endpoint idea in (1) is just one example.

You can also let the Kafka Streams application write its readiness status into a Kafka topic, and your test program will subscribe to that topic to determine when all apps are ready.

Another option would be to provide a custom JMX metric in your Kafka Streams apps that your test program can then access.


问:
Input from stream to enum type
How to input from stream to enum type?

I can do it so

```<code>unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);
</code>```

Otherwise?

答:
```<code>inline std::istream & operator>>(std::istream & str, Sex & v) {
  unsigned int sex = 0;
  if (str >> sex)
    v = static_cast<Sex>(sex);
  return str;
}
</code>```

If you want to ensure that the value is valid, you can do something like this:

```<code>enum Sex {
    Male,
    Female,
    Sex_COUNT
};

inline std::istream & operator>>(std::istream & str, Sex & v) {
  unsigned int sex = 0;
  if (!(str >> sex))
    return str;
  if (sex >= Sex_COUNT) {
    str.setstate(str.rdstate() | std::ios::failbit);
    return str;
  }
  v = static_cast<Sex>(sex);
  return str;
}
</code>```

Title: Input from stream to enum type

Body:
How to input from stream to enum type?

I can do it so

unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);

Otherwise?

Body:
inline std::istream & operator>>(std::istream & str, Sex & v) {
  unsigned int sex = 0;
  if (str >> sex)
    v = static_cast<Sex>(sex);
  return str;
}

If you want to ensure that the value is valid, you can do something like this:

enum Sex {
    Male,
    Female,
    Sex_COUNT
};

inline std::istream & operator>>(std::istream & str, Sex & v) {
  unsigned int sex = 0;
  if (!(str >> sex))
    return str;
  if (sex >= Sex_COUNT) {
    str.setstate(str.rdstate() | std::ios::failbit);
    return str;
  }
  v = static_cast<Sex>(sex);
  return str;
}


问:
Expand a column entry and adding values from one or more rows in pandas
I have a data frame with entries that have the same meaning, I'd like to get them in the same row(and column).
My mock df:

```<code>my = pd.DataFrame(
{'fruit': ['Apple', 'Banana', 'Pomme', 'aeble', 'Banan', 'Orange', 'Apelsin'],
'bites': [1, 2, 3, 1, 2, 3, 4]})
</code>```

and what I would like it to be:

The closest I've gotten is

```<code>my.loc['Apple'] +=my.loc['Pomme'] += my.loc['aeble']
</code>```

But I am wondering if there is an easier way.

答:
If you had some dict mapping all fruit values to one language, you could use groupby and map with agg functions join and sum:

```<code>d = {'Apple': 'Apple',
     'Banana': 'Banana',
     'Pomme': 'Apple',
     'aeble': 'Apple',
     'Banan': 'Banana',
     'Orange': 'Orange',
     'Apelsin': 'Orange'
    }

my.groupby(my['fruit'].map(d)).agg({'fruit': lambda x: ', '.join(x),
                                    'bites': 'sum'})
</code>```

[out]

```<code>                      fruit  bites
fruit
Apple   Apple, Pomme, aeble      5
Banana        Banana, Banan      4
Orange      Orange, Apelsin      7
</code>```

One way to help generate you're mapping dict could be to use the googletrans package:

```<code>from googletrans import Translator
translator = Translator()

d = {x.origin: x.text for x in translator.translate(my['fruit'].unique().tolist())}
</code>```

[out]

```<code>{'Apple': 'Apple',
 'Banana': 'Banana',
 'Pomme': 'Apple',
 'aeble': 'aeble',
 'Banan': 'Banana',
 'Orange': 'Orange',
 'Apelsin': 'Orange'}
</code>```

As you can see, it's not perfect, but will give you a head-start instead of creating entirely manually.

Body:
I have a data frame with entries that have the same meaning, I'd like to get them in the same row(and column).
My mock df:

my = pd.DataFrame(
{'fruit': ['Apple', 'Banana', 'Pomme', 'aeble', 'Banan', 'Orange', 'Apelsin'],
'bites': [1, 2, 3, 1, 2, 3, 4]})

and what I would like it to be:

The closest I've gotten is

my.loc['Apple'] +=my.loc['Pomme'] += my.loc['aeble']

But I am wondering if there is an easier way.

Body:
If you had some dict mapping all fruit values to one language, you could use groupby and map with agg functions join and sum:

d = {'Apple': 'Apple',
     'Banana': 'Banana',
     'Pomme': 'Apple',
     'aeble': 'Apple',
     'Banan': 'Banana',
     'Orange': 'Orange',
     'Apelsin': 'Orange'
    }

my.groupby(my['fruit'].map(d)).agg({'fruit': lambda x: ', '.join(x),
                                    'bites': 'sum'})

[out]

                      fruit  bites
fruit
Apple   Apple, Pomme, aeble      5
Banana        Banana, Banan      4
Orange      Orange, Apelsin      7

One way to help generate you're mapping dict could be to use the googletrans package:

from googletrans import Translator
translator = Translator()

d = {x.origin: x.text for x in translator.translate(my['fruit'].unique().tolist())}

[out]

{'Apple': 'Apple',
 'Banana': 'Banana',
 'Pomme': 'Apple',
 'aeble': 'aeble',
 'Banan': 'Banana',
 'Orange': 'Orange',
 'Apelsin': 'Orange'}

As you can see, it's not perfect, but will give you a head-start instead of creating entirely manually.