问:
mongoose TypeError: Schema is not a constructor
I've encountered a strange thing. I have several mongoose models - and in one of them (only in one!) I get this error:

```<code>TypeError: Schema is not a constructor
</code>```

I find it very strange as I have several working schemas. I tried logging mongoose.Schema in the non-working schema and it is indeed different from the mongoose.Schema in my working schemas - how is that possible? The code is almost identical.
Here's the code for the non-working schema:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var errSchema = new Schema({
  name: String,
  images:[{
    type:String
  }],
  sizes:[{
    type: String
  }],
  colors:[{
    type: Schema.ObjectId,
    ref: 'Color'
  }],
  frontColors:[{
    type: Schema.ObjectId,
    ref: 'Color'
  }],
  script: Boolean
},{
  timestamps: true
});

var Err = mongoose.model('Err', errSchema);

module.exports = Err;
</code>```

Code for a working schema:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var colorSchema = new Schema({
  name: String,
  image: String,
  rgb: String,
  comment: String,
});

var Color = mongoose.model('Color', colorSchema);

module.exports = Color;
</code>```

Any help would be appreciated!

答:
I have encountered the same thing. I have previous code like this

```<code>    var mongoose = require('mongoose');
    var Schema = mongoose.Schema();
    var schema = new Schema({
        path : {type:string , required:true},
        title: {type:string , required: true}
    })
 module.export = mongoose.model('game', schema);
</code>```

Then I solved the constructor problem using below script

```<code>   var mongoose = require('mongoose');
    var schema = mongoose.Schema({
        path : {type:string , required:true},
        title: {type:string , required: true}
    })
 module.export = mongoose.model('game', schema);
</code>```

Body:
I've encountered a strange thing. I have several mongoose models - and in one of them (only in one!) I get this error:

TypeError: Schema is not a constructor

I find it very strange as I have several working schemas. I tried logging mongoose.Schema in the non-working schema and it is indeed different from the mongoose.Schema in my working schemas - how is that possible? The code is almost identical.
Here's the code for the non-working schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var errSchema = new Schema({
  name: String,
  images:[{
    type:String
  }],
  sizes:[{
    type: String
  }],
  colors:[{
    type: Schema.ObjectId,
    ref: 'Color'
  }],
  frontColors:[{
    type: Schema.ObjectId,
    ref: 'Color'
  }],
  script: Boolean
},{
  timestamps: true
});

var Err = mongoose.model('Err', errSchema);

module.exports = Err;

Code for a working schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var colorSchema = new Schema({
  name: String,
  image: String,
  rgb: String,
  comment: String,
});

var Color = mongoose.model('Color', colorSchema);

module.exports = Color;

Any help would be appreciated!

Body:
I have encountered the same thing. I have previous code like this

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema();
    var schema = new Schema({
        path : {type:string , required:true},
        title: {type:string , required: true}
    })
 module.export = mongoose.model('game', schema);

Then I solved the constructor problem using below script

   var mongoose = require('mongoose');
    var schema = mongoose.Schema({
        path : {type:string , required:true},
        title: {type:string , required: true}
    })
 module.export = mongoose.model('game', schema);


来源: stackexchange

问:
How do I utilize dot notation when rendering components?
I have a simple component which is supposed to render different kind of fields into my form component:

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

export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (
          <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>
          )
      }
      case 'text': {
        return (
          <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>
        )
      }
    }
  }
}
</code>```

And I'm using this component in my form component like this:

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

  render() {
    return (
        .
        .
        .
        <Field
          type="text"
          placeholder="something"
          name="something"
        />
        <Field
          type="textarea"
          placeholder="another"
          name="othername"
        />
        .
        .
        .
    )
  }
}
</code>```

What I have in mind is to somehow implement my field component to be able to use dot notation as explained in Using Dot Notation for JSX components which I have seen many other libraries and I want to be able to use this component like this:

```<code><Field.Text name="sth" placeholder="sth" />
<Field.TextArea name="other" placeholder="other stuff" />
</code>```

But I can't do it the way mentioned in React docs. How can I do this?

答:
```<code>export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (
          <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>
          )
      }
      case 'text': {
        return (
          <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>
        )
      }
    }
  }
}
</code>```

chnage this as following way

```<code>const Field = {
    text: function(){
      // your text code
    }
}

export default Field;
</code>```

Same way they have mentioned in the facebook react docs. Instead of component you can return object which contain your functions.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple component which is supposed to render different kind of fields into my form component:

import React from "react";

export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (

            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>

          )
      }
      case 'text': {
        return (

            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />

        )
      }
    }
  }
}

And I'm using this component in my form component like this:

export default class SubmitForm extends React.Component {

  render() {
    return (
        .
        .
        .
        <Field
          type="text"
          placeholder="something"
          name="something"
        />
        <Field
          type="textarea"
          placeholder="another"
          name="othername"
        />
        .
        .
        .
    )
  }
}

What I have in mind is to somehow implement my field component to be able to use dot notation as explained in Using Dot Notation for JSX components which I have seen many other libraries and I want to be able to use this component like this:

<Field.Text name="sth" placeholder="sth" />
<Field.TextArea name="other" placeholder="other stuff" />

But I can't do it the way mentioned in React docs. How can I do this?

Body:
export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (
          <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>
          )
      }
      case 'text': {
        return (
          <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>
        )
      }
    }
  }
}

chnage this as following way

const Field = {
    text: function(){
      // your text code
    }
}

export default Field;

Same way they have mentioned in the facebook react docs. Instead of component you can return object which contain your functions.


问:
display unique values between two dataframe columns - pyspark
say I have two "ID" columns in 2 dataframes, I want to display ID from DF1 that doesnt exists in DF2

I dont know if I should use join, merge, or isin.

```<code>cond = [df.name != df3.name]
df.join(df3, cond, 'outer').select(df.name, df3.age).collect()
</code>```

not sure if changing the condition will give me the result.

