问:
Problems With Play/Pause Toggle
I haven't found any post exactly like mine so here's the problem. I'm making an mp3 player and the play/pause is two separate buttons. Here's my code.

prevButton = document.getElementById("prevbtn");
playButton = document.getElementById("playbtn");
pauseButton = document.getElementById("pausebtn");
nextButton = document.getElementById("nextbtn");

prevButton.addEventListener("click", function() {

});
playButton.addEventListener("click", function() {
  playButton.style.display = "none";
  pauseButton.style.display = "block";
});
pauseButton.addEventListener("click", function() {
  playButton.style.display = "block";
  pauseButton.style.display = "none";
});
nextButton.addEventListener("click", function() {

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bottomToolbar {
  width: 100%; height: 7%;
  background-color: rgb(30, 30, 30);
  text-align: center;
  position: absolute;
  left: 0; bottom: 0;
}

.bottomToolbar button {
  width: 7%; height: 100%;
  background: none;
  background-repeat: no-repeat;
  background-size: auto 75%;
  background-position: center;
  background-color: rgb(150, 150, 150);
  border: none;
  outline: none;
  color: rgb(255, 255, 255);
}

.bottomToolbar .prevButton {
  background-image: url("../icons/PrevIcon64.png");
}
.bottomToolbar .playButton {
  background-image: url("../icons/PlayIcon64.png");
}
.bottomToolbar .pauseButton {
  background-image: url("../icons/PauseIcon64.png");
  display: none;
}
.bottomToolbar .nextButton {
  background-image: url("../icons/NextIcon64.png");
}</code>```

  <button class="prevButton" id="prevbtn">Prev</button>
  <button class="playButton" id="playbtn">Play</button>
  <button class="pauseButton" id="pausebtn">Pause</button>
  <button class="nextButton" id="nextbtn">Next</button>

```

The snippet above does what my Chrome app does. When the play button is clicked it hides all but the prev button. Why does this happen?

答:
Your button(s) aren't disappearing, they're just getting dropped onto the next line after a click because their display type is changing.

When the page loads, the buttons all have a display of "inline-block" because they're button elements which don't have a default display of "block". However, once you've clicked one, you're changing their display type to "block" so the button in the middle is now being instructed to take up an entire row, pushing the previous and next buttons away so it's all wrapping into three lines instead of staying in one line.

To fix it, I've just changed the display type to "inline-block" in your JavaScript instead of "block".

I've also added the "var" keyword before each variables declaration so that they're not global variables getting assigned to the window object, but that's not causing any problems for you here.

Try the snippet below to see it working as intended.

var prevButton = document.getElementById("prevbtn");
var playButton = document.getElementById("playbtn");
var pauseButton = document.getElementById("pausebtn");
var nextButton = document.getElementById("nextbtn");

prevButton.addEventListener("click", function() {

});
playButton.addEventListener("click", function() {
  playButton.style.display = "none";
  pauseButton.style.display = "inline-block";
});
pauseButton.addEventListener("click", function() {
  playButton.style.display = "inline-block";
  pauseButton.style.display = "none";
});
nextButton.addEventListener("click", function() {

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bottomToolbar {
  width: 100%; height: 7%;
  background-color: rgb(30, 30, 30);
  text-align: center;
  position: absolute;
  left: 0; bottom: 0;
}

.bottomToolbar button {
  width: 7%; height: 100%;
  background: none;
  background-repeat: no-repeat;
  background-size: auto 75%;
  background-position: center;
  background-color: rgb(150, 150, 150);
  border: none;
  outline: none;
  color: rgb(255, 255, 255);
}

.bottomToolbar .prevButton {
  background-image: url("../icons/PrevIcon64.png");
}
.bottomToolbar .playButton {
  background-image: url("../icons/PlayIcon64.png");
}
.bottomToolbar .pauseButton {
  background-image: url("../icons/PauseIcon64.png");
  display: none;
}
.bottomToolbar .nextButton {
  background-image: url("../icons/NextIcon64.png");
}</code>```

  <button class="prevButton" id="prevbtn">Prev</button>
  <button class="playButton" id="playbtn">Play</button>
  <button class="pauseButton" id="pausebtn">Pause</button>
  <button class="nextButton" id="nextbtn">Next</button>

```

Title: Problems With Play/Pause Toggle

Body:
I haven't found any post exactly like mine so here's the problem. I'm making an mp3 player and the play/pause is two separate buttons. Here's my code.

prevButton = document.getElementById("prevbtn");
playButton = document.getElementById("playbtn");
pauseButton = document.getElementById("pausebtn");
nextButton = document.getElementById("nextbtn");

prevButton.addEventListener("click", function() {

});
playButton.addEventListener("click", function() {
  playButton.style.display = "none";
  pauseButton.style.display = "block";
});
pauseButton.addEventListener("click", function() {
  playButton.style.display = "block";
  pauseButton.style.display = "none";
});
nextButton.addEventListener("click", function() {

});

.bottomToolbar {
  width: 100%; height: 7%;
  background-color: rgb(30, 30, 30);
  text-align: center;
  position: absolute;
  left: 0; bottom: 0;
}

.bottomToolbar button {
  width: 7%; height: 100%;
  background: none;
  background-repeat: no-repeat;
  background-size: auto 75%;
  background-position: center;
  background-color: rgb(150, 150, 150);
  border: none;
  outline: none;
  color: rgb(255, 255, 255);
}

.bottomToolbar .prevButton {
  background-image: url("../icons/PrevIcon64.png");
}
.bottomToolbar .playButton {
  background-image: url("../icons/PlayIcon64.png");
}
.bottomToolbar .pauseButton {
  background-image: url("../icons/PauseIcon64.png");
  display: none;
}
.bottomToolbar .nextButton {
  background-image: url("../icons/NextIcon64.png");
}

  <button class="prevButton" id="prevbtn">Prev</button>
  <button class="playButton" id="playbtn">Play</button>
  <button class="pauseButton" id="pausebtn">Pause</button>
  <button class="nextButton" id="nextbtn">Next</button>

The snippet above does what my Chrome app does. When the play button is clicked it hides all but the prev button. Why does this happen?

Body:
Your button(s) aren't disappearing, they're just getting dropped onto the next line after a click because their display type is changing.

When the page loads, the buttons all have a display of "inline-block" because they're button elements which don't have a default display of "block". However, once you've clicked one, you're changing their display type to "block" so the button in the middle is now being instructed to take up an entire row, pushing the previous and next buttons away so it's all wrapping into three lines instead of staying in one line.

To fix it, I've just changed the display type to "inline-block" in your JavaScript instead of "block".

I've also added the "var" keyword before each variables declaration so that they're not global variables getting assigned to the window object, but that's not causing any problems for you here.

Try the snippet below to see it working as intended.

var prevButton = document.getElementById("prevbtn");
var playButton = document.getElementById("playbtn");
var pauseButton = document.getElementById("pausebtn");
var nextButton = document.getElementById("nextbtn");

prevButton.addEventListener("click", function() {

});
playButton.addEventListener("click", function() {
  playButton.style.display = "none";
  pauseButton.style.display = "inline-block";
});
pauseButton.addEventListener("click", function() {
  playButton.style.display = "inline-block";
  pauseButton.style.display = "none";
});
nextButton.addEventListener("click", function() {

});

.bottomToolbar {
  width: 100%; height: 7%;
  background-color: rgb(30, 30, 30);
  text-align: center;
  position: absolute;
  left: 0; bottom: 0;
}

.bottomToolbar button {
  width: 7%; height: 100%;
  background: none;
  background-repeat: no-repeat;
  background-size: auto 75%;
  background-position: center;
  background-color: rgb(150, 150, 150);
  border: none;
  outline: none;
  color: rgb(255, 255, 255);
}

.bottomToolbar .prevButton {
  background-image: url("../icons/PrevIcon64.png");
}
.bottomToolbar .playButton {
  background-image: url("../icons/PlayIcon64.png");
}
.bottomToolbar .pauseButton {
  background-image: url("../icons/PauseIcon64.png");
  display: none;
}
.bottomToolbar .nextButton {
  background-image: url("../icons/NextIcon64.png");
}

<div class="bottomToolbar">
  <button class="prevButton" id="prevbtn">Prev</button>
  <button class="playButton" id="playbtn">Play</button>
  <button class="pauseButton" id="pausebtn">Pause</button>
  <button class="nextButton" id="nextbtn">Next</button>
</div>


来源: stackexchange

问:
Validate format of GitHub "Squash and Merge" commit messages
I want to set up a GitHub project to use conventional-changelog standard version to generate its changelog. We use a squash and merge workflow to merge PRs into our main development branch.

Is there a way that I can enforce that the commit message of the squashed commit follows a specific format?

Ideally this would work nicely with the GitHub UI, such as showing as a failing check. I realize I could simply write a browser extension to enforce this, but then everyone working on the project would need to install the extension which is too high of a barrier to entry for an open source project.

答:
It's not clear if you're intending for this to be on GitHub Public or Enterprise.  I haven't tried to implement this on GitHub Public.

On Enterprise the process is to create a pre-receive hook for the specific repo you're interested in protecting.  Keep in mind, unless you're willing to upload a new environment, you'll be limited in the tools that your pre-receive hook can use.

The best details can be found at:
https://help.github.com/enterprise/2.11/admin/guides/developer-workflow/creating-a-pre-receive-hook-script/

Essentially the flow will be looking something like:

```<code>#!/usr/bin/env bash
#
DEFAULT_BRANCH=$(git symbolic-ref HEAD)

while read oldrev newrev refname; do
  # We only care about these changes to master
  if [[ "${refname}" != "${DEFAULT_BRANCH:=refs/heads/master}" ]]; then
    exit 0
  fi

  # branch or tag got deleted
  if [ "${newrev}" = "${zero_commit}" ]; then
    continue
  fi

  # branch or tag is being created
  if [ "${oldrev}" = "${zero_commit}" ]; then
    continue
  fi

  for COMMIT_HASH in `git rev-list ${oldrev}..${newrev}`;
  do
    # Add your COMMIT_HASH scrubbing process here
    # On failure exit 1
  done
done
exit 0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's not clear if you're intending for this to be on GitHub Public or Enterprise.  I haven't tried to implement this on GitHub Public.

On Enterprise the process is to create a pre-receive hook for the specific repo you're interested in protecting.  Keep in mind, unless you're willing to upload a new environment, you'll be limited in the tools that your pre-receive hook can use.

The best details can be found at:
https://help.github.com/enterprise/2.11/admin/guides/developer-workflow/creating-a-pre-receive-hook-script/

Essentially the flow will be looking something like:

#!/usr/bin/env bash
#
DEFAULT_BRANCH=$(git symbolic-ref HEAD)

while read oldrev newrev refname; do
  # We only care about these changes to master
  if [[ "${refname}" != "${DEFAULT_BRANCH:=refs/heads/master}" ]]; then
    exit 0
  fi

  # branch or tag got deleted
  if [ "${newrev}" = "${zero_commit}" ]; then
    continue
  fi

  # branch or tag is being created
  if [ "${oldrev}" = "${zero_commit}" ]; then
    continue
  fi

  for COMMIT_HASH in `git rev-list ${oldrev}..${newrev}`;
  do
    # Add your COMMIT_HASH scrubbing process here
    # On failure exit 1
  done
done
exit 0


问:
Undefined index: uploadimage UPDATE: UPLOADS BUT DOESN'T ADD DIRECTORY TO COLUMN
So i've been trying to make a form with an IMG uploader.
The db is working and i can send the information to the database.
When I tried to implement the image uploader it gives me this print:
So in the form I only added the buttom to upload image, added name and on the post method i tried to upload the image before adding the data.

I did a print, and this is what it came out:
Field 'imgdire' doesn't have a default value

Can someone tell me what's wrong?

PHP

```<code> **if($_SERVER["REQUEST_METHOD"] == "POST"){
  // Validate album

   $UploadedFileName=$_FILES['uploadimage']['name'];
   if($UploadedFileName!='')
   {
   $upload_directory = "uploads/";
   $TargetPath=time().$UploadedFileName;
    if(move_uploaded_file($_FILES['files']['tmp_name'],
  $upload_directory.$TargetPath)){
     $QueryInsertFile="INSERT INTO album SET imgdire='$TargetPath'";

   }
}
</code>```

Send Information to database

```<code>// Check input errors before inserting in database
if(empty($artist_err) && empty($album_err) && empty($stock_err) &&
 empty($price_err) && empty($genre_err)){

    // Prepare an insert statement
    $sql = "INSERT INTO album (nomealbum, stock, price, genero, nomeinter) VALUES (?, ?, ?, ?, ?)";

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "sssss", $param_album, $param_stock, $param_price, $param_genre, $param_artist);

        // Set parameters
        $param_album = $album;
        $param_stock = $stock;
        $param_price = $price;
        $param_genre = $genre;
        $param_artist = $artist;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){

            // Redirect to admin page
            header("location: admin.php");
        } else{
           print mysqli_error($link);
            echo "Algo não correu bem, por favor tente mais uma vez";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}
</code>```

FORM

```<code>  <form method="POST" action="admin.php" enctype="multipart/form-data">

  <div class="form-group <?php echo (!empty($artist_err)) ? 'has-error' :
  ''; ?>">
  <label>Intérprete</label>
  <input  type="text" name="inter" class="form-control" placeholder="Nome do
  Artista" value="<?php echo $artist; ?>">
  <span class="help-block"><?php echo $artist_err; ?></span>
</div>

 <div class="form-group <?php echo (!empty($album_err)) ? 'has-error' : '';
  ?
 >">
  <label>Nome do Albúm:</label>
  <input  type="text" name="aname" class="form-control" placeholder="Album"
  value="<?php echo $album; ?>">
  <span class="help-block"><?php echo $album_err; ?></span>
  </div>

    <div class="form-group <?php echo (!empty($stock_err)) ? 'has-error' :
    ''; ?>">
  <label>Stock</label>
  <input  type="text" name="stocks" class="form-control"  placeholder=""
  value="<?php echo $stock; ?>">
  <span class="help-block"><?php echo $stock_err; ?></span>
</div>

<div class="form-group <?php echo (!empty($price_err)) ? 'has-error' : ''; ?
>">
  <label>Preço</label>
  <input  type="text"  name="prices" class="form-control"  placeholder=""
value="<?php echo $price; ?>">
  <span class="help-block"><?php echo $price_err; ?></span>
</div>

<div class="form-group <?php echo (!empty($genre_err)) ? 'has-error' : ''; ?
>">
  <label>Género</label>
  <input type="text" name="genres"  class="form-control" placeholder=""
 value="<?php echo $genre; ?>">
  <span class="help-block"><?php echo $genre_err; ?></span>
</div>
<div class="form-group">
<input type="file" name="uploadimage">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">

 </div>
 </form>

</div>
</code>```

答:
You are accessing the wrong keys in move uploaded file line
Should be </p>

```<code>if(move_uploaded_file($_FILES['uploadimage']['tmp_name'])){//uploadimage is the key

}
</code>```

Body:
So i've been trying to make a form with an IMG uploader.
The db is working and i can send the information to the database.
When I tried to implement the image uploader it gives me this print:
So in the form I only added the buttom to upload image, added name and on the post method i tried to upload the image before adding the data.

I did a print, and this is what it came out:
Field 'imgdire' doesn't have a default value

Can someone tell me what's wrong?

PHP

 **if($_SERVER["REQUEST_METHOD"] == "POST"){
  // Validate album

   $UploadedFileName=$_FILES['uploadimage']['name'];
   if($UploadedFileName!='')
   {
   $upload_directory = "uploads/";
   $TargetPath=time().$UploadedFileName;
    if(move_uploaded_file($_FILES['files']['tmp_name'],
  $upload_directory.$TargetPath)){
     $QueryInsertFile="INSERT INTO album SET imgdire='$TargetPath'";

   }
}

Send Information to database

// Check input errors before inserting in database
if(empty($artist_err) && empty($album_err) && empty($stock_err) &&
 empty($price_err) && empty($genre_err)){

    // Prepare an insert statement
    $sql = "INSERT INTO album (nomealbum, stock, price, genero, nomeinter) VALUES (?, ?, ?, ?, ?)";

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "sssss", $param_album, $param_stock, $param_price, $param_genre, $param_artist);

        // Set parameters
        $param_album = $album;
        $param_stock = $stock;
        $param_price = $price;
        $param_genre = $genre;
        $param_artist = $artist;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){

            // Redirect to admin page
            header("location: admin.php");
        } else{
           print mysqli_error($link);
            echo "Algo não correu bem, por favor tente mais uma vez";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}

FORM

  <form method="POST" action="admin.php" enctype="multipart/form-data">

  <div class="form-group <?php echo (!empty($artist_err)) ? 'has-error' :
  ''; ?>">
  Intérprete
  <input  type="text" name="inter" class="form-control" placeholder="Nome do
  Artista" value="<?php echo $artist; ?>">
  <?php echo $artist_err; ?>

 <div class="form-group <?php echo (!empty($album_err)) ? 'has-error' : '';
  ?
 >">
  Nome do Albúm:
  <input  type="text" name="aname" class="form-control" placeholder="Album"
  value="<?php echo $album; ?>">
  <?php echo $album_err; ?>

    <div class="form-group <?php echo (!empty($stock_err)) ? 'has-error' :
    ''; ?>">
  Stock
  <input  type="text" name="stocks" class="form-control"  placeholder=""
  value="<?php echo $stock; ?>">
  <?php echo $stock_err; ?>

<div class="form-group <?php echo (!empty($price_err)) ? 'has-error' : ''; ?
>">
  Preço
  <input  type="text"  name="prices" class="form-control"  placeholder=""
value="<?php echo $price; ?>">
  <?php echo $price_err; ?>

<div class="form-group <?php echo (!empty($genre_err)) ? 'has-error' : ''; ?
>">
  Género
  <input type="text" name="genres"  class="form-control" placeholder=""
 value="<?php echo $genre; ?>">
  <?php echo $genre_err; ?>

<input type="file" name="uploadimage">

<input type="submit" class="btn btn-primary" value="Submit">

 </form>

Body:
You are accessing the wrong keys in move uploaded file line
Should be

if(move_uploaded_file($_FILES['uploadimage']['tmp_name'])){//uploadimage is the key

}


问:
Iterating with v-for on dynamic item
I'm trying to iterate through a db object I fetch during created(), I get the values in a console.log but the v-for template part remains empty. My sub-question is : is this good practice ? I'm quite new to Vue and my searches on this issue make me think it's a lifecycle issue.

Thanks for the help.

TEMPLATE PART :

```<code> .content(v-for="(content, key, index) in contents")
   h3 {{key}}
   .line
   | {{getValue(content)}} // this is blank
</code>```

METHODS PART:

```<code>getValue(value) {
  PagesService.fetchDataWrap({
    id: value
  }).then((response) => {
    const test = response.data.values[0].value
    console.log(test) //this is working and gives the right value
    return test
  })
},
getPage() {
  PagesService.fetchPage({
    id: this.$route.params.page
  }).then((response) => {
    this.name = response.data.result.name
    this.langs = response.data.result.langs
    this.project = response.data.result.parent
    this.contents = response.data.result.values
  })
  this.getProject()
}
</code>```

console.log(this.contents) result :

```<code>{__ob__: Observer}
footer: "5a29943b719236225dce6191"
header: "5a29a9f080568b2484b31ee1"
</code>```

which is the values I want to send when v-for iterates on contents so the getValue can process it to fetch corresponding values

答:
I wouldn't recommend attempting to output the value of an asynchronous method. It's highly unlikely that it will work correctly.

Instead, populate your contents array / object fully during the created hook. For example, this can replace the contents hash value with whatever comes back from fetchDataWrap...

getPage () {
  PagesService.fetchPage({
    id: this.$route.params.page
  }).then(response => {
    this.name = response.data.result.name
    this.langs = response.data.result.langs
    this.project = response.data.result.parent

    let contents = response.data.result.values
    Promise.all(Object.keys(contents).map(key => {
      // map each key to a "fetchDataWrap" promise
      return PageService.fetchDataWrap({
        id: contents[key]
      }).then(res => {
        // replace the hash with the resolved value
        contents[key] = res.data.values[0].value
      })
    }).then(() => {
      // all done, assign the data property
      this.contents = contents
    })
  })
}
```
<hr />
<p>Then you can trust that the content has been loaded for rendering</p>
```.content(v-for="(content, key, index) in contents")
  h3 {{key}}
  .line
  | {{content}}
```

Title: Iterating with v-for on dynamic item

Body:
I'm trying to iterate through a db object I fetch during created(), I get the values in a console.log but the v-for template part remains empty. My sub-question is : is this good practice ? I'm quite new to Vue and my searches on this issue make me think it's a lifecycle issue.

Thanks for the help.

TEMPLATE PART :

 .content(v-for="(content, key, index) in contents")
   h3 {{key}}
   .line
   | {{getValue(content)}} // this is blank

METHODS PART:

getValue(value) {
  PagesService.fetchDataWrap({
    id: value
  }).then((response) => {
    const test = response.data.values[0].value
    console.log(test) //this is working and gives the right value
    return test
  })
},
getPage() {
  PagesService.fetchPage({
    id: this.$route.params.page
  }).then((response) => {
    this.name = response.data.result.name
    this.langs = response.data.result.langs
    this.project = response.data.result.parent
    this.contents = response.data.result.values
  })
  this.getProject()
}

console.log(this.contents) result :

{__ob__: Observer}
footer: "5a29943b719236225dce6191"
header: "5a29a9f080568b2484b31ee1"

which is the values I want to send when v-for iterates on contents so the getValue can process it to fetch corresponding values

Body:
I wouldn't recommend attempting to output the value of an asynchronous method. It's highly unlikely that it will work correctly.

Instead, populate your contents array / object fully during the created hook. For example, this can replace the contents hash value with whatever comes back from fetchDataWrap...

getPage () {
  PagesService.fetchPage({
    id: this.$route.params.page
  }).then(response => {
    this.name = response.data.result.name
    this.langs = response.data.result.langs
    this.project = response.data.result.parent

    let contents = response.data.result.values
    Promise.all(Object.keys(contents).map(key => {
      // map each key to a "fetchDataWrap" promise
      return PageService.fetchDataWrap({
        id: contents[key]
      }).then(res => {
        // replace the hash with the resolved value
        contents[key] = res.data.values[0].value
      })
    }).then(() => {
      // all done, assign the data property
      this.contents = contents
    })
  })
}

Then you can trust that the content has been loaded for rendering

.content(v-for="(content, key, index) in contents")
  h3 {{key}}
  .line
  | {{content}}

ContentLicense: CC BY-SA 4.0


问:
IP based redirection on our website
We would like to have a middle east version as well as an international version for our website. The middle east version would be like:

domain.com/me/home

and the international version would be like:

domain.com/home

However, it's not only the home page that we want to redirect. We want a lot more pages on our website to be redirected as well. Why do we need to redirect other pages? Because if a person has a direct URL such as

domain.com/page1

we want them to go to

domain.com/me/page1

The developer that we contacted said that it is easy to redirect the home page, but if we try to do that for many other pages, it would seriously slow down the site. The main reason he mentioned was because each page would have to go through an IP check.

Is there a way to accomplish this without a serious hit on our site speed?

I hope my question was clear enough.

Thank you in advance.

答:
This is not true. You just need to query the geolocation information once per IP address and then stores it in session. In this case, you do not need to query every page for the same visitor.

Below is one example of performing redirection using PHP and MySQL.

https://www.ip2location.com/tutorials/redirect-web-visitors-by-country-using-php-and-mysql-database

You can get the free database from https://lite.ip2location.com

I hope this free solution help your developers.

Title: IP based redirection on our website


问:
Hide navbar when scrolling, but do it so that it's not animated but naturally 'scrolled away'
so hiding the navbar when scrolling simply by adding a class with "top: -50px" for example is easy. However, it doesn't feel very natural. It would be so much nicer, if the navbar would be hiding through actual scrolling, so that the speed of the scrolling always fits. Instead of animating it away, I want to scroll the navbar away and back onscreen (instantly away and after a certain amount of pixels of scrolling up back onscreen again).

How would you approach this?

By the way, I don't really want to use any JQuery for this, I'm using Vue.

答: I hope I didn't get things wrong but if you want the bar to hide when you scroll, why not just position: absolute it and leave the normal scrolling make it disappear ? that might sound trivial but if you want a natural disappearance, that might be it, no ?


问:
Can a Spring Bean class contain static methods?
I hope this isn't too noob of a question, I'm still quite new to Spring. Can a bean class contain static methods? My initial thoughts is no because a static method is global, there's one instance per the entire application and threads to share but a bean might not be defined as such.

I tried searching for this question but couldn't find a clear answer.

答:
Yes,

A spring bean may have static methods too.

Using constructor @Autowired

```<code>@Component
public class Boo {

    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }

    public static int getThree(){
         return 3;
    }
}
</code>```

You may also do it this way:
Using @PostConstruct to hand value over to static field

The idea here is to hand over a bean to a static field after bean is configured by spring.

```<code>@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}
</code>```

source: @Autowired and static method

Body:
Yes,

A spring bean may have static methods too.

Using constructor @Autowired

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }

    public static int getThree(){
         return 3;
    }
}

You may also do it this way:
Using @PostConstruct to hand value over to static field

The idea here is to hand over a bean to a static field after bean is configured by spring.

@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

source: @Autowired and static method


问:
Fade out sankey links if they are not connected to a node onclick

I'd like to be able to fade out all of the links that are not connected to a particular node in a sankey diagram when that node is clicked.

```<code>       var link = svg.append("g").selectAll(".link")
           .data(energy.links)
           .enter().append("path")
           .attr("class", "link")
           .attr("d", path)
           .style("stroke-width", function(d) { return 16; })
           .style("stroke", function(d){return d.color;})
           .sort(function(a, b) { return b.dy - a.dy; });
</code>```

The result should be that all unconnected links fade when a node is clicked.

I am not able to think of the logic required to do this.

答:
Link objects have a source and target node object. If you selectAll links and style their opacity based on if the id you are using nodes matches the clicked node. For example if 'name' is the unique ID, then</p>

```<code>node.on("click", function(d) {
   link.style("opacity", function(l) {
      if (l.source.name == d.name || l.target.name == d.name) {
         return 1
      } else {
         return 0.1
      }
   })
})
</code>```

Body:
I'd like to be able to fade out all of the links that are not connected to a particular node in a sankey diagram when that node is clicked.

       var link = svg.append("g").selectAll(".link")
           .data(energy.links)
           .enter().append("path")
           .attr("class", "link")
           .attr("d", path)
           .style("stroke-width", function(d) { return 16; })
           .style("stroke", function(d){return d.color;})
           .sort(function(a, b) { return b.dy - a.dy; });

The result should be that all unconnected links fade when a node is clicked.

I am not able to think of the logic required to do this.

Body:
Link objects have a source and target node object. If you selectAll links and style their opacity based on if the id you are using nodes matches the clicked node. For example if 'name' is the unique ID, then

node.on("click", function(d) {
   link.style("opacity", function(l) {
      if (l.source.name == d.name || l.target.name == d.name) {
         return 1
      } else {
         return 0.1
      }
   })
})


问:
git clone modifies file type and content in a non-reproducible way
I am experiencing a strange behavior of git clone -- some of the files in a git repository, hosted on bitbucket, are modified right after git clone. This problem looks similar to the one reported in the following questions,

Files showing as modified directly after git clone

Git status shows files as changed even though contents are the same

but does not look quite the same. In my case, only a couple of files out of about two thousands are modified. I detected the modification by git status right after git clone. These modified files were originally text files with ascii encoding, but after cloning they were regarded as a binary file, as the file command showed:

```<code>norio@machine-original $ file -bi t_pot_2e_fft002.f90
text/plain; charset=us-ascii

norio@machine-new $ file -bi t_pot_2e_fft002.f90
application/octet-stream; charset=binary
</code>```

where t_pot_2e_fft002.f90 is a file that was found to be modified.

In these modified files, a few but not all of commas ,, white spaces , and underscores _ were replaced with some non-ASCII characters, but I can still read most part of the file by the less command or emacs.

I repeated cloning 6 times into a different local directories, and I saw the modification 2 times. In the other 4 times, there was no modification. In the 2 cases in which files were modified, the files modified were different from one case to another.

I worked on repositories on machine-original and machine-original2 (to which I do not have access any more) pushing to and fetching from a remote repository on bitbucket. Now I am cloning this repository on bitbucket to machine-new. The version of git is 1.9.1 on machine-original and 2.14.1 on machine-new. (Edit: machine-original runs ubuntu 14.04 and machine-new runs ubuntu 17.10.)

I had core.filemode=true on machine-original until I realize this problem. Then, I changed it to false, but I do not know how to propagate the effect to remote repository -- I did git push, but only got Everything up-to-date.

I do not have the .gitattributes file mentioned in an answer to one of the questions above.

Can anyone explain why these non-reproducible modifications are made upon cloning? Is it safe to keep using a cloned repository if no modification was detected by git status right after git clone?

答:
Since the output hexdump -bc t_pot_2e_fft002.f90 from the separate machines are different, that means the encodings are different. Maybe when the file pushed from a different machine with a kind of encoding, and when you clone the repo to another machine, it will encoding with a different way.

More details about encodings, you can also refer Dealing with inconsistent or corrupt character encodings.

When you set core.filemode as false, you actually didn’t change the file but "ignore the original encoding".  And for your situation, you’d better set core.filemode as false:

core.fileMode

Tells Git if the executable bit of files in the working
tree is to be honored.

Some filesystems lose the executable bit when a file that is marked as
executable is checked out, or checks out a non-executable file with
executable bit on. git-clone1 or git-init1 probe the filesystem to
see if it handles the executable bit correctly and this variable is
automatically set as necessary.

A repository, however, may be on a filesystem that handles the
filemode correctly, and this variable is set to true when created, but
later may be made accessible from another environment that loses the
filemode (e.g. exporting ext4 via CIFS mount, visiting a Cygwin
created repository with Git for Windows or Eclipse). In such a case it
may be necessary to set this variable to false. See
git-update-index1.

The default is true (when core.filemode is not specified in the config
file).

More details, you can refer core.fileMode.

Body:
I am experiencing a strange behavior of git clone -- some of the files in a git repository, hosted on bitbucket, are modified right after git clone. This problem looks similar to the one reported in the following questions,

Files showing as modified directly after git clone

Git status shows files as changed even though contents are the same

but does not look quite the same. In my case, only a couple of files out of about two thousands are modified. I detected the modification by git status right after git clone. These modified files were originally text files with ascii encoding, but after cloning they were regarded as a binary file, as the file command showed:

norio@machine-original $ file -bi t_pot_2e_fft002.f90
text/plain; charset=us-ascii

norio@machine-new $ file -bi t_pot_2e_fft002.f90
application/octet-stream; charset=binary

where t_pot_2e_fft002.f90 is a file that was found to be modified.

In these modified files, a few but not all of commas ,, white spaces , and underscores _ were replaced with some non-ASCII characters, but I can still read most part of the file by the less command or emacs.

I repeated cloning 6 times into a different local directories, and I saw the modification 2 times. In the other 4 times, there was no modification. In the 2 cases in which files were modified, the files modified were different from one case to another.

I worked on repositories on machine-original and machine-original2 (to which I do not have access any more) pushing to and fetching from a remote repository on bitbucket. Now I am cloning this repository on bitbucket to machine-new. The version of git is 1.9.1 on machine-original and 2.14.1 on machine-new. (Edit: machine-original runs ubuntu 14.04 and machine-new runs ubuntu 17.10.)

I had core.filemode=true on machine-original until I realize this problem. Then, I changed it to false, but I do not know how to propagate the effect to remote repository -- I did git push, but only got Everything up-to-date.

I do not have the .gitattributes file mentioned in an answer to one of the questions above.

Can anyone explain why these non-reproducible modifications are made upon cloning? Is it safe to keep using a cloned repository if no modification was detected by git status right after git clone?


问:
Getting Directions From an Annotation on the Map
I am trying to get directions from any annotations that are found on my map. I am using CloudKit as a database to store all my user's information. The annotations use the location index in CloudKit to map out their location on the map. Every time I run my code the annotation comes back as nil, how do I get my code to recognize the location from the annotation and return directions from apple maps?

```<code>@IBAction func getDirections(_ sender: Any) {

    let view = MKPointAnnotation().coordinate

    print("Annotation: \(String(describing: view ))")

    let currentLocMapItem = MKMapItem.forCurrentLocation()

    let selectedPlacemark = MKPlacemark(coordinate: view, addressDictionary: nil)
    let selectedMapItem = MKMapItem(placemark: selectedPlacemark)

    let mapItems = [selectedMapItem, currentLocMapItem]

    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]

    MKMapItem.openMaps(with: mapItems, launchOptions:launchOptions)

}
</code>```

答:
There are two options:

You can use MKDirections to get directions right in your app, without ever going to the Maps app.

You can also pass it off to the Maps app (like your above example) so that the user can then enjoy the full real-time navigation (see traffic, etc.).

But you don’t use the “open in Maps” API to return directions within your app. Use MKDirections for that.

In your code snippet, you are doing:

```<code>let view = MKAnnotationView()
</code>```

That creates an blank annotation view (with no annotation), so obviously if you try to get the annotation for it, it doesn't have one. You presumably want to either

save the original annotation that you added to your map view and use that;

respond to one of the MKMapViewDelegate methods and use the annotation for that annotation view on your map view; or

go back to your original data source from which you originally created the annotation and create a new annotation (not annotation view) from that.

But don't try to create a new, blank annotation view and try to retrieve the annotation view for it, because it won't have one.

Body:
I am trying to get directions from any annotations that are found on my map. I am using CloudKit as a database to store all my user's information. The annotations use the location index in CloudKit to map out their location on the map. Every time I run my code the annotation comes back as nil, how do I get my code to recognize the location from the annotation and return directions from apple maps?

@IBAction func getDirections(_ sender: Any) {

    let view = MKPointAnnotation().coordinate

    print("Annotation: \(String(describing: view ))")

    let currentLocMapItem = MKMapItem.forCurrentLocation()

    let selectedPlacemark = MKPlacemark(coordinate: view, addressDictionary: nil)
    let selectedMapItem = MKMapItem(placemark: selectedPlacemark)

    let mapItems = [selectedMapItem, currentLocMapItem]

    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]

    MKMapItem.openMaps(with: mapItems, launchOptions:launchOptions)

}

Body:
There are two options:

You can use MKDirections to get directions right in your app, without ever going to the Maps app.

You can also pass it off to the Maps app (like your above example) so that the user can then enjoy the full real-time navigation (see traffic, etc.).

But you don’t use the “open in Maps” API to return directions within your app. Use MKDirections for that.

In your code snippet, you are doing:

let view = MKAnnotationView()

That creates an blank annotation view (with no annotation), so obviously if you try to get the annotation for it, it doesn't have one. You presumably want to either

save the original annotation that you added to your map view and use that;

respond to one of the MKMapViewDelegate methods and use the annotation for that annotation view on your map view; or

go back to your original data source from which you originally created the annotation and create a new annotation (not annotation view) from that.

But don't try to create a new, blank annotation view and try to retrieve the annotation view for it, because it won't have one.


问:
Invalid block tag. Did you forget to register or load this tag?
Getting an invalid block tag message Invalid block tag on line 2: 'out'. Did you forget to register or load this tag? but don't know why. Here's my setup:

graphs.html

```<code>{% out %}
</code>```

views.py

```<code>out = 'something to say'
template = loader.get_template('viz_proj/graphs.html')
context = {
    'out' : out
}
return HttpResponse(template.render(context, request))
</code>```

settings.py

```<code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'viz_proj'
]
</code>```

project heirarchy

```<code>viz_proj
|
viz_proj----------------------------------------templates
    |                                              |
    settings.py--views.py--urls.py               graphs.html
</code>```

答:
The solution is {{out}} and not {% out %}. This is because out is a variable.

Reference: https://docs.djangoproject.com/en/1.11/topics/templates/#the-django-template-language

Body:
Getting an invalid block tag message Invalid block tag on line 2: 'out'. Did you forget to register or load this tag? but don't know why. Here's my setup:

graphs.html

{% out %}

views.py

out = 'something to say'
template = loader.get_template('viz_proj/graphs.html')
context = {
    'out' : out
}
return HttpResponse(template.render(context, request))

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'viz_proj'
]

project heirarchy

viz_proj
|
viz_proj----------------------------------------templates
    |                                              |
    settings.py--views.py--urls.py               graphs.html


问:
Formatting Layouts on Xamarin with Visual Studio 2017
I am trying to create a page on my mobile app that shows a list of student accommodations. It is supposed to display the address and then have a button underneath that links to a page which displays more information.
I have tried using LinearLayout and RelativeLayout (see as below)

The code I am using to create this is

```<code>                    LinearLayout newLayout = new LinearLayout(Application.Context);
                TextView displayAddress = new TextView(Application.Context);
                displayAddress.Text = "Address: " + accomodation.address1 + ", " + accomodation.address2 + ", " +
                    accomodation.city + ", " + accomodation.postcode;
                newLayout.AddView(displayAddress);
                Button moreInformation = new Button(Application.Context);
                moreInformation.Text = "More Info";
                moreInformation.SetY(displayAddress.GetY() + 100);
                newLayout.AddView(moreInformation);
                mainLayout.AddView(newLayout);
</code>```

Is there any way I can format either layout so the button sits nicely underneath the text? Thank you.

答:
You could create a .axml layout to implement this function, for example :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <TextView
      android:id="@+id/textView_displayAddress"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Address:  accomodation.address1  accomodation.address2 accomodation.city  accomodation.postcode" />
  <Button
      android:id="@+id/moreInformation"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="moreInfo" />
</LinearLayout>
</code>```

Effect.

Body:
I am trying to create a page on my mobile app that shows a list of student accommodations. It is supposed to display the address and then have a button underneath that links to a page which displays more information.
I have tried using LinearLayout and RelativeLayout (see as below)

The code I am using to create this is

                    LinearLayout newLayout = new LinearLayout(Application.Context);
                TextView displayAddress = new TextView(Application.Context);
                displayAddress.Text = "Address: " + accomodation.address1 + ", " + accomodation.address2 + ", " +
                    accomodation.city + ", " + accomodation.postcode;
                newLayout.AddView(displayAddress);
                Button moreInformation = new Button(Application.Context);
                moreInformation.Text = "More Info";
                moreInformation.SetY(displayAddress.GetY() + 100);
                newLayout.AddView(moreInformation);
                mainLayout.AddView(newLayout);

Is there any way I can format either layout so the button sits nicely underneath the text? Thank you.

Body:
You could create a .axml layout to implement this function, for example :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <TextView
      android:id="@+id/textView_displayAddress"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Address:  accomodation.address1  accomodation.address2 accomodation.city  accomodation.postcode" />
  <Button
      android:id="@+id/moreInformation"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="moreInfo" />
</LinearLayout>

Effect.


问:
Azure Storage explorer download failed with success message?
I'm trying to download a file from azure storage explorer from azure blob container. But the download is getting failed with success msg with below error.

{

"name": "Error",

"message": "self signed certificate in certificate chain",

"stack": "Error: self signed certificate in certificate chain\n    at TLSSocket. (_tls_wrap.js:1088:38)\n    at emitNone (events.js:86:13)\n    at TLSSocket.emit (events.js:188:7)\n    at TLSSocket._finishInit (_tls_wrap.js:610:8)\n    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:440:38)",

"code": "SELF_SIGNED_CERT_IN_CHAIN"

}

Can someone shed some light on this issue please ?

Thx,
Arun

答:
self signed certificate in certificate chain

SELF_SIGNED_CERT_IN_CHAIN it indicates that Azure no longer know whether the received HTTPS message is tampered. You also could get the answer from Azure Storage Explorer troubleshooting guide.

Root Cause :

Error: Self-Signed Certificate in Certificate Chain

There are several reasons why you may encounter this error, and the most common two reasons are as follows:

The app is connected through a “transparent proxy”, which means a server (such as your company server) is intercepting HTTPS traffic, decrypting it, and then encrypting it using a self-signed certificate.

You are running an application, such as antivirus software, which is injecting a self-signed SSL certificate into the HTTPS messages that you receive.

Solution:

You can let Storage Explorer trust it.

When Storage Explorer encounters one of the issues, it can no longer know whether the received HTTPS message is tampered. If you have a copy of the self-signed certificate, you can let Storage Explorer trust it. If you are unsure of who is injecting the certificate, follow these steps to find it:

Install Open SSL

Windows (any of the light versions should be sufficient)

Mac and Linux: should be included with your operating system

Run Open SSL

Windows: open the installation directory, click /bin/, and then double-click openssl.exe.

Mac and Linux: run openssl from a terminal.

Execute s_client -showcerts -connect microsoft.com:443

Look for self-signed certificates. If you are unsure which are self-signed, look for anywhere the subject ("s:") and issuer ("i:") are the same.

When you have found any self-signed certificates, for each one, copy and paste everything from and including -----BEGIN CERTIFICATE----- to -----END CERTIFICATE----- to a new .cer file.
  Open Storage Explorer, click Edit > SSL Certificates > Import Certificates, and then use the file picker to find, select, and open the .cer files that you created.

If you cannot find any self-signed certificates using the above steps, contact Azure team through the feedback tool for more help


问:
Change React State through Event Handlers
Here my question is:

How can I change the state of my default set object using multiple select ?

Here let's say, I have states checkDevice and checkCountry, so in the below fiddle I did set all values to false.

I want to set the values of only those properties to true which are selected in the multi select dropdown.

For example: In multi select, if I just select US and UK then in my state is there a way to get something like:

```<code>checkCountry:
     {
        'US': true,
        'UK': true,
        'JP': false
      }
</code>```

class Box extends React.Component {

  constructor() {
    super();
    this.state = {
      checkDevice: {
        'iPhone 4': false,
        'iPhone 5': false,
        'iPhone 6': false,
        'iPhone 7': false,
        'iPhone 8': false,
        'iPhone X': false,
      },
      checkCountry: {
        'US': false,
        'UK': false,
        'JP': false
      }
    }
  }

  componentDidMount() {
    $(document).ready(function() {
      $('#country').material_select();
    });
    $(document).ready(function() {
      $('#device').material_select();
    });
  }

  render() {
    return (

        <form className="row">

              <select value="" multiple id="country">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">US</option>
                <option value="2">UK</option>
                <option value="3">JP</option>
              </select>
              Country

              <select value="" multiple id="device">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">iPhone 4</option>
                <option value="2">iPhone 5</option>
                <option value="3">iPhone 6</option>
                <option value="4">iPhone 7</option>
                <option value="5">iPhone 8</option>
                <option value="6">iPhone X</option>
              </select>
              Devices

        </form>

          ```{JSON.stringify(this.state.checkCountry,null,2)}```

          ```{JSON.stringify(this.state.checkDevice,null,2)}```

    );
  };
}

ReactDOM.render( < Box / > , document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
<div id='root'></div></code>```

CODEPEN, this will give you more freedom to play with.

UPDATE:

Here in the official documentation of React, we can see how to change the complete state, but is there a way to change just the property of the existing value

For Example::

```<code>handleChange(event){
    this.setState({checkCountry["event.target.value"] === true ? false: true});
}
</code>```

But I don't think, I can get in this way. But I'm trying something like this.

Ans to questions that might help:
Updating an object with setstate in react

答:
You must call a event handler from a onChange event to do that.

If you weren't using a fancy jQuery plugin, you could just:

handleChange(event) {
  this.setState({name: event.target.value})
}

render(){

  return <input onChange={event => this.handleChange(event)}
}```
</div>
</div>
</p>

<p>But as you are using this jQuery plugin which mutates the DOM without React knowledge, you should look into the plugin API and call this event handler within the jQuery Plugin event handler.</p>

<p>Lets assume material_select has a onChange option. You should call your component event handler within the material_select event handler.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>handleChange(event) {
      this.setState({name: event.target.value})
    }

    render(){

      return "Your current markup here"
    }

  componentDidMount() {
    $(document).ready(function() {
      $('#country').material_select({
        onChange: (event) => this.onChange(event)
      });
    });

  }</code>```

If you manage to do that, changing the state is just a matter of array mapping, or diffing it with a library like lodash.

By the way, you shouldn't be using jQuery with React. You should look for a React wrapper/alternative to the jQuery plugin you intend to use. This library would expose its API by props, ensuring that you could program it in the React way.

Body:
Here my question is:

How can I change the state of my default set object using multiple select ?

Here let's say, I have states checkDevice and checkCountry, so in the below fiddle I did set all values to false.

I want to set the values of only those properties to true which are selected in the multi select dropdown.

For example: In multi select, if I just select US and UK then in my state is there a way to get something like:

checkCountry:
     {
        'US': true,
        'UK': true,
        'JP': false
      }

class Box extends React.Component {

  constructor() {
    super();
    this.state = {
      checkDevice: {
        'iPhone 4': false,
        'iPhone 5': false,
        'iPhone 6': false,
        'iPhone 7': false,
        'iPhone 8': false,
        'iPhone X': false,
      },
      checkCountry: {
        'US': false,
        'UK': false,
        'JP': false
      }
    }
  }

  componentDidMount() {
    $(document).ready(function() {
      $('#country').material_select();
    });
    $(document).ready(function() {
      $('#device').material_select();
    });
  }

  render() {
    return (

        <form className="row">

              <select value="" multiple id="country">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">US</option>
                <option value="2">UK</option>
                <option value="3">JP</option>
              </select>
              Country

              <select value="" multiple id="device">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">iPhone 4</option>
                <option value="2">iPhone 5</option>
                <option value="3">iPhone 6</option>
                <option value="4">iPhone 7</option>
                <option value="5">iPhone 8</option>
                <option value="6">iPhone X</option>
              </select>
              Devices

        </form>

{JSON.stringify(this.state.checkCountry,null,2)}

{JSON.stringify(this.state.checkDevice,null,2)}

    );
  };
}

ReactDOM.render( < Box / > , document.getElementById('root'));

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css" rel="stylesheet" />

CODEPEN, this will give you more freedom to play with.

UPDATE:

Here in the official documentation of React, we can see how to change the complete state, but is there a way to change just the property of the existing value

For Example::

handleChange(event){
    this.setState({checkCountry["event.target.value"] === true ? false: true});
}

But I don't think, I can get in this way. But I'm trying something like this.

Ans to questions that might help:
Updating an object with setstate in react

Body:
You must call a event handler from a onChange event to do that.

If you weren't using a fancy jQuery plugin, you could just:

handleChange(event) {
  this.setState({name: event.target.value})
}

render(){

  return <input onChange={event => this.handleChange(event)}
}

But as you are using this jQuery plugin which mutates the DOM without React knowledge, you should look into the plugin API and call this event handler within the jQuery Plugin event handler.

Lets assume material_select has a onChange option. You should call your component event handler within the material_select event handler.

handleChange(event) {
      this.setState({name: event.target.value})
    }

    render(){

      return "Your current markup here"
    }

  componentDidMount() {
    $(document).ready(function() {
      $('#country').material_select({
        onChange: (event) => this.onChange(event)
      });
    });

  }

If you manage to do that, changing the state is just a matter of array mapping, or diffing it with a library like lodash.

By the way, you shouldn't be using jQuery with React. You should look for a React wrapper/alternative to the jQuery plugin you intend to use. This library would expose its API by props, ensuring that you could program it in the React way.


问:
Suddenly I can't load some newly upgraded modules in Python
I suddenly can't load newly upgraded modules modules, e.g scikit-learn, zope, but I can find other packages. Even though the path links from the import points to the correct anaconda folder, which contains all the code. Any ideas what might be wrong and how to fix it?

```<code>Python 2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
>>> import sklearn
>>> from os import listdir
>>> print(dir(sklearn))
['_ASSUME_FINITE', '__SKLEARN_SETUP__', '__all__', '__builtins__', '__check_build', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_contextmanager', 'base', 'clone', 'config_context', 'exceptions', 'externals', 'get_config', 'logger', 'logging', 'os', 're', 'set_config', 'setup_module', 'sys', 'utils', 'warnings']
>>> print(listdir(sklearn.__path__[0]))
['exceptions.py', 'cross_validation.pyc', 'lda.py', 'naive_bayes.pyc', 'isotonic.py', '_build_utils', 'neighbors', 'cluster', 'naive_bayes.py', '__init__.pyc', 'multiclass.py', 'dummy.pyc', 'grid_search.pyc', 'tests', '__init__.py', 'calibration.py', '_isotonic.so', 'neural_network', 'datasets', 'preprocessing', '__check_build', 'random_projection.py', 'multiclass.pyc', 'model_selection', 'calibration.pyc', 'pipeline.pyc', 'qda.py', 'learning_curve.py', 'ensemble', 'tree', 'isotonic.pyc', 'kernel_ridge.py', 'gaussian_process', 'decomposition', 'base.pyc', 'dummy.py', 'utils', 'pipeline.py', 'cross_decomposition', 'covariance', 'qda.pyc', 'multioutput.pyc', 'lda.pyc', 'feature_selection', 'linear_model', 'metrics', 'kernel_ridge.pyc', 'setup.py', 'semi_supervised', 'exceptions.pyc', 'multioutput.py', 'cross_validation.py', 'discriminant_analysis.py', 'kernel_approximation.pyc', 'base.py', 'random_projection.pyc', 'setup.pyc', 'kernel_approximation.py', 'grid_search.py', 'discriminant_analysis.pyc', 'mixture', 'manifold', 'externals', 'svm', 'feature_extraction', 'learning_curve.pyc']
>>> import zope
>>> print(dir(zope))
['__doc__', '__name__', '__path__']
>>> print(listdir(zope.__path__[0]))
['interface']
>>> zope.interface
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'interface'
>>> sklearn.lda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'lda'
</code>```

答:
The Attribute error that you are presenting is the expected behaviour of Python3. Did you upgrade from Python 2 to Python 3 Because there are many differences between both version families... read more about this here:
https://docs.python.org/3/howto/pyporting.html

To load the sklearn.lda module you have to explicitly import the part of the module that you need.

from sklearn import lda

or

import sklearn.lda

I hope this answers your question!

Body:
I suddenly can't load newly upgraded modules modules, e.g scikit-learn, zope, but I can find other packages. Even though the path links from the import points to the correct anaconda folder, which contains all the code. Any ideas what might be wrong and how to fix it?

Python 2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
>>> import sklearn
>>> from os import listdir
>>> print(dir(sklearn))
['_ASSUME_FINITE', '__SKLEARN_SETUP__', '__all__', '__builtins__', '__check_build', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_contextmanager', 'base', 'clone', 'config_context', 'exceptions', 'externals', 'get_config', 'logger', 'logging', 'os', 're', 'set_config', 'setup_module', 'sys', 'utils', 'warnings']
>>> print(listdir(sklearn.__path__[0]))
['exceptions.py', 'cross_validation.pyc', 'lda.py', 'naive_bayes.pyc', 'isotonic.py', '_build_utils', 'neighbors', 'cluster', 'naive_bayes.py', '__init__.pyc', 'multiclass.py', 'dummy.pyc', 'grid_search.pyc', 'tests', '__init__.py', 'calibration.py', '_isotonic.so', 'neural_network', 'datasets', 'preprocessing', '__check_build', 'random_projection.py', 'multiclass.pyc', 'model_selection', 'calibration.pyc', 'pipeline.pyc', 'qda.py', 'learning_curve.py', 'ensemble', 'tree', 'isotonic.pyc', 'kernel_ridge.py', 'gaussian_process', 'decomposition', 'base.pyc', 'dummy.py', 'utils', 'pipeline.py', 'cross_decomposition', 'covariance', 'qda.pyc', 'multioutput.pyc', 'lda.pyc', 'feature_selection', 'linear_model', 'metrics', 'kernel_ridge.pyc', 'setup.py', 'semi_supervised', 'exceptions.pyc', 'multioutput.py', 'cross_validation.py', 'discriminant_analysis.py', 'kernel_approximation.pyc', 'base.py', 'random_projection.pyc', 'setup.pyc', 'kernel_approximation.py', 'grid_search.py', 'discriminant_analysis.pyc', 'mixture', 'manifold', 'externals', 'svm', 'feature_extraction', 'learning_curve.pyc']
>>> import zope
>>> print(dir(zope))
['__doc__', '__name__', '__path__']
>>> print(listdir(zope.__path__[0]))
['interface']
>>> zope.interface
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'interface'
>>> sklearn.lda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'lda'


问:
Proxy authentication with Twilio voice api in C#
I want make outbound calls from my console application using C# With Twilio voice api. But most of the time i am getting the connection error message. My system is using the proxy server. So i want to add proxy authentication with the code. Please suggest.

My code is as below :

```<code>const string accountSid = "*****************";
const string authToken = "*****************";
var client = new TwilioRestClient(accountSid, authToken); TwilioClient.Init(accountSid, authToken);
var to = new PhoneNumber("*****************");
var from = new PhoneNumber("*****************"); `enter code here`
var call = CallResource.Create(to, from, url: new Uri(tempURL));</code>```

答:
Twilio Evangelist here.

If you're trying to use the proxy here, I think using our Rest API is going to be helpful. Try this code below to hook your proxy server up to the HttpClient object:

```<code>public static HttpClient GetProxy()
{
    // First create a proxy object
    var proxyUri = $"{proxyServerSettings.Address}:{proxyServerSettings.Port}";

    var proxyCreds = new NetworkCredential("proxyuser", "proxypassword");

    var proxy = new WebProxy(proxyUri, false)
    {
        UseDefaultCredentials = false,
        Credentials = proxyCreds,
    };

    // Now create a client handler which uses that proxy
    var httpClientHandler = new HttpClientHandler()
    {
        Proxy = proxy,
        PreAuthenticate = true,
        UseDefaultCredentials = false,
    };

    return new HttpClient(httpClientHandler);
}
</code>```

To make the telephone call with the proxy, you can use the sample code here:

```<code>const string accountSid = "*****************";
const string authToken = "*****************";
string to = "+1xxxxxxxxxx";
string from = "+1xxxxxxxxxx";
string callUrl = $"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Calls";
var httpClient = GetProxy();
var authorizationValue = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{accountSid}:{authToken}"));
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {authorizationValue}");
var result= httpClient.PostAsync(callUrl, new FormUrlEncodedContent(new Dictionary<string,string>
 {
     {"To", to},
     {"From", from},
     {"Url", "http://demo.twilio.com/docs/voice.xml"}
 }));
</code>```

Let me know if this helps or if you run into additional problems. Happy to help here

Body:
I want make outbound calls from my console application using C# With Twilio voice api. But most of the time i am getting the connection error message. My system is using the proxy server. So i want to add proxy authentication with the code. Please suggest.

My code is as below :

const string accountSid = "*****************";
const string authToken = "*****************";
var client = new TwilioRestClient(accountSid, authToken); TwilioClient.Init(accountSid, authToken);
var to = new PhoneNumber("*****************");
var from = new PhoneNumber("*****************"); `enter code here`
var call = CallResource.Create(to, from, url: new Uri(tempURL));

Body:
Twilio Evangelist here.

If you're trying to use the proxy here, I think using our Rest API is going to be helpful. Try this code below to hook your proxy server up to the HttpClient object:

public static HttpClient GetProxy()
{
    // First create a proxy object
    var proxyUri = $"{proxyServerSettings.Address}:{proxyServerSettings.Port}";

    var proxyCreds = new NetworkCredential("proxyuser", "proxypassword");

    var proxy = new WebProxy(proxyUri, false)
    {
        UseDefaultCredentials = false,
        Credentials = proxyCreds,
    };

    // Now create a client handler which uses that proxy
    var httpClientHandler = new HttpClientHandler()
    {
        Proxy = proxy,
        PreAuthenticate = true,
        UseDefaultCredentials = false,
    };

    return new HttpClient(httpClientHandler);
}

To make the telephone call with the proxy, you can use the sample code here:

const string accountSid = "*****************";
const string authToken = "*****************";
string to = "+1xxxxxxxxxx";
string from = "+1xxxxxxxxxx";
string callUrl = $"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Calls";
var httpClient = GetProxy();
var authorizationValue = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{accountSid}:{authToken}"));
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {authorizationValue}");
var result= httpClient.PostAsync(callUrl, new FormUrlEncodedContent(new Dictionary<string,string>
 {
     {"To", to},
     {"From", from},
     {"Url", "http://demo.twilio.com/docs/voice.xml"}
 }));

Let me know if this helps or if you run into additional problems. Happy to help here


问:
Why is my Uninstall method not called from the msi?
I am writing an installer for my web app and I struggle with the uninstaller part. Despite the fact that I created a custom action on Uninstall in my Application Setup Project, the InstallerClass is set to true, the method:

```<code>public override void Uninstall(IDictionary savedState)
    {
        //MessageBox.Show("Attach debugger!", "Viper.Setup");
        Cleanup();
        base.Uninstall(savedState);
    }
</code>```

on the installer class doesn't seem to be called. Any ideas what could be the reason?

EDIT: I also noticed that it not only doesn't run the Installer, but also doesn't delete my main dll file. To make it worse, when I install a new version after uninstalling the previous one, this dll is still the old one (even though installation and uninstallation were successful)

答: I solved this by setting the 'InstallerClass' property of my custom action to False.</p>

OwnerDisplayName: Grzenio

ContentLicense: CC BY-SA 2.5

Body:
I am writing an installer for my web app and I struggle with the uninstaller part. Despite the fact that I created a custom action on Uninstall in my Application Setup Project, the InstallerClass is set to true, the method:

public override void Uninstall(IDictionary savedState)
    {
        //MessageBox.Show("Attach debugger!", "Viper.Setup");
        Cleanup();
        base.Uninstall(savedState);
    }

on the installer class doesn't seem to be called. Any ideas what could be the reason?

EDIT: I also noticed that it not only doesn't run the Installer, but also doesn't delete my main dll file. To make it worse, when I install a new version after uninstalling the previous one, this dll is still the old one (even though installation and uninstallation were successful)

LastEditorDisplayName: Grzenio


问:
Javascript/CSS - animation duration in pixel per second
How can i set the duration of an transition/animation to pixel per second?

You see the two different wrappers, with a different total height depending on it's colored content. The total speed is the same, given from the css transition attribute, thats okay if you want several animations with the same duration. For a smoother look i want to set this transition/animation effect to pixel per second so it takes as long as many pixels there. More content = more pixel = longer animation.

How can i achieve this with vanilla javascript or even css?

var wrapper1 = document.getElementById('wrapper1');
var wrapper2 = document.getElementById('wrapper2');
var header1 = document.getElementById('header1');
var header2 = document.getElementById('header2');
var wrapper1CmputedHeight = wrapper1.scrollHeight;
var wrapper2CmputedHeight = wrapper2.scrollHeight;

header1.addEventListener('click', function() {
  if (wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
  } else {
    wrapper1.style.height = '60px';
  }
})

header2.addEventListener('click', function() {
  if (wrapper2.style.height === '60px') {
    wrapper2.style.height = wrapper2CmputedHeight + 'px';
  } else {
    wrapper2.style.height = '60px';
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper1,
#wrapper2 {
  background: #fff;
  border: 1px solid grey;
  overflow: hidden;
  transition: height .2s linear
}

#wrapper1 {
  margin-bottom: 40px
}

#header1,
#header2 {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer
}

#content1 {
  height: 20px;
  background: blue
}

#content2 {
  height: 600px;
  background: green
}</code>```

    header

    header

```

