问:
Keep getting a "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup" when attempting to google plus login on my web app
I'm trying to implement Google plus sign up on my web app and I followed the google docs to set up the sign up however when I attempt a signup after accepting permissions and using the access token returned to me any api restcall I make returns the Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup error. I have already signed up my app with a ouath 2.0 key, so I don't seem to get what I'm doing wrong. Here is my code.

Cient Side:

```<code>const clientId = "5XXX000XX.apps.googleusercontent.com";
const apiKey = "AIzaSyCAXE5JSa36jcC*X7HV40SBcIWBiVGUTBE";
const scopes = "https://www.googleapis.com/auth/plus.login";
let accessToken = null;

function initer() {
  gapi.client.setApiKey(apiKey);
  // alert("Hello init");
  if ($("#authorize-button").length > 0) {
    $("#authorize-button").click(onLoginClick);
  }
}

function onLoginClick() {
  // $("#modalLoading").modal();
  // alert("yeah");
  gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, onConnect);
}

function onConnect(authResult) {
  // alert("On connect");
  if (authResult && !authResult.error) {
    alert("Hey");
    accessToken = authResult.access_token;
    triggerLogin();
  } else {
    alert("Error");
  }
}

triggerLogin = function() {
  alert("Triggering login");
  $("#modalLoading").modal();
  $.ajax({
    url: window.config.site_root + "account/google_login",
    type: "POST",
    data: "access_token=" + accessToken,
    success: onLogin,
    error() {
      onError("Logging In", "starting your session");
    },
  });
};

onLogin = function(login) {
  alert("Login start");
  $("#modalLoading").modal("hide");
  if (login.operation) {
    location.reload();
  } else {
    alert("Register will start");
    triggerRegistration();
  }
};

triggerRegistration = function() {
  $("#modalLoading").modal();
  $.ajax({
    url: window.config.site_root + "account/google_registration",
    type: "POST",
    data: "access_token=" + accessToken,
    success: onRegistration,
    error() {
      alert("An Error");
    },
  });
};

onRegistration = function(data) {
  alert("Handling register");
  $("#modalLoading").modal("hide");
  if (data.account_exists) {
    stage.showErrorModal(
      "Account already registered",
      "There is already an account with that email address, are you sure you created an account using this login method?",
    );
  } else if (data.operation) {
    alert("Login now");
    triggerLogin();
  } else {
    alert("Error");
    onError("Registering", "creating your account");
  }
};
</code>```

Here is my server side code

```<code> public function google_registration()
            {
                $access_token = (isset($_POST["access_token"]) && !empty($_POST["access_token"])) ? $_POST["access_token"] : null;

                $name = null;
                $email = null;
                $account_id = null;
                $picture = null;
                $gender = null;

                try
                {
                    if($access_token)
                    {
                        $me = file_get_contents("https://www.googleapis.com/plus/v1/people/me?access_token=".$access_token);
                        if($me)
                        {
                            $me = json_decode($me);
                            $name = $me->name.formatted;
                            $email = $me->email;
                            $account_id = $me->id;
                            $picture = $me->image;
                            $gender = ($me->gender == "female") ? 1 : 0;
                        }
                    }
                }
                catch(Exception $error)
                {
                    // let the system handle the error quietly.
                }
                return $this->service_registration("google", $name, $email, $account_id, $picture, $gender);

            }
</code>```

答:
I was also desperate, and finally I managed to find a solution. The only problem is to add the correct api token linked to your app, in my case was the browser token, and it all works.

Example: I wanted to have all the events associated with my calendar

https://www.googleapis.com/calendar/v3/calendars/{calendar_id}/events?&key={api_key}

maybe I will help someone who is having the same problem.

Good Luck

Body:
I'm trying to implement Google plus sign up on my web app and I followed the google docs to set up the sign up however when I attempt a signup after accepting permissions and using the access token returned to me any api restcall I make returns the Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup error. I have already signed up my app with a ouath 2.0 key, so I don't seem to get what I'm doing wrong. Here is my code.

Cient Side:

const clientId = "5XXX000XX.apps.googleusercontent.com";
const apiKey = "AIzaSyCAXE5JSa36jcC*X7HV40SBcIWBiVGUTBE";
const scopes = "https://www.googleapis.com/auth/plus.login";
let accessToken = null;

function initer() {
  gapi.client.setApiKey(apiKey);
  // alert("Hello init");
  if ($("#authorize-button").length > 0) {
    $("#authorize-button").click(onLoginClick);
  }
}

function onLoginClick() {
  // $("#modalLoading").modal();
  // alert("yeah");
  gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, onConnect);
}

function onConnect(authResult) {
  // alert("On connect");
  if (authResult && !authResult.error) {
    alert("Hey");
    accessToken = authResult.access_token;
    triggerLogin();
  } else {
    alert("Error");
  }
}

triggerLogin = function() {
  alert("Triggering login");
  $("#modalLoading").modal();
  $.ajax({
    url: window.config.site_root + "account/google_login",
    type: "POST",
    data: "access_token=" + accessToken,
    success: onLogin,
    error() {
      onError("Logging In", "starting your session");
    },
  });
};

onLogin = function(login) {
  alert("Login start");
  $("#modalLoading").modal("hide");
  if (login.operation) {
    location.reload();
  } else {
    alert("Register will start");
    triggerRegistration();
  }
};

triggerRegistration = function() {
  $("#modalLoading").modal();
  $.ajax({
    url: window.config.site_root + "account/google_registration",
    type: "POST",
    data: "access_token=" + accessToken,
    success: onRegistration,
    error() {
      alert("An Error");
    },
  });
};

onRegistration = function(data) {
  alert("Handling register");
  $("#modalLoading").modal("hide");
  if (data.account_exists) {
    stage.showErrorModal(
      "Account already registered",
      "There is already an account with that email address, are you sure you created an account using this login method?",
    );
  } else if (data.operation) {
    alert("Login now");
    triggerLogin();
  } else {
    alert("Error");
    onError("Registering", "creating your account");
  }
};

Here is my server side code

 public function google_registration()
            {
                $access_token = (isset($_POST["access_token"]) && !empty($_POST["access_token"])) ? $_POST["access_token"] : null;

                $name = null;
                $email = null;
                $account_id = null;
                $picture = null;
                $gender = null;

                try
                {
                    if($access_token)
                    {
                        $me = file_get_contents("https://www.googleapis.com/plus/v1/people/me?access_token=".$access_token);
                        if($me)
                        {
                            $me = json_decode($me);
                            $name = $me->name.formatted;
                            $email = $me->email;
                            $account_id = $me->id;
                            $picture = $me->image;
                            $gender = ($me->gender == "female") ? 1 : 0;
                        }
                    }
                }
                catch(Exception $error)
                {
                    // let the system handle the error quietly.
                }
                return $this->service_registration("google", $name, $email, $account_id, $picture, $gender);

            }


来源: stackexchange

问:
C++ Move Constructor With Pointers (*&& Syntax)
I would like to know if there are any problems with the construction <type>*&& in C++. Let me give a concrete example.

Say we have a class that should be constructed from an array. We would usually do something like this:

```<code>class Things
{

    public:
         Things(const ThingType* arrayOfThings, int sizeOfArray)
            : myArray(new ThingType[sizeOfArray])
         {
              for (int i = 0; i < sizeOfArray; i++)
                  myArray[i] = arrayOfThings[i];

         }

    private:
         ThingType* myArray;
  }
</code>```

This is fine if we want to preserve arrayOfThings, because we are doing a deep copy of it. Moreover, by using const we are ensuring it won't be modified inside the constructor.

But suppose our program has a lot of statements like this one:

```<code>Things myThings(new ThingType[9001] {thing_0, ... , thing_9000}, 9001);
</code>```

This might seem weird, but it may happen that the huge ThingType array is returned from a function as a rvalue.

In that case, we don't care about preserving the pointer passed as a parameter. In fact, we definitely don't want to do a deep copy of it, because it would be a huge waste of time preserving something we are about to destroy anyways.

One possible solution to this would to add another constructor that would handle the case of a non-const rvalue ThingType pointer, like a general move constructor handles the case of a non-const rvalue instance of the class:

```<code>public:
     Things(ThingType*&& arrayOfThings, int sizeOfArray)
            : myArray(arrayOfThings)
         {
              arrayOfThings = NULL;
         }
</code>```

This seems to be solving the problem for me, but I did not find much information about the <type>*&& construction seen above. Is it kosher, or will I be sent to the dungeons for mixing pointers and references?

答:
After some time I believe I found satisfactory - although far from optimal - solutions. Since no one answered the question, I will share the best workarounds I found.

As Justin pointed out, using ThingType*&& can lead to trouble when we take the address of a variable of ThingType (but not of a ThingType pointer, as he implied in his answer) in the constructor call.

If t is a ThingType, the expression &t is an r-value of type ThingType*, so Thing myThing(&t, ...) will call the move constructor, with the result of making myThing.myArray point to t. This is not what we would want in most cases.

One solution is to use vectors instead of arrays, as illustrated below:

```<code>// Copy
explicit Things(const std::vector<ThingType>& vectorOfThings)
            : myVector(vectorOfThings)
         {  }

// Move
explicit Things(std::vector<ThingType>&& vectorOfThings)
        : myVector(std::move(vectorOfThings))
         {  }
</code>```

The move constructor would then be used in situations like this:

Things myThings(vector<ThingType>{thing_0, ... , thing_9000});

Although this solves the problem, it is not feasible if we are dependent on an API which returns raw pointers, or if we want don't want to give up arrays. In this case, we can use smart pointers to solve the problem.

Suppose, we have a function ThingType* generateArray() which we want to use to initialize our object of type Things. The first thing we should do is to wrap this function with another function that returns a smart pointer instead.

```<code>unique_ptr<ThingType[]> generateSmartPointer()
{
  return unique_ptr<ThingType[]>(generateArray());
}
</code>```

Here I used a unique_pointer, but this could change depending on the implementation.

Now we add a new constructor to Things, with a instance of unique_ptr as an argument. This will act as the move constructor for arrays of ThingType:

```<code>Things(unique_ptr<ThingType[]> thingsPointer, int sizeOfArray)
        : myArray(thingsInput.release()), size(sizeOfArray)
         {  }
</code>```

unique_ptr<T>.release() is used to get the array, and at the same time make the unique pointer release ownership of it, preventing the array from being deleted once the unique pointer is destroyed.