答:
use isin and fir ~df1['id] for dataframe compare.

df1:

```<code> id name
    0   1    a
    1   2    b
    2   3    c
    3   4    d
</code>```

df2:

```<code>id name
0   1   aa
1   5   bb
2   2   cc
3  10   dd

result = df1.loc[~df1['id'].isin(df2['id'])]

result

    id name
2   3    c
3   4    d
</code>```

hope this answer is helpful.

Body:
say I have two "ID" columns in 2 dataframes, I want to display ID from DF1 that doesnt exists in DF2

I dont know if I should use join, merge, or isin.

cond = [df.name != df3.name]
df.join(df3, cond, 'outer').select(df.name, df3.age).collect()

not sure if changing the condition will give me the result.

Body:
use isin and fir ~df1['id] for dataframe compare.

df1:

 id name
    0   1    a
    1   2    b
    2   3    c
    3   4    d

df2:

id name
0   1   aa
1   5   bb
2   2   cc
3  10   dd

result = df1.loc[~df1['id'].isin(df2['id'])]

result

    id name
2   3    c
3   4    d

hope this answer is helpful.


问:
How to return warnings from server side to silverlight
We have a business case that need to return both validation errors and warings from server side and display on silverlight.
I see the silverlight is using System.ComponentModel.DataAnnotations.ValidationResult to process errors. It does not contain and fields for "warnings".

I am wondering if anybody has a good idea to handle this problem. Thanks.

答:
I think ValidationResult is used by ValidationException which is thrown by the subclasses of ValidationAttribute. Normally this mecanism is used with blocking validation errors because throwing to exception stops execution of the code. If it happens in your service, the exception can be sent to the client and processessed, but this is not always a wanted scenario.

You could extend this model (those classes ValidationAttribute, its subclasses, ValidationException are not sealed) to add a warning flag but then you'd have to trap the exception to continue the processing and rethrow in case of a warning.

Another alternative is to add business logic validation errors and warnings to your response to the client. I like this approach because you can then include whatever info you want the way you want/need it.

ContentLicense: CC BY-SA 2.5


问:
Mysql, hibernate slow_query_log logs set timestamp
I'm running a load test on java application which uses hibernate framework in DAO layer. I found several occurrences of following in slow query log.

```<code># Time: 170704 15:06:47
# User@Host: user[user] @ localhost [127.0.0.1]  Id:   163
# Query_time: 0.428159  Lock_time: 0.000000 Rows_sent: 0  Rows_examined: 0
SET timestamp=1499161007;
commit;
</code>```

I'm using mysql  Ver 14.14 Distrib 5.1.73, for redhat-linux-gnu (x86_64) using readline 5.1 on Cent OS.
EhCache has been used as the caching provider for hibernate for some entities. I'm using 3GB inno_db_buffer_pool_size for 199.6MB database with 32-64 pooled mysql connections in my application. Additionally server has 16GB of total RAM and application JVM is configured to use 4GB heap.

I found this article written back in 2007. I'm not sure whether hibernate involves in calling NOW() or any other problem causing action in my case. Anything like that has not been explicitly done in the code. Any idea about the root cause of this log line?

答:
According to this stackoverflow question commit; statement is the reason to be this record in slow query log. SET timestamp=1499161007; has been executed prior to get statistical details.

I also needed to find what queries were executed in the transaction that has taken long time to commit. Digging little deeper I found mysql query log and suggestions provided in this question can be used.

Body:
I'm running a load test on java application which uses hibernate framework in DAO layer. I found several occurrences of following in slow query log.

# Time: 170704 15:06:47
# User@Host: user[user] @ localhost [127.0.0.1]  Id:   163
# Query_time: 0.428159  Lock_time: 0.000000 Rows_sent: 0  Rows_examined: 0
SET timestamp=1499161007;
commit;

I'm using mysql  Ver 14.14 Distrib 5.1.73, for redhat-linux-gnu (x86_64) using readline 5.1 on Cent OS.
EhCache has been used as the caching provider for hibernate for some entities. I'm using 3GB inno_db_buffer_pool_size for 199.6MB database with 32-64 pooled mysql connections in my application. Additionally server has 16GB of total RAM and application JVM is configured to use 4GB heap.

I found this article written back in 2007. I'm not sure whether hibernate involves in calling NOW() or any other problem causing action in my case. Anything like that has not been explicitly done in the code. Any idea about the root cause of this log line?


问:
Assigning dynamic ids to elements using jQuery
Hi I am using jQuery and creating tags in a loop.

Ex -

```<code>for(var i=0;i<length;i++){

            jQuery("#dailydata").append("<table class='table'><tr>"+
                "<th>Min Temp : </th><td>"+ data[i]</td>" +
                "</tr></table>";

                if(data[i] <=10){
                    //add color to th
                }else{
                    //add different color to th
                }
        }
</code>```

I am creating a Table Row in every loop and appending to a HTML element. and just after that I am checking the value and according to that value I want to change the background color of the  tag.

Can somebody tell me how to achieve this?

答:
You can just add an extra if condition to check the value of i

Here in this example , assume length is value greater than i. Also in your example you are using data[i] but the loop will run on length variable.There is a typo here data[i]	" It need to be data[i]+"	". Also the append method be closed with )

var length = 15;
for (var i = 0; i < length; i++) {

  if (i < 10) {
    jQuery("#dailydata").append("

" +
      "Min Temp : 	" + i + "	" +
      "

");
  } else {
    jQuery("#dailydata").append("

" +
      "Min Temp : 	" + i + "	" +
      "

");
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.less10 {
  color: green
}

.more10 {
  color: blue
}</code>```

```

Body:
Hi I am using jQuery and creating tags in a loop.

Ex -

for(var i=0;i<length;i++){

            jQuery("#dailydata").append("

"+
                "Min Temp : 	"+ data[i]	" +
                "

";

                if(data[i] <=10){
                    //add color to th
                }else{
                    //add different color to th
                }
        }

I am creating a Table Row in every loop and appending to a HTML element. and just after that I am checking the value and according to that value I want to change the background color of the  tag.

Can somebody tell me how to achieve this?

Body:
You can just add an extra if condition to check the value of i

Here in this example , assume length is value greater than i. Also in your example you are using data[i] but the loop will run on length variable.There is a typo here data[i]</td>" It need to be data[i]+"</td>". Also the append method be closed with )

var length = 15;
for (var i = 0; i < length; i++) {

  if (i < 10) {
    jQuery("#dailydata").append("<table class='table'><tr>" +
      "<th class='less10'>Min Temp : </th><td>" + i + "</td>" +
      "</tr></table>");
  } else {
    jQuery("#dailydata").append("<table class='table'><tr>" +
      "<th class='more10'>Min Temp : </th><td>" + i + "</td>" +
      "</tr></table>");
  }

}

.less10 {
  color: green
}

.more10 {
  color: blue
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dailydata">
</div>


问:
Using values from two data files for one formula for calculation in R
I'm a trying-to-be R user. I never learned to code properly and have been just doing it by finding stuff online.

I encountered a problem that I would need some of you experts' help.

I have two data files.

Particulate matter (PM) concentrations (~20000 observations)

Coefficient combinations to use with the particulate matter concentrations to calculate final concentrations.

For example..

Data set 1.

```<code>ID      PM
 1       5
 2      10
...    ...
1500    25
</code>```

Data set 2.

```<code>alpha    beta
    5       6
    1       2
  ...     ...
</code>```

I ultimately have to use all the coefficient combinations (alpha and beta) for each of the IDs from data set 1. For example, if I have 10 observations in data set 1, and 10 coefficient combinations in data set 2, my output table should have 100 different output values (10*10=100).

```<code>for (i in cmaq$FID) {
  mean=cmaq$PM*IER$alpha*IER$beta
}
</code>```

I used the above code to do what I'm trying to do, but it only gave me 10 output values rather than 100. I think using the split function first, and somehow use that with the second dataset would work, but have not figured out how...

It may be a very very simple problem, but after spending hours to figure it out, I thought it may be a better strategy to get some help from R experts.

Thank you in advance!!!

答:
You can do:</p>

```<code>df1 = data.frame(
    ID = c(1, 2, 1500),
    PM = c(5, 10, 25)
)
df2 = data.frame(
    alpha = c(5, 6),
    beta = c(1, 2)
)

library(tidyverse)
library(dplyr)

df1 %>%
    group_by(ID) %>%
    do(data.frame(result = .$PM * df2$alpha * df2$beta,
                  alpha = df2$alpha,
                  beta = df2$beta))
</code>```

Body:
I'm a trying-to-be R user. I never learned to code properly and have been just doing it by finding stuff online.

I encountered a problem that I would need some of you experts' help.

I have two data files.

Particulate matter (PM) concentrations (~20000 observations)

Coefficient combinations to use with the particulate matter concentrations to calculate final concentrations.

For example..

Data set 1.

ID      PM
 1       5
 2      10
...    ...
1500    25

Data set 2.

alpha    beta
    5       6
    1       2
  ...     ...

I ultimately have to use all the coefficient combinations (alpha and beta) for each of the IDs from data set 1. For example, if I have 10 observations in data set 1, and 10 coefficient combinations in data set 2, my output table should have 100 different output values (10*10=100).

for (i in cmaq$FID) {
  mean=cmaq$PM*IER$alpha*IER$beta
}

I used the above code to do what I'm trying to do, but it only gave me 10 output values rather than 100. I think using the split function first, and somehow use that with the second dataset would work, but have not figured out how...

It may be a very very simple problem, but after spending hours to figure it out, I thought it may be a better strategy to get some help from R experts.

Thank you in advance!!!

Body:
You can do:

df1 = data.frame(
    ID = c(1, 2, 1500),
    PM = c(5, 10, 25)
)
df2 = data.frame(
    alpha = c(5, 6),
    beta = c(1, 2)
)

library(tidyverse)
library(dplyr)

df1 %>%
    group_by(ID) %>%
    do(data.frame(result = .$PM * df2$alpha * df2$beta,
                  alpha = df2$alpha,
                  beta = df2$beta))


问:
IE 11 on Windows 7 VS IE 11 on Windows 10
Could anyone please detail the difference between IE 11 on windows 7 and IE 11 on windows 10.

My organization has done lot of testing while moving from IE 8 to IE 11 on windows 7 and now they want to upgrade to windows 10.

However before moving to Win 10, they want to be sure that IE11 on Win 10 is exactly same as IE 11 on Windows 7.

I am not able to find any article on Microsoft website, which explains it.

Thanks in Advance.

Regards

答:
I would imagine they render the page in the same way (CSS etc.) but there are some security changes.

On Windows 8 and later IE can run in a AppContainer sandbox. Enhanced Protected Mode can cause issues with 3rd-party browser extensions and local files. EPM is optional and can be turned on/off.

There are also changes at the network level and backend storage.

If you rely on 3rd-party extensions or local file/localhost access you might want to do some testing before migrating, if not then I don't see any real showstoppers.


问:
How to get values from multidimensional array using checkbox in php
this is my array and back end (controller)

```<code>$newA = array("agents" => array("value" => array( "65" => array( "drive" => "number","cars" => "78"),"68" => array( "drive" => "num","cars" => "98"))));

$test2 = $r->myCheckbox;
</code>```

Now I can display '65' and '68' this values I get from checkbox selected by users, but I want to display values in the 65 and 68.
please help me thank you.

答: Assume that your user checkbox return is $return and this equal 65. To get the value, just use $newA['agents']['value'][$return];

Body:
this is my array and back end (controller)

$newA = array("agents" => array("value" => array( "65" => array( "drive" => "number","cars" => "78"),"68" => array( "drive" => "num","cars" => "98"))));

$test2 = $r->myCheckbox;

Now I can display '65' and '68' this values I get from checkbox selected by users, but I want to display values in the 65 and 68.
please help me thank you.


问:
Faild composer network deploy with time out
I executed this command.

```<code>composer network deploy -a basic-sample-network.bna -p defaultProfile -i admin -s Xurw3yU9zI0l
</code>```

But,faild with time out..

Here is log.

```<code>Deploying business network from archive: basic-sample-network.bna
Business network definition:
    Identifier: basic-sample-network@0.0.10
    Description: The Hello World of Hyperledger Composer samples

✖ Deploying business network definition. This may take a minute...

timed out waiting for transaction to complete
Command failed
</code>```

Colud you tell me the way to composer network deploy with no time out.

答:
This is new CONTEINER ID.

```<code>vagrant@ubuntu:~/composer/bna$ docker ps -a
CONTAINER ID        IMAGE                                                COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
180a05ba4a66        hyperledger/composer-playground                      "pm2-docker compos..."   6 minutes ago       Up 2 minutes        0.0.0.0:8080->8080/tcp                                                                           fabricconfig_composer_1
47525938ac95        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7150->7050/tcp, 0.0.0.0:7151->7051/tcp, 0.0.0.0:7152->7052/tcp, 0.0.0.0:7153->7053/tcp   fabricconfig_vp1_1
962df523b480        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7350->7050/tcp, 0.0.0.0:7351->7051/tcp, 0.0.0.0:7352->7052/tcp, 0.0.0.0:7353->7053/tcp   fabricconfig_vp3_1
6ea2ec92d454        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7250->7050/tcp, 0.0.0.0:7251->7051/tcp, 0.0.0.0:7252->7052/tcp, 0.0.0.0:7253->7053/tcp   fabricconfig_vp2_1
fb09850fba53        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7050-7053->7050-7053/tcp                                                                 fabricconfig_vp0_1
1e5d14cacb02        hyperledger/fabric-membersrvc:x86_64-0.6.1-preview   "membersrvc"             6 minutes ago       Up 2 minutes        0.0.0.0:7054->7054/tcp                                                                           fabricconfig_membersrvc_1
</code>```

Here is 'docker logs '
It looks like connection error.

```<code>vagrant@ubuntu:~/composer/bna$ docker logs 47525938ac95
:
04:59:24.290 [dockercontroller] deployImage -> ERRO 117 Error building images: manifest for hyperledger/fabric-baseimage:latest not found
04:59:24.290 [dockercontroller] deployImage -> ERRO 118 Image Output:
********************
Step 1/4 : FROM hyperledger/fabric-baseimage

********************
</code>```

and

```<code>  vagrant@ubuntu:~/composer/bna$ docker logs 962df523b480
    :
    02:51:31.563 [peer] chatWithPeer -> ERRO 15aa Error creating connection to peer address 172.18.0.5:7051: grpc: timed out when dialing
    :
</code>```

and

```<code>vagrant@ubuntu:~/composer/bna$ docker logs 6ea2ec92d454
:
02:54:25.298 [peer] chatWithPeer -> ERRO 1a05 Error creating connection to peer address 172.18.0.5:7051: grpc: timed out when dialing
:
</code>```

and

```<code>vagrant@ubuntu:~/composerPoCTool-master/tools/composer/bna$ docker logs fb09850fba53
:
02:55:48.718 [peer] chatWithPeer -> ERRO 1c33 Error creating connection to peer address 172.18.0.5:7051: grpc: timed out when dialing
:
</code>```

Body:
I executed this command.

composer network deploy -a basic-sample-network.bna -p defaultProfile -i admin -s Xurw3yU9zI0l

But,faild with time out..

Here is log.

Deploying business network from archive: basic-sample-network.bna
Business network definition:
    Identifier: basic-sample-network@0.0.10
    Description: The Hello World of Hyperledger Composer samples

✖ Deploying business network definition. This may take a minute...

timed out waiting for transaction to complete
Command failed

Colud you tell me the way to composer network deploy with no time out.

Body:
This is new CONTEINER ID.

vagrant@ubuntu:~/composer/bna$ docker ps -a
CONTAINER ID        IMAGE                                                COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
180a05ba4a66        hyperledger/composer-playground                      "pm2-docker compos..."   6 minutes ago       Up 2 minutes        0.0.0.0:8080->8080/tcp                                                                           fabricconfig_composer_1
47525938ac95        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7150->7050/tcp, 0.0.0.0:7151->7051/tcp, 0.0.0.0:7152->7052/tcp, 0.0.0.0:7153->7053/tcp   fabricconfig_vp1_1
962df523b480        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7350->7050/tcp, 0.0.0.0:7351->7051/tcp, 0.0.0.0:7352->7052/tcp, 0.0.0.0:7353->7053/tcp   fabricconfig_vp3_1
6ea2ec92d454        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7250->7050/tcp, 0.0.0.0:7251->7051/tcp, 0.0.0.0:7252->7052/tcp, 0.0.0.0:7253->7053/tcp   fabricconfig_vp2_1
fb09850fba53        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   6 minutes ago       Up 2 minutes        0.0.0.0:7050-7053->7050-7053/tcp                                                                 fabricconfig_vp0_1
1e5d14cacb02        hyperledger/fabric-membersrvc:x86_64-0.6.1-preview   "membersrvc"             6 minutes ago       Up 2 minutes        0.0.0.0:7054->7054/tcp                                                                           fabricconfig_membersrvc_1

Here is 'docker logs '
It looks like connection error.

vagrant@ubuntu:~/composer/bna$ docker logs 47525938ac95
:
04:59:24.290 [dockercontroller] deployImage -> ERRO 117 Error building images: manifest for hyperledger/fabric-baseimage:latest not found
04:59:24.290 [dockercontroller] deployImage -> ERRO 118 Image Output:
********************
Step 1/4 : FROM hyperledger/fabric-baseimage

********************

and

  vagrant@ubuntu:~/composer/bna$ docker logs 962df523b480
    :
    02:51:31.563 [peer] chatWithPeer -> ERRO 15aa Error creating connection to peer address 172.18.0.5:7051: grpc: timed out when dialing
    :

and

vagrant@ubuntu:~/composer/bna$ docker logs 6ea2ec92d454
:
02:54:25.298 [peer] chatWithPeer -> ERRO 1a05 Error creating connection to peer address 172.18.0.5:7051: grpc: timed out when dialing
:

and

vagrant@ubuntu:~/composerPoCTool-master/tools/composer/bna$ docker logs fb09850fba53
:
02:55:48.718 [peer] chatWithPeer -> ERRO 1c33 Error creating connection to peer address 172.18.0.5:7051: grpc: timed out when dialing
:


问:
Updating the input value on button click Jquery
For The code below, when the button is clicked, it's supposed to update the name of the text. ie hisally, hellosally, supsally,
but instead the current is hitomsally, hellotomsally, suptomsally.
i m wondering is there any way to update the name while keeping the text hi,hellop and sup.
Many thanks

$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>

    <td>
     <input type="button" value="ok" class="ok"></td>
    <td>done<input type="text" value="sally" class="done" \> </td>
    <td>text1<textarea class="text" data-value="hitom">hitom</textarea> </td>
    <td>text2<textarea class="text" data-value="hellotom">hellotom</textarea> </td>
    <td>text3<textarea class="text" data-value="suptom">suptom</textarea> </td>

  </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

答:
you need to change your data-value to only the values that you want to prepend in textarea

$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>

    <td>
     <input type="button" value="ok" class="ok"></td>
    <td>done<input type="text" value="sally" class="done" \> </td>
    <td>text1<textarea class="text" data-value="hi">hitom</textarea> </td>
    <td>text2<textarea class="text" data-value="hello">hellotom</textarea> </td>
    <td>text3<textarea class="text" data-value="sup">suptom</textarea> </td>

  </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

Body:
For The code below, when the button is clicked, it's supposed to update the name of the text. ie hisally, hellosally, supsally,
but instead the current is hitomsally, hellotomsally, suptomsally.
i m wondering is there any way to update the name while keeping the text hi,hellop and sup.
Many thanks

$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});

     <input type="button" value="ok" class="ok">
    done<input type="text" value="sally" class="done" \>
    text1<textarea class="text" data-value="hitom">hitom</textarea>
    text2<textarea class="text" data-value="hellotom">hellotom</textarea>
    text3<textarea class="text" data-value="suptom">suptom</textarea>

Body:
you need to change your data-value to only the values that you want to prepend in textarea

$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});

<table>
  <tr>

    <td>
     <input type="button" value="ok" class="ok"></td>
    <td>done<input type="text" value="sally" class="done" \> </td>
    <td>text1<textarea class="text" data-value="hi">hitom</textarea> </td>
    <td>text2<textarea class="text" data-value="hello">hellotom</textarea> </td>
    <td>text3<textarea class="text" data-value="sup">suptom</textarea> </td>

  </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>


问:
Update Redux state on route change
I've been trying to figure this out for a while and I'm getting more and more confused.

I want to reset/change Redux state every time I leave or change route. I'm using react-router-redux with history.listener dispatching an action every time route changes

```<code>history.listen(location => store.dispatch(resetManualsCategory()));
</code>```

Action creator:

```<code>export function resetManualsCategory() {
    return {
        type: 'RESET_MANUALS_CATEGORY'
    }
}
</code>```

Reducer

```<code>export function manualCategories(state=[], action) {
    switch (action.type) {
        case 'SELECT_MANUALS_CATEGORY':
           [...]

        case 'RESET_MANUALS_CATEGORY':
            console.log('test reducer');
            return Object.assign({}, state, {
                manualCategory: 'test'
            })

        default:
            return state
    }
}
</code>```

What confuses me the most, the state updates if I refresh the page or click twice on the route in the top nav, but a single route change doesn't affect the redux state even though the action and reducer fire (displays the test message in the console).

What am I doing wrong and what actually is happening here?

答:
I used different approach for resetting the state when changing routes. Instead of listening to history/ router, I used componentWillMount event on my page containers to dispatch a "reset page" action.
Example:

Router:

```<code><Provider store={store}>
  <Router history={history}>
    <Route path="/page1" component={Page1Container} />
    <Route path="/page2" component={Page2Container} />
  </Router>
</Provider>
</code>```

Page1 container:

```<code>class Page1Container extends Component {

  componentWillMount() {
    this.props.resetPage()
  }

  render() {
    // render Page1
  }
}

const mapStateToProps = (state) => {
  return {
    // ...
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    // ...
    resetPage: () => { dispatch({type: 'PAGE1_RESET_PAGE'}) }
  }
}

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

Reducer:

```<code>const initialState = null

export function Page1Reducer (state = initialState, action) {
  switch (action.type) {
    case 'PAGE1_RESET_PAGE': {
      state = initialState
      break
    }

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

Update:
As @DavidHarkness mentioned, the flaw of this approach is that the component will render twice on mounting.
And apart from that, I now tend to think that this solution is not elegant and it is better to avoid using bussiness logic inside components.
Moving the logic inside the reducer would be a better option (see @DiegoHaz answer).

Title: Update Redux state on route change

Body:
I've been trying to figure this out for a while and I'm getting more and more confused.

I want to reset/change Redux state every time I leave or change route. I'm using react-router-redux with history.listener dispatching an action every time route changes

history.listen(location => store.dispatch(resetManualsCategory()));

Action creator:

export function resetManualsCategory() {
    return {
        type: 'RESET_MANUALS_CATEGORY'
    }
}

Reducer

export function manualCategories(state=[], action) {
    switch (action.type) {
        case 'SELECT_MANUALS_CATEGORY':
           [...]

        case 'RESET_MANUALS_CATEGORY':
            console.log('test reducer');
            return Object.assign({}, state, {
                manualCategory: 'test'
            })

        default:
            return state
    }
}

What confuses me the most, the state updates if I refresh the page or click twice on the route in the top nav, but a single route change doesn't affect the redux state even though the action and reducer fire (displays the test message in the console).

What am I doing wrong and what actually is happening here?

Body:
I used different approach for resetting the state when changing routes. Instead of listening to history/ router, I used componentWillMount event on my page containers to dispatch a "reset page" action.
Example:

Router:

<Provider store={store}>
  <Router history={history}>
    <Route path="/page1" component={Page1Container} />
    <Route path="/page2" component={Page2Container} />
  </Router>
</Provider>

Page1 container:

class Page1Container extends Component {

  componentWillMount() {
    this.props.resetPage()
  }

  render() {
    // render Page1
  }
}

const mapStateToProps = (state) => {
  return {
    // ...
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    // ...
    resetPage: () => { dispatch({type: 'PAGE1_RESET_PAGE'}) }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Page1Container)

Reducer:

const initialState = null

export function Page1Reducer (state = initialState, action) {
  switch (action.type) {
    case 'PAGE1_RESET_PAGE': {
      state = initialState
      break
    }

    // ...
  }
}

Update:
As @DavidHarkness mentioned, the flaw of this approach is that the component will render twice on mounting.
And apart from that, I now tend to think that this solution is not elegant and it is better to avoid using bussiness logic inside components.
Moving the logic inside the reducer would be a better option (see @DiegoHaz answer).

ContentLicense: CC BY-SA 4.0


问:
How does x86 pause instruction work in spinlock *and* can it be used in other scenarios?
The pause instruction is commonly used in the loop of testing spinlock, when some other thread owns the spinlock, to mitigate the tight loop. It's said that it is equivalent to some NOP instructions. Could somebody tell me how exactly it works for spinlock optimization? It seems to me that even the NOP instructions are a waste of CPU time. Will they decrease CPU usage?

Another question is that could I use pause instruction for other similar purposes. For example, I have a busy thread which keeps scanning some places (e.g. a queue) to retrieve new nodes; however, sometimes the queue is empty and the thread is just wasting cpu time. Sleep the thread and wake it up by other threads may be an option, however the thread is critical, so I don't want to make it sleep.

Could pause instruction work for my purpose to mitigate the CPU usage? Currently it uses 100% cpu of a physical core?

答:
Pause-based spin-wait loops

As I understood from your questions, the waits in your case are known in advance to be very long. In this case, spin-wait loops are not recommended at all. But if you are using a spin-loop that keeps checking a value from memory (e.g. a byte-sized synchronization variable), use PAUSE. See the Section 11.4.2 "Synchronization for Short Periods" of the Intel 64 and IA-32 Architectures Optimization Reference Manual.

You wrote that you have a "thread which keeps scanning some places (e.g. a queue) to retrieve new nodes".

In such a case (i.e. the long wait), Intel recommends using synchronization API functions of your operating system. For example, you can create an event when a new node appears in a queue, and just wait for this event using the WaitForSingleObject(Handle, INFINITE). The queue will trigger this event whenever a new node will appear.

According to the Intel Optimization Reference Manual, Section, 2.3.4 "Pause Latency in Skylake Client Microarchitecture",

The PAUSE instruction is typically used with software threads
executing on two logical processors located in the same processor
core, waiting for a lock to be released. Such short wait loops tend to
last between tens and a few hundreds of cycles, so performance-wise it
is better to wait while occupying the CPU than yielding to the OS.

By "tens and a few hundreds of cycles" of the above quote I understand from 20 to 500 CPU cycles.

500 CPU cycles on a 4500 MHz Intel Core i7 7700K processor (released on January 2017, based on Kaby-Lake-S microarchitecture) is 0.0000001 seconds, i.e. 1/10000000th of a second: the CPU can make 10 million times per second this 500-CPU-cycles loop.

This 500 cycle limit recommended by Intel is theoretical, and all depends on particular use case, i.e. on the logic of the code that needs to be synchronized by spin-wait loops. Some scenarios like FastMM4-AVX memory manger for Delphi work better with the value of 5000, according to the benchmarks. Even though, these benchmarks do not always reflect real-world scenario, and real program use cases should be measured.

As you see, this PAUSE-based spin-wait loop is for really short periods of time.

On the other hand, each call to an API function like Sleep() experiences the expensive cost of a context switch, which can be 10000+ cycles; it also suffers the cost of ring 3 to ring 0 transitions, which can be 1000+ cycles.

If there are more threads then the processor cores (multiplied to hyperthreading feature, if present) are available, and a thread will get switched to another one in the middle of a critical section, waiting for the critical section from another thread may really take looong, at least 10000+ cycles, so the PAUSE-based spin-wait loop will be futile.

In addition to the relevant chapters of the Intel Optimization Reference Manual, please see the following articles for more information:

https://software.intel.com/en-us/articles/long-duration-spin-wait-loops-on-hyper-threading-technology-enabled-intel-processors

https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops

When the wait loop is expected to last for thousands of cycles or more, it is
preferable to yield to the operating system by calling one of the OS synchronization API functions, such as WaitForSingleObject or SwitchToThread on Windows OS.

As a conclusion: in your scenario, the PAUSE-based spin-wait loop won't be the best choice, since your waiting time is long while the spin-wait loop is intended for very short loops.

The PAUSE instruction takes about 140 CPU cycles on processors based on Skylake microarchitecture, or later processors. For example, it is just or 35.10ns on Intel Core i7-6700K CPU (4GHz) released on August 2015, or 49.47ns on Intel Core i7-1165G7 CPU for mobile devices released on September 2020. On earlier processors (prior to Skylake), like those based on Haswell microarchitecture, it has about 9 cycles. It is 2.81ns on Intel Core i5-4430 (3GHz) released on June 2013. So, for the long loops, it's better to relinquish control to other threads using the OS synchronization API functions than to occupy CPU with the PAUSE loop, regardless of the microarchitecture.

Test, Test-and-Set

Please note that the spin-wait loops have also to be implemented properly. Intel recommends the so-called "test, test-and-set" technique (see Section 11.4.3 "Optimization with Spin-Locks" of the Intel 64 and IA-32 Architectures Optimization Reference Manual) to determine the availability of the synchronization variable. According to this technique, the first "test" is done via the normal (non-locking) memory load to prevent excessive bus locking during the spin-wait loop; if the variable is available upon the non-locking memory load of the first step ("test"), proceed to the second step ("test-and-set") which is done via the bus-locking atomic xchg instruction.

But be aware that this two-steps approach of using "test" before "test-and-set" can increase the cost for the un-contended case comparing to just single-step "test-and-set". The initial read-only access might only get the cache line in Shared state, so the atomic operation like test-and-set (xchg) or compare-and-swap (cmpxchg) still needs a ''Read For Ownership'' (RFO) operation to get exclusive ownership of the cache line. This operation is issued by a processor trying to write into a cache line that is in the Shared state.

Does cmpxchg write destination cache line on failure? If not, is it better than xchg for spinlock?

atomic operation cost


问:
how to rotate a fragment inside an activity without activity rotation?
There is an android program
I have a bottom navigation bar inside my app that i don't want to change its orientation because of quality reduce
I want to rotate a fragment inside an activity when change orientation of the phone without activity rotation. how can i do this?

Thanks.

答:
Open your Manifest.XML
Find your activity.
Add tag inside </p>

```<code><activity
        android:configChanges="orientation"/>
</code>```

Body:
Open your Manifest.XML
Find your activity.
Add tag inside

<activity
        android:configChanges="orientation"/>


答:
The data-value contains wrong values for the textareas, and you are actually concatenating the value of the textbox to them. Correct the values in the data-value attributes, and you will be done!

$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>

    <td>
     <input type="button" value="ok" class="ok"></td>
    <td>done<input type="text" value="sally" class="done" \> </td>
    <td>text1<textarea class="text" data-value="hi">hitom</textarea> </td>
    <td>text2<textarea class="text" data-value="hello">hellotom</textarea> </td>
    <td>text3<textarea class="text" data-value="sup">suptom</textarea> </td>

  </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

Title: Updating the input value on button click Jquery

Body:
The data-value contains wrong values for the textareas, and you are actually concatenating the value of the textbox to them. Correct the values in the data-value attributes, and you will be done!

$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});

<table>
  <tr>

    <td>
     <input type="button" value="ok" class="ok"></td>
    <td>done<input type="text" value="sally" class="done" \> </td>
    <td>text1<textarea class="text" data-value="hi">hitom</textarea> </td>
    <td>text2<textarea class="text" data-value="hello">hellotom</textarea> </td>
    <td>text3<textarea class="text" data-value="sup">suptom</textarea> </td>

  </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>


问:
Kotlin Simplify Boolean Expression
Why do I get a minor error that says "Simplify boolean expression" in my if condition line?

For instance this snippet of code:

```<code>if (isClear==true){
    displayText.setText("")
}
</code>```

答:
To handle Boolean isClear in Kotlin,following expression can be used.

```<code>when(isClear) {
 true -> {}
 false -> {}
}
</code>```

However in case, isClear is nullable,we can use following code snippet.

```<code> when(isClear) {
 true -> {}
 false -> {}
 null -> {}
}
</code>```

Title: Kotlin Simplify Boolean Expression

Body:
Why do I get a minor error that says "Simplify boolean expression" in my if condition line?

For instance this snippet of code:

if (isClear==true){
    displayText.setText("")
}

Body:
To handle Boolean isClear in Kotlin,following expression can be used.

when(isClear) {
 true -> {}
 false -> {}
}

However in case, isClear is nullable,we can use following code snippet.

 when(isClear) {
 true -> {}
 false -> {}
 null -> {}
}


问:
How can i access a jinja2 variable outside the for loop?
im trying to use a for loop to add up some numbers for each day
and i would like to access the variable outside the for loop  im not sure how to go about this   I am using the flask framework with python  and just come from weppy where this was not a problem  is there a way to make it work the same way in flask?

here is some simple code

```<code>{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{ newtotal }}</span>
</div>
</code>```

the numbers collected by item[10] are dollar values
if i place the {{ newtotal }} before the endfor it shows every value as its being added up this is not what I want

EDIT:
if it helps daily is a list of 8 tuples

答:
One solution (probably the "simplest") would be to change your Python script to pass in a variable named newtotal that would simply be the length of the daily list!

Alternatively, you could use the length filter:

```<code>{{things|length}}
</code>```

In which case your code could look something like this:

```<code>{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{daily|length}}</span>
</div>
</code>```

Hope it helps!

Additional Sources:

jinja2: get lengths of list

How do I access Jinja2 for loop variables outside the loop?

EDIT

Sorry, I misread the question!

You can use the sum filter instead ({{ list | sum() }}).

So your code could look like:

```<code>{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{ daily | sum() }}</span>
</div>
</code>```

New sources:

Documentation
Sum elements of the list in Jinja 2

Body:
im trying to use a for loop to add up some numbers for each day
and i would like to access the variable outside the for loop  im not sure how to go about this   I am using the flask framework with python  and just come from weppy where this was not a problem  is there a way to make it work the same way in flask?

here is some simple code

{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

    Total: {{ newtotal }}

the numbers collected by item[10] are dollar values
if i place the {{ newtotal }} before the endfor it shows every value as its being added up this is not what I want

EDIT:
if it helps daily is a list of 8 tuples

Body:
One solution (probably the "simplest") would be to change your Python script to pass in a variable named newtotal that would simply be the length of the daily list!

Alternatively, you could use the length filter:

{{things|length}}

In which case your code could look something like this:

{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{daily|length}}</span>
</div>

Hope it helps!

Additional Sources:

jinja2: get lengths of list

How do I access Jinja2 for loop variables outside the loop?

EDIT

Sorry, I misread the question!

You can use the sum filter instead ({{ list | sum() }}).

So your code could look like:

{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{ daily | sum() }}</span>
</div>

New sources:

Documentation
Sum elements of the list in Jinja 2


问:
TS 2.1 targeting ES5, visual studio complaining async functions are only available when targeting ECMAScript 2015 or higher
It is my understanding that with version 2.1.x of TS that async/await works for ES3/ES5 yet I'm still getting warnings from visual studio 2015 about async functions not being available. Code seems to compile and work but why is visual studio 2015 giving this error message?

package.json

```<code>"typescript": "~2.1.6"
</code>```

tsconfig

```<code>{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"noEmitHelpers": true,
"strictNullChecks": false,
"baseUrl": "./src",
"paths": {
},
"lib": [
  "dom",
  "es6"
],
"types": [
  "node",
  "source-map"
]
},
"exclude": [
"node_modules",
"dist",
"**/*.aot.ts",
"**/*.ngfactory.ts"
],
"awesomeTypescriptLoaderOptions": {
"forkChecker": true,
"useWebpackText": true
},
"compileOnSave": false,
"buildOnSave": false,
"atom": { "rewriteTsconfig": false }
}
</code>```

答:
I had the same problem. It is because the typescript version for your VisualStudio's intelliSense still below 2.1.x . I believe the problem happen because this intelliSense doesn't get the typescript from your package.json (which then will be installed using npm I presume), but it use the VisualStudio's typescript.

So the solution is to update your visualStudio's typescript version. You can update it by install the typescript from the official site of microsoft (currently the latest version is 2.4.1). Restart your visualStudio after installation and hopefully your problem is solved just like mine (The warning from the intelliSense is gone).

Body:
It is my understanding that with version 2.1.x of TS that async/await works for ES3/ES5 yet I'm still getting warnings from visual studio 2015 about async functions not being available. Code seems to compile and work but why is visual studio 2015 giving this error message?

package.json

"typescript": "~2.1.6"

tsconfig

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"noEmitHelpers": true,
"strictNullChecks": false,
"baseUrl": "./src",
"paths": {
},
"lib": [
  "dom",
  "es6"
],
"types": [
  "node",
  "source-map"
]
},
"exclude": [
"node_modules",
"dist",
"**/*.aot.ts",
"**/*.ngfactory.ts"
],
"awesomeTypescriptLoaderOptions": {
"forkChecker": true,
"useWebpackText": true
},
"compileOnSave": false,
"buildOnSave": false,
"atom": { "rewriteTsconfig": false }
}


问:
firebase auth with email and password doesnt work with mobile data connection
I do firebase authentication with email and password work fine when i have wifi but i connected mobile data connection firebase authentication fail and get this message:

```<code>"a network error (such as timeout, interrupted connection or unreachable
host) has occurred."
</code>```

this is my gradle:

```<code>classpath 'com.google.gms:google-services:3.1.0'

compile 'com.google.firebase:firebase-auth:11.0.1'
</code>```

This is my manifest:

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Only WiFi work fine. Mobile data connection doesn't work

答: Firebase has limitation on proxies. See this comment from a member from Firebase team. Maybe your mobile connection uses proxies</p>

Body:
I do firebase authentication with email and password work fine when i have wifi but i connected mobile data connection firebase authentication fail and get this message:

"a network error (such as timeout, interrupted connection or unreachable
host) has occurred."

this is my gradle:

classpath 'com.google.gms:google-services:3.1.0'

compile 'com.google.firebase:firebase-auth:11.0.1'

This is my manifest:

<uses-permission android:name="android.permission.INTERNET" />

Only WiFi work fine. Mobile data connection doesn't work


问:
C# String Array Contains
Can someone explain to me why the top part of the code works but when test is an array it doesn't?

```<code>string test = "Customer - ";
if (test.Contains("Customer"))
{
    test = "a";
}
</code>```

The code below doesn't work

```<code>string[] test = { "Customer - " };
if (test.Contains("Customer"))
{
    test[0] = "a";
}
</code>```

答:
In first case, you call String.Contains which checks if string contains substring.

So, this condition returns true.

In the second case, you call Enumerable.Contains on string[] which checks if string array contains a specific value.

Since there is no "Customer" string in your collection, it returns false.

These are two similarly called but actually different methods of different types.

If you want to check if any string in collection contains "Customer" as a substring, then you can use LINQ .Any():

```<code>if (test.Any(s => s.Contains("Customer"))
{
    test[1] = "a";
}
</code>```

Title: C# String Array Contains

Body:
Can someone explain to me why the top part of the code works but when test is an array it doesn't?

string test = "Customer - ";
if (test.Contains("Customer"))
{
    test = "a";
}

The code below doesn't work

string[] test = { "Customer - " };
if (test.Contains("Customer"))
{
    test[0] = "a";
}

Body:
In first case, you call String.Contains which checks if string contains substring.

So, this condition returns true.

In the second case, you call Enumerable.Contains on string[] which checks if string array contains a specific value.

Since there is no "Customer" string in your collection, it returns false.

These are two similarly called but actually different methods of different types.

If you want to check if any string in collection contains "Customer" as a substring, then you can use LINQ .Any():

if (test.Any(s => s.Contains("Customer"))
{
    test[1] = "a";
}


问:
Is it possible to wrap a C# singleton in an interface?
I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.

But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?

答: You can make all the other members of your singleton implement corresponding members in an interface.  However, you are correct that the Instance property cannot be part of the interface since it is (and must remain) static.


问:
Issue with CodeIgniter redirect
Here i'm creating a login system. Once the user is verified the controller redirects the page to home.php.

There are 2 pages here login_registration.php and home.php

login_registration.php consists login and registration form from here the user is redirected to home.php. both the files are in path C:\wamp\www\CI-Project_1\application\views\login

The issue is it show 404 Page Not Found when redirected.

```<code> class Login extends CI_Controller {
    public function __construct(){
        parent::__construct();
                $this->load->helper('url');
        //LOAD MODELS HERE
        $this->load->model('Login_model');
    }

    public function index(){
        $this->load->view('login/login_registration.php');
    }

    function login_user(){
        $login_btn = $this->input->post('login_btn');

        if($login_btn == TRUE){
            $arr['login'] = array(
                'username'=>$this->input->post('username'),
                'password'=>$this->input->post('password')
            );

            $query = $this->Login_model->users_login($arr);

            if($query->num_rows() > 0 && $query->num_rows() == 1){
                $this->load->library('session');
                $this->session->set_userdata($arr['login']);
                redirect('login/home.php', 'location');
            }
            else
            {
                $this->index();
            }
        }
        else
        {
            $this->index();
        }
    }
}
</code>```

THANKS IN ADVANCE

答:
You have to mention the name of your controller and method name where you want to redirect something like this </p>

```<code>redirect('controllername/methodname');
</code>```

Title: Issue with CodeIgniter redirect

Body:
Here i'm creating a login system. Once the user is verified the controller redirects the page to home.php.

There are 2 pages here login_registration.php and home.php

login_registration.php consists login and registration form from here the user is redirected to home.php. both the files are in path C:\wamp\www\CI-Project_1\application\views\login

The issue is it show 404 Page Not Found when redirected.

 class Login extends CI_Controller {
    public function __construct(){
        parent::__construct();
                $this->load->helper('url');
        //LOAD MODELS HERE
        $this->load->model('Login_model');
    }

    public function index(){
        $this->load->view('login/login_registration.php');
    }

    function login_user(){
        $login_btn = $this->input->post('login_btn');

        if($login_btn == TRUE){
            $arr['login'] = array(
                'username'=>$this->input->post('username'),
                'password'=>$this->input->post('password')
            );

            $query = $this->Login_model->users_login($arr);

            if($query->num_rows() > 0 && $query->num_rows() == 1){
                $this->load->library('session');
                $this->session->set_userdata($arr['login']);
                redirect('login/home.php', 'location');
            }
            else
            {
                $this->index();
            }
        }
        else
        {
            $this->index();
        }
    }
}

THANKS IN ADVANCE

Body:
You have to mention the name of your controller and method name where you want to redirect something like this

redirect('controllername/methodname');


问:
Query - min(Cost) and show Supplier for that cost
I've been stuck on a MySQL query. The table is:

```<code>CREATE TABLE items_costs (
  UPC varchar(15) NOT NULL,
  SupplierID int(11) NOT NULL,
  Current_as_of_Date datetime DEFAULT NULL,
  Cost1 float DEFAULT NULL,
  Cost2 float DEFAULT NULL,
  Cost3 float DEFAULT NULL,
  MSRP float DEFAULT NULL,
  MAP float DEFAULT NULL,
  Unique_Entry_Id datetime DEFAULT NULL,
  PRIMARY KEY (UPC,SupplierID),
  KEY SupplierID (SupplierID),
  CONSTRAINT items_costs_ibfk_1 FOREIGN KEY (UPC) REFERENCES items (UPC),
  CONSTRAINT items_costs_ibfk_2 FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8`
</code>```

I'm getting the lowest of Cost1, Cost2, Cost3 for each item:

```<code>MIN(LEAST(IFNULL(ic.Cost3, ic.Cost1), IFNULL(ic.Cost2, ic.Cost1), ic.Cost1)) AS Cost
</code>```

However, now I need to get the SupplierID associated with that particular Cost

I've tried:

```<code>SELECT
    ic.UPC,
    ic.SupplierID,
    ic.Current_as_of_Date,
    ic.Cost1 AS Cost,
    ic.MSRP,
    ic.MAP,
    s.SupplierName,
    s.Map_YN AS Supplier_MAP
FROM
    items_costs AS ic
        JOIN
    suppliers AS s ON s.supplierId = ic.SupplierID
WHERE
    (ic.upc , ic.Cost1) IN (SELECT
            ic_min.UPC,
                MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                        IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
        FROM
            items_costs ic_min
        GROUP BY ic_min.UPC))
</code>```

...which gives the lowest Cost by UPC, as recommended in other threads. However, still getting duplicate UPC's, which should be unique.

What could I be doing wrong here?

Thanks a lot!

答:
Thanks for your help!

I found the answer here, and it seems to be a common question: https://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html

```<code>SELECT
ic1.upc,
ic1.supplierid,
ic1.MSRP,
ic1.MAP,
ROUND((LEAST(IFNULL(ic1.Cost3, ic1.Cost1),
                IFNULL(ic1.Cost2, ic1.Cost1),
                ic1.Cost1)),
        2) AS Cost,
s.SupplierName,
s.Map_YN AS Supplier_MAP
FROM
items_costs AS ic1

    JOIN
suppliers AS s ON s.supplierid = ic1.supplierid

WHERE
ic1.cost1 = (SELECT
        MIN(ic2.cost1)
    FROM
        items_costs AS ic2
    WHERE
        ic1.upc = ic2.upc)
</code>```

Body:
I've been stuck on a MySQL query. The table is:

CREATE TABLE items_costs (
  UPC varchar(15) NOT NULL,
  SupplierID int(11) NOT NULL,
  Current_as_of_Date datetime DEFAULT NULL,
  Cost1 float DEFAULT NULL,
  Cost2 float DEFAULT NULL,
  Cost3 float DEFAULT NULL,
  MSRP float DEFAULT NULL,
  MAP float DEFAULT NULL,
  Unique_Entry_Id datetime DEFAULT NULL,
  PRIMARY KEY (UPC,SupplierID),
  KEY SupplierID (SupplierID),
  CONSTRAINT items_costs_ibfk_1 FOREIGN KEY (UPC) REFERENCES items (UPC),
  CONSTRAINT items_costs_ibfk_2 FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8`

I'm getting the lowest of Cost1, Cost2, Cost3 for each item:

MIN(LEAST(IFNULL(ic.Cost3, ic.Cost1), IFNULL(ic.Cost2, ic.Cost1), ic.Cost1)) AS Cost

However, now I need to get the SupplierID associated with that particular Cost

I've tried:

SELECT
    ic.UPC,
    ic.SupplierID,
    ic.Current_as_of_Date,
    ic.Cost1 AS Cost,
    ic.MSRP,
    ic.MAP,
    s.SupplierName,
    s.Map_YN AS Supplier_MAP
FROM
    items_costs AS ic
        JOIN
    suppliers AS s ON s.supplierId = ic.SupplierID
WHERE
    (ic.upc , ic.Cost1) IN (SELECT
            ic_min.UPC,
                MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                        IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
        FROM
            items_costs ic_min
        GROUP BY ic_min.UPC))

...which gives the lowest Cost by UPC, as recommended in other threads. However, still getting duplicate UPC's, which should be unique.

What could I be doing wrong here?

Thanks a lot!

Body:
Thanks for your help!

I found the answer here, and it seems to be a common question: https://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html

SELECT
ic1.upc,
ic1.supplierid,
ic1.MSRP,
ic1.MAP,
ROUND((LEAST(IFNULL(ic1.Cost3, ic1.Cost1),
                IFNULL(ic1.Cost2, ic1.Cost1),
                ic1.Cost1)),
        2) AS Cost,
s.SupplierName,
s.Map_YN AS Supplier_MAP
FROM
items_costs AS ic1

    JOIN
suppliers AS s ON s.supplierid = ic1.supplierid

WHERE
ic1.cost1 = (SELECT
        MIN(ic2.cost1)
    FROM
        items_costs AS ic2
    WHERE
        ic1.upc = ic2.upc)


问:
Assigning dynamic ids to elements using jQuery
Hi I am using jQuery and creating tags in a loop.

Ex -

```<code>for(var i=0;i<length;i++){

            jQuery("#dailydata").append("<table class='table'><tr>"+
                "<th>Min Temp : </th><td>"+ data[i]</td>" +
                "</tr></table>";

                if(data[i] <=10){
                    //add color to th
                }else{
                    //add different color to th
                }
        }
</code>```

I am creating a Table Row in every loop and appending to a HTML element. and just after that I am checking the value and according to that value I want to change the background color of the  tag.

Can somebody tell me how to achieve this?

答:
Firstly:

You should not use numeric values (0,1,2,3,etc) for ids. The HTML specification say this:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Secondly:

Your code is weight... Did you create a variable called "length" in lines not shown in your example? I assume in your for loop you meant i<data.length

So with that in mind use an alphabetical prefix to your ids:

```<code>// Note jQuery("#dailydata") same as $("#dailydata") unless you override the use of the "$" symbol

for(var i=0; i<data.length; i++) {
    var newElementId = "some_prefix_"+i;

    var newElementToAppend = $("<div>").attr("id", newElementId);
    $("#dailydata").append(newElementToAppend);
}
</code>```

Body:
Hi I am using jQuery and creating tags in a loop.

Ex -

for(var i=0;i<length;i++){

            jQuery("#dailydata").append("

"+
                "Min Temp : 	"+ data[i]	" +
                "

";

                if(data[i] <=10){
                    //add color to th
                }else{
                    //add different color to th
                }
        }

I am creating a Table Row in every loop and appending to a HTML element. and just after that I am checking the value and according to that value I want to change the background color of the  tag.

Can somebody tell me how to achieve this?

Body:
Firstly:

You should not use numeric values (0,1,2,3,etc) for ids. The HTML specification say this:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Secondly:

Your code is weight... Did you create a variable called "length" in lines not shown in your example? I assume in your for loop you meant i<data.length

So with that in mind use an alphabetical prefix to your ids:

// Note jQuery("#dailydata") same as $("#dailydata") unless you override the use of the "$" symbol

for(var i=0; i<data.length; i++) {
    var newElementId = "some_prefix_"+i;

    var newElementToAppend = $("<div>").attr("id", newElementId);
    $("#dailydata").append(newElementToAppend);
}


问:
Cross join on a group based on the condition in SQL Server
I have Item and Exam tables -

My desire result -

I tried a lot but I am unable to join Exam table to Item table based on Code group.

Is it possible to cross join or any other join for these two tables to get the desire result?

答:
I don't see a way around generating the missing data.  The calendar table approach would be to cross join all codes with all exams.  Then, left join this table to Item and order to get the result you want:

```<code>WITH cte AS (
   SELECT *
   FROM (SELECT DISTINCT Code FROM Item) AS C
   CROSS JOIN Exam
)
SELECT
    t1.Code,
    t2.Item,
    t1.Exam
FROM cte t1
LEFT JOIN Item t2
    ON t1.Code = t2.Code AND
       t1.Exam = t2.Exam
ORDER BY
    t1.Code,
    CASE WHEN t2.Item IS NOT NULL THEN 0 ELSE 1 END,
    t1.Exam
</code>```

Demo here:

Rextester

Body:
I don't see a way around generating the missing data.  The calendar table approach would be to cross join all codes with all exams.  Then, left join this table to Item and order to get the result you want:

WITH cte AS (
   SELECT *
   FROM (SELECT DISTINCT Code FROM Item) AS C
   CROSS JOIN Exam
)
SELECT
    t1.Code,
    t2.Item,
    t1.Exam
FROM cte t1
LEFT JOIN Item t2
    ON t1.Code = t2.Code AND
       t1.Exam = t2.Exam
ORDER BY
    t1.Code,
    CASE WHEN t2.Item IS NOT NULL THEN 0 ELSE 1 END,
    t1.Exam

Demo here:

Rextester


问:
How do I utilize dot notation when rendering components?
I have a simple component which is supposed to render different kind of fields into my form component:

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

export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (
          <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>
          )
      }
      case 'text': {
        return (
          <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>
        )
      }
    }
  }
}
</code>```

And I'm using this component in my form component like this:

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

  render() {
    return (
        .
        .
        .
        <Field
          type="text"
          placeholder="something"
          name="something"
        />
        <Field
          type="textarea"
          placeholder="another"
          name="othername"
        />
        .
        .
        .
    )
  }
}
</code>```

