问:
How to check if value exists in multidimensional array with keys?
I have an array that looks like this:

```<code>$array = array(
   array('name' => 'number1', 'number' => '0612345675'),
   array('name' => 'number2', 'number' => '0634345675'),
   array('name' => 'number3', 'number' => '0634378675')
);
</code>```

Now I have this number: 0634345675.

How can I check If this number exists in the array $array?

I tried to do this:

```<code>if(!in_array('0634345675', $array)){
   // insert into DB
}
</code>```

But this keeps adding multiple of the same rows.

Does anyone knows how to check if this number exists in $array?

Full code:

```<code>foreach($DN as $number){ // $DN got ['0634345675', '0632545675', '0614342375']
    if(!in_array($number, $array)){
       // insert into DB
    }
}
</code>```

答:
You have to use in_array() along with array_column()

```<code><?php

$array = array(
   array('name' => 'number1', 'number' => '0612345675'),
   array('name' => 'number2', 'number' => '0634345675'),
   array('name' => 'number3', 'number' => '0634378675')
);

$valueToFind = '0634345675';

if (in_array($valueToFind, array_column($array, 'number'))){
    echo 'found';
}else{
    echo 'not found';
}
</code>```

Output:- https://3v4l.org/TUtSL

If you want to show that array too, then use array_search()

```<code>$key = array_search($valueToFind, array_column($array, 'number'));
if($key){
    echo 'value found';
    echo PHP_EOL;
    echo "matched array is";
    echo PHP_EOL;
    print_r($array[$key]);
}
</code>```

Output:-https://3v4l.org/Mc2cC

In case multiple match found:

```<code>$valueToFind = '0634378675';

$matchedArray = array();
foreach($array as $arr){
    if($valueToFind == $arr['number']){
        $matchedArray[] = $arr;
    }
}

if( count($matchedArray) > 0){
    echo "match found";
    echo PHP_EOL;
    print_r($matchedArray);
}
</code>```

Output:- https://3v4l.org/p439T

Body:
I have an array that looks like this:

$array = array(
   array('name' => 'number1', 'number' => '0612345675'),
   array('name' => 'number2', 'number' => '0634345675'),
   array('name' => 'number3', 'number' => '0634378675')
);

Now I have this number: 0634345675.

How can I check If this number exists in the array $array?

I tried to do this:

if(!in_array('0634345675', $array)){
   // insert into DB
}

But this keeps adding multiple of the same rows.

Does anyone knows how to check if this number exists in $array?

Full code:

foreach($DN as $number){ // $DN got ['0634345675', '0632545675', '0614342375']
    if(!in_array($number, $array)){
       // insert into DB
    }
}

Body:
You have to use in_array() along with array_column()

<?php

$array = array(
   array('name' => 'number1', 'number' => '0612345675'),
   array('name' => 'number2', 'number' => '0634345675'),
   array('name' => 'number3', 'number' => '0634378675')
);

$valueToFind = '0634345675';

if (in_array($valueToFind, array_column($array, 'number'))){
    echo 'found';
}else{
    echo 'not found';
}

Output:- https://3v4l.org/TUtSL

If you want to show that array too, then use array_search()

$key = array_search($valueToFind, array_column($array, 'number'));
if($key){
    echo 'value found';
    echo PHP_EOL;
    echo "matched array is";
    echo PHP_EOL;
    print_r($array[$key]);
}

Output:-https://3v4l.org/Mc2cC

In case multiple match found:

$valueToFind = '0634378675';

$matchedArray = array();
foreach($array as $arr){
    if($valueToFind == $arr['number']){
        $matchedArray[] = $arr;
    }
}

if( count($matchedArray) > 0){
    echo "match found";
    echo PHP_EOL;
    print_r($matchedArray);
}

Output:- https://3v4l.org/p439T


来源: stackexchange

问:
POST method is not supported for this route
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

```<code><div class="card-body">
    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location" value="{{$info->location}}">
        </div>
        <div class="form-group">
            <label for="about">About</label>
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
        </div>
        <div class="form-control">
            <p class="text-center">
                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
            </p>
        </div>
    </form>
</div>
</code>```

Routes:

```<code>Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});
</code>```

in controller:

```<code>public function update(Request $request, $id)
{

    dd($request->all());

}
</code>```

答:
Here is the correction in your provided example.

In form route('profile.update', ['id' => {here you have to place id of record which you want to update}]).

View File

         $info->id])}}" method="post">

```<code>        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location" value="{{$info->location}}">
        </div>
        <div class="form-group">
            <label for="about">About</label>
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
        </div>
        <div class="form-control">
            <p class="text-center">
                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
            </p>
        </div>
    </form>
</div>
</code>```

In Route

```<code>Route::group(["middleware" => "auth"], function(){
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::get("/profile/edit/profile", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::post("/profile/update/profile/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});
</code>```

In Controller

```<code>public function update(Request $request, $id)
{
    dd($id, $request->all());
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

            Location
            <input class="form-control" type="text" name="location" value="{{$info->location}}">

            About
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>

                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>

    </form>

Routes:

Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});

in controller:

public function update(Request $request, $id)
{

    dd($request->all());

}

Body:
Here is the correction in your provided example.

In form route('profile.update', ['id' => {here you have to place id of record which you want to update}]).

View File

         $info->id])}}" method="post">

        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location" value="{{$info->location}}">
        </div>
        <div class="form-group">
            <label for="about">About</label>
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
        </div>
        <div class="form-control">
            <p class="text-center">
                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
            </p>
        </div>
    </form>
</div>

In Route

Route::group(["middleware" => "auth"], function(){
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::get("/profile/edit/profile", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::post("/profile/update/profile/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});

In Controller

public function update(Request $request, $id)
{
    dd($id, $request->all());
}


问:
Unexpected "{" in a long code line that is located in a code with many if's and if-else structures are mixed together?
When trying to write a function fromNdpTo10 that converts normalized double precision number (in memory) to decimal number, I get "unexpected '{' in:" error, but I should not get that error. I cared the opening and closing number of paranthesis, braces, brackets to be equal. Look:

```<code>SubstringHoldingLeading0s <- function(x) {
  x <- formatC(x, flag="0", width=11, format="d")
  substr(x, 1, 11)
}
SubstringHoldingLeading0s(00100101101) # "00100101101"

from2to10 <- function(binaryNumber) {
  # Via SubstringHoldingLeading0s, the loss is prevented when converting string (holded as numeric) to character
  sapply(strsplit(SubstringHoldingLeading0s(binaryNumber), split = ""), function(x) sum(as.numeric(x) * 2^(rev(seq_along(x) - 1))))}
from2to10(00100101101) # 301