And that's it. These are the two best solutions I found to this problem, and while they are far from perfect, they have worked so far considering the objectives for each implementation.

ContentLicense: CC BY-SA 3.0

Body:
I would like to know if there are any problems with the construction <type>*&& in C++. Let me give a concrete example.

Say we have a class that should be constructed from an array. We would usually do something like this:

class Things
{

    public:
         Things(const ThingType* arrayOfThings, int sizeOfArray)
            : myArray(new ThingType[sizeOfArray])
         {
              for (int i = 0; i < sizeOfArray; i++)
                  myArray[i] = arrayOfThings[i];

         }

    private:
         ThingType* myArray;
  }

This is fine if we want to preserve arrayOfThings, because we are doing a deep copy of it. Moreover, by using const we are ensuring it won't be modified inside the constructor.

But suppose our program has a lot of statements like this one:

Things myThings(new ThingType[9001] {thing_0, ... , thing_9000}, 9001);

This might seem weird, but it may happen that the huge ThingType array is returned from a function as a rvalue.

In that case, we don't care about preserving the pointer passed as a parameter. In fact, we definitely don't want to do a deep copy of it, because it would be a huge waste of time preserving something we are about to destroy anyways.

One possible solution to this would to add another constructor that would handle the case of a non-const rvalue ThingType pointer, like a general move constructor handles the case of a non-const rvalue instance of the class:

public:
     Things(ThingType*&& arrayOfThings, int sizeOfArray)
            : myArray(arrayOfThings)
         {
              arrayOfThings = NULL;
         }

This seems to be solving the problem for me, but I did not find much information about the <type>*&& construction seen above. Is it kosher, or will I be sent to the dungeons for mixing pointers and references?

Body:
After some time I believe I found satisfactory - although far from optimal - solutions. Since no one answered the question, I will share the best workarounds I found.

As Justin pointed out, using ThingType*&& can lead to trouble when we take the address of a variable of ThingType (but not of a ThingType pointer, as he implied in his answer) in the constructor call.

If t is a ThingType, the expression &t is an r-value of type ThingType*, so Thing myThing(&t, ...) will call the move constructor, with the result of making myThing.myArray point to t. This is not what we would want in most cases.

One solution is to use vectors instead of arrays, as illustrated below:

// Copy
explicit Things(const std::vector<ThingType>& vectorOfThings)
            : myVector(vectorOfThings)
         {  }

// Move
explicit Things(std::vector<ThingType>&& vectorOfThings)
        : myVector(std::move(vectorOfThings))
         {  }

The move constructor would then be used in situations like this:

Things myThings(vector<ThingType>{thing_0, ... , thing_9000});

Although this solves the problem, it is not feasible if we are dependent on an API which returns raw pointers, or if we want don't want to give up arrays. In this case, we can use smart pointers to solve the problem.

Suppose, we have a function ThingType* generateArray() which we want to use to initialize our object of type Things. The first thing we should do is to wrap this function with another function that returns a smart pointer instead.

unique_ptr<ThingType[]> generateSmartPointer()
{
  return unique_ptr<ThingType[]>(generateArray());
}

Here I used a unique_pointer, but this could change depending on the implementation.

Now we add a new constructor to Things, with a instance of unique_ptr as an argument. This will act as the move constructor for arrays of ThingType:

Things(unique_ptr<ThingType[]> thingsPointer, int sizeOfArray)
        : myArray(thingsInput.release()), size(sizeOfArray)
         {  }

unique_ptr<T>.release() is used to get the array, and at the same time make the unique pointer release ownership of it, preventing the array from being deleted once the unique pointer is destroyed.

And that's it. These are the two best solutions I found to this problem, and while they are far from perfect, they have worked so far considering the objectives for each implementation.


问:
TypeError: Cannot read property 'length' of undefined array shuffle in react
I am new to React and I am trying to figure out how I can shuffle an array. I have tried different way to shuffle the array but the problem is always with the length. TypeError: Cannot read property 'length' of undefined. I am not sure why this is happening or how I should deal with it in React. To me, this shouldn't be an issue with React but again I don't know. What should happen when everything works:

You click on the button 'hard' and it should render the two first elements from the array challenge, and every time you click on that button the array should be shuffled.

Do you have any idea that could help me?

This is the code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

let era = [
  60, 70, 80, 90, 2000
]

let genre = [
  'Rock', 'Pop', 'Jazz', 'Country'
]

let challenge = [
  'LikeElvis', 'Parent\'s favourite songs', 'too high for me'
]

class Karaoke extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      'easy': '',
      'easyChallenge': '',
      'hard': '',
      'hardChallenge': '',
      'hardEra': ''
    }
  };

  selectEasy = () => {
    let genreSelected = [];
    let challengeSelected = [];
    genreSelected.push(genre[Math.floor(Math.random() * genre.length)]);
    this.setState({"easy": genreSelected})

    challengeSelected.push(challenge[Math.floor(Math.random() * challenge.length)]);
    this.setState({"easyChallenge": challengeSelected})
  }

  selectHard = () => {
    let genreSelected = [];
    let challengeSelected = [];
    let eraSelected = [];
    genreSelected.push(genre[Math.floor(Math.random() * genre.length)]);
    eraSelected.push(era[Math.floor(Math.random() * era.length)]);

    this.setState({ "hard": genreSelected} );
    this.setState({ "hardEra": eraSelected} );
    this.setState({ "hardChallenge": challengeSelected} );

    challengeSelected.push(challenge.slice(0, 2))
    console.log(challengeSelected);
  }

  shuffle = (challenge) => {
    let i = challenge.length, temporaryValue, randomIndex;
    while (0 !== i) {
      randomIndex = Math.floor(Math.random() * i);
      i -= 1;
      temporaryValue = challenge[i];
      challenge[i] = challenge[randomIndex];
      challenge[randomIndex] = temporaryValue;
    }
    return challenge
  }

  click = () => {
    this.selectHard();
    this.shuffle();
  }

  render = () => {
    return(
      <div>
        <button onClick={this.selectEasy}>Easy</button>
        <button onClick={this.click}>Hard</button>
        <h1>the genre is {this.state.easy} </h1>
        <h1>the challenge is {this.state.easyChallenge} </h1>
        <h1>Hard mode: {this.state.hard} + {this.state.hardEra + '\'s'}</h1>
        <h1>Hard mode challenge: {this.state.hardChallenge} </h1>
      </div>
    )
  }

}

ReactDOM.render(<Karaoke />, document.getElementById('root'));
</code>```

答:
You are defining your suffle method expecting an argument. But then when you call it from the click method you are not providing said argument:

```<code>shuffle(challenge) {
    // ...
}

click = () => {
    // ...
    this.shuffle();
}
</code>```

This will cause the declared argument to be undefined and the suffle method will not default the global challenge variable.

To solve this, you need to either remove the argument from the method defintion or pass it in the click function:

```<code>shuffle() {
    // ...
}
click = () => {
    // ...
    this.shuffle();
}

/* OR */

shuffle(challenge) {
    // ...
}
click = () => {
    // ...
    this.shuffle(challenge);
}
</code>```

Body:
I am new to React and I am trying to figure out how I can shuffle an array. I have tried different way to shuffle the array but the problem is always with the length. TypeError: Cannot read property 'length' of undefined. I am not sure why this is happening or how I should deal with it in React. To me, this shouldn't be an issue with React but again I don't know. What should happen when everything works:

You click on the button 'hard' and it should render the two first elements from the array challenge, and every time you click on that button the array should be shuffled.

Do you have any idea that could help me?

This is the code:

import React from 'react';
import ReactDOM from 'react-dom';

let era = [
  60, 70, 80, 90, 2000
]

let genre = [
  'Rock', 'Pop', 'Jazz', 'Country'
]

let challenge = [
  'LikeElvis', 'Parent\'s favourite songs', 'too high for me'
]

class Karaoke extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      'easy': '',
      'easyChallenge': '',
      'hard': '',
      'hardChallenge': '',
      'hardEra': ''
    }
  };

  selectEasy = () => {
    let genreSelected = [];
    let challengeSelected = [];
    genreSelected.push(genre[Math.floor(Math.random() * genre.length)]);
    this.setState({"easy": genreSelected})

    challengeSelected.push(challenge[Math.floor(Math.random() * challenge.length)]);
    this.setState({"easyChallenge": challengeSelected})
  }

  selectHard = () => {
    let genreSelected = [];
    let challengeSelected = [];
    let eraSelected = [];
    genreSelected.push(genre[Math.floor(Math.random() * genre.length)]);
    eraSelected.push(era[Math.floor(Math.random() * era.length)]);

    this.setState({ "hard": genreSelected} );
    this.setState({ "hardEra": eraSelected} );
    this.setState({ "hardChallenge": challengeSelected} );

    challengeSelected.push(challenge.slice(0, 2))
    console.log(challengeSelected);
  }

  shuffle = (challenge) => {
    let i = challenge.length, temporaryValue, randomIndex;
    while (0 !== i) {
      randomIndex = Math.floor(Math.random() * i);
      i -= 1;
      temporaryValue = challenge[i];
      challenge[i] = challenge[randomIndex];
      challenge[randomIndex] = temporaryValue;
    }
    return challenge
  }

  click = () => {
    this.selectHard();
    this.shuffle();
  }

  render = () => {
    return(

        <button onClick={this.selectEasy}>Easy</button>
        <button onClick={this.click}>Hard</button>

the genre is {this.state.easy}

the challenge is {this.state.easyChallenge}

Hard mode: {this.state.hard} + {this.state.hardEra + '\'s'}

Hard mode challenge: {this.state.hardChallenge}

    )
  }

}

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

Body:
You are defining your suffle method expecting an argument. But then when you call it from the click method you are not providing said argument:

shuffle(challenge) {
    // ...
}

click = () => {
    // ...
    this.shuffle();
}

This will cause the declared argument to be undefined and the suffle method will not default the global challenge variable.

To solve this, you need to either remove the argument from the method defintion or pass it in the click function:

shuffle() {
    // ...
}
click = () => {
    // ...
    this.shuffle();
}

/* OR */

shuffle(challenge) {
    // ...
}
click = () => {
    // ...
    this.shuffle(challenge);
}


问:
Eliminate the "conversion to std::vector<int>::size_type to int" warning
I want to eliminate warnings in my code and I am looking for an answer regarding those two:

```<code>1.   warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for( auto i = 0; i < w.size(); i++ ) {
</code>```

and

```<code>2. warning: conversion to ‘std::vector<int>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Wsign-conversion]
         for ( int count = 0; count < w[i]; count++ )
