问:
Python making multiple zip objects will overwrite the first one
I was working on a project when I came into this really weird bug, and I have managed to cut it down to this:

```<code>xr = zip(range(0, 5), range(0, 5))
yr = zip(range(3, 4), range(0, 1))

print(list(xr), list(yr))
print(list(xr))
</code>```

The expected output would be this:

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

Because I don't change xr or yr after I set them. I am just printing them as a list to the shell. But, when I actually run it, I get this output:

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

I have absolutely no clue why. I have been using python for about a week, and maybe this is supposed to happen, but I would appreciate it if someone told me what's going on here. Thanks!

My python version is Python 3.8.3

答:
That's because you're exhausting the iterator.

Use this:

xr = list(zip(range(0, 5), range(0, 5)))
yr = list(zip(range(3, 4), range(0, 1)))

print(xr, yr)
print(xr)
```

Body:
I was working on a project when I came into this really weird bug, and I have managed to cut it down to this:

xr = zip(range(0, 5), range(0, 5))
yr = zip(range(3, 4), range(0, 1))

print(list(xr), list(yr))
print(list(xr))

The expected output would be this:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

Because I don't change xr or yr after I set them. I am just printing them as a list to the shell. But, when I actually run it, I get this output:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[]

I have absolutely no clue why. I have been using python for about a week, and maybe this is supposed to happen, but I would appreciate it if someone told me what's going on here. Thanks!

My python version is Python 3.8.3


来源: stackexchange

问:
How to get sum of 2 arrays
I've been trying to make a calculator in JavaScript.

My issue is I don't know how to find the sum of 2 arrays (the first number (33) is saved to an array called num1 ) (the second number (99) is saved to an array called num2 )  example(33+99 = ?)

I wrote the below statement but the total returns in a concatenated format ex(1,3,5,3) which is not my intended solution

```<code>     const calculate = (n1,n2) => {
     let result =""

     if (n1.length > 0 ){
        result =  n1 + n2
     }
        return result
     }

     v.push(calculate(num1, num2))
     document.getElementById("answer").innerHTML = v
</code>```

答:
The example to use only one reduce:

```<code>let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];
array1.concat(array2).reduce((a,v) => a + v,0)
</code>```

Or even like that:

```<code>let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];
[...array1, ...array2].reduce((a,v) => a + v,0)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get sum of 2 arrays

Body:
I've been trying to make a calculator in JavaScript.

My issue is I don't know how to find the sum of 2 arrays (the first number (33) is saved to an array called num1 ) (the second number (99) is saved to an array called num2 )  example(33+99 = ?)

I wrote the below statement but the total returns in a concatenated format ex(1,3,5,3) which is not my intended solution

     const calculate = (n1,n2) => {
     let result =""

     if (n1.length > 0 ){
        result =  n1 + n2
     }
        return result
     }

     v.push(calculate(num1, num2))
     document.getElementById("answer").innerHTML = v

Body:
The example to use only one reduce:

let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];
array1.concat(array2).reduce((a,v) => a + v,0)

Or even like that:

let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];
[...array1, ...array2].reduce((a,v) => a + v,0)


问:
Watcher in vue.js won't receive value
Im using a watcher in vue for updating the values in the component Persons.vue as soon as an array Im passing from the App.vue to the Persons.vue as a prop changes. It works fine and updates when Im updating the prop by using the optionlist. But as soon as Im using a datepicker to set the a new date the array that is saved to the prop personData is updated correctly in the console log but is not received in the watcher.

Any hint of solving this is very much apreciated!

This is i fictive codesetup based on a much bigger application but I hope you get the problem.

App.vue

```<code><template>
  <div id="app">
    <select @change="person($event)">
      <option :value="selectionOne">One</option>
      <option :value="selectionTwo">Two</option>
    </select>
    <flat-pickr v-model="initDate" :config="config" @on-change="changeTime"></flat-pickr>
  </div>
</template>
</code>```

if I start with updating the person the value is sent to the watcher correctly but if I after that is running the changeTime function by changing the date the value is not sent to the watcher

```<code>  data() {
    return {
      selected: "selectionOne",
      selectionOne: "selectionOne",
      selectionTwo: "selectionTwo",
      personOne: [{ firstName: "XX" }, { born: "XXXX" }],
      personTwo: [{ firstName: "YY" }, { born: "YYYY" }],
      personData: []
    };
  },
  created() {
    this.personData = [{ firstName: "XX" }, { born: "XXXX" }];
  },

  methods: {
    // if I start with updating the person the value is sent to the watcher correctly
    person(e) {
      this.selected = e;
      this.updateNames(e);
    },
    // but if I after that is running the changeTime function by changing the date the value is not sent to the watcher
    changeTime(selectedDates) {
      this.born = this.timeFormatter(selectedDates[0]);
      this.updateNames(this.selected);
    },

    updateNames(e) {
      this.selected = e;
      let selection = e.target.value.split(",");
      if (selection == "selectionOne") {
        this.personData = this.personOne;
        // updating the second position with new born object
        this.personData[1] = { born: this.born };
      }
      if (selection == "selectionTwo") {
        this.personData = this.personTwo;
        this.personData[1] = { born: this.born };
      }
      console.log(this.personData)
    }
  }
};
</code>```

Persons.vue

```<code>export default {
  name: "Persons",
  props: {
    personData: {
      type: Array
    }
  },

  watch: {
    personData: {
      deep: true,
      immediate: true,
      handler(newValue) {
        try {
          console.log("newValue", newValue);
        } catch (err) {
          console.log("no data yet ...");
        }
      }
    }
  }
};
</script>
</code>```

答:
You could try using this.$set like this:

updateNames(e) {
  this.selected = e;
  let selection = e.target.value.split(",");
  if (selection == "selectionOne") {
    this.personData = this.personOne;
    // updating the second position with new born object
    this.$set(this.personData, 1, { born: this.born });
  }
  if (selection == "selectionTwo") {
    this.personData = this.personTwo;
    this.$set(this.personData, 1, { born: this.born });
  }
  console.log(this.personData)
}
```

But you might want to re-evaluate your setup. Storing the data as an object in an array, copied from another array, seems like a cumbersome way to handle this data.

Title: Watcher in vue.js won't receive value

Body:
Im using a watcher in vue for updating the values in the component Persons.vue as soon as an array Im passing from the App.vue to the Persons.vue as a prop changes. It works fine and updates when Im updating the prop by using the optionlist. But as soon as Im using a datepicker to set the a new date the array that is saved to the prop personData is updated correctly in the console log but is not received in the watcher.

Any hint of solving this is very much apreciated!

This is i fictive codesetup based on a much bigger application but I hope you get the problem.

App.vue

<template>

    <select @change="person($event)">
      <option :value="selectionOne">One</option>
      <option :value="selectionTwo">Two</option>
    </select>
    <flat-pickr v-model="initDate" :config="config" @on-change="changeTime"></flat-pickr>

</template>

if I start with updating the person the value is sent to the watcher correctly but if I after that is running the changeTime function by changing the date the value is not sent to the watcher

  data() {
    return {
      selected: "selectionOne",
      selectionOne: "selectionOne",
      selectionTwo: "selectionTwo",
      personOne: [{ firstName: "XX" }, { born: "XXXX" }],
      personTwo: [{ firstName: "YY" }, { born: "YYYY" }],
      personData: []
    };
  },
  created() {
    this.personData = [{ firstName: "XX" }, { born: "XXXX" }];
  },

  methods: {
    // if I start with updating the person the value is sent to the watcher correctly
    person(e) {
      this.selected = e;
      this.updateNames(e);
    },
    // but if I after that is running the changeTime function by changing the date the value is not sent to the watcher
    changeTime(selectedDates) {
      this.born = this.timeFormatter(selectedDates[0]);
      this.updateNames(this.selected);
    },

    updateNames(e) {
      this.selected = e;
      let selection = e.target.value.split(",");
      if (selection == "selectionOne") {
        this.personData = this.personOne;
        // updating the second position with new born object
        this.personData[1] = { born: this.born };
      }
      if (selection == "selectionTwo") {
        this.personData = this.personTwo;
        this.personData[1] = { born: this.born };
      }
      console.log(this.personData)
    }
  }
};

Persons.vue

export default {
  name: "Persons",
  props: {
    personData: {
      type: Array
    }
  },

  watch: {
    personData: {
      deep: true,
      immediate: true,
      handler(newValue) {
        try {
          console.log("newValue", newValue);
        } catch (err) {
          console.log("no data yet ...");
        }
      }
    }
  }
};
</script>

Body:
You could try using this.$set like this:

updateNames(e) {
  this.selected = e;
  let selection = e.target.value.split(",");
  if (selection == "selectionOne") {
    this.personData = this.personOne;
    // updating the second position with new born object
    this.$set(this.personData, 1, { born: this.born });
  }
  if (selection == "selectionTwo") {
    this.personData = this.personTwo;
    this.$set(this.personData, 1, { born: this.born });
  }
  console.log(this.personData)
}

But you might want to re-evaluate your setup. Storing the data as an object in an array, copied from another array, seems like a cumbersome way to handle this data.


问:
Does AWS request signing hide the access key?
If I sign a request to the AWS API and I then forward this request to a client to have it execute the request, can the client (given the request) reverse engineer the access key that was used?

In other words, if I sign a request with my access key, can I safely have someone else execute that request for me, without them knowing the access key?

And can the client see the request contents that are being fired?

答: Your access key id will be visible but your secret access key will not. Signing a request does not encrypt the contents so the contents would still be readable.</p>


问:
How to make a table with automatic column widths without using HTML table?
I have a big table I'm trying to add some hover effects to and finding that CSS tables are relatively inflexible, so I'd like to try to implement some other way (see background below).

I'm thinking CSS grid might work. How can I make a CSS table using CSS grid? I need the columns widths to adjust automatically (and of course be synced between rows), as they do with a regular CSS table, and (I think) I need each row to be a parent element to its cells, as in tables.

I read here that the level 2 specifications of CSS grid incorporate a subgrid, but I've been unable to find an example of using subgrid to duplicate basic table functionality. It seems most browsers don't yet implement subgrid, so display: contents might be an alternative.

Background in case you need it: I'm trying to implement a sort of action-bar hover-overlay, as in Gmail: when you hover the cursor over a row/email, an overlay appears on the right side of the row with various actions you can perform on the row/email, such as Move to folder, Delete. Gmail displays the table rows as flex boxes to make this possible, but that means the column widths have to be set "by hand." In my case I have a massive table of various data and setting column widths by hand isn't feasible.

UPDATE: what does it look like? It's an ordinary table with rows and columns. You have certainly seen such things before. I'm asking a general question and the particulars of the table are irrelevant.

Here is a screen shot from Gmail, fwiw:

答:
Just to show how the
 can be used in the "flex" way. Ofcourse you may change the table and table related elements in a
 element. Use in both solutions the table structure.

The css is cross browser and responsive for smartphone, tablet, desktop and other devices.

```<code><div class="tbl">   or   <div class="tbl">
  <table>                  <div class="table">
    <tr>                     <div class="tr">
      ...                      ...
    </tr>                    </div>
  </table>                 </div>