fromNdpTo10 <- function(NdpNumber) {
  NdpNumber <- as.character(NdpNumber)
  out <- list()

  # Handle special cases (0, Inf, -Inf)
  If (NdpNumber %in% c(
    "0000000000000000000000000000000000000000000000000000000000000000",
    "0111111111110000000000000000000000000000000000000000000000000000",
    "1111111111110000000000000000000000000000000000000000000000000000")) {
    # special cases
    If (NdpNumber == "0000000000000000000000000000000000000000000000000000000000000000") { out <- "0" }
    If (NdpNumber == "0111111111110000000000000000000000000000000000000000000000000000") { out <- "Inf" }
    If (NdpNumber == "1111111111110000000000000000000000000000000000000000000000000000") { out <- "-Inf" }
  } else { # if NdpNumber not in special cases, begins

    signOfNumber <- "+" # initialization
    If (substr(NdpNumber, 1, 1) == 0) { signOfNumber <- "+"
    } else { signOfNumber <- "-" }

    # From BiasedExponent to RealExponent (Biased Exponent=Real exponent +1023;  Real exponent=Biased Exponent-1023)
    BiasedExponent <- substr(NdpNumber, 2, 12)
    BiasedExponent <- from2to10(BiasedExponent)
    RealExponent <- BiasedExponent - 1023

    # Significand
    Significand <- substr(NdpNumber, 13, 64)
    Significand <- from2to10(Significand)

    out <- paste0(c(signOfNumber, Significand, "e", RealExponent), collapse = '')
  } # if NdpNumber not in special cases, ends

  out
}
</code>```

The error is:

```<code>Error: unexpected '{' in:
"        "0111111111110000000000000000000000000000000000000000000000000000",
        "1111111111110000000000000000000000000000000000000000000000000000")) {"
</code>```

The problem seems to be caused by long code in single line. Is there a limit for characters in a single line? Any idea on how to solve the problem?

答:
You have a syntax error here:

```<code>If (substr(NdpNumber, 1, 1) == 0) { signOfNumber <- "+"
</code>```

'if' is written with lower starting case 'i'.

As a piece of advice, try to follow common coding style conventions (variables with lower case first letter, ...)

Body:
When trying to write a function fromNdpTo10 that converts normalized double precision number (in memory) to decimal number, I get "unexpected '{' in:" error, but I should not get that error. I cared the opening and closing number of paranthesis, braces, brackets to be equal. Look:

SubstringHoldingLeading0s <- function(x) {
  x <- formatC(x, flag="0", width=11, format="d")
  substr(x, 1, 11)
}
SubstringHoldingLeading0s(00100101101) # "00100101101"

from2to10 <- function(binaryNumber) {
  # Via SubstringHoldingLeading0s, the loss is prevented when converting string (holded as numeric) to character
  sapply(strsplit(SubstringHoldingLeading0s(binaryNumber), split = ""), function(x) sum(as.numeric(x) * 2^(rev(seq_along(x) - 1))))}
from2to10(00100101101) # 301

fromNdpTo10 <- function(NdpNumber) {
  NdpNumber <- as.character(NdpNumber)
  out <- list()

  # Handle special cases (0, Inf, -Inf)
  If (NdpNumber %in% c(
    "0000000000000000000000000000000000000000000000000000000000000000",
    "0111111111110000000000000000000000000000000000000000000000000000",
    "1111111111110000000000000000000000000000000000000000000000000000")) {
    # special cases
    If (NdpNumber == "0000000000000000000000000000000000000000000000000000000000000000") { out <- "0" }
    If (NdpNumber == "0111111111110000000000000000000000000000000000000000000000000000") { out <- "Inf" }
    If (NdpNumber == "1111111111110000000000000000000000000000000000000000000000000000") { out <- "-Inf" }
  } else { # if NdpNumber not in special cases, begins

    signOfNumber <- "+" # initialization
    If (substr(NdpNumber, 1, 1) == 0) { signOfNumber <- "+"
    } else { signOfNumber <- "-" }

    # From BiasedExponent to RealExponent (Biased Exponent=Real exponent +1023;  Real exponent=Biased Exponent-1023)
    BiasedExponent <- substr(NdpNumber, 2, 12)
    BiasedExponent <- from2to10(BiasedExponent)
    RealExponent <- BiasedExponent - 1023

    # Significand
    Significand <- substr(NdpNumber, 13, 64)
    Significand <- from2to10(Significand)

    out <- paste0(c(signOfNumber, Significand, "e", RealExponent), collapse = '')
  } # if NdpNumber not in special cases, ends

  out
}

The error is:

Error: unexpected '{' in:
"        "0111111111110000000000000000000000000000000000000000000000000000",
        "1111111111110000000000000000000000000000000000000000000000000000")) {"

The problem seems to be caused by long code in single line. Is there a limit for characters in a single line? Any idea on how to solve the problem?

Body:
You have a syntax error here:

If (substr(NdpNumber, 1, 1) == 0) { signOfNumber <- "+"

'if' is written with lower starting case 'i'.

As a piece of advice, try to follow common coding style conventions (variables with lower case first letter, ...)


问:
querySelectorAll() match all h1's except from a div
I want to match all h1's on the document except from a div containing other h1's, currently i can do querySelectorAll('h1:not(.demo)) to get all h1's with except h1's with demo class.

But how can i do querySelectorAll('h1:not(div#demo)) or similar thing?

Below is a sample html

First

Second

Third

Fourth

```

答:
You can first get all the divs except those you want to match, then run a query selector from those:

const divsWhichArentDemo = document.querySelectorAll('div:not(#demo)');
const h1sWhichArentInDemoDivs = Array.prototype.slice.call(divsWhichArentDemo)
  .map(div => Array.prototype.slice.call(div.querySelectorAll('h1')))
  .flat();

console.dir(h1sWhichArentInDemoDivs);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h1>First</h1>
  <h1>Second</h1>
</div>
<div id="demo">
  <h1 class="demo">Third</h1>
</div>
<div>
  <h1>Fourth</h1>
</div></code>```

Body:
You can first get all the divs except those you want to match, then run a query selector from those:

const divsWhichArentDemo = document.querySelectorAll('div:not(#demo)');
const h1sWhichArentInDemoDivs = Array.prototype.slice.call(divsWhichArentDemo)
  .map(div => Array.prototype.slice.call(div.querySelectorAll('h1')))
  .flat();

console.dir(h1sWhichArentInDemoDivs);

<div>
  <h1>First</h1>
  <h1>Second</h1>
</div>
<div id="demo">
  <h1 class="demo">Third</h1>
</div>
<div>
  <h1>Fourth</h1>
</div>


问:
How do I extract the key of an element which has been comma delimited?
The XML...

```<code><BaseElement>
     <AttributeList
     >ThreadId=1,ThreadName=Foo,ApplicationName=Bar</AttributeList>
</BaseElement>
</code>```

I'm trying to extract the value within ThreadId...

```<code><xsl:apply-templates select="AttributesList"/>
</code>```

The above displays the entire list; ThreadId=1,ThreadName=Foo, ...

Looked into substring but that appears fairly fixed in nature. It needs to dynamic so that if the the key, which in this case would be ThreadId changes to NewFangledThreadId it continues to function.

答:
The following stylesheet:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="AttributeList">
        <xsl:value-of select="substring-before(substring-after(., '='), ',')"/>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code>1
</code>```

It selects the portion of the string that comes after the first = and before the first ,.

ContentLicense: CC BY-SA 3.0

Body:
The XML...

<BaseElement>
     <AttributeList
     >ThreadId=1,ThreadName=Foo,ApplicationName=Bar</AttributeList>
</BaseElement>

I'm trying to extract the value within ThreadId...

<xsl:apply-templates select="AttributesList"/>

The above displays the entire list; ThreadId=1,ThreadName=Foo, ...

Looked into substring but that appears fairly fixed in nature. It needs to dynamic so that if the the key, which in this case would be ThreadId changes to NewFangledThreadId it continues to function.

Body:
The following stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="AttributeList">
        <xsl:value-of select="substring-before(substring-after(., '='), ',')"/>
    </xsl:template>
</xsl:stylesheet>

Output:

1

It selects the portion of the string that comes after the first = and before the first ,.


问:
How to Update list of entity to database
I have my entity class called employee and I want to soft delete my entity when I select and press delete button. I can able to select multiple employees as well, So in Java I used List of employee Entities and I want to update whole list into database table if I use merge of entityManager I can able to update only one row i.e only one entity so how do I solve this problem?

Here is some sample code.

```<code>@Entity
@Table(name="EmpInfo",schema="Auth")
public class EmpInfo{

@Id
@Column(name="EmpId")
private String userId;

@Column(name="EmailId")
private String emailId;

@Column(name="FirstName")
private String firstName;

@Column(name="LastName")
private String lastName;

@Column(name="MiddleName")
private String middleName;

@Column(name="UserAttributes")
private String userAttributes;

@Column(name="AddedDate")
private Timestamp addedDate;

@Column(name="ModifiedDate")
private Timestamp modifiedDate;

@Column(name="LastLoginDate")
private Timestamp lastLoginDate;

@Column(name="IsDeleted")
private int isDeleted;

@Column(name="AddedBy")
private String addedBy;

@Transient
private String addedByEmailId;

public String getAddedByEmailId() {
    return addedByEmailId;
}
public void setAddedByEmailId(String addedByEmailId) {
    this.addedByEmailId = addedByEmailId;
}

public EmpInfo() {
    // TODO Auto-generated constructor stub
}
public EmpInfo(EmpInfo uInfo){
    super();
    this.userId=uInfo.userId;
    this.emailId=uInfo.emailId;
    this.firstName=uInfo.firstName;
    this.lastName=uInfo.lastName;
    this.middleName=uInfo.middleName;
    this.userAttributes=uInfo.userAttributes;
    this.addedDate=uInfo.addedDate;
    this.lastLoginDate=uInfo.lastLoginDate;
    this.modifiedDate=uInfo.modifiedDate;
    this.addedBy=uInfo.addedBy;
    this.roles=uInfo.roles;

}

public List<RoleName> getRoles() {
    return roles;
}
public void setRoles(List<RoleName> roles) {
    this.roles = roles;
}
public int getIsDeleted() {
    return isDeleted;
}
public void setIsDeleted(int isDeleted) {
    this.isDeleted = isDeleted;
}
public Date getAddedDate() {
    return addedDate;
}
public void setAddedDate(Timestamp addedDate) {
    this.addedDate = addedDate;
}
public Date getModifiedDate() {
    return modifiedDate;
}
public void setModifiedDate(Timestamp modifiedDate) {
    this.modifiedDate = modifiedDate;
}
public Date getLastLoginDate() {
    return lastLoginDate;
}
public void setLastLoginDate(Timestamp lastLoginDate) {
    this.lastLoginDate = lastLoginDate;
}
public String getUserId() {
    return userId;
}
public void setUserId(String userId) {
    this.userId = userId;
}
public String getEmailId() {
    return emailId;
}
public void setEmailId(String emailId) {
    this.emailId = emailId;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getMiddleName() {
    return middleName;
}
public void setMiddleName(String middleName) {
    this.middleName = middleName;
}

public String getUserAttributes() {
    return userAttributes;
}
public void setUserAttributes(String userAttributes) {
    this.userAttributes = userAttributes;
}

public String getAddedBy() {
    return addedBy;
}
public void setAddedBy(String addedBy) {
    this.addedBy = addedBy;
}
@Override
public String toString() {
    return "EmpInfo [userId=" + userId + ", emailId=" + emailId + ", firstName=" + firstName + ", lastName="
            + lastName + ", middleName=" + middleName + ", userAttributes=" + userAttributes + ", addedDate="
            + addedDate + ", modifiedDate=" + modifiedDate + ", lastLoginDate=" + lastLoginDate + ", isDeleted="
            + isDeleted + ", addedBy=" + addedBy + "]";
}
}
</code>```

答:
```<code>public interface EmpInfoRepository extends JpaRepository<EmpInfo, String> {
}
</code>```

use this to save list of entities as follows

```<code>@Autowired
private EmpInfoRepository empInfoRepository;

empInfoRepository.save(listOfEntity)
</code>```

Since there is no custom implementation defined, implementation done by SimpleJpaRepository  will be used, which will update the entities according to the @Id annotated field

Body:
I have my entity class called employee and I want to soft delete my entity when I select and press delete button. I can able to select multiple employees as well, So in Java I used List of employee Entities and I want to update whole list into database table if I use merge of entityManager I can able to update only one row i.e only one entity so how do I solve this problem?

Here is some sample code.

@Entity
@Table(name="EmpInfo",schema="Auth")
public class EmpInfo{

@Id
@Column(name="EmpId")
private String userId;

@Column(name="EmailId")
private String emailId;

@Column(name="FirstName")
private String firstName;

@Column(name="LastName")
private String lastName;

@Column(name="MiddleName")
private String middleName;

@Column(name="UserAttributes")
private String userAttributes;

@Column(name="AddedDate")
private Timestamp addedDate;

@Column(name="ModifiedDate")
private Timestamp modifiedDate;

@Column(name="LastLoginDate")
private Timestamp lastLoginDate;

@Column(name="IsDeleted")
private int isDeleted;

@Column(name="AddedBy")
private String addedBy;

@Transient
private String addedByEmailId;

public String getAddedByEmailId() {
    return addedByEmailId;
}
public void setAddedByEmailId(String addedByEmailId) {
    this.addedByEmailId = addedByEmailId;
}

public EmpInfo() {
    // TODO Auto-generated constructor stub
}
public EmpInfo(EmpInfo uInfo){
    super();
    this.userId=uInfo.userId;
    this.emailId=uInfo.emailId;
    this.firstName=uInfo.firstName;
    this.lastName=uInfo.lastName;
    this.middleName=uInfo.middleName;
    this.userAttributes=uInfo.userAttributes;
    this.addedDate=uInfo.addedDate;
    this.lastLoginDate=uInfo.lastLoginDate;
    this.modifiedDate=uInfo.modifiedDate;
    this.addedBy=uInfo.addedBy;
    this.roles=uInfo.roles;

}

public List<RoleName> getRoles() {
    return roles;
}
public void setRoles(List<RoleName> roles) {
    this.roles = roles;
}
public int getIsDeleted() {
    return isDeleted;
}
public void setIsDeleted(int isDeleted) {
    this.isDeleted = isDeleted;
}
public Date getAddedDate() {
    return addedDate;
}
public void setAddedDate(Timestamp addedDate) {
    this.addedDate = addedDate;
}
public Date getModifiedDate() {
    return modifiedDate;
}
public void setModifiedDate(Timestamp modifiedDate) {
    this.modifiedDate = modifiedDate;
}
public Date getLastLoginDate() {
    return lastLoginDate;
}
public void setLastLoginDate(Timestamp lastLoginDate) {
    this.lastLoginDate = lastLoginDate;
}
public String getUserId() {
    return userId;
}
public void setUserId(String userId) {
    this.userId = userId;
}
public String getEmailId() {
    return emailId;
}
public void setEmailId(String emailId) {
    this.emailId = emailId;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getMiddleName() {
    return middleName;
}
public void setMiddleName(String middleName) {
    this.middleName = middleName;
}

public String getUserAttributes() {
    return userAttributes;
}
public void setUserAttributes(String userAttributes) {
    this.userAttributes = userAttributes;
}

public String getAddedBy() {
    return addedBy;
}
public void setAddedBy(String addedBy) {
    this.addedBy = addedBy;
}
@Override
public String toString() {
    return "EmpInfo [userId=" + userId + ", emailId=" + emailId + ", firstName=" + firstName + ", lastName="
            + lastName + ", middleName=" + middleName + ", userAttributes=" + userAttributes + ", addedDate="
            + addedDate + ", modifiedDate=" + modifiedDate + ", lastLoginDate=" + lastLoginDate + ", isDeleted="
            + isDeleted + ", addedBy=" + addedBy + "]";
}
}

Body:
public interface EmpInfoRepository extends JpaRepository<EmpInfo, String> {
}

use this to save list of entities as follows

@Autowired
private EmpInfoRepository empInfoRepository;

empInfoRepository.save(listOfEntity)

Since there is no custom implementation defined, implementation done by SimpleJpaRepository  will be used, which will update the entities according to the @Id annotated field


问:
Angular 4 - using objects for option values in a select list
I know that similar questions have been asked, but I've found none with a good answer. I want to create a select list in an Angular form, where the value for each option is an object. Also, I do NOT want to use 2 way data binding. e.g. if my Component has these fields:

```

    lUsers: any[] = [
        { Name: 'Billy Williams', Gender: 'male' },
        { Name: 'Sally Ride', Gender: 'female'}
        ];
    curUser: any;

```

I would like my HTML template to contain this:

```

    <select #selectElem (change)="setNewUser(selectElem.value)">
        <option *ngFor="let user of lUsers" [ngValue]="user">
            {{user.Name}}
        </option>
    </select>

```

With this code, though, my setNewUser() function receives the contents of the selected user's Name field. Why it picks that specific field, I have no idea.  What I expect is that it would receive the "value" of the selected option, which I specifically set to a user object.

Note that I used ngValue instead of value in the option. That was by suggestion of others on SO. If I use value instead, what happens is that the object gets converted to the string '[Object object]', which is what setNewUser() receives, which is useless.

FYI, I'm working on Windows 10, using angular 4.0.0 with @angular/cli 1.1.2. Here is the setNewUser() method:

```

    setNewUser(user: User): void {

    console.log(user);
    this.curUser = user;
    } // setNewUser()

```

I am determining just what exactly is being passed to it both my logging it, and also including this on the template: ```{{curUser}}```

答:
ANGULAR 6 SIMPLY DO THIS

HTML

```<code><div class="col-3" style="float:left;padding-left: 18px !important;">
      <label>Vehicle No.</label>
      <div *ngIf="gpsDevicesArray && gpsDevicesArray.length > 0">
            <select [ngModel]="selectedVehicle" style="padding: 7px;border-radius: 4px;"
                    (ngModelChange)="onVehicleNumberChange($event)">
                    <option *ngFor=" let device of gpsDevicesArray" [ngValue]="device">
                        {{device.vehicleNumber}}
                    </option>
            </select>
      </div>
</div>
</code>```

TYPESCRIPT

// For intital Value ( put this line inside server calling function )

```<code> this.selectedVehicle = gpsDevicesArray[0];
</code>```

// listener

```<code> onVehicleNumberChange(device) {
        console.log("selectedVehicle ====", device);
 }
</code>```

Body:
I know that similar questions have been asked, but I've found none with a good answer. I want to create a select list in an Angular form, where the value for each option is an object. Also, I do NOT want to use 2 way data binding. e.g. if my Component has these fields:

    lUsers: any[] = [
        { Name: 'Billy Williams', Gender: 'male' },
        { Name: 'Sally Ride', Gender: 'female'}
        ];
    curUser: any;

I would like my HTML template to contain this:

    <select #selectElem (change)="setNewUser(selectElem.value)">
        <option *ngFor="let user of lUsers" [ngValue]="user">
            {{user.Name}}
        </option>
    </select>

With this code, though, my setNewUser() function receives the contents of the selected user's Name field. Why it picks that specific field, I have no idea.  What I expect is that it would receive the "value" of the selected option, which I specifically set to a user object.

Note that I used ngValue instead of value in the option. That was by suggestion of others on SO. If I use value instead, what happens is that the object gets converted to the string '[Object object]', which is what setNewUser() receives, which is useless.

FYI, I'm working on Windows 10, using angular 4.0.0 with @angular/cli 1.1.2. Here is the setNewUser() method:

    setNewUser(user: User): void {

    console.log(user);
    this.curUser = user;
    } // setNewUser()

I am determining just what exactly is being passed to it both my logging it, and also including this on the template:
{{curUser}}

Body:
ANGULAR 6 SIMPLY DO THIS

HTML

<div class="col-3" style="float:left;padding-left: 18px !important;">
      <label>Vehicle No.</label>
      <div *ngIf="gpsDevicesArray && gpsDevicesArray.length > 0">
            <select [ngModel]="selectedVehicle" style="padding: 7px;border-radius: 4px;"
                    (ngModelChange)="onVehicleNumberChange($event)">
                    <option *ngFor=" let device of gpsDevicesArray" [ngValue]="device">
                        {{device.vehicleNumber}}
                    </option>
            </select>
      </div>
</div>

TYPESCRIPT

// For intital Value ( put this line inside server calling function )

 this.selectedVehicle = gpsDevicesArray[0];

// listener

 onVehicleNumberChange(device) {
        console.log("selectedVehicle ====", device);
 }


问:
DecisionTree model has Zero Accuracy
Train model on basic dataset (2d array Hours_Studied and Test_Grade)
and have some predictions, but when I try to calculate accuracy_score it`s always 0.0

I guess the problem is in my array shape after splitting

```<code>import pandas as pd
import numpy as np

df = pd.read_csv('c:/Rawdata/grade2.csv', header=0)

print ('Raw Dataset Lenght:', len(df))
print ('Raw Dataset Shape:', df.shape)
# raw dataset info output is "Raw Dataset Lenght: 9" and "Raw Dataset Shape: (9, 2)"

from sklearn.model_selection import train_test_split

X = np.array(df['Hours_Studied']).reshape(-1, 1)
y = df['Test_Grade']

print ('Processed Dataset shape', X.shape, y.shape)
# Processed dataset output is "(9, 1) (9,)"
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=100)
</code>```

instead of this

```<code>from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(criterion = 'entropy', random_state=100)
</code>```

new code

```<code>from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor(random_state=100)
</code>```

here no changes

```<code>tree.fit(X_train, y_train)
tree_pred = tree.predict(X_test)
print ('tree predicted array is', tree_pred)
# output is "[57 96 79]"
</code>```

instead of accuracy_score

```<code>from sklearn.metrics import accuracy_score
</code>```

use this one

```<code>from sklearn.metrics import r2_score

print('current y_test is ', '\n', y_test)
#output is
# 1    66
#6    91
#5    81
#Name: Test_Grade, dtype: int64
</code>```

instead of this

```<code>print('Accuracy tree is', accuracy_score(y_test, tree_pred))
# output is "Accuracy tree is 0.0"
</code>```

now we have

```<code>print('Accuracy tree is', r2_score(y_test, tree_pred)*100)
# output is "Accuracy tree is 65.26315789473685"
</code>```

The problem about zero accuracies is solved, Thx!

答: Use classification tree when you have been given discrete labels and use regression tree when you have been given continuous values like in this case.</p>

Title: DecisionTree model has Zero Accuracy

Body:
Train model on basic dataset (2d array Hours_Studied and Test_Grade)
and have some predictions, but when I try to calculate accuracy_score it`s always 0.0

I guess the problem is in my array shape after splitting

import pandas as pd
import numpy as np

df = pd.read_csv('c:/Rawdata/grade2.csv', header=0)

print ('Raw Dataset Lenght:', len(df))
print ('Raw Dataset Shape:', df.shape)
# raw dataset info output is "Raw Dataset Lenght: 9" and "Raw Dataset Shape: (9, 2)"

from sklearn.model_selection import train_test_split

X = np.array(df['Hours_Studied']).reshape(-1, 1)
y = df['Test_Grade']

print ('Processed Dataset shape', X.shape, y.shape)
# Processed dataset output is "(9, 1) (9,)"
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=100)

instead of this

from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(criterion = 'entropy', random_state=100)

new code

from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor(random_state=100)

here no changes

tree.fit(X_train, y_train)
tree_pred = tree.predict(X_test)
print ('tree predicted array is', tree_pred)
# output is "[57 96 79]"

instead of accuracy_score

from sklearn.metrics import accuracy_score

use this one

from sklearn.metrics import r2_score

print('current y_test is ', '\n', y_test)
#output is
# 1    66
#6    91
#5    81
#Name: Test_Grade, dtype: int64

instead of this

print('Accuracy tree is', accuracy_score(y_test, tree_pred))
# output is "Accuracy tree is 0.0"

now we have

print('Accuracy tree is', r2_score(y_test, tree_pred)*100)
# output is "Accuracy tree is 65.26315789473685"

The problem about zero accuracies is solved, Thx!


问:
Unable to save formulas under excel file when it is saved using openpyxl lib
Formulas in the excel sheet are getting removed when it is saved through an openpyxl python script.

Is there any way to save excel file without removing formulas using a python script

Expected: Formulas should not be removed and data should be read through openpyxl lib

Actual: Data is read, but formulas are getting removed

答:
If you read file with data_only = True argument you read value from formula, but not formula.
From docs

data_only controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet.


问:
Path file issue when uploading csv file via laravel form to database
I want to upload a csv file to my database via a laravel form. I can only insert file if the file is stored into public folder. How can I correctly set path with fopen function?

When submitting form, my code uses only the csv that already exists in public folder and not the csv I try to upload. Except from the csv I also pass some other data to my controller. How can I alter code to receive form file and not public folder stored file?

1) Below is my form excerpt. At the bottom lines I try to upload the file.

