问:
transfer object ownership with placement new
I have a Visual Studio 2008 C++ project with a class that manages a resource that cannot be copied. I have implemented transfer-by-reference-structure semantics (ala std::auto_ptr).

```<code>class Test;

struct Test_Ref
{
    Test& ref_;
    Test_Ref( Test& t ) : ref_( t ) { };
private:
    Test_Ref& operator=( Test_Ref const& );
}; // struct Test_Ref

class Test
{
public:
    explicit Test( int f = 0 ) : foo_( f ) { };

    Test( Test& other ) : foo_( other.Detach() ) { };

    Test& operator=( Test& other )
    {
        foo_ = other.Detach();
        return *this;
    };

    Test( Test_Ref other ) : foo_( other.ref_.Detach() ) { };

    Test& operator=( Test_Ref other )
    {
        foo_ = other.ref_.Detach();
        return *this;
    };

    operator Test_Ref() { return Test_Ref( *this ); };

private:

    int Detach()
    {
        int tmp = foo_;
        foo_ = 0;
        return tmp;
    };

    // resource that cannot be copied.
    int foo_;
}; // class Test
</code>```

Unfortunately, when I use this pattern with a library that uses placement-new, I get a compiler error:

```<code>.\test.cpp(58) : error C2558: class 'Test' : no copy constructor available or copy constructor is declared 'explicit'
    .\test.cpp(68) : see reference to function template instantiation 'void Copy<Test>(T *,const T &)' being compiled
    with
    [
        T=Test
    ]
</code>```

For example:

```<code>template< class T > inline void Copy( T* p, const T& val )
{
    new( p ) T( val );
}

int _tmain( int /*argc*/, _TCHAR* /*argv*/[] )
{
    Test* __p = new Test();
    Test __val;
    Copy( __p, __val );
    return 0;
}
</code>```

How can I modify Test such that it can be used with placement new and still retain its ownership semantics?

Thanks,
PaulH

答:
Focusing on the main function, as that should indicate your intended semantics, there are two big problems: First, you are not allocating memory, which means that if the compiler would process the code, it would cause UB (would try to call the constructor of Test over the NULL address in the placement new operation.

The other issue is well known to users of std::auto_ptr: The signature of the copy constructor takes a non-const reference, and that means that you cannot call it on a const object. On the other end you are trying to call the copy constructor inside the Copy template that promised not to change the object referenced by the second argument:

```<code>template <typename T>
void Copy( T* p, T& o ) {
   new (p) T( o );         // would work, object is non-const
}
</code>```

Finally, I am not sure if due to copying into the question, but I am not sure of what your intentions are with the reference wrapper class that you are providing in the beginning, so you might want to clarify.

Body:
I have a Visual Studio 2008 C++ project with a class that manages a resource that cannot be copied. I have implemented transfer-by-reference-structure semantics (ala std::auto_ptr).

class Test;

struct Test_Ref
{
    Test& ref_;
    Test_Ref( Test& t ) : ref_( t ) { };
private:
    Test_Ref& operator=( Test_Ref const& );
}; // struct Test_Ref

class Test
{
public:
    explicit Test( int f = 0 ) : foo_( f ) { };

    Test( Test& other ) : foo_( other.Detach() ) { };

    Test& operator=( Test& other )
    {
        foo_ = other.Detach();
        return *this;
    };

    Test( Test_Ref other ) : foo_( other.ref_.Detach() ) { };

    Test& operator=( Test_Ref other )
    {
        foo_ = other.ref_.Detach();
        return *this;
    };

    operator Test_Ref() { return Test_Ref( *this ); };

private:

    int Detach()
    {
        int tmp = foo_;
        foo_ = 0;
        return tmp;
    };

    // resource that cannot be copied.
    int foo_;
}; // class Test

Unfortunately, when I use this pattern with a library that uses placement-new, I get a compiler error:

.\test.cpp(58) : error C2558: class 'Test' : no copy constructor available or copy constructor is declared 'explicit'
    .\test.cpp(68) : see reference to function template instantiation 'void Copy<Test>(T *,const T &)' being compiled
    with
    [
        T=Test
    ]

For example:

template< class T > inline void Copy( T* p, const T& val )
{
    new( p ) T( val );
}

int _tmain( int /*argc*/, _TCHAR* /*argv*/[] )
{
    Test* __p = new Test();
    Test __val;
    Copy( __p, __val );
    return 0;
}

How can I modify Test such that it can be used with placement new and still retain its ownership semantics?

Thanks,
PaulH

Body:
Focusing on the main function, as that should indicate your intended semantics, there are two big problems: First, you are not allocating memory, which means that if the compiler would process the code, it would cause UB (would try to call the constructor of Test over the NULL address in the placement new operation.

The other issue is well known to users of std::auto_ptr: The signature of the copy constructor takes a non-const reference, and that means that you cannot call it on a const object. On the other end you are trying to call the copy constructor inside the Copy template that promised not to change the object referenced by the second argument:

template <typename T>
void Copy( T* p, T& o ) {
   new (p) T( o );         // would work, object is non-const
}

Finally, I am not sure if due to copying into the question, but I am not sure of what your intentions are with the reference wrapper class that you are providing in the beginning, so you might want to clarify.


来源: stackexchange

问:
How do I prevent recursive results in RestController?
Classes:

```<code>@Entity
@Table(name = "question")
@Data
@NoArgsConstructor
public class Question {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column
private String text;

@OneToMany(mappedBy="question", fetch = FetchType.LAZY)
private List<Answer> answers;

public void addAnswer(Answer answer){
    answer.setQuestion(this);
    this.answers.add(answer);
}
}

@Entity
@Table(name = "answer")
@Data
@NoArgsConstructor
public class Answer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@Column
private String text;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="question_id")
private Question question;
}
</code>```

Controller:

```<code>@RestController
@CrossOrigin("*")
@RequestMapping("/question")
public class QuestionController {

@Autowired
private QuestionRepository questionRepository;

@GetMapping
public List<Question> list(){
    return questionRepository.findAll();
}

@PostMapping(value = "")
public Question add(@RequestBody Question question){
    return questionRepository.save(question);
}
}
</code>```

calling 'localhost:8080/answer' returns this:

```<code>{
"text": "something else again",
"question": {
    "id": 4,
    "text": "question 3",
    "answers": [
        {
            "id": 1,
            "text": "something",
            "question": {
                "id": 4,
                "text": "question 3",
                "answers": [
                    {
                        "id": 1,
                        "text": "something",
                        "question": {
                            "id": 4,
                            "text": "question 3",
                            "answers": [
                                {
                                    "id": 1,
                                    "text": "something",
                                    "question": {
                                        "id": 4,
                                        "text": "question 3",
                                        "answers": [
                                            {
                                                "id": 1,
                                                "text": "something",
                                                "question": {
                                                    "id": 4,
                                                    "text": "question 3",
                                                    "answers": [
                                                        {
                                                            "id": 1,
                                                            "text": "something",
                                                            "question": {
                                                                "id": 4,
                                                                "text": "question 3",
                                                                "answers": [
                                                                    {
                                                                        "id": 1,
                                                                        "text": "something",
                                                                        "question": {
                                                                            "id": 4,
                                                                            "text": "question 3",
                                                                            "answers": [
                                                                                {
                                                                                "id": 1,
                                                                                "text": "something",
                                                                                "question": {
                                                                                "id": 4,
                                                                                "text": "question 3",
                                                                                "answers": [
                                                                                {
                                                                                "id": 1,
                                                                                "text": "something",
                                                                                "question": {
                                                                                "id": 4,
                                                                                "text": "question 3",
                                                                                "answers": [
</code>```

Shouldn't it just return something like this:

```<code>{
"text": "something else again",
"question": {
    "id": 4,
    "text": "question 3",
    "answers": [
        {
            "id": 1,
            "text": "something"
         }
    ]
}
</code>```

答:
It depends on what JSON library you use to serialise object to JSON. In case you are using Jackson , you can use @JsonIgnoreProperties to break the cycles:

@Entity
@Table(name = "question")
public class Question {

         [....]

         @JsonIgnoreProperties("question")
         public List<Answer> getAnswers(){
             return answers;
         }
}
```

<p>The same issue may probably happen if you get Answer , so you may also need to break the cycle from there:</p>

<pre class="lang-java prettyprint-override"><code>@Entity
@Table(name = "answer")
public class Answer {

         [....]

         @JsonIgnoreProperties("answers")
         public Question getQuestion(){
             return question;
         }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Classes:

@Entity
@Table(name = "question")
@Data
@NoArgsConstructor
public class Question {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column
private String text;

@OneToMany(mappedBy="question", fetch = FetchType.LAZY)
private List<Answer> answers;

public void addAnswer(Answer answer){
    answer.setQuestion(this);
    this.answers.add(answer);
}
}

@Entity
@Table(name = "answer")
@Data
@NoArgsConstructor
public class Answer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@Column
private String text;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="question_id")
private Question question;
}

Controller:

@RestController
@CrossOrigin("*")
@RequestMapping("/question")
public class QuestionController {

@Autowired
private QuestionRepository questionRepository;

@GetMapping
public List<Question> list(){
    return questionRepository.findAll();
}

@PostMapping(value = "")
public Question add(@RequestBody Question question){
    return questionRepository.save(question);
}
}

calling 'localhost:8080/answer' returns this:

{
"text": "something else again",
"question": {
    "id": 4,
    "text": "question 3",
    "answers": [
        {
            "id": 1,
            "text": "something",
            "question": {
                "id": 4,
                "text": "question 3",
                "answers": [
                    {
                        "id": 1,
                        "text": "something",
                        "question": {
                            "id": 4,
                            "text": "question 3",
                            "answers": [
                                {
                                    "id": 1,
                                    "text": "something",
                                    "question": {
                                        "id": 4,
                                        "text": "question 3",
                                        "answers": [
                                            {
                                                "id": 1,
                                                "text": "something",
                                                "question": {
                                                    "id": 4,
                                                    "text": "question 3",
                                                    "answers": [
                                                        {
                                                            "id": 1,
                                                            "text": "something",
                                                            "question": {
                                                                "id": 4,
                                                                "text": "question 3",
                                                                "answers": [
                                                                    {
                                                                        "id": 1,
                                                                        "text": "something",
                                                                        "question": {
                                                                            "id": 4,
                                                                            "text": "question 3",
                                                                            "answers": [
                                                                                {
                                                                                "id": 1,
                                                                                "text": "something",
                                                                                "question": {
                                                                                "id": 4,
                                                                                "text": "question 3",
                                                                                "answers": [
                                                                                {
                                                                                "id": 1,
                                                                                "text": "something",
                                                                                "question": {
                                                                                "id": 4,
                                                                                "text": "question 3",
                                                                                "answers": [

Shouldn't it just return something like this:

{
"text": "something else again",
"question": {
    "id": 4,
    "text": "question 3",
    "answers": [
        {
            "id": 1,
            "text": "something"
         }
    ]
}

Body:
It depends on what JSON library you use to serialise object to JSON. In case you are using Jackson , you can use @JsonIgnoreProperties to break the cycles:

@Entity
@Table(name = "question")
public class Question {

         [....]

         @JsonIgnoreProperties("question")
         public List<Answer> getAnswers(){
             return answers;
         }
}

The same issue may probably happen if you get Answer , so you may also need to break the cycle from there:

@Entity
@Table(name = "answer")
public class Answer {

         [....]

         @JsonIgnoreProperties("answers")
         public Question getQuestion(){
             return question;
         }
}


问:
Accessing an element inside an array with multiple objects
I'm trying to use an api with football teams, I want to simply render the name of the teams in a div or a list. But it just render the last one.

When I console.log it, it shows all the teams

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    }
  }
  componentDidMount() {
    fetch('https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League')
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json,
        })
      })
  }
  render() {
    var {
      isLoaded,
      data
    } = this.state;
    if (!isLoaded) {
      return
 Loading...

    } else {
      for (var key in data.teams) {
        if (data.teams.hasOwnProperty(key))
          console.log(data.teams[key].strTeam)
      }
      return (

        Premier League Teams!{
          data.teams[key].strTeam
        }

      );
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
Try this,

import React from "react";

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League"
    )
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json
        });
      });
  }

  render() {
    var { isLoaded, data } = this.state;

    if (!isLoaded) {
      return
Loading...
;
    } else {
      return (

          Premier League Teams!
          {data.teams.map(team => (

 {team.strTeam}

          ))}

      );
    }
  }
}
export default Test;
```

Body:
Try this,

import React from "react";

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League"
    )
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json
        });
      });
  }

  render() {
    var { isLoaded, data } = this.state;

    if (!isLoaded) {
      return <div>Loading... </div>;
    } else {
      return (
        <div className="App">
          Premier League Teams!
          {data.teams.map(team => (
            <div> {team.strTeam} </div>
          ))}
        </div>
      );
    }
  }
}
export default Test;


