问:
foreach and or if array statement
I have a profile that shows profiles in a list. as shown in the image below.

users table

```<code> id    |  email  |  full_name  |  job_title  | bio |  profile_photo
</code>```

images table

```<code> image_id  | id  | artist_img
</code>```

CODE

```<code><?php

$db = dbconnect();
$stmt = $db->prepare('SELECT
 users.email,
 users.full_name,
 users.job_title,
 users.bio,
 users.profile_photo,
 images.id,
 images.artist_img
FROM users
INNER JOIN images ON users.id=images.id GROUP BY images.id');
$stmt->execute();
$result = $stmt->get_result();

while (($row = mysqli_fetch_assoc($result)) != false) {

        $id = $row['id'];
        $full_name = $row['full_name'];
        $email = $row['email'];
        $job_title = $row['job_title'];
        $bio = $row['bio'];
        $ProfilePhoto = $row['profile_photo'];
        $artist_img = $row['artist_img'];

        if (isset($ProfilePhoto) && ! empty($ProfilePhoto)) {
            $image = "$ProfilePhoto";
        } else {
            $image = "avatar.jpg";
       }

   echo "<div class='container team-wrap'>
           <div class='row'>
             <div class='col-md-6'>
                <img class='img-responsive' src='artist/$image'>
               </div>
                 <div class=\"col-md-6\">
                    <strong>$full_name<br>$job_title</strong>
                      <br>
                      <p>$bio</p>
                      <a href='mailto:$email' class='btn btn-info'>Contact Me</a>
                </div>
             </div>
          </div>

          <div class=\"container space team-wrap\">
           <div class=\"row\">
              <div class=\"col-lg-12\">
                    <div id=\"gallery-slider\" class=\"slider responsive\">
                      <div>";

                          echo"
                        <img src=\"gallery/$artist_img\" alt=\"\"></a>";

                      echo "</div>
                    </div>
                  <hr>
               </div>
            </div>
        </div>";
    }
 ?>
</code>```

Problem area

```<code>echo"<img src=\"gallery/$artist_img\" alt=\"\"></a>";
</code>```

The issue I am having is that it repeats the profile for each image if the user has 5 images  it will add 5 profiles 1 for each img.

and does not show the other users profile at all. show how it shows up is look at the image for example its got 4 images under profile 1 and it shows there profile pic.. well it repats all that info for each image I want the pics that have the same id as the user to show up as a slider like below..

and it also refuses to show the other profiles of other users.

答:
yes because it is not seeing the variable because you echo it as text

```<code>echo"<img src=\"gallery/$artist_img\" alt=\"\"></a>";
</code>```

should be

```<code>$r=0;
foreach ($images as $image.id){
    [$artist_img=$images[$r];
    echo "<img src=\"gallery/".$artist_img."\" alt=\"\"></a>";
    $r++;
    }
</code>```

//

i don't like to echo to much html because very easy to make a mistake that way i prefer it is to stay in html and just echo my variable like the but that is just me

```<code><html>
   <body>
      <a><img src="gallery/<? php echo $artist_img; ?>" alt=""></a>
   </body>
</html>
</code>```

do you see here you fetch the variable for the picture as single row

```<code>$artist_img = $row['artist_img'];
</code>```

you need to make it a array because it is a array you must remember using inner generates a number of pieces of data, maybe for you it will be better to run 2 query second query loads the images.inner join is useful for some people but complex and dont really give any advantage because still searches the whole tables twice to get the results
something like this might work for for you

```<code> $artist_img2=array();
//because there are more then one piece of data in it
$artist_img2 = $row['images'];
//then you need to do another loop to put the data in variables or echo them out
// in the loop
    //note the row refers to id and not image.id because in the inner array the key will be id
     $artist_img3=row2['id'];
     echo "<img src=\"gallery/".$artist_img3."\" alt=\"\"></a>";
     //end loop
</code>```

Title: foreach and or if array statement

Body:
I have a profile that shows profiles in a list. as shown in the image below.

users table

 id    |  email  |  full_name  |  job_title  | bio |  profile_photo

images table

 image_id  | id  | artist_img

CODE

<?php