</code>```

The source code is below. A vector of ints is returned with some random numbers.

```<code> for( auto i = 0; i < w.size(); i++ ) {
</code>```

```<code>     std::vector<int> random(std::vector<int>& w){

        std::vector<int> v;
        v.clear();

        std::random_device device;
        std::mt19937 generator(device());

        for( auto i = 0; i < w.size(); i++ ) {

            for ( int count = 0; count < w[i]; count++ )
                v.push_back(i);
        }

        std::shuffle(v.begin(), v.end(), generator);

        return v;
    }
</code>```

Optimal solution?

答:
To fix the first warning:

```<code>for( std::vector<int>::size_type i = 0; i < w.size(); i++ ) {
</code>```

To fix the second warning:

```<code>for ( std::vector<int>::size_type count = 0; count < w[i]; count++ )
</code>```

To make that a little less typing:

```<code>using index_t = std::vector<int>::size_type;
</code>```

UPDATE: ha-ha (doh!), my mistake on the second warning.  It was caused by using i, not by count's type.

Body:
I want to eliminate warnings in my code and I am looking for an answer regarding those two:

1.   warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for( auto i = 0; i < w.size(); i++ ) {

and

2. warning: conversion to ‘std::vector<int>::size_type {aka long unsigned int}’ from ‘int’ may change the sign of the result [-Wsign-conversion]
         for ( int count = 0; count < w[i]; count++ )

The source code is below. A vector of ints is returned with some random numbers.

 for( auto i = 0; i < w.size(); i++ ) {

     std::vector<int> random(std::vector<int>& w){

        std::vector<int> v;
        v.clear();

        std::random_device device;
        std::mt19937 generator(device());

        for( auto i = 0; i < w.size(); i++ ) {

            for ( int count = 0; count < w[i]; count++ )
                v.push_back(i);
        }

        std::shuffle(v.begin(), v.end(), generator);

        return v;
    }

Optimal solution?

Body:
To fix the first warning:

for( std::vector<int>::size_type i = 0; i < w.size(); i++ ) {

To fix the second warning:

for ( std::vector<int>::size_type count = 0; count < w[i]; count++ )

To make that a little less typing:

using index_t = std::vector<int>::size_type;

UPDATE: ha-ha (doh!), my mistake on the second warning.  It was caused by using i, not by count's type.


问:
Ionic change navbar color dynamically
I have to change the color of the navbar of one page when scrolling a bit.

Here we have part of my xml file:

```<code><ion-header no-border>

  <ion-navbar color="{{ toolbar_color }}">
    <ion-title (click)="change()">{{userdata.Name}}</ion-title>
  </ion-navbar>

</ion-header>

<ion-content fullscreen class="container" (ionScrollEnd)="scrollHandler($event)">
</code>```

I tryed first by changing it using a click event and it worked fine.

```<code>change() {
    if ( this.toolbar_color == "danger" ) {
      this.toolbar_color = "light"
    } else {
      this.toolbar_color = "danger"
    }
}
</code>```

And this is the ionScrollEnd listener, that does not work. The event is fired correctly, but the changes on toolbar_color are not taking any effect on the navbar.

```<code>scrollHandler(event) {
    if ( event.scrollTop > 100 ) {
      console.log("ScrollEvent --> "+JSON.stringify(event));
      this.toolbar_color = "light"
      // this.toolbar_change = true;
    } else {
      this.toolbar_color = "danger"
      // this.toolbar_change = false;
    }
}
</code>```

How the hell can I do this?

Thank you :)

答:
Add @ViewChild(Content) content: Content in the TS file and subscribe to scroll end event. refer this link for working version. Also see the ionic forum discussion on this issue

```<code>import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';
import { NavController, Content } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Content) content: Content;
  Arr = Array; //Array type captured in a variable
  num:number = 1000;
  toolbar_color: string;

  constructor(public navCtrl: NavController, public ref : ChangeDetectorRef) {
    this.toolbar_color="secondary";
  }

  changeColor(){
    this.toolbar_color="primary";
    this.ref.detectChanges();
  }

  ionViewDidLoad() {
    //this.content.enableJsScroll();
    this.content.ionScrollEnd.subscribe(() => {
        this.changeColor();
    });
}

}
</code>```

HTML file

```<code><ion-header>
  <ion-navbar [color]="toolbar_color">
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to Ionic!</h2>
  <p>
    This starter project comes with simple tabs-based layout for apps
    that are going to primarily use a Tabbed UI.
  </p>
  <p>
    Take a look at the <code>pages/</code> directory to add or change tabs,
    update any existing page or create new pages.
  </p>
  <div  *ngFor="let i of Arr(num).fill(1)">{{i}}</div>

</ion-content>
</code>```

Update-1

Added code to change color on scrolling

Sometimes angular will not run changeDetector automatically. we can manually trigger it by using ChangeDetectorRef. it's added to detect the changes while scrolling.

Working version is also updated. Please check the above link

Title: Ionic change navbar color dynamically

Body:
I have to change the color of the navbar of one page when scrolling a bit.

Here we have part of my xml file:

<ion-header no-border>

  <ion-navbar color="{{ toolbar_color }}">
    <ion-title (click)="change()">{{userdata.Name}}</ion-title>
  </ion-navbar>

</ion-header>

<ion-content fullscreen class="container" (ionScrollEnd)="scrollHandler($event)">

I tryed first by changing it using a click event and it worked fine.

change() {
    if ( this.toolbar_color == "danger" ) {
      this.toolbar_color = "light"
    } else {
      this.toolbar_color = "danger"
    }
}

And this is the ionScrollEnd listener, that does not work. The event is fired correctly, but the changes on toolbar_color are not taking any effect on the navbar.

scrollHandler(event) {
    if ( event.scrollTop > 100 ) {
      console.log("ScrollEvent --> "+JSON.stringify(event));
      this.toolbar_color = "light"
      // this.toolbar_change = true;
    } else {
      this.toolbar_color = "danger"
      // this.toolbar_change = false;
    }
}

How the hell can I do this?

Thank you :)

Body:
Add @ViewChild(Content) content: Content in the TS file and subscribe to scroll end event. refer this link for working version. Also see the ionic forum discussion on this issue

import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';
import { NavController, Content } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Content) content: Content;
  Arr = Array; //Array type captured in a variable
  num:number = 1000;
  toolbar_color: string;

  constructor(public navCtrl: NavController, public ref : ChangeDetectorRef) {
    this.toolbar_color="secondary";
  }

  changeColor(){
    this.toolbar_color="primary";
    this.ref.detectChanges();
  }

  ionViewDidLoad() {
    //this.content.enableJsScroll();
    this.content.ionScrollEnd.subscribe(() => {
        this.changeColor();
    });
}

}

HTML file

<ion-header>
  <ion-navbar [color]="toolbar_color">
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to Ionic!</h2>
  <p>
    This starter project comes with simple tabs-based layout for apps
    that are going to primarily use a Tabbed UI.
  </p>
  <p>
    Take a look at the <code>pages/</code> directory to add or change tabs,
    update any existing page or create new pages.
  </p>
  <div  *ngFor="let i of Arr(num).fill(1)">{{i}}</div>

</ion-content>

Update-1

Added code to change color on scrolling

Sometimes angular will not run changeDetector automatically. we can manually trigger it by using ChangeDetectorRef. it's added to detect the changes while scrolling.

Working version is also updated. Please check the above link


问:
Visual Studio 2015 RTM - Debugging not working
I have installed VS 2015 RTM (nothing else) and I'm unable to debug any solution, not matter if it's an existing one or a brand new one (created with VS 2015 and compiled against .Net Framework 4.6), it only opens a new tab in VS which is called Break Mode with the following text:
The application is in break mode
Your app has entered a break state, but no code is executing that is supported by the selected debug  engine  (for e.g. only native runtime code is executing).
And if I check the Debug --> Module Window:
VS2015Test.vshost.exe no symbols loaded (even if I click load symbol it does not work)
VS2015Test.exe symbols loaded

And it also doesn't show the output on the console(it's a console application that just has the following lines of code:

```<code>class Program
{
        static void Main(string[] args)
        {
            Console.WriteLine("TEST");
            Console.ReadKey();
        }
    }
