问:
Numpy: Check if float array contains whole numbers
In Python, it is possible to check if a float contains an integer value using n.is_integer(), based on this QA: How to check if a float value is a whole number.

Does numpy have a similar operation that can be applied to arrays? Something that would allow the following:

```<code>>>> x = np.array([1.0 2.1 3.0 3.9])
>>> mask = np.is_integer(x)
>>> mask
array([True, False, True, False], dtype=bool)
</code>```

It is possible to do something like

```<code>>>> mask = (x == np.floor(x))
</code>```

or

```<code>>>> mask = (x == np.round(x))
</code>```

but they involve calling extra methods and creating a bunch of temp arrays that could be potentially avoided.

Does numpy have a vectorized function that checks for fractional parts of floats in a way similar to Python's float.is_integer?

答:
I needed an answer to this question for a slightly different reason: checking when I can convert an entire array of floating point numbers to integers without losing data.

Hunse's answer almost works for me, except that I obviously can't use the in-place trick, since I need to be able to undo the operation:

```<code>if np.all(np.mod(x, 1) == 0):
    x = x.astype(int)
</code>```

From there, I thought of the following option which probably is faster in many situations:

```<code>x_int = x.astype(int)
if np.all((x - x_int) == 0):
    x = x_int
</code>```

The reason is that the modulo operation is slower than subtraction. However, now we do the casting to integers up-front - I don't know how fast that operation is, relatively speaking. But if most of your arrays are integers (they are in my case), the latter version is almost certainly faster.

Another benefit is that you could replace the subraction with something like np.isclose to check within a certain tolerance (of course you should be careful here, since truncation is not proper rounding!).

```<code>x_int = x.astype(int)
if np.all(np.isclose(x, x_int, 0.0001)):
    x = x_int
</code>```

EDIT: Slower, but perhaps worth it depending on your use-case, is also converting integers individually if present.

```<code>x_int = x.astype(int)
safe_conversion = (x - x_int) == 0
# if we can convert the whole array to integers, do that
if np.all(safe_conversion):
    x = x_int.tolist()
else:
    x  = x.tolist()
    # if there are _some_ integers, convert them
    if np.any(safe_conversion):
        for i in range(len(x)):
            if safe_conversion[i]:
                x[i] = int(x[i])
</code>```

As an example of where this matters: this works out for me, because I have sparse data (which means mostly zeros) which I then convert to JSON, once, and reuse later on a server. For floats, ujson converts those as [ ...,0.0,0.0,0.0,... ], and for ints that results in [...,0,0,0,...], saving up to half the numbers of characters in the string. This reduces overhead on both the server (shorter strings) and the client (shorter strings, presumably slightly faster JSON parsing).

Body:
In Python, it is possible to check if a float contains an integer value using n.is_integer(), based on this QA: How to check if a float value is a whole number.

Does numpy have a similar operation that can be applied to arrays? Something that would allow the following:

>>> x = np.array([1.0 2.1 3.0 3.9])
>>> mask = np.is_integer(x)
>>> mask
array([True, False, True, False], dtype=bool)

It is possible to do something like

>>> mask = (x == np.floor(x))

or

>>> mask = (x == np.round(x))

but they involve calling extra methods and creating a bunch of temp arrays that could be potentially avoided.

Does numpy have a vectorized function that checks for fractional parts of floats in a way similar to Python's float.is_integer?

Body:
I needed an answer to this question for a slightly different reason: checking when I can convert an entire array of floating point numbers to integers without losing data.

Hunse's answer almost works for me, except that I obviously can't use the in-place trick, since I need to be able to undo the operation:

if np.all(np.mod(x, 1) == 0):
    x = x.astype(int)

From there, I thought of the following option which probably is faster in many situations:

x_int = x.astype(int)
if np.all((x - x_int) == 0):
    x = x_int

The reason is that the modulo operation is slower than subtraction. However, now we do the casting to integers up-front - I don't know how fast that operation is, relatively speaking. But if most of your arrays are integers (they are in my case), the latter version is almost certainly faster.

Another benefit is that you could replace the subraction with something like np.isclose to check within a certain tolerance (of course you should be careful here, since truncation is not proper rounding!).

x_int = x.astype(int)
if np.all(np.isclose(x, x_int, 0.0001)):
    x = x_int

EDIT: Slower, but perhaps worth it depending on your use-case, is also converting integers individually if present.

x_int = x.astype(int)
safe_conversion = (x - x_int) == 0
# if we can convert the whole array to integers, do that
if np.all(safe_conversion):
    x = x_int.tolist()
else:
    x  = x.tolist()
    # if there are _some_ integers, convert them
    if np.any(safe_conversion):
        for i in range(len(x)):
            if safe_conversion[i]:
                x[i] = int(x[i])

As an example of where this matters: this works out for me, because I have sparse data (which means mostly zeros) which I then convert to JSON, once, and reuse later on a server. For floats, ujson converts those as [ ...,0.0,0.0,0.0,... ], and for ints that results in [...,0,0,0,...], saving up to half the numbers of characters in the string. This reduces overhead on both the server (shorter strings) and the client (shorter strings, presumably slightly faster JSON parsing).


来源: stackexchange

问:
Postgres: upsert a row and update a primary key column
Suppose I have two tables in my Postgres database:

```<code>create table transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);

-- same columns
create temporary table updated_transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);
</code>```

Both tables have just a primary key, and no unique indexes.

I need to upsert rows from updated_transactions into transactions using the following rules:

id column values in transactions and updated_transactions don't match

other columns like doc_id, etc (except of the amount) should match

when a matching row is found, update both amount and id columns

when a matching row is not found, insert it

id values in updated_transactions are taken from a sequence.
A business object just populates updated_transactions and then merges the
new or updated rows from it into transactions using an upsert query.
So my old unchanged transactions keep their ids intact, and the updated ones
are assigned new ids.

In MSSQL and Oracle, it would be a merge statement similar to this:

```<code>merge into transactions t
using updated_transactions ut on t.doc_id = ut.doc_id, ...
when matched then
    update set t.id = ut.id, t.amount = ut.amount
when not matched then
    insert (t.id, t.doc_id, ..., t.amount)
    values (ut.id, ut.doc_id, ..., ut.amount);
</code>```

In PostgreSQL, I suppose it should be something like this:

```<code>insert into transactions(id, doc_id, ..., amount)
select coalesce(t.id, ut.id), ut.doc_id, ... ut.amount
from updated_transactions ut
left join transactions t on t.doc_id = ut.doc_id, ....
    on conflict
    on constraint transactions_pkey
    do update
    set amount = excluded.amount, id = excluded.id
</code>```

The problem is with the do update clause: excluded.id is an old value
from transactions table, while I need a new value from updated_transactions.

ut.id value is inaccessible for the do update clause, and the only thing I can
use is the excluded row. But the excluded row has only coalesce(t.id, ut.id)
expression which returns old id values for the existing rows.

Is it possible to update both id and amount columns using the upsert query?

答:
Create unique index on those columns you use as key and pass its name in your upsert expression, so that it uses it instead of pkey.
Then it will insert row if no matches were found, using ID from updated_transactions. If it finds match, then you can use excluded.id to get ID from updated_transactions.

I think that left join transactions is redundant.

So it would look kinda like this:

