问:
In IE8 enter key in a form does not work
I have a problem that in IE8 the enter does not work to submit a form. I have generated a test page to expose this problem. It seems that displaying the form in the onLoad function disables results that the enter button does not trigger a submit anymore. Is this a bug in IE8 or is it some security issue?

The code to reproduce this is:

onload = function() {
    document.getElementById('test').style.display = 'block';
} ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test {
    display: none;
}</code>```

<form id="test" method="get" action="javascript:alert('woei!')">
    <input type="text" name="user" value="">
    <input type="password" name="pw" value="">
    <input type="submit" value="submit" id="submit">
</form> ```

答:
Yeah, I was bitten by this bug too today. I found this workaround, though (diff from the OP):

```<code> <script type="text/javascript">
 onload = function() {
     document.getElementById('test').style.display = 'block';
+    document.getElementById('test').innerHTML =
+        document.getElementById('test').innerHTML;
 }
 </script>
 </head>
</code>```

Simply recreate the contents of the form from the contents of itself. Yikes. But it works. (Famous last words...)

Body:
I have a problem that in IE8 the enter does not work to submit a form. I have generated a test page to expose this problem. It seems that displaying the form in the onLoad function disables results that the enter button does not trigger a submit anymore. Is this a bug in IE8 or is it some security issue?

The code to reproduce this is:

onload = function() {
    document.getElementById('test').style.display = 'block';
}

#test {
    display: none;
}

<form id="test" method="get" action="javascript:alert('woei!')">
    <input type="text" name="user" value="">
    <input type="password" name="pw" value="">
    <input type="submit" value="submit" id="submit">
</form>

Body:
Yeah, I was bitten by this bug too today. I found this workaround, though (diff from the OP):

 <script type="text/javascript">
 onload = function() {
     document.getElementById('test').style.display = 'block';
+    document.getElementById('test').innerHTML =
+        document.getElementById('test').innerHTML;
 }
 </script>
 </head>

Simply recreate the contents of the form from the contents of itself. Yikes. But it works. (Famous last words...)


来源: stackexchange

问:
CodeIgniter session id changing and not working
Because of our payment system we have to use some kind of relay system that is on third party website, to have valid PCI (HTTPS).

We are currently facing a wierd bug we have used too many hours on now.

We have 4 steps in our registration.

Enter all the data.

Add images

Payment

This is how we do:
On step 1 we save all post data into a session
     $this->session->set_userdata("campaigncreation", $out);
And yes $out contains all the data.

On step we can easily print out the session data for campaigncreation;
<?print_r($this->session->userdata)?>

Because we need to go to another website, we add the session_id into our call, to keep the session on third party website.

Our url is like:
https://relay.ditonlinebetalingssystem.dk/relay/v2/relay.cgi/http://xxxx.dk/something/controller/a1264526031adb9c71ae433eef44bfa0

As you see we take the session_id (<?=$this->session->userdata("session_id")?>) in the URL, and in our controller we replace the session id with that in the controller as this:

$phpsess is "a1264526031adb9c71ae433eef44bfa0"

```<code>if ( !empty($phpsess)){
            $this->session->set_userdata("session_id",$phpsess);
}
</code>```

When we now print out the user data we get the correctly session_id, but it doesn't take the data with us from step 1 in some how. What do to?

I only get

```<code> Array
(
[session_id] => a1264526031adb9c71ae433eef44bfa0
[ip_address] => 87.54.46.121
[user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36
[last_activity] => 1383052142
[user_data] =>
[advertiser_id] => 1
[advertiser_name] => xxxx
</code>```

)

But in some way it still have the correct data for advertiser_id and advertiser_name, so that is totally wierd.

What do to?

It's like codeigniter refresh the session_id on each page load and therefore there will be problem.

Or maybe because of the domain cookie settings? I dont know, please help us.

答:
According to CI's Session.php, the ID is changed on every update, but they keep a reference to the old ID so that they can update it right row.

Also, according to the doc: "session_id" is regenerated (by default) every five minutes".

If there is no specific reason to use "session id" I would suggest you to set another unique variable in the userdata and use it as "session id".

```<code>$uniqueId = uniqid(time()+$unique_user_variable, TRUE);
$this->session->set_userdata("my_session_id", md5($uniqueId));
</code>```

as the "Unique user variable" may vary from user ip, user name, user id and etc. according to your specific case.

ContentLicense: CC BY-SA 3.0

Body:
Because of our payment system we have to use some kind of relay system that is on third party website, to have valid PCI (HTTPS).

We are currently facing a wierd bug we have used too many hours on now.

We have 4 steps in our registration.

Enter all the data.

Add images

Payment

This is how we do:
On step 1 we save all post data into a session
     $this->session->set_userdata("campaigncreation", $out);
And yes $out contains all the data.

On step we can easily print out the session data for campaigncreation;
<?print_r($this->session->userdata)?>

Because we need to go to another website, we add the session_id into our call, to keep the session on third party website.

Our url is like:
https://relay.ditonlinebetalingssystem.dk/relay/v2/relay.cgi/http://xxxx.dk/something/controller/a1264526031adb9c71ae433eef44bfa0

As you see we take the session_id (<?=$this->session->userdata("session_id")?>) in the URL, and in our controller we replace the session id with that in the controller as this:

$phpsess is "a1264526031adb9c71ae433eef44bfa0"

if ( !empty($phpsess)){
            $this->session->set_userdata("session_id",$phpsess);
}

When we now print out the user data we get the correctly session_id, but it doesn't take the data with us from step 1 in some how. What do to?

I only get

 Array
(
[session_id] => a1264526031adb9c71ae433eef44bfa0
[ip_address] => 87.54.46.121
[user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36
[last_activity] => 1383052142
[user_data] =>
[advertiser_id] => 1
[advertiser_name] => xxxx

)

But in some way it still have the correct data for advertiser_id and advertiser_name, so that is totally wierd.

What do to?

It's like codeigniter refresh the session_id on each page load and therefore there will be problem.

Or maybe because of the domain cookie settings? I dont know, please help us.

Body:
According to CI's Session.php, the ID is changed on every update, but they keep a reference to the old ID so that they can update it right row.

Also, according to the doc: "session_id" is regenerated (by default) every five minutes".

If there is no specific reason to use "session id" I would suggest you to set another unique variable in the userdata and use it as "session id".

$uniqueId = uniqid(time()+$unique_user_variable, TRUE);
$this->session->set_userdata("my_session_id", md5($uniqueId));

as the "Unique user variable" may vary from user ip, user name, user id and etc. according to your specific case.


问:
Replace single zeros of a tab-separated-values file
How do I replace single zeros (0) with string NA in a tab-separated-values file?

Suppose I have the table:

```<code>0\t0.15\t0t\8.05\t0\t0\t0.15\7.0306\n
5\t0.18\t0\8.05\t0\t0\t0.5t\50\n
1\t15\t0205\t0\t0.16\t200t\40.90\n
</code>```

I would like to get:

```<code>NA\t0.15\NAt\8.05\tNA\tNA\t0.15t\7.0306\n
5\t0.18\tNA\8.05\tNA\tNA\t0.5t\50\n
1\t15\t0205\tNA\t0.16\t200t\40.90\n
</code>```

That is, I would like to match the null measures of the data frame.

Body:
How do I replace single zeros (0) with string NA in a tab-separated-values file?

Suppose I have the table:

0\t0.15\t0t\8.05\t0\t0\t0.15\7.0306\n
5\t0.18\t0\8.05\t0\t0\t0.5t\50\n
1\t15\t0205\t0\t0.16\t200t\40.90\n

I would like to get:

NA\t0.15\NAt\8.05\tNA\tNA\t0.15t\7.0306\n
5\t0.18\tNA\8.05\tNA\tNA\t0.5t\50\n
1\t15\t0205\tNA\t0.16\t200t\40.90\n

That is, I would like to match the null measures of the data frame.

Body:
With GNU or OSX sed for -E for EREs:

$ sed -E 's/(^|\t)0(\t|$)/\1NA\2/g; s/(^|\t)0(\t|$)/\1NA\2/g' file
NA      0.15    NA      8.05    NA      NA      0.15    7.0306
5       0.18    NA      8.05    NA      NA      0.5     50
1       15      NA      205     NA      0.16    200     40.90

See https://stackoverflow.com/a/44908420/1745001 for why it takes 2 passes.


问:
Vue.js - update child component's function
I have a child component with a prop, but also there's is a mounted function to init date and hour. How to update this function when data from parent is reloaded?

Parent component:

```<code> <template>
      <div>
        <ul>
          <li v-for="item in occurrences">
            {{ item.title }} {{ item.completed }}</small>
          </li>
        </ul>
        <sourceupd class="source" v-bind:source='source'></sourceupd>
      </div>
    </template>

    <script>
      import axios from 'axios'
      import sourceupd from './SourceAndUpdated'

      export default {

        name: 'Occurrences',

        components: {
          sourceupd
        },

        data: function () {
          return {
            occurrences: [],
            source: 'ANPC'
          }
        },

        mounted: function () {
          var _self = this

          function callAPI () {
            // call api code
          }

          callAPI()

          setInterval(() => {
            callAPI()
          }, 1024 * 3)
        }
      }
    </script>
</code>```

Child Component:

```<code><template lang="html">
    <small class="source-ref">Fonte: {{ source }} | Actualização:{{ updated.hour }}:{{ updated.minutes }}</small>
</template>

<script>
import moment from 'moment'

export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],

  mounted: function () {
    moment.locale('pt')

    this.updated.hour = moment().format('HH')
    this.updated.minutes = moment().format('mm')
    this.updated.seconds = moment().format('ss')
  }
}
</script>
</code>```

When callAPI() is reloaded, I would like to update time as well. I'm newbie with Vue.js (or this kind of framework) and I'm struggling how to handle this kind of dynamic information.

Thanks in advance.

答:
There are a couple of ways you could do this.

If the source property of your parent component is updated by callAPI then this would be as simple as moving your code into the updated handler.

```<code>export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],
  methods: {
    update(){
      moment.locale('pt')

      this.updated.hour = moment().format('HH')
      this.updated.minutes = moment().format('mm')
      this.updated.seconds = moment().format('ss')

    }
  },
  updated: function () {
    this.update()
  },
  mounted: function(){
    this.update()
  }
}
</code>```

Since it's not clear that you are updating any properties of the sourceupd, another way would be to just call the method using a ref.

In the Parent component template:

```<code><sourceupd ref="sourceupd" class="source" v-bind:source='source'></sourceupd>
</code>```

In your mounted handler:

```<code>setInterval(() => {
  callAPI()
  this.$refs.sourceupd.update()
}, 1024 * 3)
</code>```

And change sourceupd:

```<code>export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],

  methods: {
    update(){
      moment.locale('pt')

      this.updated.hour = moment().format('HH')
      this.updated.minutes = moment().format('mm')
      this.updated.seconds = moment().format('ss')

    }
  },

  mounted: function () {
    this.update()
  }
}
</code>```

I should also point out that you should add seconds to the updated property of your data, otherwise it will not be reactive.

```<code>  updated: {
    hour: '',
    minutes: '',
    seconds: ''
  }
</code>```

Body:
I have a child component with a prop, but also there's is a mounted function to init date and hour. How to update this function when data from parent is reloaded?

Parent component:

 <template>

            {{ item.title }} {{ item.completed }}

        <sourceupd class="source" v-bind:source='source'></sourceupd>

    </template>

Child Component:

<template lang="html">
    Fonte: {{ source }} | Actualização:{{ updated.hour }}:{{ updated.minutes }}
</template>

When callAPI() is reloaded, I would like to update time as well. I'm newbie with Vue.js (or this kind of framework) and I'm struggling how to handle this kind of dynamic information.

Thanks in advance.

Body:
There are a couple of ways you could do this.

If the source property of your parent component is updated by callAPI then this would be as simple as moving your code into the updated handler.

export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],
  methods: {
    update(){
      moment.locale('pt')

      this.updated.hour = moment().format('HH')
      this.updated.minutes = moment().format('mm')
      this.updated.seconds = moment().format('ss')

    }
  },
  updated: function () {
    this.update()
  },
  mounted: function(){
    this.update()
  }
}