</code>```

I tried to reinstall VS 2015, restarted the computer, deleted all files in %temp%/AppData/Microsoft/Visual Studio/14, started VS in Admin Mode but nothing seems to work.

One thing which makes debugging working is this option:
Tools --> Options --> Debugging --> Use Managed Compability Mode

^^But that can't be the solution to use an old/legacy mode.

BTW: Debugging in VS 2013 is working fine.

Any help would be appreciated.

答:
In my case it was due to the project Target platforms were different.

Consider :  ProjectA (Entry) --> ProjectB

ProjectA's platform in properties was set to x64.
And ProjectB's platform was 'AnyCPU'.

So after setting ProjectB's target platform to x64 this issue got fixed.

Note: It's just that Target Platform has to be in sync be it x64 or
  'Any CPU'

Body:
I have installed VS 2015 RTM (nothing else) and I'm unable to debug any solution, not matter if it's an existing one or a brand new one (created with VS 2015 and compiled against .Net Framework 4.6), it only opens a new tab in VS which is called Break Mode with the following text:
The application is in break mode
Your app has entered a break state, but no code is executing that is supported by the selected debug  engine  (for e.g. only native runtime code is executing).
And if I check the Debug --> Module Window:
VS2015Test.vshost.exe no symbols loaded (even if I click load symbol it does not work)
VS2015Test.exe symbols loaded

And it also doesn't show the output on the console(it's a console application that just has the following lines of code:

class Program
{
        static void Main(string[] args)
        {
            Console.WriteLine("TEST");
            Console.ReadKey();
        }
    }

I tried to reinstall VS 2015, restarted the computer, deleted all files in %temp%/AppData/Microsoft/Visual Studio/14, started VS in Admin Mode but nothing seems to work.

One thing which makes debugging working is this option:
Tools --> Options --> Debugging --> Use Managed Compability Mode

^^But that can't be the solution to use an old/legacy mode.

BTW: Debugging in VS 2013 is working fine.

Any help would be appreciated.


问:
EPL Online Tool from Esper Tech gives a status 0
I am testing the Esper EPL Online Tool with the default example written on the form. However, when I click the "Submit" button, I only get a pop up with the message "Status 0".

Should the example run as it is or am I missing something? Is there a problem with the online tool?

Thanks in advance.

答: So, it seems it had something to do with the firewall set by the university network. I tried accessing it from the outside and it works perfectly. Thanks for your help.</p>


问:
Error in getEndOffsetInclusive function
I'm trying to delete all the text from a certain part of the document to the end of the document. However, when I run the the below code, I get an error:

```<code>TypeError: Cannot find function getEndOffsetInclusive in object Text. (line 79, file "Code")
</code>```

The line in question is:

```<code>var endOff = text.getEndOffsetInclusive();
</code>```

Below is the full function:

```<code>    function removeText() {
    var body = DocumentApp.getActiveDocument().getBody();
    var text = body.editAsText();
    var endOff = text.getEndOffsetInclusive();

    var search = "TESTHERE";
    var rangeElement = DocumentApp.getActiveDocument().getBody().findText(search);
    if (rangeElement.isPartial()) {
       var startOffset = rangeElement.getStartOffset();
       var endOffset = text.getEndOffsetInclusive();
       rangeElement.getElement().asText().deleteText(startOffset,endOffset);
    }

}
</code>```

Any ideas as to why it's giving this error?

答:
That function does not exist on Text instances. But it does exist on the RangeElement object. Update your code to:

```<code>var endOffset = rangeElement.getEndOffsetInclusive();
</code>```

Title: Error in getEndOffsetInclusive function

Body:
I'm trying to delete all the text from a certain part of the document to the end of the document. However, when I run the the below code, I get an error:

TypeError: Cannot find function getEndOffsetInclusive in object Text. (line 79, file "Code")

The line in question is:

var endOff = text.getEndOffsetInclusive();

Below is the full function:

    function removeText() {
    var body = DocumentApp.getActiveDocument().getBody();
    var text = body.editAsText();
    var endOff = text.getEndOffsetInclusive();

    var search = "TESTHERE";
    var rangeElement = DocumentApp.getActiveDocument().getBody().findText(search);
    if (rangeElement.isPartial()) {
       var startOffset = rangeElement.getStartOffset();
       var endOffset = text.getEndOffsetInclusive();
       rangeElement.getElement().asText().deleteText(startOffset,endOffset);
    }

}

Any ideas as to why it's giving this error?

Body:
That function does not exist on Text instances. But it does exist on the RangeElement object. Update your code to:

var endOffset = rangeElement.getEndOffsetInclusive();


问:
Internal Server Errors are mapped to 302 Found with a redirect to "/offline_pages/" on Swisscom CloudFoundry
We are using the Swisscom CloudFoundry solution with a Java and a Node.JS application. Since very recently, every HTTP status code starting with 5xx (tested with 500 and 503) is automatically mapped to the status code 302 Found with a redirect header to /offline_pages/ (tested with DELETE, POST and GET). This is done in-between our application and the front-end, requesting a resource with a status code 5xx.

We are actively using the 5xx status codes to report a server error to the front-end over our REST API (including maintenance down-time etc.). This does not work anymore, because of the automatic mapping. For instance, there is no automatic redirect to a maintenance page anymore, because the front-end does not see 3xx status as an error.

This issue occurs in both our applications (Java and Node.JS). The logs, however, display the correct 503 respectively 500 error. Furthermore, in our application's code base the redirect URL string /offline_pages/ is not even present; which leads to the conclusion, that this must be done outside of our application.

If a visible browser page returns a 500 the user is actually redirected to the page /offline_pages which displays a Swisscom error page. This error page (to which it redirected), then returns a 200 status code on its part, making it impossible to automatically detect the error in a Kiosk browser.

Is there any possibility to configure the Swisscom CloudFoundry to deactivate this behavior, which is suddenly occurring?

This is the request made by the front-end:

```<code>GET /api/account HTTP/1.1
Host: <HOST>
Connection: keep-alive
Accept: application/json, text/plain, */*
User-Agent: <USER-AGENT>
Referer: <REFERER>
Accept-Encoding: gzip, deflate, br
Accept-Language: <LANGUAGES>
</code>```

And this is the response:

```<code>HTTP/1.0 302 Found
Location: /offline_pages/
Connection: Keep-Alive
Content-Length: 0
</code>```

Excpected is the same as in the server logs, in this case a 503. Here are the logs for this request:

```<code>2017-11-14 13:54:07 [RTR/1] OUT <HOST> - [2017-11-14T12:54:07.455+0000] "GET /api/account HTTP/1.1" 503 [...]
</code>```

答: There has been a reconfiguration of Swisscoms load balancer that caused this weird behavior. It should be fixed now.</p>

Body:
We are using the Swisscom CloudFoundry solution with a Java and a Node.JS application. Since very recently, every HTTP status code starting with 5xx (tested with 500 and 503) is automatically mapped to the status code 302 Found with a redirect header to /offline_pages/ (tested with DELETE, POST and GET). This is done in-between our application and the front-end, requesting a resource with a status code 5xx.

We are actively using the 5xx status codes to report a server error to the front-end over our REST API (including maintenance down-time etc.). This does not work anymore, because of the automatic mapping. For instance, there is no automatic redirect to a maintenance page anymore, because the front-end does not see 3xx status as an error.

This issue occurs in both our applications (Java and Node.JS). The logs, however, display the correct 503 respectively 500 error. Furthermore, in our application's code base the redirect URL string /offline_pages/ is not even present; which leads to the conclusion, that this must be done outside of our application.

If a visible browser page returns a 500 the user is actually redirected to the page /offline_pages which displays a Swisscom error page. This error page (to which it redirected), then returns a 200 status code on its part, making it impossible to automatically detect the error in a Kiosk browser.

Is there any possibility to configure the Swisscom CloudFoundry to deactivate this behavior, which is suddenly occurring?

This is the request made by the front-end:

GET /api/account HTTP/1.1
Host: <HOST>
Connection: keep-alive
Accept: application/json, text/plain, */*
User-Agent: <USER-AGENT>
Referer: <REFERER>
Accept-Encoding: gzip, deflate, br
Accept-Language: <LANGUAGES>

And this is the response:

HTTP/1.0 302 Found
Location: /offline_pages/
Connection: Keep-Alive
Content-Length: 0

Excpected is the same as in the server logs, in this case a 503. Here are the logs for this request:

2017-11-14 13:54:07 [RTR/1] OUT <HOST> - [2017-11-14T12:54:07.455+0000] "GET /api/account HTTP/1.1" 503 [...]


问:
Syntax - what does square brackets around a variable declaration mean
Take the following line of code

```<code>const [component] = router.getMatchedComponents({ ...to })
</code>```

Could anyone advise what the square brackets around component means here? I have tried to google this but struggling to find an answer

答:
It's called Destructuring assignment, and it's used to unpack the values of an array and assign them to new variables.

So here in your code:

```<code>const [component] = router.getMatchedComponents({ ...to })
</code>```

You are assigning to the component variable the first element held in the array that will be returned by router.getMatchedComponents({...to}), where to is an array-like structure turned into object using the spread operation.

Body:
Take the following line of code

const [component] = router.getMatchedComponents({ ...to })

Could anyone advise what the square brackets around component means here? I have tried to google this but struggling to find an answer

Body:
It's called Destructuring assignment, and it's used to unpack the values of an array and assign them to new variables.

So here in your code:

const [component] = router.getMatchedComponents({ ...to })

You are assigning to the component variable the first element held in the array that will be returned by router.getMatchedComponents({...to}), where to is an array-like structure turned into object using the spread operation.

ContentLicense: CC BY-SA 4.0


问:
How do I create and load an egg-file in Python?
I am researching for a way to distribute a python module as a single egg-file. Supposing I have a python module called my_module and I want to write a python script that generates an egg-file for my module. So I found setuptools.

```<code>from setuptools import setup

setup(
    name="my_module",
    packages=[my_package],
    version="1.0",
)
</code>```

And I've had some disadvantages regarding these issues:

This script should be run as python setup.py install. In other words, I need to specify command line arguments. Instead I want to generate my egg-file automatically during my python code, that has its own control over the command line arguments.

The result files are outputed into the setup's file directory. I would like to control the output directory path in the script.

The script create build and dist folders that I don't actually need. Probably, I could solve it by removing the folders after calling setup.

How should I use setuptools for my purposes covering the issues above?

And also how can I load my module from given egg-file?

Supposing I have a following module:

```<code># my_module.py

class MyClass:
    def __init__(self):
        self._x = None

    def set_x(self, x):
        self._x = x

    def get_x(self):
        return self._x
</code>```

I wrote this script to create an egg-file:

```<code># create_egg.py

from setuptools import setup

setup(
    name="my_module",
    packages=['my_module'],
    version="1.0",
)
</code>```

I get such error, when I run creage_egg.py:

```<code>$ python3 create_egg.py
usage: create_egg.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: create_egg.py --help [cmd1 cmd2 ...]
   or: create_egg.py --help-commands
   or: create_egg.py cmd --help

error: no commands supplied
</code>```

答:
First thing I found out is that a package must be a directory. So it's necessary to keep such structure:

```<code>my_project/
    my_module/
        __init__.py
    output/
    create_egg.py
test_egg.py
</code>```

To skip the necessity of specifying the command line arguments there's a special option script_args. I found it here: http://peak.telecommunity.com/DevCenter/setuptools

My __init__.py:

```<code>class MyClass:
    def __init__(self):
        self._x = None

    def set_x(self, x):
        self._x = x

    def get_x(self):
        return self._x
</code>```

My create_egg.py:

```<code>import os
import shutil
from setuptools import setup

OUTPUT_DIR = 'output'

if __name__ == "__main__":
    setup(
        name="my_module",
        packages=['my_module'],
        version="1.0",
        script_args=['--quiet', 'bdist_egg'], # to create egg-file only
    )

    egg_name = os.listdir('dist')[0]

    os.rename(
        os.path.join('dist', egg_name),
        os.path.join(OUTPUT_DIR, egg_name)
    )

    shutil.rmtree('build')
    shutil.rmtree('dist')
    shutil.rmtree('my_module.egg-info')
</code>```

My test_egg.py:

```<code>import sys
sys.path.append('my_project/output/my_module-1.0-py3.5.egg')

import my_module

obj = my_module.MyClass()
obj.set_x(29)
print(obj.get_x())
</code>```

Creating egg-file:

```<code>~/Stuff/my_project $ python3 create_egg.py
zip_safe flag not set; analyzing archive contents...
</code>```

Testing the module:

```<code>~/Stuff $ python3 test_egg.py
29
</code>```

Body:
I am researching for a way to distribute a python module as a single egg-file. Supposing I have a python module called my_module and I want to write a python script that generates an egg-file for my module. So I found setuptools.

from setuptools import setup

setup(
    name="my_module",
    packages=[my_package],
    version="1.0",
)

And I've had some disadvantages regarding these issues:

This script should be run as python setup.py install. In other words, I need to specify command line arguments. Instead I want to generate my egg-file automatically during my python code, that has its own control over the command line arguments.

The result files are outputed into the setup's file directory. I would like to control the output directory path in the script.

The script create build and dist folders that I don't actually need. Probably, I could solve it by removing the folders after calling setup.

How should I use setuptools for my purposes covering the issues above?

And also how can I load my module from given egg-file?

Supposing I have a following module:

# my_module.py

class MyClass:
    def __init__(self):
        self._x = None

    def set_x(self, x):
        self._x = x

    def get_x(self):
        return self._x

I wrote this script to create an egg-file:

# create_egg.py

from setuptools import setup

setup(
    name="my_module",
    packages=['my_module'],
    version="1.0",
)

I get such error, when I run creage_egg.py:

$ python3 create_egg.py
usage: create_egg.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: create_egg.py --help [cmd1 cmd2 ...]
   or: create_egg.py --help-commands
   or: create_egg.py cmd --help

error: no commands supplied

Body:
First thing I found out is that a package must be a directory. So it's necessary to keep such structure:

my_project/
    my_module/
        __init__.py
    output/
    create_egg.py
test_egg.py

To skip the necessity of specifying the command line arguments there's a special option script_args. I found it here: http://peak.telecommunity.com/DevCenter/setuptools

My __init__.py:

class MyClass:
    def __init__(self):
        self._x = None

    def set_x(self, x):
        self._x = x

    def get_x(self):
        return self._x

My create_egg.py:

import os
import shutil
from setuptools import setup

OUTPUT_DIR = 'output'

if __name__ == "__main__":
    setup(
        name="my_module",
        packages=['my_module'],
        version="1.0",
        script_args=['--quiet', 'bdist_egg'], # to create egg-file only
    )

    egg_name = os.listdir('dist')[0]

    os.rename(
        os.path.join('dist', egg_name),
        os.path.join(OUTPUT_DIR, egg_name)
    )

    shutil.rmtree('build')
    shutil.rmtree('dist')
    shutil.rmtree('my_module.egg-info')

My test_egg.py:

import sys
sys.path.append('my_project/output/my_module-1.0-py3.5.egg')

import my_module

obj = my_module.MyClass()
obj.set_x(29)
print(obj.get_x())

Creating egg-file:

~/Stuff/my_project $ python3 create_egg.py
zip_safe flag not set; analyzing archive contents...

Testing the module:

~/Stuff $ python3 test_egg.py
29


问:
Strange SQL Performance: Parameter slower than Function call
I've had a project dumped in my lap, and I'm pretty far outside of my element.  There is a table with roughly 10,000,000 rows that is being queried.  There is one query in particular that is taking too long to run, and is timing out.  The query generated by Linq is

```<code>-- Region Parameters
DECLARE @p0 Int = 335
DECLARE @p1 DateTime = DATEADD(day,-7,GETDATE())
-- EndRegion
SELECT *
FROM [Events] AS [t0],
    [Devices] AS [t1],
    [EventTypes] AS [t2],
    [DeviceTypes] AS [t3]
WHERE ([t1].[DeviceID] = [t0].[DeviceID])
    AND ([t2].[EventTypeID] = [t0].[EventTypeID])
    AND ([t3].[DeviceTypeID] = [t1].[DeviceTypeID])
    AND ([t1].[RoomID] = @p0)
    AND ([t0].[EventTime] >= @p1)
</code>```

If I change the last line to be [t0].[EventTime] >= DATEADD(day,-7,GETDATE()) instead of using the variable @p1, the query goes from taking 45 seconds to run, to taking 3 seconds to run.

My two questions are 1) Why does this simple change increase performance so drastically and 2) is there a way to force Linq to not use the variable and inline the datetime object?

The Linq code is C# .NET 3.5 and the server is MSSQL 2005

Edit: I added the SELECT * for brevity, the actual query does not do that.

答:
If I change the last line to be
  [t0].[EventTime] >=
  DATEADD(day,-7,GETDATE()) instead of
  using the variable @p1, the query goes
  from taking 45 seconds to run, to
  taking 3 seconds to run.

I am rather suspicious of that statement. Are you sure you flushed buffers after the swap? Did you try swapping back and it still performs as badly when using the @p1 param?

General notes on performance troubleshooting.

Run both statements "set statistics io on" and "set statistics time on"

Hit Ctrl-M or use toolbar to show Actual execution plan

Always flush buffers and clear the plan cache between runs using "dbcc freeproccache" and "dbcc dropcleanbuffers"

Line up multiple versions and run them together to see the relative COST from the execution plans

If required when seeking advice, dump the text versions of the plans "set showplan_text on" and run the query in to-Text mode

The execution plan gives you a general direction of where it is going, but it is not always accurate. Balance it with the IO and CPU statistics.

ContentLicense: CC BY-SA 2.5

Body:
I've had a project dumped in my lap, and I'm pretty far outside of my element.  There is a table with roughly 10,000,000 rows that is being queried.  There is one query in particular that is taking too long to run, and is timing out.  The query generated by Linq is

-- Region Parameters
DECLARE @p0 Int = 335
DECLARE @p1 DateTime = DATEADD(day,-7,GETDATE())
-- EndRegion
SELECT *
FROM [Events] AS [t0],
    [Devices] AS [t1],
    [EventTypes] AS [t2],
    [DeviceTypes] AS [t3]
WHERE ([t1].[DeviceID] = [t0].[DeviceID])
    AND ([t2].[EventTypeID] = [t0].[EventTypeID])
    AND ([t3].[DeviceTypeID] = [t1].[DeviceTypeID])
    AND ([t1].[RoomID] = @p0)
    AND ([t0].[EventTime] >= @p1)

If I change the last line to be [t0].[EventTime] >= DATEADD(day,-7,GETDATE()) instead of using the variable @p1, the query goes from taking 45 seconds to run, to taking 3 seconds to run.

My two questions are 1) Why does this simple change increase performance so drastically and 2) is there a way to force Linq to not use the variable and inline the datetime object?

The Linq code is C# .NET 3.5 and the server is MSSQL 2005

Edit: I added the SELECT * for brevity, the actual query does not do that.


问:
get first record in group by result base on condition
this is my database structure
create database testGroupfirst;
go

```<code>use testGroupfirst;
go

create table testTbl (

id int primary key identity,name nvarchar(50) ,year int ,degree int , place  nvarchar(50)

)

insert into testTbl values ('jack',2015,50,'giza')
insert into testTbl values ('jack',2016,500,'cai')
insert into testTbl values ('jack',2017,660,'alex')
insert into testTbl values ('jack',2018,666,'giza')
insert into testTbl values ('jack',2011,50,'alex')
insert into testTbl values ('rami',2015,5054,'giza')
insert into testTbl values ('rami',2016,1500,'cai')
insert into testTbl values ('rami',2017,66220,'giza')
insert into testTbl values ('rami',2018,6656,'alex')
insert into testTbl values ('rami',2011,540,'cai')
insert into testTbl values ('jack',2010,50,'cai')
select * from testTbl
</code>```

this is the result till now

i created simple group by

select name , year ,degree ,place from testTbl group by name ,YEAR ,degree,place

as shown in pic 2 - I want to get the data for the first user and detailed description in their first year
- cursor could make that but I didn't want to use it, and I think that there are many ways could handle the situation in the better way like cross apply or cte .
I found a related question here
Get top 1 row of each group
but this doesn't work in my situation or I couldn't apply it so I made this new question here.

so i need to get the first row (top 1) from every group (user) and want to get the first record and must contains the first year that user works in it (order by desc)

答:
Use ROW_NUMBER:

```<code>SELECT name, year, degree, place
FROM
(
    SELECT name, year, degree, place,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY year) rn
    FROM testTbl
) t
WHERE rn = 1;
</code>```

If you wanted to consider the possibility of returning ties should, for example, a given name have two or more records with the same lowest year, there are a bunch of options.  One would be to add other conditions to the ORDER BY clause used in the call to row number, to break the tie.  Another option would be to use a rank function instead of row number, and return all ties.

Body:
this is my database structure
create database testGroupfirst;
go

use testGroupfirst;
go

create table testTbl (

id int primary key identity,name nvarchar(50) ,year int ,degree int , place  nvarchar(50)

)

insert into testTbl values ('jack',2015,50,'giza')
insert into testTbl values ('jack',2016,500,'cai')
insert into testTbl values ('jack',2017,660,'alex')
insert into testTbl values ('jack',2018,666,'giza')
insert into testTbl values ('jack',2011,50,'alex')
insert into testTbl values ('rami',2015,5054,'giza')
insert into testTbl values ('rami',2016,1500,'cai')
insert into testTbl values ('rami',2017,66220,'giza')
insert into testTbl values ('rami',2018,6656,'alex')
insert into testTbl values ('rami',2011,540,'cai')
insert into testTbl values ('jack',2010,50,'cai')
select * from testTbl

this is the result till now

i created simple group by

select name , year ,degree ,place from testTbl group by name ,YEAR ,degree,place

as shown in pic 2 - I want to get the data for the first user and detailed description in their first year
- cursor could make that but I didn't want to use it, and I think that there are many ways could handle the situation in the better way like cross apply or cte .
I found a related question here
Get top 1 row of each group
but this doesn't work in my situation or I couldn't apply it so I made this new question here.

so i need to get the first row (top 1) from every group (user) and want to get the first record and must contains the first year that user works in it (order by desc)

Body:
Use ROW_NUMBER:

SELECT name, year, degree, place
FROM
(
    SELECT name, year, degree, place,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY year) rn
    FROM testTbl
) t
WHERE rn = 1;