```<code><body>

    <form method='post' enctype="multipart/form-data" action="/hard">

        {{csrf_field()}}

        <section>
        <br>
            <legend><i><b> Complete Data Below</b></i></legend>
        <br>
        </section>

        <section>
        Choose program:
            <select name="sc" id="xaos">

            <optgroup label="postgraduates">
                @foreach($transport as $y)
                    <option value="{{$y->object_id}}">{{$y->object_name}}</option>
                @endforeach
            </optgroup>

            </select>
        </section>

    <br>

        <section>
        ID number:
            <input name='am' type='number' min="1000000" max="1999999" required="" oninvalid="this.setCustomValidity('1000000 < Value < 1999999')">
        </section>

        <br>

        <section>
        Select Language:
            <select name="language" id="lang">
                    <option value="GR"> Greek</option>
                    <option value="EN"> English</option>
            </select>
        </section>
        <br>
        <section>
        <label for="upload-file">select csv file</label>
            <input type="file" name="upload-file">
        </div>
            <input type='submit' name='upload' value="Submit!">
        </section>

    </form>
    <br>
    <br>

</body>
</code>```

2) And below is my controller code excerpt which handles file imported.

```<code>public function job(Request $p)
    {
        $a1 = $p -> get('sc');
        $a2 = $p -> get('am');
        $a3 = $p -> get('language');

    $f_rownum = 0;

    if (($handle = fopen ( 'MOCK_DATA.csv', 'r' )) !== FALSE)

    {
        while ( ($data = fgetcsv ( $handle, 1000, ';' )) !== FALSE )
        {
            $ac1=$data[0];
            $ac2=iconv("Windows-1253", "UTF-8", $data[1]);
            $ac3=iconv("Windows-1253", "UTF-8", $data[2]);
            $ac4=iconv("Windows-1253", "UTF-8", $data[3]);
            $ac5=$data[4];
...............
</code>```