$db = dbconnect();
$stmt = $db->prepare('SELECT
 users.email,
 users.full_name,
 users.job_title,
 users.bio,
 users.profile_photo,
 images.id,
 images.artist_img
FROM users
INNER JOIN images ON users.id=images.id GROUP BY images.id');
$stmt->execute();
$result = $stmt->get_result();

while (($row = mysqli_fetch_assoc($result)) != false) {

        $id = $row['id'];
        $full_name = $row['full_name'];
        $email = $row['email'];
        $job_title = $row['job_title'];
        $bio = $row['bio'];
        $ProfilePhoto = $row['profile_photo'];
        $artist_img = $row['artist_img'];

        if (isset($ProfilePhoto) && ! empty($ProfilePhoto)) {
            $image = "$ProfilePhoto";
        } else {
            $image = "avatar.jpg";
       }

   echo "

                    $full_name
$job_title

$bio

                      Contact Me

";

                          echo"
                        ";

                      echo "

";
    }
 ?>

Problem area

echo"";

The issue I am having is that it repeats the profile for each image if the user has 5 images  it will add 5 profiles 1 for each img.

and does not show the other users profile at all. show how it shows up is look at the image for example its got 4 images under profile 1 and it shows there profile pic.. well it repats all that info for each image I want the pics that have the same id as the user to show up as a slider like below..

and it also refuses to show the other profiles of other users.

Body:
yes because it is not seeing the variable because you echo it as text

echo"<img src=\"gallery/$artist_img\" alt=\"\"></a>";

should be

$r=0;
foreach ($images as $image.id){
    [$artist_img=$images[$r];
    echo "<img src=\"gallery/".$artist_img."\" alt=\"\"></a>";
    $r++;
    }

//

i don't like to echo to much html because very easy to make a mistake that way i prefer it is to stay in html and just echo my variable like the but that is just me

<html>
   <body>
      <a><img src="gallery/<? php echo $artist_img; ?>" alt=""></a>
   </body>
</html>

do you see here you fetch the variable for the picture as single row

$artist_img = $row['artist_img'];

you need to make it a array because it is a array you must remember using inner generates a number of pieces of data, maybe for you it will be better to run 2 query second query loads the images.inner join is useful for some people but complex and dont really give any advantage because still searches the whole tables twice to get the results
something like this might work for for you

 $artist_img2=array();
//because there are more then one piece of data in it
$artist_img2 = $row['images'];
//then you need to do another loop to put the data in variables or echo them out
// in the loop
    //note the row refers to id and not image.id because in the inner array the key will be id
     $artist_img3=row2['id'];
     echo "<img src=\"gallery/".$artist_img3."\" alt=\"\"></a>";
     //end loop


来源: stackexchange

问:
Python - read excel data when format changes every time

I get an excel from someone and I need to read the data every month. The format is not stable each time, and by saying "not stable" I mean:

Where the data starts changes: e.g. Section A may start on row 4, column D this time, but next time it may start at row 2, column E.

Under each section there are tags. The number of tags may change as well. But every time I only need the data in tag_2 and tag_3 (these two will always show up)

The only data that I need is from tag_2, tag_3, for each month (month1 - month8). And I want to find a way using Python first locate the section name, then find tag_2, tag_3 under that section, then get the data for month1 to month8 (number of months may change as well).

Please note that I do NOT want to locate the data that I need by specifying locations in excel since the locations change every time. How to I do this?

The end product should be a pandas dataframe that has monthly data for tag_2, tag_3, with a column that says which section the data come from.

Thanks.

答:
I think you can directly read it as a comma separated text file. Based on what you need you can look at the tag2 ant tag3 for each line.</p>

```<code>with open(filename, "r") as fs:
    for line in fs:
        cell_list = line.split(",")
        # This point you will have all elements on the line as a list
        # you can check for the size and implement your logic
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think you can directly read it as a comma separated text file. Based on what you need you can look at the tag2 ant tag3 for each line.

with open(filename, "r") as fs:
    for line in fs:
        cell_list = line.split(",")
        # This point you will have all elements on the line as a list
        # you can check for the size and implement your logic


问:
Math.min give NaN
I am creating array using $.map as below

```<code>var correctScores = $('[id^="dvAns_"] input[type="text"]').map(function () {
   return $(this).val().trim() == "" ? 0 : parseFloat($(this).val());
}).get();
</code>```

it gives me array as [5, 0]

when I am writing Math.min(correctScores) it returns NaN instead of 0.

Why so?

答:
It needs to be out of array, like this;</p>

```<code>Math.min(correctScores[0],correctScores[1]); // 0
</code>```

Title: Math.min give NaN

Body:
I am creating array using $.map as below

var correctScores = $('[id^="dvAns_"] input[type="text"]').map(function () {
   return $(this).val().trim() == "" ? 0 : parseFloat($(this).val());
}).get();

it gives me array as [5, 0]

when I am writing Math.min(correctScores) it returns NaN instead of 0.

Why so?

Body:
It needs to be out of array, like this;

Math.min(correctScores[0],correctScores[1]); // 0

ContentLicense: CC BY-SA 4.0


问:
Might a State pattern help if I have only a few states?
If something has only two to three states, is it overkill to use the State pattern?</p>

答:
We can't say much in your precise case, because your give too little information.

But in general ...

Other expressed opinions may differ, but ...

The Agile movement is gaining a lot of strengh.
They would recommend YAGNI (You Aren't Gonna Need It).

The idea is to delay complexity until later, because :

We developpers tend to love complexity, and sometimes put it where it is not needed.

You will understand your code better later ; and then you might find a simpler solution.

You user (or the person who specifies what to do, even if that is you) will have used your software later, so the requirements are likely to change. So any complexity anticipated might prove unusable at that point.

Even in the (rare) case that you would later add exactly the same complexity that you would add now ... In the mean time, your code base is simpler, so your other coding activities are simpler and faster. That is also a gain.

Also consider that your time is not infinite, and possibly someone pays for this (even you if it is your free time, or training time). Your effort might be more useful if spend on the current problem, rather that spending time for the future...

That said, if you enjoy the idea, go for it, follow your dreams ! :-)

ContentLicense: CC BY-SA 2.5


答:
You will have to use apply to be able to use Math.min() in connection with an array. In its native form it expects individual arguments.

See here: Math.min.apply(0, array) - why?

Title: Math.min give NaN


问:
Git ignore SSH key and prompt for credential
I would like to push code to a Github repository from a location that has been configured with a read-only deploy key.

Currently, a git push results in:

ERROR: The key you are authenticating with has been marked as read only.
  fatal: Could not read from remote repository.

Please make sure you have the correct access rights

Is there a way to trigger a one-time exception that prompts me to enter my credentials instead?

答:
If you don't want to change the URL of your existing remote, then you can add a new one:

```<code>git remote add https https://github.com/username/repo.git
git push https
</code>```

Then you don't have to change back and forth.

Body:
If you don't want to change the URL of your existing remote, then you can add a new one:

git remote add https https://github.com/username/repo.git
git push https

Then you don't have to change back and forth.


答:
Assuming that the (presumably manually pasted) block of information is unlikely to end up in the very bottom-right corner of the excel sheet, you could simply iterate over rows and columns (set maximum values for each to prevent long searching times) until you find a familiar value (such as "Section A") and go from there.

Unless I misunderstood you, the rest of the format should consistent between the months so you can simply assume that "month_1" is always one cell up and two to the right of that initial spot.

I have not personally worked with excel sheets in python, so I cannot state whether the following is possible in python, but it definitely works in ExcelVBA:

You could just as well use the Range.find() method to find the value "Section A" and continue with the same process as above, perhaps writing any results to a txt file and calling your python script from there if neccessary.

I hope this helps a little.

Title: Python - read excel data when format changes every time

Body:
I get an excel from someone and I need to read the data every month. The format is not stable each time, and by saying "not stable" I mean:

Where the data starts changes: e.g. Section A may start on row 4, column D this time, but next time it may start at row 2, column E.

Under each section there are tags. The number of tags may change as well. But every time I only need the data in tag_2 and tag_3 (these two will always show up)

The only data that I need is from tag_2, tag_3, for each month (month1 - month8). And I want to find a way using Python first locate the section name, then find tag_2, tag_3 under that section, then get the data for month1 to month8 (number of months may change as well).

Please note that I do NOT want to locate the data that I need by specifying locations in excel since the locations change every time. How to I do this?

The end product should be a pandas dataframe that has monthly data for tag_2, tag_3, with a column that says which section the data come from.

Thanks.


问:
Why won't my changes in git go through?
All I wanted to do was to add all files.

Now I got directories that are just icons and I never saw something like that before.

I just wanted to add all files. I did

```<code>git add *
git commit -m "added"
git push
</code>```

And now I got this incomprehensible mess.

How can you explain this state?

答:
You can use code below on cmd, cli, shell or git bash.

git status

git add -A

git commit -m "[your commit message]"

git push origin {your-branch}

example:

git status [enter]

git add -A [enter]

git commit -m "new commit" [enter]

git push origin master [enter]

Don't use "git add .", because it will overwrite all of your code.

Title: Why won't my changes in git go through?

Body:
All I wanted to do was to add all files.

Now I got directories that are just icons and I never saw something like that before.

I just wanted to add all files. I did

git add *
git commit -m "added"
git push

And now I got this incomprehensible mess.

How can you explain this state?


问:
What is this syntax in ES6 or ES7?
I came across this syntax which I believe is ES6 or ES7. What do these lines of code do?</p>

```<code>module.exports = async (taskData) => {
  // do stuff
}
</code>```

答:
It exports an asynchronous arrow function which takes in an argument taskData. The asynchronous function is new syntax that is set to come with this year's release, ES2017, called the async function, though the rest of the code is ES6 (ES2015) and ES5 (ES2011). It goes hand-in-hand with await and returns a Promise.

It's primarily useful to clean up promise chains, where the code can get really messy. Consider this example using promises, found here:

```<code>function loadStory() {
  return getJSON('story.json').then(function(story) {
    addHtmlToPage(story.heading);

    return story.chapterURLs.map(getJSON)
      .reduce(function(chain, chapterPromise) {
        return chain.then(function() {
          return chapterPromise;
        }).then(function(chapter) {
          addHtmlToPage(chapter.html);
        });
      }, Promise.resolve());
  }).then(function() {
    addTextToPage("All done");
  }).catch(function(err) {
    addTextToPage("Argh, broken: " + err.message);
  }).then(function() {
    document.querySelector('.spinner').style.display = 'none';
  });
}
</code>```

The example above fetches a story, and iterates through all the chapters and adds them to the HTML. It works, but it can be very messy and hard to follow if you've got lots of stuff to do. Instead, you can use async and await, which is just syntactic sugar, but makes it much more clean:

```<code>async function loadStory() {
  try {
    let story = await getJSON('story.json');
    addHtmlToPage(story.heading);
    for (let chapter of story.chapterURLs.map(getJSON)) {
      addHtmlToPage((await chapter).html);
    }
    addTextToPage("All done");
  } catch (err) {
    addTextToPage("Argh, broken: " + err.message);
  }
  document.querySelector('.spinner').style.display = 'none';
}
</code>```

The above is (in my opinion) way more clean and easy to follow, versus the messy promise chain in the first example.

Title: What is this syntax in ES6 or ES7?

Body:
I came across this syntax which I believe is ES6 or ES7. What do these lines of code do?

module.exports = async (taskData) => {
  // do stuff
}

Body:
It exports an asynchronous arrow function which takes in an argument taskData. The asynchronous function is new syntax that is set to come with this year's release, ES2017, called the async function, though the rest of the code is ES6 (ES2015) and ES5 (ES2011). It goes hand-in-hand with await and returns a Promise.

It's primarily useful to clean up promise chains, where the code can get really messy. Consider this example using promises, found here:

function loadStory() {
  return getJSON('story.json').then(function(story) {
    addHtmlToPage(story.heading);

    return story.chapterURLs.map(getJSON)
      .reduce(function(chain, chapterPromise) {
        return chain.then(function() {
          return chapterPromise;
        }).then(function(chapter) {
          addHtmlToPage(chapter.html);
        });
      }, Promise.resolve());
  }).then(function() {
    addTextToPage("All done");
  }).catch(function(err) {
    addTextToPage("Argh, broken: " + err.message);
  }).then(function() {
    document.querySelector('.spinner').style.display = 'none';
  });
}

The example above fetches a story, and iterates through all the chapters and adds them to the HTML. It works, but it can be very messy and hard to follow if you've got lots of stuff to do. Instead, you can use async and await, which is just syntactic sugar, but makes it much more clean:

async function loadStory() {
  try {
    let story = await getJSON('story.json');
    addHtmlToPage(story.heading);
    for (let chapter of story.chapterURLs.map(getJSON)) {
      addHtmlToPage((await chapter).html);
    }
    addTextToPage("All done");
  } catch (err) {
    addTextToPage("Argh, broken: " + err.message);
  }
  document.querySelector('.spinner').style.display = 'none';
}

The above is (in my opinion) way more clean and easy to follow, versus the messy promise chain in the first example.


问:
How do I use JQuery to add an event to a textbox when the user pushes enter?
And please don't submit the form when the user pushes enter on THAT SPECIFIC textbox.</p>

答:
```<code>#("#id_textbox").keydown(function(event){
         if(event.keyCode == 13){
                //fire
         }
}
</code>```

will this work?

Body:
#("#id_textbox").keydown(function(event){
         if(event.keyCode == 13){
                //fire
         }
}

will this work?


问:
How to connect to Websocket Server from PHP Server NOT Javascript
I'm running a ratchet websocket server.  Due to some complicated circumstances I need to be able to talk to this websocket server via my PHP Server in realtime not Javascript to be able to send it information that will then be passed on later to any clients connected to it.

I did some looking around on stackoverflow but everything is about how to create a websocket server with PHP which is not what I'm looking for.

Below is a visual of what I'm trying to achieve.

The key here is how to connect to a Websocket server like ratchet using PHP?

Things I have tried/considered:

I've considered using the serialization approach.  This would be serializing in the database and unserializing.  I'm not sure if this is better than this approach, please advise.

This is where I started : Ratchet Store Connection of User & Send Message Outside of Server Instance

答:
I would suggest using REST as API layer for communication between your Symfony app and Ratchet app. Because it doesn't make much sense to use Websocket from your Symfony app. Websockets are used for bidirectional real-time communication, whereas you only need to send a piece of data from your Symfony app. For this purpose, HTTP REST API would be more convenient.
To wrap it up, in your Ratchet app you use 2 servers (Ratchet allows creating as many servers as you want within a single app): web-socket server and http-server. In your Symfony app, you send traditional HTTP requests to your Ratchet server.

You can create multiple Ratchet servers in a single app like so:

```<code>// 1. Create the event loop
$loop = React\EventLoop\Factory::create();

// 2. Create servers
// websocket
$webSock = new React\Socket\Server($loop);
new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer( $wsConnectionsHandler )
    ),
    $webSock
);
$webSock->listen($portWS, '0.0.0.0');

// http
$httpSock = new React\Socket\Server($loop);
new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        $HTTPConnectionsHandler
    ),
    $httpSock
);
$httpSock->listen($portHTTP, '0.0.0.0');