Since it's not clear that you are updating any properties of the sourceupd, another way would be to just call the method using a ref.

In the Parent component template:

<sourceupd ref="sourceupd" class="source" v-bind:source='source'></sourceupd>

In your mounted handler:

setInterval(() => {
  callAPI()
  this.$refs.sourceupd.update()
}, 1024 * 3)

And change sourceupd:

export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],

  methods: {
    update(){
      moment.locale('pt')

      this.updated.hour = moment().format('HH')
      this.updated.minutes = moment().format('mm')
      this.updated.seconds = moment().format('ss')

    }
  },

  mounted: function () {
    this.update()
  }
}

I should also point out that you should add seconds to the updated property of your data, otherwise it will not be reactive.

  updated: {
    hour: '',
    minutes: '',
    seconds: ''
  }


问:
Scala: Making higher kinded type with some generic type
For example I have defined a Monad Trait like this:

```<code>trait Monad[F[_]] {
  def unit[T](a: => T): F[T]
  def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}
</code>```

I create a ListMonad that implement above interface:

```<code> class ListMonad extends Monad[List] {
    override def unit[T](a: => T): List[T] = List(a)

    override def flatMap[A, B](fa: List[A])(f: (A) => List[B]): List[B] = fa flatMap f
  }
</code>```

Now I want to verify above Monad in "Generic way". First attribute of monad is Left Identity. That means: if we giving a monad "m", an value " x"and a function "f". It should satisfied: m.(identity(x)).flatMap(f) == f(x)

So for example I create following verifier class for checking that assumption:

```<code>case class MonadVerifier[A, F[_]](monad: Monad[F[_]])(f: A => F[A]) {
  def leftIdentity(value: A): Boolean =
    monad.flatMap[A, A](monad.unit(value))(f) == f(value)
}
</code>```

In this code, I meet error:

Type mismatch. expected: (A) => F[_][A], actual: (A) => F[A]

I don't know in Scala, how can I express F[A] as generic. I think if I defined F[_] Scala will insert generic type into [_] when calling F[A] but it isn't true.

Please help me in this case. Thanks

答:
What @Dima said:

The error is that

```<code>MonadVerifier[A, F[_]](monad: Monad[F[_]])
</code>```

should be

```<code>MonadVerifier[A, F[_]](monad: Monad[F])
</code>```

What the first line is saying is not that F is a monad (F has kind * -> * and values of type F[_]), but that F[_] (that is, type constructor F applied to any type of the right kind) is a monad, (F has kind * -> (* -> *) and values of type F[_][_]).

Expanding on that (ignore this if you want): Monad expects its type argument to take one type argument and return a concrete type. The argument to Monad is said to have kind * -> * ("function" from concrete types to concrete types), and Monad itself has kind (* -> *) -> * ("function" from "functions" from concrete types to concrete types to concrete types). When you say Monad[F[_]], you imply that the argument (F[_]) has kind * -> *, because that's the kind Monad expects. F[_] is the application of a type constructor F (kind a -> b for some unknown kinds a and b) to any concrete type (implied by _, forcing the kind of F to be constrained to * -> k for some unknown k). Since F[_] also has to be * -> * because of Monad, this constrains k = (* -> *) and so F is forced to be of kind * -> (* -> *) which is the curried version of (*, *) -> *. This implies that F has two type parameters, and it is monadic in the second one (like Either).

In the future, maybe use a context bound to avoid similar mixups:

```<code>MonadVerifier[A, F[_]: Monad] // no params needed
</code>```

Body:
For example I have defined a Monad Trait like this:

trait Monad[F[_]] {
  def unit[T](a: => T): F[T]
  def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}

I create a ListMonad that implement above interface:

 class ListMonad extends Monad[List] {
    override def unit[T](a: => T): List[T] = List(a)

    override def flatMap[A, B](fa: List[A])(f: (A) => List[B]): List[B] = fa flatMap f
  }

Now I want to verify above Monad in "Generic way". First attribute of monad is Left Identity. That means: if we giving a monad "m", an value " x"and a function "f". It should satisfied: m.(identity(x)).flatMap(f) == f(x)

So for example I create following verifier class for checking that assumption:

case class MonadVerifier[A, F[_]](monad: Monad[F[_]])(f: A => F[A]) {
  def leftIdentity(value: A): Boolean =
    monad.flatMap[A, A](monad.unit(value))(f) == f(value)
}

In this code, I meet error:

Type mismatch. expected: (A) => F[_][A], actual: (A) => F[A]

I don't know in Scala, how can I express F[A] as generic. I think if I defined F[_] Scala will insert generic type into [_] when calling F[A] but it isn't true.

Please help me in this case. Thanks

Body:
What @Dima said:

The error is that

MonadVerifier[A, F[_]](monad: Monad[F[_]])

should be

MonadVerifier[A, F[_]](monad: Monad[F])

What the first line is saying is not that F is a monad (F has kind * -> * and values of type F[_]), but that F[_] (that is, type constructor F applied to any type of the right kind) is a monad, (F has kind * -> (* -> *) and values of type F[_][_]).

Expanding on that (ignore this if you want): Monad expects its type argument to take one type argument and return a concrete type. The argument to Monad is said to have kind * -> * ("function" from concrete types to concrete types), and Monad itself has kind (* -> *) -> * ("function" from "functions" from concrete types to concrete types to concrete types). When you say Monad[F[_]], you imply that the argument (F[_]) has kind * -> *, because that's the kind Monad expects. F[_] is the application of a type constructor F (kind a -> b for some unknown kinds a and b) to any concrete type (implied by _, forcing the kind of F to be constrained to * -> k for some unknown k). Since F[_] also has to be * -> * because of Monad, this constrains k = (* -> *) and so F is forced to be of kind * -> (* -> *) which is the curried version of (*, *) -> *. This implies that F has two type parameters, and it is monadic in the second one (like Either).

In the future, maybe use a context bound to avoid similar mixups:

MonadVerifier[A, F[_]: Monad] // no params needed


问:
404 Rejected-By-UrlScan Delete Request
On my Web API I have a few [HttpGet] functions that work perfectly, but the one that is [HttpDelete] (on the same Controller) doesn't work, it returns 404 error.