</div>                   </div>
</code>```

with css

```<code>.tbl {
  max-width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}
.tbl * {
  box-sizing: border-box;
  margin: 0;
}
table, .table {
  display: flex;
  flex-wrap: wrap;
  position: relative;
  border-collapse: collapse;
  background-color: transparent;
}
thead, tbody, tfoot, .thead, .tbody, .tfoot {
  display: block;
  flex: 0 0 100%;
  width: 100%;
  max-width: 100%;
  position: relative;
}
tr, .tr {
  display: flex;
  flex-wrap: nowrap;
  position: relative;
}
th, td, .th, .td {
  display: block;
  width: 100%;
  flex: 0 0 25%;  /* column width */
  max-width: 25%; /* column width */
  white-space: normal;
  word-break: break-all; /* for very long words */
}
/* below for smartphone */
@media (max-width: 767.9px) {
  table, .table {
    border: 0;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    -ms-overflow-style: -ms-autohiding-scrollbar;
  }
}
/* below some styling */
table, .table {
  border-top: 1px solid silver;
  border-left: 1px solid silver;
}
th, td, .th, .td {
  border-right: 1px solid silver;
  border-bottom: 1px solid silver;
}
</code>```

Example below you'll find the extra css for a table with 3 flex columns where each column has a different width.

Note that the sum of all columns is 100%

```<code>tr th:nth-child(1), tr td:nth-child(1) {
  flex: 0 0 22%;
  max-width: 22%;
}
tr th:nth-child(2), tr td:nth-child(2) {
  flex: 0 0 46%;
  max-width: 46%;
}
tr th:nth-child(3), tr td:nth-child(3) {
  flex: 0 0 32%;
  max-width: 32%;
}
</code>```

Body:
Just to show how the <table> can be used in the "flex" way. Ofcourse you may change the table and table related elements in a <div class=".."> element. Use in both solutions the table structure.

The css is cross browser and responsive for smartphone, tablet, desktop and other devices.

<div class="tbl">   or   <div class="tbl">
  <table>                  <div class="table">
    <tr>                     <div class="tr">
      ...                      ...
    </tr>                    </div>
  </table>                 </div>
</div>                   </div>

with css

.tbl {
  max-width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}
.tbl * {
  box-sizing: border-box;
  margin: 0;
}
table, .table {
  display: flex;
  flex-wrap: wrap;
  position: relative;
  border-collapse: collapse;
  background-color: transparent;
}
thead, tbody, tfoot, .thead, .tbody, .tfoot {
  display: block;
  flex: 0 0 100%;
  width: 100%;
  max-width: 100%;
  position: relative;
}
tr, .tr {
  display: flex;
  flex-wrap: nowrap;
  position: relative;
}
th, td, .th, .td {
  display: block;
  width: 100%;
  flex: 0 0 25%;  /* column width */
  max-width: 25%; /* column width */
  white-space: normal;
  word-break: break-all; /* for very long words */
}
/* below for smartphone */
@media (max-width: 767.9px) {
  table, .table {
    border: 0;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    -ms-overflow-style: -ms-autohiding-scrollbar;
  }
}
/* below some styling */
table, .table {
  border-top: 1px solid silver;
  border-left: 1px solid silver;
}
th, td, .th, .td {
  border-right: 1px solid silver;
  border-bottom: 1px solid silver;
}

Example below you'll find the extra css for a table with 3 flex columns where each column has a different width.

Note that the sum of all columns is 100%

tr th:nth-child(1), tr td:nth-child(1) {
  flex: 0 0 22%;
  max-width: 22%;
}
tr th:nth-child(2), tr td:nth-child(2) {
  flex: 0 0 46%;
  max-width: 46%;
}
tr th:nth-child(3), tr td:nth-child(3) {
  flex: 0 0 32%;
  max-width: 32%;
}


问:
Laravel 419 error on POST request via axios React
I'm trying to send a POST request to my API which is running Laravel 7.

My route is as follows:

```<code>Route::get('/data', 'CartographieController@dataToJson');
Route::post('/addDraft', 'CartographieController@addDraft');
</code>```

this is my post function in controller:

```<code>public function addDraft(Request $request)
{
    $draft = Draft::create($request->all());
    return response()->json($draft, 201);
}
</code>```

I send the from React form here is:

```<code>handleAdd(event) {
event.preventDefault();

var draft = {
  description: this.state.description,
};

try {
  const nextData = clone(this.state);
  nextData.drafts.push(draft);
  //console.log("state" + this.state);
  this.setState({ drafts: nextData.drafts });
  console.log("state" + this.state);
} catch (error) {
  console.log(error);
}

axios
  .post("http://127.0.0.1:8000/addDraft/", this.state.drafts)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</code>```

As a response to the request I get:
Request failed with status code 419

答: Hi 419 is unproccesble entity error, better you can catch this error and display as exception error</p>

Body:
I'm trying to send a POST request to my API which is running Laravel 7.

My route is as follows:

Route::get('/data', 'CartographieController@dataToJson');
Route::post('/addDraft', 'CartographieController@addDraft');

this is my post function in controller:

public function addDraft(Request $request)
{
    $draft = Draft::create($request->all());
    return response()->json($draft, 201);
}

I send the from React form here is:

handleAdd(event) {
event.preventDefault();

var draft = {
  description: this.state.description,
};

try {
  const nextData = clone(this.state);
  nextData.drafts.push(draft);
  //console.log("state" + this.state);
  this.setState({ drafts: nextData.drafts });
  console.log("state" + this.state);
} catch (error) {
  console.log(error);
}

axios
  .post("http://127.0.0.1:8000/addDraft/", this.state.drafts)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

As a response to the request I get:
Request failed with status code 419


问:
Is there any practical reason to check if something is destructible before calling its destructor?
So I've been messing around trying to implement a variant/tagged union class and needed a way to write generic destructors and made what I thought was a silly mistake forgetting that some types don't have destructors, doing something like

```<code>template<typename T>
void destruct(T& thing) {
    thing.~T();
}
</code>```

Yet, this worked fine even with types that didn't have destructors, like int or struct A {int b;};. I still think it's more readable and easier to reason with something that uses something like this

```<code>template<typename T>
void destruct(T& thing) {
    if constexpr(std::is_destructible<T>::value) {
        thing.~T();
    }
}
</code>```

But is there actually any difference between the code? The first one feels pretty undefined behavoiry/just wrong to me.

答:
You don't need to check. In this context for a type like int it translates to a pseudo-destructor call. The result is a near no-op

[expr.pseudo]

1 The use of a pseudo-destructor-name after a dot . or arrow ->
  operator represents the destructor for the non-class type denoted by
  type-name or decltype-specifier. The result shall only be used as the
  operand for the function call operator (), and the result of such a
  call has type void. The only effect is the evaluation of the
  postfix-expression before the dot or arrow.

2 The left-hand side of the dot operator shall be of scalar type. The
  left-hand side of the arrow operator shall be of pointer to scalar
  type. This scalar type is the object type. The cv-unqualified versions
  of the object type and of the type designated by the
  pseudo-destructor-name shall be the same type. Furthermore, the two
  type-names in a pseudo-destructor-name of the form

```
nested-name-specifier<sub>opt</sub>type-name :: ~ type-name
```

shall designate the same scalar type (ignoring cv-qualification).

This sort of expression exists in the language deliberately, in order to make the writing of generic code easier. So your destruct is fine without the if.

As an aside, you might be interested to know that the standard library has a function like that. It's std::destroy_at. Other than handling arrays as a special case, it pretty much does what you do already.

Body:
So I've been messing around trying to implement a variant/tagged union class and needed a way to write generic destructors and made what I thought was a silly mistake forgetting that some types don't have destructors, doing something like

template<typename T>
void destruct(T& thing) {
    thing.~T();
}

Yet, this worked fine even with types that didn't have destructors, like int or struct A {int b;};. I still think it's more readable and easier to reason with something that uses something like this

template<typename T>
void destruct(T& thing) {
    if constexpr(std::is_destructible<T>::value) {
        thing.~T();
    }
}

But is there actually any difference between the code? The first one feels pretty undefined behavoiry/just wrong to me.

Body:
You don't need to check. In this context for a type like int it translates to a pseudo-destructor call. The result is a near no-op

[expr.pseudo]

1 The use of a pseudo-destructor-name after a dot . or arrow ->
  operator represents the destructor for the non-class type denoted by
  type-name or decltype-specifier. The result shall only be used as the
  operand for the function call operator (), and the result of such a
  call has type void. The only effect is the evaluation of the
  postfix-expression before the dot or arrow.

2 The left-hand side of the dot operator shall be of scalar type. The
  left-hand side of the arrow operator shall be of pointer to scalar
  type. This scalar type is the object type. The cv-unqualified versions
  of the object type and of the type designated by the
  pseudo-destructor-name shall be the same type. Furthermore, the two
  type-names in a pseudo-destructor-name of the form

nested-name-specifieropttype-name :: ~ type-name

shall designate the same scalar type (ignoring cv-qualification).

This sort of expression exists in the language deliberately, in order to make the writing of generic code easier. So your destruct is fine without the if.

As an aside, you might be interested to know that the standard library has a function like that. It's std::destroy_at. Other than handling arrays as a special case, it pretty much does what you do already.


问:
sum values in 2 JSON objects from 2 files
I am using jq tools to merge 2 json files but there are some duplicate keys, and I would like for the duplicate keys to sum their values.

Here are the files:

file1:

```<code>{
  "total": {
    "seconds": 1490
  },
  "days": {
    "2020-05-20": {
      "seconds": 1400
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}
</code>```

file2:

```<code>{
  "total": {
    "seconds": 295
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 95
    }
  }
}
</code>```

Expected output:

```<code>{
  "total": {
    "seconds": 1785
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 1495
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}
</code>```

I have tried starting with this command, but do not know where to go next:

```<code>jq -s '.[0] * .[1]' file1 file2
</code>```

答:
```<code>jq -s '
    reduce (paths(numbers) as $p | [$p[1:], getpath($p)]) as $i
        ({}; setpath($i[0]; getpath($i[0]) + $i[1]))' file1 file2
</code>```

This only considers leaf nodes which are numbers and produces a merged object with all numbers at similar paths summed up. It works for any number of files.

Online Demo. https://jqplay.org/s/DRkQwRC9Rx

Body:
I am using jq tools to merge 2 json files but there are some duplicate keys, and I would like for the duplicate keys to sum their values.

Here are the files:

file1:

{
  "total": {
    "seconds": 1490
  },
  "days": {
    "2020-05-20": {
      "seconds": 1400
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}

file2:

{
  "total": {
    "seconds": 295
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 95
    }
  }
}

Expected output:

{
  "total": {
    "seconds": 1785
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 1495
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}

I have tried starting with this command, but do not know where to go next:

jq -s '.[0] * .[1]' file1 file2

Body:
jq -s '
    reduce (paths(numbers) as $p | [$p[1:], getpath($p)]) as $i
        ({}; setpath($i[0]; getpath($i[0]) + $i[1]))' file1 file2

This only considers leaf nodes which are numbers and produces a merged object with all numbers at similar paths summed up. It works for any number of files.

Online Demo. https://jqplay.org/s/DRkQwRC9Rx


问:
state changing twice react
good afternoon
I have a component where I select a value.
I control the value of that component with a state and to change that state I pass a function to the component. From the moment I change the state of this component, it changes twice, the state triggers the ID and immediately afterwards the ID becomes zero.</p>

```<code> const [currency, setCurrency] = useState('');

 const handleChange = (event) => {
    setCurrency(event.target.value);
  };

  <TextField
    select
    value={state}
    onChange={handleChange}
    margin="normal"
    helperText="Selection value"
    fullWidth
  >
    {optionsAPI.map((option) => (
      <MenuItem key={option.id} value={option.id}>
          {option.descrition}
      </MenuItem>
    ))}
  </TextField>
</code>```

答:
You passing state which is undefined  as a value to value props.
currency should be passed instead.

```<code><TextField
        select
        value={currency} // not state.
        onChange={handleChange}
        margin="normal"
        helperText="Selection value"
        fullWidth
      >
</code>```

Also, you have to stop event bubbling.

```<code>const handleChange = (event) => {
    event.stopPropagation();
    setCurrency(event.target.value);
  };
</code>```

Title: state changing twice react

Body:
good afternoon
I have a component where I select a value.
I control the value of that component with a state and to change that state I pass a function to the component. From the moment I change the state of this component, it changes twice, the state triggers the ID and immediately afterwards the ID becomes zero.

 const [currency, setCurrency] = useState('');

 const handleChange = (event) => {
    setCurrency(event.target.value);
  };

  <TextField
    select
    value={state}
    onChange={handleChange}
    margin="normal"
    helperText="Selection value"
    fullWidth
  >
    {optionsAPI.map((option) => (
      <MenuItem key={option.id} value={option.id}>
          {option.descrition}
      </MenuItem>
    ))}
  </TextField>

Body:
You passing state which is undefined  as a value to value props.
currency should be passed instead.

<TextField
        select
        value={currency} // not state.
        onChange={handleChange}
        margin="normal"
        helperText="Selection value"
        fullWidth
      >

Also, you have to stop event bubbling.

const handleChange = (event) => {
    event.stopPropagation();
    setCurrency(event.target.value);
  };


问:
vps ssh whenever i close, after time jar stops running

vps ssh whenever i close, after time jar stops running.

I am new for java, i started jar file on a vps server by the command

```<code>$ java -jar MyCode.jar server sample.yml
</code>```

and everything works great, but whenever i close ssh, jar file stops. Not right after i stop ssh,
i don't know how long it stays alive, it varies 10min or more, but it definitely closes.

How can i fix it.

And also where i can see all logs. For example after running this command:

```<code>    $ java -jar MyCode.jar server sample.yml
</code>```

I see logs, but i won't leave my notebook running forever, where i can view those logs saved somewhere.

And also whenever i open ssh, i firstly have to kill running process and run it again

```<code>    $ java -jar MyCode.jar server sample.yml
</code>```

To be able to view the logs, and be sure that everything is fine.
How can i connect again to the running jar process without restarting?

答:
When you run a command like this it runs it in the instance of the user being logged in. If you close the shell, it kills the process that is currently running on the user's account.

There are a couple of ways going around this; I highly recommend using the application screen.

Check to see if the screen is installed on your VPS by running, screen --version. This should output the version that the screen is currently running. If screen is not installed, then it will fail to run. Then you need to install screen using your favorite package manager.

Once you have screen installed, log into your VPS and run the command screen which will open a screen session on your VPS through your user. If you want to name the session that you are starting to run screen -S session_name. You should now be able to run your command without it closing when you exit your VPS.

You can use their keyboard shortcuts to detach from a screen(d), reattach, and list all screens. The prefix for the shortcuts is normally Ctrl+a.

References:
https://linuxize.com/post/how-to-use-linux-screen/

Body:
vps ssh whenever i close, after time jar stops running.

I am new for java, i started jar file on a vps server by the command

$ java -jar MyCode.jar server sample.yml

and everything works great, but whenever i close ssh, jar file stops. Not right after i stop ssh,
i don't know how long it stays alive, it varies 10min or more, but it definitely closes.

How can i fix it.

And also where i can see all logs. For example after running this command:

    $ java -jar MyCode.jar server sample.yml

I see logs, but i won't leave my notebook running forever, where i can view those logs saved somewhere.

And also whenever i open ssh, i firstly have to kill running process and run it again

    $ java -jar MyCode.jar server sample.yml

To be able to view the logs, and be sure that everything is fine.
How can i connect again to the running jar process without restarting?


问:
Laravel 5.3 Migration: 1215 Cannot add foreign key constraint
I'm using Laravel 5.3 and I'm trying to create  FK, however when I migrate my table using artisan I'm getting the following error:

```<code>  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `topic_video` add constraint `topic_video_vendor_id_foreign` foreign key (`vendor_id`) references `vendors` (`id`))

  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
</code>```

I have tried multiple solutions on SOF for different laravel versions but none of them work.

This is my topic_video table (InnoDB)

This is an old and big project, as I don't have migrations for it, only for new tables we have migrations. So I have created a vendors (MyISAM)

```<code>Schema::create('vendors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('channel_url');
            $table->timestamps();
        });
</code>```

Then I have add FK of above migration to topic_video table.

```<code>Schema::table('topic_video', function (Blueprint $table) {
            $table->integer('vendor_id')->unsigned()->nullable();
            $table->foreign('vendor_id')->references('id')->on('vendors');
        });
</code>```

I have tried without unsigned(), without nullable() but still didn't work! Any help would be appreciated!

答:
i think i have found the problem ...

If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.

so you must add 'unique' constraint on

```<code>$table->integer('vendor_id')->unsigned()->nullable()->unique();
</code>```

please see:

https://stackoverflow.com/a/18435114/10573560

https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175464(v=sql.105)?redirectedfrom=MSDN

Body:
I'm using Laravel 5.3 and I'm trying to create  FK, however when I migrate my table using artisan I'm getting the following error:

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `topic_video` add constraint `topic_video_vendor_id_foreign` foreign key (`vendor_id`) references `vendors` (`id`))

  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

I have tried multiple solutions on SOF for different laravel versions but none of them work.

This is my topic_video table (InnoDB)

This is an old and big project, as I don't have migrations for it, only for new tables we have migrations. So I have created a vendors (MyISAM)

Schema::create('vendors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('channel_url');
            $table->timestamps();
        });

Then I have add FK of above migration to topic_video table.

Schema::table('topic_video', function (Blueprint $table) {
            $table->integer('vendor_id')->unsigned()->nullable();
            $table->foreign('vendor_id')->references('id')->on('vendors');
        });

I have tried without unsigned(), without nullable() but still didn't work! Any help would be appreciated!

Body:
i think i have found the problem ...

If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.

so you must add 'unique' constraint on

$table->integer('vendor_id')->unsigned()->nullable()->unique();

please see:

https://stackoverflow.com/a/18435114/10573560

https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175464(v=sql.105)?redirectedfrom=MSDN


问:
Open a PDF, from a URL, with pdfminer.six
Background: Python 3.7 & pdfminer.six

Using the information found here: Exporting Data from PDFs with Python, I have the following code:

```<code>import io

from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage

def extract_text_from_pdf(pdf_path):
    resource_manager = PDFResourceManager()
    fake_file_handle = io.StringIO()
    converter = TextConverter(resource_manager, fake_file_handle)
    page_interpreter = PDFPageInterpreter(resource_manager, converter)

    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh,
                                      caching=True,
                                      check_extractable=True):
            page_interpreter.process_page(page)

        text = fake_file_handle.getvalue()

    # close open handles
    converter.close()
    fake_file_handle.close()

    if text:
        return text