What I have in mind is to somehow implement my field component to be able to use dot notation as explained in Using Dot Notation for JSX components which I have seen many other libraries and I want to be able to use this component like this:

```<code><Field.Text name="sth" placeholder="sth" />
<Field.TextArea name="other" placeholder="other stuff" />
</code>```

But I can't do it the way mentioned in React docs. How can I do this?

答:
Simply following the docs.

```<code>const Field = {
  Text: function Text(props) {
    return <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>;
  },
  Textarea: function Textarea(props) {
    return <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>;
  }
}
</code>```

Then when your dot usage

```<code><Field.Text placeholder="something" name="something" />
</code>```

Body:
I have a simple component which is supposed to render different kind of fields into my form component:

import React from "react";

export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (

            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>

          )
      }
      case 'text': {
        return (

            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />

        )
      }
    }
  }
}

And I'm using this component in my form component like this:

export default class SubmitForm extends React.Component {

  render() {
    return (
        .
        .
        .
        <Field
          type="text"
          placeholder="something"
          name="something"
        />
        <Field
          type="textarea"
          placeholder="another"
          name="othername"
        />
        .
        .
        .
    )
  }
}

What I have in mind is to somehow implement my field component to be able to use dot notation as explained in Using Dot Notation for JSX components which I have seen many other libraries and I want to be able to use this component like this:

<Field.Text name="sth" placeholder="sth" />
<Field.TextArea name="other" placeholder="other stuff" />

But I can't do it the way mentioned in React docs. How can I do this?

Body:
Simply following the docs.

const Field = {
  Text: function Text(props) {
    return <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>;
  },
  Textarea: function Textarea(props) {
    return <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>;
  }
}

Then when your dot usage

<Field.Text placeholder="something" name="something" />


问:
Selenium WebDriverException: Reached error page
I am following a Django TDD tutorial at:

http://www.marinamele.com/taskbuster-django-tutorial/taskbuster-working-environment-and-start-django-project

I get the following error when running 'all_users.py' before and after I start the development server 'python manage.py runserver':

Traceback (most recent call last):
   File "functional_tests/all_users.py", line 15, in test_it_worked
     self.browser.get('http://localhost:8000')
   File "/Users/samgao/.virtualenvs/tb_test/lib/python3.6/site->packages/selenium/webdriver/remote/webdriver.py", line 264, in get
     self.execute(Command.GET, {'url': url})
   File "/Users/samgao/.virtualenvs/tb_test/lib/python3.6/site->packages/selenium/webdriver/remote/webdriver.py", line 252, in execute
     self.error_handler.check_response(response)
   File "/Users/samgao/.virtualenvs/tb_test/lib/python3.6/site->packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
     raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.WebDriverException: Message: Reached error page: >about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF->8&f=regular&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20s>erver%20at%20localhost%3A8000.