```<code>[Authorize]
[RoutePrefix("Users")]
public class UsersController : ApiController
{
    [HttpDelete]
    [Route("DeleteUser/{ID}")]
    public void Delete(int id)
    {
        _UserRepository.Delete(id);
    }
}
</code>```

On the web.config I have the verb set to *:

```<code> <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</code>```

The AJAX call:

```<code>deleteUser = function (id, callback) {
    $.ajax({
        url: "../../API/Users/DeleteUser/" + id,
        type: "DELETE",
        success: function () {
            callback;
        }
    });
}
</code>```

The error:

HTTP Error 404.0 - Not Found
  Detailed Error Information
  Module    IIS Web Core Notification   MapRequestHandler Handler   StaticFile

Error Code    0x80070002

Requested
  URL   https://www.example.com:443/Rejected-By-UrlScan?~/API/Users/DeleteUser/155

Physical Path d:\wr\mySite\example.com\Rejected-By-UrlScan
  Logon Method  Anonymous Logon User    Anonymous

All the calls are authenticated with OWIN Authentication and a bearer token.

An example of a working call on the same page:

```<code>getUsers = function (callback) {
    $.get("../../API/Users/GetUsers/", callback);
}
</code>```

What can causes it?

答:
Try setting the verbs manually

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0"
           path="*."
           verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
           type="System.Web.Handlers.TransferRequestHandler"
           preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
```

<p>Also check to make sure </p>

<ul>
<li><p>That you are calling the correct path.</p></li>
<li><p>you do not have a folder that matches the intended route </p></li>
</ul>

<hr>

<p>Also, your route template place holder needs to match the action parameter name</p>

```[Authorize]
[RoutePrefix("Users")]
public class UsersController : ApiController {

    [HttpDelete]
    [Route("DeleteUser/{id:int}")] //Matches DELETE {root}/Users/DeleteUser/5
    [AcceptVerbs("DELETE")]
    public IHttpActionResult Delete(int id) {
        //TODO: check if {id} exists and if not, then return NotFound()
        _UserRepository.Delete(id);
        return Ok();
    }

    //...other members
}
```

Title: 404 Rejected-By-UrlScan Delete Request

Body:
On my Web API I have a few [HttpGet] functions that work perfectly, but the one that is [HttpDelete] (on the same Controller) doesn't work, it returns 404 error.

[Authorize]
[RoutePrefix("Users")]
public class UsersController : ApiController
{
    [HttpDelete]
    [Route("DeleteUser/{ID}")]
    public void Delete(int id)
    {
        _UserRepository.Delete(id);
    }
}

On the web.config I have the verb set to *:

 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

The AJAX call:

deleteUser = function (id, callback) {
    $.ajax({
        url: "../../API/Users/DeleteUser/" + id,
        type: "DELETE",
        success: function () {
            callback;
        }
    });
}

The error:

HTTP Error 404.0 - Not Found
  Detailed Error Information
  Module    IIS Web Core Notification   MapRequestHandler Handler   StaticFile

Error Code    0x80070002

Requested
  URL   https://www.example.com:443/Rejected-By-UrlScan?~/API/Users/DeleteUser/155

Physical Path d:\wr\mySite\example.com\Rejected-By-UrlScan
  Logon Method  Anonymous Logon User    Anonymous

All the calls are authenticated with OWIN Authentication and a bearer token.

An example of a working call on the same page:

getUsers = function (callback) {
    $.get("../../API/Users/GetUsers/", callback);
}

What can causes it?

Body:
Try setting the verbs manually

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0"
           path="*."
           verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
           type="System.Web.Handlers.TransferRequestHandler"
           preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

Also check to make sure

That you are calling the correct path.

you do not have a folder that matches the intended route

Also, your route template place holder needs to match the action parameter name

[Authorize]
[RoutePrefix("Users")]
public class UsersController : ApiController {

    [HttpDelete]
    [Route("DeleteUser/{id:int}")] //Matches DELETE {root}/Users/DeleteUser/5
    [AcceptVerbs("DELETE")]
    public IHttpActionResult Delete(int id) {
        //TODO: check if {id} exists and if not, then return NotFound()
        _UserRepository.Delete(id);
        return Ok();
    }

    //...other members
}


问:
How to read key value in a grouped IEnumerable list?
How to access/read the key value in the resultListGrouped below?</p>

```<code>IEnumerable resultList = from...select...ToList();

var resultListGrouped = ResultList.GroupBy(t => t.Code).ToList();

// how to read the key value?
foreach ( ????)
{

}
</code>```

答:
Just use the Key property of the group:

```<code>foreach (var group in resultListGrouped)
{
    var code = group.Key;
}
</code>```

Side-note: it's not necessary to append everywhere ToList. Note that it's creating a new list in a loop. If you want to do further actions with a query and you don't need that list it's more efficient to use ToList only at the end. If you only need it in the foreach you don't need ToList at all.

Body:
How to access/read the key value in the resultListGrouped below?

IEnumerable resultList = from...select...ToList();

var resultListGrouped = ResultList.GroupBy(t => t.Code).ToList();

// how to read the key value?
foreach ( ????)
{

}

Body:
Just use the Key property of the group:

foreach (var group in resultListGrouped)
{
    var code = group.Key;
}

Side-note: it's not necessary to append everywhere ToList. Note that it's creating a new list in a loop. If you want to do further actions with a query and you don't need that list it's more efficient to use ToList only at the end. If you only need it in the foreach you don't need ToList at all.


问:
Check if running phonegap or apk
I have a code that will not run if the app is running via Phonegap (it will completly stop the script), will only run as an apk (needs to be built). How can I create an if that will check if its in phonegap or a standalone apk?</p>

答:
I test my apps using IIS (localhost). I use to check if the url contained "localhost", later found out about checking window.cordova to determine if the app is running as Cordova App.

Example:

```<code>function isRunningLocalhost() {

    if (window.cordova) {
        console.log('runningLocalhost() - False In Cordova');
        return false;
    }
    else {
        console.log('runningLocalhost() - True Running Localhost');
       return true;
   }
}

if (isRunningLocalhost() === true)
{
  //Not running as an APK
}
</code>```

Title: Check if running phonegap or apk

Body:
I test my apps using IIS (localhost). I use to check if the url contained "localhost", later found out about checking window.cordova to determine if the app is running as Cordova App.

Example:

function isRunningLocalhost() {

    if (window.cordova) {
        console.log('runningLocalhost() - False In Cordova');
        return false;
    }
    else {
        console.log('runningLocalhost() - True Running Localhost');
       return true;
   }
}

if (isRunningLocalhost() === true)
{
  //Not running as an APK
}


问:
How to know once a dynamically added script is parsed/loaded/executed?
I am trying to dynamically load a JavaScript file and, once it is loaded, run a function that is inside the file.  In my main HTML, I basically have:

```<code>function load_javascript(js_file)
{
    function load_js_callback(example)
    {
        console.log("function " + function_in_js_file + " is " + typeof(function_name));
        if (typeof(function_in_js_file) == "undefined")
        {
            window.setTimeout(load_js_callback(example), 500);
            return false;
        }
        function_in_js_file(example);
    }

    var jstag = document.createElement("script");
    document.head.appendChild(jstag);

    // Browsers:
    jstag.onload=load_js_callback("example");
    // Internet Explorer:
    jstag.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            load_js_callback("example");
        }
    }
    jstag.setAttribute('src',js_file);
}

load_javascript("/js/example.js");
</code>```

From what I can find on the internet (https://stackoverflow.com/a/3248500 and https://stackoverflow.com/a/16231055) this should work, but the jstag.onload runs before the function_in_js_file is defined, so I need the window.setTimeout to check again until the function is defined.

Ideally, I would like to get rid of that timeout.  Is there any way to know when the file has been completed loaded/parsed/executed (I'm not sure which is the right term) and the function is defined, ideally without changing the dynamic file?  I have also tried putting the document.head.appendChild(jstag); after the jstag.setAttribute, but with the same results.

答:
try this define a function called

```<code>function loadScript(sScriptSrc, oCallback) {
    var oHead = document.getElementsByTagName('head')[0];
    var oScript = document.createElement('script');
    oScript.type = 'text/javascript';
    oScript.src = sScriptSrc;
    // most browsers
    oScript.onload = oCallback;
    // IE 6 & 7
    oScript.onreadystatechange = function () {
        if (this.readyState == 'complete') {
            oCallback();
        }
    }
    oHead.appendChild(oScript);
}
</code>```

and then call your script file and function inside it via callback

```<code>    loadScript("/js/example.js", function () {
                //call function
function_in_js_file(example);
            });