if __name__ == '__main__':
    path = '../_pdfs/mypdf.pdf'
    print(extract_text_from_pdf(path))
</code>```

This works (yay!), but what I really want to do is request the pdf directly, via its url, rather than open a pdf that has been pre-saved to a local drive.

I have no idea how I need to amend the "with open" logic to call from a remote url, nor am I sure which request library I would be best using for the latest version of Python (requests, urllib, urllib2, etc.?)

I'm new to Python, so please bear that in mind (P.s. I have found other questions on this, but nothing I can make work - possibly because they tend to be quite old.)

Any help would be greatly appreciated! Thank you!

答:
You can use PyPDF2 to parse a pdf file.

Try this :

```<code>import requests, PyPDF2
# Fill address with your url
try:
    response = requests.get(address)
except:
    print("Error")
my_raw_data = response.content
with open("my_pdf.pdf", 'wb') as my_data:
    my_data.write(my_raw_data)
my_data.close()
open_pdf_file = open("my_pdf.pdf", 'rb')
try:
    read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
except:
    print("Failed to read, Press Enter to continue :")
if read_pdf.isEncrypted:
    read_pdf.decrypt("")
n = read_pdf.getNumPages()
for x in range(0,n):
    try:
        s = read_pdf.getPage(x).extractText()
    except:
        print("Error in",i)
        continue
    print(s)
</code>```

Body:
Background: Python 3.7 & pdfminer.six

Using the information found here: Exporting Data from PDFs with Python, I have the following code:

import io

from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage

def extract_text_from_pdf(pdf_path):
    resource_manager = PDFResourceManager()
    fake_file_handle = io.StringIO()
    converter = TextConverter(resource_manager, fake_file_handle)
    page_interpreter = PDFPageInterpreter(resource_manager, converter)

    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh,
                                      caching=True,
                                      check_extractable=True):
            page_interpreter.process_page(page)

        text = fake_file_handle.getvalue()

    # close open handles
    converter.close()
    fake_file_handle.close()

    if text:
        return text

if __name__ == '__main__':
    path = '../_pdfs/mypdf.pdf'
    print(extract_text_from_pdf(path))

This works (yay!), but what I really want to do is request the pdf directly, via its url, rather than open a pdf that has been pre-saved to a local drive.

I have no idea how I need to amend the "with open" logic to call from a remote url, nor am I sure which request library I would be best using for the latest version of Python (requests, urllib, urllib2, etc.?)

I'm new to Python, so please bear that in mind (P.s. I have found other questions on this, but nothing I can make work - possibly because they tend to be quite old.)

Any help would be greatly appreciated! Thank you!

Body:
You can use PyPDF2 to parse a pdf file.

Try this :

import requests, PyPDF2
# Fill address with your url
try:
    response = requests.get(address)
except:
    print("Error")
my_raw_data = response.content
with open("my_pdf.pdf", 'wb') as my_data:
    my_data.write(my_raw_data)
my_data.close()
open_pdf_file = open("my_pdf.pdf", 'rb')
try:
    read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
except:
    print("Failed to read, Press Enter to continue :")
if read_pdf.isEncrypted:
    read_pdf.decrypt("")
n = read_pdf.getNumPages()
for x in range(0,n):
    try:
        s = read_pdf.getPage(x).extractText()
    except:
        print("Error in",i)
        continue
    print(s)


问:
How to get the wald test of a specific variable in a multivariate Coxph?
I fitted a multivariate Cox model using the R survival package like follow:

```<code>library(survival)
data(lung)
res.cox1 <- coxph(Surv(time, status) ~  sex + ph.karno + wt.loss, data =  lung)
res.cox1
Call:
coxph(formula = Surv(time, status) ~ sex + ph.karno + wt.loss,
    data = lung)

              coef exp(coef)  se(coef)      z       p