答:
I found this example here but it seems to do the trick for you (after some tweaking). In this case it implements a quartic interpolation, however you could adjust this algorithm to linear / other if so desired.

//
// Animate
//
var btn1 = document.querySelector('.animate');
btn1.addEventListener('click', function() {
  reset();
  animate();
  btn1.disabled = true;
});

//
// http://easings.net/#easeInOutQuart
//  t: current time
//  b: beginning value
//  c: change in value
//  d: duration
//
function easeInOutQuart(t, b, c, d) {
  if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
  return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
}

function reset() {
  document.querySelector('.square').style.width = Math.floor((Math.random() * 500) + 1) + "px";
}

function animate() {

  var rect = document.querySelector('.square');
  var from = 0;
  var to = window.getComputedStyle(rect, null).getPropertyValue("width").split('px')[0];
  var duration = to * 10;

  var start = new Date().getTime();
  var timer = setInterval(function() {
    var time = new Date().getTime() - start;
    var width = easeInOutQuart(time, from, to - from, duration);
    rect.style.width = width + "px";
    if (time >= duration) {
      clearInterval(timer);
      btn1.disabled = false;
    }
  }, 1000 / 60);
  rect.style.width = from;
}

reset();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.square {
  position: relative;
  display: block;
  width: 30px;
  height: 30px;
  background-color: #f00;
}</code>```

<button class="animate">Animate</button>```