```<code>insert into transactions(id, doc_id, ..., amount)
select ut.id, ut.doc_id, ... ut.amount
from updated_transactions ut
    on conflict
    on constraint transactions_multi_column_unique_index
    do update
    set amount = excluded.amount, id = excluded.id
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have two tables in my Postgres database:

create table transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);

-- same columns
create temporary table updated_transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);

Both tables have just a primary key, and no unique indexes.

I need to upsert rows from updated_transactions into transactions using the following rules:

id column values in transactions and updated_transactions don't match

other columns like doc_id, etc (except of the amount) should match

when a matching row is found, update both amount and id columns

when a matching row is not found, insert it

id values in updated_transactions are taken from a sequence.
A business object just populates updated_transactions and then merges the
new or updated rows from it into transactions using an upsert query.
So my old unchanged transactions keep their ids intact, and the updated ones
are assigned new ids.

In MSSQL and Oracle, it would be a merge statement similar to this:

merge into transactions t
using updated_transactions ut on t.doc_id = ut.doc_id, ...
when matched then
    update set t.id = ut.id, t.amount = ut.amount
when not matched then
    insert (t.id, t.doc_id, ..., t.amount)
    values (ut.id, ut.doc_id, ..., ut.amount);

In PostgreSQL, I suppose it should be something like this:

insert into transactions(id, doc_id, ..., amount)
select coalesce(t.id, ut.id), ut.doc_id, ... ut.amount
from updated_transactions ut
left join transactions t on t.doc_id = ut.doc_id, ....
    on conflict
    on constraint transactions_pkey
    do update
    set amount = excluded.amount, id = excluded.id

The problem is with the do update clause: excluded.id is an old value
from transactions table, while I need a new value from updated_transactions.

ut.id value is inaccessible for the do update clause, and the only thing I can
use is the excluded row. But the excluded row has only coalesce(t.id, ut.id)
expression which returns old id values for the existing rows.

Is it possible to update both id and amount columns using the upsert query?

Body:
Create unique index on those columns you use as key and pass its name in your upsert expression, so that it uses it instead of pkey.
Then it will insert row if no matches were found, using ID from updated_transactions. If it finds match, then you can use excluded.id to get ID from updated_transactions.

I think that left join transactions is redundant.

So it would look kinda like this:

insert into transactions(id, doc_id, ..., amount)
select ut.id, ut.doc_id, ... ut.amount
from updated_transactions ut
    on conflict
    on constraint transactions_multi_column_unique_index
    do update
    set amount = excluded.amount, id = excluded.id


问:
How to add new item to top of Dojo DataGrid
I'm trying to implement a data item panel which is more like a mailing system. Where I need to add every new item to top of datagrid. After googling for a long time, I could still not find a proper dojo implementation of my requirement. Any help/guidance me to achieve this will be appreciated

Thank you.

答:
I think the question is that a new item should appear at the first row of the grid, instead of the last row. It looks like the email box, new emails are always put to the head of the mail list.

One possible solution I would suggest is to create you own data store implementation by extending the existing dojo.data.ItemFileWriteStore. This store uses an array to store the items internally. When a new item is added, it's pushed to the end of the array. You can override the newItem function and use unshift instead to add the item to the front of the array.

Another approach is to manage the items yourself. You can create an array to keep track of all the items. When a new item is added to the front of the array, just recreate the data store from the array and update the grid. That will work but have performance penalty.

ContentLicense: CC BY-SA 2.5


问:
Responsive logo placement
I am trying to figure out how to place the logo in the middle of the two sections of my landing page but only on the mobile view. The text class is for my logo. I cant seem to figure out the best way to do so.

```<code>.text {
 position: absolute;
 right: 70px;
 left: 70px;
 text-align: center;
 z-index: 10;
 margin: auto;
 max-width: 600px;
}
</code>```

Here is the codepen: http://codepen.io/anon/pen/xqQPVN?editors=1100

答:
If you want to have total control over the positioning i'd say go for progressively specific media queries (say: 425px, 375px, 320px) and use pixel positioning.
If you want to keep it generic, you must be prepared to have some small differences between these sizes, but you can use percentages and the result isn't so bad.</p>

```<code>@media (max-width: 425px) {
   .text {
       position: absolute;
       right: 34%;
       left: 32%;
       top: 34%;
   }

}
</code>```

Title: Responsive logo placement

Body:
I am trying to figure out how to place the logo in the middle of the two sections of my landing page but only on the mobile view. The text class is for my logo. I cant seem to figure out the best way to do so.

.text {
 position: absolute;
 right: 70px;
 left: 70px;
 text-align: center;
 z-index: 10;
 margin: auto;
 max-width: 600px;
}

Here is the codepen: http://codepen.io/anon/pen/xqQPVN?editors=1100

Body:
If you want to have total control over the positioning i'd say go for progressively specific media queries (say: 425px, 375px, 320px) and use pixel positioning.
If you want to keep it generic, you must be prepared to have some small differences between these sizes, but you can use percentages and the result isn't so bad.

@media (max-width: 425px) {
   .text {
       position: absolute;
       right: 34%;
       left: 32%;
       top: 34%;
   }

}


问:
Draw a dashed line between two UIButtons using getting dynamically positions of Frame
Hi I want to draw dashed line from one UIButton to another button.

I have taken this code to draw line between to points:

```<code>func addDashedLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.moveToPoint(start)
    linePath.addLineToPoint(end)
    line.path = linePath.CGPath
    line.strokeColor = UIColor.redColor().CGColor
    line.lineWidth = 1
   //line.lineJoin = kCALineJoinRound
    line.lineDashPattern = [8, 8]
    self.view.layer.addSublayer(line)
}
</code>```

To take startPoint and Endpoint I am using button.center() for both button. But Line is not drawing from center to center. It's drawing outside of UIButton. I have used Autolayout for button, and set constraints from superview using multiplier.

Please suggest me how to do this.?

答:
My suggestion:

```<code>let startPoint = CGPoint(x: button1.frame.origin.x + button1.frame.size.width, y: button1.frame.origin.y + (button1.frame.size.height/2.0))
let endPoint = CGPoint(x: button2.frame.origin.x, y: button2.frame.origin.y + (button2.frame.size.height / 2.0))
addDashedLine(fromPoint start:stratrPoint, toPoint end:endPoint)
</code>```

EDIT

But maybe if you are using AutoLayout, if you are using a StackView this should not work

Body:
Hi I want to draw dashed line from one UIButton to another button.

I have taken this code to draw line between to points:

func addDashedLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.moveToPoint(start)
    linePath.addLineToPoint(end)
    line.path = linePath.CGPath
    line.strokeColor = UIColor.redColor().CGColor
    line.lineWidth = 1
   //line.lineJoin = kCALineJoinRound
    line.lineDashPattern = [8, 8]
    self.view.layer.addSublayer(line)
}

To take startPoint and Endpoint I am using button.center() for both button. But Line is not drawing from center to center. It's drawing outside of UIButton. I have used Autolayout for button, and set constraints from superview using multiplier.

Please suggest me how to do this.?

Body:
My suggestion:

let startPoint = CGPoint(x: button1.frame.origin.x + button1.frame.size.width, y: button1.frame.origin.y + (button1.frame.size.height/2.0))
let endPoint = CGPoint(x: button2.frame.origin.x, y: button2.frame.origin.y + (button2.frame.size.height / 2.0))
addDashedLine(fromPoint start:stratrPoint, toPoint end:endPoint)

EDIT

But maybe if you are using AutoLayout, if you are using a StackView this should not work


问:
Catching Error when using Task.Factory
i am using the following

```<code>Task.Factory.StartNew(() => DoPrintConfigPage(serial));
</code>```

then the function i am calling looks like this

```<code>private void DoPrintConfigPage(string serial)
{
    //do printing work
}
</code>```

My problem is an exception is being thrown inside the thread and not being handled.

I have tried wrapping it in a try catch

```<code>try
{
    Task.Factory.StartNew(() => DoPrintConfigPage(serial));
}
catch (Exception ex) { }
</code>```

but it still is not catching the error and thus crashing the application.

How can I catch exceptions in the main thread so I can handle them?

Update

I have made the changes recommended below and still it is saying the exception is unhandled

```<code>var task =  Task.Factory.StartNew(() => DoPrintConfigPage(serial))
                               .ContinueWith(tsk =>
                               {
                                  MessageBox.Show("something broke");
                               },TaskContinuationOptions.OnlyOnFaulted);
</code>```

then in my DoConfigPage I added another try catch.

In this catch is now where it is crashing and saying the exception being thrown was unhandled, what am I missing?

```<code>private void DoPrintConfigPage(string serial)
{
    try
    {
        //call the print function
    }
    catch (Exception ex)
    {
        throw ex;   //it is crashing here and saying it is unhandled
    }
}
</code>```

I also tried what Eric J. suggested with the same results

```<code>var task = Task.Factory.StartNew(() => DoPrintConfigPage(serial));

try
{
    task.Wait();
}
catch (AggregateException ex) { MessageBox.Show("something broke"); }
</code>```

答: Maybe you are trying to catch a Corrupted State Exception. Since .NET 4 applications are unable to catch such exceptions by default. You could try to add the legacyCorruptedStateExceptionsPolicy=true entry to your configuration file as stated in the MSDN article linked above.

Title: Catching Error when using Task.Factory

Body:
i am using the following

Task.Factory.StartNew(() => DoPrintConfigPage(serial));

then the function i am calling looks like this

private void DoPrintConfigPage(string serial)
{
    //do printing work
}

My problem is an exception is being thrown inside the thread and not being handled.

I have tried wrapping it in a try catch

try
{
    Task.Factory.StartNew(() => DoPrintConfigPage(serial));
}
catch (Exception ex) { }

but it still is not catching the error and thus crashing the application.

How can I catch exceptions in the main thread so I can handle them?

Update

I have made the changes recommended below and still it is saying the exception is unhandled

var task =  Task.Factory.StartNew(() => DoPrintConfigPage(serial))
                               .ContinueWith(tsk =>
                               {
                                  MessageBox.Show("something broke");
                               },TaskContinuationOptions.OnlyOnFaulted);

then in my DoConfigPage I added another try catch.

In this catch is now where it is crashing and saying the exception being thrown was unhandled, what am I missing?

private void DoPrintConfigPage(string serial)
{
    try
    {
        //call the print function
    }
    catch (Exception ex)
    {
        throw ex;   //it is crashing here and saying it is unhandled
    }
}

I also tried what Eric J. suggested with the same results

var task = Task.Factory.StartNew(() => DoPrintConfigPage(serial));

try
{
    task.Wait();
}
catch (AggregateException ex) { MessageBox.Show("something broke"); }


问:
Simple question on printf and C. Printing characters of a string one by one
I have weird string that I want to inspect by printing its characters one by one. How can this be done?

I'm worried in case it has any special characters that may obstruct its printing. Can they be 'escaped'?

答:
You could loop over the string, printing the characters one by one, and conditionally choosing to print the character or an escape sequence:

```<code>char *str, // the original string
     *tmp;