答:
According to Laravel documentation you can store your csv file into the storage like this:

```<code>public function storeFile(Request $request)
    {
        $path = $request->file('upload-file')->store('{directoryName}');

        return $path;
    }
</code>```

The above code store your file in storage and returns tha path which you can save it into your DB.

For retrieving the file, you can use this code if you want to force user to download the file:

```<code>return Storage::download('{pathWhichYouSavedInDB}');
</code>```

or you can retrieve the content of the file by using this code:

```<code>$contents = Storage::get('{pathWhichYouSavedInDB}');
</code>```

[I add the extra response which I wrote in the comments]
fopen requires a full-path url of the stored file to be able to open it. So you can get the file url and then pass it to the fopen function like this:

```<code>$url = Storage::url('file.jpg');
</code>```

Or you can not to use fopen at all and just use the $contents which you already retrieved with

```<code>$contents = Storage::get('{pathWhichYouSavedInDB}');
</code>```

Body:
I want to upload a csv file to my database via a laravel form. I can only insert file if the file is stored into public folder. How can I correctly set path with fopen function?

When submitting form, my code uses only the csv that already exists in public folder and not the csv I try to upload. Except from the csv I also pass some other data to my controller. How can I alter code to receive form file and not public folder stored file?

1) Below is my form excerpt. At the bottom lines I try to upload the file.

    <form method='post' enctype="multipart/form-data" action="/hard">

        {{csrf_field()}}

            <legend> Complete Data Below</legend>

        Choose program:
            <select name="sc" id="xaos">

            <optgroup label="postgraduates">
                @foreach($transport as $y)
                    <option value="{{$y->object_id}}">{{$y->object_name}}</option>
                @endforeach
            </optgroup>

            </select>

        ID number:
            <input name='am' type='number' min="1000000" max="1999999" required="" oninvalid="this.setCustomValidity('1000000 < Value < 1999999')">

        Select Language:
            <select name="language" id="lang">
                    <option value="GR"> Greek</option>
                    <option value="EN"> English</option>
            </select>

        select csv file
            <input type="file" name="upload-file">

            <input type='submit' name='upload' value="Submit!">

    </form>