Body:
How can i set the duration of an transition/animation to pixel per second?

You see the two different wrappers, with a different total height depending on it's colored content. The total speed is the same, given from the css transition attribute, thats okay if you want several animations with the same duration. For a smoother look i want to set this transition/animation effect to pixel per second so it takes as long as many pixels there. More content = more pixel = longer animation.

How can i achieve this with vanilla javascript or even css?

var wrapper1 = document.getElementById('wrapper1');
var wrapper2 = document.getElementById('wrapper2');
var header1 = document.getElementById('header1');
var header2 = document.getElementById('header2');
var wrapper1CmputedHeight = wrapper1.scrollHeight;
var wrapper2CmputedHeight = wrapper2.scrollHeight;

header1.addEventListener('click', function() {
  if (wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
  } else {
    wrapper1.style.height = '60px';
  }
})

header2.addEventListener('click', function() {
  if (wrapper2.style.height === '60px') {
    wrapper2.style.height = wrapper2CmputedHeight + 'px';
  } else {
    wrapper2.style.height = '60px';
  }
})

#wrapper1,
#wrapper2 {
  background: #fff;
  border: 1px solid grey;
  overflow: hidden;
  transition: height .2s linear
}

#wrapper1 {
  margin-bottom: 40px
}

#header1,
#header2 {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer
}