问:
custom tableviewcell dynamic height not updating as per constraints (with programmatically autolayout)
I have a custom uitableviewcell in app, I am trying to update its length dynamically based on its subviews (labels) contents.

but it's not working.

find related code as below.

```<code>class TransactionTableViewCell: UITableViewCell{

    private lazy var dateLabel: UILabel = {
        let datelabel = UILabel()
        datelabel.textColor = .label
        datelabel.backgroundColor = .red
        datelabel.lineBreakMode = .byTruncatingTail
        datelabel.numberOfLines = 0
        datelabel.translatesAutoresizingMaskIntoConstraints = false
        return datelabel
    }()

another method in same class:

 func setupDefaultUI(){
        self.contentView.addSubview(dateLabel)
}

 override func awakeFromNib() {
        super.awakeFromNib()
        setupDefaultUI()
        buildConstraints()
    }

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupDefaultUI()
        buildConstraints()
    }

 func buildConstraints(){

        let marginGuide = self.contentView

        NSLayoutConstraint.activate([
            dateLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor)
            ,
            dateLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor),
            dateLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor),
            dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
            ,

            dateLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor)
  ])
    }

</code>```

and inside viewcontroller file:

```<code> private lazy var transactionTableView: UITableView = {
        let tableview = UITableView.init()
        tableview.backgroundView = nil
        tableview.backgroundColor = .clear
        tableview.rowHeight = UITableView.automaticDimension
        tableview.estimatedRowHeight = 300
        return tableview
    }()

</code>```

and in viewdidload:

```<code>    transactionTableView.dataSource = Objdatasource
        transactionTableView.delegate = Objdelegate

        transactionTableView.register(TransactionTableViewCell.self, forCellReuseIdentifier: CellIdentifiers.transactionCell)

</code>```

答:
Remove this</p>

```<code>dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
</code>```

Body:
I have a custom uitableviewcell in app, I am trying to update its length dynamically based on its subviews (labels) contents.

but it's not working.

find related code as below.

class TransactionTableViewCell: UITableViewCell{

    private lazy var dateLabel: UILabel = {
        let datelabel = UILabel()
        datelabel.textColor = .label
        datelabel.backgroundColor = .red
        datelabel.lineBreakMode = .byTruncatingTail
        datelabel.numberOfLines = 0
        datelabel.translatesAutoresizingMaskIntoConstraints = false
        return datelabel
    }()

another method in same class:

 func setupDefaultUI(){
        self.contentView.addSubview(dateLabel)
}

 override func awakeFromNib() {
        super.awakeFromNib()
        setupDefaultUI()
        buildConstraints()
    }

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupDefaultUI()
        buildConstraints()
    }

 func buildConstraints(){

        let marginGuide = self.contentView

        NSLayoutConstraint.activate([
            dateLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor)
            ,
            dateLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor),
            dateLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor),
            dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
            ,

            dateLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor)
  ])
    }

and inside viewcontroller file:

 private lazy var transactionTableView: UITableView = {
        let tableview = UITableView.init()
        tableview.backgroundView = nil
        tableview.backgroundColor = .clear
        tableview.rowHeight = UITableView.automaticDimension
        tableview.estimatedRowHeight = 300
        return tableview
    }()

and in viewdidload:

    transactionTableView.dataSource = Objdatasource
        transactionTableView.delegate = Objdelegate

        transactionTableView.register(TransactionTableViewCell.self, forCellReuseIdentifier: CellIdentifiers.transactionCell)

Body:
Remove this

dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)


问:
How do I get list of Physical Partition in Azure CosmosDb, is there a way to get list of physical partitions?
Although I am setting high RUs, I am not getting required results.

Background is: I am working on IOT application and unfortunately partition key set is very bad {deviceID}+ {dd/mm/yyyy hh:mm:sec:}, which means technically speaking each logical partition would have very less items (never reach 10 GB limit), but I feel there is a huge number of physical partitions got created which is forcing my RUs to split. How do I get physical partition list

答:
This information used to be displayed straight forwardly in the portal but this was removed in a redesign.

I feel that this is a mistake as provisoning RU requires knowledge of peak RU per partition multiplied by number of partitions so this number should be easily accessible.

The information is returned in the JSON returned to the portal but not shown to us. For collections provisioned with dedicated throughput (i.e. not using database provisioned throughput) this javascript bookmark shows the information.

```<code>javascript:(function () {     var ss = ko.contextFor($(".ext-quickstart-tabs-left-margin")[0]).$rawData().selectedSection();      var coll = ss.selectedCollectionId();      if (coll === null) {         alert("Please drill down into a specific container");     }     else {         alert("Partition count for container " + coll + " is " + ss.selectedCollectionPartitionCount());     } })();
</code>```

Visit the metrics tab in the portal and select the database and container and then run the bookmark to see the count in an alert box as below.

You can also see this information from the pkranges REST end point. This is used by the SDK. Some code that works in the V2 SDK is below

```<code>var documentClient = new DocumentClient(new Uri(endpointUrl), authorizationKey,
 new ConnectionPolicy {
  ConnectionMode = ConnectionMode.Direct
 });

var partitionKeyRangesUri = UriFactory.CreatePartitionKeyRangesUri(dbName, collectionName);
FeedResponse < PartitionKeyRange > response = null;

do {
 response = await documentClient.ReadPartitionKeyRangeFeedAsync(partitionKeyRangesUri,
  new FeedOptions {
   MaxItemCount = 1000
  });
 foreach(var pkRange in response) {
  //TODO: Something with the pkRange
 }

} while (!string.IsNullOrEmpty(response.ResponseContinuation));
</code>```

Body:
This information used to be displayed straight forwardly in the portal but this was removed in a redesign.

I feel that this is a mistake as provisoning RU requires knowledge of peak RU per partition multiplied by number of partitions so this number should be easily accessible.

The information is returned in the JSON returned to the portal but not shown to us. For collections provisioned with dedicated throughput (i.e. not using database provisioned throughput) this javascript bookmark shows the information.

javascript:(function () {     var ss = ko.contextFor($(".ext-quickstart-tabs-left-margin")[0]).$rawData().selectedSection();      var coll = ss.selectedCollectionId();      if (coll === null) {         alert("Please drill down into a specific container");     }     else {         alert("Partition count for container " + coll + " is " + ss.selectedCollectionPartitionCount());     } })();

Visit the metrics tab in the portal and select the database and container and then run the bookmark to see the count in an alert box as below.

You can also see this information from the pkranges REST end point. This is used by the SDK. Some code that works in the V2 SDK is below

var documentClient = new DocumentClient(new Uri(endpointUrl), authorizationKey,
 new ConnectionPolicy {
  ConnectionMode = ConnectionMode.Direct
 });

var partitionKeyRangesUri = UriFactory.CreatePartitionKeyRangesUri(dbName, collectionName);
FeedResponse < PartitionKeyRange > response = null;

do {
 response = await documentClient.ReadPartitionKeyRangeFeedAsync(partitionKeyRangesUri,
  new FeedOptions {
   MaxItemCount = 1000
  });
 foreach(var pkRange in response) {
  //TODO: Something with the pkRange
 }

} while (!string.IsNullOrEmpty(response.ResponseContinuation));


问:
np.outer output changes when stored in an array
I have a NxN matrix which I am interested in its eigenvalue decomposition in order to obtain P=exp(tA). In order to evaluate the P_ij(t) functions, I want to prepare a E=NxNxN matrix where E is the outer product of v[i] and np.linalg.inv(v)[i] and v[i] is one of the eigenvectors.

The sample code with my 3x3 toy matrix is as