// 3. Run the loop
$loop->run();
</code>```

How do I pass the information from the http server to the websocket server?

React/Ratchet app is an event-driven app, like a typical NodeJS app. So the best way for the components of the app to communicate with each other is to dispatch/subscribe events. For example, you create $eventDispatcher object, pass it to every component (http-handler & ws-handler), and then use $eventDispatcher->subscibe(eventName, func) and $eventDispatcher->emit(eventName, data) to subscribe to events and dispatch them accordingly.

If you are not convinced, then you need to use a Websocket Client library to connect to Websocket server. There are a few of them, just google it. I personally never used a PHP websocket-client library, so I can't recommend any.

Body:
I would suggest using REST as API layer for communication between your Symfony app and Ratchet app. Because it doesn't make much sense to use Websocket from your Symfony app. Websockets are used for bidirectional real-time communication, whereas you only need to send a piece of data from your Symfony app. For this purpose, HTTP REST API would be more convenient.
To wrap it up, in your Ratchet app you use 2 servers (Ratchet allows creating as many servers as you want within a single app): web-socket server and http-server. In your Symfony app, you send traditional HTTP requests to your Ratchet server.

You can create multiple Ratchet servers in a single app like so:

// 1. Create the event loop
$loop = React\EventLoop\Factory::create();

// 2. Create servers
// websocket
$webSock = new React\Socket\Server($loop);
new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer( $wsConnectionsHandler )
    ),
    $webSock
);
$webSock->listen($portWS, '0.0.0.0');

// http
$httpSock = new React\Socket\Server($loop);
new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        $HTTPConnectionsHandler
    ),
    $httpSock
);
$httpSock->listen($portHTTP, '0.0.0.0');

// 3. Run the loop
$loop->run();

How do I pass the information from the http server to the websocket server?

React/Ratchet app is an event-driven app, like a typical NodeJS app. So the best way for the components of the app to communicate with each other is to dispatch/subscribe events. For example, you create $eventDispatcher object, pass it to every component (http-handler & ws-handler), and then use $eventDispatcher->subscibe(eventName, func) and $eventDispatcher->emit(eventName, data) to subscribe to events and dispatch them accordingly.

If you are not convinced, then you need to use a Websocket Client library to connect to Websocket server. There are a few of them, just google it. I personally never used a PHP websocket-client library, so I can't recommend any.


问:
iOS app rejected - Your app enables the display of nearby users' locations on a map, but does not have the required privacy precautions in place
My iOS app rejected from apple due to following reason :-

Your app enables the display of nearby users' locations on a map, but
  does not have the required privacy precautions in place.

And they are sharing this screenshot of my app with rejection message.

In my app, I am using user’s location for showing near by events on the Map. Also I have enabled option showing user’s location on the Map.

I am using following code for setting up location services into my app.

```<code>//Declarting objects in .h file
CLGeocoder *geocoder;
CLPlacemark *placemark;

@property (nonatomic,retain) CLLocationManager *locationManager;

//Calling this method from viewDidLoad for setup location services..
-(void)getUserCurrentLocation
{
    geocoder = [[CLGeocoder alloc] init];

    self.locationManager=[[CLLocationManager alloc]init];
    self.locationManager.delegate=self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter=kCLDistanceFilterNone;

    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    {
        [_locationManager requestWhenInUseAuthorization];
    }

    [self.locationManager startUpdatingLocation];
}

-(void)StopUpdateLOcation
{
    if([CLLocationManager locationServicesEnabled])
    {
        [self.locationManager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil)
    {

        //Saving location
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.latitude] forKey:@"CurrentLocationLatitude"];
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.longitude] forKey:@"CurrentLocationLongitude"];

       //Here reverseGeocodeLocation method for fetching address from location

        [self StopUpdateLOcation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
}
</code>```

Also I have added property “Privacy - Location When In Use Usage Description” with proper message. Also I have disabled the location service when got the location.

Not sure, why they are rejecting app. Did I miss something.?

How can I resolved this issue.?

Any help would be appreciated.

答:
Have you added this message to iTunes store description:

Continued use of GPS running in the background can dramatically
  decrease battery life.

e.g: check the last line in Google Maps description:

https://itunes.apple.com/us/app/google-maps-navigation-transit/id585027354?mt=8

Body:
My iOS app rejected from apple due to following reason :-

Your app enables the display of nearby users' locations on a map, but
  does not have the required privacy precautions in place.

And they are sharing this screenshot of my app with rejection message.

In my app, I am using user’s location for showing near by events on the Map. Also I have enabled option showing user’s location on the Map.

I am using following code for setting up location services into my app.

//Declarting objects in .h file
CLGeocoder *geocoder;
CLPlacemark *placemark;

@property (nonatomic,retain) CLLocationManager *locationManager;

//Calling this method from viewDidLoad for setup location services..
-(void)getUserCurrentLocation
{
    geocoder = [[CLGeocoder alloc] init];

    self.locationManager=[[CLLocationManager alloc]init];
    self.locationManager.delegate=self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter=kCLDistanceFilterNone;

    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    {
        [_locationManager requestWhenInUseAuthorization];
    }

    [self.locationManager startUpdatingLocation];
}

-(void)StopUpdateLOcation
{
    if([CLLocationManager locationServicesEnabled])
    {
        [self.locationManager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil)
    {

        //Saving location
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.latitude] forKey:@"CurrentLocationLatitude"];
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.longitude] forKey:@"CurrentLocationLongitude"];

       //Here reverseGeocodeLocation method for fetching address from location

        [self StopUpdateLOcation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
}

Also I have added property “Privacy - Location When In Use Usage Description” with proper message. Also I have disabled the location service when got the location.

Not sure, why they are rejecting app. Did I miss something.?

How can I resolved this issue.?

Any help would be appreciated.


问:
How Pass parameters and access them in javascript
```<code><html>
<body>
<form action="">
<script>
 for(i=0;i<50;i++)
 {
  document.writeln("<input type='button' value ='"+i+"'        onclick='clicked(i)'/>");

 }
function clicked(Number x)
{
 alert("selected:" +x);
}
</script>
</form>
</body>
</html>
</code>```

I want to know which button is selected in this code how to perform that please can someone help me

答:
Check out how to declare functions in JavaScript here:
https://www.w3schools.com/js/js_function_parameters.asp</p>

Body:
<form action="">

</form>

I want to know which button is selected in this code how to perform that please can someone help me


问:
Common libraries in a large team
Assume you have five products, and all of them use one or more of the company's internal libraries, written by individual developers.

It sounds simple but in practice, I found it to be very difficult to maintain.

How do you deal with the following scenarios:

A developer unintentionally introduces a bug and breaks everything in production.

Every library has to mature, That means the API needs to evolve, so how do you deploy the updated version to production if every developer needs to update/test their code while they are extremely busy on other projects? Is this a resource and time issue?

Version control, deployment,and usage. Would you store this in one global location or force each project to use, say, svn:externals to "tie" a library?

I've found that it is extremely hard to come up with a good strategy. My own pet theory is this:

Each common library has to have a super-thorough set of tests or else it should never be common, even if it means someone else duplicates the effort. Duplicate untested code is better than common untested code (you break only one project).

Each common library has to have a dedicated maintainer (can be offset by a really good test suite in a smaller team).

Each project should check out the version of the library that is known to work with it. This means a developer does not have to get pulled away to update API usage, as the common code gets updated. Which it will be. Every non-trivial piece of code evolves over months and years.

Thank you for your thoughts on this!

答:
I used to work in a similar situation to what you're describing, only my company had dozens of software products.  I worked on the team that was responsible for maintaining and upgrading the core set of libraries that everyone else used.

We dealt with those scenarios as follows:

Test the heck out of the core libraries.  Maintaining duplicate code is a nightmare.  You're not just maintaining the core and one copy.  Somewhere in your company's source control there are several copies of the same code.  We had dozens of products, so that would have meant dozens of copies.  Hunt them down and kill them.

We had a small team of 10-12 developers dedicated to maintaining the core library and its test suites.  We were also responsible for fielding calls from the other 1100 developers in the company about how to use the core library, so as you can imagine, we were very busy.

Each other project needs to work with the version of the core library that it is known to work with.  You can use version control branches to test new releases of the core library with old products to make sure you don't break code that works.  If the core team does a thorough job of testing, this should go very smoothly.  The only time this ever got really complicated for us was when the core API changed, or when we flat out screwed something up.  Even if you're very confident in your core testing, use branches to test individual products.

OwnerDisplayName: Andrei

Title: Common libraries in a large team

LastEditorDisplayName: Roger Lipscombe

OwnerDisplayName: Bill the Lizard


问:
How to make PHP code like this?
```<code>$this->admin_model->list_user()
</code>```

I am writing most of the time my programs in OOP PHP. but I am writing like this...

```<code>$this->hello_world().
</code>```

The above code is CodeIgniter and I think CakePHP also following same coding style.

Please give me simple example how to make my "hello_world" like

```<code>$this->something->hello_world().
</code>```

Thanks you on advance.

Surya

答:
Its nothing special; $this->admin_model is a property which contains an object, and for all purposes is identical to $object->method();

A step by step would look like:

```<code>$this->property = new MyObjectWIthADoItMethod();
$this->property->DoIt();
</code>```

Title: How to make PHP code like this?

Body:
$this->admin_model->list_user()

I am writing most of the time my programs in OOP PHP. but I am writing like this...

$this->hello_world().

The above code is CodeIgniter and I think CakePHP also following same coding style.

Please give me simple example how to make my "hello_world" like

$this->something->hello_world().

Thanks you on advance.

Surya

Body:
Its nothing special; $this->admin_model is a property which contains an object, and for all purposes is identical to $object->method();

A step by step would look like:

$this->property = new MyObjectWIthADoItMethod();
$this->property->DoIt();


问:
What's wrong with this subscription? I get updates but the view is not refreshed
I'm trying to refresh a counter with a subscription done with ApolloGraphql.
It's almost workingsince I can see in the dev-tool the following data coming from the server on event:

{
  "type": "subscription_data",
  "id": 0,
  "payload": {
    "data": {
      "dealVoteAdded": {
        "voteCount": 16,
        "__typename": "VoteType"
      }
    }
  }
}
```

<p>Before this event, the counter was 15. It should go to 16 since that's the new value I get but nothing changes. <strong>The view is never refreshed. Why?</strong></p>

<p>Here is my code:</p>

<p><strong>ParentComponent</strong>
</p>