2) And below is my controller code excerpt which handles file imported.

public function job(Request $p)
    {
        $a1 = $p -> get('sc');
        $a2 = $p -> get('am');
        $a3 = $p -> get('language');

    $f_rownum = 0;

    if (($handle = fopen ( 'MOCK_DATA.csv', 'r' )) !== FALSE)

    {
        while ( ($data = fgetcsv ( $handle, 1000, ';' )) !== FALSE )
        {
            $ac1=$data[0];
            $ac2=iconv("Windows-1253", "UTF-8", $data[1]);
            $ac3=iconv("Windows-1253", "UTF-8", $data[2]);
            $ac4=iconv("Windows-1253", "UTF-8", $data[3]);
            $ac5=$data[4];
...............

Body:
According to Laravel documentation you can store your csv file into the storage like this:

public function storeFile(Request $request)
    {
        $path = $request->file('upload-file')->store('{directoryName}');

        return $path;
    }

The above code store your file in storage and returns tha path which you can save it into your DB.

For retrieving the file, you can use this code if you want to force user to download the file:

return Storage::download('{pathWhichYouSavedInDB}');

or you can retrieve the content of the file by using this code:

$contents = Storage::get('{pathWhichYouSavedInDB}');

[I add the extra response which I wrote in the comments]
fopen requires a full-path url of the stored file to be able to open it. So you can get the file url and then pass it to the fopen function like this:

$url = Storage::url('file.jpg');

Or you can not to use fopen at all and just use the $contents which you already retrieved with

$contents = Storage::get('{pathWhichYouSavedInDB}');


问:
Select All / Unselect All option in react-select
Is it possible to have the 'Select All / Unselect All' option in react-select?
Is this something that is built in, or I have to do it my self?</p>

答:
I  inspired from Alex's method, but i changed some section of his code. There is a example i prepared, if you still need, you can check.

And also I made another example for the case that there is too much data, i solved performance problem with react-window and i changed input value if user select more than 5 items.


问:
jtextfiled not retrieving the value picked from combobox
I want retrieve the value picked from combo box to jtextfield. As per my UI combobox is in 4th. So I coded:

```<code>pst.setString(4, (String)cmbPaySub.getSelectedItem());
</code>```

and the error pop-up:

Parameter index out of range.(4> number of parameters, which is 1".

I tried by coding;

```<code>pst.setString(1, (String)cmbPaySub.getSelectedItem());
</code>```

Neither error will pop-up and value also not picking up.

```<code>private void cmbPaySubActionPerformed(java.awt.event.ActionEvent evt) {
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sipnena", "root", "");
        String sql="select * from payments where cmbSubject=?";
        PreparedStatement pst=con.prepareStatement(sql);
        pst.setString(4, (String)cmbPaySub.getSelectedItem());

        ResultSet rs=pst.executeQuery();

        while(rs.next()){
            txtFee.setText(rs.getString("Fee"));
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}
</code>```

Kindly help me to retrieve the value to the jtextfield.

答:
When reading the result you're replacing the entire text by the result's value in a loop so only the last value will show:

```<code>while(rs.next()){
    txtFee.setText(rs.getString("Fee"));
}
</code>```

You should concatenate all the values, and then set the text:

```<code>StringBuilder text = new StringBuilder();
while(rs.next()){
    text.append(rs.getString("Fee"));
    text.append("\n");
}
txtFee.setText(text.toString());
</code>```

Body:
I want retrieve the value picked from combo box to jtextfield. As per my UI combobox is in 4th. So I coded:

pst.setString(4, (String)cmbPaySub.getSelectedItem());

and the error pop-up:

Parameter index out of range.(4> number of parameters, which is 1".

I tried by coding;

pst.setString(1, (String)cmbPaySub.getSelectedItem());

Neither error will pop-up and value also not picking up.

private void cmbPaySubActionPerformed(java.awt.event.ActionEvent evt) {
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sipnena", "root", "");
        String sql="select * from payments where cmbSubject=?";
        PreparedStatement pst=con.prepareStatement(sql);
        pst.setString(4, (String)cmbPaySub.getSelectedItem());

        ResultSet rs=pst.executeQuery();

        while(rs.next()){
            txtFee.setText(rs.getString("Fee"));
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

Kindly help me to retrieve the value to the jtextfield.

Body:
When reading the result you're replacing the entire text by the result's value in a loop so only the last value will show:

while(rs.next()){
    txtFee.setText(rs.getString("Fee"));
}

You should concatenate all the values, and then set the text:

StringBuilder text = new StringBuilder();
while(rs.next()){
    text.append(rs.getString("Fee"));
    text.append("\n");
}
txtFee.setText(text.toString());


问:
Change Navigation Bar Item Dynamically - Swift
I am creating a NavigationBar with UIBarButtonItem which located on right side of screen. As default I set that setRightBarButton with UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(editProfile)) and when I clicked on that it should change that rightBarButton to other title but it doesn't work.

Here is I tried to change with I clicked on it

```<code>@objc
func editProfile() {
    self.navigationItem.setRightBarButton(cancelActionBar, animated: true)

}
</code>```

This is object of cancelActionBar

```<code>let cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelEdit))
</code>```

And this is its action which change it back to default.

```<code>@objc
func cancelEdit() {
    self.navigationItem.setRightBarButton(editActionBar, animated: true)
}
</code>```

I also tried to use main thread as well but it is not working as I expected.

答:
In viewDidLoad method set edit as bar button</p>

```<code>override func viewDidLoad() {
      self.setBarButton(isSetEditBarButton: true)
}

@objc func editProfile() {
    self.setBarButton(isSetEditBarButton: false)
}

@objc func cancelEdit() {
    self.setBarButton(isSetEditBarButton: true)
}

 private func setBarButton(isSetEditBarButton: Bool) {
     if isSetEditBarButton {
           let editActionBar = UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(editProfile))
           self.navigationItem.setRightBarButton(editActionBar, animated: true)
     } else {
           let cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelEdit))
           self.navigationItem.setRightBarButton(cancelActionBar, animated: true)
     }
   }
</code>```

Body:
I am creating a NavigationBar with UIBarButtonItem which located on right side of screen. As default I set that setRightBarButton with UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(editProfile)) and when I clicked on that it should change that rightBarButton to other title but it doesn't work.

Here is I tried to change with I clicked on it

@objc
func editProfile() {
    self.navigationItem.setRightBarButton(cancelActionBar, animated: true)

}

This is object of cancelActionBar

let cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelEdit))

And this is its action which change it back to default.

@objc
func cancelEdit() {
    self.navigationItem.setRightBarButton(editActionBar, animated: true)
}

I also tried to use main thread as well but it is not working as I expected.

Body:
In viewDidLoad method set edit as bar button

override func viewDidLoad() {
      self.setBarButton(isSetEditBarButton: true)
}

@objc func editProfile() {
    self.setBarButton(isSetEditBarButton: false)
}

@objc func cancelEdit() {
    self.setBarButton(isSetEditBarButton: true)
}

 private func setBarButton(isSetEditBarButton: Bool) {
     if isSetEditBarButton {
           let editActionBar = UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(editProfile))
           self.navigationItem.setRightBarButton(editActionBar, animated: true)
     } else {
           let cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelEdit))
           self.navigationItem.setRightBarButton(cancelActionBar, animated: true)
     }
   }