sex      -0.521839  0.593428  0.174454 -2.991 0.00278
ph.karno -0.015243  0.984873  0.005988 -2.546 0.01091
wt.loss  -0.002523  0.997480  0.006233 -0.405 0.68558

Likelihood ratio test=16.42  on 3 df, p=0.0009298
n= 214, number of events= 152
   (14 observations deleted due to missingness)
</code>```

How can one get the 3 values of the Wald test of each variable (sex, ph.karno and wt.loss) in a multivariate Cox model (sex + ph.karno + wt.loss)?

I tried to look at the structure of the coxph and the summary of the coxph object, and I found only one single value of the wald test $wald.test : num 16.5, $ waldtest : Named num [1:3] 1.65e+01 3.00 8.81e-04 ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"!

What does this test value correspond to?
How to get the 3 values of the Wald test of sex, ph.karno and wt.loss ?

```<code>str(res.cox1)
List of 20
 $ coefficients     : Named num [1:3] -0.52184 -0.01524 -0.00252
  ..- attr(*, "names")= chr [1:3] "sex" "ph.karno" "wt.loss"
 $ var              : num [1:3, 1:3] 3.04e-02 -6.78e-05 2.77e-05 -6.78e-05 3.59e-05 ...
 $ loglik           : num [1:2] -680 -672
 $ score            : num 16.9
 $ iter             : int 4
 $ linear.predictors: num [1:214] 0.0756 0.0756 0.0857 -0.039 0.7232 ...
 $ residuals        : Named num [1:214] -0.147 -2.93 0.58 -1.613 -5.599 ...
  ..- attr(*, "names")= chr [1:214] "2" "3" "4" "5" ...
 $ means            : Named num [1:3] 1.4 82.06 9.83
  ..- attr(*, "names")= chr [1:3] "sex" "ph.karno" "wt.loss"
 $ method           : chr "efron"
 $ n                : int 214
 $ nevent           : num 152
 $ terms            :Classes 'terms', 'formula'  language Surv(time, status) ~ sex + ph.karno + wt.loss
  .. ..- attr(*, "variables")= language list(Surv(time, status), sex, ph.karno, wt.loss)
  .. ..- attr(*, "factors")= int [1:4, 1:3] 0 1 0 0 0 0 1 0 0 0 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:4] "Surv(time, status)" "sex" "ph.karno" "wt.loss"
  .. .. .. ..$ : chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..- attr(*, "term.labels")= chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..- attr(*, "specials")=Dotted pair list of 2
  .. .. ..$ strata: NULL
  .. .. ..$ tt    : NULL
  .. ..- attr(*, "order")= int [1:3] 1 1 1
  .. ..- attr(*, "intercept")= num 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
  .. ..- attr(*, "predvars")= language list(Surv(time, status), sex, ph.karno, wt.loss)
  .. ..- attr(*, "dataClasses")= Named chr [1:4] "nmatrix.2" "numeric" "numeric" "numeric"
  .. .. ..- attr(*, "names")= chr [1:4] "Surv(time, status)" "sex" "ph.karno" "wt.loss"
 $ assign           :List of 3
  ..$ sex     : int 1
  ..$ ph.karno: int 2
  ..$ wt.loss : int 3
 $ wald.test        : num 16.5
 $ concordance      : Named num [1:7] 11071 6046 96 22 0 ...
  ..- attr(*, "names")= chr [1:7] "concordant" "discordant" "tied.x" "tied.y" ...
 $ na.action        : 'omit' Named int [1:14] 1 20 36 44 56 63 108 138 178 183 ...
  ..- attr(*, "names")= chr [1:14] "1" "20" "36" "44" ...
 $ y                : 'Surv' num [1:214, 1:2]  455  1010+  210   883  1022+  310   361   218   166   170  ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:214] "2" "3" "4" "5" ...
  .. ..$ : chr [1:2] "time" "status"
  ..- attr(*, "type")= chr "right"
 $ timefix          : logi TRUE
 $ formula          :Class 'formula'  language Surv(time, status) ~ sex + ph.karno + wt.loss
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 $ call             : language coxph(formula = Surv(time, status) ~ sex + ph.karno +      wt.loss, data = lung)
 - attr(*, "class")= chr "coxph"

str(summary(res.cox1))
List of 14
 $ call        : language coxph(formula = Surv(time, status) ~ sex + ph.karno +      wt.loss, data = lung)
 $ fail        : NULL
 $ na.action   : 'omit' Named int [1:14] 1 20 36 44 56 63 108 138 178 183 ...
  ..- attr(*, "names")= chr [1:14] "1" "20" "36" "44" ...
 $ n           : int 214
 $ loglik      : num [1:2] -680 -672
 $ nevent      : num 152
 $ coefficients: num [1:3, 1:5] -0.52184 -0.01524 -0.00252 0.59343 0.98487 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..$ : chr [1:5] "coef" "exp(coef)" "se(coef)" "z" ...
 $ conf.int    : num [1:3, 1:4] 0.593 0.985 0.997 1.685 1.015 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..$ : chr [1:4] "exp(coef)" "exp(-coef)" "lower .95" "upper .95"
 $ logtest     : Named num [1:3] 16.42029 3 0.00093
  ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"
 $ sctest      : Named num [1:3] 1.69e+01 3.00 7.52e-04
  ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"
 $ rsq         : Named num [1:2] 0.0739 0.9983
  ..- attr(*, "names")= chr [1:2] "rsq" "maxrsq"
 $ waldtest    : Named num [1:3] 1.65e+01 3.00 8.81e-04
  ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"
 $ used.robust : logi FALSE
 $ concordance : Named num [1:2] 0.646 0.0274
  ..- attr(*, "names")= chr [1:2] "C" "se(C)"
 - attr(*, "class")= chr "summary.coxph"
</code>```

Thank you!

答:
http://www.sthda.com/english/wiki/cox-proportional-hazards-model

The "z" column is the same as the Wald test statistic for each covariate in the multivariable Cox model.

You can also call the Cox model statistics this way:

summary(res.cox1)

Body:
I fitted a multivariate Cox model using the R survival package like follow:

library(survival)
data(lung)
res.cox1 <- coxph(Surv(time, status) ~  sex + ph.karno + wt.loss, data =  lung)
res.cox1
Call:
coxph(formula = Surv(time, status) ~ sex + ph.karno + wt.loss,
    data = lung)

              coef exp(coef)  se(coef)      z       p
sex      -0.521839  0.593428  0.174454 -2.991 0.00278
ph.karno -0.015243  0.984873  0.005988 -2.546 0.01091
wt.loss  -0.002523  0.997480  0.006233 -0.405 0.68558

Likelihood ratio test=16.42  on 3 df, p=0.0009298
n= 214, number of events= 152
   (14 observations deleted due to missingness)

How can one get the 3 values of the Wald test of each variable (sex, ph.karno and wt.loss) in a multivariate Cox model (sex + ph.karno + wt.loss)?

I tried to look at the structure of the coxph and the summary of the coxph object, and I found only one single value of the wald test $wald.test : num 16.5, $ waldtest : Named num [1:3] 1.65e+01 3.00 8.81e-04 ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"!

What does this test value correspond to?
How to get the 3 values of the Wald test of sex, ph.karno and wt.loss ?

str(res.cox1)
List of 20
 $ coefficients     : Named num [1:3] -0.52184 -0.01524 -0.00252
  ..- attr(*, "names")= chr [1:3] "sex" "ph.karno" "wt.loss"
 $ var              : num [1:3, 1:3] 3.04e-02 -6.78e-05 2.77e-05 -6.78e-05 3.59e-05 ...
 $ loglik           : num [1:2] -680 -672
 $ score            : num 16.9
 $ iter             : int 4
 $ linear.predictors: num [1:214] 0.0756 0.0756 0.0857 -0.039 0.7232 ...
 $ residuals        : Named num [1:214] -0.147 -2.93 0.58 -1.613 -5.599 ...
  ..- attr(*, "names")= chr [1:214] "2" "3" "4" "5" ...
 $ means            : Named num [1:3] 1.4 82.06 9.83
  ..- attr(*, "names")= chr [1:3] "sex" "ph.karno" "wt.loss"
 $ method           : chr "efron"
 $ n                : int 214
 $ nevent           : num 152
 $ terms            :Classes 'terms', 'formula'  language Surv(time, status) ~ sex + ph.karno + wt.loss
  .. ..- attr(*, "variables")= language list(Surv(time, status), sex, ph.karno, wt.loss)
  .. ..- attr(*, "factors")= int [1:4, 1:3] 0 1 0 0 0 0 1 0 0 0 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:4] "Surv(time, status)" "sex" "ph.karno" "wt.loss"
  .. .. .. ..$ : chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..- attr(*, "term.labels")= chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..- attr(*, "specials")=Dotted pair list of 2
  .. .. ..$ strata: NULL
  .. .. ..$ tt    : NULL
  .. ..- attr(*, "order")= int [1:3] 1 1 1
  .. ..- attr(*, "intercept")= num 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
  .. ..- attr(*, "predvars")= language list(Surv(time, status), sex, ph.karno, wt.loss)
  .. ..- attr(*, "dataClasses")= Named chr [1:4] "nmatrix.2" "numeric" "numeric" "numeric"
  .. .. ..- attr(*, "names")= chr [1:4] "Surv(time, status)" "sex" "ph.karno" "wt.loss"
 $ assign           :List of 3
  ..$ sex     : int 1
  ..$ ph.karno: int 2
  ..$ wt.loss : int 3
 $ wald.test        : num 16.5
 $ concordance      : Named num [1:7] 11071 6046 96 22 0 ...
  ..- attr(*, "names")= chr [1:7] "concordant" "discordant" "tied.x" "tied.y" ...
 $ na.action        : 'omit' Named int [1:14] 1 20 36 44 56 63 108 138 178 183 ...
  ..- attr(*, "names")= chr [1:14] "1" "20" "36" "44" ...
 $ y                : 'Surv' num [1:214, 1:2]  455  1010+  210   883  1022+  310   361   218   166   170  ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:214] "2" "3" "4" "5" ...
  .. ..$ : chr [1:2] "time" "status"
  ..- attr(*, "type")= chr "right"
 $ timefix          : logi TRUE
 $ formula          :Class 'formula'  language Surv(time, status) ~ sex + ph.karno + wt.loss
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 $ call             : language coxph(formula = Surv(time, status) ~ sex + ph.karno +      wt.loss, data = lung)
 - attr(*, "class")= chr "coxph"

str(summary(res.cox1))
List of 14
 $ call        : language coxph(formula = Surv(time, status) ~ sex + ph.karno +      wt.loss, data = lung)
 $ fail        : NULL
 $ na.action   : 'omit' Named int [1:14] 1 20 36 44 56 63 108 138 178 183 ...
  ..- attr(*, "names")= chr [1:14] "1" "20" "36" "44" ...
 $ n           : int 214
 $ loglik      : num [1:2] -680 -672
 $ nevent      : num 152
 $ coefficients: num [1:3, 1:5] -0.52184 -0.01524 -0.00252 0.59343 0.98487 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..$ : chr [1:5] "coef" "exp(coef)" "se(coef)" "z" ...
 $ conf.int    : num [1:3, 1:4] 0.593 0.985 0.997 1.685 1.015 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:3] "sex" "ph.karno" "wt.loss"
  .. ..$ : chr [1:4] "exp(coef)" "exp(-coef)" "lower .95" "upper .95"
 $ logtest     : Named num [1:3] 16.42029 3 0.00093
  ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"
 $ sctest      : Named num [1:3] 1.69e+01 3.00 7.52e-04
  ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"
 $ rsq         : Named num [1:2] 0.0739 0.9983
  ..- attr(*, "names")= chr [1:2] "rsq" "maxrsq"
 $ waldtest    : Named num [1:3] 1.65e+01 3.00 8.81e-04
  ..- attr(*, "names")= chr [1:3] "test" "df" "pvalue"
 $ used.robust : logi FALSE
 $ concordance : Named num [1:2] 0.646 0.0274
  ..- attr(*, "names")= chr [1:2] "C" "se(C)"
 - attr(*, "class")= chr "summary.coxph"

Thank you!


问:
XSD specifying a table (all elements) should be filled completely or not at all?
I am looking for a solution within the XML 1.0 constraints to specify in XSD schema that a table should be filled completely or not at all. The table is optional and only needs to be filled when applicable, but if applicable all elements in the table are mandatory. I tried with specifying the table with minOccurrences = "0" and the elements within the table with minOccurrences = "1", but then I always have to provide a value for those elements.

答:
You can set constraints on attributes and elements as well.

Example of restriction on attributes -

```<code><xsd:element name="remove">
<xsd:complexType>
    <xsd:attribute name="ref" use="optional"/>
    <xsd:attribute name="uri" use="optional"/>
    <xsd:assert test="(@ref and not(@uri)) or (not(@ref) and @uri)"/>