```export class DealVoteComponent implements OnInit, OnDestroy {

  public voteCount$;
  private voteCounterSub$;

  @Input() deal: Deal;

  constructor(private dealService: DealService) { }

  ngOnInit() {
    /**
     * Get update of dealVoteCount
     */
    this.voteCount$ = this.dealService.getDealVote({
      externalId: this.deal.externalId
    })
      .map(({data}) => {
        console.log("voteCount$ data", data);
        return data.getDealVote.voteCount;
      })

    /**
     * Subscription of dealVoteCount
     */
    this.voteCounterSub$ = this.dealService.dealVoteAdded({
      externalId: this.deal.externalId
    }).subscribe({
      next: (data:any) => {
        this.voteCount$.updateQuery(prev => {
          const newCount = {
            getDealVote: {
              voteCount: data.dealVoteAdded.voteCount
            }
          };
          return newCount;
        });
      },
      error(err: any): void {
        console.error('err', err);
      }
    })
  }

  ngOnDestroy() {
    this.voteCounterSub$.unsubscribe();
  }
}
```

<p><strong>View</strong>
</p>

```<dealtd-deal-vote-counter
  [voteCount]="voteCount$ | async">
</dealtd-deal-vote-counter>
```

<p><strong>Service</strong>
</p>

```@Injectable()
export class DealService {

  constructor(private apollo: Apollo) { }

  getDealVote(params) {
    const params = {
      query: getDealVote,
      variables: variables
    };
    return this.apollo.watchQuery<any>(params);
  }

  dealVoteAdded(data) {
    const params = {
      query: dealVoteAdded,
      variables: data
    };
    return getClient().subscribe(params);
  }
}
```

<p><strong>schemas</strong>
</p>

```import gql from "graphql-tag";

export const VoteCountFragment = {
  entry: gql`
    fragment vote on VoteType {
      voteCount
      __typename
    }
  `
};

export const dealVoteAdded = gql`
  subscription dealVoteAdded($externalId: String!) {
    dealVoteAdded(externalId: $externalId) {
      ...vote
    }
  }
  ${VoteCountFragment.entry}
`;

export const getDealVote = gql`
  query getDealVote($externalId: String!) {
    getDealVote(externalId: $externalId) {
      ...vote
    }
  }
  ${VoteCountFragment.entry}
`;
```

答:
I would use a BehaviorSubject observable in the service in these cases

```<code>import {BehaviorSubject} from 'rxjs/BehaviorSubject';

let bSubject = new BehaviorSubject(null);

  getDealVote(params) {
    const params = {
      query: getDealVote,
      variables: variables
    };
       bSubject.next(new value);
  }
</code>```

in the parent component

```<code>this.voteCount$ = this.dealService.bSubject
</code>```

Body:
I'm trying to refresh a counter with a subscription done with ApolloGraphql.
It's almost workingsince I can see in the dev-tool the following data coming from the server on event:

{
  "type": "subscription_data",
  "id": 0,
  "payload": {
    "data": {
      "dealVoteAdded": {
        "voteCount": 16,
        "__typename": "VoteType"
      }
    }
  }
}

Before this event, the counter was 15. It should go to 16 since that's the new value I get but nothing changes. The view is never refreshed. Why?

Here is my code:

ParentComponent

export class DealVoteComponent implements OnInit, OnDestroy {

  public voteCount$;
  private voteCounterSub$;

  @Input() deal: Deal;

  constructor(private dealService: DealService) { }

  ngOnInit() {
    /**
     * Get update of dealVoteCount
     */
    this.voteCount$ = this.dealService.getDealVote({
      externalId: this.deal.externalId
    })
      .map(({data}) => {
        console.log("voteCount$ data", data);
        return data.getDealVote.voteCount;
      })

    /**
     * Subscription of dealVoteCount
     */
    this.voteCounterSub$ = this.dealService.dealVoteAdded({
      externalId: this.deal.externalId
    }).subscribe({
      next: (data:any) => {
        this.voteCount$.updateQuery(prev => {
          const newCount = {
            getDealVote: {
              voteCount: data.dealVoteAdded.voteCount
            }
          };
          return newCount;
        });
      },
      error(err: any): void {
        console.error('err', err);
      }
    })
  }

  ngOnDestroy() {
    this.voteCounterSub$.unsubscribe();
  }
}

View

<dealtd-deal-vote-counter
  [voteCount]="voteCount$ | async">
</dealtd-deal-vote-counter>

Service

@Injectable()
export class DealService {

  constructor(private apollo: Apollo) { }

  getDealVote(params) {
    const params = {
      query: getDealVote,
      variables: variables
    };
    return this.apollo.watchQuery<any>(params);
  }

  dealVoteAdded(data) {
    const params = {
      query: dealVoteAdded,
      variables: data
    };
    return getClient().subscribe(params);
  }
}

schemas

import gql from "graphql-tag";

export const VoteCountFragment = {
  entry: gql`
    fragment vote on VoteType {
      voteCount
      __typename
    }
  `
};

export const dealVoteAdded = gql`
  subscription dealVoteAdded($externalId: String!) {
    dealVoteAdded(externalId: $externalId) {
      ...vote
    }
  }
  ${VoteCountFragment.entry}
`;

export const getDealVote = gql`
  query getDealVote($externalId: String!) {
    getDealVote(externalId: $externalId) {
      ...vote
    }
  }
  ${VoteCountFragment.entry}
`;

Body:
I would use a BehaviorSubject observable in the service in these cases

import {BehaviorSubject} from 'rxjs/BehaviorSubject';

let bSubject = new BehaviorSubject(null);

  getDealVote(params) {
    const params = {
      query: getDealVote,
      variables: variables
    };
       bSubject.next(new value);
  }

in the parent component

this.voteCount$ = this.dealService.bSubject


问:
C++ Templates - How to use static vector inside a static method
I wrote a simple test code and I am try to use a static vector inside a static method.

Here is the code.

```<code>#include <iostream>
#include <vector>

using namespace std;

template <class T1>
class A
{
  static T1 x;
  static vector<T1> v;

public:
  static void testOne();
};

template <class T1>
T1 A<T1>::x = 56;

template <class T1>
void
A<T1>::testOne()
{

  A::x = 45;
  A::v.push_back(34);

  cout << A::x << endl;
  cout << A::v.size() << endl;
}

int
main(int argc, char* argv[])
{
  A<int>::testOne();

  return 0;
}
</code>```

But when I compiled, I get the following:

```<code>static.cpp:25:6: warning: instantiation of variable 'A<int>::v' required here,
      but no definition is available [-Wundefined-var-template]
  A::v.push_back(34);
     ^
static.cpp:34:11: note: in instantiation of member function 'A<int>::testOne'
      requested here
  A<int>::testOne();
          ^
static.cpp:10:21: note: forward declaration of template entity is here
  static vector<T1> v;
                    ^
1 warning generated.
Undefined symbols for architecture x86_64:
  "A<int>::v", referenced from:
      A<int>::testOne() in static-9790dc.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I tried to add the following vector<T1>A::v;, but when I compiled, I get the following:

```<code>static.cpp:18:8: error: use of undeclared identifier 'T1'
vector<T1>A::v;
       ^
static.cpp:18:11: error: 'A' is not a class, namespace, or enumeration
vector<T1>A::v;
          ^
static.cpp:7:7: note: 'A' declared here
class A
      ^
2 errors generated.
</code>```

What is the best solution?

答:
You need to define v just like you defined x.

```<code>template <class T1>
std::vector<T1> A<T1>::v{ /* Put any initializzation paramters here */ };
</code>```

You may also omit the A:: when referencing x and v in A<T1>::testOne().

```<code>template <class T1>
void A<T1>::testOne()
{
   x = 45;
   v.push_back(34);

   cout << x << endl;
   cout << v.size() << endl;
}
</code>```

Body:
I wrote a simple test code and I am try to use a static vector inside a static method.

Here is the code.

#include <iostream>
#include <vector>

using namespace std;

template <class T1>
class A
{
  static T1 x;
  static vector<T1> v;

public:
  static void testOne();
};

template <class T1>
T1 A<T1>::x = 56;

template <class T1>
void
A<T1>::testOne()
{

  A::x = 45;
  A::v.push_back(34);

  cout << A::x << endl;
  cout << A::v.size() << endl;
}

int
main(int argc, char* argv[])
{
  A<int>::testOne();

  return 0;
}

But when I compiled, I get the following:

static.cpp:25:6: warning: instantiation of variable 'A<int>::v' required here,
      but no definition is available [-Wundefined-var-template]
  A::v.push_back(34);
     ^
static.cpp:34:11: note: in instantiation of member function 'A<int>::testOne'
      requested here
  A<int>::testOne();
          ^
static.cpp:10:21: note: forward declaration of template entity is here
  static vector<T1> v;
                    ^
1 warning generated.
Undefined symbols for architecture x86_64:
  "A<int>::v", referenced from:
      A<int>::testOne() in static-9790dc.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried to add the following vector<T1>A::v;, but when I compiled, I get the following:

static.cpp:18:8: error: use of undeclared identifier 'T1'
vector<T1>A::v;
       ^
static.cpp:18:11: error: 'A' is not a class, namespace, or enumeration
vector<T1>A::v;
          ^
static.cpp:7:7: note: 'A' declared here
class A
      ^
2 errors generated.

What is the best solution?

Body:
You need to define v just like you defined x.

template <class T1>
std::vector<T1> A<T1>::v{ /* Put any initializzation paramters here */ };

You may also omit the A:: when referencing x and v in A<T1>::testOne().

template <class T1>
void A<T1>::testOne()
{
   x = 45;
   v.push_back(34);

   cout << x << endl;
   cout << v.size() << endl;
}


问:
how to loop css value with interval
I'm trying to add css value with interval, when I try run with append it works well. But why it doesn't work when I try to increase css value like my code below.

How I can increase css value with interval?

$(document).ready(function(){
  var imgBg = $('.img-bg');
  var addBlur = $(imgBg).find('img');

  var blurVal = 0;
  var filterBlur = {
    'filter' : 'blur('+blurVal+'px)',
    '-webkit-filter': 'blur('+blurVal+'px)',
    '-moz-filter': 'blur('+blurVal+'px)',
    '-o-filter': 'blur('+blurVal+'px)',
    '-ms-filter': 'blur('+blurVal+'px)'
  };

  //$(addBlur).css(filterBlur);

function blurLoop(){
  blurVal++;
  //$('.container').append('
test '+blurVal+'
');
  $(addBlur).css(filterBlur);
}

  var interval = setInterval(function(){
    var test = blurLoop();
    if(blurVal >= 5){
      clearInterval(interval);
    }
  },1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  paddding: 0 15px;
}

.header {
  position: relative;
  overflow: hidden;
  background-color: red;
}</code>```