def eig_trial(A,n):
        v,w=np.linalg.eig(A)
        w_inv=np.linalg.inv(
        eigs=np.array([[[0 for k in xrange(len(v))] for j in xrange(n)] for i in xrange(n)])
        for i in range(len(v)):
            q=np.outer(np.array(w[:,i]),np.array(w_inv[i]))
            eigs[i]=q
        pprint.pprint(eigs)

A=np.asarray([[6,3,-2],[-4, -1, 2],[13,9,-3]])
eig_trial(A,3)
```

The problem is, q=np.outer(...), which is the correct value, is not equal to eigs[i].

Is there a reason why I can't store this into a matrix? If it helps, I am using Canopy Version: 2.1.9.3717 (64 bit) and Python 2.7.13.

Thanks!

答:
The problem is that the eigs array that you initialize has dtype int

```<code>In [96]: alist = ([[0 for k in range(5)] for j in range(3)])
In [97]: arr = np.array(alist)
In [98]: alist
Out[98]: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
In [99]: arr
Out[99]:
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
</code>```

And do some assignments:

```<code>In [100]: arr[0] = np.arange(5)
In [101]: alist[0] = np.arange(5)
In [102]: arr[1] = np.arange(5)*.1
In [103]: alist[1] = np.arange(5)*.1
</code>```

arr is still integers, even though the last assignment includes floats

```<code>In [104]: arr
Out[104]:
array([[0, 1, 2, 3, 4],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
In [105]: alist
Out[105]: [array([0, 1, 2, 3, 4]), array([0. , 0.1, 0.2, 0.3, 0.4]), [0, 0, 0, 0, 0]]
</code>```

You can see the truncation more clearly with:

```<code>In [108]: arr[1] = np.arange(5)*1.3
In [109]: arr
Out[109]:
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 5],
       [0, 0, 0, 0, 0]])
</code>```

If the array started as float dtype:

```<code>    In [110]: arr = np.zeros((3,5))  # float dtype default
    In [111]: arr[0] = np.arange(5)
    In [112]: arr[1] = np.arange(5)*1.3
    In [113]: arr
    Out[113]:
    array([[0. , 1. , 2. , 3. , 4. ],
           [0. , 1.3, 2.6, 3.9, 5.2],
           [0. , 0. , 0. , 0. , 0. ]])
</code>```

You could have also initialed eigs with 0. instead of 0

```<code>In [114]: np.array([0. for _ in range(5)])
Out[114]: array([0., 0., 0., 0., 0.])
</code>```

but the zeros I used above is faster (and simpler)

You didn't need to assign the full nested depth of the list. Just the first layer would have been enough.  List's can assigned anything:

```<code>In [115]: alist = [None for _ in range(5)]
In [116]: alist
Out[116]: [None, None, None, None, None]
In [117]: alist[0] = np.arange(5)
In [118]: alist[1] = 32
In [119]: alist[2] = np.ones((3,2))
In [120]: alist
Out[120]:
[array([0, 1, 2, 3, 4]), 32, array([[1., 1.],
        [1., 1.],
        [1., 1.]]), None, None]
</code>```

The array assignment arr[0] = np.arange(5) is different.  There's an implied arr[0,:,:] = ....  If the selected slot in the arr does not match with the RHS array, you'll get an error.  match means either exact match in shape, or match in broadcasting terms.

When you run into problems like this, experiment with the small parts of the code as I demonstrate.  It's a lot easier to track down problems with small interactive examples.

Body:
I have a NxN matrix which I am interested in its eigenvalue decomposition in order to obtain P=exp(tA). In order to evaluate the P_ij(t) functions, I want to prepare a E=NxNxN matrix where E is the outer product of v[i] and np.linalg.inv(v)[i] and v[i] is one of the eigenvectors.

The sample code with my 3x3 toy matrix is as

def eig_trial(A,n):
        v,w=np.linalg.eig(A)
        w_inv=np.linalg.inv(
        eigs=np.array([[[0 for k in xrange(len(v))] for j in xrange(n)] for i in xrange(n)])
        for i in range(len(v)):
            q=np.outer(np.array(w[:,i]),np.array(w_inv[i]))
            eigs[i]=q
        pprint.pprint(eigs)

A=np.asarray([[6,3,-2],[-4, -1, 2],[13,9,-3]])
eig_trial(A,3)

The problem is, q=np.outer(...), which is the correct value, is not equal to eigs[i].

Is there a reason why I can't store this into a matrix? If it helps, I am using Canopy Version: 2.1.9.3717 (64 bit) and Python 2.7.13.

Thanks!

Body:
The problem is that the eigs array that you initialize has dtype int

In [96]: alist = ([[0 for k in range(5)] for j in range(3)])
In [97]: arr = np.array(alist)
In [98]: alist
Out[98]: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
In [99]: arr
Out[99]:
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

And do some assignments:

In [100]: arr[0] = np.arange(5)
In [101]: alist[0] = np.arange(5)
In [102]: arr[1] = np.arange(5)*.1
In [103]: alist[1] = np.arange(5)*.1

arr is still integers, even though the last assignment includes floats

In [104]: arr
Out[104]:
array([[0, 1, 2, 3, 4],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
In [105]: alist
Out[105]: [array([0, 1, 2, 3, 4]), array([0. , 0.1, 0.2, 0.3, 0.4]), [0, 0, 0, 0, 0]]

You can see the truncation more clearly with:

In [108]: arr[1] = np.arange(5)*1.3
In [109]: arr
Out[109]:
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 5],
       [0, 0, 0, 0, 0]])

If the array started as float dtype:

    In [110]: arr = np.zeros((3,5))  # float dtype default
    In [111]: arr[0] = np.arange(5)
    In [112]: arr[1] = np.arange(5)*1.3
    In [113]: arr
    Out[113]:
    array([[0. , 1. , 2. , 3. , 4. ],
           [0. , 1.3, 2.6, 3.9, 5.2],
           [0. , 0. , 0. , 0. , 0. ]])

You could have also initialed eigs with 0. instead of 0

In [114]: np.array([0. for _ in range(5)])
Out[114]: array([0., 0., 0., 0., 0.])

but the zeros I used above is faster (and simpler)

You didn't need to assign the full nested depth of the list. Just the first layer would have been enough.  List's can assigned anything:

In [115]: alist = [None for _ in range(5)]
In [116]: alist
Out[116]: [None, None, None, None, None]
In [117]: alist[0] = np.arange(5)
In [118]: alist[1] = 32
In [119]: alist[2] = np.ones((3,2))
In [120]: alist
Out[120]:
[array([0, 1, 2, 3, 4]), 32, array([[1., 1.],
        [1., 1.],
        [1., 1.]]), None, None]

The array assignment arr[0] = np.arange(5) is different.  There's an implied arr[0,:,:] = ....  If the selected slot in the arr does not match with the RHS array, you'll get an error.  match means either exact match in shape, or match in broadcasting terms.

When you run into problems like this, experiment with the small parts of the code as I demonstrate.  It's a lot easier to track down problems with small interactive examples.


问:
How could I run a function after the completion of a for loop in Node.js?
Say if I have a structure in Node.js shown below:

```<code>for (i = 0; i < 50; i++) {
    //Doing a for loop.
}

function after_forloop() {
    //Doing a function.
}

after_forloop();
</code>```

So how could I make sure the after_forloop() function is fired after the forloop is completed?

In case if you want to see what I am actually working on:

```<code>var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

var proxyChecker = require('proxy-checker');
var fs = require('fs');

function get_line(filename, line_no, callback) {
    fs.readFile(filename, function (err, data) {
        if (err) throw err;
        var lines = data.toString('utf-8').split("\n");
        var firstLineBreak = data.toString('utf-8').indexOf("\n");
        var originalText = data.toString('utf-8');
        var newText = originalText.substr(firstLineBreak + 1);
        if(+line_no > lines.length){
            return callback('File end reached without finding line', null);
        }

        callback(null, lines[+line_no], newText);
    });
}

for (i = 0; i < 50; i++) {
    get_line('proxy_full.txt', i, function(err, line, newText){
        fs.appendFile('proxy.txt', line + '\n', function (err) {
            if (err) throw err;
        });
        fs.writeFile('proxy_full.txt', newText, function (err) {
            if (err) throw err;
        });
    })
}

after_forloop();

function after_forloop() {
    proxyChecker.checkProxiesFromFile(
        // The path to the file containing proxies
        'proxy.txt',
        {
            // the complete URL to check the proxy
            url: 'http://google.com',
            // an optional regex to check for the presence of some text on the page
            regex: /.*/
        },
        // Callback function to be called after the check
        function(host, port, ok, statusCode, err) {
            if (ok) {
                console.log(host + ':' + port);
                fs.appendFile('WorkingProxy.txt', host + ':' + port + '\n', function (err) {
                    if (err) throw err;
                });
            }
        }
    );

    setTimeout(function(){
        fs.writeFile('proxy.txt', "", function (err) {
            if (err) throw err;
        });
        console.log('Proxy Check Completed.')
        process.exit(1);
    }, 5000);
}
</code>```

Basically I like to allow the node server run 50 test on a list proxy servers at a time (within five seconds). And then the server should save the working proxies to a new file.

答:
You can handle the last iteration of the for loop with a conditional checking index.

for(let i = 0; i < 10; i++){
  if(i == 10 - 1){
    your_function();
  }
}```

ContentLicense: CC BY-SA 3.0

Body:
Say if I have a structure in Node.js shown below:

for (i = 0; i < 50; i++) {
    //Doing a for loop.
}

function after_forloop() {
    //Doing a function.
}

after_forloop();

So how could I make sure the after_forloop() function is fired after the forloop is completed?

In case if you want to see what I am actually working on:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

var proxyChecker = require('proxy-checker');
var fs = require('fs');

function get_line(filename, line_no, callback) {
    fs.readFile(filename, function (err, data) {
        if (err) throw err;
        var lines = data.toString('utf-8').split("\n");
        var firstLineBreak = data.toString('utf-8').indexOf("\n");
        var originalText = data.toString('utf-8');
        var newText = originalText.substr(firstLineBreak + 1);
        if(+line_no > lines.length){
            return callback('File end reached without finding line', null);
        }

        callback(null, lines[+line_no], newText);
    });
}

for (i = 0; i < 50; i++) {
    get_line('proxy_full.txt', i, function(err, line, newText){
        fs.appendFile('proxy.txt', line + '\n', function (err) {
            if (err) throw err;
        });
        fs.writeFile('proxy_full.txt', newText, function (err) {
            if (err) throw err;
        });
    })
}

after_forloop();