</xsd:complexType>
</code>```

Example of restriction on elements -

```<code><xs:complexType name="IfBlockType">
<xs:sequence>
  <xs:element type="IfType" name="If"/>
  <xs:choice maxOccurs="unbounded" minOccurs="0">
    <xs:element type="ElseIfType" name="ElseIf"/>
  </xs:choice>
  <xs:choice maxOccurs="1" minOccurs="0">
    <xs:element type="ElseType" name="Else"/>
  </xs:choice>
</xs:sequence>
</code>```

Body:
You can set constraints on attributes and elements as well.

Example of restriction on attributes -

<xsd:element name="remove">
<xsd:complexType>
    <xsd:attribute name="ref" use="optional"/>
    <xsd:attribute name="uri" use="optional"/>
    <xsd:assert test="(@ref and not(@uri)) or (not(@ref) and @uri)"/>
</xsd:complexType>

Example of restriction on elements -

<xs:complexType name="IfBlockType">
<xs:sequence>
  <xs:element type="IfType" name="If"/>
  <xs:choice maxOccurs="unbounded" minOccurs="0">
    <xs:element type="ElseIfType" name="ElseIf"/>
  </xs:choice>
  <xs:choice maxOccurs="1" minOccurs="0">
    <xs:element type="ElseType" name="Else"/>
  </xs:choice>
</xs:sequence>


问:
ggplot2 - How to sort stackedbars based on categorical and numerical variables
I am trying to create a stacked barplot, using ggplot2, sorting by multiple criteria. Here is the dataframe I am working with -

```<code>my_df<-data.frame('sub_n'=c(rep(1,3),rep(2,3),rep(3,3),rep(4,3),rep(5,3)),'total'=c(1, 3, 3, 2, 1, 2, 1, 3, 3, 1, 3, 1, 3, 1, 3),'choice'=c(rep(c('a','b','c'),5)))
</code>```

What I ultimately wish to have, is a stacked barplot, sorted based on the quantities of 'choice' present. Specifically, I want to create a sideways, stacked plot, with the bars at the top having the highest 'total' values of choice==b, followed by the bars that have the highest 'total' values of choice==c, followed by the bars that have the highest 'total' values of choice==a.

Here is what I have tried to do so far -

```<code>require(dplyr)
require(forcats)
my_df<-my_df %>%
  arrange(choice, desc(total)) %>%
  mutate(choice=fct_reorder(choice,total))
order_1<-unique(my_df$sub_n)
my_df$sub_n<-factor(my_df$sub_n, levels=order_1)
my_df <- my_df[order(my_df$sub_n),]
ggplot(data=my_df, aes(x=sub_n, y=total, fill=choice))+
  geom_bar(position="stack",stat="identity")+
  coord_flip()
</code>```

I am not even sure if I am explaining this correctly, please let me know if there is something else I can include to make it clearer.

答:
This one is surprisingly tricky in my opinion. Here's an approach that uses arrange to order by the conditions and then row_number() to set the rank. Thanks to @akrun in this answer for the inspiration.

We can use pivot_wider to make it easy to order by each of the variables.

Once we've got the ranks set up, we can join back onto the data and re-order the factors with fct_reorder as you did in your attempt.

If you want to re-order the place in the bar the factors are, you can use fct_relevel.

```<code>library(dplyr)
library(tidyr)
library(forcats)
library(ggplot)
my_df %>%
  pivot_wider(names_from = "choice", values_from = "total") %>%
  arrange(desc(b),desc(c),desc(a)) %>%
  mutate(rank = row_number()) %>%
  right_join(my_df,by = "sub_n") %>%
  mutate(sub_n = fct_reorder(as.factor(sub_n), desc(rank)),
         choice = fct_relevel(choice,c("a","c","b"))) %>%
ggplot(aes(x=sub_n, y=total, fill=choice))+
  geom_bar(position="stack",stat="identity")+
  scale_fill_manual(values = c(b = "#00BA38", c = "#619CFF", a = "#F8766D")) +
  coord_flip()
</code>```

Body:
I am trying to create a stacked barplot, using ggplot2, sorting by multiple criteria. Here is the dataframe I am working with -

my_df<-data.frame('sub_n'=c(rep(1,3),rep(2,3),rep(3,3),rep(4,3),rep(5,3)),'total'=c(1, 3, 3, 2, 1, 2, 1, 3, 3, 1, 3, 1, 3, 1, 3),'choice'=c(rep(c('a','b','c'),5)))

What I ultimately wish to have, is a stacked barplot, sorted based on the quantities of 'choice' present. Specifically, I want to create a sideways, stacked plot, with the bars at the top having the highest 'total' values of choice==b, followed by the bars that have the highest 'total' values of choice==c, followed by the bars that have the highest 'total' values of choice==a.

Here is what I have tried to do so far -

require(dplyr)
require(forcats)
my_df<-my_df %>%
  arrange(choice, desc(total)) %>%
  mutate(choice=fct_reorder(choice,total))
order_1<-unique(my_df$sub_n)
my_df$sub_n<-factor(my_df$sub_n, levels=order_1)
my_df <- my_df[order(my_df$sub_n),]
ggplot(data=my_df, aes(x=sub_n, y=total, fill=choice))+
  geom_bar(position="stack",stat="identity")+
  coord_flip()

I am not even sure if I am explaining this correctly, please let me know if there is something else I can include to make it clearer.

Body:
This one is surprisingly tricky in my opinion. Here's an approach that uses arrange to order by the conditions and then row_number() to set the rank. Thanks to @akrun in this answer for the inspiration.

We can use pivot_wider to make it easy to order by each of the variables.

Once we've got the ranks set up, we can join back onto the data and re-order the factors with fct_reorder as you did in your attempt.

If you want to re-order the place in the bar the factors are, you can use fct_relevel.

library(dplyr)
library(tidyr)
library(forcats)
library(ggplot)
my_df %>%
  pivot_wider(names_from = "choice", values_from = "total") %>%
  arrange(desc(b),desc(c),desc(a)) %>%
  mutate(rank = row_number()) %>%
  right_join(my_df,by = "sub_n") %>%
  mutate(sub_n = fct_reorder(as.factor(sub_n), desc(rank)),
         choice = fct_relevel(choice,c("a","c","b"))) %>%
ggplot(aes(x=sub_n, y=total, fill=choice))+
  geom_bar(position="stack",stat="identity")+
  scale_fill_manual(values = c(b = "#00BA38", c = "#619CFF", a = "#F8766D")) +
  coord_flip()


问:
Bcrypt Elastic beanstalk nodejs deploy
I'm trying to deploy my nodejs backend with codeship to elastic beanstalk. But everytime I get the following error: </p>

```<code>bcrypt@1.0.3 install /tmp/deployment/application/node_modules/bcrypt
node-pre-gyp install --fallback-to-build

module.js:471
throw err;
^

Error: Cannot find module '../'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/tmp/deployment/application/node_modules/.bin/node-pre-gyp:15:20)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