```

答:
$(document).ready(function(){
  var imgBg = $('.img-bg');
  var addBlur = $(imgBg).find('img');

  var blurVal = 0;

  //$(addBlur).css(filterBlur);

function blurLoop(){
  blurVal++;

   var filterBlur = {
    'filter' : 'blur('+blurVal+'px)',
    '-webkit-filter': 'blur('+blurVal+'px)',
    '-moz-filter': 'blur('+blurVal+'px)',
    '-o-filter': 'blur('+blurVal+'px)',
    '-ms-filter': 'blur('+blurVal+'px)'
  };
  //$('.container').append('
test '+blurVal+'
');
  $(addBlur).css(filterBlur);
}

  var interval = setInterval(function(){
    var test = blurLoop();

    if(blurVal >= 5){
      clearInterval(interval);
    }
  },1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  paddding: 0 15px;
}

.header {
  position: relative;
  overflow: hidden;
  background-color: red;
}</code>```

```

Title: how to loop css value with interval

Body:
I'm trying to add css value with interval, when I try run with append it works well. But why it doesn't work when I try to increase css value like my code below.

How I can increase css value with interval?

$(document).ready(function(){
  var imgBg = $('.img-bg');
  var addBlur = $(imgBg).find('img');

  var blurVal = 0;
  var filterBlur = {
    'filter' : 'blur('+blurVal+'px)',
    '-webkit-filter': 'blur('+blurVal+'px)',
    '-moz-filter': 'blur('+blurVal+'px)',
    '-o-filter': 'blur('+blurVal+'px)',
    '-ms-filter': 'blur('+blurVal+'px)'
  };

  //$(addBlur).css(filterBlur);

function blurLoop(){
  blurVal++;
  //$('.container').append('
test '+blurVal+'
');
  $(addBlur).css(filterBlur);
}

  var interval = setInterval(function(){
    var test = blurLoop();
    if(blurVal >= 5){
      clearInterval(interval);
    }
  },1000);
});

.container {
  width: 100%;
  paddding: 0 15px;
}

.header {
  position: relative;
  overflow: hidden;
  background-color: red;
}

Body:
$(document).ready(function(){
  var imgBg = $('.img-bg');
  var addBlur = $(imgBg).find('img');

  var blurVal = 0;

  //$(addBlur).css(filterBlur);

function blurLoop(){
  blurVal++;

   var filterBlur = {
    'filter' : 'blur('+blurVal+'px)',
    '-webkit-filter': 'blur('+blurVal+'px)',
    '-moz-filter': 'blur('+blurVal+'px)',
    '-o-filter': 'blur('+blurVal+'px)',
    '-ms-filter': 'blur('+blurVal+'px)'
  };
  //$('.container').append('<p>test '+blurVal+'</p>');
  $(addBlur).css(filterBlur);
}

  var interval = setInterval(function(){
    var test = blurLoop();

    if(blurVal >= 5){
      clearInterval(interval);
    }
  },1000);
});

.container {
  width: 100%;
  paddding: 0 15px;
}

.header {
  position: relative;
  overflow: hidden;
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="header">
    <div class="img-bg">
      <img src="https://unsplash.it/200/300?image=0" alt="" />
      <img src="https://unsplash.it/200/300?image=0" alt="" />
    </div>
  </div>
</div>


问:
How do I bring up the debug diagnostics tool windows while debugging my project in Visual Studio 2013 Professional?
While all the other versions and editions of Visual Studio I use on different machines bring up the Diagnostics Tools windows when I launch any of my projects in the Visual Studio debugger by pressing F5, the Visual Studio 2013 Professional edition installation I have doesn't.

It does have the diagnostic tools, though.

How do I get it to start the debug session with diagnostics and to display the diagnostics windows as well automatically upon starting a debugging session?

答:
In VS2015, it has the option "Enable Diagnostic Tools while debugging" under TOOLS->Options->Debugging->General.

But it doesn't have this feature in VS2013. It has the function Performance and Diagnostics hub under Debug menu.

It was the new feature in VS2015:

https://blogs.msdn.microsoft.com/visualstudioalm/2015/07/20/performance-and-diagnostic-tools-in-visual-studio-2015/


问:
Tableview Cell Is override from bottom
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

```<code>static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);
</code>```

答:
There are many ways to design Layout for Cell in tableview with dynamic height

here I am sharing some links related to dynamic height and cell autolayout will help to get out form your issue.

Raywenderlich : https://www.raywenderlich.com/129059/self-sizing-table-view-cells

AppCoda : http://www.appcoda.com/self-sizing-cells/

Some answer form SO :

Dynamically increase height of UILabel & TableView Cell?

Dynamic height of cell with UILabel in tableview ios

Hope this will help you to solve your issue.

Title: Tableview Cell Is override from bottom

Body:
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);


问:
SQL Query question
No particular DBMS in mind, how would I do the following:

```<code># There are many tables per one restaurant, many napkins per one table
# Pseudo SQL

SELECT RESTAURANT WHERE ID = X;
SELECT ALL TABLES WHERE RESTAURANT_ID = RESTAURANT.ID;
SELECT ALL NAPKINS WHERE TABLE_ID = TABLE.ID;
</code>```

But, all in one query? I've used a JOIN to get all the tables in the same query as restaurant, but is it possible to get all napkins for each table as well, in the same query?

答:
```<code>select * -- replace * with the columns you need...
from restaurant as r
    inner join tables as t on t.restaurant_id = r.id
    inner join napkins as n on n.table_id = t.id
where r.id = [restaurant id]
</code>```

Title: SQL Query question

Body:
No particular DBMS in mind, how would I do the following:

# There are many tables per one restaurant, many napkins per one table
# Pseudo SQL

SELECT RESTAURANT WHERE ID = X;
SELECT ALL TABLES WHERE RESTAURANT_ID = RESTAURANT.ID;
SELECT ALL NAPKINS WHERE TABLE_ID = TABLE.ID;

But, all in one query? I've used a JOIN to get all the tables in the same query as restaurant, but is it possible to get all napkins for each table as well, in the same query?


问:
Can't able to do start testing in(Internal Tester) in Testflight
I'm getting Below Error while click start testing Button in Testflight,

"This version can’t be tested because you have reached the maximum number of apps allowed for testing at once."

I don't know why this is happened,

Advice me to fix this issue

Screenshot: Here is the Screenshot for your reference

答:
This version can’t be tested because you have reached the maximum number of apps allowed for testing at once

From apple :

Your internal team, Each app can be tested by up to 25 members of your team who have been assigned the Developer or Admin role in iTunes Connect. Each member can test on up to 10 devices.
Once you’re ready, you can invite up to 2,000 users who do not need to be part of your development organization to beta test an app that you intend for public release on the App Store. A review is required for new versions of your app that contain significant changes. Up to 100 apps can be tested at a time, internally or externally.


问:
Vtiger 6.5 error after installatiion
I've just installed Vtiger 6.5 on windows xampp server, the installation went smoothly but as soon as I started the browser (localhost/vtigercrm) I get this error.

Fatal error: Cannot unset $this in C:\xampp\htdocs\vtigercrm\libraries\adodb\adodb-xmlschema.inc.php on line 160

Does anyone know what I've done wrong? I've downloaded and tried it several times, I've also changed the php.ini file according to the manual but doesn't seem to have an effect.

答:
This error may occurs in PHP 7 version. So proposed solution is below.
Please update that function with this one in file vtigercrm\libraries\adodb\adodb-xmlschema.inc.php on line 160

```<code>function Destroy() {
    ini_set("magic_quotes_runtime", $this->mgq ); //Add this line
    unset( $this );
}
</code>```

Title: Vtiger 6.5 error after installatiion

Body:
This error may occurs in PHP 7 version. So proposed solution is below.
Please update that function with this one in file vtigercrm\libraries\adodb\adodb-xmlschema.inc.php on line 160

function Destroy() {
    ini_set("magic_quotes_runtime", $this->mgq ); //Add this line
    unset( $this );
}


问:
Shortcuts for git commands
I would like to use shortcuts or aliases for git commands.

```<code>git diff
git status
git push
git pull
git stash
git branch -a
</code>```

How do I create shortcuts or aliases, is there a predefined list?

答:
More than one way to do this. Explained below with examples:

[1] Using the "alias" option provided by the git itself.

Example: git config --global alias.co checkout

Usage hence: git co

This is equivalent to making entries manually in the '~/.gitconfig' (this path since, --global is used, otherwise the .gitconfig file of the project, in which you attempting to set will be used).

```<code>[alias]
  co = checkout
