问:
Connection between two pods located in independent Kubernetes clusters
I have two (independent) Kubernetes clusters, one setup as a GKE/GCE cluster and the other setup in an AWS environment created using the kube-up.sh script. Both clusters are working properly and I can start / stop pods, services, and everything else between.

I want pods located in these clusters to communicate with each other, but without exposing them as services. In order to achieve this, I have setup a VPN connection between the two clusters, and also a couple of routing / firewall rules to make sure the VMs / pods can see each other.

I can confirm that the following scenarios are working properly:

VM in GCE -> VM in AWS (OK)

Pod in GCE -> VM in AWS (OK)

VM in AWS -> VM in GCE (OK)

VM in AWS -> Pod in GCE (OK)

Pod in AWS -> Pod in GCE (OK)

However, I can't make a VM or Pod in GCE communicate with a Pod in AWS.

I was wondering if there is any way of making this work with current AWS VPC capabilities. It seems that when the AWS end of the VPN tunnel receives packets addressed to a pod, it doesn't really know what to do with them. On the other hand, GCE networking is automatically configured with routes that associate pod IPs to a GKE cluster. In this case, when a packet addressed to a pod reaches the GCE end of the VPN tunnel, it is correctly forwarded to its destination.

That's my configuration:

GKE/GCE in us-east1

Network: 10.142.0.0/20

VM1 IP: 10.142.0.2

Pod range (for VM1) : 10.52.4.0/24

Pod1 IP: 10.52.4.4 (running busybox)

Firewall rule: Allows any traffic from 172.16.0.0/12

Route: Sends everything with destination 172.16.0.0/12 to the VPN tunnel (automatically added when the VPN is created)

AWS in ap-northeast-1

VPC: 172.24.0.0/16

Subnet1: 172.24.1.0/24

VM3 IP (in Subnet1): 172.24.1.5

Kubernetes cluster network (NON_MASQUERADE_CIDR): 172.16.0.0/16

Pod range (CLUSTER_IP_RANGE): 172.16.128.0/17

Pod range (for VM3) : 172.16.129.0/24

Pod3 IP: 172.16.129.5

Security Group: Allows any traffic from 10.0.0.0/8

Routes:

Destination 10.0.0.0/8 to the VPN tunnel

Destination 172.16.129.0/24 to VM3

Has anyone tried to do something similar? Is there any way to configure AWS VPC VPN Gateway to ensure the packets destined to Pods are correctly sent to the VMs that host them? Any suggestions?

答:
What you are asking in kubernetes federation.

Federation makes it easy to manage multiple clusters. It does so by
  providing 2 major building blocks:

Sync resources across clusters: Federation provides the ability to keep resources in multiple clusters in sync. This can be used, for
  example, to ensure that the same deployment exists in multiple
  clusters.

Cross cluster discovery: It provides the ability to auto-configure DNS servers and load balancers with backends from all clusters. This
  can be used, for example, to ensure that a global VIP or DNS record
  can be used to access backends from multiple clusters.

Also,this one might help you https://kubernetes.io/docs/admin/multiple-zones/


来源: stackexchange

问:
Multiple lines not reading into one list item
For some reason when I read in clipboard data and write it to a file, read that file in and set it to a list after delineating it with ¢ it loads up my listbox just fine on the first load as in when my form first loads up. However I have the following trigger on a button click, it is for some reason splitting up multiple line sections into separate list items, which is not what I want and not what the same code does when the form first loads. It's a little frustrating as it's writing to the text file and everything the same way.

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

        // until next comment this is the same as what I have run at the start of the
        // program, it loads up multiple lines into one list item as it should
        string checkForDupe = File.ReadAllText(@"C:\temp\testfile.txt");
        string checkResponses = File.ReadAllText(@"C:\temp\testfile2.txt");
        if (Clipboard.ContainsText() && !checkForDupe.Contains(Clipboard.GetText()))
        {
            if (!checkResponses.Contains(Clipboard.GetText()))
            {
                var text = "\n" + Clipboard.GetText() + "¢";

                File.AppendAllText(@"C:\temp\testfile.txt", text);
            }
        }
        //The following has no affect on the issue stated in my question I have tried with out it.
        string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");
        List<string> _responseTags2 = new List<string>(responseTags2);
        var count = _responseTags2.Count;
        // Perform a reverse tracking.
        for (var i = count - 1; i > -1; i--)
        {
            if (_responseTags2[i] == string.Empty) _responseTags2.RemoveAt(i);
        }
        // Keep only the unique list items.
        _responseTags2 = _responseTags2.Distinct().ToList();

        listBox1.BeginUpdate();
        listBox1.DataSource = _responseTags2;
        listBox1.EndUpdate();
    }
</code>```

input example:
"This is multiple lines in
a text file that is for testing
this application"

right output example (what I get when the same code is running at the start of the program before the form is loaded):
"This is multiple lines in
a text file that is for testing
this application" ,

"This is ANOTHER multiple lines in
a text file that is for testing
this application" ,

"This is a single line"

WRONG output (what I get when I run off the button click that eventual updates the UI):

"This is multiple lines in",
"a text file that is for testing",
"this application"

答:
What I ended up doing is the following;

```<code>string responseTags2 = checkForDupe.Replace('\n', '╜');
</code>```

I replaced new lines with a rarely used character, then split by ¢ to fill the list.

To replace the special character so that it would be formatted correctly again I just replaced it when setting the clipboard text with the \n again.

ContentLicense: CC BY-SA 3.0

Body:
For some reason when I read in clipboard data and write it to a file, read that file in and set it to a list after delineating it with ¢ it loads up my listbox just fine on the first load as in when my form first loads up. However I have the following trigger on a button click, it is for some reason splitting up multiple line sections into separate list items, which is not what I want and not what the same code does when the form first loads. It's a little frustrating as it's writing to the text file and everything the same way.

private void button2_Click_1(object sender, EventArgs e)
    {

        // until next comment this is the same as what I have run at the start of the
        // program, it loads up multiple lines into one list item as it should
        string checkForDupe = File.ReadAllText(@"C:\temp\testfile.txt");
        string checkResponses = File.ReadAllText(@"C:\temp\testfile2.txt");
        if (Clipboard.ContainsText() && !checkForDupe.Contains(Clipboard.GetText()))
        {
            if (!checkResponses.Contains(Clipboard.GetText()))
            {
                var text = "\n" + Clipboard.GetText() + "¢";

                File.AppendAllText(@"C:\temp\testfile.txt", text);
            }
        }
        //The following has no affect on the issue stated in my question I have tried with out it.
        string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");
        List<string> _responseTags2 = new List<string>(responseTags2);
        var count = _responseTags2.Count;
        // Perform a reverse tracking.
        for (var i = count - 1; i > -1; i--)
        {
            if (_responseTags2[i] == string.Empty) _responseTags2.RemoveAt(i);
        }
        // Keep only the unique list items.
        _responseTags2 = _responseTags2.Distinct().ToList();

        listBox1.BeginUpdate();
        listBox1.DataSource = _responseTags2;
        listBox1.EndUpdate();
    }

input example:
"This is multiple lines in
a text file that is for testing
this application"

right output example (what I get when the same code is running at the start of the program before the form is loaded):
"This is multiple lines in
a text file that is for testing
this application" ,

"This is ANOTHER multiple lines in
a text file that is for testing
this application" ,

"This is a single line"

WRONG output (what I get when I run off the button click that eventual updates the UI):

"This is multiple lines in",
"a text file that is for testing",
"this application"

Body:
What I ended up doing is the following;

string responseTags2 = checkForDupe.Replace('\n', '╜');

I replaced new lines with a rarely used character, then split by ¢ to fill the list.

To replace the special character so that it would be formatted correctly again I just replaced it when setting the clipboard text with the \n again.


问:
Push local Git repo to new remote including all branches and tags
I have a local Git repo that I would like to push to a new remote repo (brand new repo set up on Beanstalk, if that matters).

My local repo has a few branches and tags, and I would like to keep all of my history.

It looks like I basically just need to do a git push, but that only uploads the master branch.

How do I push everything so I get a full replica of my local repo on the remote?

答:
I found that none of these seemed to work properly for me. Feel free to flame this to death but for some reason couldn't get the other options to work properly.

Expected result was a repo "cloned" to another remote (ie from Github to another provider):

All branches are created on new remote

All branch history are created on new remote

(this was missed on every solution I tried)

All tags are created on new remote

Source moves over (a given)

Non-destructive (giving pause to the --mirror option)

The major issue I was seeing was either all remote branches didn't get recreated in the new remote. If a command did, the new remote did not have the branch history (ie doing a git checkout branch; git log wouldn't show the expected branch commits).

I noticed git checkout -b branchname is NOT the same as git checkout branchname (the latter being what I needed). I notice git checkout --track branchname didn't appear to pull the branch history.

My Solution (powershell based):

Function Git-FetchRemoteBranches {
$originalbranch = (git symbolic-ref HEAD).split("/")[-1]

Foreach ($entry in (git branch -r)) {

If ($entry -like "*->*") {
  $branch = $entry.split("->")[2].split("/")[1]
}
  else {$branch = $entry.split("/")[1]}

Write-Host "--Trying git checkout " -NoNewline
Write-Host "$branch" -Foreground Yellow

git checkout $branch

Remove-Variable branch -Force

""}

#Switch back to original branch, if needed
If ( ((git symbolic-ref HEAD).split("/")[-1]) -ne $originalbranch) {
"Switching back to original branch"
git checkout $originalbranch
Remove-Variable originalbranch -Force
}
}

git clone http://remoterepo
cd remoterepo
Git-FetchRemoteBranches
git remote add newremote
git push newremote --all
git push newremote --tags #Not sure if neeeded, but added for good measure
```