for(tmp = str; *tmp; tmp++)
  {
    printf((iscntrl(*tmp) ? "%02x\n" : "'%c'\n"), *tmp);
  }
</code>```

This prints one character per line, with control characters printed in hex format.

Body:
You could loop over the string, printing the characters one by one, and conditionally choosing to print the character or an escape sequence:

char *str, // the original string
     *tmp;
for(tmp = str; *tmp; tmp++)
  {
    printf((iscntrl(*tmp) ? "%02x\n" : "'%c'\n"), *tmp);
  }

This prints one character per line, with control characters printed in hex format.


问:
What is the meaning for .= (dot + =) in perl
I am new to perl scripting, so can anyone please let me know what is the meaning for .= in perl scripting. Will the data will be appended to that variable?

Input file has
1
2
3

Using loop access the file and write the variable.

I see the corresponding value are assigned like below.

```<code>$a .= $ipval
</code>```

So please let me know what does .= refers to.

答:
Yes, the value is concatenated to the variable on left.

Essentially

```<code>$a .= $ipval
</code>```

Is the same as:

```<code>$a = $a . $ipval
</code>```

Body:
I am new to perl scripting, so can anyone please let me know what is the meaning for .= in perl scripting. Will the data will be appended to that variable?

Input file has
1
2
3

Using loop access the file and write the variable.

I see the corresponding value are assigned like below.

$a .= $ipval

So please let me know what does .= refers to.

Body:
Yes, the value is concatenated to the variable on left.

Essentially

$a .= $ipval

Is the same as:

$a = $a . $ipval


问:
I can't get the EnvelopeTabs list
We are trying to execute below:
In the program using C # DocuSign API REST version SDK,
You are trying to create an envelope with a template,
At that timing, in the field defined in the template,
I want to fill in values from the program.
(The template contains the field of the signature tag.)

■ Issue
In order to obtain a list of DocuSign fields,
The API (EnvelopeTabs: list) is issued,
【Coding example】
Tabs tabs = envelopesApi.ListTabs (accountId, envelopeSummary.EnvelopeId, "1");

Following error has occurs.
By specifying a template, the field list defined in that template
The following error occurred when acquiring.

“  Error converting value 1 to type 'DocuSign.eSign.Model.Number'. Path 'signHereTabs [0] .scaleValue', line 6, position 23.”

■ Specific implementation details
Published from DocuSign

· CoreRecipes.cs
We used the following.

At the end of the requestSignatureOnDocumentTest method of CoreRecipes.cs,
Add the following code to get a list of tabs.
Tabs tabs = envelopesApi.ListTabs (accountId, envelopeSummary.EnvelopeId, "1");

In the Main method of CoreRecipes.cs,
// *** TEST 1 - Request Signature (on local document)
EnvelopeSummary envSummary = recipes.requestSignatureOnDocumentTest ();
Conducted.

■ Other information
If the signature field does not exist
(Eg Field A, Field B, Field C), you can get the field list,
In the case of
When the signature field exists
(Eg field A, field B, field C, signature field),
An error is returned and it can not be acquired.

答:
CoreRecipes.cs (Our Source Code)</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

using DocuSign.eSign.Api;
using DocuSign.eSign.Model;
using DocuSign.eSign.Client;

namespace TestProj
{
    class CoreRecipes
    {
        // Integrator Key (aka API key) is needed to authenticate your API calls.  This is an application-wide key
        private string INTEGRATOR_KEY = "[INTEGRATOR_KEY]";

        //////////////////////////////////////////////////////////
        // Main()
        //////////////////////////////////////////////////////////
        static void Main(string[] args)
        {
            CoreRecipes recipes = new CoreRecipes();

            //*** TEST 1 - Request Signature (on local document)
            EnvelopeSummary envSummary = recipes.requestSignatureOnDocumentTest();

            Console.Read();
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public EnvelopeSummary requestSignatureOnDocumentTest()
        {
            // Enter your DocuSign credentials below.  Note: You only need a DocuSign account to SEND documents,
            // signing is always free and signers do not need an account.
            string username = "[EMAIL]";
            string password = "[PASSWORD]";

            // Enter recipient (signer) name and email address
            string recipientName = "[RECIPIENT_NAME]";
            string recipientEmail = "[RECIPIENT_EMAIL]";

            // the document (file) we want signed
            const string SignTest1File = @"[PATH/TO/DOCUMENT/TEST.PDF]";

            // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
            configureApiClient("https://demo.docusign.net/restapi");

            //===========================================================
            // Step 1: Login()
            //===========================================================

            // call the Login() API which sets the user's baseUrl and returns their accountId
            string accountId = loginApi(username, password);

            //===========================================================
            // Step 2: Signature Request (AKA create & send Envelope)
            //===========================================================

            // Read a file from disk to use as a document.
            byte[] fileBytes = File.ReadAllBytes(SignTest1File);

            EnvelopeDefinition envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";

            // Add a document to the envelope
            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            envDef.Documents = new List<Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.Email = recipientEmail;
            signer.Name = recipientName;
            signer.RecipientId = "1";

            // Create a |SignHere| tab somewhere on the document for the recipient to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "100";
            signHere.YPosition = "100";
            signer.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients = new Recipients();
            envDef.Recipients.Signers = new List<Signer>();
            envDef.Recipients.Signers.Add(signer);

            // set envelope status to "sent" to immediately send the signature request
            envDef.Status = "sent";

            // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
            EnvelopesApi envelopesApi = new EnvelopesApi();
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);

            // print the JSON response
            Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));

            // *** I added a code here ***
            Tabs tabs = envelopesApi.ListTabs(accountId, envelopeSummary.EnvelopeId, "1");
            // *** I added a code here ***

            return envelopeSummary;

        } // end requestSignatureTest()

        //**********************************************************************************************************************
        //**********************************************************************************************************************
        //*  HELPER FUNCTIONS
        //**********************************************************************************************************************
        //**********************************************************************************************************************
        public void configureApiClient(string basePath)
        {
            // instantiate a new api client
            ApiClient apiClient = new ApiClient(basePath);

            // set client in global config so we don't need to pass it to each API object.
            Configuration.Default.ApiClient = apiClient;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public string loginApi(string usr, string pwd)
        {
            // we set the api client in global config when we configured the client
            ApiClient apiClient = Configuration.Default.ApiClient;
            string authHeader = "{\"Username\":\"" + usr + "\", \"Password\":\"" + pwd + "\", \"IntegratorKey\":\"" + INTEGRATOR_KEY + "\"}";
            Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);

            // we will retrieve this from the login() results
            string accountId = null;

            // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
            AuthenticationApi authApi = new AuthenticationApi();
            LoginInformation loginInfo = authApi.Login();

            // find the default account for this user
            foreach (LoginAccount loginAcct in loginInfo.LoginAccounts)
            {
                if (loginAcct.IsDefault == "true")
                {
                    accountId = loginAcct.AccountId;
                    break;
                }
            }
            if (accountId == null)
            { // if no default found set to first account
                accountId = loginInfo.LoginAccounts[0].AccountId;
            }
            return accountId;
        }

    } // end class
} // end namespace
</code>```

Title: I can't get the EnvelopeTabs list

Body:
CoreRecipes.cs (Our Source Code)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

using DocuSign.eSign.Api;
using DocuSign.eSign.Model;
using DocuSign.eSign.Client;

namespace TestProj
{
    class CoreRecipes
    {
        // Integrator Key (aka API key) is needed to authenticate your API calls.  This is an application-wide key
        private string INTEGRATOR_KEY = "[INTEGRATOR_KEY]";