</code>```

Therefore, manually making entry to the file, as specified can also be another way of setting your aliases.

for more Info

[2] Using .bash_profile/.bashrc.

Edit your ~/.bash_profile or ~/.bashrc, as below:

Example: alias go='git checkout'

Usage hence: go

(Do not forget to 'source ~/.bash_profile' or 'source ~/.bashrc' after the changes to the file, based on your case).

for more Info

So, if you clearly see, the second way is to further put the shorthand/aliases to the git-command usage (for your profile).

Also, the aliases meant for ease of usability, hence what you prefer/at ease, is what you can add (like: i can say probably, Giraffe = git checkout, if that is my ease).

Title: Shortcuts for git commands

Body:
I would like to use shortcuts or aliases for git commands.

git diff
git status
git push
git pull
git stash
git branch -a

How do I create shortcuts or aliases, is there a predefined list?

Body:
More than one way to do this. Explained below with examples:

[1] Using the "alias" option provided by the git itself.

Example: git config --global alias.co checkout

Usage hence: git co

This is equivalent to making entries manually in the '~/.gitconfig' (this path since, --global is used, otherwise the .gitconfig file of the project, in which you attempting to set will be used).

[alias]
  co = checkout

Therefore, manually making entry to the file, as specified can also be another way of setting your aliases.

for more Info

[2] Using .bash_profile/.bashrc.

Edit your ~/.bash_profile or ~/.bashrc, as below:

Example: alias go='git checkout'

Usage hence: go

(Do not forget to 'source ~/.bash_profile' or 'source ~/.bashrc' after the changes to the file, based on your case).

for more Info

So, if you clearly see, the second way is to further put the shorthand/aliases to the git-command usage (for your profile).

Also, the aliases meant for ease of usability, hence what you prefer/at ease, is what you can add (like: i can say probably, Giraffe = git checkout, if that is my ease).


问:
How to deserialize multiple objects sequentially using jackson-databind
I am using msgpack to serialize data. I have some code works fine with serializing data.

```<code>public void testJackson() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, data1);
    mapper.writeValue(out, data2);
    mapper.writeValue(out, data3);

    // TODO: How to deserialize?

}
</code>```

But now I don't know how to deserialize data.
I am not finding any solution anywhere. It will be good if anyone can help how to proceed.

答: You'll want to use one of the readValue methods from ObjectMapper - probably one that has a Reader or InputStream as the first parameter.

Body:
I am using msgpack to serialize data. I have some code works fine with serializing data.

public void testJackson() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, data1);
    mapper.writeValue(out, data2);
    mapper.writeValue(out, data3);

    // TODO: How to deserialize?

}

But now I don't know how to deserialize data.
I am not finding any solution anywhere. It will be good if anyone can help how to proceed.


问:
jQuery click event fires on parent element multiple times
https://jsfiddle.net/50Lw423g/2/

```<code>  gameLogic: function() {
    console.log("GAME LOGIC");
    alert("Your Turn!");
    var that = this;
    $(".game-screen").on("click", ".tic", function() {
      console.log("EVENT ATTACHED");
      var movesDisplay = $(this).text(),
        playerOne = that.playerOneMoves,
        moveID = +(this.id);
      if (movesDisplay !== "O" && movesDisplay !== "X") {
        that.playerOneMoves.push(moveID);
        if (playerOne.length > 2) {
          if (that.checkIfWinCondition(playerOne, that.winConditions)) {
            alert("GAME OVER!");
            that.inGame = false;
            ticTacToe.restartGame();
          }
        }
        $(this).text(that.playerFaction === "X" ? "X" : "O");
      }
    });
  },
</code>```

I'm writing a Tic-Tac-Toe game and ran into this problem - when multiple sessions are "played" click events keep compounding. Which I solved by clearing the previous click events every time before a new one is attached.

```<code>$(".game-screen").off().on("click", ".tic", function () { //do stuff }
</code>```

By the way event.stopPropagation() and event.stopImmediatePropagation() did NOT work.

Anyway, while I managed to fix the problem and understand why the click events where compounding, what I can't seem to wrap my head around is why those compounded click events kept calling the parent function gameLogic: function(). Try "playing" several sessions in a row -

console.log("GAME LOGIC");
        alert("Your Turn!");
get called exponentially more with every session. Does jQuery use the parent function to track the click events or something? Can anyone explain what's happening under the hood? Why do the event handlers keep referring to the parent function?

答:
I traced the call stack, and looked at the jQuery dispatch: function(). Actually, as it turns out, the problem wasn't with the way jQuery internally refers to it's click functions and handlers.

The culprit was on line 46. The getUserInput() attaches an event handler which in turn attaches the chooseFaction() event handler. On the next session, getUserInput() gets attached one more time and chooseFaction() is attached 2 times (+1 time from before) - so chooseFaction() fires 3 times calling generateBoard(), and in turn, calling gameLogic()etc. Thus calls to gameLogic() exponentially increasing with every iteration.

Moved $(.game-screen).off() to the restartGame() function, to remove all click events before starting a new session, as a cleaner solution.

Solution: https://jsfiddle.net/50Lw423g/4/

Body:
https://jsfiddle.net/50Lw423g/2/

  gameLogic: function() {
    console.log("GAME LOGIC");
    alert("Your Turn!");
    var that = this;
    $(".game-screen").on("click", ".tic", function() {
      console.log("EVENT ATTACHED");
      var movesDisplay = $(this).text(),
        playerOne = that.playerOneMoves,
        moveID = +(this.id);
      if (movesDisplay !== "O" && movesDisplay !== "X") {
        that.playerOneMoves.push(moveID);
        if (playerOne.length > 2) {
          if (that.checkIfWinCondition(playerOne, that.winConditions)) {
            alert("GAME OVER!");
            that.inGame = false;
            ticTacToe.restartGame();
          }
        }
        $(this).text(that.playerFaction === "X" ? "X" : "O");
      }
    });
  },

I'm writing a Tic-Tac-Toe game and ran into this problem - when multiple sessions are "played" click events keep compounding. Which I solved by clearing the previous click events every time before a new one is attached.

$(".game-screen").off().on("click", ".tic", function () { //do stuff }

By the way event.stopPropagation() and event.stopImmediatePropagation() did NOT work.

Anyway, while I managed to fix the problem and understand why the click events where compounding, what I can't seem to wrap my head around is why those compounded click events kept calling the parent function gameLogic: function(). Try "playing" several sessions in a row -

console.log("GAME LOGIC");
        alert("Your Turn!");
get called exponentially more with every session. Does jQuery use the parent function to track the click events or something? Can anyone explain what's happening under the hood? Why do the event handlers keep referring to the parent function?


问:
What is this syntax in ES6 or ES7?
I came across this syntax which I believe is ES6 or ES7. What do these lines of code do?</p>

```<code>module.exports = async (taskData) => {
  // do stuff
}
</code>```

答:
This is an async function which is set to return Promise as @Andrew says.
It is using Arrow Function syntax.

```<code>()=>{}
</code>```

This function is in ES6 and does not define its own this context and any use of this will refer to the outer scope.

Title: What is this syntax in ES6 or ES7?

Body:
I came across this syntax which I believe is ES6 or ES7. What do these lines of code do?

module.exports = async (taskData) => {
  // do stuff
}

Body:
This is an async function which is set to return Promise as @Andrew says.
It is using Arrow Function syntax.

()=>{}

This function is in ES6 and does not define its own this context and any use of this will refer to the outer scope.


问:
Which version of Visual Studio and SSDT-BI need to use for SQL server 2008 R2?
Which version of Visual Studio and SSDT-BI I need to use to create and deploy a SSIS project for SQL server 2008 R2?</p>

答:
You have to install Microsoft Visual Studio 2008 to deploy package for SQL Server 2008 or SQL Server R2 by default. (newer versions will not work correctly)

This Link contains very helpful informations:

https://learn.microsoft.com/en-us/sql/integration-services/install-windows/installing-integration-services-versions-side-by-side

There are a lot of links saying that newer versions of visual studio cannot deploy SSIS 2008 packages correctly:

Can SQL Server Data Tools work with SQL Server 2008 SSIS?

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bff5e145-1c63-4221-b2ba-009ea96a9e05/can-i-use-vs2012-to-create-and-deploy-ssis-for-sql2008r2?forum=sqlintegrationservices

https://www.sqlservercentral.com/Forums/Topic1560322-364-1.aspx

But in theory, You can create SSIS 2008 package using Visual Studio 2012 or 2013. if you decide to try this you can refer to this link it may help


问:
How do I use JQuery to add an event to a textbox when the user pushes enter?
And please don't submit the form when the user pushes enter on THAT SPECIFIC textbox.</p>

答:
Use the keypress event

Your textbox:

```<code><input type="text" id="myText" />
</code>```

Your script:

```<code>$("#myText").keypress(function(e) {
   if(e.keyCode == 13) {
      alert("pressed");
   }
});
</code>```

Body:
Use the keypress event

Your textbox:

<input type="text" id="myText" />

Your script:

$("#myText").keypress(function(e) {
   if(e.keyCode == 13) {
      alert("pressed");
   }
});


答:
Follow the below steps :

Change label numberOfLines property to zero

add constraints to label

Change height constraint relationship

Implement these two tableView delegates methods

```<code>func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat{
      return 55
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
      return UITableViewAutomaticDimension
}
</code>```

Now run your project and check.

Expected output:

Title: Tableview Cell Is override from bottom

Body:
Follow the below steps :

Change label numberOfLines property to zero

add constraints to label

Change height constraint relationship

Implement these two tableView delegates methods

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat{
      return 55
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
      return UITableViewAutomaticDimension
}

Now run your project and check.

Expected output:


问:
Service Fabric: Use Refresh Mode for Faster Debugging
The Service Fabric Team announced in their blog post that Service Fabric now supports Refresh Mode in Preview when debugging on a 1 Node cluster in Visual Studio 2015.

I've just installed the new Service Fabric SDK from the Web Platform Installer and have a .Net Core Web Application Service I'd like to try this out with.

Is there anything else I need to do to configure the Service/Application for Refresh Mode? I haven't noticed any new controls as such in Visual Studio. I can only hit Debug as normal.

答:
As the announce states about Refresh application debug mode in Visual Studio 2015 as follows:

In conjunction with ASP.NET Core integration support, we’ve added a new application debug mode to the Service Fabric Application project. Refresh Mode allows you to quickly iterate between writing code and debugging and supports edit and refresh for ASP.NET Core services, so you can now develop ASP.NET Core services in Service Fabric the same way you would outside of Service Fabric.

Though LoekD has pointed it out, I also tried to install Azure Service Fabric 5.5 and SDK 2.5, you could find the Refresh Application (Preview) as follows:


问:
How to handle a PBXCp error with EarlGrey?

I keep getting this error recently when I did a pod update, pod install and then executed my test cases using EarlGrey.
And when I try to resolve the path with terminal, I do not have anything in that path, nor do I have a EarlGrey-1.0.0 in my system.

答:
although the above change may fix the problem, but after earlgrey gem 0.2 release, the integration process should be a lot smoother w/o any post_install or require in your Podfile.

for more info here


问:
How to search for subarrays with a specific ids and generate a new array from their elements?
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

```<code>$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);
</code>```

And the output for the following is:

```<code>Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)
</code>```

Although what I'm trying to accomplish is:

```<code>Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