#content1 {
  height: 20px;
  background: blue
}

#content2 {
  height: 600px;
  background: green
}

    header

    header

Body:
I found this example here but it seems to do the trick for you (after some tweaking). In this case it implements a quartic interpolation, however you could adjust this algorithm to linear / other if so desired.

//
// Animate
//
var btn1 = document.querySelector('.animate');
btn1.addEventListener('click', function() {
  reset();
  animate();
  btn1.disabled = true;
});

//
// http://easings.net/#easeInOutQuart
//  t: current time
//  b: beginning value
//  c: change in value
//  d: duration
//
function easeInOutQuart(t, b, c, d) {
  if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
  return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
}

function reset() {
  document.querySelector('.square').style.width = Math.floor((Math.random() * 500) + 1) + "px";
}

function animate() {

  var rect = document.querySelector('.square');
  var from = 0;
  var to = window.getComputedStyle(rect, null).getPropertyValue("width").split('px')[0];
  var duration = to * 10;

  var start = new Date().getTime();
  var timer = setInterval(function() {
    var time = new Date().getTime() - start;
    var width = easeInOutQuart(time, from, to - from, duration);
    rect.style.width = width + "px";
    if (time >= duration) {
      clearInterval(timer);
      btn1.disabled = false;
    }
  }, 1000 / 60);
  rect.style.width = from;
}