ContentLicense: CC BY-SA 4.0


问:
Sorting words according the alphabet
I need to make a program that can sort the words according the alphabet from a to z. the current program I made is capable of sorting the words but only if there on a new line ('\n').

The words that are further in the line are not sorted.

Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define SIZE 30
#define LEN 31

void bron (char *fnamer)
{
printf("\nGeef de naam van de in te lezen txt file: \n");
gets(fnamer);
//getchar(fnamer);
}

void uitgave (char *fnamer2)
{
printf("\nGeef de naam van de nieuwe geschreven txt file: \n");
gets(fnamer2);
//getchar(fnamer2);
}

int main()
{
char name[LEN][SIZE];
char hold[LEN] ;
int i,j ;
int last ;
FILE *fp;
FILE *fp2;

char ch;
char fnamer[1000];
char fnamer2[1000];

bron(fnamer);

fp=fopen(fnamer,"r");
if(fp==NULL)
{
    printf("Error!");
    exit(1);
}
uitgave(fnamer2);
fp2=fopen(fnamer2,"w");
if(fp2==NULL)
{
    printf("Error!");
    exit(1);
}
else
{

    for(i = 0 ; !feof(fp) ; i++ )

    {
        fgets( name[i] , LEN, fp);
    }
    last = i - 1 ;

    fclose(fp);

    for (i = last ; i > 0 ; i--)
        for (j = 1 ; j <= i ; j++)

            if (strcmp(name[j],name[j - 1]) < 0)
            {
                strcpy(hold,name[j]) ;
                strcpy(name[j],name[j - 1]) ;
                strcpy(name[j - 1],hold) ;
            }

    for (i = 0 ; i <= last ; i++)
    {
        printf("%s",name[i]) ;
       // fprintf("%s", name [i]); herzien
    }

}
printf("\n%s \t%s",fnamer,fnamer2) ;
//fprintf(fp, %s) ; // herzien
fclose(fp2);
return 0;
}
</code>```

What is the problem?

答: yes that is correct. But i cant find where it goes wrong. First of all. i can't manage the programe van writing the words to a textfile and second i have no idea how to give the program the wright code to look to all the words and not only the words on a new line.</p>

Title: Sorting words according the alphabet

Body:
I need to make a program that can sort the words according the alphabet from a to z. the current program I made is capable of sorting the words but only if there on a new line ('\n').

The words that are further in the line are not sorted.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define SIZE 30
#define LEN 31

void bron (char *fnamer)
{
printf("\nGeef de naam van de in te lezen txt file: \n");
gets(fnamer);
//getchar(fnamer);
}

void uitgave (char *fnamer2)
{
printf("\nGeef de naam van de nieuwe geschreven txt file: \n");
gets(fnamer2);
//getchar(fnamer2);
}

int main()
{
char name[LEN][SIZE];
char hold[LEN] ;
int i,j ;
int last ;
FILE *fp;
FILE *fp2;

char ch;
char fnamer[1000];
char fnamer2[1000];

bron(fnamer);

fp=fopen(fnamer,"r");
if(fp==NULL)
{
    printf("Error!");
    exit(1);
}
uitgave(fnamer2);
fp2=fopen(fnamer2,"w");
if(fp2==NULL)
{
    printf("Error!");
    exit(1);
}
else
{

    for(i = 0 ; !feof(fp) ; i++ )

    {
        fgets( name[i] , LEN, fp);
    }
    last = i - 1 ;

    fclose(fp);

    for (i = last ; i > 0 ; i--)
        for (j = 1 ; j <= i ; j++)

            if (strcmp(name[j],name[j - 1]) < 0)
            {
                strcpy(hold,name[j]) ;
                strcpy(name[j],name[j - 1]) ;
                strcpy(name[j - 1],hold) ;
            }

    for (i = 0 ; i <= last ; i++)
    {
        printf("%s",name[i]) ;
       // fprintf("%s", name [i]); herzien
    }

}
printf("\n%s \t%s",fnamer,fnamer2) ;
//fprintf(fp, %s) ; // herzien
fclose(fp2);
return 0;
}

What is the problem?


问:
Removing a bad commit pushed using git
I am working on a project using BitBucket. I have been able to commit/push all my code until one day my vendor was not ignored, not sure why.

In order to fix I had to un-track the vendor folder. Doing that caused my files in the repository being removed because it was not being tracked anymore.

Now every time I need to push something and do a git pull it deletes my entire vendor folder.

How can  I remove this commit and go back to a good commit?

Below is my git log showing the merges, etc. I would like to go back to this hash commit(e5835fa) which is my good commit before the "untrack vendor directory".

```<code>* 66ef40d (HEAD, origin/master, origin/HEAD, master) finalized importing players from excel.
* cfa37b3 pushing import players code
* 3a8f272 implemented importing players from excel.
* 9cf59ad implemented importing players
* 188db12 implemented imprting for players oly from excel file
* 72c086a untrack vendor directory
* e5835fa refactoring chart  display
* a5ffd72 fixed offset on duplicate players started import tool for players and  teams.
* 349dfc0 divided the result by 2
* 27e2845 updqted the sql duplicate teams.
* 80b3741 format change.
</code>```

答:
Rollback to the specified commit:

git reset --hard e5835fa

Move head:

git reset --soft HEAD@{1}

Commit this state:

git commit -m "Rollback to e5835fa"

Push the changes (if desired):

git push

Title: Removing a bad commit pushed using git

Body:
I am working on a project using BitBucket. I have been able to commit/push all my code until one day my vendor was not ignored, not sure why.

In order to fix I had to un-track the vendor folder. Doing that caused my files in the repository being removed because it was not being tracked anymore.

Now every time I need to push something and do a git pull it deletes my entire vendor folder.

How can  I remove this commit and go back to a good commit?

Below is my git log showing the merges, etc. I would like to go back to this hash commit(e5835fa) which is my good commit before the "untrack vendor directory".

* 66ef40d (HEAD, origin/master, origin/HEAD, master) finalized importing players from excel.
* cfa37b3 pushing import players code
* 3a8f272 implemented importing players from excel.
* 9cf59ad implemented importing players
* 188db12 implemented imprting for players oly from excel file
* 72c086a untrack vendor directory
* e5835fa refactoring chart  display
* a5ffd72 fixed offset on duplicate players started import tool for players and  teams.
* 349dfc0 divided the result by 2
* 27e2845 updqted the sql duplicate teams.
* 80b3741 format change.


问:
Simulating MySql 5.7 delete query
I am working on purging a huge database (~ 1TB data ) with over 10 million records using InnoDB engine. Whoever set up the database schema, set the foreign keys but did not set on delete cascade. I want to do a selective time based purge. Two parts to my question

Can I set "on delete cascade" without any side-effects ?

Can I simulate my delete to check for foreign key reference violation ? I know I can use START TRANSACTION and ROLLBACK

TRANSACTION, but it is not something I am looking for

答:
10 million records is tiny.

1TB is huge.

This points to the use of humongous BLOBs. Always a good idea to store huge BLOBs in the database: everyone knows the longer backups take, the better.

Now,

Can I set "on delete cascade" without any side-effects ?

Yeah, as long as you don't DELETE anything...

Can I simulate my delete to check for foreign key reference violation ? I know I can use START TRANSACTION and ROLLBACK
  TRANSACTION, but it is not something I am looking for

Yeah, but the ROLLBACK will probably take just as long as the operation you cancelled, if not more, and the best thing is... you can't interrupt it! You will sit in front of your terminal... and you have no idea when it will end!

Now, either it is "ON DELETE CASCADE" and it won't fail, it'll just keep deleting for a few days if you screw it up, or it's ON DELETE RESTRICT and it will fail on the first row it attempts to delete, and there will be nothing to roll back, so it will be fast. Both case don't "simulate" anything useful though.

Or it's ON DELETE SET NULL, and your database ends up screwed up.

Now, if you have huge BLOBs, and you want to mess around in your database, this is what I would suggest: make a copy of the database, but without the BLOBs. You know, CREATE TABLE LIKE... and then INSERT INTO SELECT. Just remove the huge BLOB column. Then you can mess around as you like and practice, check if your queries actually delete the right thing...

Note: if you delete like 90% of your database, consider creating new tables (with INSERT INTO SELECT only the rows you wanna keep) instead of DELETE. Because DELETE doesn't shrink the files.

About that: think about it first. If you copy what you want to keep in a new database, read the docs (I don't remember the details) but perhaps you need to make a tablespace or something, so later you can purge your old 1TB almost-empty ibdata file.

Title: Simulating MySql 5.7 delete query


问:
node.js noobie trying to follow a tutorial - need to change jade reference to pug
I'm trying to follow this tutorial to learn about node.js:

http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/

When I run "npm install" some of the messages I see include this:

```<code>npm WARN deprecated jade@1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm WARN deprecated transformers@2.1.0: Deprecated, use jstransformer
</code>```

And then it goes ahead and seems to set up the application anyways.
My package.json file currently looks like this:

```<code>{
  "name": "testapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "mongodb": "^1.4.4",
    "monk": "^1.0.1"
  }
}
</code>```

Questions:
(these questions apply to both packages that I got warned about, but for discussion purposes, I'm just going to pick on jade / pug)

If I wanted to change jade to pug, do i need to specify a version number in this package.json file?  Or can I just tell it to get latest somehow?
Also, do I need to blow away my folder structure and then rerun the npm install command?  Or can I just edit the package.json file and retry npm install?

Lastly, based on your experience, how critical is it for me to change from jade to pug if i'm just trying to learn how node works?  I'm tempted to just leave as is... but then again, if this app works, i know it's going to be rolled out into production..
so... i guess i should make the right decisions up front.

Thanks and sorry if my questions are really remedial.

答:
If you use jade/pug files with Node.js/Express, change the template engine of your app to:

```<code>app.set('view engine', 'pug')
</code>```

Also

```<code>npm install pug --save
</code>```

will install the latest version of pug@2.0.0-beta11 as of Mar 2017. This may require some changes in your old .jade files, for example you should simplify:

```<code>a(href="/#{link}")
</code>```

to

```<code>a(href=link)
</code>```

More about Breaking Changes #2305

Body:
I'm trying to follow this tutorial to learn about node.js:

http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/

When I run "npm install" some of the messages I see include this:

npm WARN deprecated jade@1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm WARN deprecated transformers@2.1.0: Deprecated, use jstransformer

And then it goes ahead and seems to set up the application anyways.
My package.json file currently looks like this:

{
  "name": "testapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "mongodb": "^1.4.4",
    "monk": "^1.0.1"
  }
}

Questions:
(these questions apply to both packages that I got warned about, but for discussion purposes, I'm just going to pick on jade / pug)

If I wanted to change jade to pug, do i need to specify a version number in this package.json file?  Or can I just tell it to get latest somehow?
Also, do I need to blow away my folder structure and then rerun the npm install command?  Or can I just edit the package.json file and retry npm install?

Lastly, based on your experience, how critical is it for me to change from jade to pug if i'm just trying to learn how node works?  I'm tempted to just leave as is... but then again, if this app works, i know it's going to be rolled out into production..
so... i guess i should make the right decisions up front.

Thanks and sorry if my questions are really remedial.

Body:
If you use jade/pug files with Node.js/Express, change the template engine of your app to:

app.set('view engine', 'pug')

Also

npm install pug --save

will install the latest version of pug@2.0.0-beta11 as of Mar 2017. This may require some changes in your old .jade files, for example you should simplify:

a(href="/#{link}")

to

a(href=link)

More about Breaking Changes #2305


问:
Certificate Authentication fails with SSL error in .Net only
I'm trying to communicate with an external website using mutual certificate authentication, but am receiving a "Could not establish secure channel for SSL/TLS with authority" exception.  I've narrowed it down to the following snippet (sensitive things removed):

```<code>void Example()
{
                string KeyIdentifier = "<MyKeyId>";

                X509Store store = new X509Store("My", StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, KeyIdentifier, true);
                X509Certificate2 certificate = certificates[0];

                HttpWebRequest r = (HttpWebRequest)HttpWebRequest.Create("https://www.example.org");
                r.ClientCertificates.Add( certificate);

                r.Accept = "text/xml";
                r.Method = WebRequestMethods.Http.Post;

                string result = null;
                using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream());
                    result = reader.ReadToEnd();
                }
}
</code>```

I've set up the certificates and such properly and this code finds them successfully, with certificate.HasPrivateKey=true, but fails.  SoapUI happily connects with TLS.  Chrome reports no certificate errors when I access the website. However, the above code always throws the exception.  I've tried all 3 TLS versions with no success.  Using ServicePointManager to skip server Cert validation makes no difference.

Strangely, if I specify SSL3

```<code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
</code>```

then the process completes successfully, but naturally I don't want to be using SSL3. The app is .Net 4.6 running on Server 2012.

答:
After several months and more digging on and off I ended up trying to make the connection using SSLStream, getting a different exception, and finding this answer: A call to SSPI failed, see inner exception - The Local Security Authority cannot be contacted

which advises you to add the following registry key:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangeAlgorithms\Diffie-Hellman] "ClientMinKeyBitLength"=dword:00000200

This switches the minimum key length for Diffie-Hellman to 512-bit.  This minimum value was raised in a Windows Update to 1024-bit to attempt to mitigate logjam attacks, so take care in setting this value as it is system wide and may open up attack vectors against your system.

Body:
I'm trying to communicate with an external website using mutual certificate authentication, but am receiving a "Could not establish secure channel for SSL/TLS with authority" exception.  I've narrowed it down to the following snippet (sensitive things removed):

void Example()
{
                string KeyIdentifier = "<MyKeyId>";

                X509Store store = new X509Store("My", StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, KeyIdentifier, true);
                X509Certificate2 certificate = certificates[0];

                HttpWebRequest r = (HttpWebRequest)HttpWebRequest.Create("https://www.example.org");
                r.ClientCertificates.Add( certificate);

                r.Accept = "text/xml";
                r.Method = WebRequestMethods.Http.Post;

                string result = null;
                using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
                {
                    StreamReader reader = new StreamReader(resp.GetResponseStream());
                    result = reader.ReadToEnd();
                }
}

I've set up the certificates and such properly and this code finds them successfully, with certificate.HasPrivateKey=true, but fails.  SoapUI happily connects with TLS.  Chrome reports no certificate errors when I access the website. However, the above code always throws the exception.  I've tried all 3 TLS versions with no success.  Using ServicePointManager to skip server Cert validation makes no difference.

Strangely, if I specify SSL3

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

then the process completes successfully, but naturally I don't want to be using SSL3. The app is .Net 4.6 running on Server 2012.


问:
ReactJS - cannot read property 'props' of undefined
I am practicing React native. When I compile the following program, I am getting Cannot read property 'props' of undefined error for Details.js. Kindly let me know as to what went wrong here.

Layout.js

```<code>import React, {Component} from 'react';
import Header from './Header';
import Details from './Details';