function after_forloop() {
    proxyChecker.checkProxiesFromFile(
        // The path to the file containing proxies
        'proxy.txt',
        {
            // the complete URL to check the proxy
            url: 'http://google.com',
            // an optional regex to check for the presence of some text on the page
            regex: /.*/
        },
        // Callback function to be called after the check
        function(host, port, ok, statusCode, err) {
            if (ok) {
                console.log(host + ':' + port);
                fs.appendFile('WorkingProxy.txt', host + ':' + port + '\n', function (err) {
                    if (err) throw err;
                });
            }
        }
    );

    setTimeout(function(){
        fs.writeFile('proxy.txt', "", function (err) {
            if (err) throw err;
        });
        console.log('Proxy Check Completed.')
        process.exit(1);
    }, 5000);
}

Basically I like to allow the node server run 50 test on a list proxy servers at a time (within five seconds). And then the server should save the working proxies to a new file.


问:
How to create a service mock implementation in laravel
I am quite on new Laravel I am trying to create some mock services.

If I will send a request to some URL :http:/example.com?token={token}. It will return user data if I have token access. The case is that I don't have token access and I cannot get user data. Now I want to create mock service to get user data when I don't have a token and save data on the database.

For example, I have CSV fill user data like this:

```<code>   *----*-------*-------------*---------------*
   | Id |  Name | phoneNumber |  dateOfBirth  |
   *----*-------*-------------*---------------*
   | #1 | test1 |   1234      |  12-12-2001   |
   | #2 | test1 |   12345     |  12-12-2005   |
   *----*-------*-------------*---------------*
</code>```

when I am sending request to my laravel application then I want to create service-mock implementation with the service interface. My mock service adapter now should user above csv data and store data in the database.

I am not getting how I can create this type of mock service on laravel. Anyone, will you please give me some idea of how I can do the implementation.

It would really help if some get some ideas for implementation.

答: I think php-vcr (https://github.com/php-vcr/php-vcr) can be used in this case.</p>

Body:
I am quite on new Laravel I am trying to create some mock services.

If I will send a request to some URL :http:/example.com?token={token}. It will return user data if I have token access. The case is that I don't have token access and I cannot get user data. Now I want to create mock service to get user data when I don't have a token and save data on the database.

For example, I have CSV fill user data like this:

   *----*-------*-------------*---------------*
   | Id |  Name | phoneNumber |  dateOfBirth  |
   *----*-------*-------------*---------------*
   | #1 | test1 |   1234      |  12-12-2001   |
   | #2 | test1 |   12345     |  12-12-2005   |
   *----*-------*-------------*---------------*

when I am sending request to my laravel application then I want to create service-mock implementation with the service interface. My mock service adapter now should user above csv data and store data in the database.

I am not getting how I can create this type of mock service on laravel. Anyone, will you please give me some idea of how I can do the implementation.

It would really help if some get some ideas for implementation.


问:
Filter out the text files
The code separates files from directories.

I am trying to filter out the text files(.txt) and print out the files that remain.

I don't want the text files to be printed at all. I want the code to be implemented after the if statement if (listOfFiles[i].isFile()) { so after it checks to see if a given value is an actual file and then to determine if it is a text file, and if either test fails, add it to the listOfFiles array list.

Need help

```<code>import java.io.BufferedInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Exc_3 {

    public static void main(String[] args) {
        File folder = new File("C:\\Users\\skyla\\Desktop");
        File[] listOfFiles = folder.listFiles();
        List<String> files = new ArrayList<>();
        List<String> directories = new ArrayList<>();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                    files.add(listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                directories.add(listOfFiles[i].getName());
            }
        }
        System.out.println("List of files :\n---------------");
        for (String fName : files)
            System.out.println(fName);

        System.out.println("\nList of directories :\n---------------------");
        for (String dName : directories)
            System.out.println(dName);
    }
}
</code>```

答:
Since you're only checking if the file extension is ".txt" then you can check the name with String.endsWith(".txt")</p>

```<code>if (listOfFiles[i].isFile()) {
   if (listOfFiles[i].getName().endsWith(".txt")) {
      files.add(listOfFiles[i].getName());
   }
}
</code>```

Title: Filter out the text files

Body:
The code separates files from directories.

I am trying to filter out the text files(.txt) and print out the files that remain.

I don't want the text files to be printed at all. I want the code to be implemented after the if statement if (listOfFiles[i].isFile()) { so after it checks to see if a given value is an actual file and then to determine if it is a text file, and if either test fails, add it to the listOfFiles array list.

Need help

import java.io.BufferedInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Exc_3 {

    public static void main(String[] args) {
        File folder = new File("C:\\Users\\skyla\\Desktop");
        File[] listOfFiles = folder.listFiles();
        List<String> files = new ArrayList<>();
        List<String> directories = new ArrayList<>();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                    files.add(listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                directories.add(listOfFiles[i].getName());
            }
        }
        System.out.println("List of files :\n---------------");
        for (String fName : files)
            System.out.println(fName);

        System.out.println("\nList of directories :\n---------------------");
        for (String dName : directories)
            System.out.println(dName);
    }
}

Body:
Since you're only checking if the file extension is ".txt" then you can check the name with String.endsWith(".txt")

if (listOfFiles[i].isFile()) {
   if (listOfFiles[i].getName().endsWith(".txt")) {
      files.add(listOfFiles[i].getName());
   }
}


问:
"no matching function for call to 'Vector::Vector'" error
How to solve the error in the title?

Vector class code:

```<code>class Vector
{
public:
    uint32_t x;
    uint32_t y;
    Vector(uint32_t x, uint32_t y);
};

Vector::Vector(uint32_t x, uint32_t y)
{
    this->x = x;
    this->y = y;
}
</code>```

Other class code:

```<code>class Test
{
    Test(Vector c1);
    Test(Vector c1, Vector c2);
    Vector c1, c2;
};

Test::Test(Vector c1) // << error here
{
    this->c1 = c1;
}

Test::Test(Vector c1, Vector c2) // << error here too
{
    this->c1 = c1;
    this->c2 = c2;
}
</code>```

I tryed to rename arguments to not be the same as in class.

答:
Your Vector class does not have a default constructor (one that takes no parameters), only a two parameter version.

The constructors for your Test class, as written, try to initialize the members c1 and c2 using their default construtors (and fail, because there are no default constructors they can use) and then assign new values to the c1 and c2 members after they have been already initialized.

You need to either provide a default constructor for Vector, or manually initialize the c1 and c2 members of Test:

```<code>Vector c1 = {0, 0}, c2 = {0, 0};
</code>```

or

```<code>Test::Test(Vector c1)
    : c1(c1), c2(0, 0)
{}
</code>```

OwnerDisplayName: anon

Body:
How to solve the error in the title?

Vector class code:

class Vector
{
public:
    uint32_t x;
    uint32_t y;
    Vector(uint32_t x, uint32_t y);
};

Vector::Vector(uint32_t x, uint32_t y)
{
    this->x = x;
    this->y = y;
}

Other class code:

class Test
{
    Test(Vector c1);
    Test(Vector c1, Vector c2);
    Vector c1, c2;
};

Test::Test(Vector c1) // << error here
{
    this->c1 = c1;
}

Test::Test(Vector c1, Vector c2) // << error here too
{
    this->c1 = c1;
    this->c2 = c2;
}

I tryed to rename arguments to not be the same as in class.

Body:
Your Vector class does not have a default constructor (one that takes no parameters), only a two parameter version.

The constructors for your Test class, as written, try to initialize the members c1 and c2 using their default construtors (and fail, because there are no default constructors they can use) and then assign new values to the c1 and c2 members after they have been already initialized.

You need to either provide a default constructor for Vector, or manually initialize the c1 and c2 members of Test:

Vector c1 = {0, 0}, c2 = {0, 0};

or

Test::Test(Vector c1)
    : c1(c1), c2(0, 0)
{}


问:
Why does this PHP code not output property values?
I am trying to import a tab delimited file after upload. The meat of this is done with the following function. I'm trying to build an array of class instances. The code follows:

Import Function

```<code>$AddedProducts;
function importList($filename)
{
    global $AddedProducts;
    $AddedProducts=array();
    $fileHandle = fopen($filename, "r");
    $currentProduct = new productImport();

      $line=fgets($fileHandle); $line=fgets($fileHandle); //throw away top 2 lines
    echo '<hr>';
    while(true)
    {
        $line = fgets($fileHandle);
        if($line == null)   break;

        $cells=explode('    ', $line);
        $i=0;

        foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];
                echo $i . '. ' . $cells[$i] . "<br>";
            }
            else return false;
            $i++;
        }
        echo "<hr>";
        $AddedProducts[]=$currentProduct;
    }
    fclose($fileHandle);
    return true;
}
</code>```

Array Output

```<code><?
$i=0;
foreach($AddedProducts as $AddedProduct)
{
    $i++;
    echo "<hr>" . $i . "<br>";
    foreach($AddedProduct as $key=>$value)
    {
        echo $key . ' = ' . $value . '<br>';
    }
}
?>
</code>```

Breakdown of Known Info

The final array length/size is correct. (Should be lines in file - 2)

It doesn't particularly matter how many properties are in the productImport class so long as it equates to the same number of tabs per line in the file being read.

importList function echos proper values for $cells[$i] which are the same values I'm missing in the array output.

The problem seems to be either the values aren't being assigned to the properties or the properties are not being read. I'm not sure of why either would be the case but I assume it is because PHP is not my primary language and likely something obvious about the foreach loops ;)

I'm using PHP v5.2.6

What's wrong with this code?

Answer:

```<code>foreach($currentProduct as $ProductProperty) becomes
foreach($currentProduct as &$ProductProperty)
</code>```

答: In addition to what the others are saying, it seems that you are attempting to insert property data to the same object every time, since you're not creating any new productImport instances in the loop.</p>

Body:
I am trying to import a tab delimited file after upload. The meat of this is done with the following function. I'm trying to build an array of class instances. The code follows:

Import Function

$AddedProducts;
function importList($filename)
{
    global $AddedProducts;
    $AddedProducts=array();
    $fileHandle = fopen($filename, "r");
    $currentProduct = new productImport();

      $line=fgets($fileHandle); $line=fgets($fileHandle); //throw away top 2 lines
    echo '
';
    while(true)
    {
        $line = fgets($fileHandle);
        if($line == null)   break;

        $cells=explode('    ', $line);
        $i=0;

        foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];
                echo $i . '. ' . $cells[$i] . "
";
            }
            else return false;
            $i++;
        }
        echo "
";
        $AddedProducts[]=$currentProduct;
    }
    fclose($fileHandle);
    return true;
}

Array Output