reset();

.square {
  position: relative;
  display: block;
  width: 30px;
  height: 30px;
  background-color: #f00;
}

<div class="square"></div>

<button class="animate">Animate</button>


问:
How to call table.reloadData by didReceiveData() in session using Multipeer Connectivity (Swift 3)
I am struggling on a problem that when I receive data from session using Multipeer Connectivity framework, I want to update the data and reload the table of a view controller instantly.

Here are my codes for didReceiveData function of MPCHandler:

```<code>func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    NSLog("%@", "didReceive: \(data)")
    if var dict: [NSDictionary] = NSKeyedUnarchiver.unarchiveObject(with: data) as? [NSDictionary]{
        let d = dict.removeFirst()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.winnerDataController.syncWinnerFromDictionary(d: dict)

    }
}
</code>```

For sync function in WinnerDataController

```<code>func syncWinnerFromDictionary(d: NSDictionary){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entityDescription = NSEntityDescription.entity(forEntityName: "Winner", in: context)!

    let winner: Winner = NSManagedObject(entity: entityDescription, insertInto: context) as! Winner
    winner.setValue(d.value(forKey: "index"), forKey: "index")
    winner.setValue(d.value(forKey: "dept"), forKey: "dept")
    winner.setValue(d.value(forKey: "name"), forKey: "name")
    save()
    appDelegate.resultViewController.tableView.reloadData()
}
</code>```