Basically the connection to localhost cannot be established.

The settings and configurations are identical to the tutorial in the previous link.

I have been struggling with the issue for two days, and would thank you most kindly if you could provide any help.

答:
Being that this is a snapshot (around Django 1.8's time) of "Obey The Testing Goat" - perhaps the instructions there are no longer relevant. I suggest going straight to the goat's mouth and starting over!

The issue could be related to virtualenvwrapper (which is no longer necessary) or it could be related to the port/address that you were trying to access. Depending on your version of Selenium and Firefox there may be issues related to that as well.


问:
What are practical guidelines for evaluating a language's "Turing Completeness"?
I've read "what-is-turing-complete" and the wikipedia page, but I'm less interested in a formal proof than in the practical implications of requirements for being Turing Complete.

What I'm actually trying to decide is if the toy language I've just designed could be used as a general-purpose language.  I know I can prove it is if I can write a Turing machine with it.  But I don't want to go through that exercise until I'm fairly certain of success.

Is there a minimum set of features without which Turing Completeness is impossible?
Is there a set of features which virtually guarantees completeness?

(My guess is that conditional branching and a readable/writeable memory store will get me most of the way there)

EDIT:

I think I've gone off on a tangent by saying "Turing Complete".   I'm trying to guess with reasonable confidence that a newly invented language with a certain feature set (or alternately, a VM with a certain instruction set) would be able to compute anything worth computing.  I know that proving you can build a Turing machine with it is one way, but not the only way.

What I was hoping for was a set of guidelines like: "if a language can do X,Y,and Z, it can probably do anything".

答:
You need some form of dynamic allocation construct (malloc ornew or cons will do) and either recursive functions or some other way of writing an infinite loop.  If you have those and can do anything at all interesting, you're almost certainly Turing-complete.

The lambda calculus is equivalent in power to a Turing machine, and if you implement lambda calculus it is actually pretty fun writing lambda calculus programs.  Way more fun than writing program for a Turing machine!

The only practical implication of Turing-completeness I'm aware of is that you can write programs that don't terminate.  I've used a couple of special-purpose languages that guarantee termination and therefore are not Turing-complete.  Sometimes it is useful to give up the extra expressive power in exchange for guaranteed termination.

OwnerDisplayName: AShelly

LastEditorDisplayName: AShelly

OwnerDisplayName: Norman Ramsey


问:
Pre Project Documentation
I have an issue that I feel many programmers can relate to...

I have worked on many small scale projects. After my initial paper brain storm I tend to start coding. What I come up with is usually a rough working model of the actual application. I design in a disconnected fashion so I am talking about underlying code libraries, user interfaces are the last thing as the library usually dictates what is needed in the UI. As my projects get bigger I worry that so should my "spec" or design document.

The above paragraph, from my investigations, is echoed all across the internet in one fashion or another. When a UI is concerned there is a bit more information but it is UI specific and does not relate to code libraries. What I am beginning to realise is that maybe code is code is code. It seems from my extensive research that there is no 1:1 mapping between a design document and the code.

When I need to research a topic I dump information into OneNote and from there I prioritise features into versions and then into related chunks so that development runs in a fairly linear fashion, my tasks tend to look like so:

Implement Binary File Reader

Implement Binary File Writer

Create Object to encapsulate Data for expression to the caller

Now any programmer worth his salt is aware that between those three to do items could be a potential wall of code that could expand out to multiple files. I have tried to map the complete code process for each task but I simply don't think it can be done effectively. By the time one mangles pseudo code it is essentially code anyway so the time investment is negated.

So my question is this:

Am I right in assuming that the best documentation is the code itself. We are all in agreement that a high level overview is needed. How high should this be? Do you design to statement, class or concept level? What works for you?

答:
I think what you want is a software requirements specification.

Coding all the stuff in a chaotic way is a wrong mode of do the job!
What you need is to create a list of function/non-functional requirements to create a linked/related/child/parent relationship with the requirements of the UI and for the business actor create use case.

After this step you need to eventually manage all the design interface in UML or SPEUDO Code, but when you are formalized the requirements (for small project) the need to have UML is putt off.

For the documentation of the code you can use doxygen or javadoc approch where in short,
you insert comment on the code and with a software all the doc is putted off in HTML/PDF.

With this way you are reached in sequence this stuff:

1 - software requirement

Now you have the complete overview of what is your software and maybe what functionality you software need with what constraints (technical/non-technical/time/business).
And also user case to test the software in the last stage of the development life cycle.

2 - UML or PSEUDO CODE

An easy way to split your work to other colleague and a simple code overview of the code interface design.

3 - library documentation for other coders like you and all the benefits to dont waste too match time to write down all the doc at the end of the project!

my 2 cents.

google keywords:
software engineering doxygen software development life cycle, CMMI, IEEE SRS (Software requirements specification).

Title: Pre Project Documentation


问:
list.append in python 3: nonetype is not iterable?
I am trying to add every word in romeo.txt to an empty list.

I thought this code was okay but python3 returns a traceback saying

File "test.py", line 13, in <module>
      if i in lst:
  TypeError: argument of type 'NoneType' is not iterable

here's my code:

```<code>fh = open("romeo.txt")
lst = list()
words = fh.read()
list1 = words.split()
for i in list1:
    if i in lst:
        continue
    else:
        lst = lst.append(i)
lst = lst.sort()
print(lst)
</code>```

答:
Explanation

You are making the same mistake twice. The first place you are making this error and the reason why you are getting the current error you are seeing is because of this:

```<code>lst = lst.append(i)
</code>```

The append method actually performs the append in place. The actual return of that call is going to be None, because it doesn't return anything. It doesn't need to, since it does the work on the list.

So, to narrow down exactly what is going on. When you did lst = lst.append(i). lst will now hold None. So, the next time it goes through its loop and you get here:

```<code>if i in lst:
</code>```

You are checking if i is in None. Since now lst will hold None, it is exactly here where your error message gets raised and you are seeing that Traceback.

To replicate:

```<code>   >>> 'a' in None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'NoneType' is not iterable
</code>```

Solution

To solve this, you just need perform the append like:

```<code>lst.append(i)
</code>```

Second Mistake

You are also making the same mistake when calling sort here:

```<code>lst = lst.sort()
</code>```

It is again a method that performs its work in place, therefore you just need:

```<code>lst.sort()
</code>```

Extra Note

Don't forget to close your file at the end of your code (or when you are done using the file:

```<code>fh.close()
</code>```

Ideally, it is always best to use a context manager as explained in the other answer here. Since the context manager does all the "cleanup" work for you.

Body:
I am trying to add every word in romeo.txt to an empty list.

I thought this code was okay but python3 returns a traceback saying

File "test.py", line 13, in <module>
      if i in lst:
  TypeError: argument of type 'NoneType' is not iterable

here's my code:

fh = open("romeo.txt")
lst = list()
words = fh.read()
list1 = words.split()
for i in list1:
    if i in lst:
        continue
    else:
        lst = lst.append(i)
lst = lst.sort()
print(lst)

Body:
Explanation

You are making the same mistake twice. The first place you are making this error and the reason why you are getting the current error you are seeing is because of this:

lst = lst.append(i)

The append method actually performs the append in place. The actual return of that call is going to be None, because it doesn't return anything. It doesn't need to, since it does the work on the list.

So, to narrow down exactly what is going on. When you did lst = lst.append(i). lst will now hold None. So, the next time it goes through its loop and you get here:

if i in lst:

You are checking if i is in None. Since now lst will hold None, it is exactly here where your error message gets raised and you are seeing that Traceback.

To replicate:

   >>> 'a' in None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'NoneType' is not iterable

Solution

To solve this, you just need perform the append like:

lst.append(i)

Second Mistake

You are also making the same mistake when calling sort here:

lst = lst.sort()

It is again a method that performs its work in place, therefore you just need:

lst.sort()

Extra Note

Don't forget to close your file at the end of your code (or when you are done using the file:

fh.close()

Ideally, it is always best to use a context manager as explained in the other answer here. Since the context manager does all the "cleanup" work for you.


问:
Android hooking of abstract class method calls using Frida
I am trying to learn Frida and have experimented with a little so far. Things have mostly worked as thankfully I could find enough examples and tutorials to help me through.
However, at this point in time, I am stuck with a very specific task at hand.

So let's say below is the Frida hook I am referring to:

```<code>Java.perform(function () {

var Activity = Java.use("myPack.myClass");

Activity.methodM1.overload('[B', 'java.lang.String').implementation = function (a, str) {

    var retval = this.methodM1(a, str);

    console.log("[*] return value4: "+retval);

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

Now as per my understanding so far, with Java.use above, I am saying that whenever an Object of myPackage.myClass is made and if that object calls the method, methodM1, get the control to my javascript function instead and do whatever is mentioned in there.

Which does the job as expected. However, the point (of interest for the sake of this discussion) was: IF the object gets made then this would happen.

Similarly, instead of Java.use, if we were talking about Java.choose() also, the situation would have been the same. So even in that case, we are saying that IF the object gets made, then call my callback.

Now, what would happen if I am trying to hook into a method of an abstract class So let's say I am trying to hook into the method

'static getInstance(String)'
  of
  java.security.KeyPairGenerator (which is an abstract class).

This class being abstract, it's object never really gets made at all. And the method being static, it is directly called using the class name itself. So in this case, neither Java.use() nor Java.choose() will be able to help (if my understanding above is correct).

So how do I hook into the getInstance() at all in such a situation?

Here's something that I have already tried:

```<code>Java.perform(
  function()
  {
    Java.enumerateLoadedClasses(
    {
      onMatch: function(className)
      {
        if(className == "java.security.KeyPairGenerator")
        {
          var item = Java.use(className);

          console.log("the PrivateKey class was just loaded");
          item.getInstance.overload('java.lang.String').implementation = function(str)
          {
            console.log("[*] This got called ");
            var ret = item.getInstance(str);
            console.log("[*] return value4: "+retval);
            return retval;
          }
        }
      },
      onComplete:function(){}
    });
  }
);
</code>```

But this does not work. Again, my assumption here is that whenever the Object gets made and the getInstance() gets called, hook it. But here, KeyPairGenerator being an abstract class, it never really gets instantiated in the first place itself. I have also tried :

className.getInstance()

instead of

item.getInstance()

and that does not work either.

答:
In addition to the awesome answer by @D4l3k, just in case anyone is on an older version of Frida (for whatsoever reasons) like I was on 10.0.5, early instrumentation can still be achieved using :
Java.performNow() instead of Java.perform()

Below is a working sample using Java.performNow():

```<code>Java.performNow(
  function()
  {
    var item = Java.use("java.security.KeyPairGenerator");
    console.log("the PrivateKey class was just loaded");
    item.getInstance.overload('java.lang.String').implementation = function(str)
    {
      console.log("[*] This got called " + str);
      var ret = this.getInstance(str);
      console.log("[*] return value4: "+ret);
      return ret;
    }
  }
);
</code>```

Body:
I am trying to learn Frida and have experimented with a little so far. Things have mostly worked as thankfully I could find enough examples and tutorials to help me through.
However, at this point in time, I am stuck with a very specific task at hand.

So let's say below is the Frida hook I am referring to:

Java.perform(function () {

var Activity = Java.use("myPack.myClass");

Activity.methodM1.overload('[B', 'java.lang.String').implementation = function (a, str) {

    var retval = this.methodM1(a, str);

    console.log("[*] return value4: "+retval);

    return retval;
};
});

Now as per my understanding so far, with Java.use above, I am saying that whenever an Object of myPackage.myClass is made and if that object calls the method, methodM1, get the control to my javascript function instead and do whatever is mentioned in there.

Which does the job as expected. However, the point (of interest for the sake of this discussion) was: IF the object gets made then this would happen.

Similarly, instead of Java.use, if we were talking about Java.choose() also, the situation would have been the same. So even in that case, we are saying that IF the object gets made, then call my callback.

Now, what would happen if I am trying to hook into a method of an abstract class So let's say I am trying to hook into the method

'static getInstance(String)'
  of
  java.security.KeyPairGenerator (which is an abstract class).

This class being abstract, it's object never really gets made at all. And the method being static, it is directly called using the class name itself. So in this case, neither Java.use() nor Java.choose() will be able to help (if my understanding above is correct).

So how do I hook into the getInstance() at all in such a situation?

Here's something that I have already tried:

Java.perform(
  function()
  {
    Java.enumerateLoadedClasses(
    {
      onMatch: function(className)
      {
        if(className == "java.security.KeyPairGenerator")
        {
          var item = Java.use(className);

          console.log("the PrivateKey class was just loaded");
          item.getInstance.overload('java.lang.String').implementation = function(str)
          {
            console.log("[*] This got called ");
            var ret = item.getInstance(str);
            console.log("[*] return value4: "+retval);
            return retval;
          }
        }
      },
      onComplete:function(){}
    });
  }
);

But this does not work. Again, my assumption here is that whenever the Object gets made and the getInstance() gets called, hook it. But here, KeyPairGenerator being an abstract class, it never really gets instantiated in the first place itself. I have also tried :

className.getInstance()

instead of

item.getInstance()

and that does not work either.

Body:
In addition to the awesome answer by @D4l3k, just in case anyone is on an older version of Frida (for whatsoever reasons) like I was on 10.0.5, early instrumentation can still be achieved using :
Java.performNow() instead of Java.perform()

Below is a working sample using Java.performNow():

Java.performNow(
  function()
  {
    var item = Java.use("java.security.KeyPairGenerator");
    console.log("the PrivateKey class was just loaded");
    item.getInstance.overload('java.lang.String').implementation = function(str)
    {
      console.log("[*] This got called " + str);
      var ret = this.getInstance(str);
      console.log("[*] return value4: "+ret);
      return ret;
    }
  }
);


答:
Try this,</p>

```<code>class Login extends CI_Controller {
public function __construct(){
    parent::__construct();
            $this->load->helper('url');
    //LOAD MODELS HERE
    $this->load->model('Login_model');
}

public function index(){
    $this->load->view('login/login_registration.php');
}

public function home(){
    $this->load->view('login/home.php');
}

function login_user(){
    $login_btn = $this->input->post('login_btn');

    if($login_btn == TRUE){
        $arr['login'] = array(
            'username'=>$this->input->post('username'),
            'password'=>$this->input->post('password')
        );

        $query = $this->Login_model->users_login($arr);

        if($query->num_rows() > 0 && $query->num_rows() == 1){
            $this->load->library('session');
            $this->session->set_userdata($arr['login']);
            redirect('login/home', 'location');
        }
        else
        {
            $this->index();
        }
    }
    else
    {
        $this->index();
    }
}
}
</code>```

Title: Issue with CodeIgniter redirect

Body:
Try this,

class Login extends CI_Controller {
public function __construct(){
    parent::__construct();
            $this->load->helper('url');
    //LOAD MODELS HERE
    $this->load->model('Login_model');
}

public function index(){
    $this->load->view('login/login_registration.php');
}

public function home(){
    $this->load->view('login/home.php');
}

function login_user(){
    $login_btn = $this->input->post('login_btn');

    if($login_btn == TRUE){
        $arr['login'] = array(
            'username'=>$this->input->post('username'),
            'password'=>$this->input->post('password')
        );

        $query = $this->Login_model->users_login($arr);

        if($query->num_rows() > 0 && $query->num_rows() == 1){
            $this->load->library('session');
            $this->session->set_userdata($arr['login']);
            redirect('login/home', 'location');
        }
        else
        {
            $this->index();
        }
    }
    else
    {
        $this->index();
    }
}
}


答:
Your problem is this line:

```<code>lst = lst.append(i)
</code>```

list.append() does not return a new list, it works in-place and returns None. That means you're only assigning lst to None. So when you try to use lst in your next iteration, it fails. Just remove the assignment to list.append():

```<code>lst.append(i)
</code>```

Note you also make the same mistake here:

```<code>lst = lst.sort()
</code>```

list.sort() works in-place. Remove the assignment.

Your code can also be improved in several ways:

Use the context manger to open your file. This ensures that your file will always close.

Since you appear to be filtering duplicates from your list, you can use a set instead to remove the duplicates, and sort the remaining words afterwards as @Julien suggested.

Here is how the new code would look:

```<code>with open('romeo.txt', 'r') as file:
    words = set(file.read().split())
    lst = sorted(words)

print(lst)
</code>```

Title: list.append in python 3: nonetype is not iterable?

Body:
Your problem is this line:

lst = lst.append(i)

list.append() does not return a new list, it works in-place and returns None. That means you're only assigning lst to None. So when you try to use lst in your next iteration, it fails. Just remove the assignment to list.append():

lst.append(i)

Note you also make the same mistake here:

lst = lst.sort()

list.sort() works in-place. Remove the assignment.

Your code can also be improved in several ways:

Use the context manger to open your file. This ensures that your file will always close.

Since you appear to be filtering duplicates from your list, you can use a set instead to remove the duplicates, and sort the remaining words afterwards as @Julien suggested.

Here is how the new code would look:

with open('romeo.txt', 'r') as file:
    words = set(file.read().split())
    lst = sorted(words)

print(lst)