问:
Secure pdf files and Xamarin Forms
I have a forms app which requires authentication.  One of my pages is a webview, and I use cookies to send the authentication status through the webview to the server.  On the webpage is a link to a .pdf file which also requires authentication.  When this link is tapped I grab the url and attempt to open it using Device.OpenUri, but the authentication fails.  Is there a way to send the authentication cookies along with the url to OpenUri, or another way to make the device's browser aware that the user is authenticated?  Or is there another way to download the pdf file in the webview?</p>

答:
Because Device.OpenUri, will just open another app with the url, there is no way to pass authentication through. What you need to do is download the PDF to local storage, then open the PDF from your local storage. You will need to place the file in shared storage on your mobile device to allow the other application to have access to it.

If that is a security risk, you will need to add an internal PDF Viewer to your app, so you can view the PDF in your app internally.

Now, if you want to download the PDF, you will need to use HttpClient. In iOS and UWP, the HttpClient and WebView share the same cookie container, which means if you authenticated on the WebView, it will already be authenticated in the HttpClient. For Android, you need to copy the authentication cookies across.

First establish a cookie container you can read.

```<code>CookieContainer _cookieContainer = new CookieContainer();
System.Net.Http.HttpClient _client = new System.Net.Http.HttpClient(new HttpClientHandler() { CookieContainer = _cookieContainer });
</code>```

Then depending upon which way you want to copy, you can do

```<code>private void CopyCookies(HttpResponseMessage result, Uri uri)
{
    foreach (var header in result.Headers)
        if (header.Key.ToLower() == "set-cookie")
            foreach (var value in header.Value)
                 _cookieManager.SetCookie($"{uri.Scheme}://{uri.Host}", value);

    foreach (var cookie in GetAllCookies(_cookieContainer))
        _cookieManager.SetCookie(cookie.Domain, cookie.ToString());
}
</code>```

or

```<code>public void ReverseCopyCookies(Uri uri)
{
    var cookie = _cookieManager.GetCookie($"{uri.Scheme}://{uri.Host}");

    if (!string.IsNullOrEmpty(cookie))
        _cookieContainer.SetCookies(new Uri($"{uri.Scheme}://{uri.Host}"), cookie);
}
</code>```

I go into more detail in Cookie Sharing with WebView and the Http Client.

Title: Secure pdf files and Xamarin Forms

Body:
Because Device.OpenUri, will just open another app with the url, there is no way to pass authentication through. What you need to do is download the PDF to local storage, then open the PDF from your local storage. You will need to place the file in shared storage on your mobile device to allow the other application to have access to it.

If that is a security risk, you will need to add an internal PDF Viewer to your app, so you can view the PDF in your app internally.

Now, if you want to download the PDF, you will need to use HttpClient. In iOS and UWP, the HttpClient and WebView share the same cookie container, which means if you authenticated on the WebView, it will already be authenticated in the HttpClient. For Android, you need to copy the authentication cookies across.

First establish a cookie container you can read.

CookieContainer _cookieContainer = new CookieContainer();
System.Net.Http.HttpClient _client = new System.Net.Http.HttpClient(new HttpClientHandler() { CookieContainer = _cookieContainer });

Then depending upon which way you want to copy, you can do

private void CopyCookies(HttpResponseMessage result, Uri uri)
{
    foreach (var header in result.Headers)
        if (header.Key.ToLower() == "set-cookie")
            foreach (var value in header.Value)
                 _cookieManager.SetCookie($"{uri.Scheme}://{uri.Host}", value);

    foreach (var cookie in GetAllCookies(_cookieContainer))
        _cookieManager.SetCookie(cookie.Domain, cookie.ToString());
}

or

public void ReverseCopyCookies(Uri uri)
{
    var cookie = _cookieManager.GetCookie($"{uri.Scheme}://{uri.Host}");

    if (!string.IsNullOrEmpty(cookie))
        _cookieContainer.SetCookies(new Uri($"{uri.Scheme}://{uri.Host}"), cookie);
}

I go into more detail in Cookie Sharing with WebView and the Http Client.


来源: stackexchange

问:
Setting Android images from string value
Currently I'm drawing a PNG image in my Android application like so:

```<code>ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))
</code>```

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

```<code>ID:    Name:    ImageName:
-      Test     testimage
</code>```

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

```<code>int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;
</code>```

However this isn't very efficient!

Thanks

答:
There is a method for doing that, you can retreive resource IDs by string using Resources.getIdentifier() http://developer.android.com/reference/android/content/res/Resources.html

Something like:

```<code>int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Currently I'm drawing a PNG image in my Android application like so:

ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

ID:    Name:    ImageName:
-      Test     testimage

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;

However this isn't very efficient!

Thanks

Body:
There is a method for doing that, you can retreive resource IDs by string using Resources.getIdentifier() http://developer.android.com/reference/android/content/res/Resources.html

Something like:

int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");


问:
flexbox overflowing container in firefox
I'm working on a flexbox layout and I have an issue where the flex items will overflow the container in firefox only. Here's as stripped down an example as I could come up with (sorry it's not super minimal, I'm unsure what's causing the issue, so it's hard to know what I can remove):

```<code><div class="css-190tu11">
  <h1 class="css-1qqir8k">Blah</h1>
  <div class="css-131b9cy">
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-kujdaf">
        Some special thing
      </div>
    </div>
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-dkez8"></div>
    </div>
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-dkez8"></div>
    </div>
    <div class="css-1suni8j">
      <a class="css-yq2t95" href="some-url">
        <span class="icon icon-register css-nwymqb" aria-hidden="true"></span>
        <h2 class="css-1892n22">Title</h2>
        <div class="css-kgza95">Description</div>
      </a>
      <div class="css-dkez8"></div
    </div>
  </div>