I want to update and reload the table of resultViewContoller upon the receive of the data. However, when it goes to appDelegate.resultViewController.tableView.reloadData(), the console gives out fatal error: unexpectedly found nil while unwrapping an Optional value. I spent all day on figuring why the tableView is nil, yet still haven't got any ideas.

Could someone plz help. Thx

I tried the following codes as provided by @Hitesh Sultaniya: NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil) and func testing(notification: Notification){
        print("testing")
        self.tableView.reloadData()
    } in result view controller. Also, NotificationCenter.default.post(name: NSNotification.Name(rawValue: "syncWinner"), object: nil) in WinnerDataController.

In the console, "testing" is printed. However, after a few seconds,
"This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes"
is shown.

Then, I tried this:

```<code>func testing(notification: Notification){
DispatchQueue.global(qos: .userInitiated).async{
   self.tableView.reloadData()
}
</code>```

}

Now, no error is shown. But the table is still not yet reloaded...

答:
With the help of @Hitesh Sultaniya, I solved the problem.

Here are my codes which work:

For sync function in WinnerDataController:

```<code>func syncWinnerFromDictionary(d: NSDictionary){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entityDescription = NSEntityDescription.entity(forEntityName: "Winner", in: context)!
    let winner: Winner = NSManagedObject(entity: entityDescription, insertInto: context) as! Winner
    winner.setValue(d.value(forKey: "index"), forKey: "index")
    winner.setValue(d.value(forKey: "dept"), forKey: "dept")
    winner.setValue(d.value(forKey: "name"), forKey: "name")
    save()
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "syncWinner"), object: nil)
</code>```