export default class Layout extends React.Component {
constructor(props){
  super(props);
    this.state = {
                     heading: "Welcome no-name guy!",
                     header: "I am your header",
                     footer: "I am your footer"
                 };
               }

render() {
   return (
           <div>
            <Header headerprop={this.state.header} />
            <Details detailprop={this.state.heading} />
          </div>
          );
         }
}
</code>```

Details.js

```<code>import React from 'react';

const Details = (detailprop) => {
 return (
  <div className="heading-style">{this.props.detailprop}</div>
 );
 };
Details.bind(this);
export default Details;
</code>```

Header.js

```<code>import React, {Component} from 'react';

export default class Header extends React.Component {
 render(){
           return(
                   <div>{this.props.headerprop}</div>
                 );
          }
 }
</code>```

答:
Your component argument should be props:

```<code>const Details = (props) => {
 return (
  <div className="heading-style">{props.detailprop}</div>
 );
 };
</code>```

It could be detailprop as you have (or anything for that matter) but you would then need to access the prop by the confusing call:

```<code>detailprop.detailprop
</code>```

props is the idiomatic approach for React.

Body:
I am practicing React native. When I compile the following program, I am getting Cannot read property 'props' of undefined error for Details.js. Kindly let me know as to what went wrong here.

Layout.js

import React, {Component} from 'react';
import Header from './Header';
import Details from './Details';

export default class Layout extends React.Component {
constructor(props){
  super(props);
    this.state = {
                     heading: "Welcome no-name guy!",
                     header: "I am your header",
                     footer: "I am your footer"
                 };
               }

render() {
   return (

          );
         }
}

Details.js

import React from 'react';

const Details = (detailprop) => {
 return (

{this.props.detailprop}

 );
 };
Details.bind(this);
export default Details;

Header.js

import React, {Component} from 'react';

export default class Header extends React.Component {
 render(){
           return(

{this.props.headerprop}

                 );
          }
 }

Body:
Your component argument should be props:

const Details = (props) => {
 return (
  <div className="heading-style">{props.detailprop}</div>
 );
 };

It could be detailprop as you have (or anything for that matter) but you would then need to access the prop by the confusing call:

detailprop.detailprop

props is the idiomatic approach for React.


问:
What is it Called When You Debug the Non-IIS Express Version of ASP.Net Core?
In ASP.Net core, there are two ways of running/debugging the app, IIS Express and ________?

I don't think it is proper to call the other way Kestrel b/c that is running in the IIS Express version, isn't it?

When I pick the green underlined option, what is that called?

Is dotnet hosting Kestrel then?

答:
As @Tratcher says: ConsoleHost would be a good term. Since your application is run with a shell around it which is called the console on windows. Which is the Host of your dotnet application.

If you want to be as appropriate as possible towards the red line IIS express which would be the host of the dotnet app, then Console would be the most appropriate, since its the host of the application.

Although in more OS independent terms its either called the shell or the terminal (console is a very windows term). But since visual studio only currently runs on windows that should be fine.


问:
Does pig support load with no delimiter?
I'd like to load a lot of small files from HDFS with Pig and process them as tuples (filename, filecontent).

```<code>a=LOAD 'mydir' USING PigStorage('','-tagPath') AS (filepath:chararray, filecontents:chararray);
</code>```

However it seems like I cannot omit specifying the delimiter. Is there some sort of a "NULL" in Pig or is there any other way to make sure the content of the file will not be split?

答:
You will have to write your own custom loader by extending LoadFunc.

Short answer to your question is no.In order to make sure the content is not split,use a delimiter that would not exist in the content.In that way, the whole content would be loaded to the field filecontents:chararray.So assuming,your input files do not have a special character '~'

```<code>a=LOAD 'mydir' USING PigStorage('~','-tagPath') AS (filepath:chararray, filecontents:chararray);
</code>```

Body:
I'd like to load a lot of small files from HDFS with Pig and process them as tuples (filename, filecontent).

a=LOAD 'mydir' USING PigStorage('','-tagPath') AS (filepath:chararray, filecontents:chararray);

However it seems like I cannot omit specifying the delimiter. Is there some sort of a "NULL" in Pig or is there any other way to make sure the content of the file will not be split?

Body:
You will have to write your own custom loader by extending LoadFunc.

Short answer to your question is no.In order to make sure the content is not split,use a delimiter that would not exist in the content.In that way, the whole content would be loaded to the field filecontents:chararray.So assuming,your input files do not have a special character '~'

a=LOAD 'mydir' USING PigStorage('~','-tagPath') AS (filepath:chararray, filecontents:chararray);


问:
Python pandas series: convert float to string, preserving nulls
How can I preserve nulls after converting to string? I'm working with social security numbers, where it's necessary to go back and forth between float and string.

```<code>import pandas as pd
import numpy as np
x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull()
</code>```

...Has nulls

```<code>y = x.astype(str)
y.isnull()
</code>```

...No nulls

So ideally x.isnull() and y.isnull() would be the same.

I think it's dangerous to use a Series of mixed dtypes, but thinking this is the best solution for the time being:

```<code>z = y.copy()
z[z == 'nan'] = np.nan
z.isnull() # works as desired
type(z[0]) # but has floats for nulls
type(z[1]) # and strings for values
</code>```

答:
If you convert np.nan to str, it becomes the string 'nan' which will be treated by isnull like every other string.

Regarding your edit: After converting to str values, you need to define, what strings are "null" in your opinion. One way to do so might be:

```<code>y.isin(['nan', '0', '']) # list contains whatever you want to be evaluated as null
</code>```

This would at least give you the desired result.

Body:
How can I preserve nulls after converting to string? I'm working with social security numbers, where it's necessary to go back and forth between float and string.

import pandas as pd
import numpy as np
x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull()

...Has nulls

y = x.astype(str)
y.isnull()

...No nulls

So ideally x.isnull() and y.isnull() would be the same.

I think it's dangerous to use a Series of mixed dtypes, but thinking this is the best solution for the time being:

z = y.copy()
z[z == 'nan'] = np.nan
z.isnull() # works as desired
type(z[0]) # but has floats for nulls
type(z[1]) # and strings for values

Body:
If you convert np.nan to str, it becomes the string 'nan' which will be treated by isnull like every other string.

Regarding your edit: After converting to str values, you need to define, what strings are "null" in your opinion. One way to do so might be:

y.isin(['nan', '0', '']) # list contains whatever you want to be evaluated as null

This would at least give you the desired result.


问:
Sequelize.js: Query for not in array ($ne for items in array)
I am looking to pull items from a postgres data base with Sequelize, but only return items that have an id that does not equal any items in a given array.

In the Sequelize documentation, there are operators $ne for not equal and $in for returning items that have properties with values that match the given array, but it doesn't look like there is an operator for something that combines those two.

For example, if I were to have items in my database with ids [1, 2, 3, 4, 5, 6], and I wanted to filter those by comparing to another array (ie [2,3,4]), so that it would return items [1, 5, 6]. In my example i also randomize the return order and limit, but that can be disregarded.

```<code>function quizQuestions(req, res) {
  const query = {
    limit: 10,
    order: [ [sequelize.fn('RANDOM')] ],
    where: {
      id: { $ne: [1, 2, 3] } // This does not work
    }
  };

  Question.findAll(query)
  .then(results => res.status(200).json(map(results, r => r.dataValues)))
  .catch(err => res.status(500).json(err));
}
</code>```

Edit: With @piotrbienias answer, my query looks like this:

```<code>  const query = {
    limit: 10,
    order: [ [sequelize.fn('RANDOM')] ],
    where: {
      id: { $notIn: [1, 2, 3] }
    }
  };