        //////////////////////////////////////////////////////////
        // Main()
        //////////////////////////////////////////////////////////
        static void Main(string[] args)
        {
            CoreRecipes recipes = new CoreRecipes();

            //*** TEST 1 - Request Signature (on local document)
            EnvelopeSummary envSummary = recipes.requestSignatureOnDocumentTest();

            Console.Read();
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public EnvelopeSummary requestSignatureOnDocumentTest()
        {
            // Enter your DocuSign credentials below.  Note: You only need a DocuSign account to SEND documents,
            // signing is always free and signers do not need an account.
            string username = "[EMAIL]";
            string password = "[PASSWORD]";

            // Enter recipient (signer) name and email address
            string recipientName = "[RECIPIENT_NAME]";
            string recipientEmail = "[RECIPIENT_EMAIL]";

            // the document (file) we want signed
            const string SignTest1File = @"[PATH/TO/DOCUMENT/TEST.PDF]";

            // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
            configureApiClient("https://demo.docusign.net/restapi");

            //===========================================================
            // Step 1: Login()
            //===========================================================

            // call the Login() API which sets the user's baseUrl and returns their accountId
            string accountId = loginApi(username, password);

            //===========================================================
            // Step 2: Signature Request (AKA create & send Envelope)
            //===========================================================

            // Read a file from disk to use as a document.
            byte[] fileBytes = File.ReadAllBytes(SignTest1File);

            EnvelopeDefinition envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";

            // Add a document to the envelope
            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            envDef.Documents = new List<Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.Email = recipientEmail;
            signer.Name = recipientName;
            signer.RecipientId = "1";

            // Create a |SignHere| tab somewhere on the document for the recipient to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "100";
            signHere.YPosition = "100";
            signer.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients = new Recipients();
            envDef.Recipients.Signers = new List<Signer>();
            envDef.Recipients.Signers.Add(signer);

            // set envelope status to "sent" to immediately send the signature request
            envDef.Status = "sent";

            // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
            EnvelopesApi envelopesApi = new EnvelopesApi();
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);

            // print the JSON response
            Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));

            // *** I added a code here ***
            Tabs tabs = envelopesApi.ListTabs(accountId, envelopeSummary.EnvelopeId, "1");
            // *** I added a code here ***

            return envelopeSummary;

        } // end requestSignatureTest()

        //**********************************************************************************************************************
        //**********************************************************************************************************************
        //*  HELPER FUNCTIONS
        //**********************************************************************************************************************
        //**********************************************************************************************************************
        public void configureApiClient(string basePath)
        {
            // instantiate a new api client
            ApiClient apiClient = new ApiClient(basePath);

            // set client in global config so we don't need to pass it to each API object.
            Configuration.Default.ApiClient = apiClient;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public string loginApi(string usr, string pwd)
        {
            // we set the api client in global config when we configured the client
            ApiClient apiClient = Configuration.Default.ApiClient;
            string authHeader = "{\"Username\":\"" + usr + "\", \"Password\":\"" + pwd + "\", \"IntegratorKey\":\"" + INTEGRATOR_KEY + "\"}";
            Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);

            // we will retrieve this from the login() results
            string accountId = null;

            // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
            AuthenticationApi authApi = new AuthenticationApi();
            LoginInformation loginInfo = authApi.Login();

            // find the default account for this user
            foreach (LoginAccount loginAcct in loginInfo.LoginAccounts)
            {
                if (loginAcct.IsDefault == "true")
                {
                    accountId = loginAcct.AccountId;
                    break;
                }
            }
            if (accountId == null)
            { // if no default found set to first account
                accountId = loginInfo.LoginAccounts[0].AccountId;
            }
            return accountId;
        }

    } // end class
} // end namespace


问:
Calculating days between two dates in java with time zone
As per this question, I have calculated the days between two dates in java.
The program is below

```<code>SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}
</code>```

But I have got issues when the dates are in daylight saving time zone. Like EDT to EST. For example, when we calculate days between (MAR 01, 2017) to (MAR 30, 2017), the actual count should be 29 but the result of the above program is  28.

答:
You can use LocalDate for that:

```<code>System.out.println(
        Period.between(
                LocalDate.parse("2017-03-01"),
                LocalDate.parse("2017-03-30")
        ).getDays()
); // 29
</code>```

or using dd M yyyy format:

```<code>DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd M yyyy");
LocalDate localDate = LocalDate.parse("01 03 2017",dateTimeFormatter);
LocalDate localDate1 = LocalDate.parse("30 03 2017",dateTimeFormatter);
System.out.println(Period.between(localDate,localDate1).getDays());
</code>```

Body:
As per this question, I have calculated the days between two dates in java.
The program is below

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

But I have got issues when the dates are in daylight saving time zone. Like EDT to EST. For example, when we calculate days between (MAR 01, 2017) to (MAR 30, 2017), the actual count should be 29 but the result of the above program is  28.

Body:
You can use LocalDate for that:

System.out.println(
        Period.between(
                LocalDate.parse("2017-03-01"),
                LocalDate.parse("2017-03-30")
        ).getDays()
); // 29

or using dd M yyyy format:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd M yyyy");
LocalDate localDate = LocalDate.parse("01 03 2017",dateTimeFormatter);
LocalDate localDate1 = LocalDate.parse("30 03 2017",dateTimeFormatter);
System.out.println(Period.between(localDate,localDate1).getDays());


问:
Uncaught ReferenceError: Link is not defined React
I am using react 0.14.7 with webpack 1.12.13 and I get the following error:

```<code>Uncaught ReferenceError: Link is not defined
</code>```

This error is happening in the browser and everything compiles without error.

```<code>import React from 'react'
import { Link } from 'react-router'

export default React.createClass({
  render() {
    return <Link {...this.props} activeClassName="active"/>
  }
})
</code>```

webpack.config

```<code>var webpack = require('webpack')

module.exports = {
  entry: './src/client/js/index.js',

  output: {
    path: 'public',
    filename: 'bundle.js',
    publicPath: '/'
  },

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  plugins: process.env.NODE_ENV === 'production' ? [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin()
  ] : [],

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' },
      { test: /\.scss$/, loaders: ['style', 'css', 'sass']}
    ]
  },

}
</code>```

A little more, to add to the confusion I have consoled react-router and there is nothing there:

```<code>import router from 'react-router'
console.info(router); //undefined
</code>```

答:
Use react-router-dom instead.

import { Link } from 'react-router-dom'
...

See react-router-dom on npm.

Body:
I am using react 0.14.7 with webpack 1.12.13 and I get the following error:

Uncaught ReferenceError: Link is not defined

This error is happening in the browser and everything compiles without error.

import React from 'react'
import { Link } from 'react-router'

export default React.createClass({
  render() {
    return <Link {...this.props} activeClassName="active"/>
  }
})

webpack.config

var webpack = require('webpack')

module.exports = {
  entry: './src/client/js/index.js',

  output: {
    path: 'public',
    filename: 'bundle.js',
    publicPath: '/'
  },

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  plugins: process.env.NODE_ENV === 'production' ? [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin()
  ] : [],

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' },
      { test: /\.scss$/, loaders: ['style', 'css', 'sass']}
    ]
  },

}

A little more, to add to the confusion I have consoled react-router and there is nothing there:

import router from 'react-router'
console.info(router); //undefined


问:
Removing columns that satisfy a condition from a big data.frame in R
I have a big data.frame; 100,000 observations of 700 variables.

Most of the variables have actually value 0 in all the observations, and I would like to remove that variables/columns.

I tried the following,

```<code>data <- data[apply(data, 2, function(x){all(x == 0)})]
</code>```

But the apply took a lot of time to resolve.

I tried a while, in case the problem was working with all data at once.

```<code>i <- 1
while (i <= ncol(data)) {
  if (all(data[i] == 0)) {
    data[i] <- NULL
  } else {
    i <- i+1
  }
}
</code>```

But I kept having the same problem, it took a lot.

So,

Why does that operation take THAT long? Even though the data.frame is big, the operation is pretty simple.

and, above all

Is there any way to do this faster?

答:
Your question is confusing. I assume you want to remove variables, i.e., columns. You can use any with automatic coercion of values to type logical. The usual warnings regarding comparison of floating point numbers apply. If you want to play it safe, you'll need to test whether the doubles are smaller than some precision value, which will be slower, but getting it right is often more important.

```<code>DF <- data.frame(x = 1:3, y = 1:3/10, z = 0)
DF[] <- lapply(DF, function(x) if (any(x)) x else NULL)
#Warning messages:
#1: In any(x) : coercing argument of type 'double' to logical
#2: In any(x) : coercing argument of type 'double' to logical
#  x   y
#1 1 0.1
#2 2 0.2
#3 3 0.3

set.seed(42)
DF2 <- as.data.frame(matrix(sample(0:1, 700*1e5, TRUE, prob = c(0.999999, 0.000001)), ncol = 700))

system.time(DF2[] <- lapply(DF2, function(x) if (any(x)) x else NULL))
#user  system elapsed
#0.10    0.02    0.11
</code>```

Safer option:

```<code>set.seed(42)
DF2 <- as.data.frame(matrix(sample(0:1, 700*1e5, TRUE, prob = c(0.999999, 0.000001)), ncol = 700))

system.time(DF2[] <- lapply(DF2, function(x) if (any(x > 1e-16)) x else NULL))
#user  system elapsed
#0.34    0.11    0.45
</code>```