If you wanted to consider the possibility of returning ties should, for example, a given name have two or more records with the same lowest year, there are a bunch of options.  One would be to add other conditions to the ORDER BY clause used in the call to row number, to break the tie.  Another option would be to use a rank function instead of row number, and return all ties.


问:
mysterious rtm abort using haswell tsx
I'm experimenting with the tsx extensions in haswell, by adapting an existing medium-sized (1000's of lines) codebase to using GCC transactional memory extensions (which indirectly are using haswell tsx in this machine) instead of coarse grained locks. I am using GCC's transactional_memory extensions, not writing my own _xbegin / _xend directly.  I am using the ITM_DEFAULT_METHOD=htm

I'm having issues getting it to work fast enough because I get high rates of hardware transaction abort for mysterious reasons. As shown below, these aborts are not due to conflicts nor due to capacity limitations.

Here is the perf command I used to quantify the failure rate and underlying causes:

```<code>perf stat \
 -e cpu/event=0x54,umask=0x2,name=tx_mem_abort_capacity_write/ \
 -e cpu/event=0x54,umask=0x1,name=tx_mem_abort_conflict/ \
 -e cpu/event=0x5d,umask=0x1,name=tx_exec_misc1/ \
 -e cpu/event=0x5d,umask=0x2,name=tx_exec_misc2/ \
 -e cpu/event=0x5d,umask=0x4,name=tx_exec_misc3/ \
 -e cpu/event=0x5d,umask=0x8,name=tx_exec_misc4/ \
 -e cpu/event=0x5d,umask=0x10,name=tx_exec_misc5/ \
 -e cpu/event=0xc9,umask=0x1,name=rtm_retired_start/ \
 -e cpu/event=0xc9,umask=0x2,name=rtm_retired_commit/ \
 -e cpu/event=0xc9,umask=0x4,name=rtm_retired_aborted/pp \
 -e cpu/event=0xc9,umask=0x8,name=rtm_retired_aborted_misc1/ \
 -e cpu/event=0xc9,umask=0x10,name=rtm_retired_aborted_misc2/ \
 -e cpu/event=0xc9,umask=0x20,name=rtm_retired_aborted_misc3/ \
 -e cpu/event=0xc9,umask=0x40,name=rtm_retired_aborted_misc4/ \
 -e cpu/event=0xc9,umask=0x80,name=rtm_retired_aborted_misc5/ \
./myprogram -th 1 -reps 3000000
</code>```

So, the program runs some code with transactions in it 30 million times. Each request involves one transaction gcc __transaction_atomic block.  There is only one thread in this run.

This particular perf command captures most of the relevant tsx performance events described in the Intel software developers manual vol 3.

The output from perf stat is the following:

```<code>             0 tx_mem_abort_capacity_write                                  [26.66%]
             0 tx_mem_abort_conflict                                        [26.65%]
    29,937,894 tx_exec_misc1                                                [26.71%]
             0 tx_exec_misc2                                                [26.74%]
             0 tx_exec_misc3                                                [26.80%]
             0 tx_exec_misc4                                                [26.92%]
             0 tx_exec_misc5                                                [26.83%]
    29,906,632 rtm_retired_start                                            [26.79%]
             0 rtm_retired_commit                                           [26.70%]
    29,985,423 rtm_retired_aborted                                          [26.66%]
             0 rtm_retired_aborted_misc1                                    [26.75%]
             0 rtm_retired_aborted_misc2                                    [26.73%]
    29,927,923 rtm_retired_aborted_misc3                                    [26.71%]
             0 rtm_retired_aborted_misc4                                    [26.69%]
           176 rtm_retired_aborted_misc5                                    [26.67%]

  10.583607595 seconds time elapsed
</code>```

As you can see from the output:

The rtm_retired_start count is 30 million (matches input to program)

The rtm_retired_abort count is about the same (no commits at all)

The abort_conflict and abort_capacity counts are 0, so these are not the reasons. Also, recall it is only one thread running, conflicts should be rare.

The only actual leads here are the high values of tx_exec_misc1 and rtm_retired_aborted_misc3, which are somewhat similar in description.

The Intel manual (vol 3) defines rtm_retired_aborted_misc3 counters:

code: C9H 20H

mnemonic: RTM_RETIRED.ABORTED_MISC3

description: Number of times an RTM execution aborted due to HLE unfriendly instructions.

The definition for tx_exec_misc1 has some similar words:

code: 5DH 01H

mnemonic: TX_EXEC.MISC1

description: Counts the number of times a class of instructions that may cause a transactional abort was executed. Since this is the count of execution, it may not always cause a transactional abort.

I checked the assembly location for the aborts using perf record/ perf report using high precision (PEBS) support for rtm_retired_aborted. The location has a mov instruction from register to register.  No weird instruction names seen nearby.

Update:

Here are two things I've tried since then:

1)  the tx_exec_misc1 and rtm_retired_aborted_misc3 signature we we see here can be obtained, for example, by a dummy block of the form

```<code>for (int i = 0; i < 10000000; i++){
  __transaction_atomic{
    _xabort(1);
  }
}
</code>```

or one of the form

```<code>for (int i = 0; i < 10000000; i++){
  __transaction_atomic{
    printf("hello");
    fflush(stdout);
  }
}
</code>```

In both cases, the perf counters look similar to what I see. However, in both cases the perf report for -e cpu/tx-abort/  points to the intuitively correct assembly lines: an xabort instruction for the first example and a syscall one for the second one.  In the real codebase, the perf report points to a stack push right at the start of a function:

```<code>           :    00000000004167e0 <myns::myfun()>:
    100.00 :      4167e0:       push   %rbp
      0.00 :      4167e1:       mov    %rsp,%rbp
      0.00 :      4167e4:       push   %r15
</code>```

I have also run the same command under the intel software development emulator. It turns out that the problem goes away in that case: I get no aborts as far as the application is concerned.

答:
Though it's been the case for a while, I found this unanswered question while searching, so here's the answer: This is a hardware bug in Haswell and early Broadwell chips.

The particular hardware erratum assigned by Intel is HSW136, and is not fixable using microcode updates. Indeed, I think it was in stepping 4 that the feature was no longer reported as available by the cpuid instruction, even when there was (faulty) silicon on the chip to implement it.

Title: mysterious rtm abort using haswell tsx

Body:
I'm experimenting with the tsx extensions in haswell, by adapting an existing medium-sized (1000's of lines) codebase to using GCC transactional memory extensions (which indirectly are using haswell tsx in this machine) instead of coarse grained locks. I am using GCC's transactional_memory extensions, not writing my own _xbegin / _xend directly.  I am using the ITM_DEFAULT_METHOD=htm

I'm having issues getting it to work fast enough because I get high rates of hardware transaction abort for mysterious reasons. As shown below, these aborts are not due to conflicts nor due to capacity limitations.

Here is the perf command I used to quantify the failure rate and underlying causes:

perf stat \
 -e cpu/event=0x54,umask=0x2,name=tx_mem_abort_capacity_write/ \
 -e cpu/event=0x54,umask=0x1,name=tx_mem_abort_conflict/ \
 -e cpu/event=0x5d,umask=0x1,name=tx_exec_misc1/ \
 -e cpu/event=0x5d,umask=0x2,name=tx_exec_misc2/ \
 -e cpu/event=0x5d,umask=0x4,name=tx_exec_misc3/ \
 -e cpu/event=0x5d,umask=0x8,name=tx_exec_misc4/ \
 -e cpu/event=0x5d,umask=0x10,name=tx_exec_misc5/ \
 -e cpu/event=0xc9,umask=0x1,name=rtm_retired_start/ \
 -e cpu/event=0xc9,umask=0x2,name=rtm_retired_commit/ \
 -e cpu/event=0xc9,umask=0x4,name=rtm_retired_aborted/pp \
 -e cpu/event=0xc9,umask=0x8,name=rtm_retired_aborted_misc1/ \
 -e cpu/event=0xc9,umask=0x10,name=rtm_retired_aborted_misc2/ \
 -e cpu/event=0xc9,umask=0x20,name=rtm_retired_aborted_misc3/ \
 -e cpu/event=0xc9,umask=0x40,name=rtm_retired_aborted_misc4/ \
 -e cpu/event=0xc9,umask=0x80,name=rtm_retired_aborted_misc5/ \
./myprogram -th 1 -reps 3000000

So, the program runs some code with transactions in it 30 million times. Each request involves one transaction gcc __transaction_atomic block.  There is only one thread in this run.

This particular perf command captures most of the relevant tsx performance events described in the Intel software developers manual vol 3.

The output from perf stat is the following:

             0 tx_mem_abort_capacity_write                                  [26.66%]
             0 tx_mem_abort_conflict                                        [26.65%]
    29,937,894 tx_exec_misc1                                                [26.71%]
             0 tx_exec_misc2                                                [26.74%]
             0 tx_exec_misc3                                                [26.80%]
             0 tx_exec_misc4                                                [26.92%]
             0 tx_exec_misc5                                                [26.83%]
    29,906,632 rtm_retired_start                                            [26.79%]
             0 rtm_retired_commit                                           [26.70%]
    29,985,423 rtm_retired_aborted                                          [26.66%]
             0 rtm_retired_aborted_misc1                                    [26.75%]
             0 rtm_retired_aborted_misc2                                    [26.73%]
    29,927,923 rtm_retired_aborted_misc3                                    [26.71%]
             0 rtm_retired_aborted_misc4                                    [26.69%]
           176 rtm_retired_aborted_misc5                                    [26.67%]

  10.583607595 seconds time elapsed

As you can see from the output:

The rtm_retired_start count is 30 million (matches input to program)

The rtm_retired_abort count is about the same (no commits at all)

The abort_conflict and abort_capacity counts are 0, so these are not the reasons. Also, recall it is only one thread running, conflicts should be rare.

The only actual leads here are the high values of tx_exec_misc1 and rtm_retired_aborted_misc3, which are somewhat similar in description.

The Intel manual (vol 3) defines rtm_retired_aborted_misc3 counters:

code: C9H 20H

mnemonic: RTM_RETIRED.ABORTED_MISC3

description: Number of times an RTM execution aborted due to HLE unfriendly instructions.

The definition for tx_exec_misc1 has some similar words:

code: 5DH 01H

mnemonic: TX_EXEC.MISC1

description: Counts the number of times a class of instructions that may cause a transactional abort was executed. Since this is the count of execution, it may not always cause a transactional abort.