npm ERR! Linux 4.9.62-21.56.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/npm" "--production" "rebuild"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! bcrypt@1.0.3 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@1.0.3 install script 'node-pre-gyp install --fallback-to-build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-pre-gyp install --fallback-to-build
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs bcrypt
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls bcrypt
npm ERR! There is likely additional logging output above.
</code>```

<p>Does anyone know how to fix it? been trying to fix it for couple days now, help is much appreciated! </p>

答:
See this GitHub comment: https://github.com/kelektiv/node.bcrypt.js/issues/509#issuecomment-313693838

TL;DR: as a workaround run npm install bcrypt before running npm install

ContentLicense: CC BY-SA 3.0

Title: Bcrypt Elastic beanstalk nodejs deploy

Body:
I'm trying to deploy my nodejs backend with codeship to elastic beanstalk. But everytime I get the following error:

bcrypt@1.0.3 install /tmp/deployment/application/node_modules/bcrypt
node-pre-gyp install --fallback-to-build

module.js:471
throw err;
^

Error: Cannot find module '../'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/tmp/deployment/application/node_modules/.bin/node-pre-gyp:15:20)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

npm ERR! Linux 4.9.62-21.56.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/npm" "--production" "rebuild"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! bcrypt@1.0.3 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@1.0.3 install script 'node-pre-gyp install --fallback-to-build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-pre-gyp install --fallback-to-build
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs bcrypt
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls bcrypt
npm ERR! There is likely additional logging output above.

Does anyone know how to fix it? been trying to fix it for couple days now, help is much appreciated!


问:
How to setup syslog in yocto?
I like to configure syslog. It seems that are more than one way to set up syslog. I am asking for the common way/steps to do that.

I have several use cases. To simplify I like to ask how to configure syslog to write an infinity long log file in /var/log/.

Following steps:

1.) configure what messages

1.1) create own "syslog.conf" (define /var/log/myLog)

1.2) append it to "recipes-core/busybox"

2.) configure how to log

??

I found two possible places to do that:

@meta-poky
-> "meta-poky/recipes-core/busybox/busybox/poky-tiny/defconfig"

```<code>#
# System Logging Utilities
#
CONFIG_SYSLOGD=y
CONFIG_FEATURE_ROTATE_LOGFILE=y
CONFIG_FEATURE_REMOTE_LOG=y
CONFIG_FEATURE_SYSLOGD_DUP=y
CONFIG_FEATURE_SYSLOGD_CFG=y
CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE=256
CONFIG_FEATURE_IPC_SYSLOG=y
CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE=16
CONFIG_LOGREAD=y
CONFIG_FEATURE_LOGREAD_REDUCED_LOCKING=y
CONFIG_KLOGD=y
CONFIG_FEATURE_KLOGD_KLOGCTL=y
CONFIG_LOGGER=y
</code>```

add/change:

```<code>"CONFIG_FEATURE_ROTATE_LOGFILE=n" by adding that line to meta-mylayer/conf/layer.conf"
</code>```

etc.

???

@ "/etc/syslog-startup.conf"

```<code># This configuration file is used by the busybox syslog init script,
# /etc/init.d/syslog[.busybox] to set syslog configuration at start time.

DESTINATION=file        # log destinations (buffer file remote)
LOGFILE=/var/log/messages   # where to log (file)
REMOTE=loghost:514      # where to log (syslog remote)
REDUCE=no           # reduce-size logging
DROPDUPLICATES=no       # whether to drop duplicate log entries
#ROTATESIZE=0           # rotate log if grown beyond X [kByte]
#ROTATEGENS=3           # keep X generations of rotated logs
BUFFERSIZE=64           # size of circular buffer [kByte]
FOREGROUND=no           # run in foreground (don't use!)
#LOGLEVEL=5         # local log level (between 1 and 8)
</code>```

In the systemV init script "/etc/init.d/syslog.bussybox" the file "/etc/syslog-startup.con" is read and used for configuration.

System behaviour:

When running my system, the log wraps when the logfile reaches 200kBytes. One logfile + one log-rotate file is generated.

Any ideas how to archive that syslog writes an infinite long log-file?

I am working on the Yocto krogoth branch + meta-atmel / meta_openembedded (@ krogoth too).

答:
Adding to the Stefan Jaritz comment, you can skip the download step by just issuing

```<code>bitbake busybox -c devshell
</code>```

Then running make menuconfig and getting the new config file from it. Note that this will use Yocto's defconfig by default, so you don't need to do worry about "what's this default config".

Title: How to setup syslog in yocto?

Body:
I like to configure syslog. It seems that are more than one way to set up syslog. I am asking for the common way/steps to do that.

I have several use cases. To simplify I like to ask how to configure syslog to write an infinity long log file in /var/log/.

Following steps:

1.) configure what messages

1.1) create own "syslog.conf" (define /var/log/myLog)

1.2) append it to "recipes-core/busybox"

2.) configure how to log

??

I found two possible places to do that:

@meta-poky
-> "meta-poky/recipes-core/busybox/busybox/poky-tiny/defconfig"

#
# System Logging Utilities
#
CONFIG_SYSLOGD=y
CONFIG_FEATURE_ROTATE_LOGFILE=y
CONFIG_FEATURE_REMOTE_LOG=y
CONFIG_FEATURE_SYSLOGD_DUP=y
CONFIG_FEATURE_SYSLOGD_CFG=y
CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE=256
CONFIG_FEATURE_IPC_SYSLOG=y
CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE=16
CONFIG_LOGREAD=y
CONFIG_FEATURE_LOGREAD_REDUCED_LOCKING=y
CONFIG_KLOGD=y
CONFIG_FEATURE_KLOGD_KLOGCTL=y
CONFIG_LOGGER=y

add/change:

"CONFIG_FEATURE_ROTATE_LOGFILE=n" by adding that line to meta-mylayer/conf/layer.conf"

etc.

???

@ "/etc/syslog-startup.conf"

# This configuration file is used by the busybox syslog init script,
# /etc/init.d/syslog[.busybox] to set syslog configuration at start time.

DESTINATION=file        # log destinations (buffer file remote)
LOGFILE=/var/log/messages   # where to log (file)
REMOTE=loghost:514      # where to log (syslog remote)
REDUCE=no           # reduce-size logging
DROPDUPLICATES=no       # whether to drop duplicate log entries
#ROTATESIZE=0           # rotate log if grown beyond X [kByte]
#ROTATEGENS=3           # keep X generations of rotated logs
BUFFERSIZE=64           # size of circular buffer [kByte]
FOREGROUND=no           # run in foreground (don't use!)
#LOGLEVEL=5         # local log level (between 1 and 8)

In the systemV init script "/etc/init.d/syslog.bussybox" the file "/etc/syslog-startup.con" is read and used for configuration.

System behaviour:

When running my system, the log wraps when the logfile reaches 200kBytes. One logfile + one log-rotate file is generated.

Any ideas how to archive that syslog writes an infinite long log-file?

I am working on the Yocto krogoth branch + meta-atmel / meta_openembedded (@ krogoth too).

Body:
Adding to the Stefan Jaritz comment, you can skip the download step by just issuing

bitbake busybox -c devshell

Then running make menuconfig and getting the new config file from it. Note that this will use Yocto's defconfig by default, so you don't need to do worry about "what's this default config".


问:
5/2 is 2 but I'm getting the one in index 3
I have a linked list 1-2-3-4-5-6. I need to get 4. I have a method that inserts all in the array and calculate the middle. if there are two, I'm printing the second one. in my head the method(I have on my text book) prints 3 but when I actually run it I get 4(as the text book indicates) </p>

```<code>public static void main(String[] args) {
    ListNode x = new ListNode(1);

    ListNode y = new ListNode(2,x);
    ListNode a = new ListNode(3, y);
    ListNode b = new ListNode(4, a);
    ListNode c = new ListNode(5, b);
    ListNode d = new ListNode(6, c);

    ListNode r= middleNode(d);
    System.out.println(r.val);

}
public static ListNode middleNode(ListNode head) {
    ListNode[] A = new ListNode[100];
    int t = 0;
    while (head.next != null) {
        A[t++] = head;
        head = head.next;
    }
    return A[5 / 2];

}
A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
A[4] = 5
A[5] = 6

A[t] =5 t being 5
thus t/2 = 2. so should print 3.
</code>```

答:
Array A actually looks like this at the end (you can print it and check):

```<code>A[0] - 6
A[1] - 5
A[2] - 4
A[3] - 3
A[4] - 2
</code>```

This is because you're passing d to middleNode() which has value 6. So 6 is the first element, then 5, then 4, and so on...

Lastly, in your while loop you're checking while (head.next != null) which is false for node x which has value 1. So value 1 is never inserted into the array (which is fine).

So at the end, your t has value 5, and so t/2 = 2 (because of integer division) and you end up with A[2] = 4

Body:
I have a linked list 1-2-3-4-5-6. I need to get 4. I have a method that inserts all in the array and calculate the middle. if there are two, I'm printing the second one. in my head the method(I have on my text book) prints 3 but when I actually run it I get 4(as the text book indicates)

public static void main(String[] args) {
    ListNode x = new ListNode(1);

    ListNode y = new ListNode(2,x);
    ListNode a = new ListNode(3, y);
    ListNode b = new ListNode(4, a);
    ListNode c = new ListNode(5, b);
    ListNode d = new ListNode(6, c);

    ListNode r= middleNode(d);
    System.out.println(r.val);

}
public static ListNode middleNode(ListNode head) {
    ListNode[] A = new ListNode[100];
    int t = 0;
    while (head.next != null) {
        A[t++] = head;
        head = head.next;
    }
    return A[5 / 2];

}
A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
A[4] = 5
A[5] = 6

A[t] =5 t being 5
thus t/2 = 2. so should print 3.

Body:
Array A actually looks like this at the end (you can print it and check):

A[0] - 6
A[1] - 5
A[2] - 4
A[3] - 3
A[4] - 2

This is because you're passing d to middleNode() which has value 6. So 6 is the first element, then 5, then 4, and so on...

Lastly, in your while loop you're checking while (head.next != null) which is false for node x which has value 1. So value 1 is never inserted into the array (which is fine).

So at the end, your t has value 5, and so t/2 = 2 (because of integer division) and you end up with A[2] = 4


问:
redirect route /login if logged in
I'm trying to make that when entering the page / login and is already logged in, direct the user to another page.

provider/AppServiceProvider.php

```<code>public function boot()
{
    Blade::if('CheckIfLogged', function () {
        return $value > 0;
    });
}
</code>```

middleware/CheckIfLogged.php

```<code><?php

namespace App\Http\Middleware;

use Closure;
use Session;

class CheckIfLogged
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $value = Session::get('user_id');
        if ($value > 0)
        return redirect()->route('inicio');

    }
}
</code>```

kernel.php

```<code>'check' => \Illuminate\Auth\Middleware\CheckIfLogged::class,
</code>```

login.blade.php

```<code>@CheckIfLogged
//content
@endCheckIfLogged
</code>```

But when accessing /login I am returning Error

```<code>Class 'App \ Providers \ Blade' not found
</code>```

答:
you can simply use auth like this

```<code>@if(Auth::user())
 // your code here
@endif
</code>```

and if in controller or anywhere else use it first like this ..

```<code>use Auth;