Body:
I have a big data.frame; 100,000 observations of 700 variables.

Most of the variables have actually value 0 in all the observations, and I would like to remove that variables/columns.

I tried the following,

data <- data[apply(data, 2, function(x){all(x == 0)})]

But the apply took a lot of time to resolve.

I tried a while, in case the problem was working with all data at once.

i <- 1
while (i <= ncol(data)) {
  if (all(data[i] == 0)) {
    data[i] <- NULL
  } else {
    i <- i+1
  }
}

But I kept having the same problem, it took a lot.

So,

Why does that operation take THAT long? Even though the data.frame is big, the operation is pretty simple.

and, above all

Is there any way to do this faster?

Body:
Your question is confusing. I assume you want to remove variables, i.e., columns. You can use any with automatic coercion of values to type logical. The usual warnings regarding comparison of floating point numbers apply. If you want to play it safe, you'll need to test whether the doubles are smaller than some precision value, which will be slower, but getting it right is often more important.

DF <- data.frame(x = 1:3, y = 1:3/10, z = 0)
DF[] <- lapply(DF, function(x) if (any(x)) x else NULL)
#Warning messages:
#1: In any(x) : coercing argument of type 'double' to logical
#2: In any(x) : coercing argument of type 'double' to logical
#  x   y
#1 1 0.1
#2 2 0.2
#3 3 0.3

set.seed(42)
DF2 <- as.data.frame(matrix(sample(0:1, 700*1e5, TRUE, prob = c(0.999999, 0.000001)), ncol = 700))

system.time(DF2[] <- lapply(DF2, function(x) if (any(x)) x else NULL))
#user  system elapsed
#0.10    0.02    0.11

Safer option:

set.seed(42)
DF2 <- as.data.frame(matrix(sample(0:1, 700*1e5, TRUE, prob = c(0.999999, 0.000001)), ncol = 700))

system.time(DF2[] <- lapply(DF2, function(x) if (any(x > 1e-16)) x else NULL))
#user  system elapsed
#0.34    0.11    0.45


问:
Google Visualization API -- Putting Y Axis on Right Side?
Using: http://code.google.com/apis/chart/interactive/docs/gallery/linechart.html#Loading

There isn't any options to put the y axis on the right side of the chart? For reals?! :P

Anyone know how to do such a 'radical' thing? The charting API lets you do this, but not the visualization?

Thanks SO.

答:
        function singleUserChart() {
            google.charts.load('current', { packages: ['corechart', 'bar'] });
            google.charts.setOnLoadCallback(drawAnnotations);

            function drawAnnotations() {
                var dataPercentage = new google.visualization.DataTable();
                dataPercentage.addColumn('string', 'Productivity');
                dataPercentage.addColumn('number', 'Ravi');
                dataPercentage.addColumn({ type: 'string', role: 'annotation' });
                dataPercentage.addColumn('number', 'Avg Data');
                dataPercentage.addColumn({ type: 'string', role: 'annotation' });

                dataPercentage.addRows([
                  ['%Score1', 12, '12%', 15, '15%'],
                  ['%Score2', 25, '25%', 21, '21%']
                ]);
                singleUserChartOptions(dataPercentage, 'individualUserPercentageChart', true, 450);
            }
        }
        function singleUserChartOptions(chartData, chartDivId, isShowPercent, chartWidth) {
            var options = {
                annotations: {
                    alwaysOutside: true,
                    textStyle: {
                        fontSize: 15,
                        color: '#000',
                        auraColor: 'none'
                    }
                },
                vAxis: { format: (isShowPercent == true) ? '#\'%\'' : '', ticks :[0,10,20,30,40,50]},
                hAxis: {
                    slantedText: true,
                    slantedTextAngle: -45,
                    textStyle: { fontSize: 11 }
                },
                series: {
                    0: { targetAxisIndex: 0, },
                    1: { targetAxisIndex: 1, }
                },
                vAxes: {
                    0: { textPosition: 'none' },
                    1: {}
                },
                legend: { position: 'top' },
                width: chartWidth,
                height: 400
            };

            var chart = new google.visualization.ColumnChart(document.getElementById(chartDivId));
            chart.draw(chartData, options);
        }
        singleUserChart();
   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
    <div id="individualUserPercentageChart" style="height: 500px; width: 100%"></div>
</body>
</html></code>```

Body:
        function singleUserChart() {
            google.charts.load('current', { packages: ['corechart', 'bar'] });
            google.charts.setOnLoadCallback(drawAnnotations);

            function drawAnnotations() {
                var dataPercentage = new google.visualization.DataTable();
                dataPercentage.addColumn('string', 'Productivity');
                dataPercentage.addColumn('number', 'Ravi');
                dataPercentage.addColumn({ type: 'string', role: 'annotation' });
                dataPercentage.addColumn('number', 'Avg Data');
                dataPercentage.addColumn({ type: 'string', role: 'annotation' });

                dataPercentage.addRows([
                  ['%Score1', 12, '12%', 15, '15%'],
                  ['%Score2', 25, '25%', 21, '21%']
                ]);
                singleUserChartOptions(dataPercentage, 'individualUserPercentageChart', true, 450);
            }
        }
        function singleUserChartOptions(chartData, chartDivId, isShowPercent, chartWidth) {
            var options = {
                annotations: {
                    alwaysOutside: true,
                    textStyle: {
                        fontSize: 15,
                        color: '#000',
                        auraColor: 'none'
                    }
                },
                vAxis: { format: (isShowPercent == true) ? '#\'%\'' : '', ticks :[0,10,20,30,40,50]},
                hAxis: {
                    slantedText: true,
                    slantedTextAngle: -45,
                    textStyle: { fontSize: 11 }
                },
                series: {
                    0: { targetAxisIndex: 0, },
                    1: { targetAxisIndex: 1, }
                },
                vAxes: {
                    0: { textPosition: 'none' },
                    1: {}
                },
                legend: { position: 'top' },
                width: chartWidth,
                height: 400
            };

            var chart = new google.visualization.ColumnChart(document.getElementById(chartDivId));
            chart.draw(chartData, options);
        }
        singleUserChart();

<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
    <div id="individualUserPercentageChart" style="height: 500px; width: 100%"></div>
</body>
</html>


问:
C++ How to design a class that can take on only a discrete set of values, e.g. Red Green Blue
Say for example that we want to design a color class, assuming that we only allow for 3 different color values: Red, Green, Blue.

How is this generally achieved in C++? Or better what is the general design pattern for this?

The only way I could think of, is to initialize 3 different static colors in the Color class, make the colourCode inaccessible and allow construction of a new Color only with an already existing one.

```<code>class Colour
{
public:
    static const Colour Red;
    static const Colour Green;
    static const Colour Blue;

    Colour(){}

    bool operator==(const Colour &other) const{
        if(other.colourCode == this->colourCode){return true;}else{return false;}
    }

    Colour & operator=(const Colour & other){
        this->colourCode = other.colourCode;
    }

    Colour(const Colour & other){
        *this = other;}

private:
    int colourCode;

    Colour(int colourCodeIn){
        colourCode = colourCodeIn;
    }
};

const Colour Colour::Red(1);
const Colour Colour::Green(2);
const Colour Colour::Blue(3);

class Pen
{
public:
    Pen(){}
    void setColour(const Colour & infarbe){
        farbe = infarbe;
    }
    Colour farbe;
};

int main()
{
    Pen myPen1;

    myPen1.setColour(Colour::Blue);

    return 0;
}
</code>```

答:
Use an enum or enum class.

References:

Cppreference has all details and covers exactly your RGB example.

Alex Allain elaborates benefits of enum classes also illustrated with RGB.

Body:
Say for example that we want to design a color class, assuming that we only allow for 3 different color values: Red, Green, Blue.

How is this generally achieved in C++? Or better what is the general design pattern for this?

The only way I could think of, is to initialize 3 different static colors in the Color class, make the colourCode inaccessible and allow construction of a new Color only with an already existing one.

class Colour
{
public:
    static const Colour Red;
    static const Colour Green;
    static const Colour Blue;

    Colour(){}

    bool operator==(const Colour &other) const{
        if(other.colourCode == this->colourCode){return true;}else{return false;}
    }

    Colour & operator=(const Colour & other){
        this->colourCode = other.colourCode;
    }

    Colour(const Colour & other){
        *this = other;}

private:
    int colourCode;

    Colour(int colourCodeIn){
        colourCode = colourCodeIn;
    }
};

const Colour Colour::Red(1);
const Colour Colour::Green(2);
const Colour Colour::Blue(3);

class Pen
{
public:
    Pen(){}
    void setColour(const Colour & infarbe){
        farbe = infarbe;
    }
    Colour farbe;
};

int main()
{
    Pen myPen1;

    myPen1.setColour(Colour::Blue);

    return 0;
}


问:
string.compare and string for comparison
I have my code like this

```<code>private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }
</code>```

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

答:
For case insensitive comparison:</p>

```<code>    string a = "text1";
    string b = "TeXt1";

    if(string.Compare( a, b, true ) == 0) {
        Console.WriteLine("Equal");
    }