I checked the assembly location for the aborts using perf record/ perf report using high precision (PEBS) support for rtm_retired_aborted. The location has a mov instruction from register to register.  No weird instruction names seen nearby.

Update:

Here are two things I've tried since then:

1)  the tx_exec_misc1 and rtm_retired_aborted_misc3 signature we we see here can be obtained, for example, by a dummy block of the form

for (int i = 0; i < 10000000; i++){
  __transaction_atomic{
    _xabort(1);
  }
}

or one of the form

for (int i = 0; i < 10000000; i++){
  __transaction_atomic{
    printf("hello");
    fflush(stdout);
  }
}

In both cases, the perf counters look similar to what I see. However, in both cases the perf report for -e cpu/tx-abort/  points to the intuitively correct assembly lines: an xabort instruction for the first example and a syscall one for the second one.  In the real codebase, the perf report points to a stack push right at the start of a function:

           :    00000000004167e0 <myns::myfun()>:
    100.00 :      4167e0:       push   %rbp
      0.00 :      4167e1:       mov    %rsp,%rbp
      0.00 :      4167e4:       push   %r15

I have also run the same command under the intel software development emulator. It turns out that the problem goes away in that case: I get no aborts as far as the application is concerned.


答:
One of the possible solutions is:

```<code>select name, year, degree, place
from
(select
    name,
    year,
    degree,
    place,
    row_number() over (partition by name order by year) rn
from testTbl
--group by name ,YEAR ,degree,place -- not really needed
) r
where rn = 1;
</code>```

UPDATE: Another solution (since both I and Tim posted the same) would be to use CROSS APPLY:

```<code>select t.*
from testTbl t
    cross apply (select top 1 id from testTbl where name = t.name order by year) r
where t.id = r.id
</code>```

Title: get first record in group by result base on condition

Body:
One of the possible solutions is:

select name, year, degree, place
from
(select
    name,
    year,
    degree,
    place,
    row_number() over (partition by name order by year) rn
from testTbl
--group by name ,YEAR ,degree,place -- not really needed
) r
where rn = 1;

UPDATE: Another solution (since both I and Tim posted the same) would be to use CROSS APPLY:

select t.*
from testTbl t
    cross apply (select top 1 id from testTbl where name = t.name order by year) r
where t.id = r.id


问:
I want to redirect the current page after submitting the form....it should return the page from where request is send using php
I want to redirect the current page after submitting the form as same form is in Multiple pages (about 25 pages) so it should return the page from where form is submit using php

Here is my HTML code:

```<code><form method="post" action="submitEnquery.php">
  <input name="name" placeholder="Full Name" type="text" >
  <input name="email" placeholder="Email Address" type="email">
  <textarea name="message" placeholder="Type your message here....">/textarea>
  <button name="submit" type="submit">send</button>
</form>
</code>```

Here is my php code:

```<code><?php
  if (isset($_POST['submit']))
  {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['msg'];
    $to = 'qwert01@exmple.com' . ', ';
    $to.= 'qwert003@exmple.com';
    $subject = "Enquery Form";
    $message = "
          <html>
          <head>
              <title>HTML email</title>
              <style>
              body{ background: #E6E4DE; }
              img{ width:200px; height:55px; display:block; text-align:center;
              margin:0 auto; }
              h3{ text-align:center;margin:25px auto; }
              table { font-family: arial, sans-serif; border: 1px solid #ddd;
              border-collapse: collapse; width: 70%; margin: 0 auto; }
              td, th { border: 1px solid #ddd; text-align: left; padding: 10px
              15px; vertical-align: top; }
              </style>
          </head>
          <body>
              <h3>Senders Detail down below</h3>
              <table rules='all' cellpadding='10'>
                  <tr style='background: #eee;'>
                      <th style='width:25%'>Name</th>
                      <th style='width:75%'>" . $name . "</th>
                  </tr>
                  <tr>
                      <td style='width:25%'>Email</td>
                      <td style='width:75%'>" . $email . "</td>
                  </tr>
                  <tr>
                      <td style='width:25%'>Message</td>
                      <td style='width:75%'>" . $msg . "</td>
                  </tr>
              </table>
          </body>
          </html>
      ";
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers.= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers.= 'From: ' . $email . "\r\n";
    $headers.= 'Cc: qwert65494@exmple.com' . "\r\n";
    $headers.= 'Bcc: iqwert@exmple.com' . "\r\n";
    mail($to, $subject, $message, $headers);
    header('Refresh:0;');
  }

  echo '<h3>Sent Sccessfully...!</h3>';
?>
</code>```

The code is working properly.
It sends mail no problem but the issue is how can redirect to the page from where en-query(contact) form is submitted.

答:
```<code>header("Location: " . $_SERVER['HTTP_REFERER']);
</code>```

OR

```<code>header("location:javascript://history.go(-1)");
</code>```

Body:
I want to redirect the current page after submitting the form as same form is in Multiple pages (about 25 pages) so it should return the page from where form is submit using php

Here is my HTML code:

<form method="post" action="submitEnquery.php">
  <input name="name" placeholder="Full Name" type="text" >
  <input name="email" placeholder="Email Address" type="email">
  <textarea name="message" placeholder="Type your message here....">/textarea>
  <button name="submit" type="submit">send</button>
</form>

Here is my php code:

<?php
  if (isset($_POST['submit']))
  {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['msg'];
    $to = 'qwert01@exmple.com' . ', ';
    $to.= 'qwert003@exmple.com';
    $subject = "Enquery Form";
    $message = "

              <title>HTML email</title>

Senders Detail down below

                      Name
                      " . $name . "

                      Email
                      " . $email . "

                      Message
                      " . $msg . "

      ";
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers.= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers.= 'From: ' . $email . "\r\n";
    $headers.= 'Cc: qwert65494@exmple.com' . "\r\n";
    $headers.= 'Bcc: iqwert@exmple.com' . "\r\n";
    mail($to, $subject, $message, $headers);
    header('Refresh:0;');
  }

  echo '
Sent Sccessfully...!
';
?>

The code is working properly.
It sends mail no problem but the issue is how can redirect to the page from where en-query(contact) form is submitted.

Body:
header("Location: " . $_SERVER['HTTP_REFERER']);

OR

header("location:javascript://history.go(-1)");


问:
How to incorporate median value into regression as an independent variable?
I want to regress y on x1 and median value of x2.
I use below code with package plm:

```<code>Result <- plm(y ~ x1 + median(x2,na.rm=T),data = Panel[which(!is.na(Panel$Firms)),],
              model = "random",effect = "time",index = c("Firms", "Time"))
</code>```

But it does not work. It returns

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :

  variable lengths differ (found for 'median(MB)')

How can I incorporate median value into regression as an independent variable?

答: The error is given because they haven't the same length, so I think there's no way of doing it without use some transformation with median.

Body:
I want to regress y on x1 and median value of x2.
I use below code with package plm:

Result <- plm(y ~ x1 + median(x2,na.rm=T),data = Panel[which(!is.na(Panel$Firms)),],
              model = "random",effect = "time",index = c("Firms", "Time"))

But it does not work. It returns

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :

  variable lengths differ (found for 'median(MB)')

How can I incorporate median value into regression as an independent variable?


问:
Saving data to .mat file in MATLAB
I'm new to MATLAB, and I can't manage to make my function work in order to save my data into a .mat file.

The input:

A structure, with 5 fields:

data: 3D matrix of 19x1000x143

labels: 1x143 matrix with 1 or -1 in it

subject_number: an integer

sampling_rate: an integer, 500 Hz

channel_names: 1x19 matrix with text in it

name: a string for the name of the file

clean: a matrix 1x143 with 1 or 0 in it.

The idea is to save only the clean data, marked as 1 in the clean matrix.

```<code> If clean(i) is equal to 1:
      save data(:,:,i) and labels(:,i)
</code>```

This is the code I've tried to implement in the saving.m file:

```<code>function saving(EEG_struct, clean, name)

subject_number = EEG_struct.subject_number;
fs = EEG_struct.sampling_rate;
chan_names = EEG_struct.channel_names;
nb_epoch = size(EEG_struct.data, 3);

for j=1:nb_epoch
    if clean(j) == 1
        % Keep the epoch and label
        data = cat(3, data, EEG_struct.data(:,:,j));
        labels = cat(2, labels, EEG_struct.labels(:,j));
    end
end

save(name, data, labels, subject_number, fs, chan_names)
</code>```

As you can see, I would like to save the data as a structure with the same shape as the EEG_struct input.
Moreover, I would like to use a parfor instead of a for, but it raised me an error I didn't quite get:

```<code>An UndefinedFunction error was thrown on the workers for 'data'.  This might be because the file containing 'data' is not accessible on the workers.  Use addAttachedFiles(pool, files) to specify the required files to be attached.  See the documentation for 'parallel.Pool/addAttachedFiles' for more details. Caused by: Undefined function or variable 'data'.
</code>```

Thanks for the help !

答:
To get a structure the same as EEG_struct but with only the data/labels corresponding with the clean variable, you can simply make a copy of the existing structure and remove the rows where clean=0

```<code>function saving(EEG_struct, clean, name)

newstruct = EEG_struct;
newstruct.data(:,:,logical(~clean)) = '';
newstruct.labels(logical(~clean)) = '';

save(name,'newstruct');
</code>```

Title: Saving data to .mat file in MATLAB

Body:
I'm new to MATLAB, and I can't manage to make my function work in order to save my data into a .mat file.

The input:

A structure, with 5 fields:

data: 3D matrix of 19x1000x143

labels: 1x143 matrix with 1 or -1 in it

subject_number: an integer

sampling_rate: an integer, 500 Hz

channel_names: 1x19 matrix with text in it

name: a string for the name of the file

clean: a matrix 1x143 with 1 or 0 in it.

The idea is to save only the clean data, marked as 1 in the clean matrix.

 If clean(i) is equal to 1:
      save data(:,:,i) and labels(:,i)

This is the code I've tried to implement in the saving.m file:

function saving(EEG_struct, clean, name)

subject_number = EEG_struct.subject_number;
fs = EEG_struct.sampling_rate;
chan_names = EEG_struct.channel_names;
nb_epoch = size(EEG_struct.data, 3);

for j=1:nb_epoch
    if clean(j) == 1
        % Keep the epoch and label
        data = cat(3, data, EEG_struct.data(:,:,j));
        labels = cat(2, labels, EEG_struct.labels(:,j));
    end