</code>```

答:
There exists $notIn, you must have missed it. Exemplary query with $notIn generates

SELECT "id", "name"
FROM "categories" AS "Category"
WHERE "Category"."id" NOT IN (1, 2);
```

EDIT

The documentation you refer to is for 2.0 version of Sequelize, you should update to 3.0.

Body:
I am looking to pull items from a postgres data base with Sequelize, but only return items that have an id that does not equal any items in a given array.

In the Sequelize documentation, there are operators $ne for not equal and $in for returning items that have properties with values that match the given array, but it doesn't look like there is an operator for something that combines those two.

For example, if I were to have items in my database with ids [1, 2, 3, 4, 5, 6], and I wanted to filter those by comparing to another array (ie [2,3,4]), so that it would return items [1, 5, 6]. In my example i also randomize the return order and limit, but that can be disregarded.

function quizQuestions(req, res) {
  const query = {
    limit: 10,
    order: [ [sequelize.fn('RANDOM')] ],
    where: {
      id: { $ne: [1, 2, 3] } // This does not work
    }
  };

  Question.findAll(query)
  .then(results => res.status(200).json(map(results, r => r.dataValues)))
  .catch(err => res.status(500).json(err));
}

Edit: With @piotrbienias answer, my query looks like this:

  const query = {
    limit: 10,
    order: [ [sequelize.fn('RANDOM')] ],
    where: {
      id: { $notIn: [1, 2, 3] }
    }
  };

Body:
There exists $notIn, you must have missed it. Exemplary query with $notIn generates

SELECT "id", "name"
FROM "categories" AS "Category"
WHERE "Category"."id" NOT IN (1, 2);

EDIT

The documentation you refer to is for 2.0 version of Sequelize, you should update to 3.0.


问:
Email action google-schema markup doesn't work
I'm sending markups copied from google developers reference (also from here). They don't work at all, even when I email to myself.

I also tested sending html email with google doc

答:
@Alireza Mirian It sounds like you're copying the JSON and pasting it into your email message in the Gmail UI.

Try using this tool  with your Gmail account.

You can also try using App Script and follow along with this tutorial.

I hope this helps.


问:
SmartAdmin DataTable Button Column
Regards, I have a problem I am using the SmartAdmin DataTable and I need to put three buttons in a column to edit, view and delete an element I have already put the buttons in a Column, but until now I have not been able to make them respond to the even to click.

Thank you.

enter image description here
This is the code I have in my ngOnInit

```<code>this.options = {
          dom: "Bfrtip",
          ajax: (data, callback, settings) => {
              this._usuarioService.readUsuarios()
                  .subscribe((data) => {
                          callback({
                              aaData: data
                          })
                  })
          },
          columns: [
              { data: 'id' },
              { data: 'persona.nombre' },
              { data: 'persona.apellido' },
              { data: 'persona.correo' },
              { data: 'rol.nombre' },
              { data: 'persona.sede.nombre' },
              {defaultContent: '<center><button class=\'btn btn-success btn-xs\'(click)=\'leerUnUsuario(id)\'> Ver </button> ' +
                               '<button class=\'btn btn-info btn-xs\' (click)=\'actualizarUsuario(id)\'> Editar </button> ' +
                               '<button class=\'btn btn-danger btn-xs\' (click)=\'eliminarUsuario(id)\'> Borrar </button></center>' },
          ]
      };
</code>```

答:
Already solved, I received help from Alain D'EURVEILHER and everything is already very well.</p>

```<code>    ngOnInit() {
          this.options = {
              dom: "Bfrtip",
              ajax: (data, callback, settings) => {
                  this._usuarioService.readUsuarios()
                      .subscribe((data) => {
                              callback({
                                  aaData: data
                              })
                      })
              },
              columns: [
                  { data: 'id' },
                  { data: 'persona.nombre' },
                  { data: 'persona.apellido' },
                  { data: 'persona.correo' },
                  { data: 'rol.nombre' },
                  { data: 'persona.sede.nombre' },
                  {
                      render: (data, type, fullRow, meta) => {
                          return `
                              <button class="btn btn-xs btn-success accion-ver-usuario" data-usuario-id="${fullRow.id}">ver</button>
                              <button class="btn btn-xs btn-info accion-editar-usuario" data-usuario-id="${fullRow.id}">editar</button>
                              <button class="btn btn-xs btn-danger accion-borrar-usuario" data-usuario-id="${fullRow.id}">borrar</button>
                          `;
                      }
                  }
              ]
          };

ngAfterViewInit(){
        document.querySelector('body').addEventListener('click', (event)=> {
            let target = <Element>event.target;// Cast EventTarget into an Element
            if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('accion-ver-usuario')) {
                this.verUsuario(target.getAttribute('data-usuario-id'));
            }
            if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('accion-editar-usuario')) {
                this.editarUsuario(target.getAttribute('data-usuario-id'));
            }
            if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('accion-borrar-usuario')) {
                this.borrarUsuario(target.getAttribute('data-usuario-id'));
            }
        });
    }

verUsuario(userId){
        console.log("user displayed:", userId);
    }

    editarUsuario(userId){
        console.log("user edited:", userId);
    }

    borrarUsuario(userId){
        console.log("Delete user", userId, "?");
    }
</code>```

Title: SmartAdmin DataTable Button Column

Body:
Regards, I have a problem I am using the SmartAdmin DataTable and I need to put three buttons in a column to edit, view and delete an element I have already put the buttons in a Column, but until now I have not been able to make them respond to the even to click.

Thank you.

enter image description here
This is the code I have in my ngOnInit

this.options = {
          dom: "Bfrtip",
          ajax: (data, callback, settings) => {
              this._usuarioService.readUsuarios()
                  .subscribe((data) => {
                          callback({
                              aaData: data
                          })
                  })
          },
          columns: [
              { data: 'id' },
              { data: 'persona.nombre' },
              { data: 'persona.apellido' },
              { data: 'persona.correo' },
              { data: 'rol.nombre' },
              { data: 'persona.sede.nombre' },
              {defaultContent: '<button class=\'btn btn-success btn-xs\'(click)=\'leerUnUsuario(id)\'> Ver </button> ' +
                               '<button class=\'btn btn-info btn-xs\' (click)=\'actualizarUsuario(id)\'> Editar </button> ' +
                               '<button class=\'btn btn-danger btn-xs\' (click)=\'eliminarUsuario(id)\'> Borrar </button>' },
          ]
      };