</code>```

Body:
I have my code like this

private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

Body:
For case insensitive comparison:

    string a = "text1";
    string b = "TeXt1";

    if(string.Compare( a, b, true ) == 0) {
        Console.WriteLine("Equal");
    }


问:
Swift 3.1 deprecates initialize(). How can I achieve the same thing?
Objective-C declares a class function, initialize(), that is run once for each class, before it is used. It is often used as an entry point for exchanging method implementations (swizzling), among other things.

Swift 3.1 deprecates this function with a warning:

Method 'initialize()' defines Objective-C class method 'initialize',
  which is not guaranteed to be invoked by Swift and will be disallowed
  in future versions

How can this be resolved, while still maintaining the same behaviour and features that I currently implement using the initialize() entry point?

答:
If you prefer Pure Swift™! then my solution to this kind of thing is running at _UIApplicationMainPreparations time to kick things off:

```<code>@UIApplicationMain
private final class OurAppDelegate: FunctionalApplicationDelegate {
    // OurAppDelegate() constructs these at _UIApplicationMainPreparations time
    private let allHandlers: [ApplicationDelegateHandler] = [
        WindowHandler(),
        FeedbackHandler(),
        ...
</code>```

Pattern here is I'm avoiding the Massive Application Delegate problem by decomposing UIApplicationDelegate into various protocols that individual handlers can adopt, in case you're wondering. But the important point is that a pure-Swift way to get to work as early as possible is dispatch your +initialize type tasks in the initialization of your @UIApplicationMain class, like the construction of allHandlers here. _UIApplicationMainPreparations time ought to be early enough for pretty much anybody!

Body:
If you prefer Pure Swift™! then my solution to this kind of thing is running at _UIApplicationMainPreparations time to kick things off:

@UIApplicationMain
private final class OurAppDelegate: FunctionalApplicationDelegate {
    // OurAppDelegate() constructs these at _UIApplicationMainPreparations time
    private let allHandlers: [ApplicationDelegateHandler] = [
        WindowHandler(),
        FeedbackHandler(),
        ...

Pattern here is I'm avoiding the Massive Application Delegate problem by decomposing UIApplicationDelegate into various protocols that individual handlers can adopt, in case you're wondering. But the important point is that a pure-Swift way to get to work as early as possible is dispatch your +initialize type tasks in the initialization of your @UIApplicationMain class, like the construction of allHandlers here. _UIApplicationMainPreparations time ought to be early enough for pretty much anybody!


问:
How to change the structure of JSON
I have a JSON like this

```<code>{"a":1,"b":2,"c":3}
</code>```

how can I convert its structure like this

```<code>[{
"option_id": "a",
"option_value": "1"
},
{
"option_id": "b",
"option_value": "2"
},
{
"option_id": "c",
"option_value": "3"
}]
</code>```

I tried JSON.stringify, result.push([i,data[i]]) etc but to no success so far

答:
```<code>var object = {"a":1, "b":2, "c":3}, resultArr = [];

for(var key in object) {
resultArr.push({
"option_id": key,
"option_value": object[key]
});
}

console.log(resultArr);

var outputArr = Object.keys(object).map(function(eachItem){
return {
"option_id": eachItem,
"option_value": object[eachItem]
};
});

console.log(outputArr);
</code>```

Title: How to change the structure of JSON

Body:
I have a JSON like this

{"a":1,"b":2,"c":3}

how can I convert its structure like this

[{
"option_id": "a",
"option_value": "1"
},
{
"option_id": "b",
"option_value": "2"
},
{
"option_id": "c",
"option_value": "3"
}]

I tried JSON.stringify, result.push([i,data[i]]) etc but to no success so far


问:
android : GIF animation cycle complete Listener
I have one GIF image and want to load in Splash Screen.
I came across few libraries like android-gif-drawable
 and Glide

Is there any way I can listen for one animation cycle complete ?
I mean once animation cycle is complete(whole animation is completed, without repeating) I want a listener, that Animation is complete, and provides us with some callback. Somewhat like:

```<code>SomeLibrary.load("GIF")
.into(imageview)
.repeat(false)
.setOnAnimationCompleteListener(new OnAnimationCompleteListener(){
    public void onAnimationComplete(){
        // Animation is completed. Do whatever you want to do..
    }
});
</code>```

I have worked with both libraries But looking for a feature as I mentioned above.

答:
Below is the complete code for gif 1 loop animation. After completing loop, control will redirects to next activity.</p>

```<code>private void initGlideGifImageView() {

    showProgressDialog("Loading image...");
    GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(imgSafetyGif, 1);
    Glide
            .with(this)
            .load(GIF_SOURCE_URL)
            .placeholder(R.drawable.img_placeholder_1)
            .error(R.drawable.img_error_1_280_text)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .listener(new RequestListener<String, GlideDrawable>() {

                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    hideProgressDialog();
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    hideProgressDialog();

                    GifDrawable gifDrawable = null;
                    Handler handler = new Handler();
                    if (resource instanceof GifDrawable) {
                        gifDrawable = (GifDrawable) resource;

                        int duration = 0;
                        GifDecoder decoder = gifDrawable.getDecoder();
                        for (int i = 0; i < gifDrawable.getFrameCount(); i++) {
                            duration += decoder.getDelay(i);
                        }

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                                startActivity(intent);
                                SplashScreenActivity.this.finish();
                            }
                        }, (duration + 3000));

                    }

                    return false;
                }

            })
            .into(imageViewTarget);
}
</code>```

Body:
I have one GIF image and want to load in Splash Screen.
I came across few libraries like android-gif-drawable
 and Glide

Is there any way I can listen for one animation cycle complete ?
I mean once animation cycle is complete(whole animation is completed, without repeating) I want a listener, that Animation is complete, and provides us with some callback. Somewhat like:

SomeLibrary.load("GIF")
.into(imageview)
.repeat(false)
.setOnAnimationCompleteListener(new OnAnimationCompleteListener(){
    public void onAnimationComplete(){
        // Animation is completed. Do whatever you want to do..
    }
});

I have worked with both libraries But looking for a feature as I mentioned above.

Body:
Below is the complete code for gif 1 loop animation. After completing loop, control will redirects to next activity.

private void initGlideGifImageView() {

    showProgressDialog("Loading image...");
    GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(imgSafetyGif, 1);
    Glide
            .with(this)
            .load(GIF_SOURCE_URL)
            .placeholder(R.drawable.img_placeholder_1)
            .error(R.drawable.img_error_1_280_text)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .listener(new RequestListener<String, GlideDrawable>() {

                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    hideProgressDialog();
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    hideProgressDialog();

                    GifDrawable gifDrawable = null;
                    Handler handler = new Handler();
                    if (resource instanceof GifDrawable) {
                        gifDrawable = (GifDrawable) resource;

                        int duration = 0;
                        GifDecoder decoder = gifDrawable.getDecoder();
                        for (int i = 0; i < gifDrawable.getFrameCount(); i++) {
                            duration += decoder.getDelay(i);
                        }

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                                startActivity(intent);
                                SplashScreenActivity.this.finish();
                            }
                        }, (duration + 3000));

                    }

                    return false;
                }

            })
            .into(imageViewTarget);
}


问:
SQL Server: Combine multiple rows into one with no overlap but new columns
I have a Table "Details" like this:

```<code>    ID         |        BookID         |        Genre
    _____________________________________________________
    1          |         12            |         AB
    1          |         05            |         AC
    2          |         12            |         AB
    2          |         08            |         BB
</code>```

Is there any way to combine the rows in this format:

```<code>    ID  | BookID1 | Genre1  | BookID2 | Genre2
    _____________________________________________________
    1   | 12      | AB      | 05      |   AC
    2   | 12      | AB      | 08      |   BB
</code>```

I need to do it in such a format to add the respective columns to a stored procedure.

I generally would love to include some code or attempts but I'm clueless at this moment.

Not a Duplicate of the below:
T-SQL dynamic pivot

1st difference im not using tsql

2nd difference is the structure of the table which can't be applied to mine.

My values are not going to be column headers instead they are gonna generate new columns such as :

```<code>    ID  | BookID1 | Genre1  | BookID2 | Genre2  | BookID3 | Genre3  | BookID4 | Genre4
    1   | 05      | Horror  | 12      | Horror  | 03      | Drama   |         |
    2   | 05      | Horror  | 15      | Advent  | 03      | Drama   | 112     | RomCom