if(Auth::user())
{
 // your code here
}
</code>```

Title: redirect route /login if logged in

Body:
I'm trying to make that when entering the page / login and is already logged in, direct the user to another page.

provider/AppServiceProvider.php

public function boot()
{
    Blade::if('CheckIfLogged', function () {
        return $value > 0;
    });
}

middleware/CheckIfLogged.php

<?php

namespace App\Http\Middleware;

use Closure;
use Session;

class CheckIfLogged
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $value = Session::get('user_id');
        if ($value > 0)
        return redirect()->route('inicio');

    }
}

kernel.php

'check' => \Illuminate\Auth\Middleware\CheckIfLogged::class,

login.blade.php

@CheckIfLogged
//content
@endCheckIfLogged

But when accessing /login I am returning Error

Class 'App \ Providers \ Blade' not found

Body:
you can simply use auth like this

@if(Auth::user())
 // your code here
@endif

and if in controller or anywhere else use it first like this ..

use Auth;

if(Auth::user())
{
 // your code here
}


问:
Verify method has been called with IEnumerable containing 'x' elements with Moq
I have a repository with an Add method that takes an IEnumerable as parameter:

```<code>public void Add<T>(T item) where T : class, new(){}
</code>```

In a unittest I want to verify that this method is called with an IEnumerable that contains exactly the same amount of elements as another IEnumerable

```<code>[Test]
public void InvoicesAreGeneratedForAllStudents()
{
    var students = StudentStub.GetStudents();
    session.Setup(x => x.All<Student>()).Returns(students.AsQueryable());

    service.GenerateInvoices(Payments.Jaar, DateTime.Now);

    session.Verify(x => x.Add(It.Is<IEnumerable<Invoice>>(
        invoices => invoices.Count() == students.Count())));
 }
</code>```

Result of the unit test:

```<code>Moq.MockException :
Expected invocation on the mock at least once, but was never performed:

x => x.Add<Invoice>(It.Is<IEnumerable`1>(i => i.Count<Invoice>() == 10))

No setups configured.
</code>```

What am I doing wrong?

答:
From your code example you haven't set up the x => x.Add on the Moq

```<code>session.Setup(x => x.Add(It.IsAny<IEnumerable>());
</code>```

Unless the Setup for x.All is meant to be x.Add? If so, you need to match the Verify and Setup exactly - a good way to do that is to extract it to a common method that returns an Expression.

EDIT: Added a sample, I have changed the signature of Add as I can't see how you could pass a collection otherwise.

```<code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        Mock<Boo> moqBoo = new Mock<Boo>();
        moqBoo.Setup(IEnumerableHasExpectedNumberOfElements(10));

        // ACT

        moqBoo.Verify(IEnumerableHasExpectedNumberOfElements(10));
    }

    private static Expression<Action<Boo>> IEnumerableHasExpectedNumberOfElements(int expectedNumberOfElements)
    {
        return b => b.Add(It.Is<IEnumerable<Invoice>>(ie => ie.Count() == expectedNumberOfElements));
    }
}

public class Boo
{
    public void Add<T>(IEnumerable<T> item) where T : class, new()
    {
    }
}

public class Invoice
{

}
</code>```

Also, a good way to debug these things is to set your Mock up with MockBehavior.Strict and then you'll be informed by the invoked code what you need to configure.

Body:
I have a repository with an Add method that takes an IEnumerable as parameter:

public void Add<T>(T item) where T : class, new(){}

In a unittest I want to verify that this method is called with an IEnumerable that contains exactly the same amount of elements as another IEnumerable

[Test]
public void InvoicesAreGeneratedForAllStudents()
{
    var students = StudentStub.GetStudents();
    session.Setup(x => x.All<Student>()).Returns(students.AsQueryable());

    service.GenerateInvoices(Payments.Jaar, DateTime.Now);

    session.Verify(x => x.Add(It.Is<IEnumerable<Invoice>>(
        invoices => invoices.Count() == students.Count())));
 }

Result of the unit test:

Moq.MockException :
Expected invocation on the mock at least once, but was never performed:

x => x.Add<Invoice>(It.Is<IEnumerable`1>(i => i.Count<Invoice>() == 10))

No setups configured.

What am I doing wrong?

Body:
From your code example you haven't set up the x => x.Add on the Moq

session.Setup(x => x.Add(It.IsAny<IEnumerable>());

Unless the Setup for x.All is meant to be x.Add? If so, you need to match the Verify and Setup exactly - a good way to do that is to extract it to a common method that returns an Expression.

EDIT: Added a sample, I have changed the signature of Add as I can't see how you could pass a collection otherwise.

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        Mock<Boo> moqBoo = new Mock<Boo>();
        moqBoo.Setup(IEnumerableHasExpectedNumberOfElements(10));

        // ACT

        moqBoo.Verify(IEnumerableHasExpectedNumberOfElements(10));
    }

    private static Expression<Action<Boo>> IEnumerableHasExpectedNumberOfElements(int expectedNumberOfElements)
    {
        return b => b.Add(It.Is<IEnumerable<Invoice>>(ie => ie.Count() == expectedNumberOfElements));
    }
}

public class Boo
{
    public void Add<T>(IEnumerable<T> item) where T : class, new()
    {
    }
}

public class Invoice
{

}

Also, a good way to debug these things is to set your Mock up with MockBehavior.Strict and then you'll be informed by the invoked code what you need to configure.


问:
Navigation drawer title according to the Drawer item
I have used getSupportActionBar().setTitle("drawer_title"); and the title changes according to drawer item. But when I go back the title does not get updated. for eg: If I'm at dashboard-fragment toolbar-title is dashboard and after that when I go to message-fragment toolbar-title changes to message, but, after when I press back button it goes back to dashboard-fragment but the title does not updated to dashboard it remains message.

How could I update the title again??

答:
In your fragment use requireActivity() to get the activity to the activitiy's SupportActionBar.

So, to set the title in the fragment then use:

```<code>((AppCompatActivity) requireActivity()).getSupportActionBar().setTitle("");
</code>```

Body:
In your fragment use requireActivity() to get the activity to the activitiy's SupportActionBar.

So, to set the title in the fragment then use:

((AppCompatActivity) requireActivity()).getSupportActionBar().setTitle("");


问:
Python :How to iterate over a list that has numbers as it's contents
I am trying to itereate over an integer list. Unfortunately, I am getting an error in this line.

```<code>odd_numbers = []
    for i in  range(1, 21, 2):
        odd_numbers.append(i)
    for odd in len(odd_numbers):
        print(odd_numbers[odd])
</code>```

How do I iterate over these integers using a for loop?

答:
Use range for the second loop. You cannot iterate in int but list of ints:

```<code>odd_numbers = []
for i in  range(1, 21, 2):
    odd_numbers.append(i)
for odd in range(len(odd_numbers)):
    print(odd_numbers[odd])
</code>```

Body:
I am trying to itereate over an integer list. Unfortunately, I am getting an error in this line.

odd_numbers = []
    for i in  range(1, 21, 2):
        odd_numbers.append(i)
    for odd in len(odd_numbers):
        print(odd_numbers[odd])

How do I iterate over these integers using a for loop?

Body:
Use range for the second loop. You cannot iterate in int but list of ints:

odd_numbers = []
for i in  range(1, 21, 2):
    odd_numbers.append(i)
for odd in range(len(odd_numbers)):
    print(odd_numbers[odd])


问:
How do I use arrow functions in React
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

```<code>import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(
      <div>this is my div</div>
    );
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;
</code>```

and the error message i'm getting is:

```<code>./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed
</code>```

any assistance will be highly appreciated

答:
you should give the context this to call your function. Try this snippet

```<code>import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: "" };
  }

  Trial = () => {
    return <div>this is my div</div>;
  };

  render() {
    return (
      <div className="App">
        <p> coucou </p>
        <this.Trial />
      </div>
    );
  }
}

export default App;
</code>```

Title: How do I use arrow functions in React

Body:
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(

this is my div

    );
  }

render(){
  return (

{this.state.apiResponse}

      <Trial />

  );
}
}

export default App;

and the error message i'm getting is:

./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed

any assistance will be highly appreciated

Body:
you should give the context this to call your function. Try this snippet

import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: "" };
  }

  Trial = () => {
    return <div>this is my div</div>;
  };

  render() {
    return (
      <div className="App">
        <p> coucou </p>
        <this.Trial />
      </div>
    );
  }
}

export default App;


问:
WPF can't locate a class even if in the same namespace
I have the following Code behind of a XAML page:

```<code>namespace Paone
{
public partial class Controls : Page
{
    public Controls()
    {
        InitializeComponent();
    }

    public enum Gender
    {
        Male,
        Female
    }

    public class Record
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Uri Website { get; set; }
        public bool IsBillionaire { get; set; }
        public Gender Gender { get; set; }
    }
  }
}
</code>```

And the XAML:

```<code><Page x:Class="Paone.Controls"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:sys="clr-namespace:System;assembly=System.Runtime"
  xmlns:local="clr-namespace:Paone"
  mc:Ignorable="d"
  d:DesignHeight="450" d:DesignWidth="800"
  Title="Controls">
...

 <DataGrid IsReadOnly="True" Grid.Row="1" Grid.Column="2" >
        <DataGrid.Resources>
            <ObjectDataProvider x:Key="genderEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
                <ObjectDataProvider.MethodParameters>
                    <x:Type Type="local:Gender" />
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </DataGrid.Resources>
        <!-- The columns: -->
        <DataGrid.Columns>
            <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
            <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
            <DataGridHyperlinkColumn Header="Website" Binding="{Binding Website}"/>
            <DataGridCheckBoxColumn Header="Billionaire?" Binding="{Binding IsBillionaire}"/>
            <DataGridComboBoxColumn Header="Gender" SelectedItemBinding="{Binding Gender}" ItemsSource="{Binding Source={StaticResource genderEnum}}"/>
        </DataGrid.Columns>
        <!-- The data: -->
        <local:Record FirstName="Adam" LastName="Nathan" Website="http://twitter.com/adamnathan" Gender="Male"/>
        <local:Record FirstName="Bill" LastName="Gates" Website="http://twitter.com/billgates" IsBillionaire="True" Gender="Male"/>
    </DataGrid>