Body:
Already solved, I received help from Alain D'EURVEILHER and everything is already very well.

    ngOnInit() {
          this.options = {
              dom: "Bfrtip",
              ajax: (data, callback, settings) => {
                  this._usuarioService.readUsuarios()
                      .subscribe((data) => {
                              callback({
                                  aaData: data
                              })
                      })
              },
              columns: [
                  { data: 'id' },
                  { data: 'persona.nombre' },
                  { data: 'persona.apellido' },
                  { data: 'persona.correo' },
                  { data: 'rol.nombre' },
                  { data: 'persona.sede.nombre' },
                  {
                      render: (data, type, fullRow, meta) => {
                          return `
                              <button class="btn btn-xs btn-success accion-ver-usuario" data-usuario-id="${fullRow.id}">ver</button>
                              <button class="btn btn-xs btn-info accion-editar-usuario" data-usuario-id="${fullRow.id}">editar</button>
                              <button class="btn btn-xs btn-danger accion-borrar-usuario" data-usuario-id="${fullRow.id}">borrar</button>
                          `;
                      }
                  }
              ]
          };

ngAfterViewInit(){
        document.querySelector('body').addEventListener('click', (event)=> {
            let target = <Element>event.target;// Cast EventTarget into an Element
            if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('accion-ver-usuario')) {
                this.verUsuario(target.getAttribute('data-usuario-id'));
            }
            if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('accion-editar-usuario')) {
                this.editarUsuario(target.getAttribute('data-usuario-id'));
            }
            if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('accion-borrar-usuario')) {
                this.borrarUsuario(target.getAttribute('data-usuario-id'));
            }
        });
    }

verUsuario(userId){
        console.log("user displayed:", userId);
    }

    editarUsuario(userId){
        console.log("user edited:", userId);
    }

    borrarUsuario(userId){
        console.log("Delete user", userId, "?");
    }


问:
Printing odd numbers
I would like help to find a short and small program in C++ to print out all odd number from 1 to 100 using a loop. Is that possible?</p>

答:
you can just do -</p>

```<code>for(int i = 1; i < 100; i = i + 2)
{
   std::cout << i << std::endl;
}
</code>```

OwnerDisplayName: BE Student

ContentLicense: CC BY-SA 2.5

Title: Printing odd numbers

Body:
you can just do -

for(int i = 1; i < 100; i = i + 2)
{
   std::cout << i << std::endl;
}


问:
Finding the max value in an array, however being less than the first number in the array
I need to find out how to find the max value in an array, being less than the first index of the array. So far, I have only found out how to find the maximum value in my array (shown below), but I need help only returning the max value less than the first number in my array from my method.

```<code>public static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {

if (endIndex == startIndex) {

    return numbers[endIndex];

}

else {

    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);   //Calling method using recursion.

    if (max < numbers[endIndex]) {

        return numbers[endIndex];

    }

    else {

        return max;

    }

}
</code>```

}

答:
Change the condition:

```<code>if (max < numbers[endIndex]) {
</code>```

To:

```<code>if (max < numbers[endIndex] && numbers[endIndex] < firstNumber) {
</code>```

Body:
I need to find out how to find the max value in an array, being less than the first index of the array. So far, I have only found out how to find the maximum value in my array (shown below), but I need help only returning the max value less than the first number in my array from my method.

public static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {

if (endIndex == startIndex) {

    return numbers[endIndex];

}

else {

    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);   //Calling method using recursion.

    if (max < numbers[endIndex]) {

        return numbers[endIndex];

    }

    else {

        return max;

    }

}

}

Body:
Change the condition:

if (max < numbers[endIndex]) {

To:

if (max < numbers[endIndex] && numbers[endIndex] < firstNumber) {


问:
Flex Layout: can width be 100% of the *visible* area of a larger container
I've got the following situation, where I have an outer Vbox that is set at a fixed width, and then inside it there is a header made from an HBox and a content area (Canvas) that is much wider than the enclosing VBox (and therefore requires scrollbars on the outer VBox to see it all).

I would like to set the width of the header to fill the entire width of the outer container, but only the visible part, and to remain fixed so that when I scroll to view the content, the header doesn't move.

Can anyone tell me how I can acomplish this please

```<code>    ______________________________
   |  _________________________   |
   | |_________________________|  |
   |                     |
   |  ____________________________|_ _ _ _ _
   | |                            |         |
   | |                            |         |
   | |                            |         |
   | |                            |         |
   |  ---------------------------------------
   |                              |
   |______________________________|
   |<|__________________________|>|
</code>```

答: Create a VBox with 1) a header at the top, and 2) a VBox underneath the header with your canvas inside that. The other answer will also work. And those graphics help a lot, good man. </p>

Body:
I've got the following situation, where I have an outer Vbox that is set at a fixed width, and then inside it there is a header made from an HBox and a content area (Canvas) that is much wider than the enclosing VBox (and therefore requires scrollbars on the outer VBox to see it all).

I would like to set the width of the header to fill the entire width of the outer container, but only the visible part, and to remain fixed so that when I scroll to view the content, the header doesn't move.

Can anyone tell me how I can acomplish this please

    ______________________________
   |  _________________________   |
   | |_________________________|  |
   |                     |
   |  ____________________________|_ _ _ _ _
   | |                            |         |
   | |                            |         |
   | |                            |         |
   | |                            |         |
   |  ---------------------------------------
   |                              |
   |______________________________|
   |<|__________________________|>|


问:
Displaying all connected users Discord.js
I'm trying to create a timer that polls all connected users with discord.js.

My current code is...

```<code>Bot.on('ready', () => {
    setInterval (function (){
        var u = Bot.users();
        console.log(u);
    }, 10000);
});
</code>```

However, it doesn't work with a error "TypeError: Bot.users is not a function".

I'm just not sure how this works. I've also tried...

```<code>Bot.server.users();
Bot.guilds.users();
</code>```

答:
Looking at https://discord.js.org/#/docs/main/master/class/Client?scrollTo=users, users is an associative array, not a function. Try:

```<code>Bot.on('ready', () => {
    setInterval (function (){
        var u, user;
        for(u in Bot.users){
           user = Bot.users[u];
           if(user instanceof Discord.User) console.log("["+u+"] "+user.username);
        }
    }, 10000);
});
</code>```

EDIT: should now print out username and user id.

Body:
I'm trying to create a timer that polls all connected users with discord.js.

My current code is...

Bot.on('ready', () => {
    setInterval (function (){
        var u = Bot.users();
        console.log(u);
    }, 10000);
});

However, it doesn't work with a error "TypeError: Bot.users is not a function".

I'm just not sure how this works. I've also tried...

Bot.server.users();
Bot.guilds.users();

Body:
Looking at https://discord.js.org/#/docs/main/master/class/Client?scrollTo=users, users is an associative array, not a function. Try:

Bot.on('ready', () => {
    setInterval (function (){
        var u, user;
        for(u in Bot.users){
           user = Bot.users[u];
           if(user instanceof Discord.User) console.log("["+u+"] "+user.username);
        }
    }, 10000);
});

EDIT: should now print out username and user id.


问:
Spring MVC @Controller to intercept own requests
Imagine we have a controller like this:

```<code>@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}
</code>```

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

答:
While HandlerInterceptorAdapter appears to be the "correct" solution,
it does not appear to be the solution you want.

The code below might be the solution you want
(or at least the one you asked for in your question).

Summary: write your own preBlam and postBlam methods.

Some code:

```<code>@RestController
@RequestMapping("/{parameter}")
public class MyController
{

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException()
    {
    /* handle */
    }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter)
    {
        preBlam(desired params here);

        /* handle */

        postBlam(desired params here);
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter)
    {
        preBlam(desired params here);

        /* handle */

        postBlam(desired params here);
    }

    private blam preBlam(parameters)
    {
    // do initial blamish work
    }

    private blam postBlam(parameters)
    {
    // do post blamish work here
    }
}
</code>```

Another option:
Use AOP to set pre and post handlers for the impacted methods.
I'm not a big AOP user, so I can't just rattle off an example.

Body:
Imagine we have a controller like this:

@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

Body:
While HandlerInterceptorAdapter appears to be the "correct" solution,
it does not appear to be the solution you want.

The code below might be the solution you want
(or at least the one you asked for in your question).

Summary: write your own preBlam and postBlam methods.

Some code:

@RestController
@RequestMapping("/{parameter}")
public class MyController
{

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException()
    {
    /* handle */
    }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter)
    {
        preBlam(desired params here);

        /* handle */

        postBlam(desired params here);
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter)
    {
        preBlam(desired params here);

        /* handle */

        postBlam(desired params here);
    }

    private blam preBlam(parameters)
    {
    // do initial blamish work
    }

    private blam postBlam(parameters)
    {
    // do post blamish work here
    }
}

Another option:
Use AOP to set pre and post handlers for the impacted methods.
I'm not a big AOP user, so I can't just rattle off an example.


问:
Serializing Object to Json
I am attempting to use Gson to to take some Java Object and serialize that to json and get a byte array that represents that Json. I need a byte array because I am passing on the output to an external dependency that requires it to be a byte array.

```<code>public byte[] serialize(Object object){
  return gson.toJson(object).getBytes();
}
</code>```

I have 2 questions:

If the input is a String gson seems to return the String as is. It doesn't do any validation of the input. Is this expected? I'd like to use Gson in a way that it would validate that the input object is actually Json. How could I do this?

I'm gonna be invoking this serialize function several thousands of times over a short period. Converting to String and then to byte[] could be some unwanted overhead. Is there a more optimal way to get the byte[]?

答:
If the input is a String gson seems to return the String as is. It doesn't do any validation of the input. Is this expected?

Yes, this is fine. It just returns a JSON string representation of the given string.

I'd like to use Gson in a way that it would validate that the input object is actually Json. How could I do this?

No need per se. Gson.toJson() method accepts objects to be serialized and it generates valid JSON always. If you mean deserialization, then Gson makes fast fails on invalid JSON documents during reading/parsing/deserialization (actually reading, this is the bottom-most layer of Gson).

I'm gonna be invoking this serialize function several thousands of times over a short period. Converting to String and then to byte[] could be some unwanted overhead. Is there a more optimal way to get the byte[]?

Yes, accumulating a JSON string to in order just to expose its internal char[] clone is memory waste, of course. Gson is basically a stream-oriented tool, and note that there are Gson.toJson method overloads accepting Appendable that are basically the Gson core (just take a quick look on how Gson.fromJson(Object) works -- it just creates a StringWriter instance to accumulate a string because of the Appendable interface). It would be extremely cool if Gson could emit JSON tokens via a Reader rather than writing to an Appendable, but this idea was refused and most likely will never be implemented in Gson, unfortunately. Since Gson does not emit JSON tokens during deserialization in read semantics manner (from your code perspective), you have to buffer the whole result:

private static byte[] serializeToBytes(final Object object)
        throws IOException {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    gson.toJson(object, writer);
    writer.flush();
    return outputStream.toByteArray();
}
```

<p>This one does not use <code>StringWriter</code> thus not accumulating an intermediate string with cloned arrays ping-pong. I don't know if there are writers/output streams that can utilize/re-use existing byte arrays, but I believe there should be some, because it makes a good rationale for the performance purposes you mentioned in your question.</p>

<p>If possible, you can also check your library interface/API for exposing/accepting <code>OutputStream</code>s somehow -- then you could probably easily pass such output streams to the <code>serializeToBytes</code> method or even remove the method. If it can use input streams, not just byte arrays, you could also take a look at converting output streams to input streams so the <code>serializeToBytes</code> method could return an <code>InputStream</code> or a <code>Reader</code> (requires some overhead, but can process infinite data -- need to find the balance):</p>

<pre class="lang-java prettyprint-override"><code>private static InputStream serializeToByteStream(final Object object)
        throws IOException {
    final PipedInputStream inputStream = new PipedInputStream();
    final OutputStream outputStream = new PipedOutputStream(inputStream);
    new Thread(() -> {
        try {
            final OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            gson.toJson(object, writer);
            writer.flush();
        } catch ( final IOException ex ) {
            throw new RuntimeException(ex);
        } finally {
            try {
                outputStream.close();
            } catch ( final IOException ex ) {
                throw new RuntimeException(ex);
            }
        }
    }).start();
    return inputStream;
}
</code>```

Example of use:

final String value = "foo";
System.out.println(Arrays.toString(serializeToBytes(value)));
try ( final InputStream inputStream = serializeToByteStream(value) ) {
    int b;
    while ( (b = inputStream.read()) != -1 ) {
        System.out.print(b);
        System.out.print(' ');
    }
    System.out.println();
}
```

Output:

[34, 102, 111, 111, 34]

  34 102 111 111 34

Both represent an array of ASCII codes representing a string "foo" literally.

Title: Serializing Object to Json

Body:
I am attempting to use Gson to to take some Java Object and serialize that to json and get a byte array that represents that Json. I need a byte array because I am passing on the output to an external dependency that requires it to be a byte array.

public byte[] serialize(Object object){
  return gson.toJson(object).getBytes();
}

I have 2 questions:

If the input is a String gson seems to return the String as is. It doesn't do any validation of the input. Is this expected? I'd like to use Gson in a way that it would validate that the input object is actually Json. How could I do this?

I'm gonna be invoking this serialize function several thousands of times over a short period. Converting to String and then to byte[] could be some unwanted overhead. Is there a more optimal way to get the byte[]?

Body:
If the input is a String gson seems to return the String as is. It doesn't do any validation of the input. Is this expected?

Yes, this is fine. It just returns a JSON string representation of the given string.

I'd like to use Gson in a way that it would validate that the input object is actually Json. How could I do this?

No need per se. Gson.toJson() method accepts objects to be serialized and it generates valid JSON always. If you mean deserialization, then Gson makes fast fails on invalid JSON documents during reading/parsing/deserialization (actually reading, this is the bottom-most layer of Gson).

I'm gonna be invoking this serialize function several thousands of times over a short period. Converting to String and then to byte[] could be some unwanted overhead. Is there a more optimal way to get the byte[]?

Yes, accumulating a JSON string to in order just to expose its internal char[] clone is memory waste, of course. Gson is basically a stream-oriented tool, and note that there are Gson.toJson method overloads accepting Appendable that are basically the Gson core (just take a quick look on how Gson.fromJson(Object) works -- it just creates a StringWriter instance to accumulate a string because of the Appendable interface). It would be extremely cool if Gson could emit JSON tokens via a Reader rather than writing to an Appendable, but this idea was refused and most likely will never be implemented in Gson, unfortunately. Since Gson does not emit JSON tokens during deserialization in read semantics manner (from your code perspective), you have to buffer the whole result:

private static byte[] serializeToBytes(final Object object)
        throws IOException {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    gson.toJson(object, writer);
    writer.flush();
    return outputStream.toByteArray();
}

This one does not use StringWriter thus not accumulating an intermediate string with cloned arrays ping-pong. I don't know if there are writers/output streams that can utilize/re-use existing byte arrays, but I believe there should be some, because it makes a good rationale for the performance purposes you mentioned in your question.

If possible, you can also check your library interface/API for exposing/accepting OutputStreams somehow -- then you could probably easily pass such output streams to the serializeToBytes method or even remove the method. If it can use input streams, not just byte arrays, you could also take a look at converting output streams to input streams so the serializeToBytes method could return an InputStream or a Reader (requires some overhead, but can process infinite data -- need to find the balance):

private static InputStream serializeToByteStream(final Object object)
        throws IOException {
    final PipedInputStream inputStream = new PipedInputStream();
    final OutputStream outputStream = new PipedOutputStream(inputStream);
    new Thread(() -> {
        try {
            final OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            gson.toJson(object, writer);
            writer.flush();
        } catch ( final IOException ex ) {
            throw new RuntimeException(ex);
        } finally {
            try {
                outputStream.close();
            } catch ( final IOException ex ) {
                throw new RuntimeException(ex);
            }
        }
    }).start();
    return inputStream;
}

Example of use:

final String value = "foo";
System.out.println(Arrays.toString(serializeToBytes(value)));
try ( final InputStream inputStream = serializeToByteStream(value) ) {
    int b;
    while ( (b = inputStream.read()) != -1 ) {
        System.out.print(b);
        System.out.print(' ');
    }
    System.out.println();
}

Output:

[34, 102, 111, 111, 34]

  34 102 111 111 34

Both represent an array of ASCII codes representing a string "foo" literally.


问:
How can I merge two object arrays by index in JavaScript?
What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

```<code>var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]
</code>```

Desired output would be:

```<code>var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]
</code>```

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.

答:
I think you are looking for matrix transposition, where the 2d array passed is [array1, array2].

Edit: It looks like this operation can also be called "zipping" when only two arrays are used. Matrix transposition can support any number of rows, not just two.

var array1 = [
  [1, 2, 3, 4],
  [4, 5, 6, 7]
]
var array2 = [
  ['a', 'b', 'c', 'd'],
  ['e', 'f', 'g', 'h']
]

function transpose(matrix) {
  return matrix.map(function(_, i) {
    return matrix.map(function(e) {
      return e[i]
    })
  })
}

var result = transpose([array1, array2])

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%; }</code>```

If you really want to have nested objects with properties array1 and array2 instead of arrays, the following solution should also work (a variation of this answer):

var array1 = [
  [1, 2, 3, 4],
  [4, 5, 6, 7]
]
var array2 = [
  ['a', 'b', 'c', 'd'],
  ['e', 'f', 'g', 'h']
]

