问:
With SQL Server how to get the most recent date while summing on amount and the sum of the amount is greater than 0?
I have a transaction table:

```<code>CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)
</code>```

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

```<code>SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID
</code>```

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

答:
You can try windowing functions which may be more efficient - This shouls work .</p>

```<code>select personid,trandate,SUM(transamount) as total
from(
select personid,
CAST(transdate as DATE) as Trandate,transamount,
RANK() over(partition by personid order by
 CAST(transdate as DATE) desc) as rnk
 from trans
 ) as x
 where rnk=1
 group by PersonID,trandate
</code>```

Body:
I have a transaction table:

CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

Body:
You can try windowing functions which may be more efficient - This shouls work .

select personid,trandate,SUM(transamount) as total
from(
select personid,
CAST(transdate as DATE) as Trandate,transamount,
RANK() over(partition by personid order by
 CAST(transdate as DATE) desc) as rnk
 from trans
 ) as x
 where rnk=1
 group by PersonID,trandate


来源: stackexchange

问:
Using Python's list index() method on a list of tuples or objects?
Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter.  For instance:

```<code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code>```

Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples?  Ideally, I'd like to be able to do something like this:

```<code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code>```

getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index.  I hope

Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that?  I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.

答:
Python's list.index(x) returns index of the first occurrence of x in the list. So we can pass objects returned by list compression to get their index.

```<code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1]
>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']
[2]
</code>```

With the same line, we can also get the list of index in case there are multiple matched elements.

```<code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter.  For instance:

>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3

Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples?  Ideally, I'd like to be able to do something like this:

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2

getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index.  I hope

Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that?  I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.

Body:
Python's list.index(x) returns index of the first occurrence of x in the list. So we can pass objects returned by list compression to get their index.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1]
>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']
[2]

With the same line, we can also get the list of index in case there are multiple matched elements.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]

ContentLicense: CC BY-SA 3.0


问:
Updating parameters in a javascript function using element ID
I'm trying to update the parameters of a function based on a an element ID. The below code works as intended since the ID parameters are hardcoded.

```<code>window.setInterval(function() {
    $('#result').text(collision_(
        $('#task1'), $('#task2'), $('#task3'), $('#task4')
    ));
}, 200);
</code>```

When I try to compile the parameters dynamically the function isn't working.

```<code>window.setInterval(function() {
    function workerTasks() {
        var task = document.getElementById("worker1").children;
        var tasks = [];
        for (i = 0; i <= task.length - 1; i++) {
            tasks.push($("#" + task[i].id))
        }
        return tasks;
    }

    $('#result').text(collision_(tasks));
}, 200);
</code>```

Any help would be greatly appreciated!

UPDATED CODE BELOW ---------

I'm pairing this with draggable collision functions that are driven off of the true or false response - but I'm still not able to indicate the array from 'workerTasks' to be used by 'collision_'.

```<code>$(document).ready(function(){
      setInterval(function() {
        $('#result').text(collision_(workerTasks()));
            console.log(tasks);
      }, 200);
    });

    function workerTasks() {
      var tasks = '';
      $('#worker1 [id^=task]').each(function(i){
        var comma = $('#worker1 [id^=task]').length == i ? '' : ',';
        tasks += $('#' + $(this).attr('id'))  + comma;
      });
      return tasks;
    }

                    function collision_() {
                            if (arguments.length > 1) {
                                    for (var x = 0; x < arguments.length; x++) {
                                            for (var y = 1; y < arguments.length; y++) {
                                                    if (x == y) {
                                                            continue;
                                                    }
                                                    if (collision(arguments[x], arguments[y])) {
                                                            return true;
                                                    }
                                            }
                                    }
                                    return false;
                            }
                    }

                    function collision($div1, $div2) {
                        var x1 = $div1.offset().left;
                        var y1 = $div1.offset().top;
                        var h1 = $div1.outerHeight(true);
                        var w1 = $div1.outerWidth(false);
                        var b1 = y1 + h1;
                        var r1 = x1 + w1;
                        var x2 = $div2.offset().left;
                        var y2 = $div2.offset().top;
                        var h2 = $div2.outerHeight(true);
                        var w2 = $div2.outerWidth(false);
                        var b2 = y2 + h2;
                        var r2 = x2 + w2;

                        if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2) return false;
                        return true;
                        }
</code>```

答:
Your last line should be

```<code>$('#result').text(function_(workerTasks()));
</code>```

and that workerTasks() function I would move it to outside of your setInterval function.

So it would be

```<code>function workerTasks() {
   var task = document.getElementById("worker1").children;
   var tasks = [];
   for (i = 0; i <= task.length - 1; i++) {
       tasks.push($("#" + task[i].id))
   }
   return tasks;
}

window.setInterval(function() {
    $('#result').text(function_(workerTasks()));
}, 200);
</code>```

Body:
I'm trying to update the parameters of a function based on a an element ID. The below code works as intended since the ID parameters are hardcoded.

window.setInterval(function() {
    $('#result').text(collision_(
        $('#task1'), $('#task2'), $('#task3'), $('#task4')
    ));
}, 200);

When I try to compile the parameters dynamically the function isn't working.

window.setInterval(function() {
    function workerTasks() {
        var task = document.getElementById("worker1").children;
        var tasks = [];
        for (i = 0; i <= task.length - 1; i++) {
            tasks.push($("#" + task[i].id))
        }
        return tasks;
    }

    $('#result').text(collision_(tasks));
}, 200);

Any help would be greatly appreciated!

UPDATED CODE BELOW ---------

I'm pairing this with draggable collision functions that are driven off of the true or false response - but I'm still not able to indicate the array from 'workerTasks' to be used by 'collision_'.

$(document).ready(function(){
      setInterval(function() {
        $('#result').text(collision_(workerTasks()));
            console.log(tasks);
      }, 200);
    });

    function workerTasks() {
      var tasks = '';
      $('#worker1 [id^=task]').each(function(i){
        var comma = $('#worker1 [id^=task]').length == i ? '' : ',';
        tasks += $('#' + $(this).attr('id'))  + comma;
      });
      return tasks;
    }

                    function collision_() {
                            if (arguments.length > 1) {
                                    for (var x = 0; x < arguments.length; x++) {
                                            for (var y = 1; y < arguments.length; y++) {
                                                    if (x == y) {
                                                            continue;
                                                    }
                                                    if (collision(arguments[x], arguments[y])) {
                                                            return true;
                                                    }
                                            }
                                    }
                                    return false;
                            }
                    }

                    function collision($div1, $div2) {
                        var x1 = $div1.offset().left;
                        var y1 = $div1.offset().top;
                        var h1 = $div1.outerHeight(true);
                        var w1 = $div1.outerWidth(false);
                        var b1 = y1 + h1;
                        var r1 = x1 + w1;
                        var x2 = $div2.offset().left;
                        var y2 = $div2.offset().top;
                        var h2 = $div2.outerHeight(true);
                        var w2 = $div2.outerWidth(false);
                        var b2 = y2 + h2;
                        var r2 = x2 + w2;

                        if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2) return false;
                        return true;
                        }

Body:
Your last line should be

$('#result').text(function_(workerTasks()));

and that workerTasks() function I would move it to outside of your setInterval function.

So it would be

function workerTasks() {
   var task = document.getElementById("worker1").children;
   var tasks = [];
   for (i = 0; i <= task.length - 1; i++) {
       tasks.push($("#" + task[i].id))
   }
   return tasks;
}

window.setInterval(function() {
    $('#result').text(function_(workerTasks()));
}, 200);


问:
draw one or more plots in the same window
I want compare two curves, it's possible with R to draw a plot and then draw another plot over it ? how ?

thanks.

答: Draw multiple curves at the same time with the matplot function. Do help(matplot) for more.</p>


问:
Permission Denied When Making Request to GCP Video Intelligence API
so I am able to make a valid request to the video intelligence api with the sample video given in the quickstart. https://cloud.google.com/video-intelligence/docs/getting-started I have tried many different ways of authenticating to the api as well. The API token I am using was created from the Credentials page in the console. There are no options to tie it to the video api so I figured it should automatically work. The API has been enabled on my account.

```<code>export TOKEN="foobar"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features": ["LABEL_DETECTION"]}'
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://cloud-ml-sandbox/video/chicago.mp4", "features": ["LABEL_DETECTION"]}'
{
  "name": "us-east1.18013173402060296928"
}
</code>```

Update:

I set the file as public and it worked. But I need to access this as private, so I gave the service account access to the file and tried to get the API key like suggested.

```<code>export TOKEN="$(gcloud auth print-access-token)"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features":["LABEL_DETECTION"]}'
{
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console",
            "url": "https://console.developers.google.com"
          }
        ]
      }
    ]
  }
}
</code>```

It seems like the token returned by this print-access-token function does not work. I do have an API key, but it does not have access to the bucket and I don't see a way to give an API key access.

Update 2:

So it looks like we were setting our token wrong. We were following this example https://cloud.google.com/video-intelligence/docs/analyze-labels#videointelligence-label-file-protocol which is where we got the apiKey=$TOKEN from. But it looks like we needed to set the Bearer Header. We did try this at first but we were having the first issue of not having access to the bucket. So thank you.

答:
TL;DR - Video Intelligence service is unable to access the file on your Cloud storage bucket because of lack of permissions. Since the API uses the permissions of the service account token being passed, you will need to grant your service account permissions to read the file in the GCS bucket or the entire GCS bucket itself.

Long version

The access token you pass should correspond to an IAM service account key. The service account will belong to a project (where you need to enable the Video intelligence API access) and the service account should have permissions to access the GCS bucket you're trying to access.

Each such service account has an associated email id in the form SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com.

In Cloud console, you can go to the Cloud storage bucket/file and grant Reader permissions for the IAM service account email address. There is no need to make this bucket public.

If you use gsutil, you can run the following equivalent command:

```<code>gsutil acl ch -u SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com:READ gs://custom-bucket/IMG_3591.mov`
</code>```

I confirmed this myself with an IAM service account that I created in my project and used this to invoke the video intelligence API. The file was not made public, but granted Reader permissions only to the service account.

I used gcloud to activate the service account and fetch the access token, although you can do this manually as well using the google OAuth APIs:

gcloud auth activate-service-account SERVICE_ACCOUNT_KEY.json

export TOKEN="$(gcloud auth print-access-token)"

The steps for creating the IAM service account using gcloud are in the same page.

Body:
so I am able to make a valid request to the video intelligence api with the sample video given in the quickstart. https://cloud.google.com/video-intelligence/docs/getting-started I have tried many different ways of authenticating to the api as well. The API token I am using was created from the Credentials page in the console. There are no options to tie it to the video api so I figured it should automatically work. The API has been enabled on my account.

export TOKEN="foobar"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features": ["LABEL_DETECTION"]}'
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://cloud-ml-sandbox/video/chicago.mp4", "features": ["LABEL_DETECTION"]}'
{
  "name": "us-east1.18013173402060296928"
}

Update:

I set the file as public and it worked. But I need to access this as private, so I gave the service account access to the file and tried to get the API key like suggested.

export TOKEN="$(gcloud auth print-access-token)"
curl -XPOST -s -k -H"Content-Type: application/json" "https://videointelligence.googleapis.com/v1beta1/videos:annotate?key=$TOKEN" --data '{"inputUri": "gs://custom-bucket/IMG_3591.mov", "features":["LABEL_DETECTION"]}'
{
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console",
            "url": "https://console.developers.google.com"
          }
        ]
      }
    ]
  }
}

It seems like the token returned by this print-access-token function does not work. I do have an API key, but it does not have access to the bucket and I don't see a way to give an API key access.

Update 2:

So it looks like we were setting our token wrong. We were following this example https://cloud.google.com/video-intelligence/docs/analyze-labels#videointelligence-label-file-protocol which is where we got the apiKey=$TOKEN from. But it looks like we needed to set the Bearer Header. We did try this at first but we were having the first issue of not having access to the bucket. So thank you.

Body:
TL;DR - Video Intelligence service is unable to access the file on your Cloud storage bucket because of lack of permissions. Since the API uses the permissions of the service account token being passed, you will need to grant your service account permissions to read the file in the GCS bucket or the entire GCS bucket itself.

Long version

The access token you pass should correspond to an IAM service account key. The service account will belong to a project (where you need to enable the Video intelligence API access) and the service account should have permissions to access the GCS bucket you're trying to access.

Each such service account has an associated email id in the form SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com.

In Cloud console, you can go to the Cloud storage bucket/file and grant Reader permissions for the IAM service account email address. There is no need to make this bucket public.

If you use gsutil, you can run the following equivalent command:

gsutil acl ch -u SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com:READ gs://custom-bucket/IMG_3591.mov`

