问:
Service error: Spreadsheets using isblank()
I have a big problem since 2 days, my functiun doesn't work anymore :/
"Service error: Spreadsheets" at "if (cell.isBlank())"

```<code>    function miseEnForme(){
  var classeur = SpreadsheetApp.getActive();
  var feuilleAdm = classeur.getSheetByName("SuiviAdministratif");

  var lastRow;
  for (var row = 3; row < 1000; row++) {
    var cell=feuilleAdm.getRange(row,3);
    if (cell.isBlank()) {
      lastRow =row;
      break;
    }
  }

  for (var i =3; i<lastRow;i++){
   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="RS" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RP" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RD")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("red");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="C")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("#00ff00");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="O")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("white");
  }
}
</code>```

Is it my fault or Google have change something?
How to solve the problem?

Thanks

答:
As Cooper say, your code is not the problem here.
Otherwise, a little workaround will help you :

```<code>function miseEnForme(){
  var classeur = SpreadsheetApp.getActive();
  var feuilleAdm = classeur.getSheetByName("SuiviAdministratif");

  // getLastRow() return the value of the last row used in the sheet
  var lastRow = feuilleAdm.getLastRow();

  for (var i =3; i<lastRow;i++){
   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="RS" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RP" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RD")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("red");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="C")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("#00ff00");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="O")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("white");
  }
}
</code>```

More about the getLastRow method : https://developers.google.com/apps-script/reference/spreadsheet/sheet#getLastRow()

Body:
I have a big problem since 2 days, my functiun doesn't work anymore :/
"Service error: Spreadsheets" at "if (cell.isBlank())"

    function miseEnForme(){
  var classeur = SpreadsheetApp.getActive();
  var feuilleAdm = classeur.getSheetByName("SuiviAdministratif");

  var lastRow;
  for (var row = 3; row < 1000; row++) {
    var cell=feuilleAdm.getRange(row,3);
    if (cell.isBlank()) {
      lastRow =row;
      break;
    }
  }

  for (var i =3; i<lastRow;i++){
   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="RS" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RP" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RD")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("red");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="C")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("#00ff00");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="O")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("white");
  }
}

Is it my fault or Google have change something?
How to solve the problem?

Thanks

Body:
As Cooper say, your code is not the problem here.
Otherwise, a little workaround will help you :

function miseEnForme(){
  var classeur = SpreadsheetApp.getActive();
  var feuilleAdm = classeur.getSheetByName("SuiviAdministratif");

  // getLastRow() return the value of the last row used in the sheet
  var lastRow = feuilleAdm.getLastRow();

  for (var i =3; i<lastRow;i++){
   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="RS" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RP" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RD")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("red");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="C")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("#00ff00");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="O")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("white");
  }
}

More about the getLastRow method : https://developers.google.com/apps-script/reference/spreadsheet/sheet#getLastRow()


来源: stackexchange

问:
how to use react-springy-parallax
How do I use the scrollTo in react-springy-parallax?

I'm trying to use react-springy-parallax in a simple portfolio page, you can click to springy parallax scroll to the next page but I want to be able to use nav links as well, here is how the app is laid out:

App.js

```<code>class App extends React.Component {
  constructor() {
    super()
    this.ref = 'parallax'
  }
  render() {
    return (
      <div>
        <Parallax ref={this.ref} pages={4}>

          <Parallax.Layer
            offset={0}
            speed={0.5}
            onClick={() => this.refs.parallax.scrollTo(1)}
          >
            <Nav />
            <Header />
          </Parallax.Layer>
          ...
</code>```

So the onClick here just scrolls to the next page, I want to be able to say in my Nav component click the About link and it will scroll +1 so scrollTo(1)

Here is the nav component:

Nav.js

```<code>class Nav extends React.Component {

  render() {
    return (
      <div className="nav">
        <ul className="links">
          <li>
            <a href="#about">About</a>
          </li>
          ...
</code>```

I did try importing the scrollTo named export from react-springy-parallax into the nav component but got an error in the Chrome dev console saying it's not a function

I'm now trying to use a click handler:

```<code>class Nav extends React.Component {

  render() {
    function handleClick(e) {
      e.preventDefault()
      console.log(e)
    }
    return (
      <div className="nav">
        <ul className="links">
          <li>
            <a
              href="#"
              onClick={handleClick}
            >
              About
            </a>
          </li>
          ...
</code>```

But I don't know how to call back to App.js to call the scrollTo

Anyone have any ideas?

答:
logged an issue with the repo owner and he was kind enough to give a few pointers:

Use contextTypes to access the scrollTo method from parallax

In the Nav component use:

```<code>Nav.contextTypes = { parallax: React.PropTypes.object }
</code>```

This will allow you to use the scrollTo method

Something like:

```<code>class Nav extends React.Component {
  render() {
    return (
      <div className="nav">
        <ul className="links">
          <li>
            <a
              href=""
              onClick={this.context.parallax.scrollTo(0)}
            >
              Home
            </a>
          </li>
          <li>
            <a
              href=""
              onClick={this.context.parallax.scrollTo(1)}
            >
              About
            </a>
          </li>
</code>```

You can also pass the function as a prop, like so:

```<code>class App extends React.Component {
  constructor(props) {
    super(props)
    this.handleScroll = value => this.parallax && this.parallax.scrollTo(value)
  }
  render() {
    return (
      <div>
        <Parallax
          ref={ref => (this.parallax = ref)}
          pages={4}
        >

        <Parallax.Layer
          offset={0}
          speed={0.5}
          onClick={() => this.handleScroll(1)}
        >
          <Nav handleScroll={this.handleScroll} />
</code>```

Then from the Nav component use props onClick={() => this.props.handleScroll(PAGE)} with PAGE being the page number you want to scroll to.

ContentLicense: CC BY-SA 3.0

Title: how to use react-springy-parallax

Body:
How do I use the scrollTo in react-springy-parallax?

I'm trying to use react-springy-parallax in a simple portfolio page, you can click to springy parallax scroll to the next page but I want to be able to use nav links as well, here is how the app is laid out:

App.js