var result = array1.map(function (e1, i) {
  return { array1: e1, array2: array2[i] }
})

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%; }</code>```

Body:
What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]

Desired output would be:

var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.

Body:
I think you are looking for matrix transposition, where the 2d array passed is [array1, array2].

Edit: It looks like this operation can also be called "zipping" when only two arrays are used. Matrix transposition can support any number of rows, not just two.

var array1 = [
  [1, 2, 3, 4],
  [4, 5, 6, 7]
]
var array2 = [
  ['a', 'b', 'c', 'd'],
  ['e', 'f', 'g', 'h']
]

function transpose(matrix) {
  return matrix.map(function(_, i) {
    return matrix.map(function(e) {
      return e[i]
    })
  })
}

var result = transpose([array1, array2])

console.log(result)

.as-console-wrapper { min-height: 100%; }

If you really want to have nested objects with properties array1 and array2 instead of arrays, the following solution should also work (a variation of this answer):

var array1 = [
  [1, 2, 3, 4],
  [4, 5, 6, 7]
]
var array2 = [
  ['a', 'b', 'c', 'd'],
  ['e', 'f', 'g', 'h']
]

var result = array1.map(function (e1, i) {
  return { array1: e1, array2: array2[i] }
})

console.log(result)

.as-console-wrapper { min-height: 100%; }


问:
Use AppleScript to change System Preferences > App Badges
I'm trying to use AppleScript to control System Preferences in the background. Specifically, I am trying to Enable / Disable "Badge app icons" for each app. There is no global way to enable / disable badge app icons in system preferences. This must be done per app.

Any idea how this might be done?

答:
Your question is broad, but here are some pointers:

While System Preferences.app can be controlled from an AppleScript, support is limited to revealing (opening) the application to a specific pane and anchor (tab).

Your best bet is to modify the underlying SQLite 3 database in which the per-application notification preferences are maintained - this answer will hopefully get you started.

macOS comes with the sqlite3 CLI.

From what I understand, while AppleScript has - limited - support for accessing SQLite databases via the Database Events app, using do shell script to call the sqlite3 utility may be the better option.

(In fact, in a brief test I wasn't even able to open a database in AppleScript on my macOS 10.12.4 machine)


Title: Printing odd numbers

Body: I would like help to find a short and small program in C++ to print out all odd number from 1 to 100 using a loop. Is that possible?

Body: for(int i = 1; i < 100; i+=2 ) std::cout << i << std::endl;


问:
Web application background image not appearing
I'm trying to add a background image to one of the html pages in my spring-boot application.
  When the application is launched the background is not loaded or any other image.

This is my html code

```<code><!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<style>
body {margin:0;}

.icon-bar {
   width: 100%;
   background-color: #555;
   overflow: auto;
 }

.icon-bar a {
   float: left;
   width: 25%;
   text-align: center;
   padding: 12px 0;
   transition: all 0.3s ease;
   color: white;
   font-size: 36px;
 }

.icon-bar a:hover {
   background-color: #300;
 }

.active {
   background-color: #4CAF50 !important;
 }
.button {
   padding: 15px 65px;
   font-size: 36px;
   text-align: center;
   cursor: pointer;
   outline: none;
   color: #fff;
   background-color: #4CAF50;
   border: none;
   border-radius: 12px;
   box-shadow: 0 9px #999;
   position:absolute;
   transition: .5s ease;
   top: 65%;
   left: 42%;
}