I tried the following:

```<code>function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}
</code>```

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

```<code>Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

答:
PHP code demo

```<code><?php
$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    $result=array();
    foreach($productIDs as $key => $productData)
    {
        if(!in_array($productData['product_id'],$urlIDs))
        {
            unset($productIDs[$key]);
        }
        else
        {
            $result[]=array("id"=>$productData['product_id'],"file"=>$productData['product_file'],"image"=>$productData['product_image']);
        }
    }

    return $result;
}
$getFiles = getFiles($productIDs, $urlIDs);
print_r($getFiles);
</code>```

Output:

```<code>Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

Body:
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);

And the output for the following is:

Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)

Although what I'm trying to accomplish is:

Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

I tried the following:

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

Body:
PHP code demo

<?php
$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    $result=array();
    foreach($productIDs as $key => $productData)
    {
        if(!in_array($productData['product_id'],$urlIDs))
        {
            unset($productIDs[$key]);
        }
        else
        {
            $result[]=array("id"=>$productData['product_id'],"file"=>$productData['product_file'],"image"=>$productData['product_image']);
        }
    }

    return $result;
}
$getFiles = getFiles($productIDs, $urlIDs);
print_r($getFiles);

Output:

Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)


问:
Javascript String to date conversion without date format but passing locale
I have this user input date field, where user can enter date as string such '010117' or '01012017' which I am converting to US date standard format(MM/dd/yyyy) using JavaScript. If we have to go international we want user to input date as string as per their country standard.

Question is, Is there any library for JavaScript that we can use to pass the date as string and locale and it will convert the string to their locale standard date format.

We don't want to pass date format for each country as it will be too much of a task to do that  for each country.

Thanks in advance.

答:
There is JavaScript library MomentJS which provides very good features about date and time.
We can pass the string to MomentJS and  it will give date.

By default MomentJS comes with English locale. You can change the locale by passing locale string to below function:

moment.locale(myLocale);

To get user's locale, you can do the following:

var myLocale = window.navigator.userLanguage || window.navigator.language;

Refer to the the link:
https://momentjs.com/docs/#/i18n/


问:
Apply a rolling function by group in r (zoo, data.table)
I am having trouble doing something fairly simple: apply a rolling function (standard deviation) by group in a data.table.
My problem is that when I use a data.table with rollapply by some column, data.table recycles the observations as noted in the warning message below. I would like to get NAs for the observations that are outside of the window instead of recycling the standard deviations.

This is my approach so far using iris, and a rolling window of size 2, aligned to the right:

```<code>library(zoo)
library(data.table)

A <- iris
setDT(A)
A[,stdev := rollapply(Petal.Width, width = 2, sd, align = 'right', partial = F),by = Species]
Warning messages:
1: In `[.data.table`(A, , `:=`(stdeev, rollapply(Petal.Width, width = 2,  :
  Supplied 49 items to be assigned to group 1 of size 50 in column 'stdeev' (recycled leaving remainder of 1 items).
2: In `[.data.table`(A, , `:=`(stdeev, rollapply(Petal.Width, width = 2,  :
  Supplied 49 items to be assigned to group 2 of size 50 in column 'stdeev' (recycled leaving remainder of 1 items).
3: In `[.data.table`(A, , `:=`(stdeev, rollapply(Petal.Width, width = 2,  :
  Supplied 49 items to be assigned to group 3 of size 50 in column 'stdeev' (recycled leaving remainder of 1 items).

> A
     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species     stdeev      stdev
  1:          5.1         3.5          1.4         0.2    setosa 0.00000000 0.00000000
  2:          4.9         3.0          1.4         0.2    setosa 0.00000000 0.00000000
  3:          4.7         3.2          1.3         0.2    setosa 0.00000000 0.00000000
  4:          4.6         3.1          1.5         0.2    setosa 0.00000000 0.00000000
  5:          5.0         3.6          1.4         0.2    setosa 0.14142136 0.14142136
 ---
146:          6.7         3.0          5.2         2.3 virginica 0.28284271 0.28284271
147:          6.3         2.5          5.0         1.9 virginica 0.07071068 0.07071068
148:          6.5         3.0          5.2         2.0 virginica 0.21213203 0.21213203
149:          6.2         3.4          5.4         2.3 virginica 0.35355339 0.35355339
150:          5.9         3.0          5.1         1.8 virginica 0.42426407 0.42426407
</code>```

答:
Add fill=NA to rollapply. This will ensure that a vector of length 50 (rather than 49) is returned, with NA as the first value (since align="right"), avoiding recycling.

```<code>A[,stdev := rollapply(Petal.Width, width=2, sd, align='right', partial=F, fill=NA), by=Species]
</code>```

```<code>    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species      stdev
1            5.1         3.5          1.4         0.2     setosa         NA
2            4.9         3.0          1.4         0.2     setosa 0.00000000
3            4.7         3.2          1.3         0.2     setosa 0.00000000
...
51           7.0         3.2          4.7         1.4 versicolor         NA
52           6.4         3.2          4.5         1.5 versicolor 0.07071068
53           6.9         3.1          4.9         1.5 versicolor 0.00000000
...
101          6.3         3.3          6.0         2.5  virginica         NA
102          5.8         2.7          5.1         1.9  virginica 0.42426407
103          7.1         3.0          5.9         2.1  virginica 0.14142136
</code>```

Body:
I am having trouble doing something fairly simple: apply a rolling function (standard deviation) by group in a data.table.
My problem is that when I use a data.table with rollapply by some column, data.table recycles the observations as noted in the warning message below. I would like to get NAs for the observations that are outside of the window instead of recycling the standard deviations.

This is my approach so far using iris, and a rolling window of size 2, aligned to the right:

library(zoo)
library(data.table)

A <- iris
setDT(A)
A[,stdev := rollapply(Petal.Width, width = 2, sd, align = 'right', partial = F),by = Species]
Warning messages:
1: In `[.data.table`(A, , `:=`(stdeev, rollapply(Petal.Width, width = 2,  :
  Supplied 49 items to be assigned to group 1 of size 50 in column 'stdeev' (recycled leaving remainder of 1 items).
2: In `[.data.table`(A, , `:=`(stdeev, rollapply(Petal.Width, width = 2,  :
  Supplied 49 items to be assigned to group 2 of size 50 in column 'stdeev' (recycled leaving remainder of 1 items).
3: In `[.data.table`(A, , `:=`(stdeev, rollapply(Petal.Width, width = 2,  :
  Supplied 49 items to be assigned to group 3 of size 50 in column 'stdeev' (recycled leaving remainder of 1 items).

> A
     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species     stdeev      stdev
  1:          5.1         3.5          1.4         0.2    setosa 0.00000000 0.00000000
  2:          4.9         3.0          1.4         0.2    setosa 0.00000000 0.00000000
  3:          4.7         3.2          1.3         0.2    setosa 0.00000000 0.00000000
  4:          4.6         3.1          1.5         0.2    setosa 0.00000000 0.00000000
  5:          5.0         3.6          1.4         0.2    setosa 0.14142136 0.14142136
 ---
146:          6.7         3.0          5.2         2.3 virginica 0.28284271 0.28284271
147:          6.3         2.5          5.0         1.9 virginica 0.07071068 0.07071068
148:          6.5         3.0          5.2         2.0 virginica 0.21213203 0.21213203
149:          6.2         3.4          5.4         2.3 virginica 0.35355339 0.35355339
150:          5.9         3.0          5.1         1.8 virginica 0.42426407 0.42426407

Body:
Add fill=NA to rollapply. This will ensure that a vector of length 50 (rather than 49) is returned, with NA as the first value (since align="right"), avoiding recycling.

A[,stdev := rollapply(Petal.Width, width=2, sd, align='right', partial=F, fill=NA), by=Species]

    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species      stdev
1            5.1         3.5          1.4         0.2     setosa         NA
2            4.9         3.0          1.4         0.2     setosa 0.00000000
3            4.7         3.2          1.3         0.2     setosa 0.00000000
...
51           7.0         3.2          4.7         1.4 versicolor         NA
52           6.4         3.2          4.5         1.5 versicolor 0.07071068
53           6.9         3.1          4.9         1.5 versicolor 0.00000000
...
101          6.3         3.3          6.0         2.5  virginica         NA
102          5.8         2.7          5.1         1.9  virginica 0.42426407
103          7.1         3.0          5.9         2.1  virginica 0.14142136


问:
Nvidia graphics driver causing noticeable frame stuttering
Ok I've been researching this issue for a few days now so let me go over what I know so far which leads me to believe this might be an issue with NVidia's driver and not my code.

Basically my game starts stuttering after running a few seconds (random frames take 70ms instead of 16ms, on a regularish pattern). This ONLY happens if a setting called "Threaded Optimization" is enabled in the Nvidia control panel (latest drivers, windows 10). Unfortunately this setting is enabled by default and I'd rather not have to have people tweak their settings to get an enjoyable experience.

The game is not CPU or GPU intensive (2ms a frame without vsync on). It's not calling any openGL functions that need to synchronize data, and it's not streaming any buffers or reading data back from the GPU or anything. About the simplest possible renderer.

The problem was always there it just only started becoming noticeable when I added in fmod for audio. fmod is not the cause of this (more later in the post)

Trying to debug the problem with NVidia Nsight made the problem go away. "Start Collecting Data" instantly causes stuttering to go away. No dice here.

In the Profiler, a lot of cpu time is spent in "nvoglv32.dll". This process only spawns if Threaded Optimization is on. I suspect it's a synchronization issue then, so I debug with visual studio Concurrency Viewer.

A-HA!

Investigating these blocks of CPU time on the nvidia thread, the earliest named function I can get in their callstack is "CreateToolhelp32Snapshot" followed by a lot of time spent in Thread32Next. I noticed Thread32Next in the profiler when looking at CPU times earlier so this does seem like I'm on the right track.

So it looks like periodically the nvidia driver is grabbing a snapshot of the whole process for some reason? What could possibly be the reason, why is it doing this, and how do I stop it?

Also this explains why the problem started becoming noticeable once I added in fmod, because its grabbing info for all the processes threads, and fmod spawns a lot of threads.

Any help? Is this just a bug in nvidia's driver or is there something I can do to fix it other telling people to disable Threaded "Optimization"?

edit 1: The same issue occurs with current nvidia drivers on my laptop too. So I'm not crazy

edit 2: the same issue occurs on version 362 (previous major version) of nvidia's driver

答:
Thanks for subGlitch's answer first, based on that proposal, I just make a safer one, which would enable you to cache and change the thread optimization, then restore it afterward.

Code is like below:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <nvapi.h>
#include <NvApiDriverSettings.h>

enum NvThreadOptimization {
    NV_THREAD_OPTIMIZATION_AUTO         = 0,
    NV_THREAD_OPTIMIZATION_ENABLE       = 1,
    NV_THREAD_OPTIMIZATION_DISABLE      = 2,
    NV_THREAD_OPTIMIZATION_NO_SUPPORT   = 3
};

bool NvAPI_OK_Verify(NvAPI_Status status)
{
    if (status == NVAPI_OK)
        return true;

    NvAPI_ShortString szDesc = {0};
    NvAPI_GetErrorMessage(status, szDesc);

    char szResult[255];
    sprintf(szResult, "NVAPI error: %s\n\0", szDesc);
    printf(szResult);

    return false;
}

NvThreadOptimization GetNVidiaThreadOptimization()
{
    NvAPI_Status status;
    NvDRSSessionHandle hSession;
    NvThreadOptimization threadOptimization = NV_THREAD_OPTIMIZATION_NO_SUPPORT;

    status = NvAPI_Initialize();
    if(!NvAPI_OK_Verify(status))
        return threadOptimization;

    status = NvAPI_DRS_CreateSession(&hSession);
    if(!NvAPI_OK_Verify(status))
        return threadOptimization;

    status = NvAPI_DRS_LoadSettings(hSession);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return threadOptimization;;
    }

    NvDRSProfileHandle hProfile;
    status = NvAPI_DRS_GetBaseProfile(hSession, &hProfile);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return threadOptimization;;
    }

    NVDRS_SETTING originalSetting;
    originalSetting.version = NVDRS_SETTING_VER;
    status = NvAPI_DRS_GetSetting(hSession, hProfile, OGL_THREAD_CONTROL_ID, &originalSetting);
    if(NvAPI_OK_Verify(status))
    {
        threadOptimization = (NvThreadOptimization)originalSetting.u32CurrentValue;
    }

    NvAPI_DRS_DestroySession(hSession);

    return threadOptimization;
}

void SetNVidiaThreadOptimization(NvThreadOptimization threadedOptimization)
{
    NvAPI_Status status;
    NvDRSSessionHandle hSession;

    if(threadedOptimization == NV_THREAD_OPTIMIZATION_NO_SUPPORT)
        return;

    status = NvAPI_Initialize();
    if(!NvAPI_OK_Verify(status))
        return;

    status = NvAPI_DRS_CreateSession(&hSession);
    if(!NvAPI_OK_Verify(status))
        return;

    status = NvAPI_DRS_LoadSettings(hSession);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return;
    }

    NvDRSProfileHandle hProfile;
    status = NvAPI_DRS_GetBaseProfile(hSession, &hProfile);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return;
    }

    NVDRS_SETTING setting;
    setting.version                 = NVDRS_SETTING_VER;
    setting.settingId               = OGL_THREAD_CONTROL_ID;
    setting.settingType             = NVDRS_DWORD_TYPE;
    setting.u32CurrentValue         = (EValues_OGL_THREAD_CONTROL)threadedOptimization;

    status = NvAPI_DRS_SetSetting(hSession, hProfile, &setting);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return;
    }

    status = NvAPI_DRS_SaveSettings(hSession);
    NvAPI_OK_Verify(status);

    NvAPI_DRS_DestroySession(hSession);
}
</code>```

Based on the two interfaces (Get/Set) above, you may well save the original setting and restore it when your application exits. That means your setting to disable thread optimization only impact your own application.

```<code>static NvThreadOptimization s_OriginalNVidiaThreadOptimization = NV_THREAD_OPTIMIZATION_NO_SUPPORT;

// Set
s_OriginalNVidiaThreadOptimization =  GetNVidiaThreadOptimization();
if(    s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_NO_SUPPORT
    && s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_DISABLE)
{
    SetNVidiaThreadOptimization(NV_THREAD_OPTIMIZATION_DISABLE);
}

//Restore
if(    s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_NO_SUPPORT
    && s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_DISABLE)
{
    SetNVidiaThreadOptimization(s_OriginalNVidiaThreadOptimization);
};
</code>```

Body:
Thanks for subGlitch's answer first, based on that proposal, I just make a safer one, which would enable you to cache and change the thread optimization, then restore it afterward.

Code is like below:

#include <stdlib.h>
#include <stdio.h>
#include <nvapi.h>
#include <NvApiDriverSettings.h>

enum NvThreadOptimization {
    NV_THREAD_OPTIMIZATION_AUTO         = 0,
    NV_THREAD_OPTIMIZATION_ENABLE       = 1,
    NV_THREAD_OPTIMIZATION_DISABLE      = 2,
    NV_THREAD_OPTIMIZATION_NO_SUPPORT   = 3
};

bool NvAPI_OK_Verify(NvAPI_Status status)
{
    if (status == NVAPI_OK)
        return true;

    NvAPI_ShortString szDesc = {0};
    NvAPI_GetErrorMessage(status, szDesc);

    char szResult[255];
    sprintf(szResult, "NVAPI error: %s\n\0", szDesc);
    printf(szResult);

    return false;
}

NvThreadOptimization GetNVidiaThreadOptimization()
{
    NvAPI_Status status;
    NvDRSSessionHandle hSession;
    NvThreadOptimization threadOptimization = NV_THREAD_OPTIMIZATION_NO_SUPPORT;

    status = NvAPI_Initialize();
    if(!NvAPI_OK_Verify(status))
        return threadOptimization;

    status = NvAPI_DRS_CreateSession(&hSession);
    if(!NvAPI_OK_Verify(status))
        return threadOptimization;

    status = NvAPI_DRS_LoadSettings(hSession);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return threadOptimization;;
    }

    NvDRSProfileHandle hProfile;
    status = NvAPI_DRS_GetBaseProfile(hSession, &hProfile);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return threadOptimization;;
    }

    NVDRS_SETTING originalSetting;
    originalSetting.version = NVDRS_SETTING_VER;
    status = NvAPI_DRS_GetSetting(hSession, hProfile, OGL_THREAD_CONTROL_ID, &originalSetting);
    if(NvAPI_OK_Verify(status))
    {
        threadOptimization = (NvThreadOptimization)originalSetting.u32CurrentValue;
    }

    NvAPI_DRS_DestroySession(hSession);

    return threadOptimization;
}

void SetNVidiaThreadOptimization(NvThreadOptimization threadedOptimization)
{
    NvAPI_Status status;
    NvDRSSessionHandle hSession;

    if(threadedOptimization == NV_THREAD_OPTIMIZATION_NO_SUPPORT)
        return;

    status = NvAPI_Initialize();
    if(!NvAPI_OK_Verify(status))
        return;

    status = NvAPI_DRS_CreateSession(&hSession);
    if(!NvAPI_OK_Verify(status))
        return;

    status = NvAPI_DRS_LoadSettings(hSession);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return;
    }

    NvDRSProfileHandle hProfile;
    status = NvAPI_DRS_GetBaseProfile(hSession, &hProfile);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return;
    }

    NVDRS_SETTING setting;
    setting.version                 = NVDRS_SETTING_VER;
    setting.settingId               = OGL_THREAD_CONTROL_ID;
    setting.settingType             = NVDRS_DWORD_TYPE;
    setting.u32CurrentValue         = (EValues_OGL_THREAD_CONTROL)threadedOptimization;

    status = NvAPI_DRS_SetSetting(hSession, hProfile, &setting);
    if(!NvAPI_OK_Verify(status))
    {
        NvAPI_DRS_DestroySession(hSession);
        return;
    }

    status = NvAPI_DRS_SaveSettings(hSession);
    NvAPI_OK_Verify(status);

    NvAPI_DRS_DestroySession(hSession);
}

Based on the two interfaces (Get/Set) above, you may well save the original setting and restore it when your application exits. That means your setting to disable thread optimization only impact your own application.

static NvThreadOptimization s_OriginalNVidiaThreadOptimization = NV_THREAD_OPTIMIZATION_NO_SUPPORT;

// Set
s_OriginalNVidiaThreadOptimization =  GetNVidiaThreadOptimization();
if(    s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_NO_SUPPORT
    && s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_DISABLE)
{
    SetNVidiaThreadOptimization(NV_THREAD_OPTIMIZATION_DISABLE);
}

//Restore
if(    s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_NO_SUPPORT
    && s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_DISABLE)
{
    SetNVidiaThreadOptimization(s_OriginalNVidiaThreadOptimization);
};