class App extends React.Component {
  constructor() {
    super()
    this.ref = 'parallax'
  }
  render() {
    return (

        <Parallax ref={this.ref} pages={4}>

          <Parallax.Layer
            offset={0}
            speed={0.5}
            onClick={() => this.refs.parallax.scrollTo(1)}
          >

          </Parallax.Layer>
          ...

So the onClick here just scrolls to the next page, I want to be able to say in my Nav component click the About link and it will scroll +1 so scrollTo(1)

Here is the nav component:

Nav.js

class Nav extends React.Component {

  render() {
    return (

            About

          ...

I did try importing the scrollTo named export from react-springy-parallax into the nav component but got an error in the Chrome dev console saying it's not a function

I'm now trying to use a click handler:

class Nav extends React.Component {

  render() {
    function handleClick(e) {
      e.preventDefault()
      console.log(e)
    }
    return (

              About

          ...

But I don't know how to call back to App.js to call the scrollTo

Anyone have any ideas?

Body:
logged an issue with the repo owner and he was kind enough to give a few pointers:

Use contextTypes to access the scrollTo method from parallax

In the Nav component use:

Nav.contextTypes = { parallax: React.PropTypes.object }

This will allow you to use the scrollTo method

Something like:

class Nav extends React.Component {
  render() {
    return (
      <div className="nav">
        <ul className="links">
          <li>
            <a
              href=""
              onClick={this.context.parallax.scrollTo(0)}
            >
              Home
            </a>
          </li>
          <li>
            <a
              href=""
              onClick={this.context.parallax.scrollTo(1)}
            >
              About
            </a>
          </li>

You can also pass the function as a prop, like so:

class App extends React.Component {
  constructor(props) {
    super(props)
    this.handleScroll = value => this.parallax && this.parallax.scrollTo(value)
  }
  render() {
    return (
      <div>
        <Parallax
          ref={ref => (this.parallax = ref)}
          pages={4}
        >

        <Parallax.Layer
          offset={0}
          speed={0.5}
          onClick={() => this.handleScroll(1)}
        >
          <Nav handleScroll={this.handleScroll} />

Then from the Nav component use props onClick={() => this.props.handleScroll(PAGE)} with PAGE being the page number you want to scroll to.


问:
Angularjs Typeahead not showing dropdown
i am trying to use an async typeahead, i can get the data fine and the inspector clearly shows data being returned. for example i am using the bootstrap example of getLocation

```<code>$scope.getLocation = function(val) {
    return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
      params: {
        address: val,
        sensor: false
      }
    }).then(function(response){
      return response.data.results.map(function(item){
        return item.formatted_address;
      });
    });
  };
</code>```

this works exactly how i want it to work and then this is my approach.

```<code>$scope.filterClients =function(val) {
        var data = $.param({
            action: "filter_clients",
            value: val
        });
        var config = {headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}}

        $http.post('http://***************.co.uk/switchboard.php', data, config)
            .then(function (response) {
                return response.data.map(function(item){
                    return item.first_name;
                  });
            });
    };
</code>```

HTML CODE

```<code><input ng-model="asyncSelected" placeholder="Select a Client" uib-typeahead="first_name for first_name in filterClients($viewValue)" class="form-control"/>
</code>```

答:
You don't return anything from $scope.filterClients. Just change your function like this :

```<code>$scope.filterClients = function (val) {
    var data = $.param({
        action: "filter_clients",
        value: val
    });
    var config = {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}}

    return $http.post('http://***************.co.uk/switchboard.php', data, config)
            .then(function (response) {
                return response.data.map(function (item) {
                    return item.first_name;
                });
            });
};
</code>```

NOTE

It is good to make sure that everything went fine before returning the data, otherwise you can get errors. Try something like this to avoid errors:

```<code>return $http.post('http://***************.co.uk/switchboard.php', data, config).then(function (response) {
    if (!angular.isObject(response) || !angular.isDefined(response.data)) {
        /* this you can put to avoid any errors */
        return;
    }

    /* if you want to limit you can use this code */
    var limit = 10;
    var data = [];
    for (var i = 0; i < response.data.length; i++) {
        if (i == limit) {
            break;
        }
        data.push(response.data[i]);
    }

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

Body:
i am trying to use an async typeahead, i can get the data fine and the inspector clearly shows data being returned. for example i am using the bootstrap example of getLocation

$scope.getLocation = function(val) {
    return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
      params: {
        address: val,
        sensor: false
      }
    }).then(function(response){
      return response.data.results.map(function(item){
        return item.formatted_address;
      });
    });
  };

this works exactly how i want it to work and then this is my approach.

$scope.filterClients =function(val) {
        var data = $.param({
            action: "filter_clients",
            value: val
        });
        var config = {headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}}

        $http.post('http://***************.co.uk/switchboard.php', data, config)
            .then(function (response) {
                return response.data.map(function(item){
                    return item.first_name;
                  });
            });
    };

HTML CODE

<input ng-model="asyncSelected" placeholder="Select a Client" uib-typeahead="first_name for first_name in filterClients($viewValue)" class="form-control"/>

Body:
You don't return anything from $scope.filterClients. Just change your function like this :

$scope.filterClients = function (val) {
    var data = $.param({
        action: "filter_clients",
        value: val
    });
    var config = {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}}

    return $http.post('http://***************.co.uk/switchboard.php', data, config)
            .then(function (response) {
                return response.data.map(function (item) {
                    return item.first_name;
                });
            });
};

NOTE

It is good to make sure that everything went fine before returning the data, otherwise you can get errors. Try something like this to avoid errors:

return $http.post('http://***************.co.uk/switchboard.php', data, config).then(function (response) {
    if (!angular.isObject(response) || !angular.isDefined(response.data)) {
        /* this you can put to avoid any errors */
        return;
    }

    /* if you want to limit you can use this code */
    var limit = 10;
    var data = [];
    for (var i = 0; i < response.data.length; i++) {
        if (i == limit) {
            break;
        }
        data.push(response.data[i]);
    }

    return data;
});


问:
How to prevent a form with GET method from sending the value of the submit button?
I have a simple form:

```<code><form action="/search" method="get">
    <input type="text" name="q" value="">
    <input type="submit" name="search" value="search">
</form>
</code>```

When submitting the url becomes `/search?q=Loremipsum&search=search

I really don't want that last bit, this seems pretty common problem and think it could be solved without js, but I realized that even google.com has this problem when you click on the search button. (maybe they don't care much about ugly urls?)

search?hl=en&source=hp&q=Loremipsum&btnG=Google+Search&aq=f&..

Is there a way to prevent the value of the submit button to be excluded without javascript?

I see in Stack overflow the search is ?q= but they don't have a submit button.

答:
You can omit name attribute in the final input like this:

```<code><form action="/search" method="get">
    <input type="text" name="q" value="">
    <input type="submit" value="search">
</form>
</code>```

Should do the trick. Keeping value attribute allows you to manipulate what text is displayed on the button.

Body:
I have a simple form:

<form action="/search" method="get">
    <input type="text" name="q" value="">
    <input type="submit" name="search" value="search">
</form>

When submitting the url becomes `/search?q=Loremipsum&search=search

I really don't want that last bit, this seems pretty common problem and think it could be solved without js, but I realized that even google.com has this problem when you click on the search button. (maybe they don't care much about ugly urls?)

search?hl=en&source=hp&q=Loremipsum&btnG=Google+Search&aq=f&..

Is there a way to prevent the value of the submit button to be excluded without javascript?

I see in Stack overflow the search is ?q= but they don't have a submit button.

Body:
You can omit name attribute in the final input like this:

<form action="/search" method="get">
    <input type="text" name="q" value="">
    <input type="submit" value="search">
</form>

Should do the trick. Keeping value attribute allows you to manipulate what text is displayed on the button.

ContentLicense: CC BY-SA 2.5


问:
How to parse JSON response in a built step in jenkins
In order to industrialize the deployments of an IBM product, I'm going to use its REST API interfaces.
I plan to use jenkins in order to orchestrate the calls to the REST APIs.
I'm still wondering if it's a good idea...?
If so, is there any way to simply parse the JSON responses in order to be able to make some conditions in the steps?
Thanks.</p>

答: If you are using Pipeline Job, you will be happy with Pipeline Utility Steps Plugin</p>


问:
implement conditions relative table django-rest-framework
I have two Models

```<code>class Parent(models.Model):
    name = models.CharField(max_length=50)

class Child(models.Model):
    parent = models.ForeignKey(Parent,related_name='child')
    child_name = models.CharField(max_length=80)
    type = models.BooleanField()
</code>```

I have implement this logic on serializer.py

```<code>class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Login
        fields = ('id', 'parent', 'child_name','type')

class ParentSerializer(serializers.ModelSerializer):
    child = ChildSerializer(many=True, read_only=True)
    class Meta:
        model = Catcher
        fields = ('id','name', 'child')
</code>```

I hit a query on Parent and get all the data from child table but i want implement condition on child table to get type = 1 only

```<code>a = Parent.objects.get(pk = 1)
serializer = ParentSerializer(a, many=True)
</code>```

it return me this json

```<code>{
    "id": 51,
    "name": "Rijo",
    "child": [
        {
          "id": 98,
          "name": "Child 1",
          "type" : 1
        },
        {
          "id": 10,
          "name": "Child 2",
          "type" : 0
        }

    ]
}
</code>```

But i want only type 1 child, how can i implement condition on child query

答:
Implement method or property in parent model:

```<code>class Parent(models.Model):
    name = models.CharField(max_length=50)

    def first_type_children(self):
        return self.child.filter(type=1)
</code>```

Use it as source in serializer field:

```<code>class ParentSerializer(serializers.ModelSerializer):
    child = ChildSerializer(source='first_type_children', many=True, read_only=True)
</code>```

Body:
I have two Models

class Parent(models.Model):
    name = models.CharField(max_length=50)

class Child(models.Model):
    parent = models.ForeignKey(Parent,related_name='child')
    child_name = models.CharField(max_length=80)
    type = models.BooleanField()

I have implement this logic on serializer.py

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Login
        fields = ('id', 'parent', 'child_name','type')

class ParentSerializer(serializers.ModelSerializer):
    child = ChildSerializer(many=True, read_only=True)
    class Meta:
        model = Catcher
        fields = ('id','name', 'child')

I hit a query on Parent and get all the data from child table but i want implement condition on child table to get type = 1 only

a = Parent.objects.get(pk = 1)
serializer = ParentSerializer(a, many=True)

it return me this json

{
    "id": 51,
    "name": "Rijo",
    "child": [
        {
          "id": 98,
          "name": "Child 1",
          "type" : 1
        },
        {
          "id": 10,
          "name": "Child 2",
          "type" : 0
        }

    ]
}

But i want only type 1 child, how can i implement condition on child query

Body:
Implement method or property in parent model:

class Parent(models.Model):
    name = models.CharField(max_length=50)

    def first_type_children(self):
        return self.child.filter(type=1)

Use it as source in serializer field:

class ParentSerializer(serializers.ModelSerializer):
    child = ChildSerializer(source='first_type_children', many=True, read_only=True)


问:
Heroku Postgres Ruby Puma Workers & Threads
For a pure Rack app running on a Heroku hobby dyno with a Heroku Postgres hobby dev add-on, how do you know how many workers & threads to configure Puma to have?</p>

答:
It depends greatly on how memory-hungry your application is. Given that it's a pure Rack app and most of the literature out there are for Rails apps - I'd imagine that your optimal values are higher.

The Librato add-on is really helpful here in letting you see your memory usage in near real-time, so you can quickly tweak and monitor how close you are to the 512MB limit. There's a free tier there, and it doesn't need any additional instrumentation either (I'm not affiliated with them in any way, but we do use their service!)


问:
Search for XML feeds usind Iphone
hi can anyone give me hint of how to start coding for an app to search the internet and find the rss xml url's using a string provided by the user.

thanks upfront.

答:
You need to use XML parsing to implement this.I suggest use touchXML

-(void)callwebservice{

```<code>NSString *path = @"YOUR URL";
[self grabRSSFeed:path];
</code>```

}

pragma mark -

pragma mark  Touch XML

pragma mark -

-(void) grabRSSFeed:(NSString *)blogAddress {

```<code>// Initialize the blogEntries MutableArray that we declared in the header
blogEntries = [[NSMutableArray alloc] init];

// Convert the supplied URL string into a usable URL object
NSURL *url = [NSURL URLWithString: blogAddress];

// Create a new rssParser object based on the TouchXML "CXMLDocument" class, this is the
// object that actually grabs and processes the RSS data
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];

// Create a new Array object to be used with the looping of the results from the rssParser
NSArray *resultNodes = NULL;

// Set the resultNodes Array to contain an object for every instance of an  node in our RSS feed
resultNodes = [rssParser nodesForXPath:@"//Node you want to parse" error:nil];

// Loop through the resultNodes to access each items actual data
for (CXMLElement *resultElement in resultNodes) {

    // Create a temporary MutableDictionary to store the items fields in, which will eventually end up in blogEntries
    NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
    // Create a counter variable as type "int"
    int counter;

    // Loop through the children of the current  node
    for(counter = 0; counter < [resultElement childCount]; counter++) {
        // Add each field to the blogItem Dictionary with the node name as key and node value as the value
        [blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
                    NSLog(@"Data = %@",[[resultElement childAtIndex:counter] stringValue]);

    }

    // Add the blogItem to the global blogEntries Array so that the view can access it.
    [blogEntries addObject:[blogItem copy]];

}
        [YourTable reloadData];
</code>```

}

Import touchXML library in you header file.

Thanks

Title: Search for XML feeds usind Iphone

Body:
You need to use XML parsing to implement this.I suggest use touchXML

-(void)callwebservice{

NSString *path = @"YOUR URL";
[self grabRSSFeed:path];

}

pragma mark -

pragma mark  Touch XML

pragma mark -

-(void) grabRSSFeed:(NSString *)blogAddress {

// Initialize the blogEntries MutableArray that we declared in the header
blogEntries = [[NSMutableArray alloc] init];

// Convert the supplied URL string into a usable URL object
NSURL *url = [NSURL URLWithString: blogAddress];

// Create a new rssParser object based on the TouchXML "CXMLDocument" class, this is the
// object that actually grabs and processes the RSS data
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];

// Create a new Array object to be used with the looping of the results from the rssParser
NSArray *resultNodes = NULL;

// Set the resultNodes Array to contain an object for every instance of an  node in our RSS feed
resultNodes = [rssParser nodesForXPath:@"//Node you want to parse" error:nil];

// Loop through the resultNodes to access each items actual data
for (CXMLElement *resultElement in resultNodes) {

    // Create a temporary MutableDictionary to store the items fields in, which will eventually end up in blogEntries
    NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
    // Create a counter variable as type "int"
    int counter;

    // Loop through the children of the current  node
    for(counter = 0; counter < [resultElement childCount]; counter++) {
        // Add each field to the blogItem Dictionary with the node name as key and node value as the value
        [blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
                    NSLog(@"Data = %@",[[resultElement childAtIndex:counter] stringValue]);

    }

    // Add the blogItem to the global blogEntries Array so that the view can access it.
    [blogEntries addObject:[blogItem copy]];

}
        [YourTable reloadData];

}

Import touchXML library in you header file.

Thanks


问:
Actions on Google and Account linking failure after tokens returned
Trying to test auth in the Web Simulator using the OAuth2 Authorization Code Flow, https://developers.google.com/actions/tools/web-simulator

See: https://developers.google.com/actions/tools/testing#testing_account_linking_with_google_home_web_simulator

And:
https://developers.google.com/actions/develop/identity/oauth2-code-flow

Provided you've setup your Action to require authorization against your authorization service, when you try to access your Action the Assistant advises you that you need to Link your account.
In the same response the simulator provides a URL for initiating the linking process, see:

```<code>"debugInfo": {
    "sharedDebugInfo": [
        {
            "name": "Account Linking Url",
            "debugInfo": "https://assistant.google.com/services/auth/handoffs/auth/start?provider=your-google-project-id_dev&scopes=your-scopes&return_url=https://www.google.com/"
        }
    ]
}
</code>```

Calling this URL (paste into a browser) will take you through an OAuth2 flow, assuming the user actions required are successful Google will call your token endpoint with the authorization code provided during the flow.

But then I was getting:

```<code>result_code=FAILURE&result_message=Account+linking+failed
</code>```

It all appeared to be working from my side but Google was returning a FAILURE.

答:
In my case, my token endpoint was returning my standard token response object, which included an access_token, a refresh_token, an expires_in, a session_state and another token that wasn't needed for this purpose but was standard to my token response.

And when I tested this same response on Googles playground it was fine:
https://developers.google.com/oauthplayground/

But not so when using the Assistant URL:
https://assistant.google.com/services/auth/handoffs/auth/start?provider=your-google-project-id_dev&scopes=your-scopes&return_url=https://www.google.com/

The reason it turns out is that the Assistant does not like superfluous properties in the response object.

I have yet to fully establish what is and isn't allowed but so far you can have:

```<code>{
    "token_type": "Bearer",
    "access_token: "xxx",
    "refresh_token": "yyy",
    "expires_in": "zzz"
}
</code>```

With these I now get:

```<code>result_code=SUCCESS
</code>```

Body:
Trying to test auth in the Web Simulator using the OAuth2 Authorization Code Flow, https://developers.google.com/actions/tools/web-simulator

See: https://developers.google.com/actions/tools/testing#testing_account_linking_with_google_home_web_simulator

And:
https://developers.google.com/actions/develop/identity/oauth2-code-flow

Provided you've setup your Action to require authorization against your authorization service, when you try to access your Action the Assistant advises you that you need to Link your account.
In the same response the simulator provides a URL for initiating the linking process, see:

"debugInfo": {
    "sharedDebugInfo": [
        {
            "name": "Account Linking Url",
            "debugInfo": "https://assistant.google.com/services/auth/handoffs/auth/start?provider=your-google-project-id_dev&scopes=your-scopes&return_url=https://www.google.com/"
        }
    ]
}

Calling this URL (paste into a browser) will take you through an OAuth2 flow, assuming the user actions required are successful Google will call your token endpoint with the authorization code provided during the flow.

But then I was getting:

result_code=FAILURE&result_message=Account+linking+failed

It all appeared to be working from my side but Google was returning a FAILURE.

Body:
In my case, my token endpoint was returning my standard token response object, which included an access_token, a refresh_token, an expires_in, a session_state and another token that wasn't needed for this purpose but was standard to my token response.

And when I tested this same response on Googles playground it was fine:
https://developers.google.com/oauthplayground/

But not so when using the Assistant URL:
https://assistant.google.com/services/auth/handoffs/auth/start?provider=your-google-project-id_dev&scopes=your-scopes&return_url=https://www.google.com/

The reason it turns out is that the Assistant does not like superfluous properties in the response object.

I have yet to fully establish what is and isn't allowed but so far you can have:

{
    "token_type": "Bearer",
    "access_token: "xxx",
    "refresh_token": "yyy",
    "expires_in": "zzz"
}

With these I now get:

result_code=SUCCESS


问:
File Locking (Read/Write) in ASP.NET Application
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

```<code>public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}
</code>```

And here's my code for the Reader :

```<code>private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}
</code>```

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

答:
You should also be disposing of your mutex, as it derives from WaitHandle, and WaitHandle implements IDisposable:

```<code>using (Mutex FileLock = new Mutex(true, "LogFileMutex"))
{
    // ...
}
</code>```

Also, perhaps consider a more unique name (a GUID perhaps) than "LogFileMutex", since another unrelated process could possibly use the same name inadvertantly.

Body:
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}

And here's my code for the Reader :

private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

Body:
You should also be disposing of your mutex, as it derives from WaitHandle, and WaitHandle implements IDisposable:

using (Mutex FileLock = new Mutex(true, "LogFileMutex"))
{
    // ...
}

Also, perhaps consider a more unique name (a GUID perhaps) than "LogFileMutex", since another unrelated process could possibly use the same name inadvertantly.

OwnerDisplayName: Mitch Wheat


问:
Android Dialog problem with TabView
```<code>   My problem is when a dialog is opened, if I change the tab,  that dialog is displayed in the activity in the next tab.How to remove that .
</code>```

Pls help.
This occurs because according to my requirement I can interact with the dialog and the view behind at the same time.

答: You should check if the dialog is open or not on the click of another tab, if open close it.</p>

Title: Android Dialog problem with TabView

Body:
   My problem is when a dialog is opened, if I change the tab,  that dialog is displayed in the activity in the next tab.How to remove that .

Pls help.
This occurs because according to my requirement I can interact with the dialog and the view behind at the same time.


问:
Spark ML pipeline usage
I created an ML pipeline with several transformers, including a StringIndexer which is used during training on the data labels.
I then store the resultant PipelineModel which will later be used for data preparation and prediction on a dataset which doesn't have labels.

The issue is that the created pipeline model's transform function cannot be applied to the new DataFrame, since it expects data labels to be available.

What am I missing?
How should this be done?

Note: My goal is to have a single pipeline (i.e. I'd like to keep the various transformations and ML algorithm together)

Thanks!

答:
You should paste your source code.Then your test data format should be consistent with your train data including the feature name.But you don't need label column.
You can refer to official site </p>

Title: Spark ML pipeline usage


问:
How to count number of leaf nodes in a binary tree using queue?
I am learning c language. It's Preety  simple to count the leaf nodes in a binary treee using recursion but how can we do it using a queue ? </p>

答:
Do a breadth first traversal of the tree using a queue and check if a particular node has both the children NULL.

Pseudocode:

```<code>queue = [root]
count = 0
while !queue.empty():
    current_node = queue.dequeue()
    if (current_node.left == NULL) and (current_node.right == NULL):
        count += 1
        continue
    if (current_node.left != NULL):
        queue.enqueue(current_node.left)
    if (current_node.right != NULL):
        queue.enqueue(current_node.right)

print count
</code>```

Body:
Do a breadth first traversal of the tree using a queue and check if a particular node has both the children NULL.

Pseudocode:

queue = [root]
count = 0
while !queue.empty():
    current_node = queue.dequeue()
    if (current_node.left == NULL) and (current_node.right == NULL):
        count += 1
        continue
    if (current_node.left != NULL):
        queue.enqueue(current_node.left)
    if (current_node.right != NULL):
        queue.enqueue(current_node.right)

print count


问:
WhiteSpaces Not allowed in Cell Editor primefaces
i am using primefaces
i cannot insert whitespace when using P:celleditor that contain facet inputtext.

```<code><p:column>
                            <f:facet name="header">
                                <h:outputText value="#{messages.lb_offr_appl}" />
                            </f:facet>
                            <p:cellEditor>
                            <f:facet name="input">
                                    <p:inputTextarea id="applicabilityinput" value="#{prest.applicability}" style="width:100%"/>
                                </f:facet>
                                <f:facet name="output">
                                    <h:outputText value="#{prest.applicability}" id="applicabilityoutput" />
                                </f:facet>

                            </p:cellEditor>
                        </p:column>
</code>```

any advice what to do to be able to insert strings with white spaces like "str1 str2"?

答:
I have the same issue in a DataTable when using rowEditor and draggableRows=true at the same time. If I remove draggableRows=true on my table then the whitespaces are accepted in the cellEditor.

I manage to make cellEditors(accepting whitespaces) and drag&drop work at he same time by using the Cell Editing with Click and RightClick and draggableRows=true.

My guess is that there is some JS/JQuery conflict/error behind it but couldn't figure it out yet. If someone has a real clue of why the whitespaces are not accepted sometime in cellEditor I'm interested as well.

I also read somewhere that when one enable a feature of DataTable is could break another one...

Body:
i am using primefaces
i cannot insert whitespace when using P:celleditor that contain facet inputtext.

                            <f:facet name="header">
                                <h:outputText value="#{messages.lb_offr_appl}" />
                            </f:facet>

                            <f:facet name="input">

                                </f:facet>
                                <f:facet name="output">
                                    <h:outputText value="#{prest.applicability}" id="applicabilityoutput" />
                                </f:facet>

any advice what to do to be able to insert strings with white spaces like "str1 str2"?


问:
Unexpected behaviours for multiple programmatic click events
I'm trying to make a Tic-Tac-Toe UI using PyQt5. Three modes are provided

Human vs. Human

Human vs. AI

AI vs. AI game

All modes work very fine except that in mode 3 (Two AIs play against each other), the UI will start loading and display the final result, instead of refreshing the intermediate steps of each turn until the game start, which I expected and preferred. How can I achieve it? Thank you!

Below is my code:

```<code>class TicTacToeUI(QtWidgets.QWidget):
    icons = ['icons/x-mark.png', 'icons/hollow-circle.png']

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("TicTacToe")
        self.setStyleSheet('background-color: #D7CCC8;')
        # Players
        self._players_selector = QtWidgets.QGridLayout()
        self._players = list()
        for p in range(2):
            label = QtWidgets.QLabel('Player {:}'.format(p))
            selectbox = QtWidgets.QComboBox()
            selectbox.setFixedHeight(24)
            selectbox.addItems(list(PLAYERS.keys()))
            self._players_selector.addWidget(label, 0, p)
            self._players_selector.addWidget(selectbox, 1, p)
            self._players.append(selectbox)
        self._grid = QtWidgets.QGridLayout()
        self._gameboard_buttons = dict()
        for i in range(self.m):
            for j in range(self.n):
                btn = self.create_gameboard_button(row=i, col=j)
                self._grid.addWidget(btn, i, j)
                self._gameboard_buttons.update({(i, j): btn})
        self._message_box = QtWidgets.QLabel('', parent=self)
        self._restart_button = QtWidgets.QPushButton('Start', parent=self)
        self._restart_button.setFixedHeight(32)
        self._restart_button.clicked.connect(self.restart)
        # Layout
        self._layout = QtWidgets.QVBoxLayout()
        self._layout.addLayout(self._players_selector)
        self._layout.addLayout(self._grid)
        self._layout.addWidget(self._message_box)
        self._layout.addWidget(self._restart_button)
        self.setLayout(self._layout)
        # The game
        self._game = TicTacToe()
        self._started = False

    def create_gameboard_button(self, row, col):
        btn = TicTacToeUIButton('', parent=self, style_sheet='background-color: #D7CCC8;')
        btn.setFixedSize(64, 64)
        btn.clicked.connect(functools.partial(self.click, row, col))
        return btn

    def click(self, row, col):
        if not self._started:
            pass
        elif self._game.is_ended:
            pass
        else:
            btn = self._gameboard_buttons.get((row, col))
            if btn is not None:
                if btn.is_occupied:
                    msg = 'It is occupied. Please select another one.'
                    self._message_box.setText(msg)
                else:
                    player = self._game.turn_player
                    # Icon appearance
                    for _, b in self._gameboard_buttons.items():
                        b.remove_border()
                    btn.setIcon(QtGui.QIcon(self.icons[player]))
                    btn.setIconSize(QtCore.QSize(48, 48))
                    btn.add_border('border: 1px solid #FF0000;')
                    btn.occupied_player = player
                    # Check result
                    self._game.move(row=row, col=col, player=player)
                    if self._game.winner is not None:
                        if self._game.winner == -1:
                            msg = 'Draw. What a game!'
                        else:
                            msg = 'Player {:} won. Congratulations!'
                            msg = msg.format(self._game.winner)
                    else:
                        msg = ''
                    self._message_box.setText(msg)
            # Next turn
            if self._game.is_ended:
                pass
            else:
                self._game.players[self._game.turn_player].decide_ui(self)

    def reset(self):
        self._started = True
        self._game.reset()
        self._game.player0 = PLAYERS.get(self._players[0].currentText())
        self._game.player1 = PLAYERS.get(self._players[1].currentText())
        self._restart_button.setText('Restart')
        self._message_box.setText('')
        for _, btn in self._gameboard_buttons.items():
            btn.reset()
        if self._game.player0.is_ai:
            self._game._player0.decide_ui(self)

    def restart(self):
        self.reset()
</code>```

Some notes:

The game will start right after 'Start'/'Restart' button is clicked, the players, either a Human or an AI will click gameboard button based on their judgment/algorithm.

Human().decide_ui(self) does nothing, while
SomeAI().decide_ui(self) will click the gameboard buttons based on some algorithms.

TicTacToe() is an object storing the gameboard matrix and the winning criteria.

If you are interested in playing the game, you can download whole set of code here.

答:
I've downloaded the full app to better understand the whole process.

So, when running, the AI is keeping the main process busy and Qt events are never processed and nothing is drawn on the UI.

The easiest solution is to call QApplication.processEvents() every turn, like this:

```<code>def click(self, row, col):
    # "click" code

    QtWidgets.qApp.processEvents()

    # Next turn
    if self._game.is_ended:
        pass
    else:
        self._game.players[self._game.turn_player].decide_ui(self)
</code>```

This will process all the pending events, and moves will be displayed one at the time.

Body:
I'm trying to make a Tic-Tac-Toe UI using PyQt5. Three modes are provided

Human vs. Human

Human vs. AI

AI vs. AI game

All modes work very fine except that in mode 3 (Two AIs play against each other), the UI will start loading and display the final result, instead of refreshing the intermediate steps of each turn until the game start, which I expected and preferred. How can I achieve it? Thank you!

Below is my code:

class TicTacToeUI(QtWidgets.QWidget):
    icons = ['icons/x-mark.png', 'icons/hollow-circle.png']

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("TicTacToe")
        self.setStyleSheet('background-color: #D7CCC8;')
        # Players
        self._players_selector = QtWidgets.QGridLayout()
        self._players = list()
        for p in range(2):
            label = QtWidgets.QLabel('Player {:}'.format(p))
            selectbox = QtWidgets.QComboBox()
            selectbox.setFixedHeight(24)
            selectbox.addItems(list(PLAYERS.keys()))
            self._players_selector.addWidget(label, 0, p)
            self._players_selector.addWidget(selectbox, 1, p)
            self._players.append(selectbox)
        self._grid = QtWidgets.QGridLayout()
        self._gameboard_buttons = dict()
        for i in range(self.m):
            for j in range(self.n):
                btn = self.create_gameboard_button(row=i, col=j)
                self._grid.addWidget(btn, i, j)
                self._gameboard_buttons.update({(i, j): btn})
        self._message_box = QtWidgets.QLabel('', parent=self)
        self._restart_button = QtWidgets.QPushButton('Start', parent=self)
        self._restart_button.setFixedHeight(32)
        self._restart_button.clicked.connect(self.restart)
        # Layout
        self._layout = QtWidgets.QVBoxLayout()
        self._layout.addLayout(self._players_selector)
        self._layout.addLayout(self._grid)
        self._layout.addWidget(self._message_box)
        self._layout.addWidget(self._restart_button)
        self.setLayout(self._layout)
        # The game
        self._game = TicTacToe()
        self._started = False

    def create_gameboard_button(self, row, col):
        btn = TicTacToeUIButton('', parent=self, style_sheet='background-color: #D7CCC8;')
        btn.setFixedSize(64, 64)
        btn.clicked.connect(functools.partial(self.click, row, col))
        return btn

    def click(self, row, col):
        if not self._started:
            pass
        elif self._game.is_ended:
            pass
        else:
            btn = self._gameboard_buttons.get((row, col))
            if btn is not None:
                if btn.is_occupied:
                    msg = 'It is occupied. Please select another one.'
                    self._message_box.setText(msg)
                else:
                    player = self._game.turn_player
                    # Icon appearance
                    for _, b in self._gameboard_buttons.items():
                        b.remove_border()
                    btn.setIcon(QtGui.QIcon(self.icons[player]))
                    btn.setIconSize(QtCore.QSize(48, 48))
                    btn.add_border('border: 1px solid #FF0000;')
                    btn.occupied_player = player
                    # Check result
                    self._game.move(row=row, col=col, player=player)
                    if self._game.winner is not None:
                        if self._game.winner == -1:
                            msg = 'Draw. What a game!'
                        else:
                            msg = 'Player {:} won. Congratulations!'
                            msg = msg.format(self._game.winner)
                    else:
                        msg = ''
                    self._message_box.setText(msg)
            # Next turn
            if self._game.is_ended:
                pass
            else:
                self._game.players[self._game.turn_player].decide_ui(self)

    def reset(self):
        self._started = True
        self._game.reset()
        self._game.player0 = PLAYERS.get(self._players[0].currentText())
        self._game.player1 = PLAYERS.get(self._players[1].currentText())
        self._restart_button.setText('Restart')
        self._message_box.setText('')
        for _, btn in self._gameboard_buttons.items():
            btn.reset()
        if self._game.player0.is_ai:
            self._game._player0.decide_ui(self)

    def restart(self):
        self.reset()

Some notes:

The game will start right after 'Start'/'Restart' button is clicked, the players, either a Human or an AI will click gameboard button based on their judgment/algorithm.

Human().decide_ui(self) does nothing, while
SomeAI().decide_ui(self) will click the gameboard buttons based on some algorithms.

TicTacToe() is an object storing the gameboard matrix and the winning criteria.

If you are interested in playing the game, you can download whole set of code here.

Body:
I've downloaded the full app to better understand the whole process.

So, when running, the AI is keeping the main process busy and Qt events are never processed and nothing is drawn on the UI.

The easiest solution is to call QApplication.processEvents() every turn, like this:

def click(self, row, col):
    # "click" code

    QtWidgets.qApp.processEvents()

    # Next turn
    if self._game.is_ended:
        pass
    else:
        self._game.players[self._game.turn_player].decide_ui(self)

This will process all the pending events, and moves will be displayed one at the time.


问:
Why need synchronizedMap() if there is ConcurrentHashMap?
I read an article about thread safe maps and got a question. Collections.synchronizedMap() proxies underlying map with adding synchronized blocks on each method. On the other hand ConcurrentHashMap doesn't lock the whole map on read/write operations. Which means all operations in multi thread system are faster.

So what are the benefits of using synchronizedMap() nowadays? I see the only:

it's available since java 1.2 (vs java 1.5 for ConcurrentHashMap)

can store nullable values (if underlying map can do it)

Are there any other situations when synchronizedMap() is better?

答: Not really. The only other case I can think of is easily making a custom map implementation thread safe. </p>


问:
Python file reading and writing is not working
I am making a game for Python and in it there is code to write to a file the answer for when I am running it myself to prevent myself having to actually play the game.
I have already coded for writing and reading a file which works fine, but for the cheat .txt file, printing its contents returns only [].

Here's a shortened example of what is happening.

```<code>file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
text = file.readlines()
print(text)
[]
file.close()

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "r+")
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']
</code>```

It appears now on a network machine that the a+ does not work, but r+. I fully understand the functionality of each mode, but can anyone suggest why it cannot read (or write, which returns the argument's length) when in a+ mode?

Note a+ is the required mode as it needs to be appended to the file.

Edit: as I am typing file.write(), the small box assisting you apply arguments reads 'See source or doc'.

答:
This is happening because of the file descriptor (fd), is at the end of the file,
If you need to move the fd to the start of the file,</p>

```<code>import os
file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
os.lseek(file, 0, 0)
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']
</code>```

Body:
I am making a game for Python and in it there is code to write to a file the answer for when I am running it myself to prevent myself having to actually play the game.
I have already coded for writing and reading a file which works fine, but for the cheat .txt file, printing its contents returns only [].

Here's a shortened example of what is happening.

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
text = file.readlines()
print(text)
[]
file.close()

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "r+")
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']

It appears now on a network machine that the a+ does not work, but r+. I fully understand the functionality of each mode, but can anyone suggest why it cannot read (or write, which returns the argument's length) when in a+ mode?

Note a+ is the required mode as it needs to be appended to the file.

Edit: as I am typing file.write(), the small box assisting you apply arguments reads 'See source or doc'.

Body:
This is happening because of the file descriptor (fd), is at the end of the file,
If you need to move the fd to the start of the file,

import os
file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
os.lseek(file, 0, 0)
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']


问:
Modifying Cordova iOS platform template -- linking frameworks?
I have been working on a Cordova project for both iOS and Android.
As part of the project as we will need to build a number of projects from a basic template.

I have done this by creating a template for the actual cordova project and also as part of it I pulled the cordova-ios-master code base for when we add the iOS platform. So we use our own cordova-ios-master due to some small modifications we needed to add.

With some of the plugins we have added / created we need to access SDK's / API's from some third party developers (this is mainly for some push notification services). Normally when we create the project and have added the platform we then need to add the linked frameworks using Xcode.

However I can see that within the cordova-ios-master there is the template Xcode project. I was hoping I could add the linked frameworks within this project so that they are already added when we first create the project and add the custom iOS platform.

What seems to be happening though is if I add the linked library into the template Xcode project and then save it. Once I then re-add that platform to the cordova project instead of the Xcode project being named after the cordova project name, it seems to have messed the re-naming of the Xcode project.

Below shows how the Xcode project normally appears when you add the libraries manually after adding the platform

So if i modify the Xcode template in cordova-ios-master, shown below....

You can see it already has a libCordova.a added.
I add one more and re-save the project.

But then when I add the platform to my project again from this source, i open the Xcode project for it and whilst my library is added, the project was named "myproject" but i can't choose to run it as the project selection seems to appear as "PROJECT_NAME" as opposed to being named and usable as "my project"....

Im fairly new to mac's and Xcode so maybe I'm doing something basic wrong.

Any suggestions or ideas would really help, I hope this post makes sense, it is a bit complex.

Thanks again
Rhys

答:
Right I found a solution. I think I was looking at the problem the wrong way round. So if I need to add a framework for a particular plugin, rather than edit the Xcode project to add the framework. Cordova actually gives you the option to add certain frameworks from within the plugin.xml. Found this answer here....

How to copy a custom ios framework using plugin.xml on Phonegap 3

so I have added a required framework like so....

```<code><framework src="src/ios/OtherLevels/OtherLevels.framework" custom="true" />
</code>```

My bad!

-Rhys

Body:
Right I found a solution. I think I was looking at the problem the wrong way round. So if I need to add a framework for a particular plugin, rather than edit the Xcode project to add the framework. Cordova actually gives you the option to add certain frameworks from within the plugin.xml. Found this answer here....

How to copy a custom ios framework using plugin.xml on Phonegap 3

so I have added a required framework like so....

<framework src="src/ios/OtherLevels/OtherLevels.framework" custom="true" />

My bad!

-Rhys


问:
Permission to create VIEW for table with SELECT right
I'm granted SELECT on table NOTMYSCHEMA.XYZ but Oracle does not allow me to create VIEW that includes this table! What's the purpose of this ban? I assume if I can see the table content then I should be allowed to make a view showing this table content by default.</p>

答:
Privileges Required to Create Views

To create a view, you must meet the following requirements:

You must have been granted the CREATE VIEW (to create a view in your schema) or CREATE ANY VIEW (to create a view in another user's schema) system privilege, either explicitly or through a role.

You must have been explicitly granted the SELECT, INSERT, UPDATE, or DELETE object privileges on all base objects underlying the view or the SELECT ANY TABLE, INSERT ANY TABLE, UPDATE ANY TABLE, or DELETE ANY TABLE system privileges. You may not have obtained these privileges through roles.

Additionally, in order to grant other users access to your view, you must have received object privilege(s) to the base objects with the GRANT OPTION option or appropriate system privileges with the ADMIN OPTION option. If you have not, grantees cannot access your view."


问:
Why getting null in the request parameter
Below is my API.

```<code>public HttpResponseMessage Delete(IEnumerable<int> customerIds)
{
    //api stuff
}
</code>```

But when this API is hit I am getting customerIds as null.

This is how I am calling the API via Postman.

```<code>{
 "customerIds" : [69,50]
}

Content-Type = application/json
</code>```

However, if I update the API as below, values are caught.

```<code>public HttpResponseMessage Delete(CustomerTO customerIds)
{
    //api stuff
}
public class CustomerTO
{
   public IEnumerable<int> CustomerIds
}
</code>```

If I do so, I think its an overhead.

Any help/suggestion highly appreciated.

答:
The problem is in your post data object.
You just need to pass an array [1,2,3,4] in your request data.

Body:
Below is my API.

public HttpResponseMessage Delete(IEnumerable<int> customerIds)
{
    //api stuff
}

But when this API is hit I am getting customerIds as null.

This is how I am calling the API via Postman.

{
 "customerIds" : [69,50]
}

Content-Type = application/json

However, if I update the API as below, values are caught.

public HttpResponseMessage Delete(CustomerTO customerIds)
{
    //api stuff
}
public class CustomerTO
{
   public IEnumerable<int> CustomerIds
}

If I do so, I think its an overhead.

Any help/suggestion highly appreciated.


问:
Markers are not loading on the map but data is coming through location.php
```<code>    <?php
    error_reporting(E_ALL ^ E_DEPRECATED);

    $conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
    mysql_select_db("db_jawandsons") or die(mysql_error());

    ?>

    <html>
    <head>
     <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Maps</title>

    <!-------- Customizable Css for Map  ----------------------------->
        <style type="text/css">
            body { font: normal 10pt Helvetica, Arial; }
            #map { width: 1200px; height: 500px; border: 0px; padding: 0px; }
        </style>

        <!---------------- Java Scripts for Map  ----------------->
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
        <!------------- Java Scripts for Map  ------------------->
        <script type="text/javascript">
    var marker;
    var map = null;
    var markersArray = [];

        //--------------------- Sample code written by vIr ------------
        var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
                   new google.maps.Size(32, 32), new google.maps.Point(0, 0),
                   new google.maps.Point(16, 32));
                        var center = null;

                        var currentPopup;
                        var bounds = new google.maps.LatLngBounds();
                        function addMarker(lat, lng, info) {
                            var pt = new google.maps.LatLng(lat, lng);
                            bounds.extend(pt);
                                marker = new google.maps.Marker({
                                position: pt,
                                draggable: true,
                                raiseOnDrag: true,
                                icon: icon,
                                map: map
                            });
                             markersArray.push(marker);
                            var popup = new google.maps.InfoWindow({
                                content: info,
                                maxWidth: 300
                            });
                            google.maps.event.addListener(marker, "click", function() {
                                if (currentPopup != null) {
                                    currentPopup.close();
                                    currentPopup = null;
                                }
                                popup.open(map, marker);
                                currentPopup = popup;
                            });
                            google.maps.event.addListener(popup, "closeclick", function() {
                                map.panTo(center);
                                currentPopup = null;
                            });
                        }

                        function initMap() {
                            map = new google.maps.Map(document.getElementById("map"), {

                                center: new google.maps.LatLng(0, 0),
                                zoom: 14,
                                mapTypeId: google.maps.MapTypeId.ROADMAP,
                                mapTypeControl: true,
                                mapTypeControlOptions: {
                                    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
                                },
                                navigationControl: true,
                                navigationControlOptions: {
                                    style: google.maps.NavigationControlStyle.ZOOM_PAN
                                }
                            });

      setInterval(function mapload(){

                    $.ajax({
                                type: "POST",
                                url: 'location.php',
                               // data: form_data,
                                success: function(data)
                                {
                                //  alert(data);
                               // var json_obj = $.parseJSON(data);//parse JSON
                                    var json_obj = jQuery.parseJSON(JSON.stringify(data));
                                    for (var i in json_obj)
                                    {   addMarker(json_obj[i].u_lat, json_obj[i].u_lon,"Longitude:" + json_obj[i].u_lon + "<br>" + json_obj[i].u_email + "<br>" + json_obj[i].u_name);

                                    }
                                },
                                dataType: "json"//set to JSON
                            })

      },3000);

       center = bounds.getCenter();
       map.fitBounds(bounds);

       }

        setInterval(function removeMarker() {
        if (markersArray) {
            for (i=0; i < markersArray.length; i++) {
                markersArray[i].setMap(null);
                 marker=null;
            }
        markersArray.length = 0;
        }
    },3000);
       </script>

      </head>
        <body onLoad="initMap()" style="margin:0px; border:0px; padding:0px;">
           <div id="map"></div>
        </body>
     </html>

It does not add markers to the map.how can i add markers to the map. please anyone tell me where is the problem is, thank in advance :)

<?php

$conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("db_jawandsons") or die(mysql_error());

$return_arr = array();
$data=array();
$result = mysql_query("SELECT lat,lng,vname,speed FROM v_data where sno='1'")or die(mysql_error());
  while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row['lat'];
    $data[] = $row['lng'];
    $data[] = $row['vname'];
    $data[] = $row['speed'];
    //array_push($return_arr,$data);
}

echo json_encode($data);

   //echo("addMarker(30.91995, 75.93287, '<b>$name</b><br />$desc');\n");
?>
</code>```

i want to add my location to the map it will come dynamically. how can i add multiple locations or single location (lat,lon) to the map.

let me know if there is problem in php code. how can i reload the map without page refreash. i tried many scripts but did not work for me. please help me.

答:
Here's what works on me. I have this html page with PHP embedded in it.Maybe you can try to look at and get what you need in here.</p>

```<code><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA0XjHka3iMTH5jEuy-bYPWNZdILVOQsWI&callback=initMap"></script>
    <script>
      function initialize() {

        var markers = [];
        var mapCanvas = document.getElementById('map-canvas');
        //San Pablo City
        var myLatlng = new google.maps.LatLng(14.0667, 121.3333);
        <?php
            if (isset($_GET['latitude']) && $_GET['latitude'] != '' && isset($_GET['longitude']) && $_GET['longitude'] != ''){
              ?>
              myLatlng = new google.maps.LatLng(<?=$_GET['latitude']?>, <?=$_GET['longitude']?>);

         <?php   } ?>

        var mapOptions = {
          center: myLatlng,
          zoom: 17,
           mapTypeControlOptions: {
           mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE,google.maps.MapTypeId.HYBRID]
        },
          mapTypeId: google.maps.MapTypeId.NORMAL
        }

        var map = new google.maps.Map(mapCanvas, mapOptions);

         map.setTilt(45);

        var infowindow = new google.maps.InfoWindow({

           maxWidth: 400

        });

         <?php foreach($crimes as $crime) {

            if ($crime['latitude'] != null AND $crime['longitude'] != '') {

            $content = "<b>Date : ". date('M d Y',strtotime($crime['date_crime']))."</b><br>";
            $content .= "<p>". $crime['useful_info']."</p>";

            ?>

            addMarker( new google.maps.LatLng(<?=$crime['latitude']?>,<?=$crime['longitude']?>), '<?=$crime['sub_category']?>','<?=str_replace('#','',$crime['color'])?>','<?=substr($crime['sub_category'],0,1)?>',<?=$crime['complaint_id']?>,<?=esc($content)?>);

         <?php  } } ?>

         addListener();

        // Add a marker to the map and push to the array.
        function addMarker(location,title,color,letter,id,content) {

          var pinColor = color;
        var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor,
                      new google.maps.Size(21, 34),
                      new google.maps.Point(0,0),
                      new google.maps.Point(10, 34));

          var marker = new google.maps.Marker({
            position: location,
            map: map,
            title : title,
            animation: google.maps.Animation.DROP,
            icon: pinImage

          });
          marker.set("id",id);
          marker.set("content",content);

          markers.push(marker);
        }

        function getMessage(title,str){
          var ret =  '<div id="content">'+
              '<div id="siteNotice">'+
              '</div>'+
              '<h4 id="firstHeading" class="firstHeading">' + title + '</h1>'+
              '<div id="bodyContent">'+ str +

               '</div>'+
              '</div>';
              return ret;
        }

        // Sets the map on all markers in the array.
        function setAllMap(map) {
          for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
          }
        }

        // Removes the markers from the map, but keeps them in the array.
        function clearMarkers() {
          setAllMap(null);
        }

        // Shows any markers currently in the array.
        function showMarkers() {
          setAllMap(map);
        }

        // Deletes all markers in the array by removing references to them.
        function deleteMarkers() {
          clearMarkers();
          markers = [];
        }

       function addListener(){
          for (var i = 0; i < markers.length; i++) {
              google.maps.event.addListener(markers[i], 'click', function () {
               // do something with this marker ...
                var id = this.get("id");
                  infowindow.setContent(getMessage(this.getTitle(),this.get("content")));
                  infowindow.setPosition(this.getPosition());
                  infowindow.open(map,markers[i]);
              });

           }
        }

        //google.maps.event.addListener(marker, 'click', function() {
          //  map.setZoom(8);
          //  map.setCenter(marker.getPosition());
       // });

      }

      google.maps.event.addDomListener(window, 'load', initialize);

    </script>
<div class="page-header">
  <h3>Report > <small>Map View</small></h2>
</div>

    <div class = "col-md-10">
             <div id="map-canvas"></div>
     </div>
</code>```

Body:
    <?php
    error_reporting(E_ALL ^ E_DEPRECATED);

    $conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
    mysql_select_db("db_jawandsons") or die(mysql_error());

    ?>

     <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Maps</title>

It does not add markers to the map.how can i add markers to the map. please anyone tell me where is the problem is, thank in advance :)

<?php

$conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("db_jawandsons") or die(mysql_error());

$return_arr = array();
$data=array();
$result = mysql_query("SELECT lat,lng,vname,speed FROM v_data where sno='1'")or die(mysql_error());
  while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row['lat'];
    $data[] = $row['lng'];
    $data[] = $row['vname'];
    $data[] = $row['speed'];
    //array_push($return_arr,$data);
}

echo json_encode($data);

   //echo("addMarker(30.91995, 75.93287, '$name
$desc');\n");
?>

i want to add my location to the map it will come dynamically. how can i add multiple locations or single location (lat,lon) to the map.

let me know if there is problem in php code. how can i reload the map without page refreash. i tried many scripts but did not work for me. please help me.

Body:
Here's what works on me. I have this html page with PHP embedded in it.Maybe you can try to look at and get what you need in here.

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA0XjHka3iMTH5jEuy-bYPWNZdILVOQsWI&callback=initMap"></script>
    <script>
      function initialize() {

        var markers = [];
        var mapCanvas = document.getElementById('map-canvas');
        //San Pablo City
        var myLatlng = new google.maps.LatLng(14.0667, 121.3333);
        <?php
            if (isset($_GET['latitude']) && $_GET['latitude'] != '' && isset($_GET['longitude']) && $_GET['longitude'] != ''){
              ?>
              myLatlng = new google.maps.LatLng(<?=$_GET['latitude']?>, <?=$_GET['longitude']?>);

         <?php   } ?>

        var mapOptions = {
          center: myLatlng,
          zoom: 17,
           mapTypeControlOptions: {
           mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE,google.maps.MapTypeId.HYBRID]
        },
          mapTypeId: google.maps.MapTypeId.NORMAL
        }

        var map = new google.maps.Map(mapCanvas, mapOptions);

         map.setTilt(45);

        var infowindow = new google.maps.InfoWindow({

           maxWidth: 400

        });

         <?php foreach($crimes as $crime) {

            if ($crime['latitude'] != null AND $crime['longitude'] != '') {

            $content = "<b>Date : ". date('M d Y',strtotime($crime['date_crime']))."</b><br>";
            $content .= "<p>". $crime['useful_info']."</p>";

            ?>

            addMarker( new google.maps.LatLng(<?=$crime['latitude']?>,<?=$crime['longitude']?>), '<?=$crime['sub_category']?>','<?=str_replace('#','',$crime['color'])?>','<?=substr($crime['sub_category'],0,1)?>',<?=$crime['complaint_id']?>,<?=esc($content)?>);

         <?php  } } ?>

         addListener();

        // Add a marker to the map and push to the array.
        function addMarker(location,title,color,letter,id,content) {

          var pinColor = color;
        var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor,
                      new google.maps.Size(21, 34),
                      new google.maps.Point(0,0),
                      new google.maps.Point(10, 34));

          var marker = new google.maps.Marker({
            position: location,
            map: map,
            title : title,
            animation: google.maps.Animation.DROP,
            icon: pinImage

          });
          marker.set("id",id);
          marker.set("content",content);

          markers.push(marker);
        }

        function getMessage(title,str){
          var ret =  '<div id="content">'+
              '<div id="siteNotice">'+
              '</div>'+
              '<h4 id="firstHeading" class="firstHeading">' + title + '</h1>'+
              '<div id="bodyContent">'+ str +

               '</div>'+
              '</div>';
              return ret;
        }

        // Sets the map on all markers in the array.
        function setAllMap(map) {
          for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
          }
        }

        // Removes the markers from the map, but keeps them in the array.
        function clearMarkers() {
          setAllMap(null);
        }

        // Shows any markers currently in the array.
        function showMarkers() {
          setAllMap(map);
        }

        // Deletes all markers in the array by removing references to them.
        function deleteMarkers() {
          clearMarkers();
          markers = [];
        }

       function addListener(){
          for (var i = 0; i < markers.length; i++) {
              google.maps.event.addListener(markers[i], 'click', function () {
               // do something with this marker ...
                var id = this.get("id");
                  infowindow.setContent(getMessage(this.getTitle(),this.get("content")));
                  infowindow.setPosition(this.getPosition());
                  infowindow.open(map,markers[i]);
              });

           }
        }

        //google.maps.event.addListener(marker, 'click', function() {
          //  map.setZoom(8);
          //  map.setCenter(marker.getPosition());
       // });

      }

      google.maps.event.addDomListener(window, 'load', initialize);

    </script>
<div class="page-header">
  <h3>Report > <small>Map View</small></h2>
</div>

    <div class = "col-md-10">
             <div id="map-canvas"></div>
     </div>


问:
django remove source files and generate pyc files
I want to remove all .py files in my django project.But pyc files are not generated as yet..

What is the settings that needs to be changed to generate the .pyc files

答:
compileall can be used to compile all Python scripts in the project directory.

```<code>python -m compileall path/to/project
</code>```

Body:
compileall can be used to compile all Python scripts in the project directory.

python -m compileall path/to/project


Title: Remove Duplicate Occurance of Values in SQL Server Select Record

Body:
Date    Time    Event   site
2017-03-29  13:09:31.0000000    IN  Old Site
2017-03-29  14:26:32.0000000    OUT Old Site
2017-03-29  14:41:02.0000000    IN  Old Site
2017-03-29  16:21:17.0000000    OUT Old Site
2017-03-29  16:54:18.0000000    IN  Old Site
2017-03-29  16:54:24.0000000    IN  Old Site
2017-03-29  17:45:05.0000000    OUT Old Site
2017-03-29  19:30:03.0000000    IN  Old Site

DECLARE @empTime TABLE ([Date] DATE,[Time] TIME,[Event] VARCHAR(30),[Site] VARCHAR(30))

INSERT INTO @empTime ([Date],[Time],[Event],[Site])
VALUES
('2017-03-29', '13:09:31.0000000', 'IN', 'Old Site'),
('2017-03-29', '14:26:32.0000000', 'OUT', 'Old Site'),
('2017-03-29', '14:41:02.0000000', 'IN', 'Old Site'),
('2017-03-29', '16:21:17.0000000', 'OUT', 'Old Site'),
('2017-03-29', '16:54:18.0000000', 'IN', 'Old Site'),
('2017-03-29', '16:54:24.0000000', 'IN', 'Old Site'),
('2017-03-29', '17:45:05.0000000', 'OUT', 'Old Site'),
('2017-03-29', '19:30:03.0000000', 'IN', 'Old Site')

SELECT *
FROM @empTime

As per above code and output, I want to remove one of the Record for 'IN' '16:54:24.0000000' because I want record in form of continuous IN-OUT-IN-OUT.

I want to remove duplicate occurrence of value in below record. I want record should be in continuous form i.e. In-Out-In-Out.

Body:
Hope this helps. As per your request this should work in SQL Server 2008

;WITH cte_empTime([Date], [Time], [Event], [Site]) AS
(
SELECT '2017-03-29','13:09:31.0000000', 'IN',   'Old Site' UNION ALL
SELECT '2017-03-29','14:26:32.0000000', 'OUT',  'Old Site' UNION ALL
SELECT '2017-03-29','14:41:02.0000000', 'IN',   'Old Site' UNION ALL
SELECT '2017-03-29','16:21:17.0000000', 'OUT',  'Old Site' UNION ALL
SELECT '2017-03-29','16:54:18.0000000', 'IN',   'Old Site' UNION ALL
SELECT '2017-03-29','16:54:24.0000000', 'IN',   'Old Site' UNION ALL
SELECT '2017-03-29','17:45:05.0000000', 'OUT',  'Old Site' UNION ALL
SELECT '2017-03-29','19:30:03.0000000', 'IN',   'Old Site'
),
cte_SeqGenerater AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [Date],[Time]) AS SeqID,
    [Date],
    [Time],
    [Event],
    [Site]
FROM cte_empTime
)
SELECT a.[Date],
    a.[Time],
    a.[Event],
    a.[Site]
FROM cte_SeqGenerater a
LEFT JOIN cte_SeqGenerater b
    ON a.SeqID = b.SeqID + 1
WHERE CASE
        WHEN a.[Event] = b.[Event] THEN 0
        ELSE 1
      END = 1

Result

+ ------------------------------------------------ +
| Date       | Time             | Event | Site     |
+ ---------- | ---------------- | ----- | -------- +
| 2017-03-29 | 13:09:31.0000000 | IN    | Old Site |
| 2017-03-29 | 14:26:32.0000000 | OUT   | Old Site |
| 2017-03-29 | 14:41:02.0000000 | IN    | Old Site |
| 2017-03-29 | 16:21:17.0000000 | OUT   | Old Site |
| 2017-03-29 | 16:54:18.0000000 | IN    | Old Site |
| 2017-03-29 | 17:45:05.0000000 | OUT   | Old Site |
| 2017-03-29 | 19:30:03.0000000 | IN    | Old Site |
+ ------------------------------------------------ +


问:
This application has no explicit mapping for /error, so you are seeing this as a fallback
```<code>    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&libraries=places&callback=initAutocomplete"></script>
    </head>
    <body>
    </body>
</html>
</code>```

<p>The Error Occurs On The script tag as Exception parsing document </p>

答: May be you are missing a closing tag somewhere. I have no idea what you have in the HTML template, unless you post the complete code.</p>


问:
"read.sql" function in R: Using R as an SQL browser?
I have a large .sql file, created as a backup from a MySQL database (containing several tables), and I would like to search elements within it from R.

Ideally, there would be a read.sql function that would turn the tables into some R list with data.frames in it.  Is there something that comes close? If not, can RSQLite or RMySQL help? (going through the reference manuals, I don't see a simple function for what I described)

答:
My workaround so far (I am also a newbie with db) is to export the database as .csv file in the phpMyAdmin (need to tick "Export tables as separate files" in the "custom" method). And then use read_csv() on tables I want to work with.

It is not ideal because I would like to export the database and work on it on my computer with R (creating functions that will work when accessing the database that is online) and access the real database later, when I have done all my testing. But from the answers here, it seems the .sql export would not help for that anyway (?) and that I would need to recreate the db locally...


问:
html2canvas not display all div as jpeg
I use htmlCanvas in angular to make div as jpeg and display it.
What happens is that the jpeg display only the part of the div that I see , as a printScreen.
The JS:</p>

```<code>$(function () {
        $("#btnSave").click(function () {
            html2canvas($("#widget"), {
                onrendered: function (canvas) {
                    document.body.appendChild(canvas);

                    // Convert and download as image
                    Canvas2Image.saveAsJPEG(canvas);
                     $("#img-out").append(canvas);

                    //document.body.removeChild(canvas);
                }
            });
        });
    });
</code>```

答:
Try modifying the code as below

```<code>  $("#img-out").append(Canvas2Image.saveAsJPEG(canvas));
</code>```

You are using Save as function and still use the old canvas object.

Title: html2canvas not display all div as jpeg

Body:
I use htmlCanvas in angular to make div as jpeg and display it.
What happens is that the jpeg display only the part of the div that I see , as a printScreen.
The JS:

$(function () {
        $("#btnSave").click(function () {
            html2canvas($("#widget"), {
                onrendered: function (canvas) {
                    document.body.appendChild(canvas);

                    // Convert and download as image
                    Canvas2Image.saveAsJPEG(canvas);
                     $("#img-out").append(canvas);

                    //document.body.removeChild(canvas);
                }
            });
        });
    });

Body:
Try modifying the code as below

  $("#img-out").append(Canvas2Image.saveAsJPEG(canvas));

You are using Save as function and still use the old canvas object.


问:
sql server invalid object name - but tables are listed in SSMS tables list
I am attempting to create a Stored Procedure for a newly created database. However the SSMS intellisense does not recognize more than half of the tables which have been created.

For example whilst in the left hand column under tables I have a table dbo.Room, when I type "dbo." in the new query window, that table is not listed, in fact only 17 out of 37 tables are listed.

I can see no difference between the tables listed by intellisense and those not. If I manually type dbo.Room, it is underlined, with an error of

Invalid Object Name 'dbo.Room'..

Have I missed something in setting up the tables?

UPDATE: I have tried refresh of the tables list (several times)

答:
Solved for SSMS 2016.

Had a similar problem, but Intellisense was not in Edit menu.

What seemed to fix it was turning Intellisens on and off, right click on the SQL editor and click 'Intellisense Enabled'. Right click again on 'Intellisense Enabled' to turn it back on again. Ctr Q, I also does this.

This solved the problem, and also I know get the Intellisense on the Edit menu.


问:
Subtract x days from day of Month
I have a date which is coming in the form of 21,23,24,25.....

What I want is to subtract 4 days from current day of the month.

My attempt is reported below but it is giving me dates in the form of dd/mm/yyyy. I just want the day.

```<code>Calendar cal=Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);
Date curdteMinusFourDays=cal.getTime();
String curdteMinusFourDaysStr=curdteMinusFourDays.toString();
System.out.println(curdteMinusFourDays);

tripDate.click();

List<WebElement> listofdates=CommonBrowserSetup.driver.findElements(By.tagName("td"));
for (int i=1;i<=listofdates.size();i++){
    System.out.println(listofdates.get(i).getText());
    String d1=listofdates.get(i).getText();
    if(d1.contains(curdteMinusFourDaysStr)){
        listofdates.get(i).click();
        break;
    }
}
</code>```

答:
you should do

System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); //after you have subtracted

for more variations have a look at https://stackoverflow.com/a/7226186/2551236

Title: Subtract x days from day of Month

Body:
I have a date which is coming in the form of 21,23,24,25.....

What I want is to subtract 4 days from current day of the month.

My attempt is reported below but it is giving me dates in the form of dd/mm/yyyy. I just want the day.

Calendar cal=Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);
Date curdteMinusFourDays=cal.getTime();
String curdteMinusFourDaysStr=curdteMinusFourDays.toString();
System.out.println(curdteMinusFourDays);

tripDate.click();

List<WebElement> listofdates=CommonBrowserSetup.driver.findElements(By.tagName("td"));
for (int i=1;i<=listofdates.size();i++){
    System.out.println(listofdates.get(i).getText());
    String d1=listofdates.get(i).getText();
    if(d1.contains(curdteMinusFourDaysStr)){
        listofdates.get(i).click();
        break;
    }
}


问:
Invoking a rest api client
I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is

```<code>package org.subhayya.amazonws.mobileanalytics;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class MobileAnalyticsModel {

    private String name;
    private Date created;
    private String location;
    private String prize;
    private String requirement;

    public MobileAnalyticsModel() {

    }
    public MobileAnalyticsModel(String name, String location, String prize, String requirement) {

        this.name = name;
        this.location = location;
        this.prize = prize;
        this.requirement = requirement;
        this.created = new Date();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPrize() {
        return prize;
    }

    public void setPrize(String prize) {
        this.prize = prize;
    }

    public String getRequirement() {
        return requirement;
    }

    public void setRequirement(String requirement) {
        this.requirement = requirement;
    }
}
</code>```

this is the json response of the created api:

and
this is my sample test code for invoking rest api:

```<code>package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

public class SampleTestREstClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient( );
        String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                .request(MediaType.APPLICATION_JSON)
                .get(String.class);

        System.out.println(reponse);
    }}
</code>```

then i got full json response.. as

```<code> [{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]
</code>```

But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below

```<code>Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
        client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                    .request(MediaType.APPLICATION_JSON)
                    .get(MobileAnalyticsModel.class);

System.out.println(reponse.getName());
</code>```

But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.

how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance

答:
Your response is a string. The simplest way to access elements of your JSON-response is to convert the resonse to a Json-Object. Then you can access the fields easily by their name.
Have a look at:
How to parse JSON in Java</p>

Title: Invoking a rest api client

Body:
I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is

package org.subhayya.amazonws.mobileanalytics;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class MobileAnalyticsModel {

    private String name;
    private Date created;
    private String location;
    private String prize;
    private String requirement;

    public MobileAnalyticsModel() {

    }
    public MobileAnalyticsModel(String name, String location, String prize, String requirement) {

        this.name = name;
        this.location = location;
        this.prize = prize;
        this.requirement = requirement;
        this.created = new Date();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPrize() {
        return prize;
    }

    public void setPrize(String prize) {
        this.prize = prize;
    }

    public String getRequirement() {
        return requirement;
    }

    public void setRequirement(String requirement) {
        this.requirement = requirement;
    }
}

this is the json response of the created api:

and
this is my sample test code for invoking rest api:

package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

public class SampleTestREstClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient( );
        String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                .request(MediaType.APPLICATION_JSON)
                .get(String.class);

        System.out.println(reponse);
    }}

then i got full json response.. as

 [{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]

But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below

Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
        client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                    .request(MediaType.APPLICATION_JSON)
                    .get(MobileAnalyticsModel.class);

System.out.println(reponse.getName());

But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.

how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance


问:
make null value as X sql server
i have problem.., i want to display the null value as 'X'
i has been using the case statement but still failed,
i already using Isnull and failed too.

```<code>DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @X AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(code)
FROM (SELECT DISTINCT code FROM edrsDB..tbl_users where area='west' ) AS status

SET @DynamicPivotQuery =
N'SELECT date, '+ @ColumnName +'
FROM (
SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DatePart(MM, [Date]) = 3
 And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
And date IS NOT NULL
 ) AS x
 PIVOT
 (
max(status)
FOR userid IN (' + @ColumnName + ')
) AS PVTTable'
 EXEC sp_executesql @DynamicPivotQuery
</code>```

this is ouput.. , i want null to be display as 'X'

output

答:
You can use ISNULL

```<code>ISNULL(<some_column/some_stuff>, 'X')
</code>```

'X' would be the value displayed instead of the first parameter if first parameter result is null

Title: make null value as X sql server

Body:
i have problem.., i want to display the null value as 'X'
i has been using the case statement but still failed,
i already using Isnull and failed too.

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @X AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(code)
FROM (SELECT DISTINCT code FROM edrsDB..tbl_users where area='west' ) AS status

SET @DynamicPivotQuery =
N'SELECT date, '+ @ColumnName +'
FROM (
SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DatePart(MM, [Date]) = 3
 And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
And date IS NOT NULL
 ) AS x
 PIVOT
 (
max(status)
FOR userid IN (' + @ColumnName + ')
) AS PVTTable'
 EXEC sp_executesql @DynamicPivotQuery

this is ouput.. , i want null to be display as 'X'

output

Body:
You can use ISNULL

ISNULL(<some_column/some_stuff>, 'X')

'X' would be the value displayed instead of the first parameter if first parameter result is null