</code>```

3rd Im not able to grasp the structure since I have zero knowledge of pivot tables

答:
Try a dynamic sql query </p>

```<code>CREATE TABLE #BookGenreMapping
(
   Id int,
   BookId int,
   Genre varchar(20)
)

INSERT INTO #BookGenreMapping VALUES (1,12,'AB'),(1,05,'AC'),(2,12,'AB'),(2,08,'BC'),(2,09,'BCD')
DECLARE @HeaderAll nvarchar(max)
DECLARE @ColumnPivotBookId nvarchar(max)
DECLARE @ColumnPivotGenre nvarchar(max)

;WITH temp AS
(
   SELECT *,
   CONCAT('BookID' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupId,
   CONCAT('BookGroupGenre' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupGenre
   FROM #BookGenreMapping bgm
),
temp1 AS
(
   SELECT DISTINCT t.BookGroupId, t.BookGroupGenre FROM temp t
)
SELECT @HeaderAll = STUFF((SELECT CONCAT(',',t.BookGroupId, ',', t.BookGroupGenre) FROM temp1 t FOR XML PATH('')), 1,1,''),
     @ColumnPivotBookId =  STUFF((SELECT CONCAT(',',t.BookGroupId) FROM temp1 t FOR XML PATH('')), 1,1,''),
     @ColumnPivotGenre =  STUFF((SELECT CONCAT(',', t.BookGroupGenre) FROM temp1 t FOR XML PATH('')), 1,1,'')

--SELECT @HeaderAll, @ColumnPivotBookId, @ColumnPivotGenre

DECLARE @query nvarchar(max) = CONCAT(
      ';WITH temp AS
      (
         SELECT *,
         CONCAT(''','BookID',''' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupId,
         CONCAT(''','BookGroupGenre',''' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupGenre
         FROM #BookGenreMapping bgm
      )
      SELECT pt1.Id, ',@HeaderAll,' FROM
      (
          SELECT Id, ',@ColumnPivotBookId,' FROM
          (
            SELECT t.Id, t.BookId, t.BookGroupId FROM temp t
          ) src
          PIVOT
          (
            MIN(BookId) FOR BookGroupId IN (',@ColumnPivotBookId,')
          ) pvt
       ) pt1
       INNER JOIN
       (
          SELECT Id, ',@ColumnPivotGenre,' FROM
          (
            SELECT t.Id, t.Genre, t.BookGroupGenre FROM temp t
          ) src
          PIVOT
          (
            MIN(Genre) FOR BookGroupGenre IN (',@ColumnPivotGenre,')
          ) pvt
       ) pt2 ON pt1.Id = pt2.Id'
       )

PRINT @query
exec(@query)

DROP TABLE #BookGenreMapping
</code>```

Body:
I have a Table "Details" like this:

    ID         |        BookID         |        Genre
    _____________________________________________________
    1          |         12            |         AB
    1          |         05            |         AC
    2          |         12            |         AB
    2          |         08            |         BB

Is there any way to combine the rows in this format:

    ID  | BookID1 | Genre1  | BookID2 | Genre2
    _____________________________________________________
    1   | 12      | AB      | 05      |   AC
    2   | 12      | AB      | 08      |   BB

I need to do it in such a format to add the respective columns to a stored procedure.

I generally would love to include some code or attempts but I'm clueless at this moment.

Not a Duplicate of the below:
T-SQL dynamic pivot

1st difference im not using tsql

2nd difference is the structure of the table which can't be applied to mine.

My values are not going to be column headers instead they are gonna generate new columns such as :

    ID  | BookID1 | Genre1  | BookID2 | Genre2  | BookID3 | Genre3  | BookID4 | Genre4
    1   | 05      | Horror  | 12      | Horror  | 03      | Drama   |         |
    2   | 05      | Horror  | 15      | Advent  | 03      | Drama   | 112     | RomCom

3rd Im not able to grasp the structure since I have zero knowledge of pivot tables

Body:
Try a dynamic sql query

CREATE TABLE #BookGenreMapping
(
   Id int,
   BookId int,
   Genre varchar(20)
)

INSERT INTO #BookGenreMapping VALUES (1,12,'AB'),(1,05,'AC'),(2,12,'AB'),(2,08,'BC'),(2,09,'BCD')
DECLARE @HeaderAll nvarchar(max)
DECLARE @ColumnPivotBookId nvarchar(max)
DECLARE @ColumnPivotGenre nvarchar(max)

;WITH temp AS
(
   SELECT *,
   CONCAT('BookID' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupId,
   CONCAT('BookGroupGenre' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupGenre
   FROM #BookGenreMapping bgm
),
temp1 AS
(
   SELECT DISTINCT t.BookGroupId, t.BookGroupGenre FROM temp t
)
SELECT @HeaderAll = STUFF((SELECT CONCAT(',',t.BookGroupId, ',', t.BookGroupGenre) FROM temp1 t FOR XML PATH('')), 1,1,''),
     @ColumnPivotBookId =  STUFF((SELECT CONCAT(',',t.BookGroupId) FROM temp1 t FOR XML PATH('')), 1,1,''),
     @ColumnPivotGenre =  STUFF((SELECT CONCAT(',', t.BookGroupGenre) FROM temp1 t FOR XML PATH('')), 1,1,'')

--SELECT @HeaderAll, @ColumnPivotBookId, @ColumnPivotGenre

DECLARE @query nvarchar(max) = CONCAT(
      ';WITH temp AS
      (
         SELECT *,
         CONCAT(''','BookID',''' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupId,
         CONCAT(''','BookGroupGenre',''' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupGenre
         FROM #BookGenreMapping bgm
      )
      SELECT pt1.Id, ',@HeaderAll,' FROM
      (
          SELECT Id, ',@ColumnPivotBookId,' FROM
          (
            SELECT t.Id, t.BookId, t.BookGroupId FROM temp t
          ) src
          PIVOT
          (
            MIN(BookId) FOR BookGroupId IN (',@ColumnPivotBookId,')
          ) pvt
       ) pt1
       INNER JOIN
       (
          SELECT Id, ',@ColumnPivotGenre,' FROM
          (
            SELECT t.Id, t.Genre, t.BookGroupGenre FROM temp t
          ) src
          PIVOT
          (
            MIN(Genre) FOR BookGroupGenre IN (',@ColumnPivotGenre,')
          ) pvt
       ) pt2 ON pt1.Id = pt2.Id'
       )

PRINT @query
exec(@query)

DROP TABLE #BookGenreMapping


问:
How do I force a task on airflow to fail?
I have a python callable process_csv_entries that processes csv file entries. I want my task to complete successfully only if all entries were processed successfully. Task should fail otherwise

```<code>def process_csv_entries(csv_file):
    # Boolean
    file_completely_parsed = <call_to_module_to_parse_csv>
    return not file_completely_parsed

CSV_FILE=<Sets path to csv file>
t1 = PythonOperator(dag=dag,
                      task_id='parse_csv_completely',
                      python_operator=process_csv_entries,
                      op_args=[CSV_FILE])
</code>```

t1 seems to complete successfully irrespective of returned value.
How do I force PythonOperator task to fail?

答:
raise exception when you meet the error condition ( in your case: when file is not sucesfully parsed)

```<code>raise ValueError('File not parsed completely/correctly')
</code>```

raise relevant error type with suitable message

Body:
I have a python callable process_csv_entries that processes csv file entries. I want my task to complete successfully only if all entries were processed successfully. Task should fail otherwise

def process_csv_entries(csv_file):
    # Boolean
    file_completely_parsed = <call_to_module_to_parse_csv>
    return not file_completely_parsed

CSV_FILE=<Sets path to csv file>
t1 = PythonOperator(dag=dag,
                      task_id='parse_csv_completely',
                      python_operator=process_csv_entries,
                      op_args=[CSV_FILE])

t1 seems to complete successfully irrespective of returned value.
How do I force PythonOperator task to fail?

Body:
raise exception when you meet the error condition ( in your case: when file is not sucesfully parsed)

raise ValueError('File not parsed completely/correctly')

raise relevant error type with suitable message


问:
Why moment is adding one hour?
When I use:

```<code>console.log(moment(1000*60*60*1).format('hh[h] mm[min] ss[sec]'));
</code>```

I get 2h 0min 0sec instead of just 1hour.

I made a workaround by adding .subtract(1, 'hour') like this:

```<code>console.log(moment(1000*60*60*1).subtract(1, 'hour').format('hh[h] mm[min] ss[sec]'));
</code>```

I'm still learning this library that i found today. Am I missing something?

What am I supposed to do if I have milliseconds and I want to get a formatted date out of it?

答:
Moment counts your timezone, to get the time without timezone offset you can use

```<code>moment(1000*60*60*1).utc().format('hh[h] mm[min] ss[sec]')
</code>```

Or

```<code>moment.utc(1000*60*60*1).format('hh[h] mm[min] ss[sec]')
</code>```

Title: Why moment is adding one hour?

Body:
When I use:

console.log(moment(1000*60*60*1).format('hh[h] mm[min] ss[sec]'));

I get 2h 0min 0sec instead of just 1hour.

I made a workaround by adding .subtract(1, 'hour') like this:

console.log(moment(1000*60*60*1).subtract(1, 'hour').format('hh[h] mm[min] ss[sec]'));

I'm still learning this library that i found today. Am I missing something?

What am I supposed to do if I have milliseconds and I want to get a formatted date out of it?

Body:
Moment counts your timezone, to get the time without timezone offset you can use

moment(1000*60*60*1).utc().format('hh[h] mm[min] ss[sec]')

Or

moment.utc(1000*60*60*1).format('hh[h] mm[min] ss[sec]')


问:
Action Button Not Appearing in Notification iOS 10
I am using local push notifications in my app. when added action button for the notification in iOS 10, it doesn't appear below the notification. the notification is appearing, but the action button is missing at the bottom of the notification. The appdelegate code is given below.</p>

```<code>import UIKit
import CoreData
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
      if !accepted {
        print("Notification access denied.")
      }
    }
    let action = UNNotificationAction(identifier: "markCompleted", title: "Mark as Completed", options: [])
    let category = UNNotificationCategory(identifier: "todoList", actions: [action], intentIdentifiers: [], options: [])
    UNUserNotificationCenter.current().setNotificationCategories([category])
    return true
  }

  func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  }

  func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  }

  func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
  }

  func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  }

  func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
  }

  // MARK: - user defined functions

  func notifyWithinApp(_ message: String) {
    Utils.sharedInstance.notifyLocally(message)
  }

  func scheduleNotification(at date: Date, body: String) {
    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = "Dont Forget"
    content.body = body
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "todoList"

    let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self
    //UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
      if let error = error {
        print("Uh oh! We had an error: \(error)")
      }
    }
  }

  // MARK: - Core Data stack

  lazy var persistentContainer: NSPersistentContainer = {
      /*
       The persistent container for the application. This implementation
       creates and returns a container, having loaded the store for the
       application to it. This property is optional since there are legitimate
       error conditions that could cause the creation of the store to fail.
      */
      let container = NSPersistentContainer(name: "ListTodo")
      container.loadPersistentStores(completionHandler: { (storeDescription, error) in
          if let error = error as NSError? {
              // Replace this implementation with code to handle the error appropriately.
              // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

              /*
               Typical reasons for an error here include:
               * The parent directory does not exist, cannot be created, or disallows writing.
               * The persistent store is not accessible, due to permissions or data protection when the device is locked.
               * The device is out of space.
               * The store could not be migrated to the current model version.
               Check the error message to determine what the actual problem was.
               */
              fatalError("Unresolved error \(error), \(error.userInfo)")
          }
      })
      return container
  }()

  // MARK: - Core Data Saving support

  func saveContext () {
      let context = persistentContainer.viewContext
      if context.hasChanges {
          do {
              try context.save()
          } catch {
              // Replace this implementation with code to handle the error appropriately.
              // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
              let nserror = error as NSError
              fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
          }
      }
  }

}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // Print message ID.
    // Print full message.
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    if response.actionIdentifier == "markCompleted" {
    }
  }
}
</code>```

答: Actually i didnt swipe the notification. then i found that the button appears only when you swipe the notification. Terrible UI/UX design by Apple.</p>

Body:
I am using local push notifications in my app. when added action button for the notification in iOS 10, it doesn't appear below the notification. the notification is appearing, but the action button is missing at the bottom of the notification. The appdelegate code is given below.

import UIKit
import CoreData
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
      if !accepted {
        print("Notification access denied.")
      }
    }
    let action = UNNotificationAction(identifier: "markCompleted", title: "Mark as Completed", options: [])
    let category = UNNotificationCategory(identifier: "todoList", actions: [action], intentIdentifiers: [], options: [])
    UNUserNotificationCenter.current().setNotificationCategories([category])
    return true
  }

  func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  }

  func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  }

  func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
  }

  func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  }

  func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
  }

  // MARK: - user defined functions

  func notifyWithinApp(_ message: String) {
    Utils.sharedInstance.notifyLocally(message)
  }

  func scheduleNotification(at date: Date, body: String) {
    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = "Dont Forget"
    content.body = body
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "todoList"

    let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self
    //UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
      if let error = error {
        print("Uh oh! We had an error: \(error)")
      }
    }
  }

  // MARK: - Core Data stack

  lazy var persistentContainer: NSPersistentContainer = {
      /*
       The persistent container for the application. This implementation
       creates and returns a container, having loaded the store for the
       application to it. This property is optional since there are legitimate
       error conditions that could cause the creation of the store to fail.
      */
      let container = NSPersistentContainer(name: "ListTodo")
      container.loadPersistentStores(completionHandler: { (storeDescription, error) in
          if let error = error as NSError? {
              // Replace this implementation with code to handle the error appropriately.
              // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

              /*
               Typical reasons for an error here include:
               * The parent directory does not exist, cannot be created, or disallows writing.
               * The persistent store is not accessible, due to permissions or data protection when the device is locked.
               * The device is out of space.
               * The store could not be migrated to the current model version.
               Check the error message to determine what the actual problem was.
               */
              fatalError("Unresolved error \(error), \(error.userInfo)")
          }
      })
      return container
  }()

  // MARK: - Core Data Saving support

  func saveContext () {
      let context = persistentContainer.viewContext
      if context.hasChanges {
          do {
              try context.save()
          } catch {
              // Replace this implementation with code to handle the error appropriately.
              // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
              let nserror = error as NSError
              fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
          }
      }
  }

}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // Print message ID.
    // Print full message.
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    if response.actionIdentifier == "markCompleted" {
    }
  }
}


问:
Two-item-to-item collaborative filtering- Is there a solution?
I have the following problem: In my case a person always buys two products (one of type X and one of type Y). After this I want to recommend further products of type Z to my customer. I already figured out that if the person only bought one item the best way would be probably an item-to-item recommender. But I can not come up with a solution where the recommendation is always based on the combination of one product of type X and one of type Y and the recommend several products of type Z to the customer.

So maybe there is a solution out there for this problem that I haven't found yet?

Many thanks

答:
One approach here is to look into building a 'hybrid' recommender system:

Calculate item-item scores using query item X

Calculate item-item scores using query item Y

You know have a new problem to solve:

Input: item_scores_X, item_scores_Y

Output: prediction_Z

There are several ways to tackle making the prediction of Z, based on knowing X and Y. You could formulate this as a regression problem, and perhaps look into RandomForests for example. You could also build a 'cascade' system if it is true to say the most recent item is more informative. There are more sophisticated ways, but the input/output of the problem remain as described. Reading about hybrid recommender systems should give you more ideas.


问:
rails don't calls the engine's controller
I am trying to define some helper methods to be used in the app's controller, but it seems that rails don't even call the controller. just for the test I have the following controller in my app/controllers/my_engine/application_controller.rb and as the documents say rails should find it first and an error should raise because THIS_SHOULD_PRODUCE_ERROR is unknown, but the rspec happily executing without any errors!

```<code>class ApplicationController <  ActionController::Base
  THIS_SHOULD_PRODUCE_ERROR