</code>```

As far as I can see, both pieces of code, the code behind page and the XAML deal with the "Paone" namespace.
However in the lines:

```<code><x:Type Type="local:Gender" />
</code>```

As well as:

```<code><local:Record FirstName="Adam" LastName="Nathan" Website="http://twitter.com/adamnathan" Gender="Male"/>
<local:Record FirstName="Bill" LastName="Gates" Website="http://twitter.com/billgates" IsBillionaire="True" Gender="Male"/>
</code>```

The Enum Gender and the class Record are not recognized by the system...

Why is that?

答: The enum is inside the class Controls. Try Controls.Gender</p>

Body:
I have the following Code behind of a XAML page:

namespace Paone
{
public partial class Controls : Page
{
    public Controls()
    {
        InitializeComponent();
    }

    public enum Gender
    {
        Male,
        Female
    }

    public class Record
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Uri Website { get; set; }
        public bool IsBillionaire { get; set; }
        public Gender Gender { get; set; }
    }
  }
}

And the XAML:

<Page x:Class="Paone.Controls"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:sys="clr-namespace:System;assembly=System.Runtime"
  xmlns:local="clr-namespace:Paone"
  mc:Ignorable="d"
  d:DesignHeight="450" d:DesignWidth="800"
  Title="Controls">
...

 <DataGrid IsReadOnly="True" Grid.Row="1" Grid.Column="2" >
        <DataGrid.Resources>
            <ObjectDataProvider x:Key="genderEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
                <ObjectDataProvider.MethodParameters>
                    <x:Type Type="local:Gender" />
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </DataGrid.Resources>

        <DataGrid.Columns>
            <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
            <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
            <DataGridHyperlinkColumn Header="Website" Binding="{Binding Website}"/>
            <DataGridCheckBoxColumn Header="Billionaire?" Binding="{Binding IsBillionaire}"/>
            <DataGridComboBoxColumn Header="Gender" SelectedItemBinding="{Binding Gender}" ItemsSource="{Binding Source={StaticResource genderEnum}}"/>
        </DataGrid.Columns>

        <local:Record FirstName="Adam" LastName="Nathan" Website="http://twitter.com/adamnathan" Gender="Male"/>
        <local:Record FirstName="Bill" LastName="Gates" Website="http://twitter.com/billgates" IsBillionaire="True" Gender="Male"/>
    </DataGrid>

As far as I can see, both pieces of code, the code behind page and the XAML deal with the "Paone" namespace.
However in the lines:

<x:Type Type="local:Gender" />

As well as:

<local:Record FirstName="Adam" LastName="Nathan" Website="http://twitter.com/adamnathan" Gender="Male"/>
<local:Record FirstName="Bill" LastName="Gates" Website="http://twitter.com/billgates" IsBillionaire="True" Gender="Male"/>

The Enum Gender and the class Record are not recognized by the system...

Why is that?


问:
While i am trying to open my react app the CMD showing an npm err! Saying 'npm err! missing script:start' can anyone help me?
enter image description here

I've searched in previous answers and tried to solve this for many hours but with no success. I've typed in the terminal npm create-react-app, moved to the correct cd, and it gives me this error:

'npm ERR! missing script: start'

答:
You should ensure that you have package.json in your project and it has the command start registered in it, example

```<code>"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
</code>```

},

Body:
You should ensure that you have package.json in your project and it has the command start registered in it, example

"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"

},


问:
Asp.Net MVC Form[GET]. Correct action url
I've got search form, which contains checkboxlist which is binded to my model. So when I set GET method to form I got long url:
(I even have exception:

```<code>The length of the query string for this request exceeds the configured maxQueryStringLength value.)
</code>```

it's expecting, [0].IsSelected=false&[0].Id=6&[1].IsSelected=false...

But I would like url like this

www.domain.com/Action/Comma-separated-selected-idx

for example:

www.domain.com/Search/1,6,7

How can I fix,edit form get action? Thanks

答:
I would do a POST instead, then redirect to the URL you desire.

OR

You could capture the form with some JavaScript and build the URL there.

Body:
I've got search form, which contains checkboxlist which is binded to my model. So when I set GET method to form I got long url:
(I even have exception:

The length of the query string for this request exceeds the configured maxQueryStringLength value.)

it's expecting, [0].IsSelected=false&[0].Id=6&[1].IsSelected=false...

But I would like url like this

www.domain.com/Action/Comma-separated-selected-idx

for example:

www.domain.com/Search/1,6,7

How can I fix,edit form get action? Thanks


Title: How is it possible to expand a DATE column in R?

Body:
I have a data frame with several columns, in the first the DATE, in the others the daily temperature of different sites

     DATE         SITE1         SITE2
1    2017-01-01  0.101694912   0.15413890
2    2017-01-02 -0.118305088  -0.06586110
3    2017-01-03 -0.938305088  -0.88586110
4    2017-01-04  1.501694912   1.55413890
5    2017-01-05 -1.238305088  -1.18586110
....

How can I expand the data frame adding a new DATE-HOUR column (by assigning the same temperature value to all the hour of the same day in the different sites)?

    DATE           DATE-HOUR             SITE1         SITE2
1    2017-01-01   2017-01-01-1:00:00    0.101694912   0.15413890
2    2017-01-01   2017-01-01-2:00:00    0.101694912   0.15413890
3    2017-01-01   2017-01-01-3:00:00    0.101694912   0.15413890
....

25   2017-01-02   2017-01-01:00:00     -0.118305088  -0.06586110
26   2017-01-02   2017-01-02:00:00     -0.118305088  -0.06586110
27   2017-01-02   2017-01-03:00:00     -0.118305088  -0.06586110
..

Body:
This is somewhat long-winded but effective and all done within base R:

n <- nrow(df)
df <- df[rep(seq(n), each = 24),]
df$DATETIME <- as.POSIXct(df$DATE) + rep(0:23 * 3600, n)
df <- df[c(1, 4, 2, 3)]
df
#>            DATE            DATETIME      SITE1      SITE2
#> 1    2017-01-01 2017-01-01 00:00:00  0.1016949  0.1541389
#> 1.1  2017-01-01 2017-01-01 01:00:00  0.1016949  0.1541389
#> 1.2  2017-01-01 2017-01-01 02:00:00  0.1016949  0.1541389
#> 1.3  2017-01-01 2017-01-01 03:00:00  0.1016949  0.1541389
#> 1.4  2017-01-01 2017-01-01 04:00:00  0.1016949  0.1541389
#> 1.5  2017-01-01 2017-01-01 05:00:00  0.1016949  0.1541389
#> 1.6  2017-01-01 2017-01-01 06:00:00  0.1016949  0.1541389
#> 1.7  2017-01-01 2017-01-01 07:00:00  0.1016949  0.1541389
#> 1.8  2017-01-01 2017-01-01 08:00:00  0.1016949  0.1541389
#> 1.9  2017-01-01 2017-01-01 09:00:00  0.1016949  0.1541389
#> 1.10 2017-01-01 2017-01-01 10:00:00  0.1016949  0.1541389
#> ...etc


问:
C# array get last item from split in one line
I know that this works to get the first item of an array

```<code>string aString = @"hello/all\this\is/a\test";
string firstItemOfSplit = aString.Split(new char[] {'\\', '/'})[0];
//firstItemOfSplit = hello
</code>```

is there a way to get the last item? Something like

```<code>string aString = @"hello/all\this\is/a\test";
string lastItemOfSplit = aString.Split(new char[] {'\\', '/'})[index.last];
//lastItemOfSplit = test
</code>```

答:
With .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type (Documentation):

```<code>string lastValue = aString.Split(new char[] { '\\', '/' })[^1];
</code>```

Body:
I know that this works to get the first item of an array

string aString = @"hello/all\this\is/a\test";
string firstItemOfSplit = aString.Split(new char[] {'\\', '/'})[0];
//firstItemOfSplit = hello

is there a way to get the last item? Something like

string aString = @"hello/all\this\is/a\test";
string lastItemOfSplit = aString.Split(new char[] {'\\', '/'})[index.last];
//lastItemOfSplit = test

Body:
With .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type (Documentation):

string lastValue = aString.Split(new char[] { '\\', '/' })[^1];


问:
How to create a new instance of a function component in react js?
i am trying to crate 2 image inputs in tow different location on my web app, by using the same component.
for examle:

```<code>function App() {
  return (
    <div className="App">
      <header className="App-header">
    <UploadImage/>
    <UploadImage/>
      </header>
    </div>
  );
}
</code>```

when i upload image in one component id overrides the other and show the image only on the first component.

the Upload Image component:

```<code>import React, { useState } from 'react'

export default function UploadImage(props) {
    const [image, setImage] = useState({ image: { preview: null, raw: null } });

    return (
        <div>
            <label htmlFor="upload-button">
                {image.preview ?
                    <img src={image.preview} style={{ maxWidth: 250, maxHeight: 250 }} alt={"image"} />
                    : <p className="text-center">Add image</p>
                }
            </label>
            <input
                type="file"
                id="upload-button"
                style={{ display: 'none', border: "5px solid red" }}
                onChange={e => setImage({
                    preview: URL.createObjectURL(e.target.files[0]),
                    raw: e.target.files[0]
                })}
                required
            />
        </div>
    )
}
</code>```

答:
You have two inputs with id="upload-button", and two labels with htmlFor="upload-button". To behave as expected, your inputs should have unique ids so they can be reliably associated with the labels. Try passing unique values as props:

```<code>import React from "react";
import UploadImage from "./UploadImage";

export default function App() {
  return (
    <div className="App">
      <header className="App-header">
        <UploadImage inputId="image-upload-1" />
        <UploadImage inputId="image-upload-2" />
      </header>
    </div>
  );
}
</code>```

```<code>import React, { useState } from "react";

export default function UploadImage(props) {
  const [image, setImage] = useState({ image: { preview: null, raw: null } });

  return (
    <div>
      <label htmlFor={props.inputId}>
        {image.preview ? (
          <img
            src={image.preview}
            style={{ maxWidth: 250, maxHeight: 250 }}
            alt={"im"}
          />
        ) : (
          <p className="text-center">Add image</p>
        )}
      </label>
      <input
        type="file"
        id={props.inputId}
        style={{ display: "none", border: "5px solid red" }}
        onChange={e =>
          setImage({
            preview: URL.createObjectURL(e.target.files[0]),
            raw: e.target.files[0]
          })
        }
        required
      />
    </div>
  );
}
</code>```

working sandbox example: https://codesandbox.io/s/modest-christian-lb9d4?file=/src/UploadImage.js

Body:
i am trying to crate 2 image inputs in tow different location on my web app, by using the same component.
for examle:

function App() {
  return (

    <UploadImage/>
    <UploadImage/>

  );
}

when i upload image in one component id overrides the other and show the image only on the first component.

the Upload Image component:

import React, { useState } from 'react'

export default function UploadImage(props) {
    const [image, setImage] = useState({ image: { preview: null, raw: null } });

    return (

                {image.preview ?

                    :
Add image

                }

            <input
                type="file"
                id="upload-button"
                style={{ display: 'none', border: "5px solid red" }}
                onChange={e => setImage({
                    preview: URL.createObjectURL(e.target.files[0]),
                    raw: e.target.files[0]
                })}
                required
            />

    )
}

Body:
You have two inputs with id="upload-button", and two labels with htmlFor="upload-button". To behave as expected, your inputs should have unique ids so they can be reliably associated with the labels. Try passing unique values as props:

import React from "react";
import UploadImage from "./UploadImage";

export default function App() {
  return (
    <div className="App">
      <header className="App-header">
        <UploadImage inputId="image-upload-1" />
        <UploadImage inputId="image-upload-2" />
      </header>
    </div>
  );
}

import React, { useState } from "react";

export default function UploadImage(props) {
  const [image, setImage] = useState({ image: { preview: null, raw: null } });

  return (
    <div>
      <label htmlFor={props.inputId}>
        {image.preview ? (
          <img
            src={image.preview}
            style={{ maxWidth: 250, maxHeight: 250 }}
            alt={"im"}
          />
        ) : (
          <p className="text-center">Add image</p>
        )}
      </label>
      <input
        type="file"
        id={props.inputId}
        style={{ display: "none", border: "5px solid red" }}
        onChange={e =>
          setImage({
            preview: URL.createObjectURL(e.target.files[0]),
            raw: e.target.files[0]
          })
        }
        required
      />
    </div>
  );
}

working sandbox example: https://codesandbox.io/s/modest-christian-lb9d4?file=/src/UploadImage.js