<?
$i=0;
foreach($AddedProducts as $AddedProduct)
{
    $i++;
    echo "
" . $i . "
";
    foreach($AddedProduct as $key=>$value)
    {
        echo $key . ' = ' . $value . '
';
    }
}
?>

Breakdown of Known Info

The final array length/size is correct. (Should be lines in file - 2)

It doesn't particularly matter how many properties are in the productImport class so long as it equates to the same number of tabs per line in the file being read.

importList function echos proper values for $cells[$i] which are the same values I'm missing in the array output.

The problem seems to be either the values aren't being assigned to the properties or the properties are not being read. I'm not sure of why either would be the case but I assume it is because PHP is not my primary language and likely something obvious about the foreach loops ;)

I'm using PHP v5.2.6

What's wrong with this code?

Answer:

foreach($currentProduct as $ProductProperty) becomes
foreach($currentProduct as &$ProductProperty)


问:
Find matching sequence between two arrays (pattern matching) C#
I have two arrays, one is a main array I am comparing against, and the second array has a number of integers whose order might be shifted to the right or left and it also might contain default values.

The result (true/false) of this comparison looks like this:

```<code>x = -9; //unknown number

int[] mainArray = new int[]{3,1,0,1};

int[] a = new int[]{x,x,x,x}; // true
int[] b = new int[]{x,x,1,x}; // true
int[] c = new int[]{x,x,1,0}; // true
int[] d = new int[]{x,x,1,0}; // true
int[] e = new int[]{x,3,1,0}; // true
int[] f = new int[]{1,3,1,0}; // true
int[] g = new int[]{3,1,0,x}; // true
int[] h = new int[]{3,1,1,0}; // false
int[] i = new int[]{x,1,1,x}; // false
int[] j = new int[]{0,1,1,x}; // false
int[] k = new int[]{3,1,x,x}; // true
</code>```

What would be the a way to search if the sequence exists in the main array?
There are two problem I cannot figure out:
1) the array might be shifted to the right or left, but the result is true even if it is shifted
2) the x value which is skipped in comparison

I end up in doing lots of if statements, but I am sure this problem was solved elegantly by someone else.

答:
If I'm getting the problem statement correctly, you could try something like this:

class MyEqualityComparer : IEqualityComparer<int>
{
    private int specialValue;
    public MyEqualityComparer(int specialValue) {this.specialValue = specialValue;}

    public bool Equals(int x, int y)
    {
        if (y == specialValue) return true;
        return x.Equals(y);
    }

    public int GetHashCode(int obj)
    {
        return obj.GetHashCode();
    }
}
void Main()
{
    int x = -9; //unknown number

    int[] mainArray = new int[] { 3, 1, 0, 1 };

    var lists = new List<int[]> {
    new int[] { x, x, x, x }, // true
    new int[] { x, x, 1, x }, // true
    new int[] { x, x, 1, 0 }, // true
    new int[] { x, x, 1, 0 }, // true
    new int[] { x, 3, 1, 0 }, // true
    new int[] { 1, 3, 1, 0 }, // true
    new int[] { 3, 1, 0, x }, // true
    new int[] { 3, 1, 1, 0 }, // false
    new int[] { x, 1, 1, x }, // false
    new int[] { 0, 1, 1, x }, // false
    new int[] { 3, 1, x, x }, // true
    };
    var mainRepeated = mainArray.ToList();
    mainRepeated.AddRange(mainArray);
    foreach (var e in lists)
    {
        foreach (var i in Enumerable.Range(0, mainArray.Length))
        {
            if (mainRepeated.Skip(i).Take(e.Count()).SequenceEqual(e, new MyEqualityComparer(x)))
            {
                Console.WriteLine(e.Aggregate(new StringBuilder(), (sb,s) => (s==x? sb.Append("x") : sb.Append(s)).Append(",")).ToString()); // we've got a match
                break;
            }
        }
    }
}
```

Body:
I have two arrays, one is a main array I am comparing against, and the second array has a number of integers whose order might be shifted to the right or left and it also might contain default values.

The result (true/false) of this comparison looks like this:

x = -9; //unknown number

int[] mainArray = new int[]{3,1,0,1};

int[] a = new int[]{x,x,x,x}; // true
int[] b = new int[]{x,x,1,x}; // true
int[] c = new int[]{x,x,1,0}; // true
int[] d = new int[]{x,x,1,0}; // true
int[] e = new int[]{x,3,1,0}; // true
int[] f = new int[]{1,3,1,0}; // true
int[] g = new int[]{3,1,0,x}; // true
int[] h = new int[]{3,1,1,0}; // false
int[] i = new int[]{x,1,1,x}; // false
int[] j = new int[]{0,1,1,x}; // false
int[] k = new int[]{3,1,x,x}; // true

What would be the a way to search if the sequence exists in the main array?
There are two problem I cannot figure out:
1) the array might be shifted to the right or left, but the result is true even if it is shifted
2) the x value which is skipped in comparison

I end up in doing lots of if statements, but I am sure this problem was solved elegantly by someone else.


问:
How do I rotate a html canvas shape by only using a transform?
I am wondering how you can rotate an image by only using the transform function. From my understanding this is not possible, since the only things you can do with transform are the following:

Horizontal scaling

Horizontal skewing

Vertical skewing

Vertical scaling

Horizontal moving

Vertical moving

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations

And I don't see how any of these would be able to rotate the shape, is this even possible. I assume it must be possible, since rotate is in-fact a type transformation.

答:
You can rotate your image easily. You can specify angles by which you wants to apply rotation.

Source : https://www.w3schools.com/cssref/css3_pr_transform.asp

```

Body:
You can rotate your image easily. You can specify angles by which you wants to apply rotation.

Source : https://www.w3schools.com/cssref/css3_pr_transform.asp

<style>
    img.a {
        transform: rotate(180deg);
    }
</style>
<img  class="a" src="https://picsum.photos/id/237/200/300"/>


问:
Issue in Passing a 2-D array
I read how to pass 2-D arrays in a function as a parameter and tried to implement the same. There are two problems which I encountered:

1) The first line of the output of the code contains garbage value.
2) What does the line ((arr + in) + j) actually do ? I mean, Why can't we do something like ((arr + i) + j) to access arr[i][j] ?

I also tried passing the matrix using parameter int **arr and then tried printing the value as arr[i][j] but there was no output.

Here is the output that I get:-

```<code>Enter number of nodes: 4
0167772161878012032-1
0000
0000
0000
</code>```

And here is my code :-

```<code>#include <iostream>
using namespace std;

void show(int* arr, int n)
{
    int i, j;

    for(i = 0; i < n; ++i)
    {
        for(j = 0; j < n; ++j)
        {
            cout << *((arr + i*n) + j);
        }

        cout << endl;
    }
}

int main()
{
    int n, i, j;

    cout << "Enter number of nodes: ";
    cin >> n;

    int arr[n][n] = {{0}}; //Will initialize all elements in the matrix with 0.

    show((int*)arr, n);
}
</code>```

答:
The biggest problem here is that you are using C and not C++.

To avoid people gasping and starting religious or political discussion, let's nail it down to:

VLAs (Variable Length Arrays) are not allowed in C++.

Additionally, you should never use raw pointers for owned memory and no pinter arithmetic.

And then the main topic:

Issue in Passing a 2-D array

The used syntax for passing arrays to function is wrong. In C++ arrays can be passed by reference or by pointer. Please see:

```<code>void function1(int(&m)[3][4])   // For passing array by reference
{}
void function2(int(*m)[3][4])   // For passing array by pointer
{}

int main()
{
    int matrix[3][4]; // Define 2 dimensional array

    function1(matrix);  // Call by reference
    function2(&matrix); // Call via pointer
    return 0;
}
</code>```

Of course we can do all kind of dirty designs with pointers. Even accepting pointer decays. But we should not do it.

Title: Issue in Passing a 2-D array

Body:
I read how to pass 2-D arrays in a function as a parameter and tried to implement the same. There are two problems which I encountered:

1) The first line of the output of the code contains garbage value.
2) What does the line ((arr + in) + j) actually do ? I mean, Why can't we do something like ((arr + i) + j) to access arr[i][j] ?

I also tried passing the matrix using parameter int **arr and then tried printing the value as arr[i][j] but there was no output.

Here is the output that I get:-

Enter number of nodes: 4
0167772161878012032-1
0000
0000
0000

And here is my code :-

#include <iostream>
using namespace std;

void show(int* arr, int n)
{
    int i, j;

    for(i = 0; i < n; ++i)
    {
        for(j = 0; j < n; ++j)
        {
            cout << *((arr + i*n) + j);
        }

        cout << endl;
    }
}

int main()
{
    int n, i, j;

    cout << "Enter number of nodes: ";
    cin >> n;

    int arr[n][n] = {{0}}; //Will initialize all elements in the matrix with 0.

    show((int*)arr, n);
}

Body:
The biggest problem here is that you are using C and not C++.

To avoid people gasping and starting religious or political discussion, let's nail it down to:

VLAs (Variable Length Arrays) are not allowed in C++.

Additionally, you should never use raw pointers for owned memory and no pinter arithmetic.

And then the main topic:

Issue in Passing a 2-D array

The used syntax for passing arrays to function is wrong. In C++ arrays can be passed by reference or by pointer. Please see:

void function1(int(&m)[3][4])   // For passing array by reference
{}
void function2(int(*m)[3][4])   // For passing array by pointer
{}

int main()
{
    int matrix[3][4]; // Define 2 dimensional array

    function1(matrix);  // Call by reference
    function2(&matrix); // Call via pointer
    return 0;
}

Of course we can do all kind of dirty designs with pointers. Even accepting pointer decays. But we should not do it.


问:
Set Android Studio layout for user feedback
I need to design question and get users feedback as per below design. please advise what is the best android studio layout to use. shall I use table layout , or use vertical layout for different questions, and then use Horizontal Layout for each question text and radio buttons.?

NB.  Layout is RTL.
     Target is 16

答: TableLayout is designed for this purpose, as it is much cleaner and more readable.</p>


问:
Postgresql stored procedure not running from script
I have several stored procedures in a postgresql database that are run from a python script.  They are all executed in the same fashion, and they all work except one.  That stored procedure works fine, if I run it from from a query tool in pgAdmin, but it does nothing when it runs from the script.  It doesn't give an error; it just doesn't do anything.  It is supposed to delete an entry from one table and update a field in another table.

Here is a gist for the stored procedure: https://gist.github.com/algaspar/e7cb4157d2f3f70f8b47439e2a4058a4