</code>```

Body:
I am trying to dynamically load a JavaScript file and, once it is loaded, run a function that is inside the file.  In my main HTML, I basically have:

function load_javascript(js_file)
{
    function load_js_callback(example)
    {
        console.log("function " + function_in_js_file + " is " + typeof(function_name));
        if (typeof(function_in_js_file) == "undefined")
        {
            window.setTimeout(load_js_callback(example), 500);
            return false;
        }
        function_in_js_file(example);
    }

    var jstag = document.createElement("script");
    document.head.appendChild(jstag);

    // Browsers:
    jstag.onload=load_js_callback("example");
    // Internet Explorer:
    jstag.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            load_js_callback("example");
        }
    }
    jstag.setAttribute('src',js_file);
}

load_javascript("/js/example.js");

From what I can find on the internet (https://stackoverflow.com/a/3248500 and https://stackoverflow.com/a/16231055) this should work, but the jstag.onload runs before the function_in_js_file is defined, so I need the window.setTimeout to check again until the function is defined.

Ideally, I would like to get rid of that timeout.  Is there any way to know when the file has been completed loaded/parsed/executed (I'm not sure which is the right term) and the function is defined, ideally without changing the dynamic file?  I have also tried putting the document.head.appendChild(jstag); after the jstag.setAttribute, but with the same results.

Body:
try this define a function called

function loadScript(sScriptSrc, oCallback) {
    var oHead = document.getElementsByTagName('head')[0];
    var oScript = document.createElement('script');
    oScript.type = 'text/javascript';
    oScript.src = sScriptSrc;
    // most browsers
    oScript.onload = oCallback;
    // IE 6 & 7
    oScript.onreadystatechange = function () {
        if (this.readyState == 'complete') {
            oCallback();
        }
    }
    oHead.appendChild(oScript);
}

and then call your script file and function inside it via callback

    loadScript("/js/example.js", function () {
                //call function
function_in_js_file(example);
            });


问:
Compile separate files
In the case to have three files:

```<code>File1
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF

File2
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA

File3
    >TAIR:812_a
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

File4
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ

File5
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
</code>```

I wrote this code to extract the name of all sequences in the directory:

```<code>#!/usr/bin/env python
from Bio import SeqIO
filenames = ["file1","file2","file3"]
ids = []

for record in filenames:
    f = SeqIO.parse(record, 'fasta')
    ids.append(f.id)

print ids
</code>```

And the output is this:

```<code> python search_list.py
[<generator object parse at 0x7f32836018c0>, <generator object parse at 0x7f3283601910>, <generator object parse at 0x7f3283601960>]
</code>```

And the output that I expect is:

```<code>file_a
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

file_b
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

file_c
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
</code>```

Any suggestion to solve this opening the files in the list "ids" and compile them?

答:
You're getting that output because you're asking python to print an object, so it is just printing the memory address by default instead of the contents.
You might be better off just using the standard python open method (iterate through the list of files you want to examine). You can then iterate through each line in the file and add it to a list or whatever you like. Let me know if an example would be helpful.</p>

Title: Compile separate files

Body:
In the case to have three files:

File1
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF

File2
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA

File3
    >TAIR:812_a
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

File4
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ

File5
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

I wrote this code to extract the name of all sequences in the directory:

#!/usr/bin/env python
from Bio import SeqIO
filenames = ["file1","file2","file3"]
ids = []

for record in filenames:
    f = SeqIO.parse(record, 'fasta')
    ids.append(f.id)

print ids

And the output is this:

 python search_list.py
[<generator object parse at 0x7f32836018c0>, <generator object parse at 0x7f3283601910>, <generator object parse at 0x7f3283601960>]

And the output that I expect is:

file_a
    >TAIR:175_a
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:674_a
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA

file_b
    >TAIR:175_b
     ZZZLAALSKDJFALKSDJFL;KJEIURALKDJFNVALKSDJFKZZZ
    >TAIR:674_b
     ASLALKSDGHDJGDGSDDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:975_b
     KLJALSKDHGLAKSDHJFIEUROWASDLKGNIEASDFJKWERLJKJ
    >TAIR:444_b
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

file_c
    >TAIR:175_c
     ALSKDJFLKAHGLKASJDFLAKJSDLKGHALKSDHGALKALKSJDF
    >TAIR:812_c
     ASLALKSDGHLA;KSJDFIEURALKSDHGLANVALKSDJGHKLJA
    >TAIR:444_c
     QQALKSDJFWOIAOQIWUERTOIUQTOIUOQIWEURLASKDJFA

Any suggestion to solve this opening the files in the list "ids" and compile them?


问:
Using React-Native with a Web Application
I have installed Expo XDE, and created a new project funproject. I understand that the XDE is meant for devices and I could connect my virtual devices.

However, I would also like to reuse the same code base for a web application.

I have broused to the location on my localhost where the app should be.

http://localhost:19001/

This looks right, I can see the index.html page. It's actual file path is.

funproject\node_modules\react-native\local-cli\server\middleware\index.html

Here are the contents of the index.html

```<code><!DOCTYPE html>
<html>
<head>
  <title>React Native</title>
</head>
<body>
  <p>React Native packager is running.</p>
  <p><a href="http://facebook.github.io/react-native/">Visit documentation</a></p>
</body>
</html>
</code>```

So I added a div for the content and the script, app.js

```<code><!DOCTYPE html>
<html>
<head>
  <title>React Native</title>
</head>
<div id="content"></div>
<body>
  <p>React Native packager is running.</p>
  <p><a href="http://facebook.github.io/react-native/">Visit documentation</a></p>
</body>
</html>
<script type="text/javascript" src="../app.js"></script>
</code>```

I am new to react, but the idea that I can target web, and mobile all in one, is very enticing. Unfortunately this does not work! When I use chrome developer tools, I am getting this error for line 1 of app.js

Uncaught SyntaxError: Unexpected token import                      app.js:1

Here is the default generated app.js

```<code>import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

答:
You had it mostly wrong, actually -- all wrong.

Let's start with;

However, I would also like to reuse the same code base for a web application.

So this is wrong, the project you are working on is a native project, which uses the component based rendering logic of react, and produces real legit native ui elements for android or iOS.

Even though you are still using "react" this does not mean you can reuse the app in your browser.

The local server that started in a development interface, or a package delivery and update system (packager) for your phone or simulator (in order to access it via wifi network).

That server and the context of it is just a development tool for you.

You should first understand the logic behind tech you are using; https://facebook.github.io/react-native/docs/getting-started.html

Body:
I have installed Expo XDE, and created a new project funproject. I understand that the XDE is meant for devices and I could connect my virtual devices.

However, I would also like to reuse the same code base for a web application.

I have broused to the location on my localhost where the app should be.

http://localhost:19001/

This looks right, I can see the index.html page. It's actual file path is.

funproject\node_modules\react-native\local-cli\server\middleware\index.html

Here are the contents of the index.html

<!DOCTYPE html>

  <title>React Native</title>

React Native packager is running.

Visit documentation

So I added a div for the content and the script, app.js

<!DOCTYPE html>

  <title>React Native</title>

React Native packager is running.

Visit documentation

I am new to react, but the idea that I can target web, and mobile all in one, is very enticing. Unfortunately this does not work! When I use chrome developer tools, I am getting this error for line 1 of app.js

Uncaught SyntaxError: Unexpected token import                      app.js:1

Here is the default generated app.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


问:
UWP: WebView on Raspberry in english and not german
I'm developing an UWP for desktop, mobile and IOT (Raspberry) devices. It runs perfectly on every device. But on the Raspberry I have the problem, that the webview olways opens the english site of our company website.

At the configuration of the Windows IOT on the Raspberry I've set the language and the keyboard to German.

So I don't know why it doesn't work.

As an workaround I'll try to set the website-open-language of the webview to german. But I don't find such a property.

Has anyone a solution for my problem?

答: You could use the "Accept-Language" header using NavigateWithHttpRequestMessage and send along e.g "de-DE" (I think this is the right ISO code for for German) and see if that resolves the problem


问:
My C# grading program keep outputting the same result
I just started C# and was making this very simple C# program to print a grade according to the inputed marks.

Here's my program:

```<code>    class data
{

    int marks;
    public void input()
    {
        Console.WriteLine("Enter your marks");
        marks = Convert.ToInt16(Console.ReadLine());

    }

    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks < 55)
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");

    }
}
}
</code>```

And here's the main:

```<code> class Program
{
    static void Main(string[] args)
    {
        data obj1 = new data();
        obj1.input();
        obj1.output();
        Console.ReadLine();

    }
}
}
</code>```

Problem is it keeps outputting "Distinction" as the grade no matter what input I give. What am I doing wrong?

Edit - Fail marks is below 40

答:
You have failed to use proper ranges; since the marks < 75 block comes before marks < 65 block, and for all cases where marks <65 (and so on) are also true for marks < 75, your code will always stop at marks < 75 and thus output Distinction.

Not seeing an obvious reason it won't output Merit for properly high values, however

Body:
I just started C# and was making this very simple C# program to print a grade according to the inputed marks.

Here's my program:

    class data
{

    int marks;
    public void input()
    {
        Console.WriteLine("Enter your marks");
        marks = Convert.ToInt16(Console.ReadLine());

    }

    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks < 55)
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");

    }
}
}

And here's the main:

 class Program
{
    static void Main(string[] args)
    {
        data obj1 = new data();
        obj1.input();
        obj1.output();
        Console.ReadLine();

    }
}
}

Problem is it keeps outputting "Distinction" as the grade no matter what input I give. What am I doing wrong?

Edit - Fail marks is below 40


问:
Hiding BottomNavigationBar not working with view set to a GridView
I am using this library to add a BottomNavigationBar to my Xamarin.Android project. I use the BottomBar.AttachShy(CoordinatorLayout, View, Bundle); method to hide the navigation bar when I begin to scroll, but it won't work with my GridView. I scroll the GridView, but the navigation bar persists. Does anyone know what I should do?