end
</code>```

I even tried to mimic the devise's way but the results are the same!

答:
The guide section on the app directory suggests that the application_controller in an engine "will provide any common functionality for the controllers of the engine".

So I wouldn't expect that any additions to that controller will be available to all controllers in an application.

That also means that your application_controller is, I suspect, not getting called when you're running your test. Which would explain why you're not seeing an error.

In terms of how devise does it I think you need to be looking at how define_helpers works. The code you've linked to in your question is the application controller in the test app for the devise gem.

Body:
I am trying to define some helper methods to be used in the app's controller, but it seems that rails don't even call the controller. just for the test I have the following controller in my app/controllers/my_engine/application_controller.rb and as the documents say rails should find it first and an error should raise because THIS_SHOULD_PRODUCE_ERROR is unknown, but the rspec happily executing without any errors!

class ApplicationController <  ActionController::Base
  THIS_SHOULD_PRODUCE_ERROR
end

I even tried to mimic the devise's way but the results are the same!


问:
SQL Server performance for alter table alter column change data type
We need to change the data types of some columns from int to bigint. Unfortunately some of these tables are large, around 7-10 million rows (but not wide).

Alter table alter column is taking forever on these tables. Is there a faster way to achieve this?

答:
create the new table you desire, with the right columntypes and indices. (script out the old table, and change the name.)

insert into new table (column list) select * from old_table;

rename the old_table old_table_back, rename new_table old_table.

create the old indices on the new table, drop any ri constraints on the old table and creaet them on the new table. Again, your rdbms will have some easy way to generate scripts to do this.