Here is a gist for the script: https://gist.github.com/algaspar/3fa548379203aff9d887caed3c92cb64

I've trimmed the script down to what isn't working.  Basically, it reads in a file with a number of items and builds a list that it passes to the stored procedure with executemany (my sample just builds a list without reading a file, but it doesn't work any better :( ).  I can run the procedure in query tool with:

```<code>CALL close_item('item1', CURRENT_DATE);
</code>```

and it does what it is supposed to do--delete an entry from the itemchanges table and update a field in the itemhistory table.  Does anyone have an idea why I shouldn't be able to run this stored procedure from a script?

Thanks--

Al

P.S.

I'd really like to get an answer to this; so I'm not making this THE answer.  I can solve my problem by running SQL in executes inside a loop.  This accomplishes, what I need (decided CURRENT_DATE was fine so the list would only have items now):

```<code>       for item in my_list:
           cursor.execute ("DELETE FROM itemchanges WHERE item = %s", (item,))
       ps_connection.commit()
       for item in my_list:
           cursor.execute ("UPDATE itemhistory SET fixed_date = CURRENT_DATE WHERE item = %s AND fixed_date IS NULL", (item,))
       ps_connection.commit()
</code>```

I'd like to know, though, why calling the stored procedure with an executemany didn't work, when the stored procedure worked just fine as a query...

答:
The commit was needed; I missed putting it in my gist.  Thanks!

My problem, though in my "real" script was that my items were being read in from a file, but in my gist example I was building the list manually.  When I read the items in from the file, I was getting 'XXXXXX\n' rather than just 'XXXXXX'.  I changed where I added them to my list to be item.rstrip(), and my stored procedure works fine now from cursor.executemany():

```<code>    for item in input_file:
        load_tuple = (item.rstrip(), today)
        item_list.append(load_tuple)
    run_SQL(item_list)
</code>```

Bottom line, I wasn't comparing apples to apples when I debugged; I need to pay more attention.

Body:
I have several stored procedures in a postgresql database that are run from a python script.  They are all executed in the same fashion, and they all work except one.  That stored procedure works fine, if I run it from from a query tool in pgAdmin, but it does nothing when it runs from the script.  It doesn't give an error; it just doesn't do anything.  It is supposed to delete an entry from one table and update a field in another table.

Here is a gist for the stored procedure: https://gist.github.com/algaspar/e7cb4157d2f3f70f8b47439e2a4058a4

Here is a gist for the script: https://gist.github.com/algaspar/3fa548379203aff9d887caed3c92cb64

I've trimmed the script down to what isn't working.  Basically, it reads in a file with a number of items and builds a list that it passes to the stored procedure with executemany (my sample just builds a list without reading a file, but it doesn't work any better :( ).  I can run the procedure in query tool with:

CALL close_item('item1', CURRENT_DATE);

and it does what it is supposed to do--delete an entry from the itemchanges table and update a field in the itemhistory table.  Does anyone have an idea why I shouldn't be able to run this stored procedure from a script?

Thanks--

Al

P.S.

I'd really like to get an answer to this; so I'm not making this THE answer.  I can solve my problem by running SQL in executes inside a loop.  This accomplishes, what I need (decided CURRENT_DATE was fine so the list would only have items now):

       for item in my_list:
           cursor.execute ("DELETE FROM itemchanges WHERE item = %s", (item,))
       ps_connection.commit()
       for item in my_list:
           cursor.execute ("UPDATE itemhistory SET fixed_date = CURRENT_DATE WHERE item = %s AND fixed_date IS NULL", (item,))
       ps_connection.commit()

I'd like to know, though, why calling the stored procedure with an executemany didn't work, when the stored procedure worked just fine as a query...

Body:
The commit was needed; I missed putting it in my gist.  Thanks!

My problem, though in my "real" script was that my items were being read in from a file, but in my gist example I was building the list manually.  When I read the items in from the file, I was getting 'XXXXXX\n' rather than just 'XXXXXX'.  I changed where I added them to my list to be item.rstrip(), and my stored procedure works fine now from cursor.executemany():

    for item in input_file:
        load_tuple = (item.rstrip(), today)
        item_list.append(load_tuple)
    run_SQL(item_list)

Bottom line, I wasn't comparing apples to apples when I debugged; I need to pay more attention.


问:
android: how to start a service separate from the app and exchange object with it?
Basically I have an app that would require things(around 20 index files) to be loaded at the start of the app in-order to do some instant-searching later in the app. Although all in all, the index files totally is only several hundred K, as decompression has to be done, the loading actually takes a while. So I am wondering if it is possible to keep it in memory by running service? I wrote a local service within the same package with my app. And when I force closed my app, my service closes too. Should I be using a remote service? if so what I have to do is when I open up my app, it should be able to get 1 int[] and 1 ArrayList from the service, is this doable? or are there any other better options? Thanks a lot</p>

答:
Keep in mind - you're developing for a mobile phone. Memory is limited. Your app will not be the only app the user will be running. Trying to hog memory persistently for the benefit of your own app is bad practice. The user will not want to have your service running all the time.

Sure, the operating system will eventually kick your service out of the window if memory gets tight, but it's better practice to not use a service to store data. Use a separate thread on startup and decompress the data.

You could consider writing the decompressed index file to external storage, or compressing it in chunks so that you can get by without having to decompress the entire thing.

If you really think this is an important feature for your app, make it optional in the settings and add a service (possibly even using a broadcast receiver on boot if your app is so important to the user) to load and decompress the data. But I would really recommend against having a service for storage, if that's what you're planning to use.


问:
Invoking Windows EC2 terminal remotely
I need to connect to my Windows EC2 terminal to invoke a local script on it from a different machine CMD.

I tried to search and I 'v found the following: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Connect-using-EC2-Instance-Connect.html.  This solves the problem for Linux, not windows. Any suggestion or lead for a solution?

答:
You can look into the option of session manager.

Please refer: https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html

To give you a brief, Session Manager is a fully managed AWS Systems Manager capability that lets you manage your Amazon EC2 instances, on-premises instances, and virtual machines (VMs) through an interactive one-click browser-based shell or through the AWS CLI.

Title: Invoking Windows EC2 terminal remotely


问:
Auto reload with delay when click
I have an online marketplace system (like an auction).
In this system I would like that after the user clicks on the button to send a purchase or sale order, the page is automatically regregulated seconds later.
The code that sends these orders is as follows:

```<code>@PlaceOrderUI = flight.component ->
  @attributes
    formSel: 'form'
    successSel: '.status-success'
    infoSel: '.status-info'
    feeSel: '.status-fee'
    dangerSel: '.status-danger'
    priceAlertSel: '.hint-price-disadvantage'
    positionsLabelSel: '.hint-positions'
    feeLabelSel: '.hint-fee'
    feeLabelInfo: '.fee-info'
    feeLabelDiscountInfo: '.fee-discount-info'

    priceSel: 'input[id$=price]'
    volumeSel: 'input[id$=volume]'
    totalSel: 'input[id$=total]'
    bidSel: "input[id='calculate_bid']"
    askSel: "input[id='calculate_ask']"

    currentBalanceSel: 'span.current-balance'
    submitButton: ':submit'

  @panelType = ->
    switch @$node.attr('id')
      when 'bid_entry' then 'bid'
      when 'ask_entry' then 'ask'

  @cleanMsg = ->
    @select('successSel').text('')
    @select('infoSel').text('')
    @select('dangerSel').text('')
    @select('feeSel').text('')

  @resetForm = (event) ->
    @trigger 'place_order::reset::price'
    @trigger 'place_order::reset::volume'
    @trigger 'place_order::reset::total'
    @priceAlertHide()

  @disableSubmit = ->
    @select('submitButton').addClass('disabled').attr('disabled', 'disabled')

  @enableSubmit = ->
    @select('submitButton').removeClass('disabled').removeAttr('disabled')

  @confirmDialogMsg = ->
    confirmType = @select('submitButton').text()
    price = @select('priceSel').val()
    volume = @select('volumeSel').val()
    sum = @select('totalSel').val()
    """
    #{gon.i18n.place_order.confirm_submit} "#{confirmType}"?

    #{gon.i18n.place_order.price}: #{price}
    #{gon.i18n.place_order.volume}: #{volume}
    #{gon.i18n.place_order.sum}: #{sum}
    """

  @beforeSend = (event, jqXHR) ->
    if true #confirm(@confirmDialogMsg())
      @disableSubmit()
    else
      jqXHR.abort()

  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()

  @handleError = (event, data) ->
    @cleanMsg()
    ef_class = 'shake shake-constant hover-stop'
    json = JSON.parse(data.responseText)
    console.log(json)
    @select('dangerSel').append(JST["templates/hint_order_warning"]({msg: json.message})).show()
      .addClass(ef_class).wait(500).removeClass(ef_class)
    window.sfx_warning()
    @enableSubmit()

  @getBalance = ->
    BigNumber( @select('currentBalanceSel').data('balance') )

  @getLastPrice = ->
    BigNumber(gon.ticker.last)

  @allIn = (event)->
    switch @panelType()
      when 'ask'
        @trigger 'place_order::input::volume', {volume: @getBalance()}
      when 'bid'
        @trigger 'place_order::input::total', {total: @getBalance()}

  @refreshBalance = (event, data) ->
    type = @panelType()
    currency = gon.market[type].currency
    balance = gon.accounts[currency]?.balance || 0

#    console.log "refreshBalance: ", type, balance, event, data

    @select('currentBalanceSel').data('balance', balance)
    @select('currentBalanceSel').text(formatter.fix(type, balance))

    @trigger "place_order::balance::change", balance: BigNumber(balance)
    @trigger "place_order::max::#{@usedInput}", max: BigNumber(balance)
    @trigger "place_order::balance::change::#{type}", balance: BigNumber(balance)

  @roundValueToText = (v, precision) ->
    v.round(precision, BigNumber.ROUND_DOWN).toF(precision)

  @updateOrder = (event, data) ->
#    console.log "updateOrder: ", event, data

    @select('priceSel').val BigNumber(data.price).round(gon.market.bid.fixed, BigNumber.ROUND_DOWN).toF(gon.market.bid.fixed)
    @select('volumeSel').val BigNumber(data.volume).round(gon.market.ask.fixed, BigNumber.ROUND_DOWN).toF(gon.market.ask.fixed)
    @select('totalSel').val BigNumber(data.total).round(gon.market.bid.fixed, BigNumber.ROUND_DOWN).toF(gon.market.bid.fixed)

    @updateAvailable(event, data)

  @updateAvailable = (event, order) ->
#    console.log "updateAvailable: ", event, order

    @current_order = order

    type = @panelType()
    node = @select('currentBalanceSel')

    order[@usedInput] = 0 unless order[@usedInput]
    available = formatter.fix type, @getBalance().minus(order[@usedInput])

    fee = 0.0
    fee_actual_percent = 0.0

    if type == 'ask'
      fee = gon.market.ask.fee
    else
      fee = gon.market.bid.fee

    spero_discount_flag = -1

    spero_account = gon.accounts['spero']
    if spero_account.hasOwnProperty('spero_discount')
      if spero_account.spero_discount == true
        spero_discount_flag = 1
      if spero_account.spero_discount == false
        spero_discount_flag = 0

    fee_actual_percent = fee
    if spero_discount_flag == 1
      fee_actual_percent = fee / 2.0

    if order.hasOwnProperty('total')
      order.fee = order.total * fee
    else
      order.fee = order[@usedInput] * fee

    order.fee_percent = fee * 100.0
    order.fee_actual_percent = fee_actual_percent * 100.0
    order.spero_discount_flag = spero_discount_flag

    if @select('priceSel').val() != 0.0 && @select('priceSel').val() != ''
      @select('feeLabelSel').hide().text(formatter.fixPriceGroup(order.fee)).fadeIn()
      @select('feeLabelInfo').hide().text(formatter.round(order.fee_actual_percent, 2) + "%").fadeIn()
    else
      @select('feeLabelSel').fadeOut().text('')
      @select('feeLabelInfo').fadeOut().text('')

    if order.spero_discount_flag == 1
      @select('feeLabelDiscountInfo').fadeOut().text('')
    else
      @select('feeLabelDiscountInfo').hide().text('how to get 50% market fee discount').fadeIn()

    if BigNumber(available).lessThan(0.000000001)
      @select('positionsLabelSel').hide().text(gon.i18n.place_order["full_#{type}"]).fadeIn()
    else
      @select('positionsLabelSel').fadeOut().text('')

    node.text(available)

  @priceAlertHide = (event) ->
    @select('priceAlertSel').fadeOut ->
      $(@).text('')

  @priceAlertShow = (event, data) ->
    @select('priceAlertSel')
      .hide().text(gon.i18n.place_order[data.label]).fadeIn()

  @clear = (e) ->

    if e.currentTarget.checked
      @disableSubmit()
      @refreshBalance(null, null)
      @trigger "place_order::max::#{@usedInput}", max: BigNumber("1000000000000.0")
      @trigger "place_order::balance::change::#{@panelType()}", balance: BigNumber("1000000000000.0")
    else
      @enableSubmit()
      @refreshBalance(null, null)

    @resetForm(e)
    @select('feeLabelSel').fadeOut().text('')
    @select('feeLabelInfo').fadeOut().text('')
    @trigger 'place_order::focus::price'

  @calculatorClick = (e) ->
#    console.log @panelType(), e

    @clear(e)

  @after 'initialize', ->
    type = @panelType()

    if type == 'ask'
      @usedInput = 'volume'
    else
      @usedInput = 'total'

    @current_order = null

    PlaceOrderData.attachTo @$node
    OrderPriceUI.attachTo   @select('priceSel'),  form: @$node, type: type
    OrderVolumeUI.attachTo  @select('volumeSel'), form: @$node, type: type
    OrderTotalUI.attachTo   @select('totalSel'),  form: @$node, type: type

    @on 'place_order::price_alert::hide', @priceAlertHide
    @on 'place_order::price_alert::show', @priceAlertShow
    @on 'place_order::order::updated', @updateAvailable
    @on 'place_order::clear', @clear
    @on 'place_order::order::total', @updateOrder

    @on document, 'account::update', @refreshBalance

    @on @select('formSel'), 'ajax:beforeSend', @beforeSend
    @on @select('formSel'), 'ajax:success', @handleSuccess
    @on @select('formSel'), 'ajax:error', @handleError

    @on @select('currentBalanceSel'), 'click', @allIn

    if @panelType() == 'bid'
      @on @select('bidSel'), 'click', @calculatorClick
    else
      @on @select('askSel'), 'click', @calculatorClick
</code>```

The most important part that needs to enter this code would be in this excerpt:

```<code>  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()
</code>```

I've already tested the following, according to some answers found here:

```<code>  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()
    setTimeout(window.location.reload(1), 3000)
</code>```

However the page reloads as soon as I click the button, there is no interval (3 seconds in this example)

答:
I managed to solve it with the following change:

```<code>setTimeout(window.location.reload(1), 3000)
</code>```

Where I converted to:

```<code>setTimeout (->
  window.location.reload 1
  return
), 3000
</code>```

The code snippet then became:

```<code>  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()
    setTimeout (->
      window.location.reload 1
      return
    ), 3000
</code>```

Title: Auto reload with delay when click

Body:
I have an online marketplace system (like an auction).
In this system I would like that after the user clicks on the button to send a purchase or sale order, the page is automatically regregulated seconds later.
The code that sends these orders is as follows:

@PlaceOrderUI = flight.component ->
  @attributes
    formSel: 'form'
    successSel: '.status-success'
    infoSel: '.status-info'
    feeSel: '.status-fee'
    dangerSel: '.status-danger'
    priceAlertSel: '.hint-price-disadvantage'
    positionsLabelSel: '.hint-positions'
    feeLabelSel: '.hint-fee'
    feeLabelInfo: '.fee-info'
    feeLabelDiscountInfo: '.fee-discount-info'

    priceSel: 'input[id$=price]'
    volumeSel: 'input[id$=volume]'
    totalSel: 'input[id$=total]'
    bidSel: "input[id='calculate_bid']"
    askSel: "input[id='calculate_ask']"

    currentBalanceSel: 'span.current-balance'
    submitButton: ':submit'

  @panelType = ->
    switch @$node.attr('id')
      when 'bid_entry' then 'bid'
      when 'ask_entry' then 'ask'

  @cleanMsg = ->
    @select('successSel').text('')
    @select('infoSel').text('')
    @select('dangerSel').text('')
    @select('feeSel').text('')

  @resetForm = (event) ->
    @trigger 'place_order::reset::price'
    @trigger 'place_order::reset::volume'
    @trigger 'place_order::reset::total'
    @priceAlertHide()

  @disableSubmit = ->
    @select('submitButton').addClass('disabled').attr('disabled', 'disabled')

  @enableSubmit = ->
    @select('submitButton').removeClass('disabled').removeAttr('disabled')

  @confirmDialogMsg = ->
    confirmType = @select('submitButton').text()
    price = @select('priceSel').val()
    volume = @select('volumeSel').val()
    sum = @select('totalSel').val()
    """
    #{gon.i18n.place_order.confirm_submit} "#{confirmType}"?

    #{gon.i18n.place_order.price}: #{price}
    #{gon.i18n.place_order.volume}: #{volume}
    #{gon.i18n.place_order.sum}: #{sum}
    """

  @beforeSend = (event, jqXHR) ->
    if true #confirm(@confirmDialogMsg())
      @disableSubmit()
    else
      jqXHR.abort()

  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()

  @handleError = (event, data) ->
    @cleanMsg()
    ef_class = 'shake shake-constant hover-stop'
    json = JSON.parse(data.responseText)
    console.log(json)
    @select('dangerSel').append(JST["templates/hint_order_warning"]({msg: json.message})).show()
      .addClass(ef_class).wait(500).removeClass(ef_class)
    window.sfx_warning()
    @enableSubmit()

  @getBalance = ->
    BigNumber( @select('currentBalanceSel').data('balance') )

  @getLastPrice = ->
    BigNumber(gon.ticker.last)

  @allIn = (event)->
    switch @panelType()
      when 'ask'
        @trigger 'place_order::input::volume', {volume: @getBalance()}
      when 'bid'
        @trigger 'place_order::input::total', {total: @getBalance()}

  @refreshBalance = (event, data) ->
    type = @panelType()
    currency = gon.market[type].currency
    balance = gon.accounts[currency]?.balance || 0

#    console.log "refreshBalance: ", type, balance, event, data

    @select('currentBalanceSel').data('balance', balance)
    @select('currentBalanceSel').text(formatter.fix(type, balance))

    @trigger "place_order::balance::change", balance: BigNumber(balance)
    @trigger "place_order::max::#{@usedInput}", max: BigNumber(balance)
    @trigger "place_order::balance::change::#{type}", balance: BigNumber(balance)

  @roundValueToText = (v, precision) ->
    v.round(precision, BigNumber.ROUND_DOWN).toF(precision)

  @updateOrder = (event, data) ->
#    console.log "updateOrder: ", event, data

    @select('priceSel').val BigNumber(data.price).round(gon.market.bid.fixed, BigNumber.ROUND_DOWN).toF(gon.market.bid.fixed)
    @select('volumeSel').val BigNumber(data.volume).round(gon.market.ask.fixed, BigNumber.ROUND_DOWN).toF(gon.market.ask.fixed)
    @select('totalSel').val BigNumber(data.total).round(gon.market.bid.fixed, BigNumber.ROUND_DOWN).toF(gon.market.bid.fixed)

    @updateAvailable(event, data)

  @updateAvailable = (event, order) ->
#    console.log "updateAvailable: ", event, order

    @current_order = order

    type = @panelType()
    node = @select('currentBalanceSel')

    order[@usedInput] = 0 unless order[@usedInput]
    available = formatter.fix type, @getBalance().minus(order[@usedInput])

    fee = 0.0
    fee_actual_percent = 0.0

    if type == 'ask'
      fee = gon.market.ask.fee
    else
      fee = gon.market.bid.fee

    spero_discount_flag = -1

    spero_account = gon.accounts['spero']
    if spero_account.hasOwnProperty('spero_discount')
      if spero_account.spero_discount == true
        spero_discount_flag = 1
      if spero_account.spero_discount == false
        spero_discount_flag = 0

    fee_actual_percent = fee
    if spero_discount_flag == 1
      fee_actual_percent = fee / 2.0

    if order.hasOwnProperty('total')
      order.fee = order.total * fee
    else
      order.fee = order[@usedInput] * fee

    order.fee_percent = fee * 100.0
    order.fee_actual_percent = fee_actual_percent * 100.0
    order.spero_discount_flag = spero_discount_flag

    if @select('priceSel').val() != 0.0 && @select('priceSel').val() != ''
      @select('feeLabelSel').hide().text(formatter.fixPriceGroup(order.fee)).fadeIn()
      @select('feeLabelInfo').hide().text(formatter.round(order.fee_actual_percent, 2) + "%").fadeIn()
    else
      @select('feeLabelSel').fadeOut().text('')
      @select('feeLabelInfo').fadeOut().text('')

    if order.spero_discount_flag == 1
      @select('feeLabelDiscountInfo').fadeOut().text('')
    else
      @select('feeLabelDiscountInfo').hide().text('how to get 50% market fee discount').fadeIn()

    if BigNumber(available).lessThan(0.000000001)
      @select('positionsLabelSel').hide().text(gon.i18n.place_order["full_#{type}"]).fadeIn()
    else
      @select('positionsLabelSel').fadeOut().text('')

    node.text(available)

  @priceAlertHide = (event) ->
    @select('priceAlertSel').fadeOut ->
      $(@).text('')

  @priceAlertShow = (event, data) ->
    @select('priceAlertSel')
      .hide().text(gon.i18n.place_order[data.label]).fadeIn()

  @clear = (e) ->

    if e.currentTarget.checked
      @disableSubmit()
      @refreshBalance(null, null)
      @trigger "place_order::max::#{@usedInput}", max: BigNumber("1000000000000.0")
      @trigger "place_order::balance::change::#{@panelType()}", balance: BigNumber("1000000000000.0")
    else
      @enableSubmit()
      @refreshBalance(null, null)

    @resetForm(e)
    @select('feeLabelSel').fadeOut().text('')
    @select('feeLabelInfo').fadeOut().text('')
    @trigger 'place_order::focus::price'

  @calculatorClick = (e) ->
#    console.log @panelType(), e

    @clear(e)

  @after 'initialize', ->
    type = @panelType()

    if type == 'ask'
      @usedInput = 'volume'
    else
      @usedInput = 'total'

    @current_order = null

    PlaceOrderData.attachTo @$node
    OrderPriceUI.attachTo   @select('priceSel'),  form: @$node, type: type
    OrderVolumeUI.attachTo  @select('volumeSel'), form: @$node, type: type
    OrderTotalUI.attachTo   @select('totalSel'),  form: @$node, type: type

    @on 'place_order::price_alert::hide', @priceAlertHide
    @on 'place_order::price_alert::show', @priceAlertShow
    @on 'place_order::order::updated', @updateAvailable
    @on 'place_order::clear', @clear
    @on 'place_order::order::total', @updateOrder

    @on document, 'account::update', @refreshBalance

    @on @select('formSel'), 'ajax:beforeSend', @beforeSend
    @on @select('formSel'), 'ajax:success', @handleSuccess
    @on @select('formSel'), 'ajax:error', @handleError

    @on @select('currentBalanceSel'), 'click', @allIn

    if @panelType() == 'bid'
      @on @select('bidSel'), 'click', @calculatorClick
    else
      @on @select('askSel'), 'click', @calculatorClick

The most important part that needs to enter this code would be in this excerpt:

  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()

I've already tested the following, according to some answers found here:

  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()
    setTimeout(window.location.reload(1), 3000)

However the page reloads as soon as I click the button, there is no interval (3 seconds in this example)

Body:
I managed to solve it with the following change:

setTimeout(window.location.reload(1), 3000)

Where I converted to:

setTimeout (->
  window.location.reload 1
  return
), 3000

The code snippet then became:

  @handleSuccess = (event, data) ->
    @cleanMsg()
    @select('successSel').append(JST["templates/hint_order_success"]({msg: data.message})).show()
    @resetForm(event)
    window.sfx_success()
    @enableSubmit()
    setTimeout (->
      window.location.reload 1
      return
    ), 3000


问:
Why does Python believe return_value is a string?
What is wrong with the following bit of code?

```<code>class Dice:
    def roll_dice(x):
        import random
        return_value = '('
        try:
            y = int(x)
        except ValueError:
            return None
        for char in range(y):
            return_value += f'{random.randint(1, 6)}, '
        return_value = list(return_value).remove[-1 and -2]
        return_value = ''.join(str(e) for e in return_value)
        return return_value + ')'

parameter = input('Number of dice rolls: ')
print(Dice.roll_dice(parameter))
</code>```

The error is

```<code>Traceback (most recent call last):
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 17, in <module>
    print(Dice.roll_dice(parameter))
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 11, in roll_dice
    return_value = list(return_value).remove[-1 and -2]
TypeError: 'builtin_function_or_method' object is not subscriptable
</code>```

If I understand Python correctly, it thinks return_value is a string. But didn't I take the list of return_value on line 11 where the problem is? How does that work?

答:
The first argument of a class method should be named self, but the class is not a real class, because this missing self is never used. Write it as a normal function.
import belongs to the beginning of the file, not inside functions.
Instead of building a string with extra , and removing it by converting it to a list and back again to a string, you could simply use

```<code>return_value = return_value[:-2]
</code>```

but it would be better to not create a string in first place, but a list:

```<code>import random

def roll_dice(x):
    try:
        y = int(x)
    except ValueError:
        return None
    values = []
    for _ in range(y):
        values.append(str(random.randint(1, 6)))
    return f'({", ".join(values)})'
</code>```

Body:
What is wrong with the following bit of code?

class Dice:
    def roll_dice(x):
        import random
        return_value = '('
        try:
            y = int(x)
        except ValueError:
            return None
        for char in range(y):
            return_value += f'{random.randint(1, 6)}, '
        return_value = list(return_value).remove[-1 and -2]
        return_value = ''.join(str(e) for e in return_value)
        return return_value + ')'

parameter = input('Number of dice rolls: ')
print(Dice.roll_dice(parameter))

The error is

Traceback (most recent call last):
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 17, in <module>
    print(Dice.roll_dice(parameter))
  File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 11, in roll_dice
    return_value = list(return_value).remove[-1 and -2]
TypeError: 'builtin_function_or_method' object is not subscriptable

If I understand Python correctly, it thinks return_value is a string. But didn't I take the list of return_value on line 11 where the problem is? How does that work?

Body:
The first argument of a class method should be named self, but the class is not a real class, because this missing self is never used. Write it as a normal function.
import belongs to the beginning of the file, not inside functions.
Instead of building a string with extra , and removing it by converting it to a list and back again to a string, you could simply use

return_value = return_value[:-2]

but it would be better to not create a string in first place, but a list:

import random

def roll_dice(x):
    try:
        y = int(x)
    except ValueError:
        return None
    values = []
    for _ in range(y):
        values.append(str(random.randint(1, 6)))
    return f'({", ".join(values)})'


问:
Uncaught TypeError: Cannot set property 'value' of undefined for input fields
I have this code:

```<code>var username = 'xyz';
var password = 'xyz';
var input = document.getElementsByClassName('_2hvTZ pexuQ zyHYP');
var button = document.getElementsByClassName('sqdOP L3NKy y3zKF');
input[0].value = username;
input[1].value = password;
button.click();
</code>```

Every time I get this error, but in the console, the two input fields are found in the dom.

Uncaught TypeError: Cannot set property 'value' of undefined

I'm able to get the HTML collection array of the two elements.

This is the outerHTML of them:

```<code><input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">

<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">"
</code>```

Here is a screen of the consolle

Any solution?

答:
For this I would think you would want to access the fields by id, not class. that's not good programming, what you have.

also, you should always check if your array contains at least 2 elements before trying to access the second element of it.

one more thing... isn't "button" an array? (which is a bad name for an array) not sure if button.click() makes any sense.

Body:
I have this code:

var username = 'xyz';
var password = 'xyz';
var input = document.getElementsByClassName('_2hvTZ pexuQ zyHYP');
var button = document.getElementsByClassName('sqdOP L3NKy y3zKF');
input[0].value = username;
input[1].value = password;
button.click();

Every time I get this error, but in the console, the two input fields are found in the dom.

Uncaught TypeError: Cannot set property 'value' of undefined

I'm able to get the HTML collection array of the two elements.

This is the outerHTML of them:

<input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">

<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">"

Here is a screen of the consolle

Any solution?


问:
Programmatically setting WPF property
I have a TextBlock control and I am declaratively setting the Text property to {loc:Translate}.

```<code><TextBlock x:Name="Message" Text="{loc:Translate}" loc:TranslateExtension.Uid="myMessage"  />
</code>```

During runtime, I update the Text property value to something else. I then need to reset it back to {loc:Translate}.

My question is, how can I programmatically set Text to {loc:Translate}?

答:
When a XAML processor processes a type node and member value that is a markup extension, it invokes the ProvideValue method of that markup extension and writes the result into the object graph or serialization stream. The XAML object writer passes service context to each such implementation through the serviceProvider parameter.

tb.Text = new TranslateExtension().ProvideValue(null) as string;
```

This should be it except that this is lacking a 'proper' IServiceProvider-parameter.

In typical usage, the .NET Framework XAML Services and the implemented XAML object writers will provide a service provider to all value converter methods it invokes during XAML processing. However, for robustness, you should provide code paths for null values both for the service provider itself and for any requested service. Null values might occur if your markup extension is applied in some circumstance where the typical service support provided by a XAML parser infrastructure is not available.

So depending on your extension implementation you could actually pass null to ProvideValue.

Title: Programmatically setting WPF property

Body:
I have a TextBlock control and I am declaratively setting the Text property to {loc:Translate}.

<TextBlock x:Name="Message" Text="{loc:Translate}" loc:TranslateExtension.Uid="myMessage"  />

During runtime, I update the Text property value to something else. I then need to reset it back to {loc:Translate}.

My question is, how can I programmatically set Text to {loc:Translate}?

Body:
When a XAML processor processes a type node and member value that is a markup extension, it invokes the ProvideValue method of that markup extension and writes the result into the object graph or serialization stream. The XAML object writer passes service context to each such implementation through the serviceProvider parameter.

tb.Text = new TranslateExtension().ProvideValue(null) as string;

This should be it except that this is lacking a 'proper' IServiceProvider-parameter.

In typical usage, the .NET Framework XAML Services and the implemented XAML object writers will provide a service provider to all value converter methods it invokes during XAML processing. However, for robustness, you should provide code paths for null values both for the service provider itself and for any requested service. Null values might occur if your markup extension is applied in some circumstance where the typical service support provided by a XAML parser infrastructure is not available.

So depending on your extension implementation you could actually pass null to ProvideValue.