For ResultViewController:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil)
    appDelegate = UIApplication.shared.delegate as! AppDelegate
    }

func testing(notification: Notification){
    if Thread.isMainThread == true{
        self.tableView.reloadData()
        print("main thread")
    }
    else{
        DispatchQueue.main.sync {
            self.updateList()
            print(winnerList.count)
            self.tableView.reloadData()
            print("not main thread")

        }
    }
</code>```

Initially, I tried this in ResultViewController but doesn't work

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil)
    appDelegate = UIApplication.shared.delegate as! AppDelegate
    }

func testing(notification: Notification){
    if Thread.isMainThread == true{
        self.tableView.reloadData()
        print("main thread")
    }
    else{
        DispatchQueue.main.sync {
            self.tableView.reloadData()
            print("not main thread")

        }
    }
</code>```

It is because when it runs the block of DispatchQueue.main.sync, it is not the main thread and hasn't got the most updated winnerList. In fact, the table has been reload yet with outdated winnerList. Therefore, it seems like table not yet reloaded.

Then, I added self.updateList() to let this thread get the most updated core data. Finally, it works.

Hope this would be helpful for those who struggle with the same problem as I did.

Body:
I am struggling on a problem that when I receive data from session using Multipeer Connectivity framework, I want to update the data and reload the table of a view controller instantly.

Here are my codes for didReceiveData function of MPCHandler:

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    NSLog("%@", "didReceive: \(data)")
    if var dict: [NSDictionary] = NSKeyedUnarchiver.unarchiveObject(with: data) as? [NSDictionary]{
        let d = dict.removeFirst()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.winnerDataController.syncWinnerFromDictionary(d: dict)

    }
}

For sync function in WinnerDataController

func syncWinnerFromDictionary(d: NSDictionary){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entityDescription = NSEntityDescription.entity(forEntityName: "Winner", in: context)!

    let winner: Winner = NSManagedObject(entity: entityDescription, insertInto: context) as! Winner
    winner.setValue(d.value(forKey: "index"), forKey: "index")
    winner.setValue(d.value(forKey: "dept"), forKey: "dept")
    winner.setValue(d.value(forKey: "name"), forKey: "name")
    save()
    appDelegate.resultViewController.tableView.reloadData()
}

I want to update and reload the table of resultViewContoller upon the receive of the data. However, when it goes to appDelegate.resultViewController.tableView.reloadData(), the console gives out fatal error: unexpectedly found nil while unwrapping an Optional value. I spent all day on figuring why the tableView is nil, yet still haven't got any ideas.

Could someone plz help. Thx