</div>
</code>```

And the CSS:

```<code>.css-190tu11,
[data-css-190tu11] {
  padding: 12px 48px 24px 48px;
  border: solid 1px #e0e0e0;
}
.css-1qqir8k,
[data-css-1qqir8k] {
  font-size: 24px;
  font-weight: 300;
  margin-bottom: 18px;
  margin-top: 0;
}
.css-131b9cy,
[data-css-131b9cy] {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.css-131b9cy > *,
[data-css-131b9cy] > * {
  flex: 0 1 auto;
  margin-left: 0;
  margin-right: 0;
}
.css-131b9cy > *:not(:first-child),
[data-css-131b9cy] > *:not(:first-child) {
  margin-left: 10px;
}
.css-131b9cy > *:not(:last-child),
[data-css-131b9cy] > *:not(:last-child) {
  margin-right: 10px;
}

.css-1suni8j,
[data-css-1suni8j] {
  display: flex;
  background-color: white;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  max-width: 186px;
  min-width: 120px;
  height: 240px;
}
.css-1suni8j > *,
[data-css-1suni8j] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-1suni8j > *:not(:first-child),
[data-css-1suni8j] > *:not(:first-child) {
  margin-top: 10px;
}
.css-1suni8j > *:not(:last-child),
[data-css-1suni8j] > *:not(:last-child) {
  margin-bottom: 10px;
}

.css-yq2t95,
[data-css-yq2t95] {
  flex: 1;
  justify-content: space-between;
  flex-direction: column;
  display: flex;
}
.css-yq2t95 > *:last-child,
[data-css-yq2t95] > *:last-child {
  flex: 0 1 auto;
}
.css-yq2t95 > *,
[data-css-yq2t95] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-yq2t95 > *:not(:first-child),
[data-css-yq2t95] > *:not(:first-child) {
  margin-top: 5px;
}
.css-yq2t95 > *:not(:last-child),
[data-css-yq2t95] > *:not(:last-child) {
  margin-bottom: 5px;
}

.css-nwymqb,
[data-css-nwymqb] {
  transition: all 0.5s ease;
  border-radius: 50%;
  display: block;
  margin-left: auto;
  border: 1px solid #0070ba;
  height: 60px;
  width: 60px;
  font-size: 30px;
  line-height: 54px;
  margin-right: auto;
}

.css-1892n22,
[data-css-1892n22] {
  font-weight: normal;
  flex: 0 1 auto;
  color: inherit;
  padding: 0;
  font-size: 16px;
  height: 80px;
}
.css-kgza95,
[data-css-kgza95] {
  font-weight: normal;
  font-size: 11px;
  color: #333333;
  height: 76px;
}
.css-kujdaf,
[data-css-kujdaf] {
  min-height: 36px;
  background-image: linear-gradient(93deg, #1446a0, #0070ba);
  width: 100%;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}
.css-dkez8,
[data-css-dkez8] {
  min-height: 36px;
}
</code>```

Here's what it looks like in Chrome and Safari (this is what I want it to look like):

And here's what it looks like in Firefox:

Even Internet Explorer 10 shows it the way I want! (Can't verify in the codepen because I removed vendor prefixes, but it works in my app).

Here's a codepen for this.

Thanks for any help!

答:
The container with the class css-1suni8j has a fixed height (240px), and also the elements in there (h2, DIV) have fixed widths which makes the last DIV with the button go under its border. If you erase the 240px height, it will remain inside the container.

Since there is a varying number of elements in your columns and justify-content is space-between, there's no way to keep the other elements a t the same height.

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a flexbox layout and I have an issue where the flex items will overflow the container in firefox only. Here's as stripped down an example as I could come up with (sorry it's not super minimal, I'm unsure what's causing the issue, so it's hard to know what I can remove):

Blah

Title

Description

        Some special thing

Title

Description

Title

Description

Title

Description

</div

And the CSS:

.css-190tu11,
[data-css-190tu11] {
  padding: 12px 48px 24px 48px;
  border: solid 1px #e0e0e0;
}
.css-1qqir8k,
[data-css-1qqir8k] {
  font-size: 24px;
  font-weight: 300;
  margin-bottom: 18px;
  margin-top: 0;
}
.css-131b9cy,
[data-css-131b9cy] {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.css-131b9cy > *,
[data-css-131b9cy] > * {
  flex: 0 1 auto;
  margin-left: 0;
  margin-right: 0;
}
.css-131b9cy > *:not(:first-child),
[data-css-131b9cy] > *:not(:first-child) {
  margin-left: 10px;
}
.css-131b9cy > *:not(:last-child),
[data-css-131b9cy] > *:not(:last-child) {
  margin-right: 10px;
}

.css-1suni8j,
[data-css-1suni8j] {
  display: flex;
  background-color: white;
  flex-direction: column;
  justify-content: space-between;
  text-align: center;
  max-width: 186px;
  min-width: 120px;
  height: 240px;
}
.css-1suni8j > *,
[data-css-1suni8j] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-1suni8j > *:not(:first-child),
[data-css-1suni8j] > *:not(:first-child) {
  margin-top: 10px;
}
.css-1suni8j > *:not(:last-child),
[data-css-1suni8j] > *:not(:last-child) {
  margin-bottom: 10px;
}

.css-yq2t95,
[data-css-yq2t95] {
  flex: 1;
  justify-content: space-between;
  flex-direction: column;
  display: flex;
}
.css-yq2t95 > *:last-child,
[data-css-yq2t95] > *:last-child {
  flex: 0 1 auto;
}
.css-yq2t95 > *,
[data-css-yq2t95] > * {
  margin-top: 0;
  margin-bottom: 0;
}
.css-yq2t95 > *:not(:first-child),
[data-css-yq2t95] > *:not(:first-child) {
  margin-top: 5px;
}
.css-yq2t95 > *:not(:last-child),
[data-css-yq2t95] > *:not(:last-child) {
  margin-bottom: 5px;
}

.css-nwymqb,
[data-css-nwymqb] {
  transition: all 0.5s ease;
  border-radius: 50%;
  display: block;
  margin-left: auto;
  border: 1px solid #0070ba;
  height: 60px;
  width: 60px;
  font-size: 30px;
  line-height: 54px;
  margin-right: auto;
}

.css-1892n22,
[data-css-1892n22] {
  font-weight: normal;
  flex: 0 1 auto;
  color: inherit;
  padding: 0;
  font-size: 16px;
  height: 80px;
}
.css-kgza95,
[data-css-kgza95] {
  font-weight: normal;
  font-size: 11px;
  color: #333333;
  height: 76px;
}
.css-kujdaf,
[data-css-kujdaf] {
  min-height: 36px;
  background-image: linear-gradient(93deg, #1446a0, #0070ba);
  width: 100%;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}
.css-dkez8,
[data-css-dkez8] {
  min-height: 36px;
}

Here's what it looks like in Chrome and Safari (this is what I want it to look like):

And here's what it looks like in Firefox:

Even Internet Explorer 10 shows it the way I want! (Can't verify in the codepen because I removed vendor prefixes, but it works in my app).

Here's a codepen for this.

Thanks for any help!


问:
Change Data Capture For Updates and Deletes Only
Our database is insert inensive (200-500k per night) but update light (maybe a few hundred per day).

I need to preserve a history of all changes to the inserted rows themselves for an indefinite period of time (but not the actual insert). I would love to use Change Data Capture but the amount of space required to support this is not avaiable. If I can figure out of to do one of the following, my life would be much easier.

1) Limite change data tracking to UPDATES and DELETES only
2) Cleanup only INSERTS from the CDC tables regularly

In the past, I'd have just used a trigger (which is still not off the table!).

答:
If space is a consideration, you can always assign the CDC tables to work with a different filegroup that could potentially live on a different server.  You'd do that this way:

```<code> ALTER DATABASE YourDatabase
 ADD FILEGROUP [cdc_ChangeTables];
 go

 --this step requires going on to somewhere on your hard drive and creating a folder
 ALTER DATABASE YourDatabase
 ADD FILE ( NAME = N'cdc_ChangeTables',
            FILENAME = N'E:\NameOfFolderYouSetUp\YourDatabase_cdc_ChangeTables.mdf',
            SIZE = 1048576KB,
            FILEGROWTH = 102400KB )
 TO FILEGROUP [cdc_ChangeTables];
 GO
</code>```

Then when you want to set up your CDC tables, you point them toward that filegroup instead:

```<code>EXEC sys.sp_cdc_enable_table
    @source_schema = N'dbo',
    @source_name = N'TableYouWantToCapture',
    @role_name = N'cdc_admin',
    @filegroup_name = N'cdc_ChangeTables', --this is where you name the filegroup from previous step
    @supports_net_changes = 1,
    @capture_instance = N'dbo_TableYouWantToCapture',
    @captured_column_list = 'ColumnName1, ColumnName2'; --comma-delimited list of column names
GO
</code>```

If you want to query only updates/deletes, you can use the system function like so:

```<code>SELECT *
FROM cdc.fn_cdc_get_all_changes_dbo_TableYouWantToCapture(@from_lsn, @to_lsn, N'all update old')
WHERE __$operation IN (1,3,4)
</code>```

Body:
If space is a consideration, you can always assign the CDC tables to work with a different filegroup that could potentially live on a different server.  You'd do that this way:

 ALTER DATABASE YourDatabase
 ADD FILEGROUP [cdc_ChangeTables];
 go

 --this step requires going on to somewhere on your hard drive and creating a folder
 ALTER DATABASE YourDatabase
 ADD FILE ( NAME = N'cdc_ChangeTables',
            FILENAME = N'E:\NameOfFolderYouSetUp\YourDatabase_cdc_ChangeTables.mdf',
            SIZE = 1048576KB,
            FILEGROWTH = 102400KB )
 TO FILEGROUP [cdc_ChangeTables];
 GO

Then when you want to set up your CDC tables, you point them toward that filegroup instead:

EXEC sys.sp_cdc_enable_table
    @source_schema = N'dbo',
    @source_name = N'TableYouWantToCapture',
    @role_name = N'cdc_admin',
    @filegroup_name = N'cdc_ChangeTables', --this is where you name the filegroup from previous step
    @supports_net_changes = 1,
    @capture_instance = N'dbo_TableYouWantToCapture',
    @captured_column_list = 'ColumnName1, ColumnName2'; --comma-delimited list of column names
GO

If you want to query only updates/deletes, you can use the system function like so:

SELECT *
FROM cdc.fn_cdc_get_all_changes_dbo_TableYouWantToCapture(@from_lsn, @to_lsn, N'all update old')
WHERE __$operation IN (1,3,4)


问:
naming the tables in a multipart from statement
I am running a query where I have 3 table variables of independent identifiers.  I want to cross join them to match up each combination from another table.

This runs fine

```<code>select i.*, d.*
  from @ids as i, @dates as d, @values as v
</code>```

But when I run

```<code>select i.*, d.*
  from @ids as i, @dates as d, @values as v
  join other_table as ot with (nolock)
    on i.id_ = ot.someid
   and d.date_ = ot.somedate
   and v.item_ = ot.someitem
</code>```

Only the last table v is recognized and I get

```<code>Msg 4104, Level 16, State 1, Line 10084
The multi-part identifier "d.date_" could not be bound.
Msg 4104, Level 16, State 1, Line 10085
The multi-part identifier "v.item_" could not be bound.
</code>```

What is the appropriate way to do this?

答:
Simple rule.  Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

In your case, you want CROSS JOIN:

```<code>select i.*, d.*
from @ids i cross join
     @dates d cross join
     @values v join
     other_tabl ot
     on i.id_ = ot.someid and
        d.date_ = ot.somedate snf
        v.item_ = ot.someitem;
</code>```

A comma is not exactly the same as CROSS JOIN.  In addition to generating a Cartesian product of the rows in the tables, it also has scoping implications.  Basically, the comma separates the name spaces in the FROM clause.  So, the tables/aliases defined before the comma are not available afterwards.  (Of course, they are available in other clauses in the query such as WHERE.)

Body:
I am running a query where I have 3 table variables of independent identifiers.  I want to cross join them to match up each combination from another table.

This runs fine

select i.*, d.*
  from @ids as i, @dates as d, @values as v

But when I run

select i.*, d.*
  from @ids as i, @dates as d, @values as v
  join other_table as ot with (nolock)
    on i.id_ = ot.someid
   and d.date_ = ot.somedate
   and v.item_ = ot.someitem

Only the last table v is recognized and I get

Msg 4104, Level 16, State 1, Line 10084
The multi-part identifier "d.date_" could not be bound.
Msg 4104, Level 16, State 1, Line 10085
The multi-part identifier "v.item_" could not be bound.

What is the appropriate way to do this?

Body:
Simple rule.  Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

In your case, you want CROSS JOIN:

select i.*, d.*
from @ids i cross join
     @dates d cross join
     @values v join
     other_tabl ot
     on i.id_ = ot.someid and
        d.date_ = ot.somedate snf
        v.item_ = ot.someitem;

A comma is not exactly the same as CROSS JOIN.  In addition to generating a Cartesian product of the rows in the tables, it also has scoping implications.  Basically, the comma separates the name spaces in the FROM clause.  So, the tables/aliases defined before the comma are not available afterwards.  (Of course, they are available in other clauses in the query such as WHERE.)


问:
Excel VBA code to attach files in QC Test Cases
I have a tool that capture screenshots of the application that we test at our workplace. Now once I complete my testing of a particular test case or scenarios, we attach the screenshot that we have taken to HP Quality Center manually.

I want to automate this and make my tool to upload the word document to a test in QC Test Lab. Is this possible? If Yes, How can we do this in Excel VBA?

Operations that we need to perform would be as below:

Connect to QC project with login credentials, domain & project details

Pick a file(s) from a local folder

Upload a file(s) to QC Test Lab, specific test case

I used the below code, but getting error in that code. I marked it in the code below, please check below :

```<code>Dim intTestID, FldPath, TestSetName, i
Dim TestSetFact, tsTreeMgr, tSetFolder, TestSetsList, theTestSet
Dim TestSetIdentifier, TSTestFact, TestSetTestsList, testInstanceF, aFilter
Dim lst, tstInstance

intTestID = "8968"

FldPath = TextBox3.Text '"Root\ProjFold\Release1\BRD"
TestSetName = ComboBox3.Text '"BRD" '

Set Connection = CreateObject("TDApiOle80.TDConnection")
Connection.InitConnectionEx Sheet2.Range("B1").Value2
Connection.Login TextBox1.Text, TextBox2.Text
Connection.Connect ComboBox1.Text, ComboBox2.Text

Set TestSetFact = Connection.TestSetFactory
Set tsTreeMgr = Connection.TestSetTreeManager

Set tSetFolder = tsTreeMgr.NodeByPath(FldPath)
Set TestSetsList = tSetFolder.FindTestSets(TestSetName)
Set theTestSet = TestSetsList.Item(1)
TestSetIdentifier = theTestSet.ID
i = 0
Set TSTestFact = theTestSet.TSTestFactory
Set TestSetTestsList = TSTestFact.NewList("")

Set testInstanceF = Connection.TSTestFactory
Set aFilter = testInstanceF.Filter

aFilter.Filter("TC_TEST_ID") = intTestID
Set lst = testInstanceF.NewList(aFilter.Text)
Set tstInstance = lst.Item(1)   <---------------- getting error here
MsgBox (tstInstance.Field("TS_Name"))
'tstInstance.Status = "Failed"
'tstInstance.Field("TC_STATUS") = Item1.Status '"Passed"
'tstInstance.Post
Dim RunF, runName, NewRun, runStepF, runlst, Item1, runStep2

MsgBox (tstInstance.Field("TS_Subject"))
Set RunF = tstInstance.RunFactory
runName = "Run_" & Month(Date) & "-" & Day(Date) & "_" & Hour(Now) & "-" & Minute(Now) &         "-" & Second(Now)
Set NewRun = RunF.AddItem(Null)
NewRun.Status = "Passed"
NewRun.Name = runName
NewRun.Post
NewRun.CopyDesignSteps
NewRun.Post
Set runStepF = NewRun.StepFactory
Set runlst = runStepF.NewList("")
For Each Item1 In runlst
      Set runStep2 = Item1
      runStep2.Status = "Passed" '
      runStep2.Field("ST_ACTUAL") = "As Expected"
      runStep2.Post
Next
'tstInstance.Refresh
tstInstance.Status = "Failed"

tstInstance.Post
Connection.DisconnectProject
Connection.ReleaseConnection
'Set QC = Nothing
Set Connection = Nothing
</code>```

答:
The error is occurring because the array of objects is not returning. You need to check if the Filter gives you a list of results before assuming that lst.Item(1) exists.

For instance:

```<code>If lst.Count > 0 Then Set tstInstance = lst.Item(1)
</code>```

Body:
I have a tool that capture screenshots of the application that we test at our workplace. Now once I complete my testing of a particular test case or scenarios, we attach the screenshot that we have taken to HP Quality Center manually.

I want to automate this and make my tool to upload the word document to a test in QC Test Lab. Is this possible? If Yes, How can we do this in Excel VBA?

Operations that we need to perform would be as below:

Connect to QC project with login credentials, domain & project details

Pick a file(s) from a local folder

Upload a file(s) to QC Test Lab, specific test case

I used the below code, but getting error in that code. I marked it in the code below, please check below :

Dim intTestID, FldPath, TestSetName, i
Dim TestSetFact, tsTreeMgr, tSetFolder, TestSetsList, theTestSet
Dim TestSetIdentifier, TSTestFact, TestSetTestsList, testInstanceF, aFilter
Dim lst, tstInstance

intTestID = "8968"

FldPath = TextBox3.Text '"Root\ProjFold\Release1\BRD"
TestSetName = ComboBox3.Text '"BRD" '

Set Connection = CreateObject("TDApiOle80.TDConnection")
Connection.InitConnectionEx Sheet2.Range("B1").Value2
Connection.Login TextBox1.Text, TextBox2.Text
Connection.Connect ComboBox1.Text, ComboBox2.Text

Set TestSetFact = Connection.TestSetFactory
Set tsTreeMgr = Connection.TestSetTreeManager

Set tSetFolder = tsTreeMgr.NodeByPath(FldPath)
Set TestSetsList = tSetFolder.FindTestSets(TestSetName)
Set theTestSet = TestSetsList.Item(1)
TestSetIdentifier = theTestSet.ID
i = 0
Set TSTestFact = theTestSet.TSTestFactory
Set TestSetTestsList = TSTestFact.NewList("")

Set testInstanceF = Connection.TSTestFactory
Set aFilter = testInstanceF.Filter

aFilter.Filter("TC_TEST_ID") = intTestID
Set lst = testInstanceF.NewList(aFilter.Text)
Set tstInstance = lst.Item(1)   <---------------- getting error here
MsgBox (tstInstance.Field("TS_Name"))
'tstInstance.Status = "Failed"
'tstInstance.Field("TC_STATUS") = Item1.Status '"Passed"
'tstInstance.Post
Dim RunF, runName, NewRun, runStepF, runlst, Item1, runStep2

MsgBox (tstInstance.Field("TS_Subject"))
Set RunF = tstInstance.RunFactory
runName = "Run_" & Month(Date) & "-" & Day(Date) & "_" & Hour(Now) & "-" & Minute(Now) &         "-" & Second(Now)
Set NewRun = RunF.AddItem(Null)
NewRun.Status = "Passed"
NewRun.Name = runName
NewRun.Post
NewRun.CopyDesignSteps
NewRun.Post
Set runStepF = NewRun.StepFactory
Set runlst = runStepF.NewList("")
For Each Item1 In runlst
      Set runStep2 = Item1
      runStep2.Status = "Passed" '
      runStep2.Field("ST_ACTUAL") = "As Expected"
      runStep2.Post
Next
'tstInstance.Refresh
tstInstance.Status = "Failed"

tstInstance.Post
Connection.DisconnectProject
Connection.ReleaseConnection
'Set QC = Nothing
Set Connection = Nothing

Body:
The error is occurring because the array of objects is not returning. You need to check if the Filter gives you a list of results before assuming that lst.Item(1) exists.

For instance:

If lst.Count > 0 Then Set tstInstance = lst.Item(1)


问:
Twilio Send SMS throw exeption Salesforce
I am trying to send and SMS using Twilio but getting an error. Earlier it was working fine but now I am getting an exception : TwilioRestException: Script-thrown exception.

I suspect its a enhancement in Salesforce but don't know how to fix it. Any suggestion is appreciated.

Thanks!

答:
Twilio recently deprecated the SMS/Messages resource and replaced with Messages resource. You can view the change log here:

https://www.twilio.com/docs/api/rest/sms

I also encountered a similar issue and resolved by implementing the new process. Hope this helps!


问:
How to get external data without CORS headers with Firebase hosted webapp?
I have my Ionic2 app hosted on Firebase. What I need is to get external data from an API service where

No 'Access-Control-Allow-Origin' header is present on the requested
  resource

I can work around it locally by using proxies in ionic.config.json file:

```<code>"proxies": [
{
"path":"/api",
"proxyUrl": "https://api.somwhere.com/"
}
]
</code>```

But I have no idea how to deal with this after deploying my app to Firebase. Is it somehow possible?

答:
The Firebase docs have an example of setting the Access-Control-Allow-Origin in your firebase.json to allow cross-origin requests for font files. You could adjust that like this:

```<code>"headers": [ {
  "source" : "**",
  "headers" : [ {
    "key" : "Access-Control-Allow-Origin",
    "value" : "*"
  } ]
}
</code>```

That will allow cross-origin requests for all resources. Of course if you want to restrict it to specific resources, you can adjust the source value.

Body:
I have my Ionic2 app hosted on Firebase. What I need is to get external data from an API service where

No 'Access-Control-Allow-Origin' header is present on the requested
  resource

I can work around it locally by using proxies in ionic.config.json file:

"proxies": [
{
"path":"/api",
"proxyUrl": "https://api.somwhere.com/"
}
]

But I have no idea how to deal with this after deploying my app to Firebase. Is it somehow possible?

Body:
The Firebase docs have an example of setting the Access-Control-Allow-Origin in your firebase.json to allow cross-origin requests for font files. You could adjust that like this:

"headers": [ {
  "source" : "**",
  "headers" : [ {
    "key" : "Access-Control-Allow-Origin",
    "value" : "*"
  } ]
}

That will allow cross-origin requests for all resources. Of course if you want to restrict it to specific resources, you can adjust the source value.


问:
Make background image clickable with other links and elements inside the same div
Right now the code below generates the content seen here:

Currently the title has to be clicked for the post page to be loaded, but I want to allow the entire background image to be clickable. Is this possible? I've tried surrounding the card div with the  tag from the title code, but that still did not let me click the background image like a link.

```<code><article id="post-<?php the_ID(); ?>" <?php post_class('card-box col-lg-4 col-md-6 col-sm-12 col-xs-12'); ?>>
    <div class="card" data-background="image" data-src="<?php esc_url( the_post_thumbnail_url( 'large' ) ); ?>">
             <div class="header">
                    <?php
                    $categories = get_the_category();
                    if ( ! empty( $categories ) ) {
                    ?>
                        <div class="category">
                            <h6>
                                <span class="category">
                                    <?php  echo '<a class="category" href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>'; ?>
                                </span>
                            </h6>
                        </div>
                    <?php } ?>
                </div>
                <div class="content">
                    <?php the_title( '<h4 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h4>' ); ?>
                    <span class="date"><?php echo esc_html( get_the_date() ); ?></span>
                </div>
                <div class="filter"></div>
                </div> <!-- end card -->
        </article>
</code>```

答:
Try jQuery approach like below   </p>

```<code>$('.card').on('click', function(event){
  var elementTag = event.target.tagName.toLowerCase();
  if(elementTag === 'div') {
     var pageurl = $(this).find('.entry-title a').attr('href');
     window.location.href = pageurl;
  }
});`
</code>```

Body:
Right now the code below generates the content seen here:

Currently the title has to be clicked for the post page to be loaded, but I want to allow the entire background image to be clickable. Is this possible? I've tried surrounding the card div with the  tag from the title code, but that still did not let me click the background image like a link.

<article id="post-<?php the_ID(); ?>" <?php post_class('card-box col-lg-4 col-md-6 col-sm-12 col-xs-12'); ?>>
    <div class="card" data-background="image" data-src="<?php esc_url( the_post_thumbnail_url( 'large' ) ); ?>">

                    <?php
                    $categories = get_the_category();
                    if ( ! empty( $categories ) ) {
                    ?>

                                    <?php  echo 'term_id ) ) . '">' . esc_html( $categories[0]->name ) . ''; ?>

                    <?php } ?>

                    <?php the_title( '
', '
' ); ?>
                    <?php echo esc_html( get_the_date() ); ?>

Body:
Try jQuery approach like below

$('.card').on('click', function(event){
  var elementTag = event.target.tagName.toLowerCase();
  if(elementTag === 'div') {
     var pageurl = $(this).find('.entry-title a').attr('href');
     window.location.href = pageurl;
  }
});`


问:
Transparent Image Overlay
I am trying to create a partially transparent blue overlay on an image. Like this-
http://tinypic.com/r/2gtnq0i/9

Here is my attempt:
https://jsfiddle.net/ypqL4zL4/

I thought that setting

```<code>z-index: 10;
</code>```

would solve the issue, but I was wrong.

答:
Your problem is that the image is contained within the element that has a background, so you can't see the background since the image is blocking it. Instead, have a div that contains the image, then the overlay. Here's the code:

.container {
  position: relative;
  height: 200px;
  width: 200px;
  overflow: hidden;
}
.image-size{
  height: 200px;
  z-index: 1;
}
.overlay{
  height: 200px;
  width: 200px;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(66, 134, 244,.7);
  z-index: 10;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img class="image-size" src="http://cdn2-www.dogtime.com/assets/uploads/gallery/30-impossibly-cute-puppies/impossibly-cute-puppy-8.jpg">
  <div class="overlay">
  </div>
</div></code>```

Title: Transparent Image Overlay

Body:
I am trying to create a partially transparent blue overlay on an image. Like this-
http://tinypic.com/r/2gtnq0i/9

Here is my attempt:
https://jsfiddle.net/ypqL4zL4/

I thought that setting

z-index: 10;

would solve the issue, but I was wrong.

Body:
Your problem is that the image is contained within the element that has a background, so you can't see the background since the image is blocking it. Instead, have a div that contains the image, then the overlay. Here's the code:

.container {
  position: relative;
  height: 200px;
  width: 200px;
  overflow: hidden;
}
.image-size{
  height: 200px;
  z-index: 1;
}
.overlay{
  height: 200px;
  width: 200px;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(66, 134, 244,.7);
  z-index: 10;
}

<div class="container">
  <img class="image-size" src="http://cdn2-www.dogtime.com/assets/uploads/gallery/30-impossibly-cute-puppies/impossibly-cute-puppy-8.jpg">
  <div class="overlay">
  </div>
</div>


问:
In Mercurial how do I extract a single file's changes from a Changeset to apply to another branch?
I have a large commit of many files on one branch, I need to transfer the modifications of a single file in that changeset to another branch. How can I do this? I am mostly using TortoiseHg but commandline solutions are also fine.

If I go to the changeset in TortoiseHg and select the file I can see the diffs I want to transfer, but not a way to actually apply them.

答:
The most basic solution is to dump the patch of the file, apply it to the current working revision, and commit it (assuming you're at the root of the repository):

```<code>$ hg up <revision-to-apply-the-patch-to>
$ hg diff -c <revision-containing-the-patch> <files-to-include> | patch -p0
$ hg ci -m "Transplanting selected changes from <revision-contain...>"
</code>```

The drawback of this method is that it isn't very obvious what you've done from a revision history perspective. A good commit message helps here, but the history graph gives no hint about the process of transplanting some changes. In that case merging and reverting may be a better solution:

```<code>$ hg up <revision-to-apply-the-patch-to>
$ hg merge -r <revision-containing-the-patch>
$ hg revert --no-backup <files-to-exclude>
$ hg ci -m "Merge in changes of <files-to-include>"
</code>```

Probably there are more solutions to do this -- these two came to my mind first.

Body:
The most basic solution is to dump the patch of the file, apply it to the current working revision, and commit it (assuming you're at the root of the repository):

$ hg up <revision-to-apply-the-patch-to>
$ hg diff -c <revision-containing-the-patch> <files-to-include> | patch -p0
$ hg ci -m "Transplanting selected changes from <revision-contain...>"

The drawback of this method is that it isn't very obvious what you've done from a revision history perspective. A good commit message helps here, but the history graph gives no hint about the process of transplanting some changes. In that case merging and reverting may be a better solution:

$ hg up <revision-to-apply-the-patch-to>
$ hg merge -r <revision-containing-the-patch>
$ hg revert --no-backup <files-to-exclude>
$ hg ci -m "Merge in changes of <files-to-include>"

Probably there are more solutions to do this -- these two came to my mind first.


问:
Is there any way to automate windows forms testing?
I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer.

I have seen watin and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source.

Does one exist or are all products based on recording mouse and keyboard presses?

Update: I have looked at this blog post on white and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison.

答:
The list

Please check the updated list at the: List of Automated Testing (TDD/BDD/ATDD/SBE) Tools and Frameworks for .NET: User Interface Testing

Framework
Comment

Coded UI
Discontinued

FlaUI

NUnitForms
Discontinued

Squish GUI Tester

TestComplete

TestStack.White

WinAppDriver

What Microsoft recommends

WinAppDriver

Microsoft recommends to use WinAppDriver:

Windows Application Driver (WinAppDriver) is a service to support
Selenium-like UI Test Automation on Windows Applications. This service
supports testing Universal Windows Platform (UWP), Windows Forms
(WinForms), Windows Presentation Foundation (WPF), and Classic Windows
(Win32) apps on Windows 10 PCs.

Coded UI (Visual Studio ≤ 2019)

Previously, Coded UI, a Visual Studio built-in feature and part of the UI Automation, was recommended for application UI testing (it's deprecated now):

Coded UI Test for automated UI-driven functional testing is
deprecated. Visual Studio 2019 is the last version where Coded UI Test
will be available. We recommend using Selenium for testing web apps
and Appium with WinAppDriver for testing desktop and UWP apps.
Consider Xamarin.UITest for testing iOS and Android apps using the
NUnit test framework.

Automated tests that drive your application through its user interface
(UI) are known as coded UI tests (CUITs). These tests include
functional testing of the UI controls. They let you verify that the
whole application, including its user interface, is functioning
correctly. Coded UI Tests are particularly useful where there is
validation or other logic in the user interface, for example in a web
page. They are also frequently used to automate an existing manual
test.

Read more at: https://learn.microsoft.com/en-us/visualstudio/test/use-ui-automation-to-test-your-code

OwnerDisplayName: John

LastEditorDisplayName: John

ContentLicense: CC BY-SA 4.0


问:
Using Alarmmanager to start a service at specific time
I have searched a lot of places but couldnt find a clean sequential explanation of how to start a service (or if thats not possible then an activity) at a specific time daily using the AlarmManager??

I want to register several such alarms and triggering them should result in a service to be started. I'll be having a small piece of code in the service which can then execute and i can finish the service for good....

```<code>Calendar cal = Calendar.getInstance();
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Date date = new Date(cur_cal.get(Calendar.YEAR), cur_cal.get(Calendar.MONTH), cur_cal.get(Calendar.DATE), 16, 45);
cal.setTime(date);
Intent intent = new Intent(ProfileList.this, ActivateOnTime.class);
intent.putExtra("profile_id", 2);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
System.out.println("The alarm set!!");
</code>```

i tried this code to activate the alarm at 4.45... but its not firing the service... do i have to keep the process running??
M i doing anything wrong???

One more thing, my service gets perfectly executed in case i use the following code:

```<code>long firstTime = SystemClock.elapsedRealtime();
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000,pintent);
</code>```

答:
The following code should work fine and it starts the service @ 7:40 PM every day. Also, if device shuts down then all your alarms get cancelled.

Make sure to set up all the alarms after BOOT is completed.

```<code>Intent slIntent = new Intent(this, x.class);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);

PendingIntent slPendingIntent = PendingIntent.getService(this, 1, slIntent, PendingIntent.FLAG_ONE_SHOT);

AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                          AlarmManager.INTERVAL_DAY, slPendingIntent);
</code>```

Body:
I have searched a lot of places but couldnt find a clean sequential explanation of how to start a service (or if thats not possible then an activity) at a specific time daily using the AlarmManager??

I want to register several such alarms and triggering them should result in a service to be started. I'll be having a small piece of code in the service which can then execute and i can finish the service for good....

Calendar cal = Calendar.getInstance();
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Date date = new Date(cur_cal.get(Calendar.YEAR), cur_cal.get(Calendar.MONTH), cur_cal.get(Calendar.DATE), 16, 45);
cal.setTime(date);
Intent intent = new Intent(ProfileList.this, ActivateOnTime.class);
intent.putExtra("profile_id", 2);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
System.out.println("The alarm set!!");

i tried this code to activate the alarm at 4.45... but its not firing the service... do i have to keep the process running??
M i doing anything wrong???

One more thing, my service gets perfectly executed in case i use the following code:

long firstTime = SystemClock.elapsedRealtime();
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000,pintent);

Body:
The following code should work fine and it starts the service @ 7:40 PM every day. Also, if device shuts down then all your alarms get cancelled.

Make sure to set up all the alarms after BOOT is completed.

Intent slIntent = new Intent(this, x.class);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);

PendingIntent slPendingIntent = PendingIntent.getService(this, 1, slIntent, PendingIntent.FLAG_ONE_SHOT);

AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                          AlarmManager.INTERVAL_DAY, slPendingIntent);


问:
Converting Array to JSON using SwiftyJSON
I'm looking for a quick way to map a a 2-dim array to JSON.  I'm using SwiftyJSON and have hit a brick wall (I'm a hardware guy lol). Thank you! </p>

```<code>import UIKit
import SwiftyJSON

var myPlaceArray = [Int:[String: Any]]()
myPlaceArray[0] = [
  "lat" : "2.590",
  "long" : "170.9"
  ]

myPlaceArray[1] = [
  "lat" : "42.90",
  "long" : "70.9"
]

//I can do this
let json = JSON(myPlaceArray[1]!)
print(json)

//but I cant do this
let jsonIndexed = JSON(myPlaceArray)
print(jsonIndexed[0] )
</code>```

答:
You are not declaring an array with this statement:

```<code>var myPlaceArray = [Int:[String: Any]]()
</code>```

Instead, what you've declared above is a dictionary where the key is an Int and the values are dictionaries.

What you need is the following:

```<code>var myPlaceArray = [[String: Any]]()
</code>```

Now, you can assign array elements as you did and you should be able to access the array as you wanted via your code. Give it a try and see :) If you run into any issues, comment here and I'll take a look.

Body:
I'm looking for a quick way to map a a 2-dim array to JSON.  I'm using SwiftyJSON and have hit a brick wall (I'm a hardware guy lol). Thank you!

import UIKit
import SwiftyJSON

var myPlaceArray = [Int:[String: Any]]()
myPlaceArray[0] = [
  "lat" : "2.590",
  "long" : "170.9"
  ]

myPlaceArray[1] = [
  "lat" : "42.90",
  "long" : "70.9"
]

//I can do this
let json = JSON(myPlaceArray[1]!)
print(json)

//but I cant do this
let jsonIndexed = JSON(myPlaceArray)
print(jsonIndexed[0] )

Body:
You are not declaring an array with this statement:

var myPlaceArray = [Int:[String: Any]]()

Instead, what you've declared above is a dictionary where the key is an Int and the values are dictionaries.

What you need is the following:

var myPlaceArray = [[String: Any]]()

Now, you can assign array elements as you did and you should be able to access the array as you wanted via your code. Give it a try and see :) If you run into any issues, comment here and I'll take a look.


问:
How to replace NaNs by preceding or next values in pandas DataFrame?
Suppose I have a DataFrame with some NaNs:

```<code>>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df
    0   1   2
0   1   2   3
1   4 NaN NaN
2 NaN NaN   9
</code>```

What I need to do is replace every NaN with the first non-NaN value in the same column above it. It is assumed that the first row will never contain a NaN. So for the previous example the result would be

```<code>   0  1  2
0  1  2  3
1  4  2  3
2  4  2  9
</code>```

I can just loop through the whole DataFrame column-by-column, element-by-element and set the values directly, but is there an easy (optimally a loop-free) way of achieving this?

答:
ffill now has it's own method pd.DataFrame.ffill

```<code>df.ffill()

     0    1    2
0  1.0  2.0  3.0
1  4.0  2.0  3.0
2  4.0  2.0  9.0
</code>```

Body:
Suppose I have a DataFrame with some NaNs:

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df
    0   1   2
0   1   2   3
1   4 NaN NaN
2 NaN NaN   9

What I need to do is replace every NaN with the first non-NaN value in the same column above it. It is assumed that the first row will never contain a NaN. So for the previous example the result would be

   0  1  2
0  1  2  3
1  4  2  3
2  4  2  9

I can just loop through the whole DataFrame column-by-column, element-by-element and set the values directly, but is there an easy (optimally a loop-free) way of achieving this?

Body:
ffill now has it's own method pd.DataFrame.ffill

df.ffill()

     0    1    2
0  1.0  2.0  3.0
1  4.0  2.0  3.0
2  4.0  2.0  9.0


问:
Atom setting to open files in the same window?
I'm just trying out Atom for the first time and I find it bothersome that Atom keeps opening a new window for each file I click on - I'd prefer that it defaulted to opening each file in the same window.

I'm hoping for something along the lines of "open_files_in_new_window" : false, in Sublime.  Unfortunately, all the google results I'm seeing just lament that this toggle is not immediately obvious.

答: In your terminal you can type atom -a <filename||folder> and the file(s) will open within the same atom window.


问:
How to correctly override `errResponse` which is passed to the `catch(function(errResponse){` function?
This is my controller:

```<code>angular.module("AuthenticationApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
        var self = this;

        self.add = function() {
            BaseService.add.user(self.user)
                .catch(function(errorResponse) {
                    self.cerrorMessages = errorResponse.data;
                });
        };
</code>```

This is my BaseApp / factory:

```<code>angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;

        self.add = {
            user: function(user) {
                $http.post("/users/", user)
                .then(function(response) {
                    $http.post("/api-auth/login", user)
                    .then(function(response) {
                        $window.location.href = "/";
                    });
                // if there are errors, rewrite the error messages
                }).catch(function(response) {
                     for (prop in response.data) {
                         if (prop == "email") {
                             response.data[prop] = "Please enter a valid email address.";
                         } else if (prop == "username") {
                             response.data[prop] = "Please enter a valid username";
                         }
                     }
                });
            }
         };
</code>```

When I try to run this code and call self.add() on my controller, I get an error saying TypeError: Cannot read property 'catch' of undefined pointing to the line .catch(function(errorResponse) { in my controller. I'm guessing this is because there is no then() function.

What should I do to properly override the errResponse parameter which is passed to the controller's .catch() function (without having a .then() function because nothing is needed to be done if it is successful)?

答:
The .then() block accepts two functions for:

handling a successful response

handling errors

You don't need a catch block. Just add the callback function in case of errors to override the response like this:

```<code>self.add = {
            user: function(user) {
                $http.post("/users/", user)
                .then(function(response) {
                    $http.post("/api-auth/login", user)
                    .then(function(response) {
                        $window.location.href = "/";
                    }, function errorCallback(response) {
                        for (prop in response.data) {
                         if (prop == "email") {
                             response.data[prop] = "Please enter a valid email address.";
                         } else if (prop == "username") {
                             response.data[prop] = "Please enter a valid username";
                 });
            }
         };
</code>```

Body:
This is my controller:

angular.module("AuthenticationApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
        var self = this;

        self.add = function() {
            BaseService.add.user(self.user)
                .catch(function(errorResponse) {
                    self.cerrorMessages = errorResponse.data;
                });
        };

This is my BaseApp / factory:

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;

        self.add = {
            user: function(user) {
                $http.post("/users/", user)
                .then(function(response) {
                    $http.post("/api-auth/login", user)
                    .then(function(response) {
                        $window.location.href = "/";
                    });
                // if there are errors, rewrite the error messages
                }).catch(function(response) {
                     for (prop in response.data) {
                         if (prop == "email") {
                             response.data[prop] = "Please enter a valid email address.";
                         } else if (prop == "username") {
                             response.data[prop] = "Please enter a valid username";
                         }
                     }
                });
            }
         };

When I try to run this code and call self.add() on my controller, I get an error saying TypeError: Cannot read property 'catch' of undefined pointing to the line .catch(function(errorResponse) { in my controller. I'm guessing this is because there is no then() function.

What should I do to properly override the errResponse parameter which is passed to the controller's .catch() function (without having a .then() function because nothing is needed to be done if it is successful)?

Body:
The .then() block accepts two functions for:

handling a successful response

handling errors

You don't need a catch block. Just add the callback function in case of errors to override the response like this:

self.add = {
            user: function(user) {
                $http.post("/users/", user)
                .then(function(response) {
                    $http.post("/api-auth/login", user)
                    .then(function(response) {
                        $window.location.href = "/";
                    }, function errorCallback(response) {
                        for (prop in response.data) {
                         if (prop == "email") {
                             response.data[prop] = "Please enter a valid email address.";
                         } else if (prop == "username") {
                             response.data[prop] = "Please enter a valid username";
                 });
            }
         };


问:
Firebase Authentication with Google issue
I have been using Firebase Authentication in my app, and have noticed an issue with a particular use case.

I have enabled account linking sign up flow for my app, and thus I can attach multiple providers associated with a single email address.

Scenario 1: (Works fine)

The user has signed up with Google initially and sometime later, signs in in with Facebook or registers with email and password.

The account linking works fine and Facebook and/or Email is added in the provider list.

So, I can have 2 or 3 providers for the email, Google (initially), Facebook and Password (after that).

Scenario 2: (The bug)

The user has signed up with Facebook and/or Email initially and later signs in with Google, now the account linking doesn't work. Google replaces the previous providers present.

Account linking fails, and I just have Google as the sole provider associated with the email address and the others are gone.

In the second scenario, while signing in with Google, it should fail and throw FirebaseAuthCollisionException but it doesn't and succeeds. This is the main issue.

I can't paste the whole code here, but just a snippet for sure.

```<code>firebaseAuth
                        .signInWithCredential(credential)
                        .addOnFailureListener(exception -> {
                            if (exception instanceof FirebaseAuthUserCollisionException) {
                                mCredentialToLinkWith = credential;
                                if (mProviderList.size() == 1) {
                                    if (mProviderList.contains(EmailAuthProvider.PROVIDER_ID)) {
                                        mRegisterProviderPresenter.linkWithEmailProvider(credential, email);
                                    } else {
                                        linkProviderAccounts(email, AuthenticationHelper.getProviderToLinkAccounts(mWeakActivity, mProviderList));
                                    }
                                } else {
                                    linkProviderAccounts(email, AuthenticationHelper.getProviderToLinkAccounts(mWeakActivity, mProviderList));
                                }
                            } else {
                                Timber.d("Failed in signInWithCredential and unexpected exception %s", exception.getLocalizedMessage());
                                mRegisterProviderPresenter.onRegistrationFailed(new ErrorBundle(ErrorBundle.FIREBASE_ERROR, exception.getLocalizedMessage()));
                            }
                        })
                        .addOnSuccessListener(authResult -> {
                            Timber.d("Success: signInCred");
                            FirebaseUser firebaseUser = authResult.getUser();
                            /**
                             * Store the user details only for first time registration
                             * and not while acc linking
                             */
                            storeUserCredentials(firebaseUser);
                            AuthenticationHelper.logUserDetails(firebaseUser);
                            mRegisterProviderPresenter.onRegistrationSuccess(mAlreadyRegistered);

                        });
</code>```

Hope someone can come up with some help.

答: just use the email and password auth for the moment or a 3rd party plugin no solution so far </p>

Body:
I have been using Firebase Authentication in my app, and have noticed an issue with a particular use case.

I have enabled account linking sign up flow for my app, and thus I can attach multiple providers associated with a single email address.

Scenario 1: (Works fine)

The user has signed up with Google initially and sometime later, signs in in with Facebook or registers with email and password.

The account linking works fine and Facebook and/or Email is added in the provider list.

So, I can have 2 or 3 providers for the email, Google (initially), Facebook and Password (after that).

Scenario 2: (The bug)

The user has signed up with Facebook and/or Email initially and later signs in with Google, now the account linking doesn't work. Google replaces the previous providers present.

Account linking fails, and I just have Google as the sole provider associated with the email address and the others are gone.

In the second scenario, while signing in with Google, it should fail and throw FirebaseAuthCollisionException but it doesn't and succeeds. This is the main issue.

I can't paste the whole code here, but just a snippet for sure.

firebaseAuth
                        .signInWithCredential(credential)
                        .addOnFailureListener(exception -> {
                            if (exception instanceof FirebaseAuthUserCollisionException) {
                                mCredentialToLinkWith = credential;
                                if (mProviderList.size() == 1) {
                                    if (mProviderList.contains(EmailAuthProvider.PROVIDER_ID)) {
                                        mRegisterProviderPresenter.linkWithEmailProvider(credential, email);
                                    } else {
                                        linkProviderAccounts(email, AuthenticationHelper.getProviderToLinkAccounts(mWeakActivity, mProviderList));
                                    }
                                } else {
                                    linkProviderAccounts(email, AuthenticationHelper.getProviderToLinkAccounts(mWeakActivity, mProviderList));
                                }
                            } else {
                                Timber.d("Failed in signInWithCredential and unexpected exception %s", exception.getLocalizedMessage());
                                mRegisterProviderPresenter.onRegistrationFailed(new ErrorBundle(ErrorBundle.FIREBASE_ERROR, exception.getLocalizedMessage()));
                            }
                        })
                        .addOnSuccessListener(authResult -> {
                            Timber.d("Success: signInCred");
                            FirebaseUser firebaseUser = authResult.getUser();
                            /**
                             * Store the user details only for first time registration
                             * and not while acc linking
                             */
                            storeUserCredentials(firebaseUser);
                            AuthenticationHelper.logUserDetails(firebaseUser);
                            mRegisterProviderPresenter.onRegistrationSuccess(mAlreadyRegistered);

                        });

Hope someone can come up with some help.


问:
Why Ruby inject method cannot sum up string lengths without initial value?
Why the following code issues an error ?

```<code>['hello','stack','overflow'].inject{|memo,s|memo+s.length}

TypeError: can't convert Fixnum into String
        from (irb):2:in `+'
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `each'
        from (irb):2:in `inject'
        from (irb):2
</code>```

If the initial value is passed, it works OK:

```<code>['hello','stack','overflow'].inject(0){|memo,s|memo+s.length}
=> 18
</code>```

答:
You have the answer in apidock :

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

That is, without an initial value, you're trying to do 'hello' + 'stack'.length

Body:
Why the following code issues an error ?

['hello','stack','overflow'].inject{|memo,s|memo+s.length}

TypeError: can't convert Fixnum into String
        from (irb):2:in `+'
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `each'
        from (irb):2:in `inject'
        from (irb):2

If the initial value is passed, it works OK:

['hello','stack','overflow'].inject(0){|memo,s|memo+s.length}
=> 18


问:
spring boot redis operation throw broken pipe error
We use redis in spring boot project. After running a period of time, the redis operation MAY throw a broken pipe error, but sometimes it will succeed. Restarting the service will resolve this problem, but it's not a good idea.

I can't tell the reason why it happens. It seems that some redis connections in the pool are unusable, but aren't closed and evicted from the pool.

my questions are:

possible reason causing the broken pipe error?

if there isn't redis operation for a long period, will the idle connection in the pool become unusable?

will the connection be closed and evicted from pool when broken pipe error happen?

pom.xml:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</code>```

application.yml:

```<code>spring:
  redis:
    database: 0
    host: ${REDIS_HOST:127.0.0.1}
    password: ${REDIS_PASSWORD:password}
    port: ${REDIS_PORT:6379}
    timeout: ${REDIS_TIMEOUT:1000}
    pool:
      max-active: ${REDIS_MAX_ACTIVE:100}
      max-wait: ${REDIS_MAX_WAIT:500}
      max-idle: ${REDIS_MAX_IDLE:20}
      min-idle: ${REDIS_MIN_IDLE:5}
</code>```

error message:

```<code>org.springframework.data.redis.RedisConnectionFailureException: java.net.SocketException: Broken pipe (Write failed); nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)
    at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:67) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:41) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:37) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:37) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisConnection.convertJedisAccessException(JedisConnection.java:212) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisConnection.hSet(JedisConnection.java:2810) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.DefaultHashOperations$9.doInRedis(DefaultHashOperations.java:173) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:204) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:166) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:88) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.DefaultHashOperations.put(DefaultHashOperations.java:170) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)
    at redis.clients.jedis.Connection.flush(Connection.java:291) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.jedis.Connection.getIntegerReply(Connection.java:220) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.jedis.BinaryJedis.hset(BinaryJedis.java:749) ~[jedis-2.8.2.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisConnection.hSet(JedisConnection.java:2808) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    ... 115 common frames omitted
Caused by: java.net.SocketException: Broken pipe (Write failed)
    at java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:1.8.0_111]
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109) ~[na:1.8.0_111]
    at java.net.SocketOutputStream.write(SocketOutputStream.java:153) ~[na:1.8.0_111]
    at redis.clients.util.RedisOutputStream.flushBuffer(RedisOutputStream.java:52) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.util.RedisOutputStream.flush(RedisOutputStream.java:216) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.jedis.Connection.flush(Connection.java:288) ~[jedis-2.8.2.jar!/:na]
    ... 118 common frames omitted
</code>```

答:
Answer my question:

why the broken pipe error happen?

TransactionSynchronizationManager will hold the RedisConnection in thread, and wont close it or return it to pool, see RedisTemplate.java and RedisConnectionUtils.java. After restarting the redis server, operation on the holded RedisConnection in thread will throw broken pipe error.

how to resolve it?

Adding try/catch for all redis operation, if the error happens , unbinding it from thread, and could get a new connection from pool and execute redis operation again.

```<code>private static final ExceptionTranslationStrategy EXCEPTION_TRANSLATION =
        new FallbackExceptionTranslationStrategy(JedisConverters.exceptionConverter());

public Object req(RedisRequest req) {
    try {
        return req.request();
    } catch (Exception ex) {
        if (ex instanceof NullPointerException) {
            throw ex;
        }
        DataAccessException exception = EXCEPTION_TRANSLATION.translate(ex);
        if (exception instanceof RedisConnectionFailureException) {
            RedisConnectionUtils.unbindConnection(factory);
            /** retry again */
            return req.request();
        } else {
            throw ex;
        }
    }
}
</code>```

Body:
We use redis in spring boot project. After running a period of time, the redis operation MAY throw a broken pipe error, but sometimes it will succeed. Restarting the service will resolve this problem, but it's not a good idea.

I can't tell the reason why it happens. It seems that some redis connections in the pool are unusable, but aren't closed and evicted from the pool.

my questions are:

possible reason causing the broken pipe error?

if there isn't redis operation for a long period, will the idle connection in the pool become unusable?

will the connection be closed and evicted from pool when broken pipe error happen?

pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml:

spring:
  redis:
    database: 0
    host: ${REDIS_HOST:127.0.0.1}
    password: ${REDIS_PASSWORD:password}
    port: ${REDIS_PORT:6379}
    timeout: ${REDIS_TIMEOUT:1000}
    pool:
      max-active: ${REDIS_MAX_ACTIVE:100}
      max-wait: ${REDIS_MAX_WAIT:500}
      max-idle: ${REDIS_MAX_IDLE:20}
      min-idle: ${REDIS_MIN_IDLE:5}

error message:

org.springframework.data.redis.RedisConnectionFailureException: java.net.SocketException: Broken pipe (Write failed); nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)
    at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:67) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:41) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:37) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:37) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisConnection.convertJedisAccessException(JedisConnection.java:212) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisConnection.hSet(JedisConnection.java:2810) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.DefaultHashOperations$9.doInRedis(DefaultHashOperations.java:173) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:204) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:166) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:88) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    at org.springframework.data.redis.core.DefaultHashOperations.put(DefaultHashOperations.java:170) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)
    at redis.clients.jedis.Connection.flush(Connection.java:291) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.jedis.Connection.getIntegerReply(Connection.java:220) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.jedis.BinaryJedis.hset(BinaryJedis.java:749) ~[jedis-2.8.2.jar!/:na]
    at org.springframework.data.redis.connection.jedis.JedisConnection.hSet(JedisConnection.java:2808) ~[spring-data-redis-1.7.6.RELEASE.jar!/:na]
    ... 115 common frames omitted
Caused by: java.net.SocketException: Broken pipe (Write failed)
    at java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:1.8.0_111]
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109) ~[na:1.8.0_111]
    at java.net.SocketOutputStream.write(SocketOutputStream.java:153) ~[na:1.8.0_111]
    at redis.clients.util.RedisOutputStream.flushBuffer(RedisOutputStream.java:52) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.util.RedisOutputStream.flush(RedisOutputStream.java:216) ~[jedis-2.8.2.jar!/:na]
    at redis.clients.jedis.Connection.flush(Connection.java:288) ~[jedis-2.8.2.jar!/:na]
    ... 118 common frames omitted

Body:
Answer my question:

why the broken pipe error happen?

TransactionSynchronizationManager will hold the RedisConnection in thread, and wont close it or return it to pool, see RedisTemplate.java and RedisConnectionUtils.java. After restarting the redis server, operation on the holded RedisConnection in thread will throw broken pipe error.

how to resolve it?

Adding try/catch for all redis operation, if the error happens , unbinding it from thread, and could get a new connection from pool and execute redis operation again.

private static final ExceptionTranslationStrategy EXCEPTION_TRANSLATION =
        new FallbackExceptionTranslationStrategy(JedisConverters.exceptionConverter());

public Object req(RedisRequest req) {
    try {
        return req.request();
    } catch (Exception ex) {
        if (ex instanceof NullPointerException) {
            throw ex;
        }
        DataAccessException exception = EXCEPTION_TRANSLATION.translate(ex);
        if (exception instanceof RedisConnectionFailureException) {
            RedisConnectionUtils.unbindConnection(factory);
            /** retry again */
            return req.request();
        } else {
            throw ex;
        }
    }
}


问:
Why does my Scanner input2 only record the the last input?
I am trying to create a college gpa calculator. The program first asks for the number of classes, the amount of credits for each class, and then for the grade for each class. The program works when the each class has the same amount of credits but does not work when there are different amounts of credits for each class. I have tried debugging the program by including print statements that show the values as the program runs and I have determined that credits only records the last inputted value. Is this just how .nextDouble() works or am I making a mistake? How would I go about fixing this problem? I am also fairly new to Java so if I am making a simple mistake there's a reason why.... Thanks

```<code>import java.util.*;

public class Calculator {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("This program calculates your college GPA.");
    System.out.println("Enter the number of classes you've taken this quarter/semester:");
    int classes;
    classes = input.nextInt();
    double gradePoint = 0;
    double credits = 0;
    double totalCredits = 0;
    String grades;
    double gpa = 0;
    double total = 0;
    // for loop record number of credits per class
    for (int i = 0; i < classes; i++) {
        Scanner input2 = new Scanner(System.in);
        if (i > 0) {
            // user will be asked this second
            System.out.println("Enter next amount of credit hours:");
        }
        else {
            // user will be asked this first
            System.out.println("Enter the number of credits for each class one by one:");
        }
        credits = input2.nextDouble();
        System.out.println("credits:" + credits);
        totalCredits += credits;
        System.out.println("totalcredits:" + totalCredits);
    }
    System.out.println("credits:" + credits);
    // for loop to record grades input and calculate gpa
    for (int b = 0; b < classes; b++) {
        System.out.println("credits:" + credits);
        Scanner input3 = new Scanner(System.in);
        if (b > 0) {
            System.out.println("Enter your next grade:");
        }
        else {
            System.out.println("To receive your GPA, enter your grades one by one:");
        }
        grades = input3.nextLine();
        // if statements will convert letter grades to grade points
        // grade points will then be multiplied by their respective amount of credits
        if (grades.equals("A+")) {
            gradePoint=4.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("A")) {
            gradePoint=4.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("A-")) {
            System.out.println("credits:" + credits);
            gradePoint=3.7;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("B+")) {
            System.out.println("credits:" + credits);
            gradePoint=3.3;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("B")) {
            System.out.println("credits:" + credits);
            gradePoint=3.0;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("B-")) {
            System.out.println("credits:" + credits);
            gradePoint=2.7;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("C+")) {
            gradePoint=2.3;
            total += (gradePoint*credits);
        }
        else if (grades.equals("C")) {
            gradePoint=2.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("C-")) {
            gradePoint=1.7;
            total += (gradePoint*credits);
        }
        else if (grades.equals("D+")) {
            gradePoint=1.3;
            total += (gradePoint*credits);
        }
        else if (grades.equals("D")) {
            gradePoint=1.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("D-")) {
            gradePoint=0.7;
            total += (gradePoint*credits);
        }
        else if (grades.equals("F")) {
            gradePoint=0;
            total += (gradePoint*credits);
        }
        else {
            System.out.println("Invalid input.");
        }
        // gpa algorithm
        gpa = total/totalCredits;
        System.out.println("totalCredits" + totalCredits);
        System.out.println("gpa:" + gpa);
    }
    System.out.println("GPA: " + gpa);
}
</code>```

}

Also, when inputted:

```<code>3
5
5
3
A+
B+
C-
</code>```

The program outputs the following:

```<code>This program calculates your college GPA.
Enter the number of classes you've taken this quarter/semester:
3
Enter the number of credits for each class one by one:
5
credits:5.0
totalcredits:5.0
Enter next amount of credit hours:
5
credits:5.0
totalcredits:10.0
Enter next amount of credit hours:
3
credits:3.0
totalcredits:13.0
credits:3.0
credits:3.0
To receive your GPA, enter your grades one by one:
A+
totalCredits13.0
gpa:0.9230769230769231
credits:3.0
Enter your next grade:
B+
credits:3.0
gradePoint:3.3
total:21.9
totalCredits13.0
gpa:1.6846153846153844
credits:3.0
Enter your next grade:
C-
totalCredits13.0
gpa:2.076923076923077
GPA: 2.076923076923077
</code>```

(the correct gpa should be 3.2)

答:
The problem in your credits variable, when you input

5

5

3

the last input which is 3 is stored into your credits variable and the same value is going through your 2nd loop which you're using for grades.

Solution 1:
Use array credits array and input your all classes credits into this array so that you can access different credits into your grades inputs.

Solution 2:
Use only one loop for credits and grades and input one by one I make some code for you.
here is the code.

```<code>for (int b = 0; b < classes; b++) {
    Scanner input3 = new Scanner(System.in);
    System.out.println("Enter credit hours for class :"+(b + 1));
    credits = input2.nextDouble();
    System.out.println("credits:" + credits);
    totalCredits += credits;
    System.out.println(" ");
    System.out.println("Enter grade for class : "+(b + 1));
    grades = input3.nextLine();

   }
</code>```

Inputs:

```<code> 3  //number of classes
 5  //first class credits
 A+ //first class grade
 5  .
 B+ .
 3  .
 c- ..........
</code>```

Output:

```<code>gpa:3.2
GPA: 3.2
</code>```

Body:
I am trying to create a college gpa calculator. The program first asks for the number of classes, the amount of credits for each class, and then for the grade for each class. The program works when the each class has the same amount of credits but does not work when there are different amounts of credits for each class. I have tried debugging the program by including print statements that show the values as the program runs and I have determined that credits only records the last inputted value. Is this just how .nextDouble() works or am I making a mistake? How would I go about fixing this problem? I am also fairly new to Java so if I am making a simple mistake there's a reason why.... Thanks

import java.util.*;

public class Calculator {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("This program calculates your college GPA.");
    System.out.println("Enter the number of classes you've taken this quarter/semester:");
    int classes;
    classes = input.nextInt();
    double gradePoint = 0;
    double credits = 0;
    double totalCredits = 0;
    String grades;
    double gpa = 0;
    double total = 0;
    // for loop record number of credits per class
    for (int i = 0; i < classes; i++) {
        Scanner input2 = new Scanner(System.in);
        if (i > 0) {
            // user will be asked this second
            System.out.println("Enter next amount of credit hours:");
        }
        else {
            // user will be asked this first
            System.out.println("Enter the number of credits for each class one by one:");
        }
        credits = input2.nextDouble();
        System.out.println("credits:" + credits);
        totalCredits += credits;
        System.out.println("totalcredits:" + totalCredits);
    }
    System.out.println("credits:" + credits);
    // for loop to record grades input and calculate gpa
    for (int b = 0; b < classes; b++) {
        System.out.println("credits:" + credits);
        Scanner input3 = new Scanner(System.in);
        if (b > 0) {
            System.out.println("Enter your next grade:");
        }
        else {
            System.out.println("To receive your GPA, enter your grades one by one:");
        }
        grades = input3.nextLine();
        // if statements will convert letter grades to grade points
        // grade points will then be multiplied by their respective amount of credits
        if (grades.equals("A+")) {
            gradePoint=4.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("A")) {
            gradePoint=4.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("A-")) {
            System.out.println("credits:" + credits);
            gradePoint=3.7;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("B+")) {
            System.out.println("credits:" + credits);
            gradePoint=3.3;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("B")) {
            System.out.println("credits:" + credits);
            gradePoint=3.0;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("B-")) {
            System.out.println("credits:" + credits);
            gradePoint=2.7;
            System.out.println("gradePoint:" + gradePoint);
            total += (gradePoint*credits);
            System.out.println("total:" + total);
        }
        else if (grades.equals("C+")) {
            gradePoint=2.3;
            total += (gradePoint*credits);
        }
        else if (grades.equals("C")) {
            gradePoint=2.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("C-")) {
            gradePoint=1.7;
            total += (gradePoint*credits);
        }
        else if (grades.equals("D+")) {
            gradePoint=1.3;
            total += (gradePoint*credits);
        }
        else if (grades.equals("D")) {
            gradePoint=1.0;
            total += (gradePoint*credits);
        }
        else if (grades.equals("D-")) {
            gradePoint=0.7;
            total += (gradePoint*credits);
        }
        else if (grades.equals("F")) {
            gradePoint=0;
            total += (gradePoint*credits);
        }
        else {
            System.out.println("Invalid input.");
        }
        // gpa algorithm
        gpa = total/totalCredits;
        System.out.println("totalCredits" + totalCredits);
        System.out.println("gpa:" + gpa);
    }
    System.out.println("GPA: " + gpa);
}

}

Also, when inputted:

3
5
5
3
A+
B+
C-

The program outputs the following:

This program calculates your college GPA.
Enter the number of classes you've taken this quarter/semester:
3
Enter the number of credits for each class one by one:
5
credits:5.0
totalcredits:5.0
Enter next amount of credit hours:
5
credits:5.0
totalcredits:10.0
Enter next amount of credit hours:
3
credits:3.0
totalcredits:13.0
credits:3.0
credits:3.0
To receive your GPA, enter your grades one by one:
A+
totalCredits13.0
gpa:0.9230769230769231
credits:3.0
Enter your next grade:
B+
credits:3.0
gradePoint:3.3
total:21.9
totalCredits13.0
gpa:1.6846153846153844
credits:3.0
Enter your next grade:
C-
totalCredits13.0
gpa:2.076923076923077
GPA: 2.076923076923077

(the correct gpa should be 3.2)

Body:
The problem in your credits variable, when you input

5

5

3

the last input which is 3 is stored into your credits variable and the same value is going through your 2nd loop which you're using for grades.

Solution 1:
Use array credits array and input your all classes credits into this array so that you can access different credits into your grades inputs.

Solution 2:
Use only one loop for credits and grades and input one by one I make some code for you.
here is the code.

for (int b = 0; b < classes; b++) {
    Scanner input3 = new Scanner(System.in);
    System.out.println("Enter credit hours for class :"+(b + 1));
    credits = input2.nextDouble();
    System.out.println("credits:" + credits);
    totalCredits += credits;
    System.out.println(" ");
    System.out.println("Enter grade for class : "+(b + 1));
    grades = input3.nextLine();

   }

Inputs:

 3  //number of classes
 5  //first class credits
 A+ //first class grade
 5  .
 B+ .
 3  .
 c- ..........

Output:

gpa:3.2
GPA: 3.2


问:
Update a List of objects by comparing with another list
I do have two different lists of same object , one is with sample data , one is with real data. Few fields in the real data are messed up, I need to update the few fields of real data list , by getting those values from sample data .

Both lists are of same object, both have same unique key .

```<code>List<pojo> real = [(code:60,active:Y,account:check),(code:61,active:Y,account:check),(code:62,active:Y,account:check)];

List<pojo> sample = [(code:60,active:Y,account:saving),(code:61,active:Y,account:check),(code:62,active:Y,account:saving)]
</code>```

I have around 60 objects in each list , In the above one I need to update real where code is 60 and 62 - account from check to saving.

I am  using  java 1.8  &  groovy

thanks

答:
Here is the script that updates real data after comparing with sample data as requested by OP.

Note that the input is not valid, so made it valid by changing values inside list as map. i.e.,

changed from (code:60,active:'Y',account:'check')

to [code:60,active:'Y',account:'check']

```<code>def realData = [[code:60,active:'Y',account:'check'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'check']]
def sampleData = [[code:60,active:'Y',account:'saving'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'saving']]
realData.collect{rd -> sampleData.find{ it.code == rd.code && (it.account == rd.account ?: (rd.account = it.account))}}
println realData
</code>```

Output:

```<code>[[code:60, active:Y, account:saving], [code:61, active:Y, account:check], [code:62, active:Y, account:saving]]
</code>```

You can quickly try online Demo

Body:
I do have two different lists of same object , one is with sample data , one is with real data. Few fields in the real data are messed up, I need to update the few fields of real data list , by getting those values from sample data .

Both lists are of same object, both have same unique key .

List<pojo> real = [(code:60,active:Y,account:check),(code:61,active:Y,account:check),(code:62,active:Y,account:check)];

List<pojo> sample = [(code:60,active:Y,account:saving),(code:61,active:Y,account:check),(code:62,active:Y,account:saving)]

I have around 60 objects in each list , In the above one I need to update real where code is 60 and 62 - account from check to saving.

I am  using  java 1.8  &  groovy

thanks

Body:
Here is the script that updates real data after comparing with sample data as requested by OP.

Note that the input is not valid, so made it valid by changing values inside list as map. i.e.,

changed from (code:60,active:'Y',account:'check')

to [code:60,active:'Y',account:'check']

def realData = [[code:60,active:'Y',account:'check'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'check']]
def sampleData = [[code:60,active:'Y',account:'saving'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'saving']]
realData.collect{rd -> sampleData.find{ it.code == rd.code && (it.account == rd.account ?: (rd.account = it.account))}}
println realData

Output:

[[code:60, active:Y, account:saving], [code:61, active:Y, account:check], [code:62, active:Y, account:saving]]

You can quickly try online Demo


问:
sqlsvr driver problems
I am trying to connect Azure database with PHP. I installed sqlsrv driver. It also appears in phpinfo as PDO drivers = mysql, sqlite, sqlsrv.

However, the below code is not working:

```<code>$serverName = "xduuewepx4.database.windows.net";

$connectionOptions = array("Database" => "master",

                           "UID" => "intelligaia",

                           "PWD" => "Maporamic7",

                           "MultipleActiveResultSets" => false);

$conn = sqlsrv_connect($serverName, $connectionOptions);

if($conn === false)

{

     die(print_r(sqlsrv_errors(), true));

}
</code>```

The reported error is:

Fatal error: Call to undefined function sqlsrv_connect() in C:\wamp\www\test.php on line 20

Looking for your support.

答:
mmm, you better use odbc, make sure you have the azure odbc driver

here are some examples (goto start -> run -> enter odbcad32.exe and create a dsn(system or user) then in php you do

```<code><?php
$connection = odbc_connect("DSN=TheNameYouHadEnterd",$username,$password);

$r_Results = odbc_exec($connection, "SELECT * FROM Table");

while($Row = odbc_fetch_array($r_Results)){
  var_dump($Row);
}
</code>```

watch out with the while it is UNTESTED

Álvaro G. Vicario is right, ms provids this native drivers if you think you might ever migrate to another db(and you will) you should use pdo.
her are:documentation
and download
but i would use the community edision(unless you are paying for support)

Title: sqlsvr driver problems

Body:
I am trying to connect Azure database with PHP. I installed sqlsrv driver. It also appears in phpinfo as PDO drivers = mysql, sqlite, sqlsrv.

However, the below code is not working:

$serverName = "xduuewepx4.database.windows.net";

$connectionOptions = array("Database" => "master",

                           "UID" => "intelligaia",

                           "PWD" => "Maporamic7",

                           "MultipleActiveResultSets" => false);

$conn = sqlsrv_connect($serverName, $connectionOptions);

if($conn === false)

{

     die(print_r(sqlsrv_errors(), true));

}

The reported error is:

Fatal error: Call to undefined function sqlsrv_connect() in C:\wamp\www\test.php on line 20

Looking for your support.

Body:
mmm, you better use odbc, make sure you have the azure odbc driver

here are some examples (goto start -> run -> enter odbcad32.exe and create a dsn(system or user) then in php you do

<?php
$connection = odbc_connect("DSN=TheNameYouHadEnterd",$username,$password);

$r_Results = odbc_exec($connection, "SELECT * FROM Table");

while($Row = odbc_fetch_array($r_Results)){
  var_dump($Row);
}

watch out with the while it is UNTESTED

Álvaro G. Vicario is right, ms provids this native drivers if you think you might ever migrate to another db(and you will) you should use pdo.
her are:documentation
and download
but i would use the community edision(unless you are paying for support)


问:
Turning off "Language Service Disabled" error message in VS2017
We are getting the following "Error" message in our MVC web application in Visual studio 2017 Enterprise.

The language service is disabled for project 'C:\Work\Blackhawk
  Platform\Platform-DEV-Branch\BlackhawkViewer\BlackhawkViewer.csproj'
  because it included a large number of .js files. Consider excluding
  files using the 'exclude' section of a 'tsconfig.json' file.

I have tried turning off the Language service in the options but this does not turn the message off:

This is a rather large web application.  Is there a way to turn this message off without disabling any files in the tsconfig.json file as it suggests?

答:
I have found a solution for this problem.

I reset my userData using:

devenv.exe /resetuserdata

Since doing this the JavaScript settings seem to have persisted and I no longer get the  language service error above.

TAKE NOTE: This will reset all your user data and customisations.