Below is my AXML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/myCoordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

  <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnWidth="100dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
        android:textAlignment="center"
        android:id="@+id/menuGrid" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Here is my C# code:

```<code>private BottomBar _bottomBar;

protected override void OnCreate(Bundle bundle) {
     _bottomBar = BottomBar.AttachShy((CoordinatorLayout)FindViewById(Resource.Id.myCoordinator),
                  FindViewById(Resource.Id.menuGrid), bundle);
     _bottomBar.UseFixedMode();

     _bottomBar.SetItems(new[]
               { new BottomBarTab(Resource.Drawable.ic_recents, "Recents"),
                 new BottomBarTab(Resource.Drawable.ic_favorites, "Favorites"),
                 new BottomBarTab(Resource.Drawable.ic_nearby, "Nearby")
               });
     _bottomBar.MapColorForTab(0, "#7B1FA2");
     _bottomBar.MapColorForTab(1, "#FF5252");
     _bottomBar.MapColorForTab(2, "#FF9800");
}
</code>```

答: I fixed this issue for anyone that comes to this post. I had to replace the GridView with a RecyclerView. You will have to implement an Adapter to do this. I used this resource to implement my RecyclerView.

Body:
I am using this library to add a BottomNavigationBar to my Xamarin.Android project. I use the BottomBar.AttachShy(CoordinatorLayout, View, Bundle); method to hide the navigation bar when I begin to scroll, but it won't work with my GridView. I scroll the GridView, but the navigation bar persists. Does anyone know what I should do?

Below is my AXML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/myCoordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

  <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnWidth="100dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
        android:textAlignment="center"
        android:id="@+id/menuGrid" />

</android.support.design.widget.CoordinatorLayout>

Here is my C# code:

private BottomBar _bottomBar;

protected override void OnCreate(Bundle bundle) {
     _bottomBar = BottomBar.AttachShy((CoordinatorLayout)FindViewById(Resource.Id.myCoordinator),
                  FindViewById(Resource.Id.menuGrid), bundle);
     _bottomBar.UseFixedMode();

     _bottomBar.SetItems(new[]
               { new BottomBarTab(Resource.Drawable.ic_recents, "Recents"),
                 new BottomBarTab(Resource.Drawable.ic_favorites, "Favorites"),
                 new BottomBarTab(Resource.Drawable.ic_nearby, "Nearby")
               });
     _bottomBar.MapColorForTab(0, "#7B1FA2");
     _bottomBar.MapColorForTab(1, "#FF5252");
     _bottomBar.MapColorForTab(2, "#FF9800");
}


问:
Delete NuGet packages from Visual Studio Online Package Feed instead of Unlist
Is it possible to delete NuGet packages from a Visual Studio Online package feed?

I've setup CI on Visual Studio Online using the Build Tasks for a dotnet core project.

One of the steps is to pack all the projects in the solution as NuGet packages and push these to the package feed.