问:
How can I do to execute some functions using Django?
Hello I have a Django project but I can't achieve to execute some functions. I precise I have a file in my app by the name of file2.py and I tried this :

```<code>import file2
</code>```

And I got this :

```<code>No module named 'file2'
</code>```

Could you help me please ?

Thank you.

答:
Try to use this:

```<code>from .file2 import *
</code>```

Can u post more information, such as the folder structure

Body:
Hello I have a Django project but I can't achieve to execute some functions. I precise I have a file in my app by the name of file2.py and I tried this :

import file2

And I got this :

No module named 'file2'

Could you help me please ?

Thank you.

Body:
Try to use this:

from .file2 import *

Can u post more information, such as the folder structure


问:
How to handle on change for an input in reactjs?
I have a component UserInput and its used in App component(class based.) Now i am not able to render the onChange event in my html

```<code>import React from 'react';

const userInput =(props) =>{
    return(
        <input  onChange={props.changed} />
    );
};

export default userInput;

</code>```

My app component looks like this.

```<code>import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';

class App extends Component{
constructor(props) {
    super(props);
        this.state = { userName: "dssdf" };
        this.handleChange = this.handleChange.bind(this);

    }
    const handleChange = (event) =>{
            this.setState({
                userName: event.target.value
            })
        }

    render(){

        return(
            <div >
                <UserInput changed={this.handleChange} />
                <UserOutput userName={this.state.userName} />

            </div>
        )
    }
}

export default App;

</code>```

Any help is appriciated.

Thanks

答:
pass the state as value to <input />

```<code>import React from 'react';

const userInput =(props) =>{
    return(
        <input value={props.value} onChange={props.changed} />
    );
};

export default userInput;

class App extends Component{
constructor(props) {
    super(props);
        this.state = { userName: "dssdf" };
        this.handleChange = this.handleChange.bind(this);

    }
    const handleChange = (event) =>{
            this.setState({
                userName: event.target.value
            })
        }

    render(){

        return(
            <div >
                <UserInput value={this.state.userName} changed={this.handleChange} />
                <UserOutput userName={this.state.userName} />

            </div>
        )
    }
}
</code>```

Body:
I have a component UserInput and its used in App component(class based.) Now i am not able to render the onChange event in my html

import React from 'react';

const userInput =(props) =>{
    return(
        <input  onChange={props.changed} />
    );
};

export default userInput;

My app component looks like this.

import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';

class App extends Component{
constructor(props) {
    super(props);
        this.state = { userName: "dssdf" };
        this.handleChange = this.handleChange.bind(this);

    }
    const handleChange = (event) =>{
            this.setState({
                userName: event.target.value
            })
        }

    render(){

        return(

                <UserInput changed={this.handleChange} />
                <UserOutput userName={this.state.userName} />

        )
    }
}

export default App;

Any help is appriciated.

Thanks

Body:
pass the state as value to <input />

import React from 'react';

const userInput =(props) =>{
    return(
        <input value={props.value} onChange={props.changed} />
    );
};

export default userInput;

class App extends Component{
constructor(props) {
    super(props);
        this.state = { userName: "dssdf" };
        this.handleChange = this.handleChange.bind(this);

    }
    const handleChange = (event) =>{
            this.setState({
                userName: event.target.value
            })
        }

    render(){

        return(
            <div >
                <UserInput value={this.state.userName} changed={this.handleChange} />
                <UserOutput userName={this.state.userName} />

            </div>
        )
    }
}


问:
Pandas series group by calculate percentage
I have a data frame. I have grouped a column status by date using

```<code>y = news_dataframe.groupby(by=[news_dataframe['date'].dt.date,news_dataframe['status']])['status'].count()
</code>```

and my output is --

```<code>date         status            count
2019-05-29   selected           24
             rejected auto     243
             waiting           109
             no action         1363
2019-05-30   selected           28
             rejected auto     188
             waiting           132
             no action         1249
             repeat              3
2019-05-31   selected           13
             rejected auto       8
             waiting             23
             no action          137
             repeat              2
             source              1
Name: reasonForReject, dtype: int64
</code>```

Now I want to calculate the percentage of each status group by date. How can I achieve this using pandas dataframe?

答:
Compute two different groupbys and divide one by the other:</p>

```<code>y_numerator = news_dataframe.groupby(by=[news_dataframe['date'].dt.date,news_dataframe['status']])['status'].count()

y_denominator = news_dataframe.groupby(by=news_dataframe['date'].dt.date)['status'].count()

y=y_numerator/y_denominator
</code>```

Body:
I have a data frame. I have grouped a column status by date using

y = news_dataframe.groupby(by=[news_dataframe['date'].dt.date,news_dataframe['status']])['status'].count()

and my output is --

date         status            count
2019-05-29   selected           24
             rejected auto     243
             waiting           109
             no action         1363
2019-05-30   selected           28
             rejected auto     188
             waiting           132
             no action         1249
             repeat              3
2019-05-31   selected           13
             rejected auto       8
             waiting             23
             no action          137
             repeat              2
             source              1
Name: reasonForReject, dtype: int64

Now I want to calculate the percentage of each status group by date. How can I achieve this using pandas dataframe?

Body:
Compute two different groupbys and divide one by the other:

y_numerator = news_dataframe.groupby(by=[news_dataframe['date'].dt.date,news_dataframe['status']])['status'].count()

y_denominator = news_dataframe.groupby(by=news_dataframe['date'].dt.date)['status'].count()

y=y_numerator/y_denominator


问:
How to remove everything fron the superView and not just the last item?
In my app i had to draw certain checkboxes at a same time and i used a single function to add all of them. Now when a user clicks one of them all of those checkboxes should get removed from the superview and currently its just removing the last one. Also i have issue to recognize those checkboxes like which one is clicked. i know it should be done through Tag property but don't know how exactly it should be implemented.
Any suggestions.</p>

答:
Removing all subviews

```<code>int numberOfSubviews = [[yourView subviews] count];

    for(int i=0;i<numberOfSubviews-1;i++
    {
      [[youView subviews]objectAtIndex:i]removeFromSuperView];
    }
</code>```

//this will leave check box that you added at last.... for first one to remain loop from 1 to numberOfSubviews....

Using tag property...
when you are creating checkbox objects use

```<code>checkBoxObject.tag = i;
</code>```

//I am considering i as looop count which you are using in a loop
to add checkboxes.

then whenever you need a object of checkbox

```<code>[yourViewonwhichYouAddedCheckBox viewWithTag:<your tag >];
</code>```

Thanks

Body:
Removing all subviews

int numberOfSubviews = [[yourView subviews] count];

    for(int i=0;i<numberOfSubviews-1;i++
    {
      [[youView subviews]objectAtIndex:i]removeFromSuperView];
    }

//this will leave check box that you added at last.... for first one to remain loop from 1 to numberOfSubviews....

Using tag property...
when you are creating checkbox objects use

checkBoxObject.tag = i;

//I am considering i as looop count which you are using in a loop
to add checkboxes.

then whenever you need a object of checkbox

[yourViewonwhichYouAddedCheckBox viewWithTag:<your tag >];

Thanks


问:
Custom font faces for jspdf-autotable plugin
Can someone help with an example for setting custom fonts for jspdf-autotable

I tried the following

```<code>var doc = new jsPDF('p', 'pt');
doc.setFont("rotobo");      ----> font face name that I declared in my css file
doc.autoTable(columns, data);
doc.save("table.pdf");
</code>```

After I tried this, the fonts in PDF did not change.

Any suggestions would be appreciated.

答:
To fix the problem, you need to do:

Download the jspdf-autotable, to work local

In the jspdf-autotable, there is 2 time calling to text(...) function, so you need to add setFont before calling to text function

The code you need to change:

jsPDF.API.autoTableText = function (text, x, y, styles) {
    styles = styles || {};
    var FONT_ROW_RATIO = 1.15;
    if (typeof x !== 'number' || typeof y !== 'number') {
        console.error('The x and y parameters are required. Missing for text: ', text);
    }
    var k = this.internal.scaleFactor;
    var fontSize = this.internal.getFontSize() / k;
    var splitRegex = /\r\n|\r|\n/g;
    var splitText = null;
    var lineCount = 1;
    if (styles.valign === 'middle' || styles.valign === 'bottom' || styles.halign === 'center' || styles.halign === 'right') {
        splitText = typeof text === 'string' ? text.split(splitRegex) : text;
        lineCount = splitText.length || 1;
    }
    // Align the top
    y += fontSize * (2 - FONT_ROW_RATIO);
    if (styles.valign === 'middle')
        y -= (lineCount / 2) * fontSize * FONT_ROW_RATIO;
    else if (styles.valign === 'bottom')
        y -= lineCount * fontSize * FONT_ROW_RATIO;
    if (styles.halign === 'center' || styles.halign === 'right') {
        var alignSize = fontSize;
        if (styles.halign === 'center')
            alignSize *= 0.5;
        if (lineCount >= 1) {
            for (var iLine = 0; iLine < splitText.length; iLine++) {
                this.text(splitText[iLine], x - this.getStringUnitWidth(splitText[iLine]) * alignSize, y);
                y += fontSize;
            }
            return this;
        }
        x -= this.getStringUnitWidth(text) * alignSize;
    }
    if (styles.halign === 'justify') {
        this.setFont("frank");   //---> this u need to adding
        this.setFontType("normal");
        this.text(text, x, y, { maxWidth: styles.maxWidth || 100, align: 'justify' });
    }
    else {
        this.setFont("frank"); //---> this u need to adding
        this.setFontType("normal");
        this.text(text, x, y);
    }
    return this;
};
```

Body:
Can someone help with an example for setting custom fonts for jspdf-autotable

I tried the following

var doc = new jsPDF('p', 'pt');
doc.setFont("rotobo");      ----> font face name that I declared in my css file
doc.autoTable(columns, data);
doc.save("table.pdf");

After I tried this, the fonts in PDF did not change.

Any suggestions would be appreciated.


问:
What would be the correct URI for an endpoint that shares a file with other users?
I've been reading through the best practices when it comes to API definitions and one of the most common recommendations is to make sure that your endpoint definitions do not contain verbs in the path (only nouns should be used for the resources as well as values for path parameters). Instead, the HTTP methods should be used as the "verbs" to perform actions over the resources.

The thing is, suppose I want to create an endpoint that allows a user to share a file with other users. The way I would do it would be as follows:

```<code>POST /api/file/{file_id}/share/
</code>```

With a request body that would look as follows

```<code>{ users: [1, 2, ... , N] }
</code>```

For me this is the most intuitive way to do it since I am performing an operation over the file resource but none of the HTTP methods is enough to describe the operation and I am forced to use the /share/ in order to be able to specify the action to perform.

I am thus violating the best practices of only using nouns in the endpoint path but I dont see any other possible way to do it except adding query parameters, but those are usually done for filters, sorting, etc.

What would be an adequate way of defining such endpoint?

答:
I think your solution is OK. You can take /share as the sub-resource of /api/file/{file_id} -- the sharing status of specific file.

So, to share a (not shared yet) file with other users:

POST /api/file/{file_id}/share

And to change the user list that file shared with:

PUT /api/file/{file_id}/share

To me, /share is a good choice -- it's concise and descriptive. However, if you really want to use a noun instead of verb, you can use /sharing or /share-status etc.

Body:
I've been reading through the best practices when it comes to API definitions and one of the most common recommendations is to make sure that your endpoint definitions do not contain verbs in the path (only nouns should be used for the resources as well as values for path parameters). Instead, the HTTP methods should be used as the "verbs" to perform actions over the resources.

The thing is, suppose I want to create an endpoint that allows a user to share a file with other users. The way I would do it would be as follows:

POST /api/file/{file_id}/share/

With a request body that would look as follows

{ users: [1, 2, ... , N] }

For me this is the most intuitive way to do it since I am performing an operation over the file resource but none of the HTTP methods is enough to describe the operation and I am forced to use the /share/ in order to be able to specify the action to perform.

I am thus violating the best practices of only using nouns in the endpoint path but I dont see any other possible way to do it except adding query parameters, but those are usually done for filters, sorting, etc.

What would be an adequate way of defining such endpoint?


问:
how to find collegue Id in table
i have one table as Employee that have two column Id and Branch. i have to find its collegue Id except his own id from table without using subquery.

```<code>Id      Branch
==============
1       Delhi
2       Mumbai
3       Delhi
4       Delhi
5       Mumbai
6       Mumbai
</code>```

if i enter e.g. 3 then my answer has to be 1 and 4.

答:
Without a subquery means with a self join:

```<code>select tt.*
from tablename t inner join tablename tt
on t.Branch = tt.Branch and tt.id <> t.id
where t.id = 3
</code>```

See the demo.

Title: how to find collegue Id in table

Body:
i have one table as Employee that have two column Id and Branch. i have to find its collegue Id except his own id from table without using subquery.

Id      Branch
==============
1       Delhi
2       Mumbai
3       Delhi
4       Delhi
5       Mumbai
6       Mumbai

if i enter e.g. 3 then my answer has to be 1 and 4.

Body:
Without a subquery means with a self join:

select tt.*
from tablename t inner join tablename tt
on t.Branch = tt.Branch and tt.id <> t.id
where t.id = 3

See the demo.


问:
Android. TextInputLayout. Toggle password visibility event listener?
There is a password visibility toggle button within TextInputLayout for InputType textPassword.

Is it somehow possible to catch toggle events?

I couldn't find any public methods for this

答:
After analyzing the View hierarchy with Layout Inspector I can see the following:

So you can either do:

```<code>val toggle = password.findViewById<CheckableImageButton?>(R.id.text_input_password_toggle)
toggle?.setOnClickListener {
    println("clicked on toggle")
}
</code>```

or manually:

```<code>// Assuming you have AndroidKTX
val views = password.children
for (v in views) {
    if (v is FrameLayout) {
        val innerViews = v.children
        for (iv in innerViews) {
            if (iv is CheckableImageButton) {
                iv.setOnClickListener {
                    println("clicked on toggle")
                }
            }
        }
    }
}
</code>```

Body:
After analyzing the View hierarchy with Layout Inspector I can see the following:

So you can either do:

val toggle = password.findViewById<CheckableImageButton?>(R.id.text_input_password_toggle)
toggle?.setOnClickListener {
    println("clicked on toggle")
}

or manually:

// Assuming you have AndroidKTX
val views = password.children
for (v in views) {
    if (v is FrameLayout) {
        val innerViews = v.children
        for (iv in innerViews) {
            if (iv is CheckableImageButton) {
                iv.setOnClickListener {
                    println("clicked on toggle")
                }
            }
        }
    }
}


问:
Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
This question is kind of duplicate but I could not find a solution to it.
When I am calling the flask app and passing the JSON data, I am getting the error:

```<code>"Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)</p>"
</code>```

Below is the flask code:

```<code>@app.route('/data_extraction', methods=['POST'])
def check_endpoint2():
    data= request.json()
    result = data['title']
    out={"result": str(result)}
    return json.dumps(out)
    #return 'JSON Posted'
</code>```

This is how I am calling it from curl

```<code>curl -i -H "Content-Type: application/json" charset=utf-8 -X POST -d '{"title":"Read a book"}' 127.0.0.1:5000/data_extraction
</code>```

I also want to know how can I curl the JSON file(test_data.json), will it be like this?

```<code>curl -i -H "Content-Type: application/json" charset=utf-8 -X POST -d @test_data.json 127.0.0.1:5000/data_extraction
</code>```

答:
Maybe you should not set the Content-Type to application/json, cancel it and retry it.
I have encountered the same problem as you, and I solved it like this.</p>

Body:
This question is kind of duplicate but I could not find a solution to it.
When I am calling the flask app and passing the JSON data, I am getting the error:

"Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
"

Below is the flask code:

@app.route('/data_extraction', methods=['POST'])
def check_endpoint2():
    data= request.json()
    result = data['title']
    out={"result": str(result)}
    return json.dumps(out)
    #return 'JSON Posted'

This is how I am calling it from curl

curl -i -H "Content-Type: application/json" charset=utf-8 -X POST -d '{"title":"Read a book"}' 127.0.0.1:5000/data_extraction

I also want to know how can I curl the JSON file(test_data.json), will it be like this?

curl -i -H "Content-Type: application/json" charset=utf-8 -X POST -d @test_data.json 127.0.0.1:5000/data_extraction


问:
Update Textbox from another class
I need to write into a textbox on Form1 class from another class, but can't get it to work.

I'll use a very simple example of what I want to acheive.  On Form1 I have a combobox with collection of items 1,2,3,4,5. And also a textbox. Based on what is selected in the combobox, a different message will appear in the text box.  For example if I choose 1 in the combobox, textbox1 will say "1 was selected". if I choose 2 in the combobox textbox1 will say "2 was selected", etc.

I'm using a switch statement for this, but I dont want the switch statement to be in Form1.cs but instead in Class1.cs  But i can't get the text into the textbox unless I have the switch statement in Form1.cs. But I really want the switch statement to be in Class1.cs.  I've tried making both my textbox and combobox public but it didn't make a difference.

This is what I have in Form1.cs:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string ComboBox1Text
    {
        get { return comboBox1.Text; }
    }

    public string TextBox1Text
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        Class1 class1 = new Class1();
        class1.FunctionSelect();
    }
}
</code>```