I tried the following codes as provided by @Hitesh Sultaniya: NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil) and func testing(notification: Notification){
        print("testing")
        self.tableView.reloadData()
    } in result view controller. Also, NotificationCenter.default.post(name: NSNotification.Name(rawValue: "syncWinner"), object: nil) in WinnerDataController.

In the console, "testing" is printed. However, after a few seconds,
"This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes"
is shown.

Then, I tried this:

func testing(notification: Notification){
DispatchQueue.global(qos: .userInitiated).async{
   self.tableView.reloadData()
}

}

Now, no error is shown. But the table is still not yet reloaded...

Body:
With the help of @Hitesh Sultaniya, I solved the problem.

Here are my codes which work:

For sync function in WinnerDataController:

func syncWinnerFromDictionary(d: NSDictionary){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entityDescription = NSEntityDescription.entity(forEntityName: "Winner", in: context)!
    let winner: Winner = NSManagedObject(entity: entityDescription, insertInto: context) as! Winner
    winner.setValue(d.value(forKey: "index"), forKey: "index")
    winner.setValue(d.value(forKey: "dept"), forKey: "dept")
    winner.setValue(d.value(forKey: "name"), forKey: "name")
    save()
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "syncWinner"), object: nil)

For ResultViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil)
    appDelegate = UIApplication.shared.delegate as! AppDelegate
    }

func testing(notification: Notification){
    if Thread.isMainThread == true{
        self.tableView.reloadData()
        print("main thread")
    }
    else{
        DispatchQueue.main.sync {
            self.updateList()
            print(winnerList.count)
            self.tableView.reloadData()
            print("not main thread")

        }
    }

Initially, I tried this in ResultViewController but doesn't work

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil)
    appDelegate = UIApplication.shared.delegate as! AppDelegate
    }

func testing(notification: Notification){
    if Thread.isMainThread == true{
        self.tableView.reloadData()
        print("main thread")
    }
    else{
        DispatchQueue.main.sync {
            self.tableView.reloadData()
            print("not main thread")

        }
    }

It is because when it runs the block of DispatchQueue.main.sync, it is not the main thread and hasn't got the most updated winnerList. In fact, the table has been reload yet with outdated winnerList. Therefore, it seems like table not yet reloaded.

Then, I added self.updateList() to let this thread get the most updated core data. Finally, it works.

Hope this would be helpful for those who struggle with the same problem as I did.


问:
Cognito get new token after updating user attributes
I have a question regarding Amazon Cognito.
What I want to achieve is to set default custom attribute for the user record.
Ideally it will be great if I could set it by default in user pool, for example "custom:domain": "some name". But I can't find an example for this, or maybe set it up in Pre sign-up trigger with Lambda, but I didn't find examples for it also. What I did, when user authenticate I get the user attributes and set the required one with updateAttributes (I use amazon-cognito-identity-js). The downside of this approach that I faced, on first user login he gets the tokens first and only after that this custom attribute it set. So in first login this attribute is missed in token. What I want to ask what is the best approach of doing this kind of staff? And if my variant is appropriate, how could I update user token after changing the user attributes, so they appear in that token.

答: Another option would be to add a Pre token generation trigger that checks to see if the value is set, and if it isn't overrides it.  http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#aws-lambda-triggers-pre-token-generation-example-1  It would be set the first time the user gets the token if done this way.</p>


问:
Create firewall rule google cloud app engine
I am trying to connect to imap.gmail.com on port 993 on googles app engine. I have created an egress (outgoing) firewall rule (VPC) to allow all ip address (0.0.0.0/0) and all ports to all instances yet still my application is blocked.

I receive this error

```<code>Type = System.Net.Internals.SocketExceptionFactory+ExtendedSocketException
Message = Network is unreachable [2404:6800:4003:c02::6c]:993
Source = System.Net.Sockets
SocketErrorCode = NetworkUnreachable
ErrorCode = 101
NativeErrorCode = 101
TargetSite = Void DoConnect(System.Net.EndPoint, System.Net.Internals.SocketAddress)
StackTrace =    at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.Socket.Connect(IPAddress address, Int32 port)
   at MailKit.Net.Imap.ImapClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken)
   at Parser.Core.Authentication.GetMailClient(Account account) in /home/admin_/emailparser/Parser.Core/Authentication.cs:line 25
HResult = -2147467259
</code>```

Any idea why this isn't working?

答:
You should not need a firewall rule for App Engine app. According to the following doc - App Engine Go Sockets - imap.gmail.com port 993 should be available.

However, under "Limitations and restrictions" section, it says "Sockets are available only for paid apps". Could it be the case that your app does not have billing enabled?

Body:
I am trying to connect to imap.gmail.com on port 993 on googles app engine. I have created an egress (outgoing) firewall rule (VPC) to allow all ip address (0.0.0.0/0) and all ports to all instances yet still my application is blocked.

I receive this error

Type = System.Net.Internals.SocketExceptionFactory+ExtendedSocketException
Message = Network is unreachable [2404:6800:4003:c02::6c]:993
Source = System.Net.Sockets
SocketErrorCode = NetworkUnreachable
ErrorCode = 101
NativeErrorCode = 101
TargetSite = Void DoConnect(System.Net.EndPoint, System.Net.Internals.SocketAddress)
StackTrace =    at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.Socket.Connect(IPAddress address, Int32 port)
   at MailKit.Net.Imap.ImapClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken)
   at Parser.Core.Authentication.GetMailClient(Account account) in /home/admin_/emailparser/Parser.Core/Authentication.cs:line 25
HResult = -2147467259

Any idea why this isn't working?


问:
configure: error: one or more libs available at link-time are not available run-time. Libs used at link-time: -lssh2 -lssl -lcrypto -lz
env: centos7
install curl

when i start install curl and ./configure --with-ssl --with-zlib, i occurs errors about libs, what mean about link-time? it's env set? i have no any experience about installtaion by make, needed to install other package? how to fix it?

```<code>./configrue --with-ssl --with-zlib
</code>```

accurs errors:

```<code>checking run-time libs availability... failed
configure: error: one or more libs available at link-time are not available
run-time. Libs used at link-time: -lssh2  -lssl -lcrypto -lz
</code>```

答:
the errors occur bebause of openssl install

after installed openssl, should check up while it usefully
when i input openssl version, it show same unkown path errors

so, u should set:

```<code>ln -s /usr/local/lib64/libssl.so.1.1 /usr/lib64/libssl.so.1.1
ln -s /usr/local/lib64/libcrypto.so.1.1 /usr/lib64/libcrypto.so.1.1
</code>```

it worked!

Body:
env: centos7
install curl

when i start install curl and ./configure --with-ssl --with-zlib, i occurs errors about libs, what mean about link-time? it's env set? i have no any experience about installtaion by make, needed to install other package? how to fix it?

./configrue --with-ssl --with-zlib

accurs errors:

checking run-time libs availability... failed
configure: error: one or more libs available at link-time are not available
run-time. Libs used at link-time: -lssh2  -lssl -lcrypto -lz

Body:
the errors occur bebause of openssl install

after installed openssl, should check up while it usefully
when i input openssl version, it show same unkown path errors

so, u should set:

ln -s /usr/local/lib64/libssl.so.1.1 /usr/lib64/libssl.so.1.1
ln -s /usr/local/lib64/libcrypto.so.1.1 /usr/lib64/libcrypto.so.1.1

it worked!


问:
The variable is being used without being initialized (C++, other solutions don't work)
My problem is that when I enter a value in my C++ program (via cin) it gives me a debug error and says "Run-time Check Failure #3 - the variable 'result' is being used without being initialized." 'result' is an int, and is initialized with a 1, but still gives me this, unlike other peoples' questions. </p>

```<code>int multiplication(int x, int y, int result)
{
    result = 1;
    result = x * y;
    return result;
}

int main() //Declares the "main" function, which is mandatory.
{
    int result = 0;
    char operation;
    int x;
    int y;
    std::cout << "Enter your first number: ";
    std::cin >> x;
    std::cout << "Enter your second number: ";
    std::cin >> y;
    std::cout << "Enter your operation (+, -, *, /): ";
    std::cin >> operation;
    if (operation == '*');
    {
        int result = multiplication(x, y, result);
    }

    std::cout << "The answer is: " << result << std::endl;
    return 0; //Ends the process with 0x0.
}
</code>```

答:
You have two different result variables.

At the top of main there is one

```<code>int result = 0;
</code>```

which is initialized.

But inside the if-statement the line

```<code>int result = multiplication(x, y, result);
</code>```

creates a new variable, also named result and then passes it to the function. Obviously the function call must be performed before the variable is assigned the value returned from the function.

Probably you didn't want this new variable, but use the one declared at the top of the function. You do that by making it an assignment instead of a new declaration:

```<code>if (operation == '*');
{
    result = multiplication(x, y, result);
}
</code>```

Body:
My problem is that when I enter a value in my C++ program (via cin) it gives me a debug error and says "Run-time Check Failure #3 - the variable 'result' is being used without being initialized." 'result' is an int, and is initialized with a 1, but still gives me this, unlike other peoples' questions.

int multiplication(int x, int y, int result)
{
    result = 1;
    result = x * y;
    return result;
}

int main() //Declares the "main" function, which is mandatory.
{
    int result = 0;
    char operation;
    int x;
    int y;
    std::cout << "Enter your first number: ";
    std::cin >> x;
    std::cout << "Enter your second number: ";
    std::cin >> y;
    std::cout << "Enter your operation (+, -, *, /): ";
    std::cin >> operation;
    if (operation == '*');
    {
        int result = multiplication(x, y, result);
    }

    std::cout << "The answer is: " << result << std::endl;
    return 0; //Ends the process with 0x0.
}

Body:
You have two different result variables.

At the top of main there is one

int result = 0;

which is initialized.

But inside the if-statement the line

int result = multiplication(x, y, result);

creates a new variable, also named result and then passes it to the function. Obviously the function call must be performed before the variable is assigned the value returned from the function.

Probably you didn't want this new variable, but use the one declared at the top of the function. You do that by making it an assignment instead of a new declaration:

if (operation == '*');
{
    result = multiplication(x, y, result);
}