The build is working fine, however in my first attempt in the pack and push build steps I used a **/.csproj wildcard instead of src/**/.csproj. So it packed and pushed all my test projects too that were under tests/**.

I'd like to delete these packages from the feed. The only option I could find in the UI was to unlist the packages. But the packages still exist after this operation.

I also tried to delete the packages through the CLI: nuget delete. But it just does the same as unlist.

Has anyone been able to delete their packages?

答:
Yes, this is possible out-of-the-box with VSTS' Package Management. Note that there is a difference between unlisting and deleting, which I'll elaborate on further.

The TL;DR story for deleting existing packages from VSTS Package Management is that you must be the 'owner' of a package OR have a 'Project Admin'-like role in order to delete it. To unlist a package, you only require the 'contributor' role. For both options, simply go the package details in VSTS and select the appropriate option from the menu under the ellipses:

Now for some background info which might be useful. There is some official documentation available on visualstudio.com:

There are two options available to remove a version of a NuGet package from a feed.

Unlist: unlisting a version of a package modifies how the package appears in NuGet clients (see the NuGet docs for a full description of how unlist works). Unlisting a version can help you prevent new usage of it without breaking dependent projects and builds.

Delete: Deleting a version of a package makes it permanently unavailable for install or restore.

Unlist and delete both respect feed immutability. Once you publish a particular version of a package to a feed, that version number is permanently reserved. You cannot upload a newer revision package with that same version number, or delete it and upload a new package at the same version.

The important part here is "feed immutability", which according to the canon, translates to:

Once you publish a particular version of a package to a feed, that version number is permanently reserved. You cannot upload a newer revision package with that same version number, or delete it and upload a new package at the same version.

The documentation also confirms, as a footnote at the bottom, what you already discovered about nuget.exe:

Currently, NuGet.exe can only unlist packages; Team Services and TFS interpret nuget.exe delete as an unlist operation to be consistent with NuGet.org. To delete a package, you must use either the REST APIs or the web interface.

Doing it programatically should therefor either be done through the REST API or the VSTS admin section, as described above. NuGet.exe can only be used for unlisting - not deleting.

With all of that taken into consideration, with VSTS you can delete packages but - as always - think twice before you do so. Remember the LeftPad debacle? ;)


问:
IPv6 filter in Scapy
I am using scapy to sniff a IPv6 packet with a specific source ip /dest ip.

Example:

```<code>filter1 ="tcp port "+`port`+ " and ip6 host 2001::4 and tcp[tcpflags] & tcp-syn !=0 and !icmp and !arp and not host "+host_ip

            a= sniff(count =1,filter=filter1,iface=eth)
</code>```

This throws an exception as shown below:
scapy.error.Scapy_Exception: Filter parse error

答:
I've never used scapy, but I noticed in your filter1 expression that you have:

```<code>+`port`+
</code>```

... yet you have:

```<code>+host_ip
</code>```

Maybe you need the back-tiks around the host_ip?

If that's not the problem, you can also try to validate capture filters using tools such as tcpdump, e.g., tcpdump -d ${filter1} or dumpcap, e.g., dumpcap -d ${filter1} before attempting to use them in scapy.

Title: IPv6 filter in Scapy

Body:
I am using scapy to sniff a IPv6 packet with a specific source ip /dest ip.

Example:

filter1 ="tcp port "+`port`+ " and ip6 host 2001::4 and tcp[tcpflags] & tcp-syn !=0 and !icmp and !arp and not host "+host_ip

            a= sniff(count =1,filter=filter1,iface=eth)

This throws an exception as shown below:
scapy.error.Scapy_Exception: Filter parse error

Body:
I've never used scapy, but I noticed in your filter1 expression that you have:

+`port`+

... yet you have:

+host_ip

Maybe you need the back-tiks around the host_ip?

If that's not the problem, you can also try to validate capture filters using tools such as tcpdump, e.g., tcpdump -d ${filter1} or dumpcap, e.g., dumpcap -d ${filter1} before attempting to use them in scapy.


问:
403 Forbidden error when making an ajax Post request in Django framework
I am trying to integrate jquery into a web application I am making with Django framework. I am however having a hard time trying to make a simple ajax call to work. My template file that contains the form html and javascript to handle the ajax call looks like:

```<code><script type="text/javascript">
$(document).ready(function() {
$( "#target" ).submit(function() {
console.log('Form was submitted');
$.ajax({
        type: "POST",
        url: "/hello/",  // or just url: "/my-url/path/"
        data: {
            query: $( "#query" ).val()
        },
        success: function(data) {
            console.log(data);
        }
    });
return false;
  });
  })
</script>
<form id="target" action="." method="post">{% csrf_token %}
 <input id= "query" type="text" value="Hello there">
 <input type="submit" value="Search Recent Tweets">
</form>
</code>```

My views.py that is supposed to handle the ajax call looks like:

```<code> from django.core.context_processors import csrf
 from django.shortcuts import render_to_response
 from django.template.loader import get_template
 from django.template import Context,RequestContext
 from django.views.decorators.csrf import ensure_csrf_cookie
 from django.http import HttpResponse

 # access resource
 def hello(request):
  c = {}
  c.update(csrf(request))
  if request.is_ajax():
        t = get_template('template.html')
        #html = t.render(Context({'result': 'hello world'}))
        con = RequestContext(request, {'result': 'hello world'})
        return render_to_response('template.html', c, con)
  else:
        return HttpResponse('Not working!')
</code>```

I have tried to follow the official documentation on Cross-Site Request Forgery Protection and also looked at several stackoverflow questions addressing a similar problem. I have included the {% csrf_token %} in my html template file but it still doesn't seem to be working. I get an error in the console suggesting that the ajax call failed:

```<code>POST http://127.0.0.1:8000/hello/ 403 (FORBIDDEN)
</code>```

How do I pass the result variable along with my http response and get the ajax call to work smoothly? Any help is deeply appreciated.

Edit-1

I wasn't supposedly passing the csrf token along with my post request. SO as per the documentation I added the following code to my template javascript:

```<code>function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken);

//Ajax call
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
</code>```

When I refresh the template html page in the browser, I get null in the console, suggesting that the cookie is not set or not defined. What am I missing?

答:
Try including this decorator on your dispatch code</p>

```<code>from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
def dispatch(self, request, *args, **kwargs):
     return super(LessonUploadWorkView,self).dispatch(request,*args,**kwargs)
</code>```

Body:
I am trying to integrate jquery into a web application I am making with Django framework. I am however having a hard time trying to make a simple ajax call to work. My template file that contains the form html and javascript to handle the ajax call looks like:

<form id="target" action="." method="post">{% csrf_token %}
 <input id= "query" type="text" value="Hello there">
 <input type="submit" value="Search Recent Tweets">
</form>

My views.py that is supposed to handle the ajax call looks like:

 from django.core.context_processors import csrf
 from django.shortcuts import render_to_response
 from django.template.loader import get_template
 from django.template import Context,RequestContext
 from django.views.decorators.csrf import ensure_csrf_cookie
 from django.http import HttpResponse

 # access resource
 def hello(request):
  c = {}
  c.update(csrf(request))
  if request.is_ajax():
        t = get_template('template.html')
        #html = t.render(Context({'result': 'hello world'}))
        con = RequestContext(request, {'result': 'hello world'})
        return render_to_response('template.html', c, con)
  else:
        return HttpResponse('Not working!')

I have tried to follow the official documentation on Cross-Site Request Forgery Protection and also looked at several stackoverflow questions addressing a similar problem. I have included the {% csrf_token %} in my html template file but it still doesn't seem to be working. I get an error in the console suggesting that the ajax call failed:

POST http://127.0.0.1:8000/hello/ 403 (FORBIDDEN)

How do I pass the result variable along with my http response and get the ajax call to work smoothly? Any help is deeply appreciated.

Edit-1

I wasn't supposedly passing the csrf token along with my post request. SO as per the documentation I added the following code to my template javascript:

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken);

//Ajax call
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

When I refresh the template html page in the browser, I get null in the console, suggesting that the cookie is not set or not defined. What am I missing?

Body:
Try including this decorator on your dispatch code

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
def dispatch(self, request, *args, **kwargs):
     return super(LessonUploadWorkView,self).dispatch(request,*args,**kwargs)


问:
Error "'git' is not recognized as an internal or external command"

I have an installation of Git for Windows, but when I try to use the git command in Command Prompt, I get the following error:

'git' is not recognized as an internal or external command,
operable program or batch file.
```

How do I fix this problem?

答:
You may not have set your PATH correctly to point at your Git installation.

You need to add the following paths to PATH:

C:\Program Files\Git\bin\

C:\Program Files\Git\cmd\

And check that these paths are correct. You may have Git installed on a different drive, or under Program Files (x86). Correct the paths if necessary.

Modifying PATH on Windows 10:

In the Start Menu or taskbar search, search for "environment variable".

Select "Edit the system environment variables".

Click the "Environment Variables" button at the bottom.

Double-click the "Path" entry under "System variables".

With the "New" button in the PATH editor, add C:\Program Files\Git\bin\ and C:\Program Files\Git\cmd\ to the end of the list.

Close and re-open your console.

Modifying PATH on Windows 7:

Right-click "Computer" on the Desktop or Start Menu.

Select "Properties".

On the very far left, click the "Advanced system settings" link.

Click the "Environment Variables" button at the bottom.

Double-click the "Path" entry under "System variables".

At the end of "Variable value", insert a ; if there is not already one, and then C:\Program Files\Git\bin\;C:\Program Files\Git\cmd\. Do not put a space between ; and the entry.

Close and re-open your console.

If these instructions weren't helpful, feel free to look at some others:

How to set the path and environment variables in Windows (Computer Hope)

How to edit your system PATH for easy command line access in Windows (How-To Geek)

How to set Path environment variables in Windows 10 (Addictive Tips)

What are PATH and other environment variables, and how can I set or use them? (Super User)

ContentLicense: CC BY-SA 4.0

Body:
I have an installation of Git for Windows, but when I try to use the git command in Command Prompt, I get the following error:

'git' is not recognized as an internal or external command,
operable program or batch file.

How do I fix this problem?


问:
how to get innerHTML value in javascript code
I want to change table  data by using innerHTML property. But after applying innerHTML property those values set in  are not accessible in Javascript code.

So is there any alternative to innerHTML property so that value can be set in  and it can also be accessed in Javascript Code.

Javascript code

```<code><script>
    var row=0,col=0,i=1;//can be used in loop

    document.getElementById("tableID").rows[row].cells[col].innerHTML=i;
</script>
</code>```

答:
your code is wrong here

.rows[row].cells[col]

This is what i suggest:
set an id for each cell, something like col1row1 as id, then access the cell by id:

```<code>document.getElementById("col1row1").innerHTML = i
</code>```

or have a for loop go through each row and cell with getElementsByType('td').innerHTML = i for example

take a look at this :
Iterating through a table with JS

Body:
your code is wrong here

.rows[row].cells[col]

This is what i suggest:
set an id for each cell, something like col1row1 as id, then access the cell by id:

document.getElementById("col1row1").innerHTML = i

or have a for loop go through each row and cell with getElementsByType('td').innerHTML = i for example

take a look at this :
Iterating through a table with JS


问:
strange behaviour when populating a select list in razor
I'm populating a select list using razor and its giving me some strange results.  The items in the list contain spaces, the text created is ok, but the value has been split into sections for each word in the text description.  Here's my razor code

<select name="fromReport[]" id="multiselectReport" class="form-control" size="15" multiple="multiple">
                                                        @foreach (var item in Model.AvailableReports)
                                                        {
                                                            <option value=@item>@item</option>
                                                        }
                                                    </select>```
</div>
</div>
</p>

<p>and the resulting HTML</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-html lang-html prettyprint-override"><code><select id="multiselect_toRpt" class="form-control" name="toReport[]" size="15" multiple="multiple">
<option value="All" trades="" activity="" last="" week="">All Trades Activity Last Week</option>
<option value="All" trades="" for="" delivery="" last="" month="">All Trades For Delivery Last Month</option>
<option value="Energy" costs="" report="">Energy Costs Report</option>
</select></code>```

so its created a section in the definition for each word in the text, why is this ?

答:
figured it out

@foreach (var item in Model.AvailableReports)
                                                        {
                                                            <option value="@item">@item</option>
                                                        }```

Body:
I'm populating a select list using razor and its giving me some strange results.  The items in the list contain spaces, the text created is ok, but the value has been split into sections for each word in the text description.  Here's my razor code

<select name="fromReport[]" id="multiselectReport" class="form-control" size="15" multiple="multiple">
                                                        @foreach (var item in Model.AvailableReports)
                                                        {
                                                            <option value=@item>@item</option>
                                                        }
                                                    </select>

and the resulting HTML

<select id="multiselect_toRpt" class="form-control" name="toReport[]" size="15" multiple="multiple">
<option value="All" trades="" activity="" last="" week="">All Trades Activity Last Week</option>
<option value="All" trades="" for="" delivery="" last="" month="">All Trades For Delivery Last Month</option>
<option value="Energy" costs="" report="">Energy Costs Report</option>
</select>

so its created a section in the definition for each word in the text, why is this ?


答:
Your problem is that your second if statement, (marks < 75) includes all the statements below it. For example, if marks < 75 is correct, then that statement will run, and no other statements will be checked like marks < 65 or marks < 55 because marks < 75 includes them. You need to do:</p>

```<code>if (marks >= 75){
    Console.WriteLine("Merit");
}else if (marks < 55){
    Console.WriteLine("Pass");
}else if (marks < 65){
    Console.WriteLine("Credit");
}else if (marks < 75){
    Console.WriteLine("Distiction");
}else
    Console.WriteLine("Fail");
</code>```

Title: My C# grading program keep outputting the same result

Body:
Your problem is that your second if statement, (marks < 75) includes all the statements below it. For example, if marks < 75 is correct, then that statement will run, and no other statements will be checked like marks < 65 or marks < 55 because marks < 75 includes them. You need to do:

if (marks >= 75){
    Console.WriteLine("Merit");
}else if (marks < 55){
    Console.WriteLine("Pass");
}else if (marks < 65){
    Console.WriteLine("Credit");
}else if (marks < 75){
    Console.WriteLine("Distiction");
}else
    Console.WriteLine("Fail");


问:
React.js passing props between separate children via a single parent
I have a front end console that I'm trying to make in react that uses a side menu to filter results from a database that are displayed in a dynamically generated table.

The hierarchy of components is as follows:

```<code>App.js
|
|--SideMenu.js
|--ResultsTable.js
</code>```

So I understand that the parent has access to props in the child components and that it can also pass props to its children too. What I'm trying to do is to get the sidemenu to speak to the results table via the parent App.js (unless there's a way to get the children to communicate directly?) and update the table accordingly however I've encountered a strange problem. When I click the filter or reset button (in SideMenu.js), there is a delay of props being picked up in the results table component that requires me to click the buttons 2 or 3 times before it registers. I'm sure the solution is simple but so far it has eluded me. I think the problem occurs when App.js is passing the new props back down to ResultTable.js but I'm not entirely sure how to fix it.

Here is my code for the SideMenu.js

```<code>export default class SideMenu extends React.Component{

    constructor(){
        super();

        this.state={

            serviceParam: '',
            filterParam: '',
            services: [],
        }

        this.handleServiceChoice = this.handleServiceChoice.bind(this);
        this.handleSearch = this.handleSearch.bind(this);
        this.getServices = this.getServices.bind(this);
        this.handleReset = this.handleReset.bind(this);

    }

    componentWillMount(){

        this.getServices();
    }

    getServices(){
        const _this =this;
        let servicesData;

        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/services";

        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                servicesData = data;

                console.log("servicesData");
                console.log(servicesData);

                _this.setState({
                    services: servicesData
                });
            });
    }

    handleReset(){
        this.setState({
            serviceParam: null,
            filterParam: null,
        });

        let dropdownArrow = document.createElement("i");
        dropdownArrow.setAttribute("class", "material-icons right");
        dropdownArrow.innerHTML = "keyboard_arrow_down";
        document.getElementById("serviceDisplay").innerHTML = "Services";
        document.getElementById("serviceDisplay").appendChild(dropdownArrow);

        this.props.filterCallback(this.state.serviceParam);
    }

    handleSearch(){

        if(document.getElementById('search').value && this.state.serviceParam){
            let filterParam = "&search="+document.getElementById('search').value;
            console.log('In child - search 1');
            console.log(filterParam);

            let parentProps;
            parentProps= this.state.serviceParam+filterParam;
            this.props.filterCallback(parentProps);
        } else if (document.getElementById('search').value){
            let filterParam = "?search="+document.getElementById('search').value;
            console.log('In child - search 2');
            console.log(filterParam);

            let parentProps;
            parentProps=filterParam;
            this.props.filterCallback(parentProps);
        } else{
            let filterParam = this.state.serviceParam;
            console.log('In child - search 3');
            console.log(filterParam);

            let parentProps;
            parentProps=filterParam;
            this.props.filterCallback(parentProps);
        }

    }

    handleServiceChoice(e){
        console.log('sidebar target id');
        console.log(e.target.id);

        let serviceParam;
        let dropdownArrow = document.createElement("i");
        dropdownArrow.setAttribute("class", "material-icons right");
        dropdownArrow.innerHTML = "keyboard_arrow_down";
        document.getElementById("serviceDisplay").innerHTML = e.target.id;
        document.getElementById("serviceDisplay").appendChild(dropdownArrow);

        serviceParam = '?service='+e.target.id ;

        this.setState({
            serviceParam: serviceParam,
        });

    }

    render(){
        return(

            <ul className="side-nav fixed blue accent-1">
                <li className="logo"></li>

                <li>
                    <a id="serviceDisplay" href="#" className="dropdown-button waves-effect" data-activates="services">Services<i className="material-icons right">keyboard_arrow_down</i></a>

                        <ul id="services" className="dropdown-content">
                            {this.state.services.map((dropdown)=>{
                                return(
                                    <li key={dropdown.service}>
                                        <a id={dropdown.service} href="#" className="waves-effect" onClick={this.handleServiceChoice}>{dropdown.service}</a>
                                    </li>
                                );
                            })}
                        </ul>

                </li>

                <li className="bold"><a href="#">Supplier ID Search</a></li>
                <li className="search">
                    <div className="container center-align">
                        <input id="search" type="text" placeholder="Enter ID here" className="validate blue accent-2"></input>

                        <button className="btn blue accent-2 waves-effect" type="submit" onClick={this.handleSearch}>
                            Filter
                            <i className="material-icons right">search</i>
                        </button>
                    </div>
                </li>
                <li >
                    <div className="container center-align">
                        <button className="btn blue accent-2 waves-effect" type="submit" onClick={this.handleReset}>
                            Reset Logs
                            <i className="material-icons right">autorenew</i>
                        </button>
                    </div>
                </li>

            </ul>
        );

    };
}
</code>```

And the ResultsTable.js:

```<code>export default class ResultsTable extends React.Component{

    constructor(){
        super();
        this.state = {
            logs: [],
            xml: '',
            render_xml: false,
        }

        this.ResultsTable = this.ResultsTable.bind(this);
        this.handleRequestXML = this.handleRequestXML.bind(this);
        this.handleResponseXML = this.handleResponseXML.bind(this);
        this.returnToLogs = this.returnToLogs.bind(this);
        this.renderTable = this.renderTable.bind(this);
        this.renderXml = this.renderXml.bind(this);
    }

    componentWillMount(){
        console.log('Child - In componentWillMount!');
        this.ResultsTable();

    }

    componentWillReceiveProps(){
        console.log('Child - In componentWillReceiveProps!');
        console.log(this.props.filter);

        this.ResultsTable();
    }

    returnToLogs(){
        this.setState({
            render_xml:false
        });
    }

    handleResponseXML(e){
        const _this =this;

        _this.setState({
            render_xml: true,
        });

        let id_param = '?_id='+e.target.id+'&type=response';
        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/xml"+id_param;
        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                let xml = data;

                console.log("xml");
                console.log(xml);

                _this.setState({
                    xml: xml,
                });

            });
    }

    handleRequestXML(e){
        const _this =this;

        _this.setState({
            render_xml: true,
        });

        let id_param = '?_id='+e.target.id+'&type=request';
        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/xml"+id_param;
        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                let xml = data;

                console.log("xml");
                console.log(xml);

                _this.setState({
                    xml: xml,
                });
            });
    }

    ResultsTable(){
        console.log('Child - In ResultsTable!');
        console.log(this.props.filter);

        const _this =this;
        let logData;

        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/logs";

        if(this.props.filter){
            console.log('Child - Service Choice!');
            console.log(this.props.filter);
            url +=this.props.filter;
        }

        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                logData = data;

                console.log("logData");
                console.log(logData);

                _this.setState({
                    logs: logData
                });
            });

    }

    renderTable(){
        console.log('In renderTable!');
        return (

            <table className="highlight">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Created</th>
                        <th>Last Changed</th>
                        <th>Service</th>
                        <th>Supplier Identifier</th>
                        <th>Request XML</th>
                        <th>Response XML</th>
                    </tr>

                </thead>
                <tbody>
                {this.state.logs.map((log)=>{
                    return(
                        <tr key={log._id}>
                            <td>{log._id}</td>
                            <td>{log.created}</td>
                            <td>{log.last_changed}</td>
                            <td>{log.service}</td>
                            <td>{log.supplier_identifier}</td>
                            <td><a id={log._id} onClick={this.handleRequestXML} href='#'>Click for XML</a></td>
                            <td><a id={log._id} onClick={this.handleResponseXML} href='#'>Click for XML</a></td>
                        </tr>
                    );
                })}

                </tbody>

            </table>

        );
    }

    renderXml(){
        console.log("In renderXml");
        return(
            <div className="card-panel">
                {this.state.xml}
                <hr/>
                <a className="waves-effect btn blue accent-2" onClick={this.returnToLogs}>Back to logs</a>
            </div>

        );
    }

    render(){
        if(this.state.render_xml){
            return this.renderXml();
        } else {
            return this.renderTable();
        }
    }
}
</code>```

And here is the parent App.js component

```<code>export default class App extends React.Component{

    constructor(){
        super();
        this.state = {
            filter: null,
        }

        this.handleFilterParam = this.handleFilterParam.bind(this);
    }

    handleFilterParam(filter){
        console.log('In parent - handleSearchParam');
        console.log(filter);
        this.setState({
            filter: filter
        });
    }

    render(){
        console.log('In parent - render');
        console.log(this.state.filter);

        return (
            <div className="row">

                <div className="col s4 l3">
                    <SideMenu
                        filterCallback={this.handleFilterParam}
                    />
                </div>
                <div className="col s12 l9">
                    <Header />
                    <ResultsTable filter={this.state.filter}/>
                </div>

            </div>

        );
    }
}
</code>```

I'm still quite new to React and ES6 so apologies in advance if some of this seems quite amateurish.

答:
I found a pretty simply solution to my problem in case anyone is wondering and viewing this question. I was using this lifecycle method before but didn't quite understand it until now.

So, in my ResultsTable component, I added this code to 'listen' for new props and update accordingly:

```<code>componentWillReceiveProps(nextProps) {
        if(this.props != nextProps) {
            this.props = nextProps;
            this.handleResultsTable();
        }
    }
</code>```

Body:
I have a front end console that I'm trying to make in react that uses a side menu to filter results from a database that are displayed in a dynamically generated table.

The hierarchy of components is as follows:

App.js
|
|--SideMenu.js
|--ResultsTable.js

So I understand that the parent has access to props in the child components and that it can also pass props to its children too. What I'm trying to do is to get the sidemenu to speak to the results table via the parent App.js (unless there's a way to get the children to communicate directly?) and update the table accordingly however I've encountered a strange problem. When I click the filter or reset button (in SideMenu.js), there is a delay of props being picked up in the results table component that requires me to click the buttons 2 or 3 times before it registers. I'm sure the solution is simple but so far it has eluded me. I think the problem occurs when App.js is passing the new props back down to ResultTable.js but I'm not entirely sure how to fix it.

Here is my code for the SideMenu.js

export default class SideMenu extends React.Component{

    constructor(){
        super();

        this.state={

            serviceParam: '',
            filterParam: '',
            services: [],
        }

        this.handleServiceChoice = this.handleServiceChoice.bind(this);
        this.handleSearch = this.handleSearch.bind(this);
        this.getServices = this.getServices.bind(this);
        this.handleReset = this.handleReset.bind(this);

    }

    componentWillMount(){

        this.getServices();
    }

    getServices(){
        const _this =this;
        let servicesData;

        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/services";

        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                servicesData = data;

                console.log("servicesData");
                console.log(servicesData);

                _this.setState({
                    services: servicesData
                });
            });
    }

    handleReset(){
        this.setState({
            serviceParam: null,
            filterParam: null,
        });

        let dropdownArrow = document.createElement("i");
        dropdownArrow.setAttribute("class", "material-icons right");
        dropdownArrow.innerHTML = "keyboard_arrow_down";
        document.getElementById("serviceDisplay").innerHTML = "Services";
        document.getElementById("serviceDisplay").appendChild(dropdownArrow);

        this.props.filterCallback(this.state.serviceParam);
    }

    handleSearch(){

        if(document.getElementById('search').value && this.state.serviceParam){
            let filterParam = "&search="+document.getElementById('search').value;
            console.log('In child - search 1');
            console.log(filterParam);

            let parentProps;
            parentProps= this.state.serviceParam+filterParam;
            this.props.filterCallback(parentProps);
        } else if (document.getElementById('search').value){
            let filterParam = "?search="+document.getElementById('search').value;
            console.log('In child - search 2');
            console.log(filterParam);

            let parentProps;
            parentProps=filterParam;
            this.props.filterCallback(parentProps);
        } else{
            let filterParam = this.state.serviceParam;
            console.log('In child - search 3');
            console.log(filterParam);

            let parentProps;
            parentProps=filterParam;
            this.props.filterCallback(parentProps);
        }

    }

    handleServiceChoice(e){
        console.log('sidebar target id');
        console.log(e.target.id);

        let serviceParam;
        let dropdownArrow = document.createElement("i");
        dropdownArrow.setAttribute("class", "material-icons right");
        dropdownArrow.innerHTML = "keyboard_arrow_down";
        document.getElementById("serviceDisplay").innerHTML = e.target.id;
        document.getElementById("serviceDisplay").appendChild(dropdownArrow);

        serviceParam = '?service='+e.target.id ;

        this.setState({
            serviceParam: serviceParam,
        });

    }

    render(){
        return(

                    Serviceskeyboard_arrow_down

                            {this.state.services.map((dropdown)=>{
                                return(

                                        {dropdown.service}

                                );
                            })}

Supplier ID Search

                        <input id="search" type="text" placeholder="Enter ID here" className="validate blue accent-2"></input>

                        <button className="btn blue accent-2 waves-effect" type="submit" onClick={this.handleSearch}>
                            Filter
                            search
                        </button>

                        <button className="btn blue accent-2 waves-effect" type="submit" onClick={this.handleReset}>
                            Reset Logs
                            autorenew
                        </button>

        );

    };
}

And the ResultsTable.js:

export default class ResultsTable extends React.Component{

    constructor(){
        super();
        this.state = {
            logs: [],
            xml: '',
            render_xml: false,
        }

        this.ResultsTable = this.ResultsTable.bind(this);
        this.handleRequestXML = this.handleRequestXML.bind(this);
        this.handleResponseXML = this.handleResponseXML.bind(this);
        this.returnToLogs = this.returnToLogs.bind(this);
        this.renderTable = this.renderTable.bind(this);
        this.renderXml = this.renderXml.bind(this);
    }

    componentWillMount(){
        console.log('Child - In componentWillMount!');
        this.ResultsTable();

    }

    componentWillReceiveProps(){
        console.log('Child - In componentWillReceiveProps!');
        console.log(this.props.filter);

        this.ResultsTable();
    }

    returnToLogs(){
        this.setState({
            render_xml:false
        });
    }

    handleResponseXML(e){
        const _this =this;

        _this.setState({
            render_xml: true,
        });

        let id_param = '?_id='+e.target.id+'&type=response';
        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/xml"+id_param;
        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                let xml = data;

                console.log("xml");
                console.log(xml);

                _this.setState({
                    xml: xml,
                });

            });
    }

    handleRequestXML(e){
        const _this =this;

        _this.setState({
            render_xml: true,
        });

        let id_param = '?_id='+e.target.id+'&type=request';
        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/xml"+id_param;
        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                let xml = data;

                console.log("xml");
                console.log(xml);

                _this.setState({
                    xml: xml,
                });
            });
    }

    ResultsTable(){
        console.log('Child - In ResultsTable!');
        console.log(this.props.filter);

        const _this =this;
        let logData;

        let url = "http://mydevsite.ie/cgi-bin/log-queries/api/logs";

        if(this.props.filter){
            console.log('Child - Service Choice!');
            console.log(this.props.filter);
            url +=this.props.filter;
        }

        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){

                logData = data;

                console.log("logData");
                console.log(logData);

                _this.setState({
                    logs: logData
                });
            });

    }

    renderTable(){
        console.log('In renderTable!');
        return (

                        ID
                        Created
                        Last Changed
                        Service
                        Supplier Identifier
                        Request XML
                        Response XML

                {this.state.logs.map((log)=>{
                    return(

                            {log._id}
                            {log.created}
                            {log.last_changed}
                            {log.service}
                            {log.supplier_identifier}
                            Click for XML
                            Click for XML

                    );
                })}

        );
    }

    renderXml(){
        console.log("In renderXml");
        return(

                {this.state.xml}

                Back to logs

        );
    }

    render(){
        if(this.state.render_xml){
            return this.renderXml();
        } else {
            return this.renderTable();
        }
    }
}

And here is the parent App.js component

export default class App extends React.Component{

    constructor(){
        super();
        this.state = {
            filter: null,
        }

        this.handleFilterParam = this.handleFilterParam.bind(this);
    }

    handleFilterParam(filter){
        console.log('In parent - handleSearchParam');
        console.log(filter);
        this.setState({
            filter: filter
        });
    }

    render(){
        console.log('In parent - render');
        console.log(this.state.filter);

        return (

                    <SideMenu
                        filterCallback={this.handleFilterParam}
                    />

                    <ResultsTable filter={this.state.filter}/>

        );
    }
}

I'm still quite new to React and ES6 so apologies in advance if some of this seems quite amateurish.

Body:
I found a pretty simply solution to my problem in case anyone is wondering and viewing this question. I was using this lifecycle method before but didn't quite understand it until now.

So, in my ResultsTable component, I added this code to 'listen' for new props and update accordingly:

componentWillReceiveProps(nextProps) {
        if(this.props != nextProps) {
            this.props = nextProps;
            this.handleResultsTable();
        }
    }


问:
PhpStorm auto complete class methods
I have an abstract class that gets a container with a magic method to pick up the container DI, in a PHPDoc documentation block I'm going to describe the container's variables with the class, I'd like the PhpStorm voce covers the autocomplete functions.

```<code><?php
namespace App\Model;

use Slim\Container;

abstract class Model
{
    protected $container;

    /**
     * @var \Slim\Container $container
     * @var \PDO $conn1
     * @var \PDO $conn2
     * @var \App\Model\Contribuinte $contribuinte
     * @var \App\Model\Debito $debito
     * @var \App\Model\Endereco $endereco
     * @var \App\Model\Imagem $imagem
     * @var \App\Model\Sistema $sistema
     * @var \App\Model\Inspecao $inspecao
     */

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function __get($key)
    {
        if ($this->container->has($key)) {
            return $this->container->{$key};
        }
        return null;
    }
}
</code>```

for example

```<code><?php
namespace App\Model;