I confirmed this myself with an IAM service account that I created in my project and used this to invoke the video intelligence API. The file was not made public, but granted Reader permissions only to the service account.

I used gcloud to activate the service account and fetch the access token, although you can do this manually as well using the google OAuth APIs:

gcloud auth activate-service-account SERVICE_ACCOUNT_KEY.json

export TOKEN="$(gcloud auth print-access-token)"

The steps for creating the IAM service account using gcloud are in the same page.


问:
How can I make JQuery autocomplete go to the user's page like Facebook in laravel?
This is my search form, all results displayed are users on my site using JQuery autocomplete. When I select the searched user's name, I simple want the form to go to the go to the profile page of the user on Submit or when I click on the selected user's name and bring up their profile. Much like Facebook.

```<code><form action="" class="navbar-form navbar-right" role="search">
      <div class="input-group">
         <input type="text" name="term" class="form-control inputsearch"  placeholder="Search..." />
         <span class="input-group-btn">
            <button class="btn btn-default searchbar" type="submit">
              <i class="fa fa-search searchnow"></i>
             </button>
         </span>
      </div>
</form>
</code>```

This is the JQuery autocomplete function

```<code>$(function() {
$("input[name=term]").autocomplete({
    source: "autocomplete",
    minLength: 3,
    select: function(event, ui) {
        $(this).val(ui.item.value);
    }
});
});
</code>```

These are my routes for the autocomplete and getting the user's profile

```<code>Route::get('/dashboard/{name}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
]);

Route::get('/autocomplete',[
'uses'=>'UserController@autocomplete',
'as'=>'autocomplete'
]);
</code>```

And finally, this is my controller:

```<code> public function autocomplete(Request $request)
{
    if ($request->ajax())
    {
        return  User::select(['id', 'name as value'])->where(function($query) use ($request) {
            if ( ($term = $request->get("term")) )
            {
                $keywords = '%' . $term . '%';
                $query->orWhere("name", 'LIKE', $keywords);
                $query->orWhere("email", 'LIKE', $keywords);
            }
        })
            ->orderBy('name', 'asc')
            ->take(5)
            ->get();
    }
}

public function getProfile($name)
{
    $user = User::where('name', $name)->first();
    if(!$user){
        abort(404);
    }
    $posts = Post::where("user_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}
</code>```

What can I modify to make this work?

答:
try something like this, the code doesnt work but it gives you an idea</p>

```<code>$(function() {
$("input[name=term]").autocomplete({
    source: "autocomplete",
    minLength: 3,
    select: function(event, ui) {
        var userid = ui.item.value; // just try to get user id here
     window.location.href = "yourapp/user/"+userid ;
    }
});
});
</code>```

Body:
This is my search form, all results displayed are users on my site using JQuery autocomplete. When I select the searched user's name, I simple want the form to go to the go to the profile page of the user on Submit or when I click on the selected user's name and bring up their profile. Much like Facebook.

<form action="" class="navbar-form navbar-right" role="search">

         <input type="text" name="term" class="form-control inputsearch"  placeholder="Search..." />

            <button class="btn btn-default searchbar" type="submit">

             </button>

</form>

This is the JQuery autocomplete function

$(function() {
$("input[name=term]").autocomplete({
    source: "autocomplete",
    minLength: 3,
    select: function(event, ui) {
        $(this).val(ui.item.value);
    }
});
});

These are my routes for the autocomplete and getting the user's profile

Route::get('/dashboard/{name}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
]);

Route::get('/autocomplete',[
'uses'=>'UserController@autocomplete',
'as'=>'autocomplete'
]);

And finally, this is my controller:

 public function autocomplete(Request $request)
{
    if ($request->ajax())
    {
        return  User::select(['id', 'name as value'])->where(function($query) use ($request) {
            if ( ($term = $request->get("term")) )
            {
                $keywords = '%' . $term . '%';
                $query->orWhere("name", 'LIKE', $keywords);
                $query->orWhere("email", 'LIKE', $keywords);
            }
        })
            ->orderBy('name', 'asc')
            ->take(5)
            ->get();
    }
}