end

save(name, data, labels, subject_number, fs, chan_names)

As you can see, I would like to save the data as a structure with the same shape as the EEG_struct input.
Moreover, I would like to use a parfor instead of a for, but it raised me an error I didn't quite get:

An UndefinedFunction error was thrown on the workers for 'data'.  This might be because the file containing 'data' is not accessible on the workers.  Use addAttachedFiles(pool, files) to specify the required files to be attached.  See the documentation for 'parallel.Pool/addAttachedFiles' for more details. Caused by: Undefined function or variable 'data'.

Thanks for the help !

Body:
To get a structure the same as EEG_struct but with only the data/labels corresponding with the clean variable, you can simply make a copy of the existing structure and remove the rows where clean=0

function saving(EEG_struct, clean, name)

newstruct = EEG_struct;
newstruct.data(:,:,logical(~clean)) = '';
newstruct.labels(logical(~clean)) = '';

save(name,'newstruct');


问:
How to access results from matplotlib's histogram-function
I have a data set which was injected to Matplotlib's plt.hist.
I saved the results of the operation as follows:

```<code>data=[1,2,3,4,5,6,7,8,9]
n,bin,patches= plt.hist(data,bins=3)
</code>```

But how can I access the list of lists saved as patches?
Could someone please explain to me the concept of silent_list's/patches.Rectangles and how to access the stored data within? I would like to loop over patches in order to get the sub-lists for each bin. Similar to:

```<code>0: [1,4,6,8]
1: [2,3]
2: [5,7,9]
</code>```

Thank you

答:
The patches returned by plt.hist is a list of rectangles. A rectangle has four corners and is a matplotlib.patches.Patch with all the corresponding attributes.

You may loop over the patches to manipulate the properties of the bars, e.g. like

```<code>import matplotlib.pyplot as plt

data=[1,2,2,3,4,5,7,7.5,9,8,9]
n,bins,patches= plt.hist(data,bins=3)

for bar in patches:
    print(bar.get_height())
    bar.set_facecolor("pink")
    bar.set_edgecolor("red")

plt.show()
</code>```

However, the patch naturally has no information about where it comes from. So in order to find the histogram data, it is of no use.

In order to find out which bin contains which points from the input data, you may loop over the bins and select those points being in the respective bin.

```<code>import matplotlib.pyplot as plt
import numpy as np

data=[1,2,2,3,4,5,7,7.5,9,8,9]
n,bins,patches= plt.hist(data,bins=3)

binlist = np.c_[bins[:-1],bins[1:]]
d = np.array(data)
for i in range(len(binlist)):
    if i == len(binlist)-1:
        l = d[(d >= binlist[i,0]) & (d <= binlist[i,1])]
    else:
        l = d[(d >= binlist[i,0]) & (d < binlist[i,1])]
    print(l)

plt.show()
</code>```

would print

```<code>[ 1.  2.  2.  3.]
[ 4.  5.]
[ 7.   7.5  9.   8.   9. ]
</code>```

Body:
I have a data set which was injected to Matplotlib's plt.hist.
I saved the results of the operation as follows:

data=[1,2,3,4,5,6,7,8,9]
n,bin,patches= plt.hist(data,bins=3)

But how can I access the list of lists saved as patches?
Could someone please explain to me the concept of silent_list's/patches.Rectangles and how to access the stored data within? I would like to loop over patches in order to get the sub-lists for each bin. Similar to:

0: [1,4,6,8]
1: [2,3]
2: [5,7,9]

Thank you

Body:
The patches returned by plt.hist is a list of rectangles. A rectangle has four corners and is a matplotlib.patches.Patch with all the corresponding attributes.

You may loop over the patches to manipulate the properties of the bars, e.g. like

import matplotlib.pyplot as plt

data=[1,2,2,3,4,5,7,7.5,9,8,9]
n,bins,patches= plt.hist(data,bins=3)

for bar in patches:
    print(bar.get_height())
    bar.set_facecolor("pink")
    bar.set_edgecolor("red")

plt.show()

However, the patch naturally has no information about where it comes from. So in order to find the histogram data, it is of no use.

In order to find out which bin contains which points from the input data, you may loop over the bins and select those points being in the respective bin.

import matplotlib.pyplot as plt
import numpy as np

data=[1,2,2,3,4,5,7,7.5,9,8,9]
n,bins,patches= plt.hist(data,bins=3)

binlist = np.c_[bins[:-1],bins[1:]]
d = np.array(data)
for i in range(len(binlist)):
    if i == len(binlist)-1:
        l = d[(d >= binlist[i,0]) & (d <= binlist[i,1])]
    else:
        l = d[(d >= binlist[i,0]) & (d < binlist[i,1])]
    print(l)

plt.show()

would print

[ 1.  2.  2.  3.]
[ 4.  5.]
[ 7.   7.5  9.   8.   9. ]


问:
How to Bind different react components with the same react-router route depending on redux state?
Using React, Redux and React-router, I want to to bind different components to the same route depending on the redux state. for example:

Assuming ComponentA and ComponentB are React components

Assuming I have this redux state

```<code>{
  flag: true;
}
</code>```

I want to have this React Router configuration /routes.js

```<code><Route path="/" component={App}>
  <Route path="/test" component={ComponentA} />
</Route>
</code>```

but if I have the flag in my Redux state to be false I want to have

```<code>...
  <Route path="/test" component={ComponentB} />
...
</code>```

I am aware that I can create a wrapper component to ComponentA and ComponentB that checks the redux state and then render the corresponding component, but I was searching for an answer that doesn't require creating new components

答:
You can use a terinary operator in the component field of route.

```<code><Route path="/test" component={flag ? ComponentA : ComponentB} />
</code>```

Edit: This is how you would map the flag from your state to a prop.

```<code>import { connect } from 'react-redux';

// ... Component Definition

const mapStateToProps = (state, ownProps) => {
  return {
    flag: state.flag
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    // Whatever you want to dispatch
  }
}

const ConnectedComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(YourComponent)
</code>```

Edit 2: Connecting React Router to Redux using a Provider

```<code>const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>
)
</code>```

Body:
Using React, Redux and React-router, I want to to bind different components to the same route depending on the redux state. for example:

Assuming ComponentA and ComponentB are React components

Assuming I have this redux state

{
  flag: true;
}

I want to have this React Router configuration /routes.js

<Route path="/" component={App}>
  <Route path="/test" component={ComponentA} />
</Route>

but if I have the flag in my Redux state to be false I want to have

...
  <Route path="/test" component={ComponentB} />
...

I am aware that I can create a wrapper component to ComponentA and ComponentB that checks the redux state and then render the corresponding component, but I was searching for an answer that doesn't require creating new components

Body:
You can use a terinary operator in the component field of route.

<Route path="/test" component={flag ? ComponentA : ComponentB} />

Edit: This is how you would map the flag from your state to a prop.

import { connect } from 'react-redux';

// ... Component Definition

const mapStateToProps = (state, ownProps) => {
  return {
    flag: state.flag
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    // Whatever you want to dispatch
  }
}

const ConnectedComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(YourComponent)

Edit 2: Connecting React Router to Redux using a Provider

const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>
)


问:
Selenium throws NoSuchElementException
When I run my appium code for mobile automation, I get the following exception

```<code>org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters.
(WARNING: The server did not provide any stacktrace information)
</code>```

Appium server version: 1.6.3
Android version: 6.0
Can any one please help me to solve the issue

答: This is known WDA issue. Update your Appium to 1.6.6-beta and try again</p>

Title: Selenium throws NoSuchElementException

Body:
When I run my appium code for mobile automation, I get the following exception

org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters.
(WARNING: The server did not provide any stacktrace information)

Appium server version: 1.6.3
Android version: 6.0
Can any one please help me to solve the issue


答:
Before anything, if the decimals of ra and dec are different from those of your values in csv file, use round() to fix the decimals first, then do the following action

using Pandas:

```<code>import pandas

ra = 59.6517601
dec = 61.5475502
pattern = [ra,dec]

table = pandas.read_csv('file.csv')
for ind,row in table.iterrows():
    if list(row.values)==pattern:
        print('pattern was detected at index {}'.format(ind))
</code>```

and without pandas:

```<code>cnt = 0

ra = 59.6517601
dec = 61.5475502
pattern = [ra,dec]

with open('file.csv','r').read() as file:
    for row in file.split('\n'):
        x = [float(row.split(',')[0]),float(row.split(',')[1])]
        if x==pattern:
            print('pattern was detected at index {}'.format(cnt))
            break
    cnt += 1
</code>```

just remember that if you come into ValueError in the second solution, it is likely because of the split behavior for text in files, where an empty element is created at last index of the list. to avoid the error, do:

file = file[:-1] after the with syntax

Title: How to compare two columns in csv with two values declared before in python?

Body:
the catalog there this values:

0.6881  -55.0099
0.6883  -80.3465
0.7827  -59.5199
0.8206  -54.5565
0.8418  -49.7932
0.9503  -43.6182
1.0236  -52.9165
1.0488  -50.6465
1.1068  -50.6182
1.134   -32.2499
1.1325  -45.4482
1.2633  -27.7416
1.2725  -50.8282
1.3115  -40.6049
1.3461  -30.5649
...
...

and my values declared before is ra = 59.6517601 dec = 61.5475502. How compare to show if there values ra, dec in my catalog?

Body:
Before anything, if the decimals of ra and dec are different from those of your values in csv file, use round() to fix the decimals first, then do the following action

using Pandas:

import pandas

ra = 59.6517601
dec = 61.5475502
pattern = [ra,dec]

table = pandas.read_csv('file.csv')
for ind,row in table.iterrows():
    if list(row.values)==pattern:
        print('pattern was detected at index {}'.format(ind))

and without pandas:

cnt = 0

ra = 59.6517601
dec = 61.5475502
pattern = [ra,dec]

with open('file.csv','r').read() as file:
    for row in file.split('\n'):
        x = [float(row.split(',')[0]),float(row.split(',')[1])]
        if x==pattern:
            print('pattern was detected at index {}'.format(cnt))
            break
    cnt += 1

just remember that if you come into ValueError in the second solution, it is likely because of the split behavior for text in files, where an empty element is created at last index of the list. to avoid the error, do:

file = file[:-1] after the with syntax