And this is the other class Class1.cs:

```<code>class Class1
{
    public void FunctionSelect()
    {
        Form1 form1 = new Form1();
        string switcher = form1.ComboBox1Text;
        switch (switcher)
        {
            case "1":
                form1.TextBox1Text = "1 was selected";
                break;
            case "2":
                form1.TextBox1Text = "2 was selected";
                break;
            case "3":
                form1.TextBox1Text = "3 was selected";
                break;
            case "4":
                form1.TextBox1Text = "4 was selected";
                break;
            case "5":
                form1.TextBox1Text = "5 was selected";
                break;
        }
    }
}
</code>```

When I select something in the combobox nothing happens in the text box.  But if I move my switch statement in FunctionSelect() from Class1.cs to Form1.cs it works exactly as I expected.  But really I need FunctionSelect() to be in Class1.cs - Not in Form1.cs.  I believe the problem is due to creating a new instance for Form1 in Class1.cs (Form1 form1 = new Form1()), which means I'm not actually writing to the Form1 displayed on the screen.  But I can't work out how to write to the textbox on Form1.cs from Class1.cs.

I'm sure I'm missing something very simple, but can't work it out, and can't find a post that answers exactly as I need.  Any help is appreciated.

答:
The form class doesn't change:

```<code> public partial class Form1 : Form
 {
     public Form1()
     {
          InitializeComponent();
     }

     public string ComboBox1Text
     {
          get { return comboBox1.Text; }
     }

    public string TextBox1Text
    {
         get { return textBox1.Text; }
         set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
          Class1 class1 = new Class1();
          class1.FunctionSelect();
    }
</code>```

And this is the second class

```<code>class Class1
{
public void FunctionSelect()
{
    Form1 form1 = (Form1)Application.OpenForms[0];

    string switcher = form1.ComboBox1Text;
    switch (switcher)
    {
        case "1":
            form1.TextBox1Text = "1 was selected";
            break;
        case "2":
            form1.TextBox1Text = "2 was selected";
            break;
        case "3":
            form1.TextBox1Text = "3 was selected";
            break;
        case "4":
            form1.TextBox1Text = "4 was selected";
            break;
        case "5":
            form1.TextBox1Text = "5 was selected";
            break;
      }
    }
 }
</code>```

Application.OpenForms[index] is readonly "FormCollection" how contains all opened forms and can be indexed by int or by string (form name), but it has to be casted in your form type because it type is "Form" (base class of your form)

Example:

```<code> MyForm fm=(MyFormType)Application.OpenForm["MyFormName"]; // or 0 for example
</code>```

https://learn.microsoft.com/en-US/dotnet/api/system.windows.forms.application.openforms?view=netframework-4.8

Title: Update Textbox from another class

Body:
I need to write into a textbox on Form1 class from another class, but can't get it to work.

I'll use a very simple example of what I want to acheive.  On Form1 I have a combobox with collection of items 1,2,3,4,5. And also a textbox. Based on what is selected in the combobox, a different message will appear in the text box.  For example if I choose 1 in the combobox, textbox1 will say "1 was selected". if I choose 2 in the combobox textbox1 will say "2 was selected", etc.

I'm using a switch statement for this, but I dont want the switch statement to be in Form1.cs but instead in Class1.cs  But i can't get the text into the textbox unless I have the switch statement in Form1.cs. But I really want the switch statement to be in Class1.cs.  I've tried making both my textbox and combobox public but it didn't make a difference.

This is what I have in Form1.cs:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string ComboBox1Text
    {
        get { return comboBox1.Text; }
    }

    public string TextBox1Text
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        Class1 class1 = new Class1();
        class1.FunctionSelect();
    }
}

And this is the other class Class1.cs:

class Class1
{
    public void FunctionSelect()
    {
        Form1 form1 = new Form1();
        string switcher = form1.ComboBox1Text;
        switch (switcher)
        {
            case "1":
                form1.TextBox1Text = "1 was selected";
                break;
            case "2":
                form1.TextBox1Text = "2 was selected";
                break;
            case "3":
                form1.TextBox1Text = "3 was selected";
                break;
            case "4":
                form1.TextBox1Text = "4 was selected";
                break;
            case "5":
                form1.TextBox1Text = "5 was selected";
                break;
        }
    }
}

When I select something in the combobox nothing happens in the text box.  But if I move my switch statement in FunctionSelect() from Class1.cs to Form1.cs it works exactly as I expected.  But really I need FunctionSelect() to be in Class1.cs - Not in Form1.cs.  I believe the problem is due to creating a new instance for Form1 in Class1.cs (Form1 form1 = new Form1()), which means I'm not actually writing to the Form1 displayed on the screen.  But I can't work out how to write to the textbox on Form1.cs from Class1.cs.

I'm sure I'm missing something very simple, but can't work it out, and can't find a post that answers exactly as I need.  Any help is appreciated.

Body:
The form class doesn't change:

 public partial class Form1 : Form
 {
     public Form1()
     {
          InitializeComponent();
     }

     public string ComboBox1Text
     {
          get { return comboBox1.Text; }
     }

    public string TextBox1Text
    {
         get { return textBox1.Text; }
         set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
          Class1 class1 = new Class1();
          class1.FunctionSelect();
    }

And this is the second class

class Class1
{
public void FunctionSelect()
{
    Form1 form1 = (Form1)Application.OpenForms[0];

    string switcher = form1.ComboBox1Text;
    switch (switcher)
    {
        case "1":
            form1.TextBox1Text = "1 was selected";
            break;
        case "2":
            form1.TextBox1Text = "2 was selected";
            break;
        case "3":
            form1.TextBox1Text = "3 was selected";
            break;
        case "4":
            form1.TextBox1Text = "4 was selected";
            break;
        case "5":
            form1.TextBox1Text = "5 was selected";
            break;
      }
    }
 }

Application.OpenForms[index] is readonly "FormCollection" how contains all opened forms and can be indexed by int or by string (form name), but it has to be casted in your form type because it type is "Form" (base class of your form)

Example:

 MyForm fm=(MyFormType)Application.OpenForm["MyFormName"]; // or 0 for example

https://learn.microsoft.com/en-US/dotnet/api/system.windows.forms.application.openforms?view=netframework-4.8


问:
React Native Navigate to screen outside render
```<code>const Card = (props) => {
    return (
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Route')}>
            ...
        </TouchableOpacity>
    );

};

export default class HorizontalList extends Component {
    ...

    render() {
          return (
                <FlatList
                    ...
                    renderItem={({item: rowData}) => {
                        return (
                            <Card
                                thumb_image={rowData.thumb_image}
                                title={rowData.title}
                                innerSubTitle={rowData.innerSubTitle}
                                innerMainTitle={rowData.innerMainTitle}
                            />
                        );
                    }}
                    keyExtractor={(item, index) => String(index)}
                />
            );
    }
}
</code>```

I want to add a onPress in Card that will open another screen in the app. Constant is declared outside the render and Card is called as a template inside the render function.

答:
Pass navigation to Card

```<code><Card
   navigation={this.props.navigation}
   thumb_image={rowData.thumb_image}
   title={rowData.title}
   innerSubTitle={rowData.innerSubTitle}
   innerMainTitle={rowData.innerMainTitle}
/>
</code>```

and use like this:

```<code>const Card = (props) => {
    return (
        <TouchableOpacity onPress={() => props.navigation.navigate('Route')}>
            ...
        </TouchableOpacity>
    );

};
</code>```

Body:
const Card = (props) => {
    return (
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Route')}>
            ...
        </TouchableOpacity>
    );

};

export default class HorizontalList extends Component {
    ...

    render() {
          return (
                <FlatList
                    ...
                    renderItem={({item: rowData}) => {
                        return (
                            <Card
                                thumb_image={rowData.thumb_image}
                                title={rowData.title}
                                innerSubTitle={rowData.innerSubTitle}
                                innerMainTitle={rowData.innerMainTitle}
                            />
                        );
                    }}
                    keyExtractor={(item, index) => String(index)}
                />
            );
    }
}

I want to add a onPress in Card that will open another screen in the app. Constant is declared outside the render and Card is called as a template inside the render function.

Body:
Pass navigation to Card

<Card
   navigation={this.props.navigation}
   thumb_image={rowData.thumb_image}
   title={rowData.title}
   innerSubTitle={rowData.innerSubTitle}
   innerMainTitle={rowData.innerMainTitle}
/>

and use like this:

const Card = (props) => {
    return (
        <TouchableOpacity onPress={() => props.navigation.navigate('Route')}>
            ...
        </TouchableOpacity>
    );

};