public function getProfile($name)
{
    $user = User::where('name', $name)->first();
    if(!$user){
        abort(404);
    }
    $posts = Post::where("user_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}

What can I modify to make this work?

Body:
try something like this, the code doesnt work but it gives you an idea

$(function() {
$("input[name=term]").autocomplete({
    source: "autocomplete",
    minLength: 3,
    select: function(event, ui) {
        var userid = ui.item.value; // just try to get user id here
     window.location.href = "yourapp/user/"+userid ;
    }
});
});


问:
Serializer perform_create not being called
I'm a little messed here with this thing... Lost few hours and did try lots of variants of this code, but with no success.

I need create an related object called ContaCorrente to each user as Usuario when it creates an account.

Those are my models:

```<code>class Usuario(models.Model):
    """Classe que ira gerir o cliente final, cadastrado via APP ou Webapp"""
    nome = models.CharField(max_length=60)
    sobrenome = models.CharField(max_length=60)
    telefone = models.CharField(max_length=20)
    .... FOR THE SAKE OF BREVITY

    def __str__(self):
        return self.nome + ' ' + self.sobrenome

class ContaCorrente(models.Model):
    """Controle financeiro do Cliente/Usuario cadastrado"""
    pontos = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    saldo_reais = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, related_name='conta_corrente')
</code>```

And this is my Serializers:

```<code>class ContaCorrenteSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
    model = ContaCorrente
    fields = ('pontos', 'saldo_reais', 'usuario_id')

class UsuariosSerializer(serializers.HyperlinkedModelSerializer):
    conta_corrente = ContaCorrenteSerializer(read_only=True)
    id = serializers.ReadOnlyField()
    class Meta:
        model = Usuario
        fields = (
        'id',
        'nome',
        'sobrenome',
        'telefone',
        ...
        FOR THE SAKE OF BREVITY
        ...
        'updated_at',
        'conta_corrente'
    )

    def perform_create(self, serializer):
        conta = ContaCorrente.objects.create(usuario_id=self.kwargs.get('pk'), saldo_reais=0, pontos=0)
        conta.save()
        serializer.save()
        return serializer
</code>```

I did try lots and lots of variants of this code, but can't find where it explodes.

The Usuario model get persisted, but the ContaCorrente not! Someone has any help to give? Thanks!

答:
There is not such method as perform_create in parent classes.
Try to use create instead. Source code.

Body:
I'm a little messed here with this thing... Lost few hours and did try lots of variants of this code, but with no success.

I need create an related object called ContaCorrente to each user as Usuario when it creates an account.

Those are my models:

class Usuario(models.Model):
    """Classe que ira gerir o cliente final, cadastrado via APP ou Webapp"""
    nome = models.CharField(max_length=60)
    sobrenome = models.CharField(max_length=60)
    telefone = models.CharField(max_length=20)
    .... FOR THE SAKE OF BREVITY

    def __str__(self):
        return self.nome + ' ' + self.sobrenome

class ContaCorrente(models.Model):
    """Controle financeiro do Cliente/Usuario cadastrado"""
    pontos = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    saldo_reais = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, related_name='conta_corrente')

And this is my Serializers:

class ContaCorrenteSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
    model = ContaCorrente
    fields = ('pontos', 'saldo_reais', 'usuario_id')

class UsuariosSerializer(serializers.HyperlinkedModelSerializer):
    conta_corrente = ContaCorrenteSerializer(read_only=True)
    id = serializers.ReadOnlyField()
    class Meta:
        model = Usuario
        fields = (
        'id',
        'nome',
        'sobrenome',
        'telefone',
        ...
        FOR THE SAKE OF BREVITY
        ...
        'updated_at',
        'conta_corrente'
    )

    def perform_create(self, serializer):
        conta = ContaCorrente.objects.create(usuario_id=self.kwargs.get('pk'), saldo_reais=0, pontos=0)
        conta.save()
        serializer.save()
        return serializer

I did try lots and lots of variants of this code, but can't find where it explodes.

The Usuario model get persisted, but the ContaCorrente not! Someone has any help to give? Thanks!


问:
xcode 8 console area doesn't show anything
I was trying to run my app but my console area doesn't show anything

I tried many solution but I can't fix that

any help please ??

答:
I think you've deactivated your console by mistake, try pressing: shift-command-c

Alternatively, you can do that by going to:

View -> Debug Area -> Activate Console.


问:
What is the best way to execute task five seconds after method call in Java
When I call the following method, I want the code nested inside of it to execute after five seconds. I know there are several ways to do this but I want to know the best and most efficient way to accomplish this in java?

```<code>public void callMe() {
  System.out.println("This is a message!");
}
</code>```

Thanks,
Faraaz

答:
In java you can accomplish that by using timer.schedule() </p>

<p>Code: </p>

```<code> public static void callMe() {
 new java.util.Timer().schedule(
    new java.util.TimerTask() {
        @Override
        public void run() {
             System.out.println("This is a message!");
        }
    },
    5000
 );
</code>```

Body:
When I call the following method, I want the code nested inside of it to execute after five seconds. I know there are several ways to do this but I want to know the best and most efficient way to accomplish this in java?

public void callMe() {
  System.out.println("This is a message!");
}

Thanks,
Faraaz

Body:
In java you can accomplish that by using timer.schedule()

Code:

 public static void callMe() {
 new java.util.Timer().schedule(
    new java.util.TimerTask() {
        @Override
        public void run() {
             System.out.println("This is a message!");
        }
    },
    5000
 );


问:
struts tiles.xml directly refer jsp without template or layout
I need to return a jsp as is in my Struts 2 application. The Struts application is setup with tiles. Some of the jsp's are already using tiles with a default template or layout. But for a new jsp, which will be embedded in a container, that I need to return as is, without any additional tag for header, body, footer, etc., inserted from tiles.xml. How can I do it?

I think there are two possible places that I can make the change:

in struts.xml, to directly say go to this jsp, instead of let tiles resolve the name

in tiles.xml, directly say go to this jsp, without template
Anybody has done this before ?

Any suggestions ?

答:
I have tested a little. It looks like in struts.xml, we can have both flavor at the same time, one to refer tiles.xml, the other use a location param.

```<code><result name="success">eventHistory</result>
<result name="none" type="dispatcher">
    <param name="location">/EventHistoryBUIC.jsp</param>
</result>
</code>```

Body:
I have tested a little. It looks like in struts.xml, we can have both flavor at the same time, one to refer tiles.xml, the other use a location param.

<result name="success">eventHistory</result>
<result name="none" type="dispatcher">
    <param name="location">/EventHistoryBUIC.jsp</param>
</result>


问:
Using standalone 'gsutil' from within GKE
I'm trying to use the standalone gsutil tool from within a container running in a GKE cluster, but I cannot get it to work. I believe the cluster has adequate permissions (see below). However, running

```<code>./gsutil ls gs://my-bucket/
</code>```

yields

```<code>ServiceException: 401 Anonymous users does not have storage.objects.list access to bucket my-bucket.
</code>```

Am I missing anything? I don't have a .boto file, as I believe it shouldn't be necessary—or is it? This is the list of scopes that the cluster and the node pool have:

```<code>- https://www.googleapis.com/auth/compute
- https://www.googleapis.com/auth/devstorage.full_control
- https://www.googleapis.com/auth/logging.write
- https://www.googleapis.com/auth/monitoring.write
- https://www.googleapis.com/auth/pubsub
- https://www.googleapis.com/auth/servicecontrol
- https://www.googleapis.com/auth/service.management.readonly
- https://www.googleapis.com/auth/trace.append
</code>```

答:
Short answer:

Yes, you'll need some sort of boto file.

Long answer:

Generally, for GCE instances, you don't need a ~/.boto file because the /etc/boto.cfg file is already present -- the Boto library that GSUtil uses knows to look for this by default.  On Debian images, it contains these lines:

```<code># This file is automatically created at boot time by the /usr/lib/python
# 2.7/dist-packages/google_compute_engine/boto/boto_config.pyc script.
# Do not edit this file directly. If you need to add items to this file,
# create or edit /etc/boto.cfg.template instead and then re-run the
# script.

[GSUtil]
default_project_id = <PROJECT NUMBER HERE>
default_api_version = 2

[GoogleCompute]
service_account = default

[Plugin]
plugin_directory = /usr/lib/python2.7/dist-packages/google_compute_engine/boto
</code>```

If you want to mimic this behavior on your GKE container, you'll have to have the google-compute-engine python package installed, along with a having a boto file that tells gsutil to load that plugin from where ever it was installed to, as seen above. On GCE (and I'm assuming GKE as well, although I've not tested it), this plugin allows a VM to talk to its metadata server to obtain credentials for the specified service account.

Body:
I'm trying to use the standalone gsutil tool from within a container running in a GKE cluster, but I cannot get it to work. I believe the cluster has adequate permissions (see below). However, running

./gsutil ls gs://my-bucket/

yields

ServiceException: 401 Anonymous users does not have storage.objects.list access to bucket my-bucket.

Am I missing anything? I don't have a .boto file, as I believe it shouldn't be necessary—or is it? This is the list of scopes that the cluster and the node pool have:

- https://www.googleapis.com/auth/compute
- https://www.googleapis.com/auth/devstorage.full_control
- https://www.googleapis.com/auth/logging.write
- https://www.googleapis.com/auth/monitoring.write
- https://www.googleapis.com/auth/pubsub
- https://www.googleapis.com/auth/servicecontrol
- https://www.googleapis.com/auth/service.management.readonly
- https://www.googleapis.com/auth/trace.append

Body:
Short answer:

Yes, you'll need some sort of boto file.

Long answer:

Generally, for GCE instances, you don't need a ~/.boto file because the /etc/boto.cfg file is already present -- the Boto library that GSUtil uses knows to look for this by default.  On Debian images, it contains these lines:

# This file is automatically created at boot time by the /usr/lib/python
# 2.7/dist-packages/google_compute_engine/boto/boto_config.pyc script.
# Do not edit this file directly. If you need to add items to this file,
# create or edit /etc/boto.cfg.template instead and then re-run the
# script.

[GSUtil]
default_project_id = <PROJECT NUMBER HERE>
default_api_version = 2

[GoogleCompute]
service_account = default

[Plugin]
plugin_directory = /usr/lib/python2.7/dist-packages/google_compute_engine/boto

If you want to mimic this behavior on your GKE container, you'll have to have the google-compute-engine python package installed, along with a having a boto file that tells gsutil to load that plugin from where ever it was installed to, as seen above. On GCE (and I'm assuming GKE as well, although I've not tested it), this plugin allows a VM to talk to its metadata server to obtain credentials for the specified service account.


问:
Ohm symbol shows in gnuplot wxt window, exported SVG from the window, but not in SVG term output
I have a sequence of gnuplot commands that produces a label with an underscript _{1} and the Ω symbol {/Symbol W} preceded by a small space &{.}, which

show correctly in the wxt window

show correctly on a  SVG file exported from the wxt window

shows no underscript and .W if plotted to the SVG terminal

Here's a snippet of the code:

```<code>set label 3 "R_{1} 100&{.}{/Symbol W}"
set terminal svg size 1024,768 dynamic font 'Lohit' fsize 14 enhanced background 'white'
set output 'svg-file.svg'
plot ...
set terminal wxt 0 font 'Lohit,14' enhanced
set output
plot ...
</code>```

I set both terminal to enhanced mode. What am I missing?

答: It's probably better these days to input Unicode directly, rather than using the Symbol font. Ω!</p>

Body:
I have a sequence of gnuplot commands that produces a label with an underscript _{1} and the Ω symbol {/Symbol W} preceded by a small space &{.}, which

show correctly in the wxt window

show correctly on a  SVG file exported from the wxt window

shows no underscript and .W if plotted to the SVG terminal

Here's a snippet of the code:

set label 3 "R_{1} 100&{.}{/Symbol W}"
set terminal svg size 1024,768 dynamic font 'Lohit' fsize 14 enhanced background 'white'
set output 'svg-file.svg'
plot ...
set terminal wxt 0 font 'Lohit,14' enhanced
set output
plot ...

I set both terminal to enhanced mode. What am I missing?


问:
why do i have to declare javascript variable with an empty value?
why must i declare the var msg = ' '; and not just var msg;  and also why msg += 'Round ' + roundNumber + ':';'  and not just msg = 'Round ' + roundNumber + ':';.... why should i add + sign before equals ?

```<code>var score = [24, 32, 17];
    var arrayLength = score.length;
    var roundNumber = 0;
    var i;
    var msg = '';

    for (i = 0; i < arrayLength; i++) {
      roundNumber = (i + 1);
      msg += 'Round ' + roundNumber + ':';
      msg += score[i] + '</br>'
    }

    document.getElementById('answer').innerHTML = msg;
</code>```

output of the above code:

```<code>Test 1:24
Test 2:32
Test 3:17
</code>```

output of the code when msg is declared only rather than giving an empty value and assigning msg without the plus (+) sign:

```<code>Test 3:17
</code>```

答:
You have confused a number of Javascript concepts.

Firstly, Javascript variables must be declared but do not have to be initialised.  To declare a Javascript variable, you use the var keyword.  For example, var msg; is valid Javascript code.  As well as declaring a variable, you can optionally initialise it using an = sign.  So, for example, var msg = ''; declares the msg variable and initialises it to an empty string.  Importantly for you, if you do not initialise a Javascript variable, it is set to a special type of variable called undefined.

The second Javascript concept you have confused is assignment and calculation.  In Javascript, you use the = sign to assign a value to a variable.  So, for example x = 1; sets the value of the x variable to 1.  The += operator is a shorthand operator.  So, x += y; is exactly the same as x = x + y;.  The crucial difference is that the = operator overwrites the existing value of the variable, whereas += uses the existing value to calculate a new value.

So, in the specific case of your code, you have used the += operator on the msg variable.  As explained, the += operator performs a calculation on the existing value of the variable.  So, this is why you had to initialise your variable when you declared it - otherwise you would have been performing a += on an undefined variable - which, in your case, does not perform the string concatenation that you expected.

The specific instances on when you should use what very much depends upon what the goal of your code is.

Body:
why must i declare the var msg = ' '; and not just var msg;  and also why msg += 'Round ' + roundNumber + ':';'  and not just msg = 'Round ' + roundNumber + ':';.... why should i add + sign before equals ?

var score = [24, 32, 17];
    var arrayLength = score.length;
    var roundNumber = 0;
    var i;
    var msg = '';

    for (i = 0; i < arrayLength; i++) {
      roundNumber = (i + 1);
      msg += 'Round ' + roundNumber + ':';
      msg += score[i] + '
'
    }

    document.getElementById('answer').innerHTML = msg;

output of the above code:

Test 1:24
Test 2:32
Test 3:17

output of the code when msg is declared only rather than giving an empty value and assigning msg without the plus (+) sign:

Test 3:17


问:
Which is the preferred solution for Kotlin koan "Partition" and why?
I worked through the Kotlin koan Partition and came wound up with this, which passes the unit test:

```<code>    fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> =
        customers.filter{it.orders.partition{it.isDelivered}
             .let{(delivered, undelivered) -> delivered.size < undelivered.size}}.toSet()
</code>```

This is a variation on the solution:

```<code>    fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> =
        customers.filter {
            val (delivered, undelivered) = it.orders.partition { it.isDelivered }
            undelivered.size > delivered.size
        }.toSet()
</code>```

Are there any reasons to prefer one of these solutions over the other?

答:
Kotlin Koans were written for Kotlin 1.0 which didn't support destructuring in lambda parameters.

Otherwise, if you're targeting Kotlin 1.1, these two solutions are equivalent.

Body:
I worked through the Kotlin koan Partition and came wound up with this, which passes the unit test:

    fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> =
        customers.filter{it.orders.partition{it.isDelivered}
             .let{(delivered, undelivered) -> delivered.size < undelivered.size}}.toSet()

This is a variation on the solution:

    fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> =
        customers.filter {
            val (delivered, undelivered) = it.orders.partition { it.isDelivered }
            undelivered.size > delivered.size
        }.toSet()

Are there any reasons to prefer one of these solutions over the other?


问:
TagHelper rendered incorrectly in ASP.NET Core 1.1
I have a tag helper I crafted like this:

```<code>public class GooglePlusOneTagHelper : TagHelper {
   [ViewContext]
    public ViewContext ViewContext { get; set; }
    public string Size { get; set; }
    public string Annotation { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output) {
        output.TagMode = TagMode.StartTagAndEndTag;
        output.TagName = "div";

        var request = ViewContext.HttpContext.Request;
        var absoluteUri = string.Concat(
            request.Scheme,
            "://",
            request.Host.ToUriComponent(),
            request.PathBase.ToUriComponent(),
            request.Path.ToUriComponent(),
            request.QueryString.ToUriComponent());

        output.Attributes.SetAttribute("class", "g-plusone");

        string size = Size.ToLower().Trim() ?? "";
        if (size == "small" || size == "medium" || size == "tall")
            output.Attributes.SetAttribute("data-size", size);

        string annotation = Annotation.ToLower().Trim() ?? "";
        if (annotation == "none" || annotation == "inline")
            output.Attributes.SetAttribute("data-annotation", annotation);

        output.Attributes.SetAttribute("data-href", absoluteUri);
    }
}
</code>```

And when I put this code in a view:

```<code><google-plusone size="medium" annotation="bubble"  />
</code>```

It gets rendered in the view like this:

```<code><google-plusone size="medium" annotation="bubble"  >
</code>```

So, the tag helper is somehow not processing it as it must really output a DIV. Additionally it transforms my raw tag from a self-closing to one that is open and never closes!

答:
Looks like the Tag Helper is not getting rendered properly. Here is the things you can verify.

Hope you added @addTagHelper *, <Your Assembly Name> in your _ViewImports.cshtml file. If not you need to add it.

Include the reference of Microsoft.AspNetCore.Mvc.TagHelpers in your project file.

Add [HtmlTargetElement("google-plusone")] attribute to your Tag Helper.

Here is the HTML output for me

And here is the screenshot.

Body:
I have a tag helper I crafted like this:

public class GooglePlusOneTagHelper : TagHelper {
   [ViewContext]
    public ViewContext ViewContext { get; set; }
    public string Size { get; set; }
    public string Annotation { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output) {
        output.TagMode = TagMode.StartTagAndEndTag;
        output.TagName = "div";

        var request = ViewContext.HttpContext.Request;
        var absoluteUri = string.Concat(
            request.Scheme,
            "://",
            request.Host.ToUriComponent(),
            request.PathBase.ToUriComponent(),
            request.Path.ToUriComponent(),
            request.QueryString.ToUriComponent());

        output.Attributes.SetAttribute("class", "g-plusone");

        string size = Size.ToLower().Trim() ?? "";
        if (size == "small" || size == "medium" || size == "tall")
            output.Attributes.SetAttribute("data-size", size);

        string annotation = Annotation.ToLower().Trim() ?? "";
        if (annotation == "none" || annotation == "inline")
            output.Attributes.SetAttribute("data-annotation", annotation);

        output.Attributes.SetAttribute("data-href", absoluteUri);
    }
}

And when I put this code in a view:

<google-plusone size="medium" annotation="bubble"  />

It gets rendered in the view like this:

<google-plusone size="medium" annotation="bubble"  >

So, the tag helper is somehow not processing it as it must really output a DIV. Additionally it transforms my raw tag from a self-closing to one that is open and never closes!

Body:
Looks like the Tag Helper is not getting rendered properly. Here is the things you can verify.

Hope you added @addTagHelper *, <Your Assembly Name> in your _ViewImports.cshtml file. If not you need to add it.

Include the reference of Microsoft.AspNetCore.Mvc.TagHelpers in your project file.

Add [HtmlTargetElement("google-plusone")] attribute to your Tag Helper.

Here is the HTML output for me

<div class="g-plus" data-action="share" data-href="http://localhost:5000/"></div>

And here is the screenshot.


Title: Merge two multidimensional lists into one list in Python

Body:
I have two lists:

a_list =
[['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21].......]

b_list =
[['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79].......]

I need to merge a_list with b_list so it becomes:

combined_list =
[['2017-06-03 23:01:49', 0, 100,01], ['2017-06-03 23:02:49', 712.32, 50.01], ['2017-06-03 23:03:49', 501.21, 521.79].......]

How would I achieve this?

Body:
a_list = [['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21]]
b_list = [['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79]]

Assuming a_list and b_list have the same length, and assuming the first sub-item of each item in both lists is always the same, as is true per your example, the solution is a one-liner.

>>> [a + [b[1]] for (a, b) in zip(a_list, b_list)]
[[['2017-06-03 23:01:49', 0, 100.01]], [['2017-06-03 23:02:49', 712.32, 50.01]], [['2017-06-03 23:03:49', 501.21, 521.79]]]


问:
firebase databasereference gives no virtual method error
I am trying to add firebase database some info by getting database reference but it gives the fallowing error:

Caused by: java.lang.NoSuchMethodError: No virtual method zzckb()Z in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.bogroup.ucuncuprogram-1/split_lib_dependencies_apk.apk:classes25.dex)

My java code is lke the fallowing:

```<code>package com.bogroup.ucuncuprogram;

import android.content.Context;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import static com.facebook.FacebookSdk.getApplicationContext;

public class database{

    private Firebase mRootRef;
    private DatabaseReference mDatabase;

    public void kullanicikontrol(String kullaniciadi){
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child("users").child(kullaniciadi).setValue("9999999");
        //chieldref.setValue("9999999");

        Context context = getApplicationContext();
        CharSequence text = kullaniciadi;
        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}
</code>```

What may be the problem, thanks in advance.

My app build.grade is like fallowing:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.bogroup.ucuncuprogram"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    packagingOptions {
        exclude 'META-INF/NOTICE' // will not include NOTICE file
        exclude 'META-INF/LICENSE' // will not include LICENSE file
        // as noted by @Vishnuvathsan you may also need to include
        // variations on the file name. It depends on your dependencies.
        // Some other common variations on notice and license file names
        exclude 'META-INF/notice'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license'
        exclude 'META-INF/license.txt'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:9.4.0'
    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.firebase:firebase-database:9.4.0'
    compile 'com.google.firebase:firebase-crash:9.4.0'
    compile 'com.firebase:firebase-client-android:2.2.4'
    //compile 'com.google.firebase:firebase-storage:9.4.0'
    compile 'com.firebaseui:firebase-ui:0.4.4'
    compile 'com.google.android.gms:play-services-auth:9.4.0'
    compile 'com.android.support:animated-vector-drawable:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'com.android.support:support-v4:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:customtabs:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.firebaseui:firebase-ui-auth:1.2.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    //compile 'com.android.support:customtabs:25.2.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
Your versions of Firebase and Firebase UI need to line up according to the table on their Github Page.

For reference, should you choose to upgrade (I would highly recommend it).

FirebaseUI Version

  1.2.0

Firebase/Play Services Version

  10.2.0

Easy way to do this

```<code>ext {
    googlePlayVer = "10.2.0"
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // For example
    compile "com.google.firebase:firebase-core:${googlePlayVer}"
    compile "com.google.firebase:firebase-auth:${googlePlayVer}"
    compile "com.google.firebase:firebase-database:${googlePlayVer}"
</code>```

Body:
I am trying to add firebase database some info by getting database reference but it gives the fallowing error:

Caused by: java.lang.NoSuchMethodError: No virtual method zzckb()Z in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.bogroup.ucuncuprogram-1/split_lib_dependencies_apk.apk:classes25.dex)

My java code is lke the fallowing:

package com.bogroup.ucuncuprogram;

import android.content.Context;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import static com.facebook.FacebookSdk.getApplicationContext;

public class database{

    private Firebase mRootRef;
    private DatabaseReference mDatabase;

    public void kullanicikontrol(String kullaniciadi){
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child("users").child(kullaniciadi).setValue("9999999");
        //chieldref.setValue("9999999");

        Context context = getApplicationContext();
        CharSequence text = kullaniciadi;
        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

What may be the problem, thanks in advance.

My app build.grade is like fallowing:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.bogroup.ucuncuprogram"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    packagingOptions {
        exclude 'META-INF/NOTICE' // will not include NOTICE file
        exclude 'META-INF/LICENSE' // will not include LICENSE file
        // as noted by @Vishnuvathsan you may also need to include
        // variations on the file name. It depends on your dependencies.
        // Some other common variations on notice and license file names
        exclude 'META-INF/notice'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license'
        exclude 'META-INF/license.txt'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-core:9.4.0'
    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.firebase:firebase-database:9.4.0'
    compile 'com.google.firebase:firebase-crash:9.4.0'
    compile 'com.firebase:firebase-client-android:2.2.4'
    //compile 'com.google.firebase:firebase-storage:9.4.0'
    compile 'com.firebaseui:firebase-ui:0.4.4'
    compile 'com.google.android.gms:play-services-auth:9.4.0'
    compile 'com.android.support:animated-vector-drawable:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'com.android.support:support-v4:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:customtabs:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.firebaseui:firebase-ui-auth:1.2.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    //compile 'com.android.support:customtabs:25.2.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Body:
Your versions of Firebase and Firebase UI need to line up according to the table on their Github Page.

For reference, should you choose to upgrade (I would highly recommend it).

FirebaseUI Version

  1.2.0

Firebase/Play Services Version

  10.2.0

Easy way to do this

ext {
    googlePlayVer = "10.2.0"
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // For example
    compile "com.google.firebase:firebase-core:${googlePlayVer}"
    compile "com.google.firebase:firebase-auth:${googlePlayVer}"
    compile "com.google.firebase:firebase-database:${googlePlayVer}"


问:
How to draw a plot chart using visual studio c++
I want to create a plot chart using visual studio with c++ code. The chart should be based on two axis. "x" axis display the time and "y" axis display the array data. array data have 100 elements and one data read in one second. How do I implement the code using any other graph library?</p>

答:
I answered a very similar question a few years ago... there's a simple, straight and compilable example:
Graphical representation - Data Distribution

Obviously, the chart is not the same one that you need. But you can modify it in order to draw anything you want using C++ and then make any chart.


问:
Python- using a string as a lambda function?
Say I have the following string

```<code>a = "x**2+5"
</code>```

and I want to use it to create the following lambda function:

```<code>b= lambda x: x**2+5
</code>```

How do I do so?

答: You can use eval(): b = lambda x: eval(a). Just remember that using eval() in a real program, where you do not have control over a and x, may cause tons of problems.

Body:
Say I have the following string

a = "x**2+5"

and I want to use it to create the following lambda function:

b= lambda x: x**2+5

How do I do so?


问:
How to programmatically update a label based on the section of a UICollectionView
Say I have a horizontal UICollectionView with 3 sections. I want it to immediately update a label based on which section the user is in as they are scrolling. I found a few solutions that do this by using scrollViewDidEndDecelerating, but I want it to update the moment it goes from section 0 to section 1, from section 1 to section 2, etc.

Any thoughts?

答:
there are

```<code>let indexPath = tableView.indexPathForSelectedRow();
var sectionNumber = indexPath.section
</code>```

and check if 0 show update the first label and so on but i think best place in cell for row at index and get the section number then update it's label

there are another solution

```<code>    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

            //Create label and autoresize it
            let headerLabel = UILabel(frame: CGRectMake(0, 0, tableView.frame.width, 2000))
            headerLabel.font = UIFont(name: "Avenir-Light", size: 30)
            headerLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section)
            headerLabel.sizeToFit()

            //Adding Label to existing headerView
            let headerView = UIView()
            headerView.addSubview(headerLabel)

            return headerView
}
</code>```

also try this

```<code> func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.font = UIFont(name: "Futura", size: 11)
    header.textLabel?.textColor = UIColor.lightGrayColor()
}
</code>```

Body:
there are

let indexPath = tableView.indexPathForSelectedRow();
var sectionNumber = indexPath.section

and check if 0 show update the first label and so on but i think best place in cell for row at index and get the section number then update it's label

there are another solution

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

            //Create label and autoresize it
            let headerLabel = UILabel(frame: CGRectMake(0, 0, tableView.frame.width, 2000))
            headerLabel.font = UIFont(name: "Avenir-Light", size: 30)
            headerLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section)
            headerLabel.sizeToFit()

            //Adding Label to existing headerView
            let headerView = UIView()
            headerView.addSubview(headerLabel)

            return headerView
}

also try this

 func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.font = UIFont(name: "Futura", size: 11)
    header.textLabel?.textColor = UIColor.lightGrayColor()
}


问:
I cannot install aws cli on mac os with pip - awscli: command not found
I tried to follow this tutorial.

This is what I did in the console:

```<code>pip3 install --user --upgrade awscli
</code>```

after that, when I write:

```<code>pip3 --version
</code>```

I'm getting:

```<code>pip 9.0.1 from /Users/user/Library/Python/3.4/lib/python/site-packages (python 3.4)
</code>```

then I wrote:

```<code>pip3 install --user --upgrade awscli
</code>```

this command downloaded awscli and automatically added this:

```<code># Setting PATH for Python 3.4
# The orginal version is saved in .profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH
</code>```

to my .profile

Later on, just to be sure, I wrote:

```<code>source ~/.profile
</code>```

and then when I type:

```<code>user$ aws
-bash: aws: command not found
</code>```

I restarted the terminal with no luck also.

What's the problem here?

答:
Here are the two steps to install AWS cli on mac OSX

FIRST

Offical version

brew install awscli

SECOND

Development version

brew install awscli --HEAD

Body:
I tried to follow this tutorial.

This is what I did in the console:

pip3 install --user --upgrade awscli

after that, when I write:

pip3 --version

I'm getting:

pip 9.0.1 from /Users/user/Library/Python/3.4/lib/python/site-packages (python 3.4)

then I wrote:

pip3 install --user --upgrade awscli

this command downloaded awscli and automatically added this:

# Setting PATH for Python 3.4
# The orginal version is saved in .profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH

to my .profile

Later on, just to be sure, I wrote:

source ~/.profile

and then when I type:

user$ aws
-bash: aws: command not found

I restarted the terminal with no luck also.

What's the problem here?


问:
Transmission of data in HTTP
I am trying to understand the basics of the internals of HTTP servers and clients with regards to how they transmit data. I have read many articles about how HTTP works but I haven't found any that answers some of my questions.
I would like to go trough the process of loading a web page as I understand it and I would appreciate if you make me notice where I got it wrong.

When I visit a site my browser asks for an HTML file to a server, for that my browser creates a socket, binds it to my ip adress, and connects it to a listening socket of the server of the site I am visiting. In order to connect my browser's socket to the server I need a port number and a hostname, the port number is 80 because this is HTTP and the hostname is obtained via DNS resolution. Now that there is a connection between sockets my browser sends a GET request. That request is an ASCII file with the contents corresponding to an HTTP request. My browser writes the ASCII raw bytes to the socket and that is written to the server's socket.

The server writes back the HTML file I requested to the socket. The HTML the server sends is just an ASCII file that the server will write byte by byte to the socket.

My browser recieves the ASCII file and parses it. Lets assume here that it finds an image tag. The browser sends an HTTP request for that image file. Here comes something I don't understand. How does the server respond? As far as I can tell the server must send back an ASCII file formed by a set of headers followed by a CRLF and then the body of the message. In this case, assuming my browser asked for a .jpeg, does the server write the headers as ASCII plaintext to the socket and then writes the raw bytes of the image to the socket?

If the HTML file has several images do we open a socket per image (per request)?

Lets assume that my browser now finds a javascript tag. When the server answers to my request for that script does the server writes the ASCII bytes of the source of the script to the socket? What happens with js libraries? Does the server have to send all the source code for each one?

On writing data to the sockets: is write(2) the correct way to do all this writing between sockets?

On the transmission of large files: if I click a button on the site that lets me download a large PDF, how is this accomplished by the server? I assume that the server tries to transmit this in pieces. As far as I can tell there is an option for chunked encoding. Is this the way? If it is, is the file divided into chunks, and these are appended to the ASCII response and written byte by byte into the socket?

Finally, how is video transmitted? I know video encoding and transmission would require entire books for a detailed explanation but if you could say something about the generalities of video transmission (for example in youtube) I would appreciate it.

Anything that you could say about HTTP on the socket level would be appreciated. Thanks.

答:
It is highly recommended to read High-Performance Browser Networking.

About HTTP

HTTP is a message structuring protocol. It can be built on top of TCP/IP, or UDP, or any other communication protocol.

IP solves the problem of figuring out which computer in a network a message is meant to get to, and TCP solves the problem of ensuring the message gets received despite noise interfering. UDP does what TCP does, but without some important guarantees that make it better in some situations, such as video streaming.

HTTP only solves the problem of what the messages should look like so everyone can understand what you mean. An HTTP message consists of a header and a body. The body is the message you want to send; the header contains meta-information about the status of the message itself. HTTP lets you structure your applications in a meaningful, context-oriented way through a standard set of terms.

For example, you can communicate character encodings of your body with HTTP, how long your content is, whether you are okay with receiving it in a compressed format, and so on and so forth. So, no, HTTP is not limited to ASCII texts - you can send UTF-8 encoded characters with BOM markings, or not even specify an encoding at all. All HTTP does is let you ask for things in the way you want it, and inform recipients how you've packaged a message.

The actual thing responsible for handling how your messages are sent rather than structured are TCP/IP and UDP. HTTP has nothing to do with it. Both TCP/IP and UDP add overhead, but are well worth it so that communication can pass through unimpeded.

About Sockets

Computers listen on "sockets", which is just a fancy name to refer to a communication channel. It does not matter what a socket is - it is just a generic name used to refer to a communication channel, be it a wire or a wireless radio. All that matters is what a socket can do. Computers can send bytes down a socket (called flushing), and can read bytes sent through a socket. Sockets always carry a certain amount of memory reserved for incoming messages (like an inbox) called a buffer, and can even bundle many messages together and send them together in one shot to save time.

Sockets at the hardware level usually devolve to a network card, which lets you talk to wireless network, or to an Ethernet cable. Note that the computer may have many more sockets than cables - this is because a socket is a generic name for a single communication channel, and a single network/ Ethernet card can handle multiple communication channels. Being able to handle multiple channels at once is called multiplexing.

TCP/IP and UDP are just blueprints - it is the responsibility of the operating system to actually do as they lay out, and most OSs have some program designed to implement these standards. At the software level, how information is read and written becomes slightly more complicated than just passing bytes since a computer must also be able to interrupt its running programs when a hardware event happens, including while communicating from a socket - here is a reference for how the Linux kernel implements TCP/IP.

All operating systems expose a set of calls to start listening to (bind) a socket, read a socket and write to a socket. You can read from a socket in multiple ways, however. These range from the basic select() and [poll()] in most Linux distributions, which force the program to wait until all the data requested for has been received and then read it, to epoll() in Linux as well, which enables a program to ask to be notified when data has been received before having to read it.

Windows exports a completely different set of system calls, so you would be well advised to consult a reference manual for the same if planning to build applications for Windows.

About TCP/IP

TCP/IP is a combination of two protocols that has mostly become the norm for ensuring reliable communication.

IP is responsible for the term IP address. Every computer has a unique address associated with it, specified as either a 32-bit number (IPv4) or a 128-bit number (IPv6, or IP version 6). Note that these addresses do not exist outside of a network: a network is just a collection of computers, and a computer's address only makes sense within that collection. The network that the computer comes from is part of the IP address of a computer; the network itself is given a unique address; and a network may be composed of multiple networks. The IP protocol introduces the concept of a port, which is essentially synonymous with the concept of a socket.

I'm just tossing about the term 'network' willy-nilly as an abstract concept, but physically it boils down to a router. A router is a special computer responsible for figuring out who is being referenced to in a message using the IP address attached to the message, for assigning IP addresses to computers it is aware of (a network is quite literally the set of computers the router knows about), and for forwarding messages to other computers or routers. An internetwork (or just the Internet) is simply a bunch of routers, each with their own network, able to communicate to each other to form one giant network of connected networks. Effectively, a router implements the IP standard.

TCP and UDP are designed to solve another harrowing problem: how to ensure all of your messages get through. Sending any message down a shared communication channel like wireless or even wired channels organised like a bus topology is inherently messy - different messages can overlap, messages can be lost unexpectedly, messages can be corrupted and so on. TCP aims to solve these problems by guaranteeing all of a message goes through. On the other hand, UDP makes no such guarantees, and thus saves time by skipping a lot of steps TCP does.

TCP and UDP chunk the message into packets of a certain size, so that a message can be sent out as quickly as possible. TCP further adds some additional structure to the exchange called a three-way handshake:

It sends off a TCP-specific message called a SYN packet to the computer it wants to send a message to, and waits for a response.

If the target computer receives it, it responds with a SYN ACK packet. On receiving this, the source computer responds with an ACK packet. This lets both computers know each other is listening, and they can start sending packets.

On the other hand, if either the source or target computer don't hear anything after a while, they wait for a while and send again, and wait some more. Every time they have to wait, they wait for twice as long as they did last time, until a maximum wait period has been reached and they abort a connection. This is called exponential backoff, and is key to TCP.

A three-way handshake ensures everyone is ready and willing to listen. However, the fun doesn't stop there:

As part of the handshake, the source computer specifies it will fire off an initial certain number of packets, each of a certain size.

After the handshake, the source computer fires off the specified packets, and waits for an ACK for every packet sent. If it doesn't receive an ACK for any packet, it goes into exponential backoff before resending that packet

Meanwhile, the target computer has been told to await a certain number of packets, so it waits until all of them are in. Packets may arrive out of order, depending on how the intervening networks routers chose to optimise the path for each packet, so each packet is prepended with a certain message indicating their order, and the target computer sorts them together into one neat message.

Once the source receives an ACK, it uses the total time taken to see how much it can send next. The better the response time, the more packets TCP is willing to send.

UDP skips the three-way handshake. It only chunks and sends. It is not guaranteed all of your message will get there. It is not guaranteed it will be sent in order (as opposed to received in order). It is perfect for cases where high network reliability means most of your messages will probably arrive, but where it doesn't matter if all of it arrives (e.g . it is okay if some frames in a video don't arrive).

About Video

Video is fundamentally no different from any other content format. It is perfectly possible to use HTTP for videos. Whether it is advisable to use TCP is another matter, but isn't bad - Skype uses both UDP and TCP.

All video consists of a series of bytes. How those bytes are to be interpreted is the job of the encoding. Video can have many encodings: avi and mp4 come readily to mind. With HTTP, you can specify the content encoding as part of the message headers.

HTTP enables compression of content, including for video. HTTP also allows you to request that a connection be kept-alive i.e. that a three-way handshake need not be performed again after a full message has been sent. An extension to HTTP called websockets was developed that effectively use these two features to provide support for real-time video passing. These only optimise the video arrival so it doesn't look laggy, but it doesn't change how the video arrives.

Of course, sometimes you want more guarantees about video, and there are lots and lots of tricks to use to support high-fidelity video in low-speed Internet environments, or enable multiple people to subscribe to a live broadcast, etc. That's when you have to get creative. But otherwise video content is not fundamentally different from any other content type.

To Answer Your Questions

When I visit a site my browser asks for an HTML file to a server, for
  that my browser creates a socket, binds it to my ip adress, and
  connects it to a listening socket of the server of the site I am
  visiting. In order to connect my browser's socket to the server I need
  a port number and a hostname, the port number is 80 because this is
  HTTP and the hostname is obtained via DNS resolution. Now that there
  is a connection between sockets my browser sends a GET request. That
  request is an ASCII file with the contents corresponding to an HTTP
  request. My browser writes the ASCII raw bytes to the socket and that
  is written to the server's socket.

HTTP does not require port 80. It is a convention that port 80 be the default port for HTTP-using servers and 443 for HTTPS, but any port can be used, so long as no other port is occupied.

You do not receive a hostname from DNS. Actually, it's the opposite - you supply a hostname, and retrieve an IP address from DNS. It is the IP address that is used to identify a location on another network.

It is not necessary for the response to be ASCII. Headers, yes, are to be interpreted as ASCII as they are part of an international standard that was developed before UTF-8 gained prominence, but no such restrictions are needed on the body. In fact, the content encoding is traditionally passed along as a header itself, which the browser or a client can use to decode the body content automatically.

The server writes back the HTML file I requested to the socket. The
  HTML the server sends is just an ASCII file that the server will write
  byte by byte to the socket.

Yes, except there is no need for it to be ASCII.

My browser recieves the ASCII file and parses it. Lets assume here
  that it finds an image tag. The browser sends an HTTP request for that
  image file. Here comes something I don't understand. How does the
  server respond? As far as I can tell the server must send back an
  ASCII file formed by a set of headers followed by a CRLF and then the
  body of the message. In this case, assuming my browser asked for a
  .jpeg, does the server write the headers as ASCII plaintext to the
  socket and then writes the raw bytes of the image to the socket?

Yes.

If the HTML file has several images do we open a socket per image (per
  request)?

See this answer. HTML is always downloaded first before the image requests are fired off, and images are always requested for in the order that they are encountered in the DOM. If you have 24 images on Chrome, 6 of them will be loaded in parallel at a time, meaning four parallel connections.

You can additionally answer this yourself by opening up your Network tab in the Chrome console, and inspecting whether requests for images are fired off in parallel.

Lets assume that my browser now finds a javascript tag. When the
  server answers to my request for that script does the server writes
  the ASCII bytes of the source of the script to the socket? What
  happens with js libraries? Does the server have to send all the source
  code for each one?

The HTML specification allows you to select what order you want your Javascript files to be downloaded.

Yes, the server writes bytes. The bytes do not need to be ASCII-encoded. The headers will be in ASCII. Yes, the server must send the source code for each library. This is why an important part of web optimisation is minimising your Javascript file sizes and bundling all the libraries into one file, in order to reduce the number and size of requests.

On writing data to the sockets: is write(2) the correct way to do all
  this writing between sockets?

It is certainly the most basic way to write to an open file descriptor on Linux kernels. Everything in Linux is treated like a file, including sockets, so yes, sockets have file descriptors and can be written to this way.

There are more complex ways of accomplishing this, all of which are referenced in the manual page for write. Most languages have support for writing to sockets, however, by having glue code to manually call write() using a friendlier interface. Perhaps the only time you would need to explicitly call write() in C is if you were writing kernel-level programs or are on embedded hardware.

On the transmission of large files: if I click a button on the site
  that lets me download a large PDF, how is this accomplished by the
  server? I assume that the server tries to transmit this in pieces. As
  far as I can tell there is an option for chunked encoding. Is this the
  way? If it is, is the file divided into chunks, and these are appended
  to the ASCII response and written byte by byte into the socket?

See the TCP/IP section I wrote above. The HTTP standard does let you get away with breaking up a message into higher-order chunks before letting TCP chunk it still further, so you can make do with small segments that arrive at a time.

Finally, how is video transmitted?

See the video section I wrote above.

Title: Transmission of data in HTTP


问:
Spring Boot: Determining what autoconfiguration are applied to jersey?
Following the online docs for adding jersey to Sring boot, it appears I just need to include the following package

```<code>spring-boot-starter-jersey
</code>```

Actually, it states that Spring Boot provides automatic configuration by including this package.

Where can I find out what exactly is happening?

If I don't add this package then what is NOT configured?

I tried searching for the package in google but got no specific explanation only saying that it automatically configures, but configures what?

I would like to know a little more of what is happening behind the scenes.

答:
All of the auto-configuration code for all that Spring Boot supports is in the spring-boot-autoconfigure module. If you look through the packages, you will see a jersey package.

The "starter" modules generally do not have any code (of course unless it is a third-party module). How it works is that the code in the auto-configuration has some annotations that are @ConditionalOnXxx, where the condition be anything from a class being on the classpath. If this class is not available, then the auto-configuration will not take place. That's pretty much all adding the jersey starter module does: it adds the jersey dependencies so that the auto-configurer will applied.

Now what exactly is being auto-configured specifically for Jersey? Check out the source for the JerseyAutoConfiguration. Basically what you are going to see is your ResourceConfig being injected into the configurer. From that ResourceConfig, it creates Jersey's ServletContainer (which is the main entry point for Jersey.

Then, depending on our properties configuration, either a FilterRegistrationBean or a ServletRegistrationBean is created as a Spring bean, wrapping Jersey's ServletContainer. Jersey can be created as a Servlet or a Servlet Filter. Whichever one we configure we be used.

And that's it for the Jersey configuration. Spring Boot will get a servlet container (e.g. Tomcat, Jetty) from some other auto-configuration, and take the Filter/ServletRegistrationBean and add the Servlet/Filter to that servlet container.

Also, not really that important, but the auto-configuration also give us some Jackson configuration helpers. For example, instead of configuring our own ContextResolver, we can just configure an ObjectMapper Spring bean.

That's really all you get. It's nothing so spectacular that you couldn't just do it yourself without depending on the auto-configuration.

Body:
Following the online docs for adding jersey to Sring boot, it appears I just need to include the following package

spring-boot-starter-jersey

Actually, it states that Spring Boot provides automatic configuration by including this package.

Where can I find out what exactly is happening?

If I don't add this package then what is NOT configured?

I tried searching for the package in google but got no specific explanation only saying that it automatically configures, but configures what?

I would like to know a little more of what is happening behind the scenes.


问:
Reference is not a tree error while deploying with capistrano and git
I been able to do capistrano deploys for a while for a certain app but recently I cannot deploy anymore git whines: "fatal: reference is not a tree: a84...". I don't know what did I do, I don't think I changed the deploy file, I am not using git submodules, and the hex reference correspond to the latest commit I do.

Thanks

答: I don't know why but changing the domain from an ip address to my domain solved the issue.</p>


问:
Get JSON and Parse it in Swift?
I am getting json file from url with httpget request. Then, I want to print all tags that comes from json to the screen. I use this code for doing that however, I couldnot get in this way. Can you help me?

Swift 3 code:

```<code>let url:URL = URL(string: "https://api.hurriyet.com.tr/v1/articles...deleted...")!
let session = URLSession.shared

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

let task = session.dataTask(with: request as URLRequest) {
    (data, response, error) in

    guard let data = data, let _:URLResponse = response, error == nil else {
        print("error")
        return
    }

    let dataString =  String(data: data, encoding: String.Encoding.utf8)

    for tags in data{
        for tag in tags["Tags"]{
            print(tag)
        }
    }

}

task.resume()
</code>```

Example json output and dataString variable's output also:

"[{"Tags":["fırat","kalkanı
  operasyonu","gazetehaberleri"]},{"Tags":["yüksek
  yargı","adliye","gazetehaberleri"]},{"Tags":["foo","Hüseyin Avni
  Mutlu","Hüseyin Çapkın","gazetehaberleri"]}]"

答:
First just a few notes about your code. Casting a URLRequest as URLRequest is redundant. You need to use JSONSerialization jsonObject with data method to parse your json data into an array of dictionaries:</p>

```<code>let jsonString = "[{\"Tags\":[\"fırat\",\"kalkanı operasyonu\",\"gazetehaberleri\"]},{\"Tags\":[\"yüksek yargı\",\"adliye\",\"gazetehaberleri\"]},{\"Tags\":[\"foo\",\"Hüseyin Avni Mutlu\",\"Hüseyin Çapkın\",\"gazetehaberleri\"]}]"

let data = Data(jsonString.utf8)

let dictionaries = (try? JSONSerialization.jsonObject(with: data)) as? [[String:Any]] ?? []

for dict in dictionaries {
    let tags = dict["Tags"] as? [String] ?? []

    for tag in tags {
        print(tag)  // fırat
                    // kalkanı operasyonu
                    // gazetehaberleri
                    // yüksek yargı
                    // adliye
                    // gazetehaberleri
                    // foo
                    // Hüseyin Avni Mutlu
                    // Hüseyin Çapkın
                    // gazetehaberleri
    }
}
</code>```

Title: Get JSON and Parse it in Swift?

Body:
I am getting json file from url with httpget request. Then, I want to print all tags that comes from json to the screen. I use this code for doing that however, I couldnot get in this way. Can you help me?

Swift 3 code:

let url:URL = URL(string: "https://api.hurriyet.com.tr/v1/articles...deleted...")!
let session = URLSession.shared

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

let task = session.dataTask(with: request as URLRequest) {
    (data, response, error) in

    guard let data = data, let _:URLResponse = response, error == nil else {
        print("error")
        return
    }

    let dataString =  String(data: data, encoding: String.Encoding.utf8)

    for tags in data{
        for tag in tags["Tags"]{
            print(tag)
        }
    }

}

task.resume()

Example json output and dataString variable's output also:

"[{"Tags":["fırat","kalkanı
  operasyonu","gazetehaberleri"]},{"Tags":["yüksek
  yargı","adliye","gazetehaberleri"]},{"Tags":["foo","Hüseyin Avni
  Mutlu","Hüseyin Çapkın","gazetehaberleri"]}]"

Body:
First just a few notes about your code. Casting a URLRequest as URLRequest is redundant. You need to use JSONSerialization jsonObject with data method to parse your json data into an array of dictionaries:

let jsonString = "[{\"Tags\":[\"fırat\",\"kalkanı operasyonu\",\"gazetehaberleri\"]},{\"Tags\":[\"yüksek yargı\",\"adliye\",\"gazetehaberleri\"]},{\"Tags\":[\"foo\",\"Hüseyin Avni Mutlu\",\"Hüseyin Çapkın\",\"gazetehaberleri\"]}]"

let data = Data(jsonString.utf8)

let dictionaries = (try? JSONSerialization.jsonObject(with: data)) as? [[String:Any]] ?? []

for dict in dictionaries {
    let tags = dict["Tags"] as? [String] ?? []

    for tag in tags {
        print(tag)  // fırat
                    // kalkanı operasyonu
                    // gazetehaberleri
                    // yüksek yargı
                    // adliye
                    // gazetehaberleri
                    // foo
                    // Hüseyin Avni Mutlu
                    // Hüseyin Çapkın
                    // gazetehaberleri
    }
}


问:
Virtual environment build on Sublime Text 3 for Windows
I seem to be unable to run my Sublime Text 3 build with any virtual environment. My latest attempt has been to use the Virtualenv package in sublime text and use the following project settings:

```<code>{
 "folders":
 [
  {
   "path": "."
  }
 ],

    "virutalenv": "C:\\Users\\alexa\\Envs\\test5",
    "settings": "C:\\Users\\alexa\\Envs\\test5\\Scripts\\python"
}
</code>```

My desired venv has pandas installed:

```<code>C:\Users\alexa\Envs\test5\Scripts>activate
(test5) C:\Users\alexa\Envs\test5\Scripts>pip install pandas
Requirement already satisfied: pandas in c:\users\alexa\envs\test5\lib\site-packages
Requirement already satisfied: python-dateutil>=2 in c:\users\alexa\envs\test5\lib\site-packages (from pandas)
Requirement already satisfied: numpy>=1.7.0 in c:\users\alexa\envs\test5\lib\site-packages (from pandas)
Requirement already satisfied: pytz>=2011k in c:\users\alexa\envs\test5\lib\site-packages (from pandas)
Requirement already satisfied: six>=1.5 in c:\users\alexa\envs\test5\lib\site-packages (from python-dateutil>=2->pandas)

(test5) C:\Users\alexa\Envs\test5\Scripts>
</code>```

But when I run my build, which is set to Python + Virtualenv, I get the following:

```<code>Traceback (most recent call last):
  File "C:\Users\alexa\Desktop\SBP\first.py", line 2, in <module>
    import pandas
ModuleNotFoundError: No module named 'pandas'
[Finished in 0.4s with exit code 1]
[shell_cmd: python -u "C:\Users\alexa\Desktop\SBP\first.py"]
[dir: C:\Users\alexa\Desktop\SBP]
[path: C:\Program Files\Dell\DW WLAN Card;;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Python35-32;C:\Python35-32\Lib\site-packages\;C:\Python35-32\Scripts\;%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;]
</code>```

答:
Have you checked out this question? It seems pretty similar, and has some helpful responses. Also, try pip freeze within your virtual environment to see if pandas is installed in your virtual environment.

Python modules not found in virtualenv

Body:
I seem to be unable to run my Sublime Text 3 build with any virtual environment. My latest attempt has been to use the Virtualenv package in sublime text and use the following project settings:

{
 "folders":
 [
  {
   "path": "."
  }
 ],

    "virutalenv": "C:\\Users\\alexa\\Envs\\test5",
    "settings": "C:\\Users\\alexa\\Envs\\test5\\Scripts\\python"
}

My desired venv has pandas installed:

C:\Users\alexa\Envs\test5\Scripts>activate
(test5) C:\Users\alexa\Envs\test5\Scripts>pip install pandas
Requirement already satisfied: pandas in c:\users\alexa\envs\test5\lib\site-packages
Requirement already satisfied: python-dateutil>=2 in c:\users\alexa\envs\test5\lib\site-packages (from pandas)
Requirement already satisfied: numpy>=1.7.0 in c:\users\alexa\envs\test5\lib\site-packages (from pandas)
Requirement already satisfied: pytz>=2011k in c:\users\alexa\envs\test5\lib\site-packages (from pandas)
Requirement already satisfied: six>=1.5 in c:\users\alexa\envs\test5\lib\site-packages (from python-dateutil>=2->pandas)

(test5) C:\Users\alexa\Envs\test5\Scripts>

But when I run my build, which is set to Python + Virtualenv, I get the following:

Traceback (most recent call last):
  File "C:\Users\alexa\Desktop\SBP\first.py", line 2, in <module>
    import pandas
ModuleNotFoundError: No module named 'pandas'
[Finished in 0.4s with exit code 1]
[shell_cmd: python -u "C:\Users\alexa\Desktop\SBP\first.py"]
[dir: C:\Users\alexa\Desktop\SBP]
[path: C:\Program Files\Dell\DW WLAN Card;;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Python35-32;C:\Python35-32\Lib\site-packages\;C:\Python35-32\Scripts\;%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;]