.button:hover {background-color: #3e8e41}

.button:active {
     background-color: #3e8e41;
     box-shadow: 0 5px #666;
     transform: translateY(4px);
   }

h2 {
      position: absolute;
      top: 57%;
      left: 46%;
   }

h3 {
     position: absolute;
     top: 75%;
     left: 43%;
   }
</style>
</head>

<body background = "page.jpg">

<div class="icon-bar">
<a class="active" href="#"><i class="fa fa-home"></i></a>
<a href="#"><i class="fa fa-search"></i></a>
<a href="#"><i class="fa fa-envelope"></i></a>
<a href="#"><i class="fa fa-globe"></i></a>
</div>
<p th:text="${msg}"></p>
<h2>join us </h2>
<form action="/Register" method="get">
 <button class="button" formaction="Register.html" >Sign up </button>
</form>
<h3> already have account ? <a href="/login">log in</a> </h3>

</body>
</html>
</code>```

I also tried the following but it's still not working.

```<code> <body background  src ="C:\Users\nourhan\workspace\ProjectSw\src\main\resources\templates\page.jpg">
</code>```

答:
This won't worK:

```<code><body background = "page.jpg">
</code>```

Make it

```<code><body style="background: url(page.jpg);">
</code>```

Body:
I'm trying to add a background image to one of the html pages in my spring-boot application.
  When the application is launched the background is not loaded or any other image.

This is my html code

<!DOCTYPE HTML>

join us

<form action="/Register" method="get">
 <button class="button" formaction="Register.html" >Sign up </button>
</form>

 already have account ? log in

I also tried the following but it's still not working.

Body:
This won't worK:

<body background = "page.jpg">

Make it

<body style="background: url(page.jpg);">


问:
Is there a limit on number of manufacturer options in Magento 2.1?
I am running Magento 2.1 for my ecommerce store. I am adding options to Manufacturer attribute, but I am not able to add more than 59. After that when I add more options, I get success message but the new option is not added. Have someone faced this before? How do I resolve this?

Ashok

答: Its probably related to the PHP directive "max_input_vars" try to increase it in your php.ini</p>


问:
spring-data-rest generating wrong entity links in proxy setup
I deployed my Spring Boot application behind an Apache powered reverse proxy. This proxy already sets the headers X-Forwarded-Proto and X-Forwarded-Host correctly. However, spring-data-rest generates weird entity and enpoint links.
E.g. requesting the news resource:

GET https://myproxyhost.net/api/news

responses with this:

```<code>{
  "_embedded" : {
    "news" : [ {
      "title" : "Testnews",
      "_links" : {
        "self" : {
          "href" : "https://myproxyhost.net/api/news/api/news/1"
        },
        "news" : {
          "href" : "https://myproxyhost.net/api/news/api/news/1{?projection}",
          "templated" : true
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "https://myproxyhost.net/api/news/api/news"
    },
    "profile" : {
      "href" : "https://myproxyhost.net/api/news/api/profile/news"
    },
    "search" : {
      "href" : "https://myproxyhost.net/api/news/api/news/search"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}
</code>```

As you can see the links are somehow doubled and I have no idea why. The only spring-data-rest specific property I use is:

```<code>spring.data.rest.base-path=/api
</code>```

Additionally in my local setup everything works fine, so I guess the proxy is somehow responsible for this.

Has anybody an idea what is going wrong here? Thanks in advance!

答:
The problem was an incorrect configuration of the ReverseProxy settings which led to urls like

```<code>http://proxiedhost.net:8080//api/news
</code>```

Which led therefore to the weird urls mentioned in the question above.

Body:
I deployed my Spring Boot application behind an Apache powered reverse proxy. This proxy already sets the headers X-Forwarded-Proto and X-Forwarded-Host correctly. However, spring-data-rest generates weird entity and enpoint links.
E.g. requesting the news resource:

GET https://myproxyhost.net/api/news

responses with this:

{
  "_embedded" : {
    "news" : [ {
      "title" : "Testnews",
      "_links" : {
        "self" : {
          "href" : "https://myproxyhost.net/api/news/api/news/1"
        },
        "news" : {
          "href" : "https://myproxyhost.net/api/news/api/news/1{?projection}",
          "templated" : true
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "https://myproxyhost.net/api/news/api/news"
    },
    "profile" : {
      "href" : "https://myproxyhost.net/api/news/api/profile/news"
    },
    "search" : {
      "href" : "https://myproxyhost.net/api/news/api/news/search"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

As you can see the links are somehow doubled and I have no idea why. The only spring-data-rest specific property I use is:

spring.data.rest.base-path=/api

Additionally in my local setup everything works fine, so I guess the proxy is somehow responsible for this.

Has anybody an idea what is going wrong here? Thanks in advance!

Body:
The problem was an incorrect configuration of the ReverseProxy settings which led to urls like

http://proxiedhost.net:8080//api/news

Which led therefore to the weird urls mentioned in the question above.


问:
Determine start and end time of current day (UTC -> EST -> UTC) ; Python
I am storing all my times in UTC and my system is set to UTC (though I am in EST).

I have dates stored as:

```<code>Wed, 20 Feb 2013 03:51:39 +0000
</code>```

However, I would like to select information based off today for EST, so I am attempting to:

Get current time as UTC and change to EST

```<code>datetime.utcnow().replace(tzinfo=tz.tzutc()).astimezone(tz.gettz('America/New_York'))
2013-02-19 23:17:20.560898-05:00
</code>```

Next I want to get the start time for the EST day (2013-02-19 00:00:00.000000-05:00) and the end time (2013-02-19 23:59:59.99999-05:00)

Once I have those values, I'd like to convert back to UTC, so I have a high and low value I can clamp by that's correct my EST (my timezone).

If this isn't the best way to do this, or I'm missing something (does seem overly complicated to me) please help me see the light!

TIA

Update per answer:

```<code>d1 = datetime.utcnow().replace(tzinfo=tz.tzutc()).astimezone(tz.gettz('America/New_York'))
print d1.strftime("%m %d %Y") ; d2 = d1.replace(day=d1.day + 1) ; print d2.strftime("%m %d %Y")
</code>```

That will give me

```<code>02 20 2013
02 21 2013
</code>```

Which is correct. I now need to generate the full EST time from that and then convert to UTC. This I cannot figure out. Actually, I probably want to convert to UTC epoch timestamp when complete because that will make my database operations pretty easy (<, >, ==, etc).

答:
Just ran into this, here's the simplest option I found:

```<code>from delorean import Delorean
today_d = Delorean()
sod_dt = today_d.start_of_day
eod_dt = today_d.end_of_day
sod_d = Delorean(sod_dt)
eod_d = Delorean(eod_dt)
sod_e = sod_d.epoch
eod_e = eod_d.epoch
</code>```

to confirm:

```<code>In [69]: eod_e - sod_e
Out[69]: 86399.99999904633
</code>```

close enough for most people

Body:
I am storing all my times in UTC and my system is set to UTC (though I am in EST).

I have dates stored as:

Wed, 20 Feb 2013 03:51:39 +0000

However, I would like to select information based off today for EST, so I am attempting to:

Get current time as UTC and change to EST

datetime.utcnow().replace(tzinfo=tz.tzutc()).astimezone(tz.gettz('America/New_York'))
2013-02-19 23:17:20.560898-05:00

Next I want to get the start time for the EST day (2013-02-19 00:00:00.000000-05:00) and the end time (2013-02-19 23:59:59.99999-05:00)

Once I have those values, I'd like to convert back to UTC, so I have a high and low value I can clamp by that's correct my EST (my timezone).

If this isn't the best way to do this, or I'm missing something (does seem overly complicated to me) please help me see the light!

TIA

Update per answer:

d1 = datetime.utcnow().replace(tzinfo=tz.tzutc()).astimezone(tz.gettz('America/New_York'))
print d1.strftime("%m %d %Y") ; d2 = d1.replace(day=d1.day + 1) ; print d2.strftime("%m %d %Y")

That will give me

02 20 2013
02 21 2013

Which is correct. I now need to generate the full EST time from that and then convert to UTC. This I cannot figure out. Actually, I probably want to convert to UTC epoch timestamp when complete because that will make my database operations pretty easy (<, >, ==, etc).

Body:
Just ran into this, here's the simplest option I found:

from delorean import Delorean
today_d = Delorean()
sod_dt = today_d.start_of_day
eod_dt = today_d.end_of_day
sod_d = Delorean(sod_dt)
eod_d = Delorean(eod_dt)
sod_e = sod_d.epoch
eod_e = eod_d.epoch

to confirm:

In [69]: eod_e - sod_e
Out[69]: 86399.99999904633

close enough for most people


问:
Handling leap seconds on sub second precision UTC time arithmetic
I'm doing a real time signal processing:

My inputs are samples tagged with timestamps.
My outputs are estimations tagged with timestamps in UTC

I need to compensate for processing delay, so at sample N I'll output the estimations of sample N-K, K being my processing delay.

The time compensation must be leap second aware. ie, with a delay of 10ms:

```<code>INPUT  TS = 20150701T000000.000000
OUTPUT TS = 20150630T235960.990000
</code>```

I thought of struct tm as timestamps, making use of the 61st second.

But I wasn't able to find ( struct tm <-> TAI ) translation functions.

答:
Howard Hinnant's timezone library (free, open-source, cross-platform, C++11) will handle this:

```<code>#include "date/tz.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    istringstream in{"20150701T000000.000000"};
    utc_time<microseconds> ts;
    in >> parse("%Y%m%dT%H%M%S", ts);
    ts -= 10ms;
    std::cout << format("%Y%m%dT%H%M%S", ts) << '\n';
}
</code>```

Output:

```<code>20150630T235960.990000
</code>```

utc_time<microseconds> is a microsecond-precision time stamp that is leap-second aware.  One can do arithmetic on it, format it and parse it.  It depends on the IANA timezone database for its source of leap second information.  This library can be configured to automatically download this information, or it can be downloaded manually.  The documentation has full installation instructions for linux, macOS, and Windows.  Even iOS and Android have support.  The library is portable from C++11 and forward.

This library has also been voted into the draft C++20 specification, and has been documented here.  So when the time comes, you will be able to get this functionality from your C++ vendor instead of from this timezone library.

Body:
I'm doing a real time signal processing:

My inputs are samples tagged with timestamps.
My outputs are estimations tagged with timestamps in UTC

I need to compensate for processing delay, so at sample N I'll output the estimations of sample N-K, K being my processing delay.

The time compensation must be leap second aware. ie, with a delay of 10ms:

INPUT  TS = 20150701T000000.000000
OUTPUT TS = 20150630T235960.990000

I thought of struct tm as timestamps, making use of the 61st second.

But I wasn't able to find ( struct tm <-> TAI ) translation functions.

Body:
Howard Hinnant's timezone library (free, open-source, cross-platform, C++11) will handle this:

#include "date/tz.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    istringstream in{"20150701T000000.000000"};
    utc_time<microseconds> ts;
    in >> parse("%Y%m%dT%H%M%S", ts);
    ts -= 10ms;
    std::cout << format("%Y%m%dT%H%M%S", ts) << '\n';
}

Output:

20150630T235960.990000

utc_time<microseconds> is a microsecond-precision time stamp that is leap-second aware.  One can do arithmetic on it, format it and parse it.  It depends on the IANA timezone database for its source of leap second information.  This library can be configured to automatically download this information, or it can be downloaded manually.  The documentation has full installation instructions for linux, macOS, and Windows.  Even iOS and Android have support.  The library is portable from C++11 and forward.

This library has also been voted into the draft C++20 specification, and has been documented here.  So when the time comes, you will be able to get this functionality from your C++ vendor instead of from this timezone library.


问:
Angular + ng-bootstrap - Modal : window does not open
I'm new with Angular, and i have a problem while trying the simple example with ng-bootstrap modal.
I just tried to have a window open and instead it appears in my application.
I'd like to have a new window open as it is explained in the ng-bootstrap example.

I am using:
 - Angular 4.0.0
 - Bootstrap 4.0.0-alpha.6
 - @ng-bootstrap/ng-bootstrap 1.0.0-alpha.22

I have in my file.html :

<template #content let-c="close" let-d="dismiss">

Modal title

            <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
                ×
            </button>

One fine body…

            <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>

    </template>

    <button class="btn btn-lg btn-outline-primary" (click)="open(content)">Launch demo modal</button>

    ```{{closeResult}}``````
</div>
</div>
</p>

<p>and in my file.ts :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { Component, Input, Output, EventEmitter, ViewContainerRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModal, NgbActiveModal, NgbModalOptions, NgbModalRef, ModalDismissReasons, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';

@Component( {
    selector: 'app-stagiaires',
    templateUrl: './stagiaires.component.html',
    styleUrls: ['./stagiaires.component.css'],
} )

export class StagiairesComponent {

    closeResult: string;

    constructor(private modalService: NgbModal) { }

    open(content) {
        this.modalService.open(content).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        });
    }

    private getDismissReason(reason: any): string {
        if (reason === ModalDismissReasons.ESC) {
            return 'by pressing ESC';
        }
        else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
            return 'by clicking on a backdrop';
        }
        else {
            return `with: ${reason}`;
        }
    }
}</code>```

I don't have any error showing, it just open the modal in my app instead of a new window and i really don't understand why.

Edit:
Here is a screen of my problem :
Problem

I have the button "launch demo modal" and when i click on it the "modal title" "one fine body..." appear underneath the button instead of in a modal

答:
As described in ng-bootstrap NgbModal "A service to open modal windows" and it has no properties to open modal window in new browser window.

I've created the same app as you:

angular 4.1.0-beta.0

bootstrap 4.0.0-alpha.6

ng-bootstrap 1.0.0-alpha.22

And modal windows works as expected, here is content of my app

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }```
</div>
</div>
</p>

<p><strong>index.html</strong> (I use Bootstrap CDN)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>AngularModal</title>
  <base href="/">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html></code>```

app.component.ts

import { Component } from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  closeResult: string;

  constructor(private modalService: NgbModal) {}

  open(content) {
    this.modalService.open(content).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return  `with: ${reason}`;
    }
  }
}```
</div>
</div>
</p>

<p><strong>app.component.html</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template #content let-c="close" let-d="dismiss">
  <div class="modal-header">
    <h4 class="modal-title">Modal title</h4>
    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    <p>One fine body…</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>
  </div>
</template>

<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Launch demo modal</button>

<hr>

```{{closeResult}}```</code>```

Body:
I'm new with Angular, and i have a problem while trying the simple example with ng-bootstrap modal.
I just tried to have a window open and instead it appears in my application.
I'd like to have a new window open as it is explained in the ng-bootstrap example.

I am using:
 - Angular 4.0.0
 - Bootstrap 4.0.0-alpha.6
 - @ng-bootstrap/ng-bootstrap 1.0.0-alpha.22

I have in my file.html :

<template #content let-c="close" let-d="dismiss">

Modal title

            <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
                ×
            </button>

One fine body…

            <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>

    </template>

    <button class="btn btn-lg btn-outline-primary" (click)="open(content)">Launch demo modal</button>

{{closeResult}}

and in my file.ts :

import { Component, Input, Output, EventEmitter, ViewContainerRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModal, NgbActiveModal, NgbModalOptions, NgbModalRef, ModalDismissReasons, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';

@Component( {
    selector: 'app-stagiaires',
    templateUrl: './stagiaires.component.html',
    styleUrls: ['./stagiaires.component.css'],
} )

export class StagiairesComponent {

    closeResult: string;

    constructor(private modalService: NgbModal) { }

    open(content) {
        this.modalService.open(content).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        });
    }

    private getDismissReason(reason: any): string {
        if (reason === ModalDismissReasons.ESC) {
            return 'by pressing ESC';
        }
        else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
            return 'by clicking on a backdrop';
        }
        else {
            return `with: ${reason}`;
        }
    }
}

I don't have any error showing, it just open the modal in my app instead of a new window and i really don't understand why.

Edit:
Here is a screen of my problem :
Problem

I have the button "launch demo modal" and when i click on it the "modal title" "one fine body..." appear underneath the button instead of in a modal

Body:
As described in ng-bootstrap NgbModal "A service to open modal windows" and it has no properties to open modal window in new browser window.

I've created the same app as you:

angular 4.1.0-beta.0

bootstrap 4.0.0-alpha.6

ng-bootstrap 1.0.0-alpha.22

And modal windows works as expected, here is content of my app

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

index.html (I use Bootstrap CDN)

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>AngularModal</title>
  <base href="/">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

app.component.ts

import { Component } from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  closeResult: string;

  constructor(private modalService: NgbModal) {}

  open(content) {
    this.modalService.open(content).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return  `with: ${reason}`;
    }
  }
}

app.component.html

<template #content let-c="close" let-d="dismiss">
  <div class="modal-header">
    <h4 class="modal-title">Modal title</h4>
    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <p>One fine body&hellip;</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>
  </div>
</template>

<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Launch demo modal</button>

<hr>

<pre>{{closeResult}}</pre>