class Contribuinte extends Model
{
    public function list()
    {
        $this->conn1->prep ....
    }
}
</code>```

答:
Use @property in PHPDoc block for the class: https://phpdoc.org/docs/latest/references/phpdoc/tags/property.html

```<code>/**
 * My class description
 *
 * @property \PDO $conn1 Optional description here
 * @property \App\Model\Endereco $endereco
 * @property \App\Model\Imagem $imagem Optional description here
 */
abstract class Model
{
...
</code>```

Title: PhpStorm auto complete class methods

Body:
I have an abstract class that gets a container with a magic method to pick up the container DI, in a PHPDoc documentation block I'm going to describe the container's variables with the class, I'd like the PhpStorm voce covers the autocomplete functions.

<?php
namespace App\Model;

use Slim\Container;

abstract class Model
{
    protected $container;

    /**
     * @var \Slim\Container $container
     * @var \PDO $conn1
     * @var \PDO $conn2
     * @var \App\Model\Contribuinte $contribuinte
     * @var \App\Model\Debito $debito
     * @var \App\Model\Endereco $endereco
     * @var \App\Model\Imagem $imagem
     * @var \App\Model\Sistema $sistema
     * @var \App\Model\Inspecao $inspecao
     */

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function __get($key)
    {
        if ($this->container->has($key)) {
            return $this->container->{$key};
        }
        return null;
    }
}

for example

<?php
namespace App\Model;

class Contribuinte extends Model
{
    public function list()
    {
        $this->conn1->prep ....
    }
}

Body:
Use @property in PHPDoc block for the class: https://phpdoc.org/docs/latest/references/phpdoc/tags/property.html

/**
 * My class description
 *
 * @property \PDO $conn1 Optional description here
 * @property \App\Model\Endereco $endereco
 * @property \App\Model\Imagem $imagem Optional description here
 */
abstract class Model
{
...